Merge branch 'master' into blender2.8
[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 #ifdef WITH_BULLET
46 #  include "RBI_api.h"
47 #endif
48
49 #include "DNA_ID.h"
50 #include "DNA_group_types.h"
51 #include "DNA_meshdata_types.h"
52 #include "DNA_object_types.h"
53 #include "DNA_object_force.h"
54 #include "DNA_rigidbody_types.h"
55 #include "DNA_scene_types.h"
56
57 #include "BKE_cdderivedmesh.h"
58 #include "BKE_effect.h"
59 #include "BKE_global.h"
60 #include "BKE_library.h"
61 #include "BKE_library_query.h"
62 #include "BKE_mesh.h"
63 #include "BKE_object.h"
64 #include "BKE_pointcache.h"
65 #include "BKE_rigidbody.h"
66 #include "BKE_scene.h"
67
68 /* ************************************** */
69 /* Memory Management */
70
71 /* Freeing Methods --------------------- */
72
73 #ifndef WITH_BULLET
74
75 static void RB_dworld_remove_constraint(void *UNUSED(world), void *UNUSED(con)) {}
76 static void RB_dworld_remove_body(void *UNUSED(world), void *UNUSED(body)) {}
77 static void RB_dworld_delete(void *UNUSED(world)) {}
78 static void RB_body_delete(void *UNUSED(body)) {}
79 static void RB_shape_delete(void *UNUSED(shape)) {}
80 static void RB_constraint_delete(void *UNUSED(con)) {}
81
82 #endif
83
84 /* Free rigidbody world */
85 void BKE_rigidbody_free_world(RigidBodyWorld *rbw)
86 {
87         /* sanity check */
88         if (!rbw)
89                 return;
90
91         if (rbw->physics_world) {
92                 /* free physics references, we assume that all physics objects in will have been added to the world */
93                 GroupObject *go;
94                 if (rbw->constraints) {
95                         for (go = rbw->constraints->gobject.first; go; go = go->next) {
96                                 if (go->ob && go->ob->rigidbody_constraint) {
97                                         RigidBodyCon *rbc = go->ob->rigidbody_constraint;
98
99                                         if (rbc->physics_constraint)
100                                                 RB_dworld_remove_constraint(rbw->physics_world, rbc->physics_constraint);
101                                 }
102                         }
103                 }
104                 if (rbw->group) {
105                         for (go = rbw->group->gobject.first; go; go = go->next) {
106                                 if (go->ob && go->ob->rigidbody_object) {
107                                         RigidBodyOb *rbo = go->ob->rigidbody_object;
108
109                                         if (rbo->physics_object)
110                                                 RB_dworld_remove_body(rbw->physics_world, rbo->physics_object);
111                                 }
112                         }
113                 }
114                 /* free dynamics world */
115                 RB_dworld_delete(rbw->physics_world);
116         }
117         if (rbw->objects)
118                 free(rbw->objects);
119
120         /* free cache */
121         BKE_ptcache_free_list(&(rbw->ptcaches));
122         rbw->pointcache = NULL;
123
124         /* free effector weights */
125         if (rbw->effector_weights)
126                 MEM_freeN(rbw->effector_weights);
127
128         /* free rigidbody world itself */
129         MEM_freeN(rbw);
130 }
131
132 /* Free RigidBody settings and sim instances */
133 void BKE_rigidbody_free_object(Object *ob)
134 {
135         RigidBodyOb *rbo = (ob) ? ob->rigidbody_object : NULL;
136
137         /* sanity check */
138         if (rbo == NULL)
139                 return;
140
141         /* free physics references */
142         if (rbo->physics_object) {
143                 RB_body_delete(rbo->physics_object);
144                 rbo->physics_object = NULL;
145         }
146
147         if (rbo->physics_shape) {
148                 RB_shape_delete(rbo->physics_shape);
149                 rbo->physics_shape = NULL;
150         }
151
152         /* free data itself */
153         MEM_freeN(rbo);
154         ob->rigidbody_object = NULL;
155 }
156
157 /* Free RigidBody constraint and sim instance */
158 void BKE_rigidbody_free_constraint(Object *ob)
159 {
160         RigidBodyCon *rbc = (ob) ? ob->rigidbody_constraint : NULL;
161
162         /* sanity check */
163         if (rbc == NULL)
164                 return;
165
166         /* free physics reference */
167         if (rbc->physics_constraint) {
168                 RB_constraint_delete(rbc->physics_constraint);
169                 rbc->physics_constraint = NULL;
170         }
171
172         /* free data itself */
173         MEM_freeN(rbc);
174         ob->rigidbody_constraint = NULL;
175 }
176
177 #ifdef WITH_BULLET
178
179 /* Copying Methods --------------------- */
180
181 /* These just copy the data, clearing out references to physics objects.
182  * Anything that uses them MUST verify that the copied object will
183  * be added to relevant groups later...
184  */
185
186 RigidBodyOb *BKE_rigidbody_copy_object(const Object *ob)
187 {
188         RigidBodyOb *rboN = NULL;
189
190         if (ob->rigidbody_object) {
191                 /* just duplicate the whole struct first (to catch all the settings) */
192                 rboN = MEM_dupallocN(ob->rigidbody_object);
193
194                 /* tag object as needing to be verified */
195                 rboN->flag |= RBO_FLAG_NEEDS_VALIDATE;
196
197                 /* clear out all the fields which need to be revalidated later */
198                 rboN->physics_object = NULL;
199                 rboN->physics_shape = NULL;
200         }
201
202         /* return new copy of settings */
203         return rboN;
204 }
205
206 RigidBodyCon *BKE_rigidbody_copy_constraint(const Object *ob)
207 {
208         RigidBodyCon *rbcN = NULL;
209
210         if (ob->rigidbody_constraint) {
211                 /* just duplicate the whole struct first (to catch all the settings) */
212                 rbcN = MEM_dupallocN(ob->rigidbody_constraint);
213
214                 /* tag object as needing to be verified */
215                 rbcN->flag |= RBC_FLAG_NEEDS_VALIDATE;
216
217                 /* clear out all the fields which need to be revalidated later */
218                 rbcN->physics_constraint = NULL;
219         }
220
221         /* return new copy of settings */
222         return rbcN;
223 }
224
225 /* ************************************** */
226 /* Setup Utilities - Validate Sim Instances */
227
228 /* get the appropriate DerivedMesh based on rigid body mesh source */
229 static DerivedMesh *rigidbody_get_mesh(Object *ob)
230 {
231         if (ob->rigidbody_object->mesh_source == RBO_MESH_DEFORM) {
232                 return ob->derivedDeform;
233         }
234         else if (ob->rigidbody_object->mesh_source == RBO_MESH_FINAL) {
235                 return ob->derivedFinal;
236         }
237         else {
238                 return CDDM_from_mesh(ob->data);
239         }
240 }
241
242 /* create collision shape of mesh - convex hull */
243 static rbCollisionShape *rigidbody_get_shape_convexhull_from_mesh(Object *ob, float margin, bool *can_embed)
244 {
245         rbCollisionShape *shape = NULL;
246         DerivedMesh *dm = NULL;
247         MVert *mvert = NULL;
248         int totvert = 0;
249
250         if (ob->type == OB_MESH && ob->data) {
251                 dm = rigidbody_get_mesh(ob);
252                 mvert   = (dm) ? dm->getVertArray(dm) : NULL;
253                 totvert = (dm) ? dm->getNumVerts(dm) : 0;
254         }
255         else {
256                 printf("ERROR: cannot make Convex Hull collision shape for non-Mesh object\n");
257         }
258
259         if (totvert) {
260                 shape = RB_shape_new_convex_hull((float *)mvert, sizeof(MVert), totvert, margin, can_embed);
261         }
262         else {
263                 printf("ERROR: no vertices to define Convex Hull collision shape with\n");
264         }
265
266         if (dm && ob->rigidbody_object->mesh_source == RBO_MESH_BASE)
267                 dm->release(dm);
268
269         return shape;
270 }
271
272 /* create collision shape of mesh - triangulated mesh
273  * returns NULL if creation fails.
274  */
275 static rbCollisionShape *rigidbody_get_shape_trimesh_from_mesh(Object *ob)
276 {
277         rbCollisionShape *shape = NULL;
278
279         if (ob->type == OB_MESH) {
280                 DerivedMesh *dm = NULL;
281                 MVert *mvert;
282                 const MLoopTri *looptri;
283                 int totvert;
284                 int tottri;
285                 const MLoop *mloop;
286                 
287                 dm = rigidbody_get_mesh(ob);
288
289                 /* ensure mesh validity, then grab data */
290                 if (dm == NULL)
291                         return NULL;
292
293                 DM_ensure_looptri(dm);
294
295                 mvert   = dm->getVertArray(dm);
296                 totvert = dm->getNumVerts(dm);
297                 looptri = dm->getLoopTriArray(dm);
298                 tottri = dm->getNumLoopTri(dm);
299                 mloop = dm->getLoopArray(dm);
300
301                 /* sanity checking - potential case when no data will be present */
302                 if ((totvert == 0) || (tottri == 0)) {
303                         printf("WARNING: no geometry data converted for Mesh Collision Shape (ob = %s)\n", ob->id.name + 2);
304                 }
305                 else {
306                         rbMeshData *mdata;
307                         int i;
308
309                         /* init mesh data for collision shape */
310                         mdata = RB_trimesh_data_new(tottri, totvert);
311                         
312                         RB_trimesh_add_vertices(mdata, (float *)mvert, totvert, sizeof(MVert));
313
314                         /* loop over all faces, adding them as triangles to the collision shape
315                          * (so for some faces, more than triangle will get added)
316                          */
317                         if (mvert && looptri) {
318                                 for (i = 0; i < tottri; i++) {
319                                         /* add first triangle - verts 1,2,3 */
320                                         const MLoopTri *lt = &looptri[i];
321                                         int vtri[3];
322
323                                         vtri[0] = mloop[lt->tri[0]].v;
324                                         vtri[1] = mloop[lt->tri[1]].v;
325                                         vtri[2] = mloop[lt->tri[2]].v;
326
327                                         RB_trimesh_add_triangle_indices(mdata, i, UNPACK3(vtri));
328                                 }
329                         }
330                         
331                         RB_trimesh_finish(mdata);
332
333                         /* construct collision shape
334                          *
335                          * These have been chosen to get better speed/accuracy tradeoffs with regards
336                          * to limitations of each:
337                          *    - BVH-Triangle Mesh: for passive objects only. Despite having greater
338                          *                         speed/accuracy, they cannot be used for moving objects.
339                          *    - GImpact Mesh:      for active objects. These are slower and less stable,
340                          *                         but are more flexible for general usage.
341                          */
342                         if (ob->rigidbody_object->type == RBO_TYPE_PASSIVE) {
343                                 shape = RB_shape_new_trimesh(mdata);
344                         }
345                         else {
346                                 shape = RB_shape_new_gimpact_mesh(mdata);
347                         }
348                 }
349
350                 /* cleanup temp data */
351                 if (ob->rigidbody_object->mesh_source == RBO_MESH_BASE) {
352                         dm->release(dm);
353                 }
354         }
355         else {
356                 printf("ERROR: cannot make Triangular Mesh collision shape for non-Mesh object\n");
357         }
358
359         return shape;
360 }
361
362 /* Create new physics sim collision shape for object and store it,
363  * or remove the existing one first and replace...
364  */
365 static void rigidbody_validate_sim_shape(Object *ob, bool rebuild)
366 {
367         RigidBodyOb *rbo = ob->rigidbody_object;
368         rbCollisionShape *new_shape = NULL;
369         BoundBox *bb = NULL;
370         float size[3] = {1.0f, 1.0f, 1.0f};
371         float radius = 1.0f;
372         float height = 1.0f;
373         float capsule_height;
374         float hull_margin = 0.0f;
375         bool can_embed = true;
376         bool has_volume;
377
378         /* sanity check */
379         if (rbo == NULL)
380                 return;
381
382         /* don't create a new shape if we already have one and don't want to rebuild it */
383         if (rbo->physics_shape && !rebuild)
384                 return;
385
386         /* if automatically determining dimensions, use the Object's boundbox
387          *      - assume that all quadrics are standing upright on local z-axis
388          *      - assume even distribution of mass around the Object's pivot
389          *        (i.e. Object pivot is centralized in boundbox)
390          */
391         // XXX: all dimensions are auto-determined now... later can add stored settings for this
392         /* get object dimensions without scaling */
393         bb = BKE_object_boundbox_get(ob);
394         if (bb) {
395                 size[0] = (bb->vec[4][0] - bb->vec[0][0]);
396                 size[1] = (bb->vec[2][1] - bb->vec[0][1]);
397                 size[2] = (bb->vec[1][2] - bb->vec[0][2]);
398         }
399         mul_v3_fl(size, 0.5f);
400
401         if (ELEM(rbo->shape, RB_SHAPE_CAPSULE, RB_SHAPE_CYLINDER, RB_SHAPE_CONE)) {
402                 /* take radius as largest x/y dimension, and height as z-dimension */
403                 radius = MAX2(size[0], size[1]);
404                 height = size[2];
405         }
406         else if (rbo->shape == RB_SHAPE_SPHERE) {
407                 /* take radius to the largest dimension to try and encompass everything */
408                 radius = MAX3(size[0], size[1], size[2]);
409         }
410
411         /* create new shape */
412         switch (rbo->shape) {
413                 case RB_SHAPE_BOX:
414                         new_shape = RB_shape_new_box(size[0], size[1], size[2]);
415                         break;
416
417                 case RB_SHAPE_SPHERE:
418                         new_shape = RB_shape_new_sphere(radius);
419                         break;
420
421                 case RB_SHAPE_CAPSULE:
422                         capsule_height = (height - radius) * 2.0f;
423                         new_shape = RB_shape_new_capsule(radius, (capsule_height > 0.0f) ? capsule_height : 0.0f);
424                         break;
425                 case RB_SHAPE_CYLINDER:
426                         new_shape = RB_shape_new_cylinder(radius, height);
427                         break;
428                 case RB_SHAPE_CONE:
429                         new_shape = RB_shape_new_cone(radius, height * 2.0f);
430                         break;
431
432                 case RB_SHAPE_CONVEXH:
433                         /* try to emged collision margin */
434                         has_volume = (MIN3(size[0], size[1], size[2]) > 0.0f);
435
436                         if (!(rbo->flag & RBO_FLAG_USE_MARGIN) && has_volume)
437                                 hull_margin = 0.04f;
438                         new_shape = rigidbody_get_shape_convexhull_from_mesh(ob, hull_margin, &can_embed);
439                         if (!(rbo->flag & RBO_FLAG_USE_MARGIN))
440                                 rbo->margin = (can_embed && has_volume) ? 0.04f : 0.0f;  /* RB_TODO ideally we shouldn't directly change the margin here */
441                         break;
442                 case RB_SHAPE_TRIMESH:
443                         new_shape = rigidbody_get_shape_trimesh_from_mesh(ob);
444                         break;
445         }
446         /* use box shape if we can't fall back to old shape */
447         if (new_shape == NULL && rbo->physics_shape == NULL) {
448                 new_shape = RB_shape_new_box(size[0], size[1], size[2]);
449         }
450         /* assign new collision shape if creation was successful */
451         if (new_shape) {
452                 if (rbo->physics_shape)
453                         RB_shape_delete(rbo->physics_shape);
454                 rbo->physics_shape = new_shape;
455                 RB_shape_set_margin(rbo->physics_shape, RBO_GET_MARGIN(rbo));
456         }
457 }
458
459 /* --------------------- */
460
461 /* helper function to calculate volume of rigidbody object */
462 // TODO: allow a parameter to specify method used to calculate this?
463 void BKE_rigidbody_calc_volume(Object *ob, float *r_vol)
464 {
465         RigidBodyOb *rbo = ob->rigidbody_object;
466
467         float size[3]  = {1.0f, 1.0f, 1.0f};
468         float radius = 1.0f;
469         float height = 1.0f;
470
471         float volume = 0.0f;
472
473         /* if automatically determining dimensions, use the Object's boundbox
474          *      - assume that all quadrics are standing upright on local z-axis
475          *      - assume even distribution of mass around the Object's pivot
476          *        (i.e. Object pivot is centralized in boundbox)
477          *      - boundbox gives full width
478          */
479         // XXX: all dimensions are auto-determined now... later can add stored settings for this
480         BKE_object_dimensions_get(ob, size);
481
482         if (ELEM(rbo->shape, RB_SHAPE_CAPSULE, RB_SHAPE_CYLINDER, RB_SHAPE_CONE)) {
483                 /* take radius as largest x/y dimension, and height as z-dimension */
484                 radius = MAX2(size[0], size[1]) * 0.5f;
485                 height = size[2];
486         }
487         else if (rbo->shape == RB_SHAPE_SPHERE) {
488                 /* take radius to the largest dimension to try and encompass everything */
489                 radius = max_fff(size[0], size[1], size[2]) * 0.5f;
490         }
491
492         /* calculate volume as appropriate  */
493         switch (rbo->shape) {
494                 case RB_SHAPE_BOX:
495                         volume = size[0] * size[1] * size[2];
496                         break;
497
498                 case RB_SHAPE_SPHERE:
499                         volume = 4.0f / 3.0f * (float)M_PI * radius * radius * radius;
500                         break;
501
502                 /* for now, assume that capsule is close enough to a cylinder... */
503                 case RB_SHAPE_CAPSULE:
504                 case RB_SHAPE_CYLINDER:
505                         volume = (float)M_PI * radius * radius * height;
506                         break;
507
508                 case RB_SHAPE_CONE:
509                         volume = (float)M_PI / 3.0f * radius * radius * height;
510                         break;
511
512                 case RB_SHAPE_CONVEXH:
513                 case RB_SHAPE_TRIMESH:
514                 {
515                         if (ob->type == OB_MESH) {
516                                 DerivedMesh *dm = rigidbody_get_mesh(ob);
517                                 MVert *mvert;
518                                 const MLoopTri *lt = NULL;
519                                 int totvert, tottri = 0;
520                                 const MLoop *mloop = NULL;
521                                 
522                                 /* ensure mesh validity, then grab data */
523                                 if (dm == NULL)
524                                         return;
525                         
526                                 DM_ensure_looptri(dm);
527                         
528                                 mvert   = dm->getVertArray(dm);
529                                 totvert = dm->getNumVerts(dm);
530                                 lt = dm->getLoopTriArray(dm);
531                                 tottri = dm->getNumLoopTri(dm);
532                                 mloop = dm->getLoopArray(dm);
533                                 
534                                 if (totvert > 0 && tottri > 0) {
535                                         BKE_mesh_calc_volume(mvert, totvert, lt, tottri, mloop, &volume, NULL);
536                                 }
537                                 
538                                 /* cleanup temp data */
539                                 if (ob->rigidbody_object->mesh_source == RBO_MESH_BASE) {
540                                         dm->release(dm);
541                                 }
542                         }
543                         else {
544                                 /* rough estimate from boundbox as fallback */
545                                 /* XXX could implement other types of geometry here (curves, etc.) */
546                                 volume = size[0] * size[1] * size[2];
547                         }
548                         break;
549                 }
550
551 #if 0 // XXX: not defined yet
552                 case RB_SHAPE_COMPOUND:
553                         volume = 0.0f;
554                         break;
555 #endif
556         }
557
558         /* return the volume calculated */
559         if (r_vol) *r_vol = volume;
560 }
561
562 void BKE_rigidbody_calc_center_of_mass(Object *ob, float r_center[3])
563 {
564         RigidBodyOb *rbo = ob->rigidbody_object;
565
566         float size[3]  = {1.0f, 1.0f, 1.0f};
567         float height = 1.0f;
568
569         zero_v3(r_center);
570
571         /* if automatically determining dimensions, use the Object's boundbox
572          *      - assume that all quadrics are standing upright on local z-axis
573          *      - assume even distribution of mass around the Object's pivot
574          *        (i.e. Object pivot is centralized in boundbox)
575          *      - boundbox gives full width
576          */
577         // XXX: all dimensions are auto-determined now... later can add stored settings for this
578         BKE_object_dimensions_get(ob, size);
579
580         /* calculate volume as appropriate  */
581         switch (rbo->shape) {
582                 case RB_SHAPE_BOX:
583                 case RB_SHAPE_SPHERE:
584                 case RB_SHAPE_CAPSULE:
585                 case RB_SHAPE_CYLINDER:
586                         break;
587
588                 case RB_SHAPE_CONE:
589                         /* take radius as largest x/y dimension, and height as z-dimension */
590                         height = size[2];
591                         /* cone is geometrically centered on the median,
592                          * center of mass is 1/4 up from the base
593                          */
594                         r_center[2] = -0.25f * height;
595                         break;
596
597                 case RB_SHAPE_CONVEXH:
598                 case RB_SHAPE_TRIMESH:
599                 {
600                         if (ob->type == OB_MESH) {
601                                 DerivedMesh *dm = rigidbody_get_mesh(ob);
602                                 MVert *mvert;
603                                 const MLoopTri *looptri;
604                                 int totvert, tottri;
605                                 const MLoop *mloop;
606                                 
607                                 /* ensure mesh validity, then grab data */
608                                 if (dm == NULL)
609                                         return;
610                         
611                                 DM_ensure_looptri(dm);
612                         
613                                 mvert   = dm->getVertArray(dm);
614                                 totvert = dm->getNumVerts(dm);
615                                 looptri = dm->getLoopTriArray(dm);
616                                 tottri = dm->getNumLoopTri(dm);
617                                 mloop = dm->getLoopArray(dm);
618                                 
619                                 if (totvert > 0 && tottri > 0) {
620                                         BKE_mesh_calc_volume(mvert, totvert, looptri, tottri, mloop, NULL, r_center);
621                                 }
622                                 
623                                 /* cleanup temp data */
624                                 if (ob->rigidbody_object->mesh_source == RBO_MESH_BASE) {
625                                         dm->release(dm);
626                                 }
627                         }
628                         break;
629                 }
630
631 #if 0 // XXX: not defined yet
632                 case RB_SHAPE_COMPOUND:
633                         volume = 0.0f;
634                         break;
635 #endif
636         }
637 }
638
639 /* --------------------- */
640
641 /**
642  * Create physics sim representation of object given RigidBody settings
643  *
644  * \param rebuild Even if an instance already exists, replace it
645  */
646 static void rigidbody_validate_sim_object(RigidBodyWorld *rbw, Object *ob, bool rebuild)
647 {
648         RigidBodyOb *rbo = (ob) ? ob->rigidbody_object : NULL;
649         float loc[3];
650         float rot[4];
651
652         /* sanity checks:
653          *      - object doesn't have RigidBody info already: then why is it here?
654          */
655         if (rbo == NULL)
656                 return;
657
658         /* make sure collision shape exists */
659         /* FIXME we shouldn't always have to rebuild collision shapes when rebuilding objects, but it's needed for constraints to update correctly */
660         if (rbo->physics_shape == NULL || rebuild)
661                 rigidbody_validate_sim_shape(ob, true);
662
663         if (rbo->physics_object && rebuild == false) {
664                 RB_dworld_remove_body(rbw->physics_world, rbo->physics_object);
665         }
666         if (!rbo->physics_object || rebuild) {
667                 /* remove rigid body if it already exists before creating a new one */
668                 if (rbo->physics_object) {
669                         RB_body_delete(rbo->physics_object);
670                 }
671
672                 mat4_to_loc_quat(loc, rot, ob->obmat);
673
674                 rbo->physics_object = RB_body_new(rbo->physics_shape, loc, rot);
675
676                 RB_body_set_friction(rbo->physics_object, rbo->friction);
677                 RB_body_set_restitution(rbo->physics_object, rbo->restitution);
678
679                 RB_body_set_damping(rbo->physics_object, rbo->lin_damping, rbo->ang_damping);
680                 RB_body_set_sleep_thresh(rbo->physics_object, rbo->lin_sleep_thresh, rbo->ang_sleep_thresh);
681                 RB_body_set_activation_state(rbo->physics_object, rbo->flag & RBO_FLAG_USE_DEACTIVATION);
682
683                 if (rbo->type == RBO_TYPE_PASSIVE || rbo->flag & RBO_FLAG_START_DEACTIVATED)
684                         RB_body_deactivate(rbo->physics_object);
685
686
687                 RB_body_set_linear_factor(rbo->physics_object,
688                                           (ob->protectflag & OB_LOCK_LOCX) == 0,
689                                           (ob->protectflag & OB_LOCK_LOCY) == 0,
690                                           (ob->protectflag & OB_LOCK_LOCZ) == 0);
691                 RB_body_set_angular_factor(rbo->physics_object,
692                                            (ob->protectflag & OB_LOCK_ROTX) == 0,
693                                            (ob->protectflag & OB_LOCK_ROTY) == 0,
694                                            (ob->protectflag & OB_LOCK_ROTZ) == 0);
695
696                 RB_body_set_mass(rbo->physics_object, RBO_GET_MASS(rbo));
697                 RB_body_set_kinematic_state(rbo->physics_object, rbo->flag & RBO_FLAG_KINEMATIC || rbo->flag & RBO_FLAG_DISABLED);
698         }
699
700         if (rbw && rbw->physics_world)
701                 RB_dworld_add_body(rbw->physics_world, rbo->physics_object, rbo->col_groups);
702 }
703
704 /* --------------------- */
705
706 /**
707  * Create physics sim representation of constraint given rigid body constraint settings
708  *
709  * \param rebuild Even if an instance already exists, replace it
710  */
711 static void rigidbody_validate_sim_constraint(RigidBodyWorld *rbw, Object *ob, bool rebuild)
712 {
713         RigidBodyCon *rbc = (ob) ? ob->rigidbody_constraint : NULL;
714         float loc[3];
715         float rot[4];
716         float lin_lower;
717         float lin_upper;
718         float ang_lower;
719         float ang_upper;
720
721         /* sanity checks:
722          *      - object should have a rigid body constraint
723          *  - rigid body constraint should have at least one constrained object
724          */
725         if (rbc == NULL) {
726                 return;
727         }
728
729         if (ELEM(NULL, rbc->ob1, rbc->ob1->rigidbody_object, rbc->ob2, rbc->ob2->rigidbody_object)) {
730                 if (rbc->physics_constraint) {
731                         RB_dworld_remove_constraint(rbw->physics_world, rbc->physics_constraint);
732                         RB_constraint_delete(rbc->physics_constraint);
733                         rbc->physics_constraint = NULL;
734                 }
735                 return;
736         }
737
738         if (rbc->physics_constraint && rebuild == false) {
739                 RB_dworld_remove_constraint(rbw->physics_world, rbc->physics_constraint);
740         }
741         if (rbc->physics_constraint == NULL || rebuild) {
742                 rbRigidBody *rb1 = rbc->ob1->rigidbody_object->physics_object;
743                 rbRigidBody *rb2 = rbc->ob2->rigidbody_object->physics_object;
744
745                 /* remove constraint if it already exists before creating a new one */
746                 if (rbc->physics_constraint) {
747                         RB_constraint_delete(rbc->physics_constraint);
748                         rbc->physics_constraint = NULL;
749                 }
750
751                 mat4_to_loc_quat(loc, rot, ob->obmat);
752
753                 if (rb1 && rb2) {
754                         switch (rbc->type) {
755                                 case RBC_TYPE_POINT:
756                                         rbc->physics_constraint = RB_constraint_new_point(loc, rb1, rb2);
757                                         break;
758                                 case RBC_TYPE_FIXED:
759                                         rbc->physics_constraint = RB_constraint_new_fixed(loc, rot, rb1, rb2);
760                                         break;
761                                 case RBC_TYPE_HINGE:
762                                         rbc->physics_constraint = RB_constraint_new_hinge(loc, rot, rb1, rb2);
763                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Z) {
764                                                 RB_constraint_set_limits_hinge(rbc->physics_constraint, rbc->limit_ang_z_lower, rbc->limit_ang_z_upper);
765                                         }
766                                         else
767                                                 RB_constraint_set_limits_hinge(rbc->physics_constraint, 0.0f, -1.0f);
768                                         break;
769                                 case RBC_TYPE_SLIDER:
770                                         rbc->physics_constraint = RB_constraint_new_slider(loc, rot, rb1, rb2);
771                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X)
772                                                 RB_constraint_set_limits_slider(rbc->physics_constraint, rbc->limit_lin_x_lower, rbc->limit_lin_x_upper);
773                                         else
774                                                 RB_constraint_set_limits_slider(rbc->physics_constraint, 0.0f, -1.0f);
775                                         break;
776                                 case RBC_TYPE_PISTON:
777                                         rbc->physics_constraint = RB_constraint_new_piston(loc, rot, rb1, rb2);
778                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X) {
779                                                 lin_lower = rbc->limit_lin_x_lower;
780                                                 lin_upper = rbc->limit_lin_x_upper;
781                                         }
782                                         else {
783                                                 lin_lower = 0.0f;
784                                                 lin_upper = -1.0f;
785                                         }
786                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_X) {
787                                                 ang_lower = rbc->limit_ang_x_lower;
788                                                 ang_upper = rbc->limit_ang_x_upper;
789                                         }
790                                         else {
791                                                 ang_lower = 0.0f;
792                                                 ang_upper = -1.0f;
793                                         }
794                                         RB_constraint_set_limits_piston(rbc->physics_constraint, lin_lower, lin_upper, ang_lower, ang_upper);
795                                         break;
796                                 case RBC_TYPE_6DOF_SPRING:
797                                         rbc->physics_constraint = RB_constraint_new_6dof_spring(loc, rot, rb1, rb2);
798
799                                         RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->flag & RBC_FLAG_USE_SPRING_X);
800                                         RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->spring_stiffness_x);
801                                         RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->spring_damping_x);
802
803                                         RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->flag & RBC_FLAG_USE_SPRING_Y);
804                                         RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->spring_stiffness_y);
805                                         RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->spring_damping_y);
806
807                                         RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->flag & RBC_FLAG_USE_SPRING_Z);
808                                         RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->spring_stiffness_z);
809                                         RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->spring_damping_z);
810
811                                         RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->flag & RBC_FLAG_USE_SPRING_ANG_X);
812                                         RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->spring_stiffness_ang_x);
813                                         RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->spring_damping_ang_x);
814
815                                         RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->flag & RBC_FLAG_USE_SPRING_ANG_Y);
816                                         RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->spring_stiffness_ang_y);
817                                         RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->spring_damping_ang_y);
818
819                                         RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->flag & RBC_FLAG_USE_SPRING_ANG_Z);
820                                         RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->spring_stiffness_ang_z);
821                                         RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->spring_damping_ang_z);
822
823                                         RB_constraint_set_equilibrium_6dof_spring(rbc->physics_constraint);
824                                         ATTR_FALLTHROUGH;
825                                 case RBC_TYPE_6DOF:
826                                         if (rbc->type == RBC_TYPE_6DOF) /* a litte awkward but avoids duplicate code for limits */
827                                                 rbc->physics_constraint = RB_constraint_new_6dof(loc, rot, rb1, rb2);
828
829                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X)
830                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->limit_lin_x_lower, rbc->limit_lin_x_upper);
831                                         else
832                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_X, 0.0f, -1.0f);
833
834                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_Y)
835                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->limit_lin_y_lower, rbc->limit_lin_y_upper);
836                                         else
837                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_Y, 0.0f, -1.0f);
838
839                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_Z)
840                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->limit_lin_z_lower, rbc->limit_lin_z_upper);
841                                         else
842                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_Z, 0.0f, -1.0f);
843
844                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_X)
845                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->limit_ang_x_lower, rbc->limit_ang_x_upper);
846                                         else
847                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_X, 0.0f, -1.0f);
848
849                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Y)
850                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->limit_ang_y_lower, rbc->limit_ang_y_upper);
851                                         else
852                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_Y, 0.0f, -1.0f);
853
854                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Z)
855                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->limit_ang_z_lower, rbc->limit_ang_z_upper);
856                                         else
857                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_Z, 0.0f, -1.0f);
858                                         break;
859                                 case RBC_TYPE_MOTOR:
860                                         rbc->physics_constraint = RB_constraint_new_motor(loc, rot, rb1, rb2);
861
862                                         RB_constraint_set_enable_motor(rbc->physics_constraint, rbc->flag & RBC_FLAG_USE_MOTOR_LIN, rbc->flag & RBC_FLAG_USE_MOTOR_ANG);
863                                         RB_constraint_set_max_impulse_motor(rbc->physics_constraint, rbc->motor_lin_max_impulse, rbc->motor_ang_max_impulse);
864                                         RB_constraint_set_target_velocity_motor(rbc->physics_constraint, rbc->motor_lin_target_velocity, rbc->motor_ang_target_velocity);
865                                         break;
866                         }
867                 }
868                 else { /* can't create constraint without both rigid bodies */
869                         return;
870                 }
871
872                 RB_constraint_set_enabled(rbc->physics_constraint, rbc->flag & RBC_FLAG_ENABLED);
873
874                 if (rbc->flag & RBC_FLAG_USE_BREAKING)
875                         RB_constraint_set_breaking_threshold(rbc->physics_constraint, rbc->breaking_threshold);
876                 else
877                         RB_constraint_set_breaking_threshold(rbc->physics_constraint, FLT_MAX);
878
879                 if (rbc->flag & RBC_FLAG_OVERRIDE_SOLVER_ITERATIONS)
880                         RB_constraint_set_solver_iterations(rbc->physics_constraint, rbc->num_solver_iterations);
881                 else
882                         RB_constraint_set_solver_iterations(rbc->physics_constraint, -1);
883         }
884
885         if (rbw && rbw->physics_world && rbc->physics_constraint) {
886                 RB_dworld_add_constraint(rbw->physics_world, rbc->physics_constraint, rbc->flag & RBC_FLAG_DISABLE_COLLISIONS);
887         }
888 }
889
890 /* --------------------- */
891
892 /* Create physics sim world given RigidBody world settings */
893 // NOTE: this does NOT update object references that the scene uses, in case those aren't ready yet!
894 void BKE_rigidbody_validate_sim_world(Scene *scene, RigidBodyWorld *rbw, bool rebuild)
895 {
896         /* sanity checks */
897         if (rbw == NULL)
898                 return;
899
900         /* create new sim world */
901         if (rebuild || rbw->physics_world == NULL) {
902                 if (rbw->physics_world)
903                         RB_dworld_delete(rbw->physics_world);
904                 rbw->physics_world = RB_dworld_new(scene->physics_settings.gravity);
905         }
906
907         RB_dworld_set_solver_iterations(rbw->physics_world, rbw->num_solver_iterations);
908         RB_dworld_set_split_impulse(rbw->physics_world, rbw->flag & RBW_FLAG_USE_SPLIT_IMPULSE);
909 }
910
911 /* ************************************** */
912 /* Setup Utilities - Create Settings Blocks */
913
914 /* Set up RigidBody world */
915 RigidBodyWorld *BKE_rigidbody_create_world(Scene *scene)
916 {
917         /* try to get whatever RigidBody world that might be representing this already */
918         RigidBodyWorld *rbw;
919
920         /* sanity checks
921          *      - there must be a valid scene to add world to
922          *      - there mustn't be a sim world using this group already
923          */
924         if (scene == NULL)
925                 return NULL;
926
927         /* create a new sim world */
928         rbw = MEM_callocN(sizeof(RigidBodyWorld), "RigidBodyWorld");
929
930         /* set default settings */
931         rbw->effector_weights = BKE_add_effector_weights(NULL);
932
933         rbw->ltime = PSFRA;
934
935         rbw->time_scale = 1.0f;
936
937         rbw->steps_per_second = 60; /* Bullet default (60 Hz) */
938         rbw->num_solver_iterations = 10; /* 10 is bullet default */
939
940         rbw->pointcache = BKE_ptcache_add(&(rbw->ptcaches));
941         rbw->pointcache->step = 1;
942
943         /* return this sim world */
944         return rbw;
945 }
946
947 RigidBodyWorld *BKE_rigidbody_world_copy(RigidBodyWorld *rbw)
948 {
949         RigidBodyWorld *rbwn = MEM_dupallocN(rbw);
950
951         if (rbw->effector_weights)
952                 rbwn->effector_weights = MEM_dupallocN(rbw->effector_weights);
953         if (rbwn->group)
954                 id_us_plus(&rbwn->group->id);
955         if (rbwn->constraints)
956                 id_us_plus(&rbwn->constraints->id);
957
958         rbwn->pointcache = BKE_ptcache_copy_list(&rbwn->ptcaches, &rbw->ptcaches, false);
959
960         rbwn->objects = NULL;
961         rbwn->physics_world = NULL;
962         rbwn->numbodies = 0;
963
964         return rbwn;
965 }
966
967 void BKE_rigidbody_world_groups_relink(RigidBodyWorld *rbw)
968 {
969         ID_NEW_REMAP(rbw->group);
970         ID_NEW_REMAP(rbw->constraints);
971         ID_NEW_REMAP(rbw->effector_weights->group);
972 }
973
974 void BKE_rigidbody_world_id_loop(RigidBodyWorld *rbw, RigidbodyWorldIDFunc func, void *userdata)
975 {
976         func(rbw, (ID **)&rbw->group, userdata, IDWALK_CB_NOP);
977         func(rbw, (ID **)&rbw->constraints, userdata, IDWALK_CB_NOP);
978         func(rbw, (ID **)&rbw->effector_weights->group, userdata, IDWALK_CB_NOP);
979
980         if (rbw->objects) {
981                 int i;
982                 for (i = 0; i < rbw->numbodies; i++) {
983                         func(rbw, (ID **)&rbw->objects[i], userdata, IDWALK_CB_NOP);
984                 }
985         }
986 }
987
988 /* Add rigid body settings to the specified object */
989 RigidBodyOb *BKE_rigidbody_create_object(Scene *scene, Object *ob, short type)
990 {
991         RigidBodyOb *rbo;
992         RigidBodyWorld *rbw = scene->rigidbody_world;
993
994         /* sanity checks
995          *      - rigidbody world must exist
996          *      - object must exist
997          *      - cannot add rigid body if it already exists
998          */
999         if (ob == NULL || (ob->rigidbody_object != NULL))
1000                 return NULL;
1001
1002         /* create new settings data, and link it up */
1003         rbo = MEM_callocN(sizeof(RigidBodyOb), "RigidBodyOb");
1004
1005         /* set default settings */
1006         rbo->type = type;
1007
1008         rbo->mass = 1.0f;
1009
1010         rbo->friction = 0.5f; /* best when non-zero. 0.5 is Bullet default */
1011         rbo->restitution = 0.0f; /* best when zero. 0.0 is Bullet default */
1012
1013         rbo->margin = 0.04f; /* 0.04 (in meters) is Bullet default */
1014
1015         rbo->lin_sleep_thresh = 0.4f; /* 0.4 is half of Bullet default */
1016         rbo->ang_sleep_thresh = 0.5f; /* 0.5 is half of Bullet default */
1017
1018         rbo->lin_damping = 0.04f; /* 0.04 is game engine default */
1019         rbo->ang_damping = 0.1f; /* 0.1 is game engine default */
1020
1021         rbo->col_groups = 1;
1022
1023         /* use triangle meshes for passive objects
1024          * use convex hulls for active objects since dynamic triangle meshes are very unstable
1025          */
1026         if (type == RBO_TYPE_ACTIVE)
1027                 rbo->shape = RB_SHAPE_CONVEXH;
1028         else
1029                 rbo->shape = RB_SHAPE_TRIMESH;
1030
1031         rbo->mesh_source = RBO_MESH_DEFORM;
1032
1033         /* set initial transform */
1034         mat4_to_loc_quat(rbo->pos, rbo->orn, ob->obmat);
1035
1036         /* flag cache as outdated */
1037         BKE_rigidbody_cache_reset(rbw);
1038
1039         /* return this object */
1040         return rbo;
1041 }
1042
1043 /* Add rigid body constraint to the specified object */
1044 RigidBodyCon *BKE_rigidbody_create_constraint(Scene *scene, Object *ob, short type)
1045 {
1046         RigidBodyCon *rbc;
1047         RigidBodyWorld *rbw = scene->rigidbody_world;
1048
1049         /* sanity checks
1050          *      - rigidbody world must exist
1051          *      - object must exist
1052          *      - cannot add constraint if it already exists
1053          */
1054         if (ob == NULL || (ob->rigidbody_constraint != NULL))
1055                 return NULL;
1056
1057         /* create new settings data, and link it up */
1058         rbc = MEM_callocN(sizeof(RigidBodyCon), "RigidBodyCon");
1059
1060         /* set default settings */
1061         rbc->type = type;
1062
1063         rbc->ob1 = NULL;
1064         rbc->ob2 = NULL;
1065
1066         rbc->flag |= RBC_FLAG_ENABLED;
1067         rbc->flag |= RBC_FLAG_DISABLE_COLLISIONS;
1068
1069         rbc->breaking_threshold = 10.0f; /* no good default here, just use 10 for now */
1070         rbc->num_solver_iterations = 10; /* 10 is Bullet default */
1071
1072         rbc->limit_lin_x_lower = -1.0f;
1073         rbc->limit_lin_x_upper = 1.0f;
1074         rbc->limit_lin_y_lower = -1.0f;
1075         rbc->limit_lin_y_upper = 1.0f;
1076         rbc->limit_lin_z_lower = -1.0f;
1077         rbc->limit_lin_z_upper = 1.0f;
1078         rbc->limit_ang_x_lower = -M_PI_4;
1079         rbc->limit_ang_x_upper = M_PI_4;
1080         rbc->limit_ang_y_lower = -M_PI_4;
1081         rbc->limit_ang_y_upper = M_PI_4;
1082         rbc->limit_ang_z_lower = -M_PI_4;
1083         rbc->limit_ang_z_upper = M_PI_4;
1084
1085         rbc->spring_damping_x = 0.5f;
1086         rbc->spring_damping_y = 0.5f;
1087         rbc->spring_damping_z = 0.5f;
1088         rbc->spring_damping_ang_x = 0.5f;
1089         rbc->spring_damping_ang_y = 0.5f;
1090         rbc->spring_damping_ang_z = 0.5f;
1091         rbc->spring_stiffness_x = 10.0f;
1092         rbc->spring_stiffness_y = 10.0f;
1093         rbc->spring_stiffness_z = 10.0f;
1094         rbc->spring_stiffness_ang_x = 10.0f;
1095         rbc->spring_stiffness_ang_y = 10.0f;
1096         rbc->spring_stiffness_ang_z = 10.0f;
1097
1098         rbc->motor_lin_max_impulse = 1.0f;
1099         rbc->motor_lin_target_velocity = 1.0f;
1100         rbc->motor_ang_max_impulse = 1.0f;
1101         rbc->motor_ang_target_velocity = 1.0f;
1102
1103         /* flag cache as outdated */
1104         BKE_rigidbody_cache_reset(rbw);
1105
1106         /* return this object */
1107         return rbc;
1108 }
1109
1110 /* ************************************** */
1111 /* Utilities API */
1112
1113 /* Get RigidBody world for the given scene, creating one if needed
1114  *
1115  * \param scene Scene to find active Rigid Body world for
1116  */
1117 RigidBodyWorld *BKE_rigidbody_get_world(Scene *scene)
1118 {
1119         /* sanity check */
1120         if (scene == NULL)
1121                 return NULL;
1122
1123         return scene->rigidbody_world;
1124 }
1125
1126 void BKE_rigidbody_remove_object(Scene *scene, Object *ob)
1127 {
1128         RigidBodyWorld *rbw = scene->rigidbody_world;
1129         RigidBodyOb *rbo = ob->rigidbody_object;
1130         RigidBodyCon *rbc;
1131         GroupObject *go;
1132         int i;
1133
1134         if (rbw) {
1135                 /* remove from rigidbody world, free object won't do this */
1136                 if (rbw->physics_world && rbo->physics_object)
1137                         RB_dworld_remove_body(rbw->physics_world, rbo->physics_object);
1138
1139                 /* remove object from array */
1140                 if (rbw && rbw->objects) {
1141                         for (i = 0; i < rbw->numbodies; i++) {
1142                                 if (rbw->objects[i] == ob) {
1143                                         rbw->objects[i] = NULL;
1144                                         break;
1145                                 }
1146                         }
1147                 }
1148
1149                 /* remove object from rigid body constraints */
1150                 if (rbw->constraints) {
1151                         for (go = rbw->constraints->gobject.first; go; go = go->next) {
1152                                 Object *obt = go->ob;
1153                                 if (obt && obt->rigidbody_constraint) {
1154                                         rbc = obt->rigidbody_constraint;
1155                                         if (ELEM(ob, rbc->ob1, rbc->ob2)) {
1156                                                 BKE_rigidbody_remove_constraint(scene, obt);
1157                                         }
1158                                 }
1159                         }
1160                 }
1161         }
1162
1163         /* remove object's settings */
1164         BKE_rigidbody_free_object(ob);
1165
1166         /* flag cache as outdated */
1167         BKE_rigidbody_cache_reset(rbw);
1168 }
1169
1170 void BKE_rigidbody_remove_constraint(Scene *scene, Object *ob)
1171 {
1172         RigidBodyWorld *rbw = scene->rigidbody_world;
1173         RigidBodyCon *rbc = ob->rigidbody_constraint;
1174
1175         /* remove from rigidbody world, free object won't do this */
1176         if (rbw && rbw->physics_world && rbc->physics_constraint) {
1177                 RB_dworld_remove_constraint(rbw->physics_world, rbc->physics_constraint);
1178         }
1179         /* remove object's settings */
1180         BKE_rigidbody_free_constraint(ob);
1181
1182         /* flag cache as outdated */
1183         BKE_rigidbody_cache_reset(rbw);
1184 }
1185
1186
1187 /* ************************************** */
1188 /* Simulation Interface - Bullet */
1189
1190 /* Update object array and rigid body count so they're in sync with the rigid body group */
1191 static void rigidbody_update_ob_array(RigidBodyWorld *rbw)
1192 {
1193         GroupObject *go;
1194         int i, n;
1195
1196         n = BLI_listbase_count(&rbw->group->gobject);
1197
1198         if (rbw->numbodies != n) {
1199                 rbw->numbodies = n;
1200                 rbw->objects = realloc(rbw->objects, sizeof(Object *) * rbw->numbodies);
1201         }
1202
1203         for (go = rbw->group->gobject.first, i = 0; go; go = go->next, i++) {
1204                 Object *ob = go->ob;
1205                 rbw->objects[i] = ob;
1206         }
1207 }
1208
1209 static void rigidbody_update_sim_world(Scene *scene, RigidBodyWorld *rbw)
1210 {
1211         float adj_gravity[3];
1212
1213         /* adjust gravity to take effector weights into account */
1214         if (scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) {
1215                 copy_v3_v3(adj_gravity, scene->physics_settings.gravity);
1216                 mul_v3_fl(adj_gravity, rbw->effector_weights->global_gravity * rbw->effector_weights->weight[0]);
1217         }
1218         else {
1219                 zero_v3(adj_gravity);
1220         }
1221
1222         /* update gravity, since this RNA setting is not part of RigidBody settings */
1223         RB_dworld_set_gravity(rbw->physics_world, adj_gravity);
1224
1225         /* update object array in case there are changes */
1226         rigidbody_update_ob_array(rbw);
1227 }
1228
1229 static void rigidbody_update_sim_ob(Scene *scene, RigidBodyWorld *rbw, Object *ob, RigidBodyOb *rbo)
1230 {
1231         float loc[3];
1232         float rot[4];
1233         float scale[3];
1234
1235         /* only update if rigid body exists */
1236         if (rbo->physics_object == NULL)
1237                 return;
1238
1239         if (rbo->shape == RB_SHAPE_TRIMESH && rbo->flag & RBO_FLAG_USE_DEFORM) {
1240                 DerivedMesh *dm = ob->derivedDeform;
1241                 if (dm) {
1242                         MVert *mvert = dm->getVertArray(dm);
1243                         int totvert = dm->getNumVerts(dm);
1244                         BoundBox *bb = BKE_object_boundbox_get(ob);
1245
1246                         RB_shape_trimesh_update(rbo->physics_shape, (float *)mvert, totvert, sizeof(MVert), bb->vec[0], bb->vec[6]);
1247                 }
1248         }
1249
1250         mat4_decompose(loc, rot, scale, ob->obmat);
1251
1252         /* update scale for all objects */
1253         RB_body_set_scale(rbo->physics_object, scale);
1254         /* compensate for embedded convex hull collision margin */
1255         if (!(rbo->flag & RBO_FLAG_USE_MARGIN) && rbo->shape == RB_SHAPE_CONVEXH)
1256                 RB_shape_set_margin(rbo->physics_shape, RBO_GET_MARGIN(rbo) * MIN3(scale[0], scale[1], scale[2]));
1257
1258         /* make transformed objects temporarily kinmatic so that they can be moved by the user during simulation */
1259         if (ob->flag & SELECT && G.moving & G_TRANSFORM_OBJ) {
1260                 RB_body_set_kinematic_state(rbo->physics_object, true);
1261                 RB_body_set_mass(rbo->physics_object, 0.0f);
1262         }
1263
1264         /* update rigid body location and rotation for kinematic bodies */
1265         if (rbo->flag & RBO_FLAG_KINEMATIC || (ob->flag & SELECT && G.moving & G_TRANSFORM_OBJ)) {
1266                 RB_body_activate(rbo->physics_object);
1267                 RB_body_set_loc_rot(rbo->physics_object, loc, rot);
1268         }
1269         /* update influence of effectors - but don't do it on an effector */
1270         /* only dynamic bodies need effector update */
1271         else if (rbo->type == RBO_TYPE_ACTIVE && ((ob->pd == NULL) || (ob->pd->forcefield == PFIELD_NULL))) {
1272                 EffectorWeights *effector_weights = rbw->effector_weights;
1273                 EffectedPoint epoint;
1274                 ListBase *effectors;
1275
1276                 /* get effectors present in the group specified by effector_weights */
1277                 effectors = pdInitEffectors(scene, ob, NULL, effector_weights, true);
1278                 if (effectors) {
1279                         float eff_force[3] = {0.0f, 0.0f, 0.0f};
1280                         float eff_loc[3], eff_vel[3];
1281
1282                         /* create dummy 'point' which represents last known position of object as result of sim */
1283                         // XXX: this can create some inaccuracies with sim position, but is probably better than using unsimulated vals?
1284                         RB_body_get_position(rbo->physics_object, eff_loc);
1285                         RB_body_get_linear_velocity(rbo->physics_object, eff_vel);
1286
1287                         pd_point_from_loc(scene, eff_loc, eff_vel, 0, &epoint);
1288
1289                         /* calculate net force of effectors, and apply to sim object
1290                          *      - we use 'central force' since apply force requires a "relative position" which we don't have...
1291                          */
1292                         pdDoEffectors(effectors, NULL, effector_weights, &epoint, eff_force, NULL);
1293                         if (G.f & G_DEBUG)
1294                                 printf("\tapplying force (%f,%f,%f) to '%s'\n", eff_force[0], eff_force[1], eff_force[2], ob->id.name + 2);
1295                         /* activate object in case it is deactivated */
1296                         if (!is_zero_v3(eff_force))
1297                                 RB_body_activate(rbo->physics_object);
1298                         RB_body_apply_central_force(rbo->physics_object, eff_force);
1299                 }
1300                 else if (G.f & G_DEBUG)
1301                         printf("\tno forces to apply to '%s'\n", ob->id.name + 2);
1302
1303                 /* cleanup */
1304                 pdEndEffectors(&effectors);
1305         }
1306         /* NOTE: passive objects don't need to be updated since they don't move */
1307
1308         /* NOTE: no other settings need to be explicitly updated here,
1309          * since RNA setters take care of the rest :)
1310          */
1311 }
1312
1313 /**
1314  * Updates and validates world, bodies and shapes.
1315  *
1316  * \param rebuild Rebuild entire simulation
1317  */
1318 static void rigidbody_update_simulation(Scene *scene, RigidBodyWorld *rbw, bool rebuild)
1319 {
1320         GroupObject *go;
1321
1322         /* update world */
1323         if (rebuild)
1324                 BKE_rigidbody_validate_sim_world(scene, rbw, true);
1325         rigidbody_update_sim_world(scene, rbw);
1326
1327         /* XXX TODO For rebuild: remove all constraints first.
1328          * Otherwise we can end up deleting objects that are still
1329          * referenced by constraints, corrupting bullet's internal list.
1330          * 
1331          * Memory management needs redesign here, this is just a dirty workaround.
1332          */
1333         if (rebuild && rbw->constraints) {
1334                 for (go = rbw->constraints->gobject.first; go; go = go->next) {
1335                         Object *ob = go->ob;
1336                         if (ob) {
1337                                 RigidBodyCon *rbc = ob->rigidbody_constraint;
1338                                 if (rbc && rbc->physics_constraint) {
1339                                         RB_dworld_remove_constraint(rbw->physics_world, rbc->physics_constraint);
1340                                         RB_constraint_delete(rbc->physics_constraint);
1341                                         rbc->physics_constraint = NULL;
1342                                 }
1343                         }
1344                 }
1345         }
1346
1347         /* update objects */
1348         for (go = rbw->group->gobject.first; go; go = go->next) {
1349                 Object *ob = go->ob;
1350
1351                 if (ob && ob->type == OB_MESH) {
1352                         /* validate that we've got valid object set up here... */
1353                         RigidBodyOb *rbo = ob->rigidbody_object;
1354                         /* update transformation matrix of the object so we don't get a frame of lag for simple animations */
1355                         BKE_object_where_is_calc(scene, ob);
1356
1357                         if (rbo == NULL) {
1358                                 /* Since this object is included in the sim group but doesn't have
1359                                  * rigid body settings (perhaps it was added manually), add!
1360                                  *      - assume object to be active? That is the default for newly added settings...
1361                                  */
1362                                 ob->rigidbody_object = BKE_rigidbody_create_object(scene, ob, RBO_TYPE_ACTIVE);
1363                                 rigidbody_validate_sim_object(rbw, ob, true);
1364
1365                                 rbo = ob->rigidbody_object;
1366                         }
1367                         else {
1368                                 /* perform simulation data updates as tagged */
1369                                 /* refresh object... */
1370                                 if (rebuild) {
1371                                         /* World has been rebuilt so rebuild object */
1372                                         rigidbody_validate_sim_object(rbw, ob, true);
1373                                 }
1374                                 else if (rbo->flag & RBO_FLAG_NEEDS_VALIDATE) {
1375                                         rigidbody_validate_sim_object(rbw, ob, false);
1376                                 }
1377                                 /* refresh shape... */
1378                                 if (rbo->flag & RBO_FLAG_NEEDS_RESHAPE) {
1379                                         /* mesh/shape data changed, so force shape refresh */
1380                                         rigidbody_validate_sim_shape(ob, true);
1381                                         /* now tell RB sim about it */
1382                                         // XXX: we assume that this can only get applied for active/passive shapes that will be included as rigidbodies
1383                                         RB_body_set_collision_shape(rbo->physics_object, rbo->physics_shape);
1384                                 }
1385                                 rbo->flag &= ~(RBO_FLAG_NEEDS_VALIDATE | RBO_FLAG_NEEDS_RESHAPE);
1386                         }
1387
1388                         /* update simulation object... */
1389                         rigidbody_update_sim_ob(scene, rbw, ob, rbo);
1390                 }
1391         }
1392         
1393         /* update constraints */
1394         if (rbw->constraints == NULL) /* no constraints, move on */
1395                 return;
1396         for (go = rbw->constraints->gobject.first; go; go = go->next) {
1397                 Object *ob = go->ob;
1398
1399                 if (ob) {
1400                         /* validate that we've got valid object set up here... */
1401                         RigidBodyCon *rbc = ob->rigidbody_constraint;
1402                         /* update transformation matrix of the object so we don't get a frame of lag for simple animations */
1403                         BKE_object_where_is_calc(scene, ob);
1404
1405                         if (rbc == NULL) {
1406                                 /* Since this object is included in the group but doesn't have
1407                                  * constraint settings (perhaps it was added manually), add!
1408                                  */
1409                                 ob->rigidbody_constraint = BKE_rigidbody_create_constraint(scene, ob, RBC_TYPE_FIXED);
1410                                 rigidbody_validate_sim_constraint(rbw, ob, true);
1411
1412                                 rbc = ob->rigidbody_constraint;
1413                         }
1414                         else {
1415                                 /* perform simulation data updates as tagged */
1416                                 if (rebuild) {
1417                                         /* World has been rebuilt so rebuild constraint */
1418                                         rigidbody_validate_sim_constraint(rbw, ob, true);
1419                                 }
1420                                 else if (rbc->flag & RBC_FLAG_NEEDS_VALIDATE) {
1421                                         rigidbody_validate_sim_constraint(rbw, ob, false);
1422                                 }
1423                                 rbc->flag &= ~RBC_FLAG_NEEDS_VALIDATE;
1424                         }
1425                 }
1426         }
1427 }
1428
1429 static void rigidbody_update_simulation_post_step(RigidBodyWorld *rbw)
1430 {
1431         GroupObject *go;
1432
1433         for (go = rbw->group->gobject.first; go; go = go->next) {
1434                 Object *ob = go->ob;
1435
1436                 if (ob) {
1437                         RigidBodyOb *rbo = ob->rigidbody_object;
1438                         /* reset kinematic state for transformed objects */
1439                         if (rbo && (ob->flag & SELECT) && (G.moving & G_TRANSFORM_OBJ)) {
1440                                 RB_body_set_kinematic_state(rbo->physics_object, rbo->flag & RBO_FLAG_KINEMATIC || rbo->flag & RBO_FLAG_DISABLED);
1441                                 RB_body_set_mass(rbo->physics_object, RBO_GET_MASS(rbo));
1442                                 /* deactivate passive objects so they don't interfere with deactivation of active objects */
1443                                 if (rbo->type == RBO_TYPE_PASSIVE)
1444                                         RB_body_deactivate(rbo->physics_object);
1445                         }
1446                 }
1447         }
1448 }
1449
1450 bool BKE_rigidbody_check_sim_running(RigidBodyWorld *rbw, float ctime)
1451 {
1452         return (rbw && (rbw->flag & RBW_FLAG_MUTED) == 0 && ctime > rbw->pointcache->startframe);
1453 }
1454
1455 /* Sync rigid body and object transformations */
1456 void BKE_rigidbody_sync_transforms(RigidBodyWorld *rbw, Object *ob, float ctime)
1457 {
1458         RigidBodyOb *rbo = ob->rigidbody_object;
1459
1460         /* keep original transform for kinematic and passive objects */
1461         if (ELEM(NULL, rbw, rbo) || rbo->flag & RBO_FLAG_KINEMATIC || rbo->type == RBO_TYPE_PASSIVE)
1462                 return;
1463
1464         /* use rigid body transform after cache start frame if objects is not being transformed */
1465         if (BKE_rigidbody_check_sim_running(rbw, ctime) && !(ob->flag & SELECT && G.moving & G_TRANSFORM_OBJ)) {
1466                 float mat[4][4], size_mat[4][4], size[3];
1467
1468                 normalize_qt(rbo->orn); // RB_TODO investigate why quaternion isn't normalized at this point
1469                 quat_to_mat4(mat, rbo->orn);
1470                 copy_v3_v3(mat[3], rbo->pos);
1471
1472                 mat4_to_size(size, ob->obmat);
1473                 size_to_mat4(size_mat, size);
1474                 mul_m4_m4m4(mat, mat, size_mat);
1475
1476                 copy_m4_m4(ob->obmat, mat);
1477         }
1478         /* otherwise set rigid body transform to current obmat */
1479         else {
1480                 mat4_to_loc_quat(rbo->pos, rbo->orn, ob->obmat);
1481         }
1482 }
1483
1484 /* Used when canceling transforms - return rigidbody and object to initial states */
1485 void BKE_rigidbody_aftertrans_update(Object *ob, float loc[3], float rot[3], float quat[4], float rotAxis[3], float rotAngle)
1486 {
1487         RigidBodyOb *rbo = ob->rigidbody_object;
1488
1489         /* return rigid body and object to their initial states */
1490         copy_v3_v3(rbo->pos, ob->loc);
1491         copy_v3_v3(ob->loc, loc);
1492
1493         if (ob->rotmode > 0) {
1494                 eulO_to_quat(rbo->orn, ob->rot, ob->rotmode);
1495                 copy_v3_v3(ob->rot, rot);
1496         }
1497         else if (ob->rotmode == ROT_MODE_AXISANGLE) {
1498                 axis_angle_to_quat(rbo->orn, ob->rotAxis, ob->rotAngle);
1499                 copy_v3_v3(ob->rotAxis, rotAxis);
1500                 ob->rotAngle = rotAngle;
1501         }
1502         else {
1503                 copy_qt_qt(rbo->orn, ob->quat);
1504                 copy_qt_qt(ob->quat, quat);
1505         }
1506         if (rbo->physics_object) {
1507                 /* allow passive objects to return to original transform */
1508                 if (rbo->type == RBO_TYPE_PASSIVE)
1509                         RB_body_set_kinematic_state(rbo->physics_object, true);
1510                 RB_body_set_loc_rot(rbo->physics_object, rbo->pos, rbo->orn);
1511         }
1512         // RB_TODO update rigid body physics object's loc/rot for dynamic objects here as well (needs to be done outside bullet's update loop)
1513 }
1514
1515 void BKE_rigidbody_cache_reset(RigidBodyWorld *rbw)
1516 {
1517         if (rbw)
1518                 rbw->pointcache->flag |= PTCACHE_OUTDATED;
1519 }
1520
1521 /* ------------------ */
1522
1523 /* Rebuild rigid body world */
1524 /* NOTE: this needs to be called before frame update to work correctly */
1525 void BKE_rigidbody_rebuild_world(Scene *scene, float ctime)
1526 {
1527         RigidBodyWorld *rbw = scene->rigidbody_world;
1528         PointCache *cache;
1529         PTCacheID pid;
1530         int startframe, endframe;
1531
1532         BKE_ptcache_id_from_rigidbody(&pid, NULL, rbw);
1533         BKE_ptcache_id_time(&pid, scene, ctime, &startframe, &endframe, NULL);
1534         cache = rbw->pointcache;
1535
1536         /* flag cache as outdated if we don't have a world or number of objects in the simulation has changed */
1537         if (rbw->physics_world == NULL || rbw->numbodies != BLI_listbase_count(&rbw->group->gobject)) {
1538                 cache->flag |= PTCACHE_OUTDATED;
1539         }
1540
1541         if (ctime == startframe + 1 && rbw->ltime == startframe) {
1542                 if (cache->flag & PTCACHE_OUTDATED) {
1543                         BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
1544                         rigidbody_update_simulation(scene, rbw, true);
1545                         BKE_ptcache_validate(cache, (int)ctime);
1546                         cache->last_exact = 0;
1547                         cache->flag &= ~PTCACHE_REDO_NEEDED;
1548                 }
1549         }
1550 }
1551
1552 /* Run RigidBody simulation for the specified physics world */
1553 void BKE_rigidbody_do_simulation(Scene *scene, float ctime)
1554 {
1555         float timestep;
1556         RigidBodyWorld *rbw = scene->rigidbody_world;
1557         PointCache *cache;
1558         PTCacheID pid;
1559         int startframe, endframe;
1560
1561         BKE_ptcache_id_from_rigidbody(&pid, NULL, rbw);
1562         BKE_ptcache_id_time(&pid, scene, ctime, &startframe, &endframe, NULL);
1563         cache = rbw->pointcache;
1564
1565         if (ctime <= startframe) {
1566                 rbw->ltime = startframe;
1567                 return;
1568         }
1569         /* make sure we don't go out of cache frame range */
1570         else if (ctime > endframe) {
1571                 ctime = endframe;
1572         }
1573
1574         /* don't try to run the simulation if we don't have a world yet but allow reading baked cache */
1575         if (rbw->physics_world == NULL && !(cache->flag & PTCACHE_BAKED))
1576                 return;
1577         else if (rbw->objects == NULL)
1578                 rigidbody_update_ob_array(rbw);
1579
1580         /* try to read from cache */
1581         // RB_TODO deal with interpolated, old and baked results
1582         bool can_simulate = (ctime == rbw->ltime + 1) && !(cache->flag & PTCACHE_BAKED);
1583
1584         if (BKE_ptcache_read(&pid, ctime, can_simulate)) {
1585                 BKE_ptcache_validate(cache, (int)ctime);
1586                 rbw->ltime = ctime;
1587                 return;
1588         }
1589
1590         /* advance simulation, we can only step one frame forward */
1591         if (ctime == rbw->ltime + 1) {
1592                 /* write cache for first frame when on second frame */
1593                 if (rbw->ltime == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact == 0)) {
1594                         BKE_ptcache_write(&pid, startframe);
1595                 }
1596
1597                 /* update and validate simulation */
1598                 rigidbody_update_simulation(scene, rbw, false);
1599
1600                 /* calculate how much time elapsed since last step in seconds */
1601                 timestep = 1.0f / (float)FPS * (ctime - rbw->ltime) * rbw->time_scale;
1602                 /* step simulation by the requested timestep, steps per second are adjusted to take time scale into account */
1603                 RB_dworld_step_simulation(rbw->physics_world, timestep, INT_MAX, 1.0f / (float)rbw->steps_per_second * min_ff(rbw->time_scale, 1.0f));
1604
1605                 rigidbody_update_simulation_post_step(rbw);
1606
1607                 /* write cache for current frame */
1608                 BKE_ptcache_validate(cache, (int)ctime);
1609                 BKE_ptcache_write(&pid, (unsigned int)ctime);
1610
1611                 rbw->ltime = ctime;
1612         }
1613 }
1614 /* ************************************** */
1615
1616 #else  /* WITH_BULLET */
1617
1618 /* stubs */
1619 #ifdef __GNUC__
1620 #  pragma GCC diagnostic push
1621 #  pragma GCC diagnostic ignored "-Wunused-parameter"
1622 #endif
1623
1624 struct RigidBodyOb *BKE_rigidbody_copy_object(const Object *ob) { return NULL; }
1625 struct RigidBodyCon *BKE_rigidbody_copy_constraint(const Object *ob) { return NULL; }
1626 void BKE_rigidbody_validate_sim_world(Scene *scene, RigidBodyWorld *rbw, bool rebuild) {}
1627 void BKE_rigidbody_calc_volume(Object *ob, float *r_vol) { if (r_vol) *r_vol = 0.0f; }
1628 void BKE_rigidbody_calc_center_of_mass(Object *ob, float r_center[3]) { zero_v3(r_center); }
1629 struct RigidBodyWorld *BKE_rigidbody_create_world(Scene *scene) { return NULL; }
1630 struct RigidBodyWorld *BKE_rigidbody_world_copy(RigidBodyWorld *rbw) { return NULL; }
1631 void BKE_rigidbody_world_groups_relink(struct RigidBodyWorld *rbw) {}
1632 void BKE_rigidbody_world_id_loop(struct RigidBodyWorld *rbw, RigidbodyWorldIDFunc func, void *userdata) {}
1633 struct RigidBodyOb *BKE_rigidbody_create_object(Scene *scene, Object *ob, short type) { return NULL; }
1634 struct RigidBodyCon *BKE_rigidbody_create_constraint(Scene *scene, Object *ob, short type) { return NULL; }
1635 struct RigidBodyWorld *BKE_rigidbody_get_world(Scene *scene) { return NULL; }
1636 void BKE_rigidbody_remove_object(Scene *scene, Object *ob) {}
1637 void BKE_rigidbody_remove_constraint(Scene *scene, Object *ob) {}
1638 void BKE_rigidbody_sync_transforms(RigidBodyWorld *rbw, Object *ob, float ctime) {}
1639 void BKE_rigidbody_aftertrans_update(Object *ob, float loc[3], float rot[3], float quat[4], float rotAxis[3], float rotAngle) {}
1640 bool BKE_rigidbody_check_sim_running(RigidBodyWorld *rbw, float ctime) { return false; }
1641 void BKE_rigidbody_cache_reset(RigidBodyWorld *rbw) {}
1642 void BKE_rigidbody_rebuild_world(Scene *scene, float ctime) {}
1643 void BKE_rigidbody_do_simulation(Scene *scene, float ctime) {}
1644
1645 #ifdef __GNUC__
1646 #  pragma GCC diagnostic pop
1647 #endif
1648
1649 #endif  /* WITH_BULLET */
1650
1651 /* -------------------- */
1652 /* Depsgraph evaluation */
1653
1654 void BKE_rigidbody_rebuild_sim(struct EvaluationContext *UNUSED(eval_ctx),
1655                                Scene *scene)
1656 {
1657         float ctime = BKE_scene_frame_get(scene);
1658
1659         if (G.debug & G_DEBUG_DEPSGRAPH) {
1660                 printf("%s at %f\n", __func__, ctime);
1661         }
1662
1663         /* rebuild sim data (i.e. after resetting to start of timeline) */
1664         if (BKE_scene_check_rigidbody_active(scene)) {
1665                 BKE_rigidbody_rebuild_world(scene, ctime);
1666         }
1667 }
1668
1669 void BKE_rigidbody_eval_simulation(struct EvaluationContext *UNUSED(eval_ctx),
1670                                    Scene *scene)
1671 {
1672         float ctime = BKE_scene_frame_get(scene);
1673
1674         if (G.debug & G_DEBUG_DEPSGRAPH) {
1675                 printf("%s at %f\n", __func__, ctime);
1676         }
1677
1678         /* evaluate rigidbody sim */
1679         if (BKE_scene_check_rigidbody_active(scene)) {
1680                 BKE_rigidbody_do_simulation(scene, ctime);
1681         }
1682 }
1683
1684 void BKE_rigidbody_object_sync_transforms(struct EvaluationContext *UNUSED(eval_ctx),
1685                                           Scene *scene,
1686                                           Object *ob)
1687 {
1688         RigidBodyWorld *rbw = scene->rigidbody_world;
1689         float ctime = BKE_scene_frame_get(scene);
1690
1691         if (G.debug & G_DEBUG_DEPSGRAPH) {
1692                 printf("%s on %s\n", __func__, ob->id.name);
1693         }
1694
1695         /* read values pushed into RBO from sim/cache... */
1696         BKE_rigidbody_sync_transforms(rbw, ob, ctime);
1697 }