06_SkeletalAnimation.lua 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. -- Skeletal animation example.
  2. -- This sample demonstrates:
  3. -- - Populating a 3D scene with skeletally animated AnimatedModel components
  4. -- - Moving the animated models and advancing their animation using a script object
  5. -- - Enabling a cascaded shadow map on a directional light, which allows high-quality shadows
  6. -- over a large area (typically used in outdoor scenes for shadows cast by sunlight)
  7. -- - Displaying renderer debug geometry
  8. require "LuaScripts/Utilities/Sample"
  9. local scene_ = nil
  10. local cameraNode = nil
  11. local yaw = 0.0
  12. local pitch = 0.0
  13. local drawDebug = false
  14. local context = GetContext()
  15. local cache = GetCache()
  16. local input = GetInput()
  17. local renderer = GetRenderer()
  18. local ui = GetUI()
  19. function Start()
  20. -- Execute the common startup for samples
  21. SampleStart()
  22. -- Create the scene content
  23. CreateScene()
  24. -- Create the UI content
  25. CreateInstructions()
  26. -- Setup the viewport for displaying the scene
  27. SetupViewport()
  28. -- Hook up to the frame update and render post-update events
  29. SubscribeToEvents()
  30. end
  31. function CreateScene()
  32. scene_ = Scene(context)
  33. -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  34. -- Also create a DebugRenderer component so that we can draw debug geometry
  35. scene_:CreateComponent("Octree")
  36. scene_:CreateComponent("DebugRenderer")
  37. -- Create scene node & StaticModel component for showing a static plane
  38. local planeNode = scene_:CreateChild("Plane")
  39. planeNode.scale = Vector3(100.0, 1.0, 100.0)
  40. local planeObject = planeNode:CreateComponent("StaticModel")
  41. planeObject.model = cache:GetResource("Model", "Models/Plane.mdl")
  42. planeObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml")
  43. -- Create a Zone component for ambient lighting & fog control
  44. local zoneNode = scene_:CreateChild("Zone")
  45. local zone = zoneNode:CreateComponent("Zone")
  46. zone.boundingBox = BoundingBox(-1000.0, 1000.0)
  47. zone.ambientColor = Color(0.15, 0.15, 0.15)
  48. zone.fogColor = Color(0.5, 0.5, 0.7)
  49. zone.fogStart = 100.0
  50. zone.fogEnd = 300.0
  51. -- Create a directional light to the world. Enable cascaded shadows on it
  52. local lightNode = scene_:CreateChild("DirectionalLight")
  53. lightNode.direction = Vector3(0.6, -1.0, 0.8)
  54. local light = lightNode:CreateComponent("Light")
  55. light.lightType = LIGHT_DIRECTIONAL
  56. light.castShadows = true
  57. light.shadowBias = BiasParameters(0.00025, 0.5)
  58. -- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  59. light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8)
  60. -- Create animated models
  61. local uint NUM_MODELS = 100
  62. local MODEL_MOVE_SPEED = 2.0
  63. local MODEL_ROTATE_SPEED = 100.0
  64. local bounds = BoundingBox(Vector3(-47.0, 0.0, -47.0), Vector3(47.0, 0.0, 47.0))
  65. for i = 1, NUM_MODELS do
  66. local modelNode = scene_:CreateChild("Jack")
  67. modelNode.position = Vector3(Random(90.0) - 45.0, 0.0, Random(90.0) - 45.0)
  68. modelNode.rotation = Quaternion(0.0, Random(360.0), 0.0)
  69. local modelObject = modelNode:CreateComponent("AnimatedModel")
  70. modelObject.model = cache:GetResource("Model", "Models/Jack.mdl")
  71. modelObject.material = cache:GetResource("Material", "Materials/Jack.xml")
  72. modelObject.castShadows = true
  73. -- Create an AnimationState for a walk animation. Its time position will need to be manually updated to advance the
  74. -- animation, The alternative would be to use an AnimationController component which updates the animation automatically,
  75. -- but we need to update the model's position manually in any case
  76. local walkAnimation = cache:GetResource("Animation", "Models/Jack_Walk.ani")
  77. local state = modelObject:AddAnimationState(walkAnimation)
  78. -- Enable full blending weight and looping
  79. state.weight = 1.0
  80. state.looped = true
  81. -- Create our Mover script object that will move & animate the model during each frame's update.
  82. local object = modelNode:CreateScriptObject("Mover")
  83. object:SetParameters(MODEL_MOVE_SPEED, MODEL_ROTATE_SPEED, bounds)
  84. end
  85. -- Create the camera. Limit far clip distance to match the fog
  86. cameraNode = scene_:CreateChild("Camera")
  87. local camera = cameraNode:CreateComponent("Camera")
  88. camera.farClip = 300.0
  89. -- Set an initial position for the camera scene node above the plane
  90. cameraNode.position = Vector3(0.0, 5.0, 0.0)
  91. end
  92. function CreateInstructions()
  93. -- Construct new Text object, set string to display and font to use
  94. local instructionText = ui.root:CreateChild("Text")
  95. instructionText:SetText("Use WASD keys and mouse to move\n"..
  96. "Space to toggle debug geometry")
  97. instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
  98. -- The text has multiple rows. Center them in relation to each other
  99. instructionText.textAlignment = HA_CENTER
  100. -- Position the text relative to the screen center
  101. instructionText.horizontalAlignment = HA_CENTER
  102. instructionText.verticalAlignment = VA_CENTER
  103. instructionText:SetPosition(0, ui.root.height / 4)
  104. end
  105. function SetupViewport()
  106. -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  107. local viewport = Viewport:new(context, scene_, cameraNode:GetComponent("Camera"))
  108. renderer:SetViewport(0, viewport)
  109. end
  110. function SubscribeToEvents()
  111. -- Subscribe HandleUpdate() function for processing update events
  112. SubscribeToEvent("Update", "HandleUpdate")
  113. -- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, sent after Renderer subsystem is
  114. -- done with defining the draw calls for the viewports (but before actually executing them.) We will request debug geometry
  115. -- rendering during that event
  116. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate")
  117. end
  118. function MoveCamera(timeStep)
  119. -- Do not move if the UI has a focused element (the console)
  120. if ui.focusElement ~= nil then
  121. return
  122. end
  123. -- Movement speed as world units per second
  124. local MOVE_SPEED = 20.0
  125. -- Mouse sensitivity as degrees per pixel
  126. local MOUSE_SENSITIVITY = 0.1
  127. -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  128. local mouseMove = input.mouseMove
  129. yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
  130. pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y
  131. pitch = Clamp(pitch, -90.0, 90.0)
  132. -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  133. cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
  134. -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  135. if input:GetKeyDown(KEY_W) then
  136. cameraNode:TranslateRelative(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
  137. end
  138. if input:GetKeyDown(KEY_S) then
  139. cameraNode:TranslateRelative(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
  140. end
  141. if input:GetKeyDown(KEY_A) then
  142. cameraNode:TranslateRelative(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  143. end
  144. if input:GetKeyDown(KEY_D) then
  145. cameraNode:TranslateRelative(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  146. end
  147. -- Toggle debug geometry with space
  148. if input:GetKeyPress(KEY_SPACE) then
  149. drawDebug = not drawDebug
  150. end
  151. end
  152. function HandleUpdate(eventType, eventData)
  153. -- Take the frame time step, which is stored as a float
  154. local timeStep = eventData:GetFloat("TimeStep")
  155. -- Move the camera, scale movement with time step
  156. MoveCamera(timeStep)
  157. end
  158. function HandlePostRenderUpdate(eventType, eventData)
  159. -- If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
  160. -- bones. Note that debug geometry has to be separately requested each frame. Disable depth test so that we can see the
  161. -- bones properly
  162. if drawDebug then
  163. renderer:DrawDebugGeometry(false)
  164. end
  165. end
  166. -- Mover script object class
  167. Mover = ScriptObject()
  168. function Mover:Start()
  169. self.moveSpeed = 0.0
  170. self.rotationSpeed = 0.0
  171. self.bounds = BoundingBox()
  172. end
  173. function Mover:SetParameters(moveSpeed, rotationSpeed, bounds)
  174. self.moveSpeed = moveSpeed
  175. self.rotationSpeed = rotationSpeed
  176. self.bounds = bounds
  177. end
  178. function Mover:Update(timeStep)
  179. local node = self:GetNode()
  180. node:TranslateRelative(Vector3(0.0, 0.0, 1.0) * self.moveSpeed * timeStep)
  181. -- If in risk of going outside the plane, rotate the model right
  182. local pos = node.position
  183. local bounds = self.bounds
  184. if pos.x < bounds.min.x or pos.x > bounds.max.x or pos.z < bounds.min.z or pos.z > bounds.max.z then
  185. node:Yaw(self.rotationSpeed * timeStep)
  186. end
  187. -- Get the model's first (only) animation state and advance its time
  188. local model = node:GetComponent("AnimatedModel")
  189. local state = model:GetAnimationState(0)
  190. if state ~= nil then
  191. state:AddTime(timeStep)
  192. end
  193. end