12_PhysicsStressTest.as 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. // Physics stress test example.
  2. // This sample demonstrates:
  3. // - Physics and rendering performance with a high (1000) moving object count
  4. // - Using triangle meshes for collision
  5. // - Optimizing physics simulation by leaving out collision event signaling
  6. #include "Scripts/Utilities/Sample.as"
  7. void Start()
  8. {
  9. // Execute the common startup for samples
  10. SampleStart();
  11. // Create the scene content
  12. CreateScene();
  13. // Create the UI content
  14. CreateInstructions();
  15. // Setup the viewport for displaying the scene
  16. SetupViewport();
  17. // Hook up to the frame update and render post-update events
  18. SubscribeToEvents();
  19. }
  20. void CreateScene()
  21. {
  22. scene_ = Scene();
  23. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  24. // Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must
  25. // exist before creating drawable components, the PhysicsWorld must exist before creating physics components.
  26. // Finally, create a DebugRenderer component so that we can draw physics debug geometry
  27. scene_.CreateComponent("Octree");
  28. scene_.CreateComponent("PhysicsWorld");
  29. scene_.CreateComponent("DebugRenderer");
  30. // Create a Zone component for ambient lighting & fog control
  31. Node@ zoneNode = scene_.CreateChild("Zone");
  32. Zone@ zone = zoneNode.CreateComponent("Zone");
  33. zone.boundingBox = BoundingBox(-1000.0f, 1000.0f);
  34. zone.ambientColor = Color(0.15f, 0.15f, 0.15f);
  35. zone.fogColor = Color(0.5f, 0.5f, 0.7f);
  36. zone.fogStart = 100.0f;
  37. zone.fogEnd = 300.0f;
  38. // Create a directional light to the world. Enable cascaded shadows on it
  39. Node@ lightNode = scene_.CreateChild("DirectionalLight");
  40. lightNode.direction = Vector3(0.6f, -1.0f, 0.8f);
  41. Light@ light = lightNode.CreateComponent("Light");
  42. light.lightType = LIGHT_DIRECTIONAL;
  43. light.castShadows = true;
  44. light.shadowBias = BiasParameters(0.00025f, 0.5f);
  45. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  46. light.shadowCascade = CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  47. {
  48. // Create a floor object, 500 x 500 world units. Adjust position so that the ground is at zero Y
  49. Node@ floorNode = scene_.CreateChild("Floor");
  50. floorNode.position = Vector3(0.0f, -0.5f, 0.0f);
  51. floorNode.scale = Vector3(500.0f, 1.0f, 500.0f);
  52. StaticModel@ floorObject = floorNode.CreateComponent("StaticModel");
  53. floorObject.model = cache.GetResource("Model", "Models/Box.mdl");
  54. floorObject.material = cache.GetResource("Material", "Materials/StoneTiled.xml");
  55. // Make the floor physical by adding RigidBody and CollisionShape components
  56. RigidBody@ body = floorNode.CreateComponent("RigidBody");
  57. CollisionShape@ shape = floorNode.CreateComponent("CollisionShape");
  58. // Set a box shape of size 1 x 1 x 1 for collision. The shape will be scaled with the scene node scale, so the
  59. // rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.)
  60. shape.SetBox(Vector3(1.0f, 1.0f, 1.0f));
  61. }
  62. {
  63. // Create static mushrooms with triangle mesh collision
  64. const uint NUM_MUSHROOMS = 50;
  65. for (uint i = 0; i < NUM_MUSHROOMS; ++i)
  66. {
  67. Node@ mushroomNode = scene_.CreateChild("Mushroom");
  68. mushroomNode.position = Vector3(Random(400.0f) - 200.0f, 0.0f, Random(400.0f) - 200.0f);
  69. mushroomNode.rotation = Quaternion(0.0f, Random(360.0f), 0.0f);
  70. mushroomNode.SetScale(5.0f + Random(5.0f));
  71. StaticModel@ mushroomObject = mushroomNode.CreateComponent("StaticModel");
  72. mushroomObject.model = cache.GetResource("Model", "Models/Mushroom.mdl");
  73. mushroomObject.material = cache.GetResource("Material", "Materials/Mushroom.xml");
  74. mushroomObject.castShadows = true;
  75. RigidBody@ body = mushroomNode.CreateComponent("RigidBody");
  76. CollisionShape@ shape = mushroomNode.CreateComponent("CollisionShape");
  77. // By default the highest LOD level will be used, the LOD level can be passed as an optional parameter
  78. shape.SetTriangleMesh(mushroomObject.model);
  79. }
  80. }
  81. {
  82. // Create a large amount of falling physics objects
  83. const uint NUM_OBJECTS = 1000;
  84. for (uint i = 0; i < NUM_OBJECTS; ++i)
  85. {
  86. Node@ boxNode = scene_.CreateChild("Box");
  87. boxNode.position = Vector3(0.0f, i * 2.0f + 100.0f, 0.0f);
  88. StaticModel@ boxObject = boxNode.CreateComponent("StaticModel");
  89. boxObject.model = cache.GetResource("Model", "Models/Box.mdl");
  90. boxObject.material = cache.GetResource("Material", "Materials/StoneSmall.xml");
  91. boxObject.castShadows = true;
  92. // Give the RigidBody mass to make it movable and also adjust friction
  93. RigidBody@ body = boxNode.CreateComponent("RigidBody");
  94. body.mass = 1.0f;
  95. body.friction = 1.0f;
  96. // Disable collision event signaling to reduce CPU load of the physics simulation
  97. body.collisionEventMode = COLLISION_NEVER;
  98. CollisionShape@ shape = boxNode.CreateComponent("CollisionShape");
  99. shape.SetBox(Vector3(1.0f, 1.0f, 1.0f));
  100. }
  101. }
  102. // Create the camera. Limit far clip distance to match the fog. Note: now we actually create the camera node outside
  103. // the scene, because we want it to be unaffected by scene load / save
  104. cameraNode = Node();
  105. Camera@ camera = cameraNode.CreateComponent("Camera");
  106. camera.farClip = 300.0f;
  107. // Set an initial position for the camera scene node above the floor
  108. cameraNode.position = Vector3(0.0f, 3.0f, -20.0f);
  109. }
  110. void CreateInstructions()
  111. {
  112. // Construct new Text object, set string to display and font to use
  113. Text@ instructionText = ui.root.CreateChild("Text");
  114. instructionText.text =
  115. "Use WASD keys and mouse to move\n"
  116. "LMB to spawn physics objects\n"
  117. "F5 to save scene, F7 to load\n"
  118. "Space to toggle physics debug geometry";
  119. instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
  120. // The text has multiple rows. Center them in relation to each other
  121. instructionText.textAlignment = HA_CENTER;
  122. // Position the text relative to the screen center
  123. instructionText.horizontalAlignment = HA_CENTER;
  124. instructionText.verticalAlignment = VA_CENTER;
  125. instructionText.SetPosition(0, ui.root.height / 4);
  126. }
  127. void SetupViewport()
  128. {
  129. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  130. Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
  131. renderer.viewports[0] = viewport;
  132. }
  133. void SubscribeToEvents()
  134. {
  135. // Subscribe HandleUpdate() function for processing update events
  136. SubscribeToEvent("Update", "HandleUpdate");
  137. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  138. // debug geometry
  139. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate");
  140. }
  141. void MoveCamera(float timeStep)
  142. {
  143. // Do not move if the UI has a focused element (the console)
  144. if (ui.focusElement !is null)
  145. return;
  146. // Movement speed as world units per second
  147. const float MOVE_SPEED = 20.0f;
  148. // Mouse sensitivity as degrees per pixel
  149. const float MOUSE_SENSITIVITY = 0.1f;
  150. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  151. IntVector2 mouseMove = input.mouseMove;
  152. yaw += MOUSE_SENSITIVITY * mouseMove.x;
  153. pitch += MOUSE_SENSITIVITY * mouseMove.y;
  154. pitch = Clamp(pitch, -90.0f, 90.0f);
  155. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  156. cameraNode.rotation = Quaternion(pitch, yaw, 0.0f);
  157. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  158. if (input.keyDown['W'])
  159. cameraNode.Translate(Vector3(0.0f, 0.0f, 1.0f) * MOVE_SPEED * timeStep);
  160. if (input.keyDown['S'])
  161. cameraNode.Translate(Vector3(0.0f, 0.0f, -1.0f) * MOVE_SPEED * timeStep);
  162. if (input.keyDown['A'])
  163. cameraNode.Translate(Vector3(-1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
  164. if (input.keyDown['D'])
  165. cameraNode.Translate(Vector3(1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
  166. // "Shoot" a physics object with left mousebutton
  167. if (input.mouseButtonPress[MOUSEB_LEFT])
  168. SpawnObject();
  169. // Check for loading / saving the scene
  170. if (input.keyPress[KEY_F5])
  171. {
  172. File saveFile(fileSystem.programDir + "Data/Scenes/PhysicsStressTest.xml", FILE_WRITE);
  173. scene_.SaveXML(saveFile);
  174. }
  175. if (input.keyPress[KEY_F7])
  176. {
  177. File loadFile(fileSystem.programDir + "Data/Scenes/PhysicsStressTest.xml", FILE_READ);
  178. scene_.LoadXML(loadFile);
  179. }
  180. // Toggle debug geometry with space
  181. if (input.keyPress[KEY_SPACE])
  182. drawDebug = !drawDebug;
  183. }
  184. void SpawnObject()
  185. {
  186. // Create a smaller box at camera position
  187. Node@ boxNode = scene_.CreateChild("SmallBox");
  188. boxNode.position = cameraNode.position;
  189. boxNode.rotation = cameraNode.rotation;
  190. boxNode.SetScale(0.25f);
  191. StaticModel@ boxObject = boxNode.CreateComponent("StaticModel");
  192. boxObject.model = cache.GetResource("Model", "Models/Box.mdl");
  193. boxObject.material = cache.GetResource("Material", "Materials/StoneSmall.xml");
  194. boxObject.castShadows = true;
  195. // Create physics components, use a smaller mass also
  196. RigidBody@ body = boxNode.CreateComponent("RigidBody");
  197. body.mass = 0.25f;
  198. body.friction = 0.75f;
  199. CollisionShape@ shape = boxNode.CreateComponent("CollisionShape");
  200. shape.SetBox(Vector3(1.0f, 1.0f, 1.0f));
  201. const float OBJECT_VELOCITY = 10.0f;
  202. // Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component
  203. // to overcome gravity better
  204. body.linearVelocity = cameraNode.rotation * Vector3(0.0f, 0.25f, 1.0f) * OBJECT_VELOCITY;
  205. }
  206. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  207. {
  208. // Take the frame time step, which is stored as a float
  209. float timeStep = eventData["TimeStep"].GetFloat();
  210. // Move the camera, scale movement with time step
  211. MoveCamera(timeStep);
  212. }
  213. void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  214. {
  215. // If draw debug mode is enabled, draw physics debug geometry. Use depth test to make the result easier to interpret
  216. if (drawDebug)
  217. scene_.physicsWorld.DrawDebugGeometry(true);
  218. }
  219. // Create XML patch instructions for screen joystick layout specific to this sample app
  220. String patchInstructions =
  221. "<patch>" +
  222. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" +
  223. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Spawn</replace>" +
  224. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" +
  225. " <element type=\"Text\">" +
  226. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" +
  227. " <attribute name=\"Text\" value=\"LEFT\" />" +
  228. " </element>" +
  229. " </add>" +
  230. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" +
  231. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" +
  232. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" +
  233. " <element type=\"Text\">" +
  234. " <attribute name=\"Name\" value=\"KeyBinding\" />" +
  235. " <attribute name=\"Text\" value=\"SPACE\" />" +
  236. " </element>" +
  237. " </add>" +
  238. "</patch>";