12_PhysicsStressTest.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. // Copyright (c) 2015 Xamarin Inc
  4. // Copyright (c) 2016 THUNDERBEAST GAMES LLC
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. using AtomicEngine;
  25. namespace FeatureExamples
  26. {
  27. public class PhysicsStressTestSample : Sample
  28. {
  29. bool drawDebug;
  30. public PhysicsStressTestSample() : base() { }
  31. public override void Start()
  32. {
  33. base.Start();
  34. CreateScene();
  35. SimpleCreateInstructionsWithWasd(
  36. "\nLMB to spawn physics objects\n" +
  37. "F5 to save scene, F7 to load\n" +
  38. "Space to toggle physics debug geometry");
  39. SetupViewport();
  40. SubscribeToEvents();
  41. }
  42. void SubscribeToEvents()
  43. {
  44. SubscribeToEvent<PostRenderUpdateEvent>(e =>
  45. {
  46. // If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
  47. // bones. Note that debug geometry has to be separately requested each frame. Disable depth test so that we can see the
  48. // bones properly
  49. if (drawDebug)
  50. {
  51. GetSubsystem<Renderer>().DrawDebugGeometry(false);
  52. }
  53. });
  54. }
  55. protected override void Update(float timeStep)
  56. {
  57. base.Update(timeStep);
  58. SimpleMoveCamera3D(timeStep);
  59. var input = GetSubsystem<Input>();
  60. // "Shoot" a physics object with left mousebutton
  61. if (input.GetMouseButtonPress(Constants.MOUSEB_LEFT))
  62. SpawnObject();
  63. /* TODO: Scene.SaveXML/Scene.LoadXML
  64. if (input.GetKeyPress(Constants.KEY_F5))
  65. scene.SaveXml(fileSystem.UserDocumentsDir + "/Scenes/PhysicsStressTest.xml");
  66. if (input.GetKeyPress(Constants.KEY_F7))
  67. scene.LoadXml(fileSystem.UserDocumentsDir + "/Scenes/PhysicsStressTest.xml");
  68. */
  69. if (input.GetKeyPress(Constants.KEY_SPACE))
  70. drawDebug = !drawDebug;
  71. }
  72. void SetupViewport()
  73. {
  74. var renderer = GetSubsystem<Renderer>();
  75. renderer.SetViewport(0, new Viewport(scene, CameraNode.GetComponent<Camera>()));
  76. }
  77. void SpawnObject()
  78. {
  79. var cache = GetSubsystem<ResourceCache>();
  80. // Create a smaller box at camera position
  81. Node boxNode = scene.CreateChild("SmallBox");
  82. boxNode.Position = CameraNode.Position;
  83. boxNode.Rotation = CameraNode.Rotation;
  84. boxNode.SetScale(0.25f);
  85. StaticModel boxObject = boxNode.CreateComponent<StaticModel>();
  86. boxObject.Model = (cache.Get<Model>("Models/Box.mdl"));
  87. boxObject.SetMaterial(cache.Get<Material>("Materials/StoneSmall.xml"));
  88. boxObject.CastShadows = true;
  89. // Create physics components, use a smaller mass also
  90. RigidBody body = boxNode.CreateComponent<RigidBody>();
  91. body.Mass = 0.25f;
  92. body.Friction = 0.75f;
  93. CollisionShape shape = boxNode.CreateComponent<CollisionShape>();
  94. shape.SetBox(Vector3.One, Vector3.Zero, Quaternion.Identity);
  95. const float objectVelocity = 10.0f;
  96. // Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component
  97. // to overcome gravity better
  98. body.SetLinearVelocity(CameraNode.Rotation * new Vector3(0.0f, 0.25f, 1.0f) * objectVelocity);
  99. }
  100. void CreateScene()
  101. {
  102. var cache = GetSubsystem<ResourceCache>();
  103. scene = new Scene();
  104. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  105. // Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must
  106. // exist before creating drawable components, the PhysicsWorld must exist before creating physics components.
  107. // Finally, create a DebugRenderer component so that we can draw physics debug geometry
  108. scene.CreateComponent<Octree>();
  109. scene.CreateComponent<PhysicsWorld>();
  110. scene.CreateComponent<DebugRenderer>();
  111. // Create a Zone component for ambient lighting & fog control
  112. Node zoneNode = scene.CreateChild("Zone");
  113. Zone zone = zoneNode.CreateComponent<Zone>();
  114. zone.SetBoundingBox(new BoundingBox(-1000.0f, 1000.0f));
  115. zone.AmbientColor = new Color(0.15f, 0.15f, 0.15f);
  116. zone.FogColor = new Color(0.5f, 0.5f, 0.7f);
  117. zone.FogStart = 100.0f;
  118. zone.FogEnd = 300.0f;
  119. // Create a directional light to the world. Enable cascaded shadows on it
  120. Node lightNode = scene.CreateChild("DirectionalLight");
  121. lightNode.SetDirection(new Vector3(0.6f, -1.0f, 0.8f));
  122. Light light = lightNode.CreateComponent<Light>();
  123. light.LightType = LightType.LIGHT_DIRECTIONAL;
  124. light.CastShadows = true;
  125. light.ShadowBias = new BiasParameters(0.00025f, 0.5f);
  126. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  127. light.ShadowCascade = new CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  128. {
  129. // Create a floor object, 500 x 500 world units. Adjust position so that the ground is at zero Y
  130. Node floorNode = scene.CreateChild("Floor");
  131. floorNode.Position = new Vector3(0.0f, -0.5f, 0.0f);
  132. floorNode.Scale = new Vector3(500.0f, 1.0f, 500.0f);
  133. StaticModel floorObject = floorNode.CreateComponent<StaticModel>();
  134. floorObject.Model = cache.Get<Model>("Models/Box.mdl");
  135. floorObject.SetMaterial(cache.Get<Material>("Materials/StoneTiled.xml"));
  136. // Make the floor physical by adding RigidBody and CollisionShape components
  137. /*RigidBody* body = */
  138. floorNode.CreateComponent<RigidBody>();
  139. CollisionShape shape = floorNode.CreateComponent<CollisionShape>();
  140. shape.SetBox(Vector3.One, Vector3.Zero, Quaternion.Identity);
  141. }
  142. {
  143. // Create static mushrooms with triangle mesh collision
  144. const uint numMushrooms = 50;
  145. for (uint i = 0; i < numMushrooms; ++i)
  146. {
  147. Node mushroomNode = scene.CreateChild("Mushroom");
  148. mushroomNode.Position = new Vector3(NextRandom(400.0f) - 200.0f, 0.0f, NextRandom(400.0f) - 200.0f);
  149. mushroomNode.Rotation = new Quaternion(0.0f, NextRandom(360.0f), 0.0f);
  150. mushroomNode.SetScale(5.0f + NextRandom(5.0f));
  151. StaticModel mushroomObject = mushroomNode.CreateComponent<StaticModel>();
  152. mushroomObject.Model = (cache.Get<Model>("Models/Mushroom.mdl"));
  153. mushroomObject.SetMaterial(cache.Get<Material>("Materials/Mushroom.xml"));
  154. mushroomObject.CastShadows = true;
  155. mushroomNode.CreateComponent<RigidBody>();
  156. CollisionShape shape = mushroomNode.CreateComponent<CollisionShape>();
  157. // By default the highest LOD level will be used, the LOD level can be passed as an optional parameter
  158. shape.SetTriangleMesh(mushroomObject.Model, 0, Vector3.One, Vector3.Zero, Quaternion.Identity);
  159. }
  160. }
  161. {
  162. // Create a large amount of falling physics objects
  163. const uint numObjects = 1000;
  164. for (uint i = 0; i < numObjects; ++i)
  165. {
  166. Node boxNode = scene.CreateChild("Box");
  167. boxNode.Position = new Vector3(0.0f, i * 2.0f + 100.0f, 0.0f);
  168. StaticModel boxObject = boxNode.CreateComponent<StaticModel>();
  169. boxObject.Model = cache.Get<Model>("Models/Box.mdl");
  170. boxObject.SetMaterial(cache.Get<Material>("Materials/StoneSmall.xml"));
  171. boxObject.CastShadows = true;
  172. // Give the RigidBody mass to make it movable and also adjust friction
  173. RigidBody body = boxNode.CreateComponent<RigidBody>();
  174. body.Mass = 1.0f;
  175. body.Friction = 1.0f;
  176. // Disable collision event signaling to reduce CPU load of the physics simulation
  177. body.CollisionEventMode = CollisionEventMode.COLLISION_NEVER;
  178. CollisionShape shape = boxNode.CreateComponent<CollisionShape>();
  179. shape.SetBox(Vector3.One, Vector3.Zero, Quaternion.Identity);
  180. }
  181. }
  182. // Create the camera. Limit far clip distance to match the fog. Note: now we actually create the camera node outside
  183. // the scene, because we want it to be unaffected by scene load / save
  184. CameraNode = new Node();
  185. Camera camera = CameraNode.CreateComponent<Camera>();
  186. camera.FarClip = 300.0f;
  187. // Set an initial position for the camera scene node above the floor
  188. CameraNode.Position = new Vector3(0.0f, 3.0f, -20.0f);
  189. }
  190. }
  191. }