06_SkeletalAnimation.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. // Copyright (c) 2015 Xamarin Inc
  4. // Copyright (c) 2016 THUNDERBEAST GAMES LLC
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. using System.Linq;
  25. using AtomicEngine;
  26. namespace FeatureExamples
  27. {
  28. public class SkeletalAnimationSample : Sample
  29. {
  30. Scene scene;
  31. Camera camera;
  32. bool drawDebug;
  33. public SkeletalAnimationSample() : base() { }
  34. void CreateScene()
  35. {
  36. var cache = GetSubsystem<ResourceCache>();
  37. scene = new Scene();
  38. // Create the Octree component to the scene so that drawable objects can be rendered. Use default volume
  39. // (-1000, -1000, -1000) to (1000, 1000, 1000)
  40. scene.CreateComponent<Octree>();
  41. scene.CreateComponent<DebugRenderer>();
  42. // Create scene node & StaticModel component for showing a static plane
  43. var planeNode = scene.CreateChild("Plane");
  44. planeNode.Scale = new Vector3(100, 1, 100);
  45. var planeObject = planeNode.CreateComponent<StaticModel>();
  46. planeObject.Model = cache.Get<Model>("Models/Plane.mdl");
  47. planeObject.SetMaterial(cache.Get<Material>("Materials/StoneTiled.xml"));
  48. // Create a Zone component for ambient lighting & fog control
  49. var zoneNode = scene.CreateChild("Zone");
  50. var zone = zoneNode.CreateComponent<Zone>();
  51. // Set same volume as the Octree, set a close bluish fog and some ambient light
  52. zone.SetBoundingBox(new BoundingBox(-1000.0f, 1000.0f));
  53. zone.AmbientColor = new Color(0.15f, 0.15f, 0.15f);
  54. zone.FogColor = new Color(0.5f, 0.5f, 0.7f);
  55. zone.FogStart = 100;
  56. zone.FogEnd = 300;
  57. // Create a directional light to the world. Enable cascaded shadows on it
  58. var lightNode = scene.CreateChild("DirectionalLight");
  59. lightNode.SetDirection(new Vector3(0.6f, -1.0f, 0.8f));
  60. var light = lightNode.CreateComponent<Light>();
  61. light.LightType = LightType.LIGHT_DIRECTIONAL;
  62. light.CastShadows = true;
  63. light.ShadowBias = new BiasParameters(0.00025f, 0.5f);
  64. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  65. light.ShadowCascade = new CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  66. // Create animated models
  67. const int numModels = 100;
  68. const float modelMoveSpeed = 2.0f;
  69. const float modelRotateSpeed = 100.0f;
  70. var bounds = new BoundingBox(new Vector3(-47.0f, 0.0f, -47.0f), new Vector3(47.0f, 0.0f, 47.0f));
  71. for (var i = 0; i < numModels; ++i)
  72. {
  73. var modelNode = scene.CreateChild("Jack");
  74. modelNode.Position = new Vector3(NextRandom(-45, 45), 0.0f, NextRandom(-45, 45));
  75. modelNode.Rotation = new Quaternion(0, NextRandom(0, 360), 0);
  76. //var modelObject = modelNode.CreateComponent<AnimatedModel>();
  77. var modelObject = new AnimatedModel();
  78. modelNode.AddComponent(modelObject);
  79. modelObject.Model = cache.Get<Model>("Models/Jack.mdl");
  80. //modelObject.Material = cache.GetMaterial("Materials/Jack.xml");
  81. modelObject.CastShadows = true;
  82. // Create an AnimationState for a walk animation. Its time position will need to be manually updated to advance the
  83. // animation, The alternative would be to use an AnimationController component which updates the animation automatically,
  84. // but we need to update the model's position manually in any case
  85. var walkAnimation = cache.Get<Animation>("Models/Jack_Walk.ani");
  86. var state = modelObject.AddAnimationState(walkAnimation);
  87. // The state would fail to create (return null) if the animation was not found
  88. if (state != null)
  89. {
  90. // Enable full blending weight and looping
  91. state.Weight = 1;
  92. state.Looped = true;
  93. }
  94. // Create our custom Mover component that will move & animate the model during each frame's update
  95. var mover = new Mover(modelMoveSpeed, modelRotateSpeed, bounds);
  96. modelNode.AddComponent(mover);
  97. }
  98. // Create the camera. Limit far clip distance to match the fog
  99. CameraNode = scene.CreateChild("Camera");
  100. camera = CameraNode.CreateComponent<Camera>();
  101. camera.FarClip = 300;
  102. // Set an initial position for the camera scene node above the plane
  103. CameraNode.Position = new Vector3(0.0f, 5.0f, 0.0f);
  104. }
  105. void SetupViewport()
  106. {
  107. var renderer = GetSubsystem<Renderer>();
  108. renderer.SetViewport(0, new Viewport(scene, camera));
  109. }
  110. protected override void Update(float timeStep)
  111. {
  112. base.Update(timeStep);
  113. SimpleMoveCamera3D(timeStep);
  114. var input = GetSubsystem<Input>();
  115. if (input.GetKeyPress(Constants.KEY_SPACE))
  116. drawDebug = !drawDebug;
  117. }
  118. void SubscribeToEvents()
  119. {
  120. // Subscribe HandlePostRenderUpdate() function for
  121. // processing the post-render update event, sent after
  122. // Renderer subsystem is done with defining the draw
  123. // calls for the viewports (but before actually
  124. // executing them.) We will request debug geometry
  125. // rendering during that event
  126. SubscribeToEvent<PostRenderUpdateEvent>(e =>
  127. {
  128. // If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
  129. // bones. Note that debug geometry has to be separately requested each frame. Disable depth test so that we can see the
  130. // bones properly
  131. if (drawDebug)
  132. {
  133. GetSubsystem<Renderer>().DrawDebugGeometry(false);
  134. }
  135. });
  136. }
  137. public override void Start()
  138. {
  139. base.Start();
  140. CreateScene();
  141. SimpleCreateInstructionsWithWasd("\nSpace to toggle debug geometry");
  142. SetupViewport();
  143. SubscribeToEvents();
  144. }
  145. // protected override string JoystickLayoutPatch => JoystickLayoutPatches.WithDebugButton;
  146. class Mover : CSComponent
  147. {
  148. float MoveSpeed { get; }
  149. float RotationSpeed { get; }
  150. BoundingBox Bounds { get; }
  151. AnimationState animState;
  152. public Mover(float moveSpeed, float rotateSpeed, BoundingBox bounds)
  153. {
  154. MoveSpeed = moveSpeed;
  155. RotationSpeed = rotateSpeed;
  156. Bounds = bounds;
  157. }
  158. void Start()
  159. {
  160. // Get the model's first (only) animation
  161. // state and advance its time. Note the
  162. // convenience accessor to other components in
  163. // the same scene node
  164. var model = GetComponent<AnimatedModel>();
  165. if (model.NumAnimationStates > 0)
  166. {
  167. animState = model.AnimationStates.First();
  168. }
  169. }
  170. void Update(float timeStep)
  171. {
  172. // This moves the character position
  173. Node.Translate(Vector3.UnitZ * MoveSpeed * timeStep, TransformSpace.TS_LOCAL);
  174. // If in risk of going outside the plane, rotate the model right
  175. var pos = Node.Position;
  176. if (pos.X < Bounds.Min.X || pos.X > Bounds.Max.X || pos.Z < Bounds.Min.Z || pos.Z > Bounds.Max.Z)
  177. Node.Yaw(RotationSpeed * timeStep, TransformSpace.TS_LOCAL);
  178. if (animState != null)
  179. animState.AddTime(timeStep);
  180. }
  181. }
  182. }
  183. }