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