13_Ragdolls.as 20 KB

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