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