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