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