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