13_Ragdolls.as 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. // Ragdoll example.
  2. // This sample demonstrates:
  3. // - Detecting physics collisions
  4. // - Moving an AnimatedModel's bones with physics and connecting them with constraints
  5. // - Using rolling friction to stop rolling objects from moving infinitely
  6. #include "Scripts/Utilities/Sample.as"
  7. void Start()
  8. {
  9. // Execute the common startup for samples
  10. SampleStart();
  11. // Create the scene content
  12. CreateScene();
  13. // Create the UI content
  14. CreateInstructions();
  15. // Setup the viewport for displaying the scene
  16. SetupViewport();
  17. // Hook up to the frame update and render post-update events
  18. SubscribeToEvents();
  19. }
  20. void CreateScene()
  21. {
  22. scene_ = Scene();
  23. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  24. // Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must
  25. // exist before creating drawable components, the PhysicsWorld must exist before creating physics components.
  26. // Finally, create a DebugRenderer component so that we can draw physics debug geometry
  27. scene_.CreateComponent("Octree");
  28. scene_.CreateComponent("PhysicsWorld");
  29. scene_.CreateComponent("DebugRenderer");
  30. // Create a Zone component for ambient lighting & fog control
  31. Node@ zoneNode = scene_.CreateChild("Zone");
  32. Zone@ zone = zoneNode.CreateComponent("Zone");
  33. zone.boundingBox = BoundingBox(-1000.0f, 1000.0f);
  34. zone.ambientColor = Color(0.15f, 0.15f, 0.15f);
  35. zone.fogColor = Color(0.5f, 0.5f, 0.7f);
  36. zone.fogStart = 100.0f;
  37. zone.fogEnd = 300.0f;
  38. // Create a directional light to the world. Enable cascaded shadows on it
  39. Node@ lightNode = scene_.CreateChild("DirectionalLight");
  40. lightNode.direction = Vector3(0.6f, -1.0f, 0.8f);
  41. Light@ light = lightNode.CreateComponent("Light");
  42. light.lightType = LIGHT_DIRECTIONAL;
  43. light.castShadows = true;
  44. light.shadowBias = BiasParameters(0.00025f, 0.5f);
  45. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  46. light.shadowCascade = CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  47. {
  48. // Create a floor object, 500 x 500 world units. Adjust position so that the ground is at zero Y
  49. Node@ floorNode = scene_.CreateChild("Floor");
  50. floorNode.position = Vector3(0.0f, -0.5f, 0.0f);
  51. floorNode.scale = Vector3(500.0f, 1.0f, 500.0f);
  52. StaticModel@ floorObject = floorNode.CreateComponent("StaticModel");
  53. floorObject.model = cache.GetResource("Model", "Models/Box.mdl");
  54. floorObject.material = cache.GetResource("Material", "Materials/StoneTiled.xml");
  55. // Make the floor physical by adding RigidBody and CollisionShape components
  56. RigidBody@ body = floorNode.CreateComponent("RigidBody");
  57. // We will be spawning spherical objects in this sample. The ground also needs non-zero rolling friction so that
  58. // the spheres will eventually come to rest
  59. body.rollingFriction = 0.15f;
  60. CollisionShape@ shape = floorNode.CreateComponent("CollisionShape");
  61. // 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
  62. // rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.)
  63. shape.SetBox(Vector3(1.0f, 1.0f, 1.0f));
  64. }
  65. // Create animated models
  66. for (int z = -1; z <= 1; ++z)
  67. {
  68. for (int x = -4; x <= 4; ++x)
  69. {
  70. Node@ modelNode = scene_.CreateChild("Jack");
  71. modelNode.position = Vector3(x * 5.0f, 0.0f, z * 5.0f);
  72. modelNode.rotation = Quaternion(0.0f, 180.0f, 0.0f);
  73. AnimatedModel@ modelObject = modelNode.CreateComponent("AnimatedModel");
  74. modelObject.model = cache.GetResource("Model", "Models/Jack.mdl");
  75. modelObject.material = cache.GetResource("Material", "Materials/Jack.xml");
  76. modelObject.castShadows = true;
  77. // Set the model to also update when invisible to avoid staying invisible when the model should come into
  78. // view, but does not as the bounding box is not updated
  79. modelObject.updateInvisible = true;
  80. // Create a rigid body and a collision shape. These will act as a trigger for transforming the
  81. // model into a ragdoll when hit by a moving object
  82. RigidBody@ body = modelNode.CreateComponent("RigidBody");
  83. // The trigger mode makes the rigid body only detect collisions, but impart no forces on the
  84. // colliding objects
  85. body.trigger = true;
  86. CollisionShape@ shape = modelNode.CreateComponent("CollisionShape");
  87. // Create the capsule shape with an offset so that it is correctly aligned with the model, which
  88. // has its origin at the feet
  89. shape.SetCapsule(0.7f, 2.0f, Vector3(0.0f, 1.0f, 0.0f));
  90. // Create a custom script object that reacts to collisions and creates the ragdoll
  91. modelNode.CreateScriptObject(scriptFile, "CreateRagdoll");
  92. }
  93. }
  94. // Create the camera. Limit far clip distance to match the fog. Note: now we actually create the camera node outside
  95. // the scene, because we want it to be unaffected by scene load / save
  96. cameraNode = Node();
  97. Camera@ camera = cameraNode.CreateComponent("Camera");
  98. camera.farClip = 300.0f;
  99. // Set an initial position for the camera scene node above the floor
  100. cameraNode.position = Vector3(0.0f, 5.0f, -20.0f);
  101. }
  102. void CreateInstructions()
  103. {
  104. // Construct new Text object, set string to display and font to use
  105. Text@ instructionText = ui.root.CreateChild("Text");
  106. instructionText.text =
  107. "Use WASD keys and mouse to move\n"
  108. "LMB to spawn physics objects\n"
  109. "F5 to save scene, F7 to load\n"
  110. "Space to toggle physics debug geometry";
  111. instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
  112. // The text has multiple rows. Center them in relation to each other
  113. instructionText.textAlignment = HA_CENTER;
  114. // Position the text relative to the screen center
  115. instructionText.horizontalAlignment = HA_CENTER;
  116. instructionText.verticalAlignment = VA_CENTER;
  117. instructionText.SetPosition(0, ui.root.height / 4);
  118. }
  119. void SetupViewport()
  120. {
  121. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  122. Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
  123. renderer.viewports[0] = viewport;
  124. }
  125. void SubscribeToEvents()
  126. {
  127. // Subscribe HandleUpdate() function for processing update events
  128. SubscribeToEvent("Update", "HandleUpdate");
  129. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  130. // debug geometry
  131. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate");
  132. }
  133. void MoveCamera(float timeStep)
  134. {
  135. // Do not move if the UI has a focused element (the console)
  136. if (ui.focusElement !is null)
  137. return;
  138. // Movement speed as world units per second
  139. const float MOVE_SPEED = 20.0f;
  140. // Mouse sensitivity as degrees per pixel
  141. const float MOUSE_SENSITIVITY = 0.1f;
  142. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  143. IntVector2 mouseMove = input.mouseMove;
  144. yaw += MOUSE_SENSITIVITY * mouseMove.x;
  145. pitch += MOUSE_SENSITIVITY * mouseMove.y;
  146. pitch = Clamp(pitch, -90.0f, 90.0f);
  147. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  148. cameraNode.rotation = Quaternion(pitch, yaw, 0.0f);
  149. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  150. if (input.keyDown['W'])
  151. cameraNode.Translate(Vector3(0.0f, 0.0f, 1.0f) * MOVE_SPEED * timeStep);
  152. if (input.keyDown['S'])
  153. cameraNode.Translate(Vector3(0.0f, 0.0f, -1.0f) * MOVE_SPEED * timeStep);
  154. if (input.keyDown['A'])
  155. cameraNode.Translate(Vector3(-1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
  156. if (input.keyDown['D'])
  157. cameraNode.Translate(Vector3(1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
  158. // "Shoot" a physics object with left mousebutton
  159. if (input.mouseButtonPress[MOUSEB_LEFT])
  160. SpawnObject();
  161. // Check for loading / saving the scene
  162. if (input.keyPress[KEY_F5])
  163. {
  164. File saveFile(fileSystem.programDir + "Data/Scenes/Ragdolls.xml", FILE_WRITE);
  165. scene_.SaveXML(saveFile);
  166. }
  167. if (input.keyPress[KEY_F7])
  168. {
  169. File loadFile(fileSystem.programDir + "Data/Scenes/Ragdolls.xml", FILE_READ);
  170. scene_.LoadXML(loadFile);
  171. }
  172. // Toggle debug geometry with space
  173. if (input.keyPress[KEY_SPACE])
  174. drawDebug = !drawDebug;
  175. }
  176. void SpawnObject()
  177. {
  178. Node@ boxNode = scene_.CreateChild("Sphere");
  179. boxNode.position = cameraNode.position;
  180. boxNode.rotation = cameraNode.rotation;
  181. boxNode.SetScale(0.25f);
  182. StaticModel@ boxObject = boxNode.CreateComponent("StaticModel");
  183. boxObject.model = cache.GetResource("Model", "Models/Sphere.mdl");
  184. boxObject.material = cache.GetResource("Material", "Materials/StoneSmall.xml");
  185. boxObject.castShadows = true;
  186. RigidBody@ body = boxNode.CreateComponent("RigidBody");
  187. body.mass = 1.0f;
  188. body.rollingFriction = 0.15f;
  189. CollisionShape@ shape = boxNode.CreateComponent("CollisionShape");
  190. shape.SetSphere(1.0f);
  191. const float OBJECT_VELOCITY = 10.0f;
  192. // Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component
  193. // to overcome gravity better
  194. body.linearVelocity = cameraNode.rotation * Vector3(0.0f, 0.25f, 1.0f) * OBJECT_VELOCITY;
  195. }
  196. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  197. {
  198. // Take the frame time step, which is stored as a float
  199. float timeStep = eventData["TimeStep"].GetFloat();
  200. // Move the camera, scale movement with time step
  201. MoveCamera(timeStep);
  202. }
  203. void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  204. {
  205. // If draw debug mode is enabled, draw physics debug geometry. Use depth test to make the result easier to interpret
  206. if (drawDebug)
  207. scene_.physicsWorld.DrawDebugGeometry(true);
  208. }
  209. // CreateRagdoll script object class
  210. class CreateRagdoll : ScriptObject
  211. {
  212. void Start()
  213. {
  214. // Subscribe physics collisions that concern this scene node
  215. SubscribeToEvent(node, "NodeCollision", "HandleNodeCollision");
  216. }
  217. void HandleNodeCollision(StringHash eventType, VariantMap& eventData)
  218. {
  219. // Get the other colliding body, make sure it is moving (has nonzero mass)
  220. RigidBody@ otherBody = eventData["OtherBody"].GetPtr();
  221. if (otherBody.mass > 0.0f)
  222. {
  223. // We do not need the physics components in the AnimatedModel's root scene node anymore
  224. node.RemoveComponent("RigidBody");
  225. node.RemoveComponent("CollisionShape");
  226. // Create RigidBody & CollisionShape components to bones
  227. CreateRagdollBone("Bip01_Pelvis", SHAPE_BOX, Vector3(0.3f, 0.2f, 0.25f), Vector3(0.0f, 0.0f, 0.0f),
  228. Quaternion(0.0f, 0.0f, 0.0f));
  229. CreateRagdollBone("Bip01_Spine1", SHAPE_BOX, Vector3(0.35f, 0.2f, 0.3f), Vector3(0.15f, 0.0f, 0.0f),
  230. Quaternion(0.0f, 0.0f, 0.0f));
  231. CreateRagdollBone("Bip01_L_Thigh", SHAPE_CAPSULE, Vector3(0.175f, 0.45f, 0.175f), Vector3(0.25f, 0.0f, 0.0f),
  232. Quaternion(0.0f, 0.0f, 90.0f));
  233. CreateRagdollBone("Bip01_R_Thigh", SHAPE_CAPSULE, Vector3(0.175f, 0.45f, 0.175f), Vector3(0.25f, 0.0f, 0.0f),
  234. Quaternion(0.0f, 0.0f, 90.0f));
  235. CreateRagdollBone("Bip01_L_Calf", SHAPE_CAPSULE, Vector3(0.15f, 0.55f, 0.15f), Vector3(0.25f, 0.0f, 0.0f),
  236. Quaternion(0.0f, 0.0f, 90.0f));
  237. CreateRagdollBone("Bip01_R_Calf", SHAPE_CAPSULE, Vector3(0.15f, 0.55f, 0.15f), Vector3(0.25f, 0.0f, 0.0f),
  238. Quaternion(0.0f, 0.0f, 90.0f));
  239. CreateRagdollBone("Bip01_Head", SHAPE_BOX, Vector3(0.2f, 0.2f, 0.2f), Vector3(0.1f, 0.0f, 0.0f),
  240. Quaternion(0.0f, 0.0f, 0.0f));
  241. CreateRagdollBone("Bip01_L_UpperArm", SHAPE_CAPSULE, Vector3(0.15f, 0.35f, 0.15f), Vector3(0.1f, 0.0f, 0.0f),
  242. Quaternion(0.0f, 0.0f, 90.0f));
  243. CreateRagdollBone("Bip01_R_UpperArm", SHAPE_CAPSULE, Vector3(0.15f, 0.35f, 0.15f), Vector3(0.1f, 0.0f, 0.0f),
  244. Quaternion(0.0f, 0.0f, 90.0f));
  245. CreateRagdollBone("Bip01_L_Forearm", SHAPE_CAPSULE, Vector3(0.125f, 0.4f, 0.125f), Vector3(0.2f, 0.0f, 0.0f),
  246. Quaternion(0.0f, 0.0f, 90.0f));
  247. CreateRagdollBone("Bip01_R_Forearm", SHAPE_CAPSULE, Vector3(0.125f, 0.4f, 0.125f), Vector3(0.2f, 0.0f, 0.0f),
  248. Quaternion(0.0f, 0.0f, 90.0f));
  249. // Create Constraints between bones
  250. CreateRagdollConstraint("Bip01_L_Thigh", "Bip01_Pelvis", CONSTRAINT_CONETWIST, Vector3(0.0f, 0.0f, -1.0f),
  251. Vector3(0.0f, 0.0f, 1.0f), Vector2(45.0f, 45.0f), Vector2(0.0f, 0.0f));
  252. CreateRagdollConstraint("Bip01_R_Thigh", "Bip01_Pelvis", CONSTRAINT_CONETWIST, Vector3(0.0f, 0.0f, -1.0f),
  253. Vector3(0.0f, 0.0f, 1.0f), Vector2(45.0f, 45.0f), Vector2(0.0f, 0.0f));
  254. CreateRagdollConstraint("Bip01_L_Calf", "Bip01_L_Thigh", CONSTRAINT_HINGE, Vector3(0.0f, 0.0f, -1.0f),
  255. Vector3(0.0f, 0.0f, -1.0f), Vector2(90.0f, 0.0f), Vector2(0.0f, 0.0f));
  256. CreateRagdollConstraint("Bip01_R_Calf", "Bip01_R_Thigh", CONSTRAINT_HINGE, Vector3(0.0f, 0.0f, -1.0f),
  257. Vector3(0.0f, 0.0f, -1.0f), Vector2(90.0f, 0.0f), Vector2(0.0f, 0.0f));
  258. CreateRagdollConstraint("Bip01_Spine1", "Bip01_Pelvis", CONSTRAINT_HINGE, Vector3(0.0f, 0.0f, 1.0f),
  259. Vector3(0.0f, 0.0f, 1.0f), Vector2(45.0f, 0.0f), Vector2(-10.0f, 0.0f));
  260. CreateRagdollConstraint("Bip01_Head", "Bip01_Spine1", CONSTRAINT_CONETWIST, Vector3(-1.0f, 0.0f, 0.0f),
  261. Vector3(-1.0f, 0.0f, 0.0f), Vector2(0.0f, 30.0f), Vector2(0.0f, 0.0f));
  262. CreateRagdollConstraint("Bip01_L_UpperArm", "Bip01_Spine1", CONSTRAINT_CONETWIST, Vector3(0.0f, -1.0f, 0.0f),
  263. Vector3(0.0f, 1.0f, 0.0f), Vector2(45.0f, 45.0f), Vector2(0.0f, 0.0f), false);
  264. CreateRagdollConstraint("Bip01_R_UpperArm", "Bip01_Spine1", CONSTRAINT_CONETWIST, Vector3(0.0f, -1.0f, 0.0f),
  265. Vector3(0.0f, 1.0f, 0.0f), Vector2(45.0f, 45.0f), Vector2(0.0f, 0.0f), false);
  266. CreateRagdollConstraint("Bip01_L_Forearm", "Bip01_L_UpperArm", CONSTRAINT_HINGE, Vector3(0.0f, 0.0f, -1.0f),
  267. Vector3(0.0f, 0.0f, -1.0f), Vector2(90.0f, 0.0f), Vector2(0.0f, 0.0f));
  268. CreateRagdollConstraint("Bip01_R_Forearm", "Bip01_R_UpperArm", CONSTRAINT_HINGE, Vector3(0.0f, 0.0f, -1.0f),
  269. Vector3(0.0f, 0.0f, -1.0f), Vector2(90.0f, 0.0f), Vector2(0.0f, 0.0f));
  270. // Disable keyframe animation from all bones so that they will not interfere with the ragdoll
  271. AnimatedModel@ model = node.GetComponent("AnimatedModel");
  272. Skeleton@ skeleton = model.skeleton;
  273. for (uint i = 0; i < skeleton.numBones; ++i)
  274. skeleton.bones[i].animated = false;
  275. // Finally remove self (the ScriptInstance which holds this script object) from the scene node. Note that this must
  276. // be the last operation performed in the function
  277. self.Remove();
  278. }
  279. }
  280. void CreateRagdollBone(const String&in boneName, ShapeType type, const Vector3&in size, const Vector3&in position,
  281. const Quaternion&in rotation)
  282. {
  283. // Find the correct child scene node recursively
  284. Node@ boneNode = node.GetChild(boneName, true);
  285. if (boneNode is null)
  286. {
  287. log.Warning("Could not find bone " + boneName + " for creating ragdoll physics components");
  288. return;
  289. }
  290. RigidBody@ body = boneNode.CreateComponent("RigidBody");
  291. // Set mass to make movable
  292. body.mass = 1.0f;
  293. // Set damping parameters to smooth out the motion
  294. body.linearDamping = 0.05f;
  295. body.angularDamping = 0.85f;
  296. // Set rest thresholds to ensure the ragdoll rigid bodies come to rest to not consume CPU endlessly
  297. body.linearRestThreshold = 1.5f;
  298. body.angularRestThreshold = 2.5f;
  299. CollisionShape@ shape = boneNode.CreateComponent("CollisionShape");
  300. // We use either a box or a capsule shape for all of the bones
  301. if (type == SHAPE_BOX)
  302. shape.SetBox(size, position, rotation);
  303. else
  304. shape.SetCapsule(size.x, size.y, position, rotation);
  305. }
  306. void CreateRagdollConstraint(const String&in boneName, const String&in parentName, ConstraintType type,
  307. const Vector3&in axis, const Vector3&in parentAxis, const Vector2&in highLimit, const Vector2&in lowLimit,
  308. bool disableCollision = true)
  309. {
  310. Node@ boneNode = node.GetChild(boneName, true);
  311. Node@ parentNode = node.GetChild(parentName, true);
  312. if (boneNode is null)
  313. {
  314. log.Warning("Could not find bone " + boneName + " for creating ragdoll constraint");
  315. return;
  316. }
  317. if (parentNode is null)
  318. {
  319. log.Warning("Could not find bone " + parentName + " for creating ragdoll constraint");
  320. return;
  321. }
  322. Constraint@ constraint = boneNode.CreateComponent("Constraint");
  323. constraint.constraintType = type;
  324. // Most of the constraints in the ragdoll will work better when the connected bodies don't collide against each other
  325. constraint.disableCollision = disableCollision;
  326. // The connected body must be specified before setting the world position
  327. constraint.otherBody = parentNode.GetComponent("RigidBody");
  328. // Position the constraint at the child bone we are connecting
  329. constraint.worldPosition = boneNode.worldPosition;
  330. // Configure axes and limits
  331. constraint.axis = axis;
  332. constraint.otherAxis = parentAxis;
  333. constraint.highLimit = highLimit;
  334. constraint.lowLimit = lowLimit;
  335. }
  336. }
  337. // Create XML patch instructions for screen joystick layout specific to this sample app
  338. String patchInstructions =
  339. "<patch>" +
  340. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" +
  341. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Spawn</replace>" +
  342. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" +
  343. " <element type=\"Text\">" +
  344. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" +
  345. " <attribute name=\"Text\" value=\"LEFT\" />" +
  346. " </element>" +
  347. " </add>" +
  348. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" +
  349. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" +
  350. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" +
  351. " <element type=\"Text\">" +
  352. " <attribute name=\"Name\" value=\"KeyBinding\" />" +
  353. " <attribute name=\"Text\" value=\"SPACE\" />" +
  354. " </element>" +
  355. " </add>" +
  356. "</patch>";