12_PhysicsStressTest.lua 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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. -- - Usage of Lua Coroutine to yield/resume based on time step
  7. require "LuaScripts/Utilities/Sample"
  8. local scene_ = nil
  9. local cameraNode = nil
  10. local yaw = 0.0
  11. local pitch = 0.0
  12. local drawDebug = false
  13. function Start()
  14. -- Execute the common startup for samples
  15. SampleStart()
  16. -- Create the scene content
  17. CreateScene()
  18. -- Create the UI content
  19. CreateInstructions()
  20. -- Setup the viewport for displaying the scene
  21. SetupViewport()
  22. -- Hook up to the frame update and render post-update events
  23. SubscribeToEvents()
  24. end
  25. function CreateScene()
  26. scene_ = Scene()
  27. -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  28. -- Create a physics simulation world with default parameters, which will update at 60ps. Like the Octree must
  29. -- exist before creating drawable components, the PhysicsWorld must exist before creating physics components.
  30. -- Finally, create a DebugRenderer component so that we can draw physics debug geometry
  31. scene_:CreateComponent("Octree")
  32. scene_:CreateComponent("PhysicsWorld")
  33. scene_:CreateComponent("DebugRenderer")
  34. -- Create a Zone component for ambient lighting & fog control
  35. local zoneNode = scene_:CreateChild("Zone")
  36. local zone = zoneNode:CreateComponent("Zone")
  37. zone.boundingBox = BoundingBox(-1000.0, 1000.0)
  38. zone.ambientColor = Color(0.15, 0.15, 0.15)
  39. zone.fogColor = Color(0.5, 0.5, 0.7)
  40. zone.fogStart = 100.0
  41. zone.fogEnd = 300.0
  42. -- Create a directional light to the world. Enable cascaded shadows on it
  43. local lightNode = scene_:CreateChild("DirectionalLight")
  44. lightNode.direction = Vector3(0.6, -1.0, 0.8)
  45. local light = lightNode:CreateComponent("Light")
  46. light.lightType = LIGHT_DIRECTIONAL
  47. light.castShadows = true
  48. light.shadowBias = BiasParameters(0.00025, 0.5)
  49. -- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  50. light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8)
  51. if true then
  52. -- Create a floor object, 500 x 500 world units. Adjust position so that the ground is at zero Y
  53. local floorNode = scene_:CreateChild("Floor")
  54. floorNode.position = Vector3(0.0, -0.5, 0.0)
  55. floorNode.scale = Vector3(500.0, 1.0, 500.0)
  56. local floorObject = floorNode:CreateComponent("StaticModel")
  57. floorObject.model = cache:GetResource("Model", "Models/Box.mdl")
  58. floorObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml")
  59. -- Make the floor physical by adding RigidBody and CollisionShape components
  60. local body = floorNode:CreateComponent("RigidBody")
  61. local shape = floorNode:CreateComponent("CollisionShape")
  62. -- 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
  63. -- rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.)
  64. shape:SetBox(Vector3(1.0, 1.0, 1.0))
  65. end
  66. -- Create static mushrooms with triangle mesh collision
  67. local NUM_MUSHROOMS = 50
  68. for i = 1, NUM_MUSHROOMS do
  69. local mushroomNode = scene_:CreateChild("Mushroom")
  70. mushroomNode.position = Vector3(Random(400.0) - 200.0, 0.0, Random(400.0) - 200.0)
  71. mushroomNode.rotation = Quaternion(0.0, Random(360.0), 0.0)
  72. mushroomNode:SetScale(5.0 + Random(5.0))
  73. local 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. local body = mushroomNode:CreateComponent("RigidBody")
  78. local 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. end
  82. -- Start coroutine to create a large amount of falling physics objects
  83. coroutine.start(function()
  84. local NUM_OBJECTS = 1000
  85. for i = 1, NUM_OBJECTS do
  86. local boxNode = scene_:CreateChild("Box")
  87. boxNode.position = Vector3(0.0, 100.0, 0.0)
  88. local 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. local body = boxNode:CreateComponent("RigidBody")
  94. body.mass = 1.0
  95. body.friction = 1.0
  96. -- Set linear velocity
  97. body.linearVelocity = Vector3(0.0, -50.0, 0.0)
  98. -- Disable collision event signaling to reduce CPU load of the physics simulation
  99. body.collisionEventMode = COLLISION_NEVER
  100. local shape = boxNode:CreateComponent("CollisionShape")
  101. shape:SetBox(Vector3(1.0, 1.0, 1.0))
  102. -- sleep coroutine
  103. coroutine.sleep(0.1)
  104. end
  105. end)
  106. -- Create the camera. Limit far clip distance to match the fog. Note: now we actually create the camera node outside
  107. -- the scene, because we want it to be unaffected by scene load/save
  108. cameraNode = Node()
  109. local camera = cameraNode:CreateComponent("Camera")
  110. camera.farClip = 300.0
  111. -- Set an initial position for the camera scene node above the floor
  112. cameraNode.position = Vector3(0.0, 3.0, -20.0)
  113. end
  114. function CreateInstructions()
  115. -- Construct new Text object, set string to display and font to use
  116. local instructionText = ui.root:CreateChild("Text")
  117. instructionText:SetText("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. end
  129. function SetupViewport()
  130. -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  131. local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
  132. renderer:SetViewport(0, viewport)
  133. end
  134. function SubscribeToEvents()
  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. end
  141. function MoveCamera(timeStep)
  142. -- Do not move if the UI has a focused element (the console)
  143. if ui.focusElement ~= nil then
  144. return
  145. end
  146. -- Movement speed as world units per second
  147. local MOVE_SPEED = 20.0
  148. -- Mouse sensitivity as degrees per pixel
  149. local MOUSE_SENSITIVITY = 0.1
  150. -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  151. local mouseMove = input.mouseMove
  152. yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
  153. pitch = pitch +MOUSE_SENSITIVITY * mouseMove.y
  154. pitch = Clamp(pitch, -90.0, 90.0)
  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.0)
  157. -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  158. if input:GetKeyDown(KEY_W) then
  159. cameraNode:TranslateRelative(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
  160. end
  161. if input:GetKeyDown(KEY_S) then
  162. cameraNode:TranslateRelative(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
  163. end
  164. if input:GetKeyDown(KEY_A) then
  165. cameraNode:TranslateRelative(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  166. end
  167. if input:GetKeyDown(KEY_D) then
  168. cameraNode:TranslateRelative(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  169. end
  170. -- "Shoot" a physics object with left mousebutton
  171. if input:GetMouseButtonPress(MOUSEB_LEFT) then
  172. SpawnObject()
  173. end
  174. -- Check for loading/saving the scene. Save the scene to the file Data/Scenes/Physics.xml relative to the executable
  175. -- directory
  176. if input:GetKeyPress(KEY_F5) then
  177. scene_:SaveXML(fileSystem:GetProgramDir().."Data/Scenes/PhysicsStressTest.xml")
  178. end
  179. if input:GetKeyPress(KEY_F7) then
  180. scene_:LoadXML(fileSystem:GetProgramDir().."Data/Scenes/PhysicsStressTest.xml")
  181. end
  182. -- Toggle debug geometry with space
  183. if input:GetKeyPress(KEY_SPACE) then
  184. drawDebug = not drawDebug
  185. end
  186. end
  187. function SpawnObject()
  188. -- Create a smaller box at camera position
  189. local boxNode = scene_:CreateChild("SmallBox")
  190. boxNode.position = cameraNode.position
  191. boxNode.rotation = cameraNode.rotation
  192. boxNode:SetScale(0.25)
  193. local 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. local body = boxNode:CreateComponent("RigidBody")
  199. body.mass = 0.25
  200. body.friction = 0.75
  201. local shape = boxNode:CreateComponent("CollisionShape")
  202. shape:SetBox(Vector3(1.0, 1.0, 1.0))
  203. local OBJECT_VELOCITY = 10.0
  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.0, 0.25, 1.0) * OBJECT_VELOCITY
  207. end
  208. function HandleUpdate(eventType, eventData)
  209. -- Take the frame time step, which is stored as a float
  210. local timeStep = eventData:GetFloat("TimeStep")
  211. -- Move the camera, scale movement with time step
  212. MoveCamera(timeStep)
  213. end
  214. function HandlePostRenderUpdate(eventType, eventData)
  215. -- If draw debug mode is enabled, draw physics debug geometry. Use depth test to make the result easier to interpret
  216. if drawDebug then
  217. scene_:GetComponent("PhysicsWorld"):DrawDebugGeometry(true)
  218. end
  219. end