11_Physics.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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 AtomicEngine;
  25. namespace FeatureExamples
  26. {
  27. public class PhysicsSample : Sample
  28. {
  29. bool drawDebug;
  30. public PhysicsSample() : base() { }
  31. public override void Start()
  32. {
  33. base.Start();
  34. CreateScene();
  35. SimpleCreateInstructionsWithWasd(
  36. "\nLMB to spawn physics objects\n" +
  37. "F5 to save scene, F7 to load\n" +
  38. "Space to toggle physics debug geometry");
  39. SetupViewport();
  40. SubscribeToEvents();
  41. }
  42. void SubscribeToEvents()
  43. {
  44. // Subscribe HandlePostRenderUpdate() function for
  45. // processing the post-render update event, sent after
  46. // Renderer subsystem is done with defining the draw
  47. // calls for the viewports (but before actually
  48. // executing them.) We will request debug geometry
  49. // rendering during that event
  50. SubscribeToEvent<PostRenderUpdateEvent>(e =>
  51. {
  52. // If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
  53. // bones. Note that debug geometry has to be separately requested each frame. Disable depth test so that we can see the
  54. // bones properly
  55. if (drawDebug)
  56. {
  57. GetSubsystem<Renderer>().DrawDebugGeometry(false);
  58. }
  59. });
  60. }
  61. protected override void Update(float timeStep)
  62. {
  63. base.Update(timeStep);
  64. var input = GetSubsystem<Input>();
  65. var fileSystem = GetSubsystem<FileSystem>();
  66. SimpleMoveCamera3D(timeStep);
  67. if (input.GetMouseButtonPress(Constants.MOUSEB_LEFT))
  68. SpawnObject();
  69. /* TODO: Scene.SaveXML/Scene.LoadXML
  70. if (input.GetKeyPress(Constants.KEY_F5))
  71. scene.SaveXml(fileSystem.UserDocumentsDir + "/Scenes/Physics.xml");
  72. if (input.GetKeyPress(Constants.KEY_F7))
  73. scene.LoadXml(fileSystem.UserDocumentsDir + "/Scenes/Physics.xml");
  74. */
  75. if (input.GetKeyPress(Constants.KEY_SPACE))
  76. drawDebug = !drawDebug;
  77. }
  78. void SetupViewport()
  79. {
  80. var renderer = GetSubsystem<Renderer>();
  81. renderer.SetViewport(0, new Viewport(scene, CameraNode.GetComponent<Camera>()));
  82. }
  83. void CreateScene()
  84. {
  85. var cache = GetSubsystem<ResourceCache>();
  86. scene = new Scene();
  87. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  88. // Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must
  89. // exist before creating drawable components, the PhysicsWorld must exist before creating physics components.
  90. // Finally, create a DebugRenderer component so that we can draw physics debug geometry
  91. scene.CreateComponent<Octree>();
  92. scene.CreateComponent<PhysicsWorld>();
  93. scene.CreateComponent<DebugRenderer>();
  94. // Create a Zone component for ambient lighting & fog control
  95. Node zoneNode = scene.CreateChild("Zone");
  96. Zone zone = zoneNode.CreateComponent<Zone>();
  97. zone.SetBoundingBox(new BoundingBox(-1000.0f, 1000.0f));
  98. zone.AmbientColor = new Color(0.15f, 0.15f, 0.15f);
  99. zone.FogColor = new Color(1.0f, 1.0f, 1.0f);
  100. zone.FogStart = 300.0f;
  101. zone.FogEnd = 500.0f;
  102. // Create a directional light to the world. Enable cascaded shadows on it
  103. Node lightNode = scene.CreateChild("DirectionalLight");
  104. lightNode.SetDirection(new Vector3(0.6f, -1.0f, 0.8f));
  105. Light light = lightNode.CreateComponent<Light>();
  106. light.LightType = LightType.LIGHT_DIRECTIONAL;
  107. light.CastShadows = true;
  108. light.ShadowBias = new BiasParameters(0.00025f, 0.5f);
  109. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  110. light.ShadowCascade = new CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  111. // Create skybox. The Skybox component is used like StaticModel, but it will be always located at the camera, giving the
  112. // illusion of the box planes being far away. Use just the ordinary Box model and a suitable material, whose shader will
  113. // generate the necessary 3D texture coordinates for cube mapping
  114. Node skyNode = scene.CreateChild("Sky");
  115. skyNode.SetScale(500.0f); // The scale actually does not matter
  116. Skybox skybox = skyNode.CreateComponent<Skybox>();
  117. skybox.Model = cache.Get<Model>("Models/Box.mdl");
  118. skybox.SetMaterial(cache.Get<Material>("Materials/Skybox.xml"));
  119. {
  120. // Create a floor object, 1000 x 1000 world units. Adjust position so that the ground is at zero Y
  121. Node floorNode = scene.CreateChild("Floor");
  122. floorNode.Position = new Vector3(0.0f, -0.5f, 0.0f);
  123. floorNode.Scale = new Vector3(1000.0f, 1.0f, 1000.0f);
  124. StaticModel floorObject = floorNode.CreateComponent<StaticModel>();
  125. floorObject.Model = cache.Get<Model>("Models/Box.mdl");
  126. floorObject.SetMaterial(cache.Get<Material>("Materials/StoneTiled.xml"));
  127. // Make the floor physical by adding RigidBody and CollisionShape components. The RigidBody's default
  128. // parameters make the object static (zero mass.) Note that a CollisionShape by itself will not participate
  129. // in the physics simulation
  130. floorNode.CreateComponent<RigidBody>();
  131. CollisionShape shape = floorNode.CreateComponent<CollisionShape>();
  132. // Set a box shape of size 1 x 1 x 1 for collision. The shape will be scaled with the scene node scale, so the
  133. // rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.)
  134. shape.SetBox(Vector3.One, Vector3.Zero, Quaternion.Identity);
  135. }
  136. {
  137. // Create a pyramid of movable physics objects
  138. for (int y = 0; y < 8; ++y)
  139. {
  140. for (int x = -y; x <= y; ++x)
  141. {
  142. Node boxNode = scene.CreateChild("Box");
  143. boxNode.Position = new Vector3((float)x, -(float)y + 8.0f, 0.0f);
  144. StaticModel boxObject = boxNode.CreateComponent<StaticModel>();
  145. boxObject.Model = cache.Get<Model>("Models/Box.mdl");
  146. boxObject.SetMaterial(cache.Get<Material>("Materials/StoneEnvMapSmall.xml"));
  147. boxObject.CastShadows = true;
  148. // Create RigidBody and CollisionShape components like above. Give the RigidBody mass to make it movable
  149. // and also adjust friction. The actual mass is not important; only the mass ratios between colliding
  150. // objects are significant
  151. RigidBody body = boxNode.CreateComponent<RigidBody>();
  152. body.Mass = 1.0f;
  153. body.Friction = 0.75f;
  154. CollisionShape shape = boxNode.CreateComponent<CollisionShape>();
  155. shape.SetBox(Vector3.One, Vector3.Zero, Quaternion.Identity);
  156. }
  157. }
  158. }
  159. // Create the camera. Limit far clip distance to match the fog. Note: now we actually create the camera node outside
  160. // the scene, because we want it to be unaffected by scene load / save
  161. CameraNode = new Node();
  162. Camera camera = CameraNode.CreateComponent<Camera>();
  163. camera.FarClip = 500.0f;
  164. // Set an initial position for the camera scene node above the floor
  165. CameraNode.Position = (new Vector3(0.0f, 5.0f, -20.0f));
  166. }
  167. void SpawnObject()
  168. {
  169. var cache = GetSubsystem<ResourceCache>();
  170. var boxNode = scene.CreateChild("SmallBox");
  171. boxNode.Position = CameraNode.Position;
  172. boxNode.Rotation = CameraNode.Rotation;
  173. boxNode.SetScale(0.25f);
  174. StaticModel boxModel = boxNode.CreateComponent<StaticModel>();
  175. boxModel.Model = cache.Get<Model>("Models/Box.mdl");
  176. boxModel.SetMaterial(cache.Get<Material>("Materials/StoneEnvMapSmall.xml"));
  177. boxModel.CastShadows = true;
  178. var body = boxNode.CreateComponent<RigidBody>();
  179. body.Mass = 0.25f;
  180. body.Friction = 0.75f;
  181. var shape = boxNode.CreateComponent<CollisionShape>();
  182. shape.SetBox(Vector3.One, Vector3.Zero, Quaternion.Identity);
  183. const float objectVelocity = 10.0f;
  184. body.SetLinearVelocity(CameraNode.Rotation * new Vector3(0f, 0.25f, 1f) * objectVelocity);
  185. }
  186. }
  187. }