rigidbody: Add rigid body constraints
[blender.git] / source / blender / blenkernel / intern / rigidbody.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2013 Blender Foundation
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Joshua Leung, Sergej Reich
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file rigidbody.c
29  *  \ingroup blenkernel
30  *  \brief Blender-side interface and methods for dealing with Rigid Body simulations
31  */
32
33 #include <stdio.h>
34 #include <string.h>
35 #include <stddef.h>
36 #include <float.h>
37 #include <math.h>
38 #include <limits.h>
39
40 #include "MEM_guardedalloc.h"
41
42 #include "BLI_blenlib.h"
43 #include "BLI_math.h"
44
45 #include "RBI_api.h"
46
47 #include "DNA_anim_types.h"
48 #include "DNA_group_types.h"
49 #include "DNA_mesh_types.h"
50 #include "DNA_meshdata_types.h"
51 #include "DNA_object_types.h"
52 #include "DNA_object_force.h"
53 #include "DNA_rigidbody_types.h"
54 #include "DNA_scene_types.h"
55
56 #include "BKE_animsys.h"
57 #include "BKE_cdderivedmesh.h"
58 #include "BKE_effect.h"
59 #include "BKE_group.h"
60 #include "BKE_object.h"
61 #include "BKE_mesh.h"
62 #include "BKE_pointcache.h"
63 #include "BKE_rigidbody.h"
64 #include "BKE_global.h"
65 #include "BKE_utildefines.h"
66
67 #include "RNA_access.h"
68
69 /* ************************************** */
70 /* Memory Management */
71
72 /* Freeing Methods --------------------- */
73
74 /* Free rigidbody world */
75 void BKE_rigidbody_free_world(RigidBodyWorld *rbw)
76 {
77         /* sanity check */
78         if (!rbw)
79                 return;
80
81         if (rbw->physics_world) {
82                 /* free physics references, we assume that all physics objects in will have been added to the world */
83                 GroupObject *go;
84                 if (rbw->constraints) {
85                         for (go = rbw->constraints->gobject.first; go; go = go->next) {
86                                 if (go->ob && go->ob->rigidbody_constraint) {
87                                         RigidBodyCon *rbc = go->ob->rigidbody_constraint;
88
89                                         if (rbc->physics_constraint)
90                                                 RB_dworld_remove_constraint(rbw->physics_world, rbc->physics_constraint);
91                                 }
92                         }
93                 }
94                 if (rbw->group) {
95                         for (go = rbw->group->gobject.first; go; go = go->next) {
96                                 if (go->ob && go->ob->rigidbody_object) {
97                                         RigidBodyOb *rbo = go->ob->rigidbody_object;
98
99                                         if (rbo->physics_object)
100                                                 RB_dworld_remove_body(rbw->physics_world, rbo->physics_object);
101                                 }
102                         }
103                 }
104                 /* free dynamics world */
105                 RB_dworld_delete(rbw->physics_world);
106         }
107         if (rbw->objects)
108                 free(rbw->objects);
109
110         /* free cache */
111         BKE_ptcache_free_list(&(rbw->ptcaches));
112         rbw->pointcache = NULL;
113
114         /* free effector weights */
115         if (rbw->effector_weights)
116                 MEM_freeN(rbw->effector_weights);
117
118         /* free rigidbody world itself */
119         MEM_freeN(rbw);
120 }
121
122 /* Free RigidBody settings and sim instances */
123 void BKE_rigidbody_free_object(Object *ob)
124 {
125         RigidBodyOb *rbo = (ob) ? ob->rigidbody_object : NULL;
126
127         /* sanity check */
128         if (rbo == NULL)
129                 return;
130
131         /* free physics references */
132         if (rbo->physics_object) {
133                 RB_body_delete(rbo->physics_object);
134                 rbo->physics_object = NULL;
135         }
136
137         if (rbo->physics_shape) {
138                 RB_shape_delete(rbo->physics_shape);
139                 rbo->physics_shape = NULL;
140         }
141
142         /* free data itself */
143         MEM_freeN(rbo);
144         ob->rigidbody_object = NULL;
145 }
146
147 /* Free RigidBody constraint and sim instance */
148 void BKE_rigidbody_free_constraint(Object *ob)
149 {
150         RigidBodyCon *rbc = (ob) ? ob->rigidbody_constraint : NULL;
151
152         /* sanity check */
153         if (rbc == NULL)
154                 return;
155
156         /* free physics reference */
157         if (rbc->physics_constraint) {
158                 RB_constraint_delete(rbc->physics_constraint);
159                 rbc->physics_constraint = NULL;
160         }
161
162         /* free data itself */
163         MEM_freeN(rbc);
164         ob->rigidbody_constraint = NULL;
165 }
166
167 /* Copying Methods --------------------- */
168
169 /* These just copy the data, clearing out references to physics objects.
170  * Anything that uses them MUST verify that the copied object will
171  * be added to relevant groups later...
172  */
173
174 RigidBodyOb *BKE_rigidbody_copy_object(Object *ob)
175 {
176         RigidBodyOb *rboN = NULL;
177
178         if (ob->rigidbody_object) {
179                 /* just duplicate the whole struct first (to catch all the settings) */
180                 rboN = MEM_dupallocN(ob->rigidbody_object);
181
182                 /* tag object as needing to be verified */
183                 rboN->flag |= RBO_FLAG_NEEDS_VALIDATE;
184
185                 /* clear out all the fields which need to be revalidated later */
186                 rboN->physics_object = NULL;
187                 rboN->physics_shape = NULL;
188         }
189
190         /* return new copy of settings */
191         return rboN;
192 }
193
194 RigidBodyCon *BKE_rigidbody_copy_constraint(Object *ob)
195 {
196         RigidBodyCon *rbcN = NULL;
197
198         if (ob->rigidbody_constraint) {
199                 /* just duplicate the whole struct first (to catch all the settings) */
200                 rbcN = MEM_dupallocN(ob->rigidbody_constraint);
201
202                 // RB_TODO be more clever about copying constrained objects
203
204                 /* tag object as needing to be verified */
205                 rbcN->flag |= RBC_FLAG_NEEDS_VALIDATE;
206
207                 /* clear out all the fields which need to be revalidated later */
208                 rbcN->physics_constraint = NULL;
209         }
210
211         /* return new copy of settings */
212         return rbcN;
213 }
214
215 /* ************************************** */
216 /* Setup Utilities - Validate Sim Instances */
217
218 /* create collision shape of mesh - convex hull */
219 static rbCollisionShape *rigidbody_get_shape_convexhull_from_mesh(Object *ob, float margin, bool *can_embed)
220 {
221         rbCollisionShape *shape = NULL;
222         Mesh *me = NULL;
223
224         if (ob->type == OB_MESH && ob->data) {
225                 me = ob->data;
226         }
227         else {
228                 printf("ERROR: cannot make Convex Hull collision shape for non-Mesh object\n");
229         }
230
231         if (me && me->totvert) {
232                 shape = RB_shape_new_convex_hull((float *)me->mvert, sizeof(MVert), me->totvert, margin, can_embed);
233         }
234         else {
235                 printf("ERROR: no vertices to define Convex Hull collision shape with\n");
236         }
237
238         return shape;
239 }
240
241 /* create collision shape of mesh - triangulated mesh
242  * returns NULL if creation fails.
243  */
244 static rbCollisionShape *rigidbody_get_shape_trimesh_from_mesh(Object *ob)
245 {
246         rbCollisionShape *shape = NULL;
247
248         if (ob->type == OB_MESH) {
249                 DerivedMesh *dm = CDDM_from_mesh(ob->data, ob);
250
251                 MVert *mvert;
252                 MFace *mface;
253                 int totvert;
254                 int totface;
255
256                 /* ensure mesh validity, then grab data */
257                 DM_ensure_tessface(dm);
258
259                 mvert   = (dm) ? dm->getVertArray(dm) : NULL;
260                 totvert = (dm) ? dm->getNumVerts(dm) : 0;
261                 mface   = (dm) ? dm->getTessFaceArray(dm) : NULL;
262                 totface = (dm) ? dm->getNumTessFaces(dm) : 0;
263
264                 /* sanity checking - potential case when no data will be present */
265                 if ((totvert == 0) || (totface == 0)) {
266                         printf("WARNING: no geometry data converted for Mesh Collision Shape (ob = %s)\n", ob->id.name + 2);
267                 }
268                 else {
269                         rbMeshData *mdata;
270                         int i;
271
272                         /* init mesh data for collision shape */
273                         mdata = RB_trimesh_data_new();
274
275                         /* loop over all faces, adding them as triangles to the collision shape
276                          * (so for some faces, more than triangle will get added)
277                          */
278                         for (i = 0; (i < totface) && (mface) && (mvert); i++, mface++) {
279                                 /* add first triangle - verts 1,2,3 */
280                                 {
281                                         MVert *va = (IN_RANGE(mface->v1, 0, totvert)) ? (mvert + mface->v1) : (mvert);
282                                         MVert *vb = (IN_RANGE(mface->v2, 0, totvert)) ? (mvert + mface->v2) : (mvert);
283                                         MVert *vc = (IN_RANGE(mface->v3, 0, totvert)) ? (mvert + mface->v3) : (mvert);
284
285                                         RB_trimesh_add_triangle(mdata, va->co, vb->co, vc->co);
286                                 }
287
288                                 /* add second triangle if needed - verts 1,3,4 */
289                                 if (mface->v4) {
290                                         MVert *va = (IN_RANGE(mface->v1, 0, totvert)) ? (mvert + mface->v1) : (mvert);
291                                         MVert *vb = (IN_RANGE(mface->v3, 0, totvert)) ? (mvert + mface->v3) : (mvert);
292                                         MVert *vc = (IN_RANGE(mface->v4, 0, totvert)) ? (mvert + mface->v4) : (mvert);
293
294                                         RB_trimesh_add_triangle(mdata, va->co, vb->co, vc->co);
295                                 }
296                         }
297
298                         /* construct collision shape
299                          *
300                          * These have been chosen to get better speed/accuracy tradeoffs with regards
301                          * to limitations of each:
302                          *    - BVH-Triangle Mesh: for passive objects only. Despite having greater
303                          *                         speed/accuracy, they cannot be used for moving objects.
304                          *    - GImpact Mesh:      for active objects. These are slower and less stable,
305                          *                         but are more flexible for general usage.
306                          */
307                         if (ob->rigidbody_object->type == RBO_TYPE_PASSIVE) {
308                                 shape = RB_shape_new_trimesh(mdata);
309                         }
310                         else {
311                                 shape = RB_shape_new_gimpact_mesh(mdata);
312                         }
313                 }
314
315                 /* cleanup temp data */
316                 if (dm) {
317                         dm->release(dm);
318                 }
319         }
320         else {
321                 printf("ERROR: cannot make Triangular Mesh collision shape for non-Mesh object\n");
322         }
323
324         return shape;
325 }
326
327 /* Create new physics sim collision shape for object and store it,
328  * or remove the existing one first and replace...
329  */
330 void BKE_rigidbody_validate_sim_shape(Object *ob, short rebuild)
331 {
332         RigidBodyOb *rbo = ob->rigidbody_object;
333         rbCollisionShape *new_shape = NULL;
334         BoundBox *bb = NULL;
335         float size[3] = {1.0f, 1.0f, 1.0f};
336         float radius = 1.0f;
337         float height = 1.0f;
338         float capsule_height;
339         float hull_margin = 0.0f;
340         bool can_embed = true;
341
342         /* sanity check */
343         if (rbo == NULL)
344                 return;
345
346         /* don't create a new shape if we already have one and don't want to rebuild it */
347         if (rbo->physics_shape && !rebuild)
348                 return;
349
350         /* if automatically determining dimensions, use the Object's boundbox
351          *      - assume that all quadrics are standing upright on local z-axis
352          *      - assume even distribution of mass around the Object's pivot
353          *        (i.e. Object pivot is centralised in boundbox)
354          */
355         // XXX: all dimensions are auto-determined now... later can add stored settings for this
356         /* get object dimensions without scaling */
357         bb = BKE_object_boundbox_get(ob);
358         if (bb) {
359                 size[0] = (bb->vec[4][0] - bb->vec[0][0]);
360                 size[1] = (bb->vec[2][1] - bb->vec[0][1]);
361                 size[2] = (bb->vec[1][2] - bb->vec[0][2]);
362         }
363         mul_v3_fl(size, 0.5f);
364
365         if (ELEM3(rbo->shape, RB_SHAPE_CAPSULE, RB_SHAPE_CYLINDER, RB_SHAPE_CONE)) {
366                 /* take radius as largest x/y dimension, and height as z-dimension */
367                 radius = MAX2(size[0], size[1]);
368                 height = size[2];
369         }
370         else if (rbo->shape == RB_SHAPE_SPHERE) {
371                 /* take radius to the the largest dimension to try and encompass everything */
372                 radius = MAX3(size[0], size[1], size[2]);
373         }
374
375         /* create new shape */
376         switch (rbo->shape) {
377                 case RB_SHAPE_BOX:
378                         new_shape = RB_shape_new_box(size[0], size[1], size[2]);
379                         break;
380
381                 case RB_SHAPE_SPHERE:
382                         new_shape = RB_shape_new_sphere(radius);
383                         break;
384
385                 case RB_SHAPE_CAPSULE:
386                         capsule_height = (height - radius) * 2.0f;
387                         new_shape = RB_shape_new_capsule(radius, (capsule_height > 0.0f) ? capsule_height : 0.0f);
388                         break;
389                 case RB_SHAPE_CYLINDER:
390                         new_shape = RB_shape_new_cylinder(radius, height);
391                         break;
392                 case RB_SHAPE_CONE:
393                         new_shape = RB_shape_new_cone(radius, height * 2.0f);
394                         break;
395
396                 case RB_SHAPE_CONVEXH:
397                         /* try to emged collision margin */
398                         if (!(rbo->flag & RBO_FLAG_USE_MARGIN))
399                                 hull_margin = 0.04f;
400                         new_shape = rigidbody_get_shape_convexhull_from_mesh(ob, hull_margin, &can_embed);
401                         if (!(rbo->flag & RBO_FLAG_USE_MARGIN))
402                                 rbo->margin = (can_embed) ? 0.04f : 0.0f;  /* RB_TODO ideally we shouldn't directly change the margin here */
403                         break;
404                 case RB_SHAPE_TRIMESH:
405                         new_shape = rigidbody_get_shape_trimesh_from_mesh(ob);
406                         break;
407         }
408         /* assign new collision shape if creation was successful */
409         if (new_shape) {
410                 if (rbo->physics_shape)
411                         RB_shape_delete(rbo->physics_shape);
412                 rbo->physics_shape = new_shape;
413                 RB_shape_set_margin(rbo->physics_shape, RBO_GET_MARGIN(rbo));
414         }
415 }
416
417 /* --------------------- */
418
419 /* Create physics sim representation of object given RigidBody settings
420  * < rebuild: even if an instance already exists, replace it
421  */
422 void BKE_rigidbody_validate_sim_object(RigidBodyWorld *rbw, Object *ob, short rebuild)
423 {
424         RigidBodyOb *rbo = (ob) ? ob->rigidbody_object : NULL;
425         float loc[3];
426         float rot[4];
427
428         /* sanity checks:
429          *      - object doesn't have RigidBody info already: then why is it here?
430          */
431         if (rbo == NULL)
432                 return;
433
434         /* make sure collision shape exists */
435         /* FIXME we shouldn't always have to rebuild collision shapes when rebuilding objects, but it's needed for constraints to update correctly */
436         if (rbo->physics_shape == NULL || rebuild)
437                 BKE_rigidbody_validate_sim_shape(ob, true);
438
439         if (rbo->physics_object) {
440                 if (rebuild == false)
441                         RB_dworld_remove_body(rbw->physics_world, rbo->physics_object);
442         }
443         if (!rbo->physics_object || rebuild) {
444                 /* remove rigid body if it already exists before creating a new one */
445                 if (rbo->physics_object) {
446                         RB_body_delete(rbo->physics_object);
447                 }
448
449                 mat4_to_loc_quat(loc, rot, ob->obmat);
450
451                 rbo->physics_object = RB_body_new(rbo->physics_shape, loc, rot);
452
453                 RB_body_set_friction(rbo->physics_object, rbo->friction);
454                 RB_body_set_restitution(rbo->physics_object, rbo->restitution);
455
456                 RB_body_set_damping(rbo->physics_object, rbo->lin_damping, rbo->ang_damping);
457                 RB_body_set_sleep_thresh(rbo->physics_object, rbo->lin_sleep_thresh, rbo->ang_sleep_thresh);
458                 RB_body_set_activation_state(rbo->physics_object, rbo->flag & RBO_FLAG_USE_DEACTIVATION);
459
460                 if (rbo->type == RBO_TYPE_PASSIVE || rbo->flag & RBO_FLAG_START_DEACTIVATED)
461                         RB_body_deactivate(rbo->physics_object);
462
463
464                 RB_body_set_linear_factor(rbo->physics_object,
465                                                                   (ob->protectflag & OB_LOCK_LOCX) == 0,
466                                           (ob->protectflag & OB_LOCK_LOCY) == 0,
467                                           (ob->protectflag & OB_LOCK_LOCZ) == 0);
468                 RB_body_set_angular_factor(rbo->physics_object,
469                                            (ob->protectflag & OB_LOCK_ROTX) == 0,
470                                            (ob->protectflag & OB_LOCK_ROTY) == 0,
471                                            (ob->protectflag & OB_LOCK_ROTZ) == 0);
472
473                 RB_body_set_mass(rbo->physics_object, RBO_GET_MASS(rbo));
474                 RB_body_set_kinematic_state(rbo->physics_object, rbo->flag & RBO_FLAG_KINEMATIC || rbo->flag & RBO_FLAG_DISABLED);
475         }
476
477         if (rbw && rbw->physics_world)
478                 RB_dworld_add_body(rbw->physics_world, rbo->physics_object, rbo->col_groups);
479 }
480
481 /* --------------------- */
482
483 /* Create physics sim representation of constraint given rigid body constraint settings
484  * < rebuild: even if an instance already exists, replace it
485  */
486 void BKE_rigidbody_validate_sim_constraint(RigidBodyWorld *rbw, Object *ob, short rebuild)
487 {
488         RigidBodyCon *rbc = (ob) ? ob->rigidbody_constraint : NULL;
489         float loc[3];
490         float rot[4];
491         float lin_lower;
492         float lin_upper;
493         float ang_lower;
494         float ang_upper;
495
496         /* sanity checks:
497          *      - object should have a rigid body constraint
498          *  - rigid body constraint should have at least one constrained object
499          */
500         if (rbc == NULL) {
501                 return;
502         }
503
504         if (ELEM4(NULL, rbc->ob1, rbc->ob1->rigidbody_object, rbc->ob2, rbc->ob2->rigidbody_object)) {
505                 if (rbc->physics_constraint) {
506                         RB_dworld_remove_constraint(rbw->physics_world, rbc->physics_constraint);
507                         RB_constraint_delete(rbc->physics_constraint);
508                         rbc->physics_constraint = NULL;
509                 }
510                 return;
511         }
512
513         if (rbc->physics_constraint) {
514                 if (rebuild == false)
515                         RB_dworld_remove_constraint(rbw->physics_world, rbc->physics_constraint);
516         }
517         if (rbc->physics_constraint == NULL || rebuild) {
518                 rbRigidBody *rb1 = rbc->ob1->rigidbody_object->physics_object;
519                 rbRigidBody *rb2 = rbc->ob2->rigidbody_object->physics_object;
520
521                 /* remove constraint if it already exists before creating a new one */
522                 if (rbc->physics_constraint) {
523                         RB_constraint_delete(rbc->physics_constraint);
524                         rbc->physics_constraint = NULL;
525                 }
526
527                 mat4_to_loc_quat(loc, rot, ob->obmat);
528
529                 if (rb1 && rb2) {
530                         switch (rbc->type) {
531                                 case RBC_TYPE_POINT:
532                                         rbc->physics_constraint = RB_constraint_new_point(loc, rb1, rb2);
533                                         break;
534                                 case RBC_TYPE_FIXED:
535                                         rbc->physics_constraint = RB_constraint_new_fixed(loc, rot, rb1, rb2);
536                                         break;
537                                 case RBC_TYPE_HINGE:
538                                         rbc->physics_constraint = RB_constraint_new_hinge(loc, rot, rb1, rb2);
539                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Z) {
540                                                 RB_constraint_set_limits_hinge(rbc->physics_constraint, rbc->limit_ang_z_lower, rbc->limit_ang_z_upper);
541                                         }
542                                         else
543                                                 RB_constraint_set_limits_hinge(rbc->physics_constraint, 0.0f, -1.0f);
544                                         break;
545                                 case RBC_TYPE_SLIDER:
546                                         rbc->physics_constraint = RB_constraint_new_slider(loc, rot, rb1, rb2);
547                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X)
548                                                 RB_constraint_set_limits_slider(rbc->physics_constraint, rbc->limit_lin_x_lower, rbc->limit_lin_x_upper);
549                                         else
550                                                 RB_constraint_set_limits_slider(rbc->physics_constraint, 0.0f, -1.0f);
551                                         break;
552                                 case RBC_TYPE_PISTON:
553                                         rbc->physics_constraint = RB_constraint_new_piston(loc, rot, rb1, rb2);
554                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X) {
555                                                 lin_lower = rbc->limit_lin_x_lower;
556                                                 lin_upper = rbc->limit_lin_x_upper;
557                                         }
558                                         else {
559                                                 lin_lower = 0.0f;
560                                                 lin_upper = -1.0f;
561                                         }
562                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_X) {
563                                                 ang_lower = rbc->limit_ang_x_lower;
564                                                 ang_upper = rbc->limit_ang_x_upper;
565                                         }
566                                         else {
567                                                 ang_lower = 0.0f;
568                                                 ang_upper = -1.0f;
569                                         }
570                                         RB_constraint_set_limits_piston(rbc->physics_constraint, lin_lower, lin_upper, ang_lower, ang_upper);
571                                         break;
572                                 case RBC_TYPE_6DOF:
573                                         rbc->physics_constraint = RB_constraint_new_6dof(loc, rot, rb1, rb2);
574
575                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X)
576                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->limit_lin_x_lower, rbc->limit_lin_x_upper);
577                                         else
578                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_X, 0.0f, -1.0f);
579
580                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_Y)
581                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->limit_lin_y_lower, rbc->limit_lin_y_upper);
582                                         else
583                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_Y, 0.0f, -1.0f);
584
585                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_Z)
586                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->limit_lin_z_lower, rbc->limit_lin_z_upper);
587                                         else
588                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_Z, 0.0f, -1.0f);
589
590                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_X)
591                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->limit_ang_x_lower, rbc->limit_ang_x_upper);
592                                         else
593                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_X, 0.0f, -1.0f);
594
595                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Y)
596                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->limit_ang_y_lower, rbc->limit_ang_y_upper);
597                                         else
598                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_Y, 0.0f, -1.0f);
599
600                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Z)
601                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->limit_ang_z_lower, rbc->limit_ang_z_upper);
602                                         else
603                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_Z, 0.0f, -1.0f);
604                                         break;
605                         }
606                 }
607
608                 RB_constraint_set_enabled(rbc->physics_constraint, rbc->flag & RBC_FLAG_ENABLED);
609
610                 if (rbc->flag & RBC_FLAG_USE_BREAKING)
611                         RB_constraint_set_breaking_threshold(rbc->physics_constraint, rbc->breaking_threshold);
612                 else
613                         RB_constraint_set_breaking_threshold(rbc->physics_constraint, FLT_MAX);
614
615                 if (rbc->flag & RBC_FLAG_OVERRIDE_SOLVER_ITERATIONS)
616                         RB_constraint_set_solver_iterations(rbc->physics_constraint, rbc->num_solver_iterations);
617                 else
618                         RB_constraint_set_solver_iterations(rbc->physics_constraint, -1);
619         }
620
621         if (rbw && rbw->physics_world && rbc->physics_constraint) {
622                 RB_dworld_add_constraint(rbw->physics_world, rbc->physics_constraint, rbc->flag & RBC_FLAG_DISABLE_COLLISIONS);
623         }
624 }
625
626 /* --------------------- */
627
628 /* Create physics sim world given RigidBody world settings */
629 // NOTE: this does NOT update object references that the scene uses, in case those aren't ready yet!
630 void BKE_rigidbody_validate_sim_world(Scene *scene, RigidBodyWorld *rbw, short rebuild)
631 {
632         /* sanity checks */
633         if (rbw == NULL)
634                 return;
635
636         /* create new sim world */
637         if (rebuild || rbw->physics_world == NULL) {
638                 if (rbw->physics_world)
639                         RB_dworld_delete(rbw->physics_world);
640                 rbw->physics_world = RB_dworld_new(scene->physics_settings.gravity);
641         }
642
643         RB_dworld_set_solver_iterations(rbw->physics_world, rbw->num_solver_iterations);
644         RB_dworld_set_split_impulse(rbw->physics_world, rbw->flag & RBW_FLAG_USE_SPLIT_IMPULSE);
645 }
646
647 /* ************************************** */
648 /* Setup Utilities - Create Settings Blocks */
649
650 /* Set up RigidBody world */
651 RigidBodyWorld *BKE_rigidbody_create_world(Scene *scene)
652 {
653         /* try to get whatever RigidBody world that might be representing this already */
654         RigidBodyWorld *rbw;
655
656         /* sanity checks
657          *      - there must be a valid scene to add world to
658          *      - there mustn't be a sim world using this group already
659          */
660         if (scene == NULL)
661                 return NULL;
662
663         /* create a new sim world */
664         rbw = MEM_callocN(sizeof(RigidBodyWorld), "RigidBodyWorld");
665
666         /* set default settings */
667         rbw->effector_weights = BKE_add_effector_weights(NULL);
668
669         rbw->ltime = PSFRA;
670
671         rbw->time_scale = 1.0f;
672
673         rbw->steps_per_second = 60; /* Bullet default (60 Hz) */
674         rbw->num_solver_iterations = 10; /* 10 is bullet default */
675
676         rbw->pointcache = BKE_ptcache_add(&(rbw->ptcaches));
677         rbw->pointcache->step = 1;
678
679         /* return this sim world */
680         return rbw;
681 }
682
683 /* Add rigid body settings to the specified object */
684 RigidBodyOb *BKE_rigidbody_create_object(Scene *scene, Object *ob, short type)
685 {
686         RigidBodyOb *rbo;
687         RigidBodyWorld *rbw = scene->rigidbody_world;
688
689         /* sanity checks
690          *      - rigidbody world must exist
691          *      - object must exist
692          *      - cannot add rigid body if it already exists
693          */
694         if (ob == NULL || (ob->rigidbody_object != NULL))
695                 return NULL;
696
697         /* create new settings data, and link it up */
698         rbo = MEM_callocN(sizeof(RigidBodyOb), "RigidBodyOb");
699
700         /* set default settings */
701         rbo->type = type;
702
703         rbo->mass = 1.0f;
704
705         rbo->friction = 0.5f; /* best when non-zero. 0.5 is Bullet default */
706         rbo->restitution = 0.0f; /* best when zero. 0.0 is Bullet default */
707
708         rbo->margin = 0.04f; /* 0.04 (in meters) is Bullet default */
709
710         rbo->lin_sleep_thresh = 0.4f; /* 0.4 is half of Bullet default */
711         rbo->ang_sleep_thresh = 0.5f; /* 0.5 is half of Bullet default */
712
713         rbo->lin_damping = 0.04f; /* 0.04 is game engine default */
714         rbo->ang_damping = 0.1f; /* 0.1 is game engine default */
715
716         rbo->col_groups = 1;
717
718         /* use triangle meshes for passive objects
719          * use convex hulls for active objects since dynamic triangle meshes are very unstable
720          */
721         if (type == RBO_TYPE_ACTIVE)
722                 rbo->shape = RB_SHAPE_CONVEXH;
723         else
724                 rbo->shape = RB_SHAPE_TRIMESH;
725
726         /* set initial transform */
727         mat4_to_loc_quat(rbo->pos, rbo->orn, ob->obmat);
728
729         /* flag cache as outdated */
730         BKE_rigidbody_cache_reset(rbw);
731
732         /* return this object */
733         return rbo;
734 }
735
736 /* Add rigid body constraint to the specified object */
737 RigidBodyCon *BKE_rigidbody_create_constraint(Scene *scene, Object *ob, short type)
738 {
739         RigidBodyCon *rbc;
740         RigidBodyWorld *rbw = scene->rigidbody_world;
741
742         /* sanity checks
743          *      - rigidbody world must exist
744          *      - object must exist
745          *      - cannot add constraint if it already exists
746          */
747         if (ob == NULL || (ob->rigidbody_constraint != NULL))
748                 return NULL;
749
750         /* create new settings data, and link it up */
751         rbc = MEM_callocN(sizeof(RigidBodyCon), "RigidBodyCon");
752
753         /* set default settings */
754         rbc->type = type;
755
756         rbc->ob1 = NULL;
757         rbc->ob2 = NULL;
758
759         rbc->flag |= RBC_FLAG_ENABLED;
760         rbc->flag |= RBC_FLAG_DISABLE_COLLISIONS;
761
762         rbc->breaking_threshold = 10.0f; /* no good default here, just use 10 for now */
763         rbc->num_solver_iterations = 10; /* 10 is Bullet default */
764
765         rbc->limit_lin_x_lower = -1.0f;
766         rbc->limit_lin_x_upper = 1.0f;
767         rbc->limit_lin_y_lower = -1.0f;
768         rbc->limit_lin_y_upper = 1.0f;
769         rbc->limit_lin_z_lower = -1.0f;
770         rbc->limit_lin_z_upper = 1.0f;
771         rbc->limit_ang_x_lower = -M_PI_4;
772         rbc->limit_ang_x_upper = M_PI_4;
773         rbc->limit_ang_y_lower = -M_PI_4;
774         rbc->limit_ang_y_upper = M_PI_4;
775         rbc->limit_ang_z_lower = -M_PI_4;
776         rbc->limit_ang_z_upper = M_PI_4;
777
778         /* flag cache as outdated */
779         BKE_rigidbody_cache_reset(rbw);
780
781         /* return this object */
782         return rbc;
783 }
784
785 /* ************************************** */
786 /* Utilities API */
787
788 /* Get RigidBody world for the given scene, creating one if needed
789  * < scene: Scene to find active Rigid Body world for
790  */
791 RigidBodyWorld *BKE_rigidbody_get_world(Scene *scene)
792 {
793         /* sanity check */
794         if (scene == NULL)
795                 return NULL;
796
797         return scene->rigidbody_world;
798 }
799
800 void BKE_rigidbody_remove_object(Scene *scene, Object *ob)
801 {
802         RigidBodyWorld *rbw = scene->rigidbody_world;
803         RigidBodyOb *rbo = ob->rigidbody_object;
804         RigidBodyCon *rbc;
805         GroupObject *go;
806         int i;
807
808         if (rbw) {
809                 /* remove from rigidbody world, free object won't do this */
810                 if (rbw->physics_world && rbo->physics_object)
811                         RB_dworld_remove_body(rbw->physics_world, rbo->physics_object);
812
813                 /* remove object from array */
814                 if (rbw && rbw->objects) {
815                         for (i = 0; i < rbw->numbodies; i++) {
816                                 if (rbw->objects[i] == ob) {
817                                         rbw->objects[i] = NULL;
818                                         break;
819                                 }
820                         }
821                 }
822
823                 /* remove object from rigid body constraints */
824                 if (rbw->constraints) {
825                         for (go = rbw->constraints->gobject.first; go; go = go->next) {
826                                 Object *obt = go->ob;
827                                 if (obt) {
828                                         rbc = obt->rigidbody_constraint;
829                                         if (rbc->ob1 == ob) {
830                                                 rbc->ob1 = NULL;
831                                                 rbc->flag |= RBC_FLAG_NEEDS_VALIDATE;
832                                         }
833                                         if (rbc->ob2 == ob) {
834                                                 rbc->ob2 = NULL;
835                                                 rbc->flag |= RBC_FLAG_NEEDS_VALIDATE;
836                                         }
837                                 }
838                         }
839                 }
840         }
841
842         /* remove object's settings */
843         BKE_rigidbody_free_object(ob);
844
845         /* flag cache as outdated */
846         BKE_rigidbody_cache_reset(rbw);
847 }
848
849 void BKE_rigidbody_remove_constraint(Scene *scene, Object *ob)
850 {
851         RigidBodyWorld *rbw = scene->rigidbody_world;
852         RigidBodyCon *rbc = ob->rigidbody_constraint;
853
854         if (rbw) {
855                 /* remove from rigidbody world, free object won't do this */
856                 if (rbw && rbw->physics_world && rbc->physics_constraint)
857                         RB_dworld_remove_constraint(rbw->physics_world, rbc->physics_constraint);
858         }
859         /* remove object's settings */
860         BKE_rigidbody_free_constraint(ob);
861
862         /* flag cache as outdated */
863         BKE_rigidbody_cache_reset(rbw);
864 }
865
866
867 /* ************************************** */
868 /* Simulation Interface - Bullet */
869
870 /* Update object array and rigid body count so they're in sync with the rigid body group */
871 static void rigidbody_update_ob_array(RigidBodyWorld *rbw)
872 {
873         GroupObject *go;
874         int i, n;
875
876         n = BLI_countlist(&rbw->group->gobject);
877
878         if (rbw->numbodies != n) {
879                 rbw->numbodies = n;
880                 rbw->objects = realloc(rbw->objects, sizeof(Object *) * rbw->numbodies);
881         }
882
883         for (go = rbw->group->gobject.first, i = 0; go; go = go->next, i++) {
884                 Object *ob = go->ob;
885                 rbw->objects[i] = ob;
886         }
887 }
888
889 static void rigidbody_update_sim_world(Scene *scene, RigidBodyWorld *rbw)
890 {
891         float adj_gravity[3];
892
893         /* adjust gravity to take effector weights into account */
894         if (scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) {
895                 copy_v3_v3(adj_gravity, scene->physics_settings.gravity);
896                 mul_v3_fl(adj_gravity, rbw->effector_weights->global_gravity * rbw->effector_weights->weight[0]);
897         }
898         else {
899                 zero_v3(adj_gravity);
900         }
901
902         /* update gravity, since this RNA setting is not part of RigidBody settings */
903         RB_dworld_set_gravity(rbw->physics_world, adj_gravity);
904
905         /* update object array in case there are changes */
906         rigidbody_update_ob_array(rbw);
907 }
908
909 static void rigidbody_update_sim_ob(Scene *scene, RigidBodyWorld *rbw, Object *ob, RigidBodyOb *rbo)
910 {
911         float loc[3];
912         float rot[4];
913         float scale[3];
914
915         /* only update if rigid body exists */
916         if (rbo->physics_object == NULL)
917                 return;
918
919         mat4_decompose(loc, rot, scale, ob->obmat);
920
921         /* update scale for all objects */
922         RB_body_set_scale(rbo->physics_object, scale);
923         /* compensate for embedded convex hull collision margin */
924         if (!(rbo->flag & RBO_FLAG_USE_MARGIN) && rbo->shape == RB_SHAPE_CONVEXH)
925                 RB_shape_set_margin(rbo->physics_shape, RBO_GET_MARGIN(rbo) * MIN3(scale[0], scale[1], scale[2]));
926
927         /* update rigid body location and rotation for kinematic bodies */
928         if (rbo->flag & RBO_FLAG_KINEMATIC) {
929                 RB_body_activate(rbo->physics_object);
930                 RB_body_set_loc_rot(rbo->physics_object, loc, rot);
931         }
932         /* update influence of effectors - but don't do it on an effector */
933         /* only dynamic bodies need effector update */
934         else if (rbo->type == RBO_TYPE_ACTIVE && ((ob->pd == NULL) || (ob->pd->forcefield == PFIELD_NULL))) {
935                 EffectorWeights *effector_weights = rbw->effector_weights;
936                 EffectedPoint epoint;
937                 ListBase *effectors;
938
939                 /* get effectors present in the group specified by effector_weights */
940                 effectors = pdInitEffectors(scene, ob, NULL, effector_weights);
941                 if (effectors) {
942                         float force[3] = {0.0f, 0.0f, 0.0f};
943                         float loc[3], vel[3];
944
945                         /* create dummy 'point' which represents last known position of object as result of sim */
946                         // XXX: this can create some inaccuracies with sim position, but is probably better than using unsimulated vals?
947                         RB_body_get_position(rbo->physics_object, loc);
948                         RB_body_get_linear_velocity(rbo->physics_object, vel);
949
950                         pd_point_from_loc(scene, loc, vel, 0, &epoint);
951
952                         /* calculate net force of effectors, and apply to sim object
953                          *      - we use 'central force' since apply force requires a "relative position" which we don't have...
954                          */
955                         pdDoEffectors(effectors, NULL, effector_weights, &epoint, force, NULL);
956                         if (G.f & G_DEBUG)
957                                 printf("\tapplying force (%f,%f,%f) to '%s'\n", force[0], force[1], force[2], ob->id.name + 2);
958                         /* activate object in case it is deactivated */
959                         if (!is_zero_v3(force))
960                                 RB_body_activate(rbo->physics_object);
961                         RB_body_apply_central_force(rbo->physics_object, force);
962                 }
963                 else if (G.f & G_DEBUG)
964                         printf("\tno forces to apply to '%s'\n", ob->id.name + 2);
965
966                 /* cleanup */
967                 pdEndEffectors(&effectors);
968         }
969         /* NOTE: passive objects don't need to be updated since they don't move */
970
971         /* NOTE: no other settings need to be explicitly updated here,
972          * since RNA setters take care of the rest :)
973          */
974 }
975
976 /* Updates and validates world, bodies and shapes.
977  * < rebuild: rebuild entire simulation
978  */
979 static void rigidbody_update_simulation(Scene *scene, RigidBodyWorld *rbw, int rebuild)
980 {
981         GroupObject *go;
982
983         /* update world */
984         if (rebuild)
985                 BKE_rigidbody_validate_sim_world(scene, rbw, true);
986         rigidbody_update_sim_world(scene, rbw);
987
988         /* update objects */
989         for (go = rbw->group->gobject.first; go; go = go->next) {
990                 Object *ob = go->ob;
991
992                 if (ob && ob->type == OB_MESH) {
993                         /* validate that we've got valid object set up here... */
994                         RigidBodyOb *rbo = ob->rigidbody_object;
995                         /* update transformation matrix of the object so we don't get a frame of lag for simple animations */
996                         BKE_object_where_is_calc(scene, ob);
997
998                         if (rbo == NULL) {
999                                 /* Since this object is included in the sim group but doesn't have
1000                                  * rigid body settings (perhaps it was added manually), add!
1001                                  *      - assume object to be active? That is the default for newly added settings...
1002                                  */
1003                                 ob->rigidbody_object = BKE_rigidbody_create_object(scene, ob, RBO_TYPE_ACTIVE);
1004                                 BKE_rigidbody_validate_sim_object(rbw, ob, true);
1005
1006                                 rbo = ob->rigidbody_object;
1007                         }
1008                         else {
1009                                 /* perform simulation data updates as tagged */
1010                                 /* refresh object... */
1011                                 if (rebuild) {
1012                                         /* World has been rebuilt so rebuild object */
1013                                         BKE_rigidbody_validate_sim_object(rbw, ob, true);
1014                                 }
1015                                 else if (rbo->flag & RBO_FLAG_NEEDS_VALIDATE) {
1016                                         BKE_rigidbody_validate_sim_object(rbw, ob, false);
1017                                 }
1018                                 /* refresh shape... */
1019                                 if (rbo->flag & RBO_FLAG_NEEDS_RESHAPE) {
1020                                         /* mesh/shape data changed, so force shape refresh */
1021                                         BKE_rigidbody_validate_sim_shape(ob, true);
1022                                         /* now tell RB sim about it */
1023                                         // XXX: we assume that this can only get applied for active/passive shapes that will be included as rigidbodies
1024                                         RB_body_set_collision_shape(rbo->physics_object, rbo->physics_shape);
1025                                 }
1026                                 rbo->flag &= ~(RBO_FLAG_NEEDS_VALIDATE | RBO_FLAG_NEEDS_RESHAPE);
1027                         }
1028
1029                         /* update simulation object... */
1030                         rigidbody_update_sim_ob(scene, rbw, ob, rbo);
1031                 }
1032         }
1033         /* update constraints */
1034         if (rbw->constraints == NULL) /* no constraints, move on */
1035                 return;
1036         for (go = rbw->constraints->gobject.first; go; go = go->next) {
1037                 Object *ob = go->ob;
1038
1039                 if (ob) {
1040                         /* validate that we've got valid object set up here... */
1041                         RigidBodyCon *rbc = ob->rigidbody_constraint;
1042                         /* update transformation matrix of the object so we don't get a frame of lag for simple animations */
1043                         BKE_object_where_is_calc(scene, ob);
1044
1045                         if (rbc == NULL) {
1046                                 /* Since this object is included in the group but doesn't have
1047                                  * constraint settings (perhaps it was added manually), add!
1048                                  */
1049                                 ob->rigidbody_constraint = BKE_rigidbody_create_constraint(scene, ob, RBC_TYPE_FIXED);
1050                                 BKE_rigidbody_validate_sim_constraint(rbw, ob, true);
1051
1052                                 rbc = ob->rigidbody_constraint;
1053                         }
1054                         else {
1055                                 /* perform simulation data updates as tagged */
1056                                 if (rebuild) {
1057                                         /* World has been rebuilt so rebuild constraint */
1058                                         BKE_rigidbody_validate_sim_constraint(rbw, ob, true);
1059                                 }
1060                                 else if (rbc->flag & RBC_FLAG_NEEDS_VALIDATE) {
1061                                         BKE_rigidbody_validate_sim_constraint(rbw, ob, false);
1062                                 }
1063                                 rbc->flag &= ~RBC_FLAG_NEEDS_VALIDATE;
1064                         }
1065                 }
1066         }
1067 }
1068
1069 /* Sync rigid body and object transformations */
1070 void BKE_rigidbody_sync_transforms(Scene *scene, Object *ob, float ctime)
1071 {
1072         RigidBodyWorld *rbw = scene->rigidbody_world;
1073         RigidBodyOb *rbo = ob->rigidbody_object;
1074
1075         /* keep original transform for kinematic and passive objects */
1076         if (ELEM(NULL, rbw, rbo) || rbo->flag & RBO_FLAG_KINEMATIC || rbo->type == RBO_TYPE_PASSIVE)
1077                 return;
1078
1079         /* use rigid body transform after cache start frame */
1080         if (ctime > rbw->pointcache->startframe) {
1081                 float mat[4][4], size_mat[4][4], size[3];
1082
1083                 /* keep original transform when the simulation is muted */
1084                 if (rbw->flag & RBW_FLAG_MUTED)
1085                         return;
1086
1087                 normalize_qt(rbo->orn); // RB_TODO investigate why quaternion isn't normalized at this point
1088                 quat_to_mat4(mat, rbo->orn);
1089                 copy_v3_v3(mat[3], rbo->pos);
1090
1091                 mat4_to_size(size, ob->obmat);
1092                 size_to_mat4(size_mat, size);
1093                 mult_m4_m4m4(mat, mat, size_mat);
1094
1095                 copy_m4_m4(ob->obmat, mat);
1096         }
1097         /* otherwise set rigid body transform to current obmat */
1098         else {
1099                 mat4_to_loc_quat(rbo->pos, rbo->orn, ob->obmat);
1100         }
1101 }
1102
1103 void BKE_rigidbody_cache_reset(RigidBodyWorld *rbw)
1104 {
1105         if (rbw)
1106                 rbw->pointcache->flag |= PTCACHE_OUTDATED;
1107 }
1108
1109 /* ------------------ */
1110
1111 /* Run RigidBody simulation for the specified physics world */
1112 void BKE_rigidbody_do_simulation(Scene *scene, float ctime)
1113 {
1114         float timestep;
1115         RigidBodyWorld *rbw = scene->rigidbody_world;
1116         PointCache *cache;
1117         PTCacheID pid;
1118         int startframe, endframe;
1119
1120         BKE_ptcache_id_from_rigidbody(&pid, NULL, rbw);
1121         BKE_ptcache_id_time(&pid, scene, ctime, &startframe, &endframe, NULL);
1122         cache = rbw->pointcache;
1123
1124         /* flag cache as outdated if we don't have a world or number of objects in the simulation has changed */
1125         if (rbw->physics_world == NULL || rbw->numbodies != BLI_countlist(&rbw->group->gobject)) {
1126                 cache->flag |= PTCACHE_OUTDATED;
1127         }
1128
1129         if (ctime <= startframe) {
1130                 rbw->ltime = startframe;
1131                 /* reset and rebuild simulation if necessary */
1132                 if (cache->flag & PTCACHE_OUTDATED) {
1133                         BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
1134                         rigidbody_update_simulation(scene, rbw, true);
1135                         BKE_ptcache_validate(cache, (int)ctime);
1136                         cache->last_exact = 0;
1137                         cache->flag &= ~PTCACHE_REDO_NEEDED;
1138                 }
1139                 return;
1140         }
1141         /* rebuild world if it's outdated on second frame */
1142         else if (ctime == startframe + 1 && rbw->ltime == startframe && cache->flag & PTCACHE_OUTDATED) {
1143                 BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
1144                 rigidbody_update_simulation(scene, rbw, true);
1145         }
1146         /* make sure we don't go out of cache frame range */
1147         else if (ctime > endframe) {
1148                 ctime = endframe;
1149         }
1150
1151         /* don't try to run the simulation if we don't have a world yet but allow reading baked cache */
1152         if (rbw->physics_world == NULL && !(cache->flag & PTCACHE_BAKED))
1153                 return;
1154         else if (rbw->objects == NULL)
1155                 rigidbody_update_ob_array(rbw);
1156
1157         /* try to read from cache */
1158         // RB_TODO deal with interpolated, old and baked results
1159         if (BKE_ptcache_read(&pid, ctime)) {
1160                 BKE_ptcache_validate(cache, (int)ctime);
1161                 rbw->ltime = ctime;
1162                 return;
1163         }
1164
1165         /* advance simulation, we can only step one frame forward */
1166         if (ctime == rbw->ltime + 1) {
1167                 /* write cache for first frame when on second frame */
1168                 if (rbw->ltime == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact == 0)) {
1169                         BKE_ptcache_write(&pid, startframe);
1170                 }
1171
1172                 /* update and validate simulation */
1173                 rigidbody_update_simulation(scene, rbw, false);
1174
1175                 /* calculate how much time elapsed since last step in seconds */
1176                 timestep = 1.0f / (float)FPS * (ctime - rbw->ltime) * rbw->time_scale;
1177                 /* step simulation by the requested timestep, steps per second are adjusted to take time scale into account */
1178                 RB_dworld_step_simulation(rbw->physics_world, timestep, INT_MAX, 1.0f / (float)rbw->steps_per_second * min_ff(rbw->time_scale, 1.0f));
1179
1180                 /* write cache for current frame */
1181                 BKE_ptcache_validate(cache, (int)ctime);
1182                 BKE_ptcache_write(&pid, (unsigned int)ctime);
1183
1184                 rbw->ltime = ctime;
1185         }
1186 }
1187 /* ************************************** */