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