06_SkeletalAnimation.as 10 KB

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