12_PhysicsStressTest.as 12 KB

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