06_SkeletalAnimation.as 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. #include "Scripts/Utilities/Sample.as"
  9. void Start()
  10. {
  11. // Execute the common startup for samples
  12. SampleStart();
  13. // Create the scene content
  14. CreateScene();
  15. // Create the UI content
  16. CreateInstructions();
  17. // Setup the viewport for displaying the scene
  18. SetupViewport();
  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. // Also create a DebugRenderer component so that we can draw debug geometry
  27. scene_.CreateComponent("Octree");
  28. scene_.CreateComponent("DebugRenderer");
  29. // Create scene node & StaticModel component for showing a static plane
  30. Node@ planeNode = scene_.CreateChild("Plane");
  31. planeNode.scale = Vector3(100.0f, 1.0f, 100.0f);
  32. StaticModel@ planeObject = planeNode.CreateComponent("StaticModel");
  33. planeObject.model = cache.GetResource("Model", "Models/Plane.mdl");
  34. planeObject.material = cache.GetResource("Material", "Materials/StoneTiled.xml");
  35. // Create a Zone component for ambient lighting & fog control
  36. Node@ zoneNode = scene_.CreateChild("Zone");
  37. Zone@ zone = zoneNode.CreateComponent("Zone");
  38. zone.boundingBox = BoundingBox(-1000.0f, 1000.0f);
  39. zone.ambientColor = Color(0.15f, 0.15f, 0.15f);
  40. zone.fogColor = Color(0.5f, 0.5f, 0.7f);
  41. zone.fogStart = 100.0f;
  42. zone.fogEnd = 300.0f;
  43. // Create a directional light to the world. Enable cascaded shadows on it
  44. Node@ lightNode = scene_.CreateChild("DirectionalLight");
  45. lightNode.direction = Vector3(0.6f, -1.0f, 0.8f);
  46. Light@ light = lightNode.CreateComponent("Light");
  47. light.lightType = LIGHT_DIRECTIONAL;
  48. light.castShadows = true;
  49. light.shadowBias = BiasParameters(0.00025f, 0.5f);
  50. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  51. light.shadowCascade = CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  52. // Create animated models
  53. const uint NUM_MODELS = 100;
  54. const float MODEL_MOVE_SPEED = 2.0f;
  55. const float MODEL_ROTATE_SPEED = 100.0f;
  56. const BoundingBox bounds(Vector3(-47.0f, 0.0f, -47.0f), Vector3(47.0f, 0.0f, 47.0f));
  57. for (uint i = 0; i < NUM_MODELS; ++i)
  58. {
  59. Node@ modelNode = scene_.CreateChild("Jack");
  60. modelNode.position = Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f);
  61. modelNode.rotation = Quaternion(0.0f, Random(360.0f), 0.0f);
  62. AnimatedModel@ modelObject = modelNode.CreateComponent("AnimatedModel");
  63. modelObject.model = cache.GetResource("Model", "Models/Jack.mdl");
  64. modelObject.material = cache.GetResource("Material", "Materials/Jack.xml");
  65. modelObject.castShadows = true;
  66. // Create an AnimationState for a walk animation. Its time position will need to be manually updated to advance the
  67. // animation, The alternative would be to use an AnimationController component which updates the animation automatically,
  68. // but we need to update the model's position manually in any case
  69. Animation@ walkAnimation = cache.GetResource("Animation", "Models/Jack_Walk.ani");
  70. AnimationState@ state = modelObject.AddAnimationState(walkAnimation);
  71. // Enable full blending weight and looping
  72. state.weight = 1.0f;
  73. state.looped = true;
  74. state.time = Random(walkAnimation.length);
  75. // Create our Mover script object that will move & animate the model during each frame's update. Here we use a shortcut
  76. // script-only API function, CreateScriptObject, which creates a ScriptInstance component into the scene node, then uses
  77. // it to instantiate the object (using the script file & class name provided)
  78. Mover@ mover = cast<Mover>(modelNode.CreateScriptObject(scriptFile, "Mover"));
  79. mover.SetParameters(MODEL_MOVE_SPEED, MODEL_ROTATE_SPEED, bounds);
  80. }
  81. // Create the camera. Limit far clip distance to match the fog
  82. cameraNode = scene_.CreateChild("Camera");
  83. Camera@ camera = cameraNode.CreateComponent("Camera");
  84. camera.farClip = 300.0f;
  85. // Set an initial position for the camera scene node above the plane
  86. cameraNode.position = Vector3(0.0f, 5.0f, 0.0f);
  87. }
  88. void CreateInstructions()
  89. {
  90. // Construct new Text object, set string to display and font to use
  91. Text@ instructionText = ui.root.CreateChild("Text");
  92. instructionText.text =
  93. "Use WASD keys and mouse to move\n"
  94. "Space to toggle debug geometry";
  95. instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
  96. // The text has multiple rows. Center them in relation to each other
  97. instructionText.textAlignment = HA_CENTER;
  98. // Position the text relative to the screen center
  99. instructionText.horizontalAlignment = HA_CENTER;
  100. instructionText.verticalAlignment = VA_CENTER;
  101. instructionText.SetPosition(0, ui.root.height / 4);
  102. }
  103. void SetupViewport()
  104. {
  105. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  106. Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
  107. renderer.viewports[0] = viewport;
  108. }
  109. void SubscribeToEvents()
  110. {
  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. }
  118. void MoveCamera(float timeStep)
  119. {
  120. // Do not move if the UI has a focused element (the console)
  121. if (ui.focusElement !is null)
  122. return;
  123. // Movement speed as world units per second
  124. const float MOVE_SPEED = 20.0f;
  125. // Mouse sensitivity as degrees per pixel
  126. const float MOUSE_SENSITIVITY = 0.1f;
  127. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  128. IntVector2 mouseMove = input.mouseMove;
  129. yaw += MOUSE_SENSITIVITY * mouseMove.x;
  130. pitch += MOUSE_SENSITIVITY * mouseMove.y;
  131. pitch = Clamp(pitch, -90.0f, 90.0f);
  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.0f);
  134. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  135. if (input.keyDown['W'])
  136. cameraNode.Translate(Vector3(0.0f, 0.0f, 1.0f) * MOVE_SPEED * timeStep);
  137. if (input.keyDown['S'])
  138. cameraNode.Translate(Vector3(0.0f, 0.0f, -1.0f) * MOVE_SPEED * timeStep);
  139. if (input.keyDown['A'])
  140. cameraNode.Translate(Vector3(-1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
  141. if (input.keyDown['D'])
  142. cameraNode.Translate(Vector3(1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
  143. // Toggle debug geometry with space
  144. if (input.keyPress[KEY_SPACE])
  145. drawDebug = !drawDebug;
  146. }
  147. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  148. {
  149. // Take the frame time step, which is stored as a float
  150. float timeStep = eventData["TimeStep"].GetFloat();
  151. // Move the camera, scale movement with time step
  152. MoveCamera(timeStep);
  153. }
  154. void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  155. {
  156. // If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
  157. // bones. Note that debug geometry has to be separately requested each frame. Disable depth test so that we can see the
  158. // bones properly
  159. if (drawDebug)
  160. renderer.DrawDebugGeometry(false);
  161. }
  162. // Mover script object class
  163. class Mover : ScriptObject
  164. {
  165. float moveSpeed = 0.0f;
  166. float rotationSpeed = 0.0f;
  167. BoundingBox bounds;
  168. void SetParameters(float moveSpeed_, float rotationSpeed_, const BoundingBox& bounds_)
  169. {
  170. moveSpeed = moveSpeed_;
  171. rotationSpeed = rotationSpeed_;
  172. bounds = bounds_;
  173. }
  174. void Update(float timeStep)
  175. {
  176. node.Translate(Vector3(0.0f, 0.0f, 1.0f) * moveSpeed * timeStep);
  177. // If in risk of going outside the plane, rotate the model right
  178. Vector3 pos = node.position;
  179. if (pos.x < bounds.min.x || pos.x > bounds.max.x || pos.z < bounds.min.z || pos.z > bounds.max.z)
  180. node.Yaw(rotationSpeed * timeStep);
  181. // Get the model's first (only) animation state and advance its time
  182. AnimatedModel@ model = node.GetComponent("AnimatedModel");
  183. AnimationState@ state = model.GetAnimationState(0);
  184. if (state !is null)
  185. state.AddTime(timeStep);
  186. }
  187. }
  188. // Create XML patch instructions for screen joystick layout specific to this sample app
  189. String patchInstructions =
  190. "<patch>"+
  191. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />"+
  192. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>"+
  193. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">"+
  194. " <element type=\"Text\">"+
  195. " <attribute name=\"Name\" value=\"KeyBinding\" />"+
  196. " <attribute name=\"Text\" value=\"SPACE\" />"+
  197. " </element>"+
  198. " </add>"+
  199. "</patch>";