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