06_SkeletalAnimation.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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. Camera camera;
  31. bool drawDebug;
  32. public SkeletalAnimationSample() : base() { }
  33. void CreateScene()
  34. {
  35. var cache = GetSubsystem<ResourceCache>();
  36. scene = new Scene();
  37. // Create the Octree component to the scene so that drawable objects can be rendered. Use default volume
  38. // (-1000, -1000, -1000) to (1000, 1000, 1000)
  39. scene.CreateComponent<Octree>();
  40. scene.CreateComponent<DebugRenderer>();
  41. // Create scene node & StaticModel component for showing a static plane
  42. var planeNode = scene.CreateChild("Plane");
  43. planeNode.Scale = new Vector3(100, 1, 100);
  44. var planeObject = planeNode.CreateComponent<StaticModel>();
  45. planeObject.Model = cache.Get<Model>("Models/Plane.mdl");
  46. planeObject.SetMaterial(cache.Get<Material>("Materials/StoneTiled.xml"));
  47. // Create a Zone component for ambient lighting & fog control
  48. var zoneNode = scene.CreateChild("Zone");
  49. var zone = zoneNode.CreateComponent<Zone>();
  50. // Set same volume as the Octree, set a close bluish fog and some ambient light
  51. zone.SetBoundingBox(new BoundingBox(-1000.0f, 1000.0f));
  52. zone.AmbientColor = new Color(0.15f, 0.15f, 0.15f);
  53. zone.FogColor = new Color(0.5f, 0.5f, 0.7f);
  54. zone.FogStart = 100;
  55. zone.FogEnd = 300;
  56. // Create a directional light to the world. Enable cascaded shadows on it
  57. var lightNode = scene.CreateChild("DirectionalLight");
  58. lightNode.SetDirection(new Vector3(0.6f, -1.0f, 0.8f));
  59. var light = lightNode.CreateComponent<Light>();
  60. light.LightType = LightType.LIGHT_DIRECTIONAL;
  61. light.CastShadows = true;
  62. light.ShadowBias = new BiasParameters(0.00025f, 0.5f);
  63. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  64. light.ShadowCascade = new CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  65. // Create animated models
  66. const int numModels = 100;
  67. const float modelMoveSpeed = 2.0f;
  68. const float modelRotateSpeed = 100.0f;
  69. var bounds = new BoundingBox(new Vector3(-47.0f, 0.0f, -47.0f), new Vector3(47.0f, 0.0f, 47.0f));
  70. for (var i = 0; i < numModels; ++i)
  71. {
  72. var modelNode = scene.CreateChild("Jack");
  73. modelNode.Position = new Vector3(NextRandom(-45, 45), 0.0f, NextRandom(-45, 45));
  74. modelNode.Rotation = new Quaternion(0, NextRandom(0, 360), 0);
  75. //var modelObject = modelNode.CreateComponent<AnimatedModel>();
  76. var modelObject = new AnimatedModel();
  77. modelNode.AddComponent(modelObject);
  78. modelObject.Model = cache.Get<Model>("Models/Jack.mdl");
  79. //modelObject.Material = cache.GetMaterial("Materials/Jack.xml");
  80. modelObject.CastShadows = true;
  81. // Create an AnimationState for a walk animation. Its time position will need to be manually updated to advance the
  82. // animation, The alternative would be to use an AnimationController component which updates the animation automatically,
  83. // but we need to update the model's position manually in any case
  84. var walkAnimation = cache.Get<Animation>("Models/Jack_Walk.ani");
  85. var state = modelObject.AddAnimationState(walkAnimation);
  86. // The state would fail to create (return null) if the animation was not found
  87. if (state != null)
  88. {
  89. // Enable full blending weight and looping
  90. state.Weight = 1;
  91. state.Looped = true;
  92. }
  93. // Create our custom Mover component that will move & animate the model during each frame's update
  94. var mover = new Mover(modelMoveSpeed, modelRotateSpeed, bounds);
  95. modelNode.AddComponent(mover);
  96. }
  97. // Create the camera. Limit far clip distance to match the fog
  98. CameraNode = scene.CreateChild("Camera");
  99. camera = CameraNode.CreateComponent<Camera>();
  100. camera.FarClip = 300;
  101. // Set an initial position for the camera scene node above the plane
  102. CameraNode.Position = new Vector3(0.0f, 5.0f, 0.0f);
  103. }
  104. void SetupViewport()
  105. {
  106. var renderer = GetSubsystem<Renderer>();
  107. renderer.SetViewport(0, new Viewport(scene, camera));
  108. }
  109. protected override void Update(float timeStep)
  110. {
  111. base.Update(timeStep);
  112. SimpleMoveCamera3D(timeStep);
  113. var input = GetSubsystem<Input>();
  114. if (input.GetKeyPress(Constants.KEY_SPACE))
  115. drawDebug = !drawDebug;
  116. }
  117. void SubscribeToEvents()
  118. {
  119. // Subscribe HandlePostRenderUpdate() function for
  120. // processing the post-render update event, sent after
  121. // Renderer subsystem is done with defining the draw
  122. // calls for the viewports (but before actually
  123. // executing them.) We will request debug geometry
  124. // rendering during that event
  125. SubscribeToEvent<PostRenderUpdateEvent>(e =>
  126. {
  127. // If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
  128. // bones. Note that debug geometry has to be separately requested each frame. Disable depth test so that we can see the
  129. // bones properly
  130. if (drawDebug)
  131. {
  132. GetSubsystem<Renderer>().DrawDebugGeometry(false);
  133. }
  134. });
  135. }
  136. public override void Start()
  137. {
  138. base.Start();
  139. CreateScene();
  140. SimpleCreateInstructionsWithWasd("\nSpace to toggle debug geometry");
  141. SetupViewport();
  142. SubscribeToEvents();
  143. }
  144. // protected override string JoystickLayoutPatch => JoystickLayoutPatches.WithDebugButton;
  145. class Mover : CSComponent
  146. {
  147. float MoveSpeed { get; }
  148. float RotationSpeed { get; }
  149. BoundingBox Bounds { get; }
  150. AnimationState animState;
  151. public Mover(float moveSpeed, float rotateSpeed, BoundingBox bounds)
  152. {
  153. MoveSpeed = moveSpeed;
  154. RotationSpeed = rotateSpeed;
  155. Bounds = bounds;
  156. }
  157. void Start()
  158. {
  159. // Get the model's first (only) animation
  160. // state and advance its time. Note the
  161. // convenience accessor to other components in
  162. // the same scene node
  163. var model = GetComponent<AnimatedModel>();
  164. if (model.NumAnimationStates > 0)
  165. {
  166. animState = model.AnimationStates.First();
  167. }
  168. }
  169. void Update(float timeStep)
  170. {
  171. // This moves the character position
  172. Node.Translate(Vector3.UnitZ * MoveSpeed * timeStep, TransformSpace.TS_LOCAL);
  173. // If in risk of going outside the plane, rotate the model right
  174. var pos = Node.Position;
  175. if (pos.X < Bounds.Min.X || pos.X > Bounds.Max.X || pos.Z < Bounds.Min.Z || pos.Z > Bounds.Max.Z)
  176. Node.Yaw(RotationSpeed * timeStep, TransformSpace.TS_LOCAL);
  177. if (animState != null)
  178. animState.AddTime(timeStep);
  179. }
  180. }
  181. }
  182. }