rigidbody: Avoid unnecessary simulation updates
[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_anim_types.h"
50 #include "DNA_group_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.h"
55 #include "DNA_rigidbody_types.h"
56 #include "DNA_scene_types.h"
57
58 #include "BKE_animsys.h"
59 #include "BKE_cdderivedmesh.h"
60 #include "BKE_effect.h"
61 #include "BKE_group.h"
62 #include "BKE_object.h"
63 #include "BKE_mesh.h"
64 #include "BKE_pointcache.h"
65 #include "BKE_rigidbody.h"
66 #include "BKE_global.h"
67 #include "BKE_utildefines.h"
68
69 #include "RNA_access.h"
70
71 #ifdef WITH_BULLET
72
73 /* ************************************** */
74 /* Memory Management */
75
76 /* Freeing Methods --------------------- */
77
78 /* Free rigidbody world */
79 void BKE_rigidbody_free_world(RigidBodyWorld *rbw)
80 {
81         /* sanity check */
82         if (!rbw)
83                 return;
84
85         if (rbw->physics_world) {
86                 /* free physics references, we assume that all physics objects in will have been added to the world */
87                 GroupObject *go;
88                 if (rbw->constraints) {
89                         for (go = rbw->constraints->gobject.first; go; go = go->next) {
90                                 if (go->ob && go->ob->rigidbody_constraint) {
91                                         RigidBodyCon *rbc = go->ob->rigidbody_constraint;
92
93                                         if (rbc->physics_constraint)
94                                                 RB_dworld_remove_constraint(rbw->physics_world, rbc->physics_constraint);
95                                 }
96                         }
97                 }
98                 if (rbw->group) {
99                         for (go = rbw->group->gobject.first; go; go = go->next) {
100                                 if (go->ob && go->ob->rigidbody_object) {
101                                         RigidBodyOb *rbo = go->ob->rigidbody_object;
102
103                                         if (rbo->physics_object)
104                                                 RB_dworld_remove_body(rbw->physics_world, rbo->physics_object);
105                                 }
106                         }
107                 }
108                 /* free dynamics world */
109                 RB_dworld_delete(rbw->physics_world);
110         }
111         if (rbw->objects)
112                 free(rbw->objects);
113
114         /* free cache */
115         BKE_ptcache_free_list(&(rbw->ptcaches));
116         rbw->pointcache = NULL;
117
118         /* free effector weights */
119         if (rbw->effector_weights)
120                 MEM_freeN(rbw->effector_weights);
121
122         /* free rigidbody world itself */
123         MEM_freeN(rbw);
124 }
125
126 /* Free RigidBody settings and sim instances */
127 void BKE_rigidbody_free_object(Object *ob)
128 {
129         RigidBodyOb *rbo = (ob) ? ob->rigidbody_object : NULL;
130
131         /* sanity check */
132         if (rbo == NULL)
133                 return;
134
135         /* free physics references */
136         if (rbo->physics_object) {
137                 RB_body_delete(rbo->physics_object);
138                 rbo->physics_object = NULL;
139         }
140
141         if (rbo->physics_shape) {
142                 RB_shape_delete(rbo->physics_shape);
143                 rbo->physics_shape = NULL;
144         }
145
146         /* free data itself */
147         MEM_freeN(rbo);
148         ob->rigidbody_object = NULL;
149 }
150
151 /* Free RigidBody constraint and sim instance */
152 void BKE_rigidbody_free_constraint(Object *ob)
153 {
154         RigidBodyCon *rbc = (ob) ? ob->rigidbody_constraint : NULL;
155
156         /* sanity check */
157         if (rbc == NULL)
158                 return;
159
160         /* free physics reference */
161         if (rbc->physics_constraint) {
162                 RB_constraint_delete(rbc->physics_constraint);
163                 rbc->physics_constraint = NULL;
164         }
165
166         /* free data itself */
167         MEM_freeN(rbc);
168         ob->rigidbody_constraint = NULL;
169 }
170
171 /* Copying Methods --------------------- */
172
173 /* These just copy the data, clearing out references to physics objects.
174  * Anything that uses them MUST verify that the copied object will
175  * be added to relevant groups later...
176  */
177
178 RigidBodyOb *BKE_rigidbody_copy_object(Object *ob)
179 {
180         RigidBodyOb *rboN = NULL;
181
182         if (ob->rigidbody_object) {
183                 /* just duplicate the whole struct first (to catch all the settings) */
184                 rboN = MEM_dupallocN(ob->rigidbody_object);
185
186                 /* tag object as needing to be verified */
187                 rboN->flag |= RBO_FLAG_NEEDS_VALIDATE;
188
189                 /* clear out all the fields which need to be revalidated later */
190                 rboN->physics_object = NULL;
191                 rboN->physics_shape = NULL;
192         }
193
194         /* return new copy of settings */
195         return rboN;
196 }
197
198 RigidBodyCon *BKE_rigidbody_copy_constraint(Object *ob)
199 {
200         RigidBodyCon *rbcN = NULL;
201
202         if (ob->rigidbody_constraint) {
203                 /* just duplicate the whole struct first (to catch all the settings) */
204                 rbcN = MEM_dupallocN(ob->rigidbody_constraint);
205
206                 /* tag object as needing to be verified */
207                 rbcN->flag |= RBC_FLAG_NEEDS_VALIDATE;
208
209                 /* clear out all the fields which need to be revalidated later */
210                 rbcN->physics_constraint = NULL;
211         }
212
213         /* return new copy of settings */
214         return rbcN;
215 }
216
217 /* preserve relationships between constraints and rigid bodies after duplication */
218 void BKE_rigidbody_relink_constraint(RigidBodyCon *rbc)
219 {
220         ID_NEW(rbc->ob1);
221         ID_NEW(rbc->ob2);
222 }
223
224 /* ************************************** */
225 /* Setup Utilities - Validate Sim Instances */
226
227 /* create collision shape of mesh - convex hull */
228 static rbCollisionShape *rigidbody_get_shape_convexhull_from_mesh(Object *ob, float margin, bool *can_embed)
229 {
230         rbCollisionShape *shape = NULL;
231         Mesh *me = NULL;
232
233         if (ob->type == OB_MESH && ob->data) {
234                 me = ob->data;
235         }
236         else {
237                 printf("ERROR: cannot make Convex Hull collision shape for non-Mesh object\n");
238         }
239
240         if (me && me->totvert) {
241                 shape = RB_shape_new_convex_hull((float *)me->mvert, sizeof(MVert), me->totvert, margin, can_embed);
242         }
243         else {
244                 printf("ERROR: no vertices to define Convex Hull collision shape with\n");
245         }
246
247         return shape;
248 }
249
250 /* create collision shape of mesh - triangulated mesh
251  * returns NULL if creation fails.
252  */
253 static rbCollisionShape *rigidbody_get_shape_trimesh_from_mesh(Object *ob)
254 {
255         rbCollisionShape *shape = NULL;
256
257         if (ob->type == OB_MESH) {
258                 DerivedMesh *dm = CDDM_from_mesh(ob->data, ob);
259
260                 MVert *mvert;
261                 MFace *mface;
262                 int totvert;
263                 int totface;
264
265                 /* ensure mesh validity, then grab data */
266                 DM_ensure_tessface(dm);
267
268                 mvert   = (dm) ? dm->getVertArray(dm) : NULL;
269                 totvert = (dm) ? dm->getNumVerts(dm) : 0;
270                 mface   = (dm) ? dm->getTessFaceArray(dm) : NULL;
271                 totface = (dm) ? dm->getNumTessFaces(dm) : 0;
272
273                 /* sanity checking - potential case when no data will be present */
274                 if ((totvert == 0) || (totface == 0)) {
275                         printf("WARNING: no geometry data converted for Mesh Collision Shape (ob = %s)\n", ob->id.name + 2);
276                 }
277                 else {
278                         rbMeshData *mdata;
279                         int i;
280
281                         /* init mesh data for collision shape */
282                         mdata = RB_trimesh_data_new();
283
284                         /* loop over all faces, adding them as triangles to the collision shape
285                          * (so for some faces, more than triangle will get added)
286                          */
287                         for (i = 0; (i < totface) && (mface) && (mvert); i++, mface++) {
288                                 /* add first triangle - verts 1,2,3 */
289                                 {
290                                         MVert *va = (IN_RANGE(mface->v1, 0, totvert)) ? (mvert + mface->v1) : (mvert);
291                                         MVert *vb = (IN_RANGE(mface->v2, 0, totvert)) ? (mvert + mface->v2) : (mvert);
292                                         MVert *vc = (IN_RANGE(mface->v3, 0, totvert)) ? (mvert + mface->v3) : (mvert);
293
294                                         RB_trimesh_add_triangle(mdata, va->co, vb->co, vc->co);
295                                 }
296
297                                 /* add second triangle if needed - verts 1,3,4 */
298                                 if (mface->v4) {
299                                         MVert *va = (IN_RANGE(mface->v1, 0, totvert)) ? (mvert + mface->v1) : (mvert);
300                                         MVert *vb = (IN_RANGE(mface->v3, 0, totvert)) ? (mvert + mface->v3) : (mvert);
301                                         MVert *vc = (IN_RANGE(mface->v4, 0, totvert)) ? (mvert + mface->v4) : (mvert);
302
303                                         RB_trimesh_add_triangle(mdata, va->co, vb->co, vc->co);
304                                 }
305                         }
306
307                         /* construct collision shape
308                          *
309                          * These have been chosen to get better speed/accuracy tradeoffs with regards
310                          * to limitations of each:
311                          *    - BVH-Triangle Mesh: for passive objects only. Despite having greater
312                          *                         speed/accuracy, they cannot be used for moving objects.
313                          *    - GImpact Mesh:      for active objects. These are slower and less stable,
314                          *                         but are more flexible for general usage.
315                          */
316                         if (ob->rigidbody_object->type == RBO_TYPE_PASSIVE) {
317                                 shape = RB_shape_new_trimesh(mdata);
318                         }
319                         else {
320                                 shape = RB_shape_new_gimpact_mesh(mdata);
321                         }
322                 }
323
324                 /* cleanup temp data */
325                 if (dm) {
326                         dm->release(dm);
327                 }
328         }
329         else {
330                 printf("ERROR: cannot make Triangular Mesh collision shape for non-Mesh object\n");
331         }
332
333         return shape;
334 }
335
336 /* Create new physics sim collision shape for object and store it,
337  * or remove the existing one first and replace...
338  */
339 void BKE_rigidbody_validate_sim_shape(Object *ob, short rebuild)
340 {
341         RigidBodyOb *rbo = ob->rigidbody_object;
342         rbCollisionShape *new_shape = NULL;
343         BoundBox *bb = NULL;
344         float size[3] = {1.0f, 1.0f, 1.0f};
345         float radius = 1.0f;
346         float height = 1.0f;
347         float capsule_height;
348         float hull_margin = 0.0f;
349         bool can_embed = true;
350
351         /* sanity check */
352         if (rbo == NULL)
353                 return;
354
355         /* don't create a new shape if we already have one and don't want to rebuild it */
356         if (rbo->physics_shape && !rebuild)
357                 return;
358
359         /* if automatically determining dimensions, use the Object's boundbox
360          *      - assume that all quadrics are standing upright on local z-axis
361          *      - assume even distribution of mass around the Object's pivot
362          *        (i.e. Object pivot is centralized in boundbox)
363          */
364         // XXX: all dimensions are auto-determined now... later can add stored settings for this
365         /* get object dimensions without scaling */
366         bb = BKE_object_boundbox_get(ob);
367         if (bb) {
368                 size[0] = (bb->vec[4][0] - bb->vec[0][0]);
369                 size[1] = (bb->vec[2][1] - bb->vec[0][1]);
370                 size[2] = (bb->vec[1][2] - bb->vec[0][2]);
371         }
372         mul_v3_fl(size, 0.5f);
373
374         if (ELEM3(rbo->shape, RB_SHAPE_CAPSULE, RB_SHAPE_CYLINDER, RB_SHAPE_CONE)) {
375                 /* take radius as largest x/y dimension, and height as z-dimension */
376                 radius = MAX2(size[0], size[1]);
377                 height = size[2];
378         }
379         else if (rbo->shape == RB_SHAPE_SPHERE) {
380                 /* take radius to the the largest dimension to try and encompass everything */
381                 radius = MAX3(size[0], size[1], size[2]);
382         }
383
384         /* create new shape */
385         switch (rbo->shape) {
386                 case RB_SHAPE_BOX:
387                         new_shape = RB_shape_new_box(size[0], size[1], size[2]);
388                         break;
389
390                 case RB_SHAPE_SPHERE:
391                         new_shape = RB_shape_new_sphere(radius);
392                         break;
393
394                 case RB_SHAPE_CAPSULE:
395                         capsule_height = (height - radius) * 2.0f;
396                         new_shape = RB_shape_new_capsule(radius, (capsule_height > 0.0f) ? capsule_height : 0.0f);
397                         break;
398                 case RB_SHAPE_CYLINDER:
399                         new_shape = RB_shape_new_cylinder(radius, height);
400                         break;
401                 case RB_SHAPE_CONE:
402                         new_shape = RB_shape_new_cone(radius, height * 2.0f);
403                         break;
404
405                 case RB_SHAPE_CONVEXH:
406                         /* try to emged collision margin */
407                         if (!(rbo->flag & RBO_FLAG_USE_MARGIN))
408                                 hull_margin = 0.04f;
409                         new_shape = rigidbody_get_shape_convexhull_from_mesh(ob, hull_margin, &can_embed);
410                         if (!(rbo->flag & RBO_FLAG_USE_MARGIN))
411                                 rbo->margin = (can_embed) ? 0.04f : 0.0f;  /* RB_TODO ideally we shouldn't directly change the margin here */
412                         break;
413                 case RB_SHAPE_TRIMESH:
414                         new_shape = rigidbody_get_shape_trimesh_from_mesh(ob);
415                         break;
416         }
417         /* assign new collision shape if creation was successful */
418         if (new_shape) {
419                 if (rbo->physics_shape)
420                         RB_shape_delete(rbo->physics_shape);
421                 rbo->physics_shape = new_shape;
422                 RB_shape_set_margin(rbo->physics_shape, RBO_GET_MARGIN(rbo));
423         }
424         else { /* otherwise fall back to box shape */
425                 rbo->shape = RB_SHAPE_BOX;
426                 BKE_rigidbody_validate_sim_shape(ob, true);
427         }
428 }
429
430 /* --------------------- */
431
432 /* Create physics sim representation of object given RigidBody settings
433  * < rebuild: even if an instance already exists, replace it
434  */
435 void BKE_rigidbody_validate_sim_object(RigidBodyWorld *rbw, Object *ob, short rebuild)
436 {
437         RigidBodyOb *rbo = (ob) ? ob->rigidbody_object : NULL;
438         float loc[3];
439         float rot[4];
440
441         /* sanity checks:
442          *      - object doesn't have RigidBody info already: then why is it here?
443          */
444         if (rbo == NULL)
445                 return;
446
447         /* make sure collision shape exists */
448         /* FIXME we shouldn't always have to rebuild collision shapes when rebuilding objects, but it's needed for constraints to update correctly */
449         if (rbo->physics_shape == NULL || rebuild)
450                 BKE_rigidbody_validate_sim_shape(ob, true);
451
452         if (rbo->physics_object) {
453                 if (rebuild == false)
454                         RB_dworld_remove_body(rbw->physics_world, rbo->physics_object);
455         }
456         if (!rbo->physics_object || rebuild) {
457                 /* remove rigid body if it already exists before creating a new one */
458                 if (rbo->physics_object) {
459                         RB_body_delete(rbo->physics_object);
460                 }
461
462                 mat4_to_loc_quat(loc, rot, ob->obmat);
463
464                 rbo->physics_object = RB_body_new(rbo->physics_shape, loc, rot);
465
466                 RB_body_set_friction(rbo->physics_object, rbo->friction);
467                 RB_body_set_restitution(rbo->physics_object, rbo->restitution);
468
469                 RB_body_set_damping(rbo->physics_object, rbo->lin_damping, rbo->ang_damping);
470                 RB_body_set_sleep_thresh(rbo->physics_object, rbo->lin_sleep_thresh, rbo->ang_sleep_thresh);
471                 RB_body_set_activation_state(rbo->physics_object, rbo->flag & RBO_FLAG_USE_DEACTIVATION);
472
473                 if (rbo->type == RBO_TYPE_PASSIVE || rbo->flag & RBO_FLAG_START_DEACTIVATED)
474                         RB_body_deactivate(rbo->physics_object);
475
476
477                 RB_body_set_linear_factor(rbo->physics_object,
478                                           (ob->protectflag & OB_LOCK_LOCX) == 0,
479                                           (ob->protectflag & OB_LOCK_LOCY) == 0,
480                                           (ob->protectflag & OB_LOCK_LOCZ) == 0);
481                 RB_body_set_angular_factor(rbo->physics_object,
482                                            (ob->protectflag & OB_LOCK_ROTX) == 0,
483                                            (ob->protectflag & OB_LOCK_ROTY) == 0,
484                                            (ob->protectflag & OB_LOCK_ROTZ) == 0);
485
486                 RB_body_set_mass(rbo->physics_object, RBO_GET_MASS(rbo));
487                 RB_body_set_kinematic_state(rbo->physics_object, rbo->flag & RBO_FLAG_KINEMATIC || rbo->flag & RBO_FLAG_DISABLED);
488         }
489
490         if (rbw && rbw->physics_world)
491                 RB_dworld_add_body(rbw->physics_world, rbo->physics_object, rbo->col_groups);
492 }
493
494 /* --------------------- */
495
496 /* Create physics sim representation of constraint given rigid body constraint settings
497  * < rebuild: even if an instance already exists, replace it
498  */
499 void BKE_rigidbody_validate_sim_constraint(RigidBodyWorld *rbw, Object *ob, short rebuild)
500 {
501         RigidBodyCon *rbc = (ob) ? ob->rigidbody_constraint : NULL;
502         float loc[3];
503         float rot[4];
504         float lin_lower;
505         float lin_upper;
506         float ang_lower;
507         float ang_upper;
508
509         /* sanity checks:
510          *      - object should have a rigid body constraint
511          *  - rigid body constraint should have at least one constrained object
512          */
513         if (rbc == NULL) {
514                 return;
515         }
516
517         if (ELEM4(NULL, rbc->ob1, rbc->ob1->rigidbody_object, rbc->ob2, rbc->ob2->rigidbody_object)) {
518                 if (rbc->physics_constraint) {
519                         RB_dworld_remove_constraint(rbw->physics_world, rbc->physics_constraint);
520                         RB_constraint_delete(rbc->physics_constraint);
521                         rbc->physics_constraint = NULL;
522                 }
523                 return;
524         }
525
526         if (rbc->physics_constraint) {
527                 if (rebuild == false)
528                         RB_dworld_remove_constraint(rbw->physics_world, rbc->physics_constraint);
529         }
530         if (rbc->physics_constraint == NULL || rebuild) {
531                 rbRigidBody *rb1 = rbc->ob1->rigidbody_object->physics_object;
532                 rbRigidBody *rb2 = rbc->ob2->rigidbody_object->physics_object;
533
534                 /* remove constraint if it already exists before creating a new one */
535                 if (rbc->physics_constraint) {
536                         RB_constraint_delete(rbc->physics_constraint);
537                         rbc->physics_constraint = NULL;
538                 }
539
540                 mat4_to_loc_quat(loc, rot, ob->obmat);
541
542                 if (rb1 && rb2) {
543                         switch (rbc->type) {
544                                 case RBC_TYPE_POINT:
545                                         rbc->physics_constraint = RB_constraint_new_point(loc, rb1, rb2);
546                                         break;
547                                 case RBC_TYPE_FIXED:
548                                         rbc->physics_constraint = RB_constraint_new_fixed(loc, rot, rb1, rb2);
549                                         break;
550                                 case RBC_TYPE_HINGE:
551                                         rbc->physics_constraint = RB_constraint_new_hinge(loc, rot, rb1, rb2);
552                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Z) {
553                                                 RB_constraint_set_limits_hinge(rbc->physics_constraint, rbc->limit_ang_z_lower, rbc->limit_ang_z_upper);
554                                         }
555                                         else
556                                                 RB_constraint_set_limits_hinge(rbc->physics_constraint, 0.0f, -1.0f);
557                                         break;
558                                 case RBC_TYPE_SLIDER:
559                                         rbc->physics_constraint = RB_constraint_new_slider(loc, rot, rb1, rb2);
560                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X)
561                                                 RB_constraint_set_limits_slider(rbc->physics_constraint, rbc->limit_lin_x_lower, rbc->limit_lin_x_upper);
562                                         else
563                                                 RB_constraint_set_limits_slider(rbc->physics_constraint, 0.0f, -1.0f);
564                                         break;
565                                 case RBC_TYPE_PISTON:
566                                         rbc->physics_constraint = RB_constraint_new_piston(loc, rot, rb1, rb2);
567                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X) {
568                                                 lin_lower = rbc->limit_lin_x_lower;
569                                                 lin_upper = rbc->limit_lin_x_upper;
570                                         }
571                                         else {
572                                                 lin_lower = 0.0f;
573                                                 lin_upper = -1.0f;
574                                         }
575                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_X) {
576                                                 ang_lower = rbc->limit_ang_x_lower;
577                                                 ang_upper = rbc->limit_ang_x_upper;
578                                         }
579                                         else {
580                                                 ang_lower = 0.0f;
581                                                 ang_upper = -1.0f;
582                                         }
583                                         RB_constraint_set_limits_piston(rbc->physics_constraint, lin_lower, lin_upper, ang_lower, ang_upper);
584                                         break;
585                                 case RBC_TYPE_6DOF_SPRING:
586                                         rbc->physics_constraint = RB_constraint_new_6dof_spring(loc, rot, rb1, rb2);
587
588                                         RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->flag & RBC_FLAG_USE_SPRING_X);
589                                         RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->spring_stiffness_x);
590                                         RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->spring_damping_x);
591
592                                         RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->flag & RBC_FLAG_USE_SPRING_Y);
593                                         RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->spring_stiffness_y);
594                                         RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->spring_damping_y);
595
596                                         RB_constraint_set_spring_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->flag & RBC_FLAG_USE_SPRING_Z);
597                                         RB_constraint_set_stiffness_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->spring_stiffness_z);
598                                         RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->spring_damping_z);
599
600                                         RB_constraint_set_equilibrium_6dof_spring(rbc->physics_constraint);
601                                 /* fall through */
602                                 case RBC_TYPE_6DOF:
603                                         if (rbc->type == RBC_TYPE_6DOF) /* a litte awkward but avoids duplicate code for limits */
604                                                 rbc->physics_constraint = RB_constraint_new_6dof(loc, rot, rb1, rb2);
605
606                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X)
607                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->limit_lin_x_lower, rbc->limit_lin_x_upper);
608                                         else
609                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_X, 0.0f, -1.0f);
610
611                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_Y)
612                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->limit_lin_y_lower, rbc->limit_lin_y_upper);
613                                         else
614                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_Y, 0.0f, -1.0f);
615
616                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_Z)
617                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->limit_lin_z_lower, rbc->limit_lin_z_upper);
618                                         else
619                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_Z, 0.0f, -1.0f);
620
621                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_X)
622                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->limit_ang_x_lower, rbc->limit_ang_x_upper);
623                                         else
624                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_X, 0.0f, -1.0f);
625
626                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Y)
627                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->limit_ang_y_lower, rbc->limit_ang_y_upper);
628                                         else
629                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_Y, 0.0f, -1.0f);
630
631                                         if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Z)
632                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->limit_ang_z_lower, rbc->limit_ang_z_upper);
633                                         else
634                                                 RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_Z, 0.0f, -1.0f);
635                                         break;
636                         }
637                 }
638
639                 RB_constraint_set_enabled(rbc->physics_constraint, rbc->flag & RBC_FLAG_ENABLED);
640
641                 if (rbc->flag & RBC_FLAG_USE_BREAKING)
642                         RB_constraint_set_breaking_threshold(rbc->physics_constraint, rbc->breaking_threshold);
643                 else
644                         RB_constraint_set_breaking_threshold(rbc->physics_constraint, FLT_MAX);
645
646                 if (rbc->flag & RBC_FLAG_OVERRIDE_SOLVER_ITERATIONS)
647                         RB_constraint_set_solver_iterations(rbc->physics_constraint, rbc->num_solver_iterations);
648                 else
649                         RB_constraint_set_solver_iterations(rbc->physics_constraint, -1);
650         }
651
652         if (rbw && rbw->physics_world && rbc->physics_constraint) {
653                 RB_dworld_add_constraint(rbw->physics_world, rbc->physics_constraint, rbc->flag & RBC_FLAG_DISABLE_COLLISIONS);
654         }
655 }
656
657 /* --------------------- */
658
659 /* Create physics sim world given RigidBody world settings */
660 // NOTE: this does NOT update object references that the scene uses, in case those aren't ready yet!
661 void BKE_rigidbody_validate_sim_world(Scene *scene, RigidBodyWorld *rbw, short rebuild)
662 {
663         /* sanity checks */
664         if (rbw == NULL)
665                 return;
666
667         /* create new sim world */
668         if (rebuild || rbw->physics_world == NULL) {
669                 if (rbw->physics_world)
670                         RB_dworld_delete(rbw->physics_world);
671                 rbw->physics_world = RB_dworld_new(scene->physics_settings.gravity);
672         }
673
674         RB_dworld_set_solver_iterations(rbw->physics_world, rbw->num_solver_iterations);
675         RB_dworld_set_split_impulse(rbw->physics_world, rbw->flag & RBW_FLAG_USE_SPLIT_IMPULSE);
676 }
677
678 /* ************************************** */
679 /* Setup Utilities - Create Settings Blocks */
680
681 /* Set up RigidBody world */
682 RigidBodyWorld *BKE_rigidbody_create_world(Scene *scene)
683 {
684         /* try to get whatever RigidBody world that might be representing this already */
685         RigidBodyWorld *rbw;
686
687         /* sanity checks
688          *      - there must be a valid scene to add world to
689          *      - there mustn't be a sim world using this group already
690          */
691         if (scene == NULL)
692                 return NULL;
693
694         /* create a new sim world */
695         rbw = MEM_callocN(sizeof(RigidBodyWorld), "RigidBodyWorld");
696
697         /* set default settings */
698         rbw->effector_weights = BKE_add_effector_weights(NULL);
699
700         rbw->ltime = PSFRA;
701
702         rbw->time_scale = 1.0f;
703
704         rbw->steps_per_second = 60; /* Bullet default (60 Hz) */
705         rbw->num_solver_iterations = 10; /* 10 is bullet default */
706
707         rbw->pointcache = BKE_ptcache_add(&(rbw->ptcaches));
708         rbw->pointcache->step = 1;
709
710         /* return this sim world */
711         return rbw;
712 }
713
714 /* Add rigid body settings to the specified object */
715 RigidBodyOb *BKE_rigidbody_create_object(Scene *scene, Object *ob, short type)
716 {
717         RigidBodyOb *rbo;
718         RigidBodyWorld *rbw = scene->rigidbody_world;
719
720         /* sanity checks
721          *      - rigidbody world must exist
722          *      - object must exist
723          *      - cannot add rigid body if it already exists
724          */
725         if (ob == NULL || (ob->rigidbody_object != NULL))
726                 return NULL;
727
728         /* create new settings data, and link it up */
729         rbo = MEM_callocN(sizeof(RigidBodyOb), "RigidBodyOb");
730
731         /* set default settings */
732         rbo->type = type;
733
734         rbo->mass = 1.0f;
735
736         rbo->friction = 0.5f; /* best when non-zero. 0.5 is Bullet default */
737         rbo->restitution = 0.0f; /* best when zero. 0.0 is Bullet default */
738
739         rbo->margin = 0.04f; /* 0.04 (in meters) is Bullet default */
740
741         rbo->lin_sleep_thresh = 0.4f; /* 0.4 is half of Bullet default */
742         rbo->ang_sleep_thresh = 0.5f; /* 0.5 is half of Bullet default */
743
744         rbo->lin_damping = 0.04f; /* 0.04 is game engine default */
745         rbo->ang_damping = 0.1f; /* 0.1 is game engine default */
746
747         rbo->col_groups = 1;
748
749         /* use triangle meshes for passive objects
750          * use convex hulls for active objects since dynamic triangle meshes are very unstable
751          */
752         if (type == RBO_TYPE_ACTIVE)
753                 rbo->shape = RB_SHAPE_CONVEXH;
754         else
755                 rbo->shape = RB_SHAPE_TRIMESH;
756
757         /* set initial transform */
758         mat4_to_loc_quat(rbo->pos, rbo->orn, ob->obmat);
759
760         /* flag cache as outdated */
761         BKE_rigidbody_cache_reset(rbw);
762
763         /* return this object */
764         return rbo;
765 }
766
767 /* Add rigid body constraint to the specified object */
768 RigidBodyCon *BKE_rigidbody_create_constraint(Scene *scene, Object *ob, short type)
769 {
770         RigidBodyCon *rbc;
771         RigidBodyWorld *rbw = scene->rigidbody_world;
772
773         /* sanity checks
774          *      - rigidbody world must exist
775          *      - object must exist
776          *      - cannot add constraint if it already exists
777          */
778         if (ob == NULL || (ob->rigidbody_constraint != NULL))
779                 return NULL;
780
781         /* create new settings data, and link it up */
782         rbc = MEM_callocN(sizeof(RigidBodyCon), "RigidBodyCon");
783
784         /* set default settings */
785         rbc->type = type;
786
787         rbc->ob1 = NULL;
788         rbc->ob2 = NULL;
789
790         rbc->flag |= RBC_FLAG_ENABLED;
791         rbc->flag |= RBC_FLAG_DISABLE_COLLISIONS;
792
793         rbc->breaking_threshold = 10.0f; /* no good default here, just use 10 for now */
794         rbc->num_solver_iterations = 10; /* 10 is Bullet default */
795
796         rbc->limit_lin_x_lower = -1.0f;
797         rbc->limit_lin_x_upper = 1.0f;
798         rbc->limit_lin_y_lower = -1.0f;
799         rbc->limit_lin_y_upper = 1.0f;
800         rbc->limit_lin_z_lower = -1.0f;
801         rbc->limit_lin_z_upper = 1.0f;
802         rbc->limit_ang_x_lower = -M_PI_4;
803         rbc->limit_ang_x_upper = M_PI_4;
804         rbc->limit_ang_y_lower = -M_PI_4;
805         rbc->limit_ang_y_upper = M_PI_4;
806         rbc->limit_ang_z_lower = -M_PI_4;
807         rbc->limit_ang_z_upper = M_PI_4;
808
809         rbc->spring_damping_x = 0.5f;
810         rbc->spring_damping_y = 0.5f;
811         rbc->spring_damping_z = 0.5f;
812         rbc->spring_stiffness_x = 10.0f;
813         rbc->spring_stiffness_y = 10.0f;
814         rbc->spring_stiffness_z = 10.0f;
815
816         /* flag cache as outdated */
817         BKE_rigidbody_cache_reset(rbw);
818
819         /* return this object */
820         return rbc;
821 }
822
823 /* ************************************** */
824 /* Utilities API */
825
826 /* Get RigidBody world for the given scene, creating one if needed
827  * < scene: Scene to find active Rigid Body world for
828  */
829 RigidBodyWorld *BKE_rigidbody_get_world(Scene *scene)
830 {
831         /* sanity check */
832         if (scene == NULL)
833                 return NULL;
834
835         return scene->rigidbody_world;
836 }
837
838 void BKE_rigidbody_remove_object(Scene *scene, Object *ob)
839 {
840         RigidBodyWorld *rbw = scene->rigidbody_world;
841         RigidBodyOb *rbo = ob->rigidbody_object;
842         RigidBodyCon *rbc;
843         GroupObject *go;
844         int i;
845
846         if (rbw) {
847                 /* remove from rigidbody world, free object won't do this */
848                 if (rbw->physics_world && rbo->physics_object)
849                         RB_dworld_remove_body(rbw->physics_world, rbo->physics_object);
850
851                 /* remove object from array */
852                 if (rbw && rbw->objects) {
853                         for (i = 0; i < rbw->numbodies; i++) {
854                                 if (rbw->objects[i] == ob) {
855                                         rbw->objects[i] = NULL;
856                                         break;
857                                 }
858                         }
859                 }
860
861                 /* remove object from rigid body constraints */
862                 if (rbw->constraints) {
863                         for (go = rbw->constraints->gobject.first; go; go = go->next) {
864                                 Object *obt = go->ob;
865                                 if (obt && obt->rigidbody_constraint) {
866                                         rbc = obt->rigidbody_constraint;
867                                         if (rbc->ob1 == ob) {
868                                                 rbc->ob1 = NULL;
869                                                 rbc->flag |= RBC_FLAG_NEEDS_VALIDATE;
870                                         }
871                                         if (rbc->ob2 == ob) {
872                                                 rbc->ob2 = NULL;
873                                                 rbc->flag |= RBC_FLAG_NEEDS_VALIDATE;
874                                         }
875                                 }
876                         }
877                 }
878         }
879
880         /* remove object's settings */
881         BKE_rigidbody_free_object(ob);
882
883         /* flag cache as outdated */
884         BKE_rigidbody_cache_reset(rbw);
885 }
886
887 void BKE_rigidbody_remove_constraint(Scene *scene, Object *ob)
888 {
889         RigidBodyWorld *rbw = scene->rigidbody_world;
890         RigidBodyCon *rbc = ob->rigidbody_constraint;
891
892         if (rbw) {
893                 /* remove from rigidbody world, free object won't do this */
894                 if (rbw && rbw->physics_world && rbc->physics_constraint)
895                         RB_dworld_remove_constraint(rbw->physics_world, rbc->physics_constraint);
896         }
897         /* remove object's settings */
898         BKE_rigidbody_free_constraint(ob);
899
900         /* flag cache as outdated */
901         BKE_rigidbody_cache_reset(rbw);
902 }
903
904
905 /* ************************************** */
906 /* Simulation Interface - Bullet */
907
908 /* Update object array and rigid body count so they're in sync with the rigid body group */
909 static void rigidbody_update_ob_array(RigidBodyWorld *rbw)
910 {
911         GroupObject *go;
912         int i, n;
913
914         n = BLI_countlist(&rbw->group->gobject);
915
916         if (rbw->numbodies != n) {
917                 rbw->numbodies = n;
918                 rbw->objects = realloc(rbw->objects, sizeof(Object *) * rbw->numbodies);
919         }
920
921         for (go = rbw->group->gobject.first, i = 0; go; go = go->next, i++) {
922                 Object *ob = go->ob;
923                 rbw->objects[i] = ob;
924         }
925 }
926
927 static void rigidbody_update_sim_world(Scene *scene, RigidBodyWorld *rbw)
928 {
929         float adj_gravity[3];
930
931         /* adjust gravity to take effector weights into account */
932         if (scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) {
933                 copy_v3_v3(adj_gravity, scene->physics_settings.gravity);
934                 mul_v3_fl(adj_gravity, rbw->effector_weights->global_gravity * rbw->effector_weights->weight[0]);
935         }
936         else {
937                 zero_v3(adj_gravity);
938         }
939
940         /* update gravity, since this RNA setting is not part of RigidBody settings */
941         RB_dworld_set_gravity(rbw->physics_world, adj_gravity);
942
943         /* update object array in case there are changes */
944         rigidbody_update_ob_array(rbw);
945 }
946
947 static void rigidbody_update_sim_ob(Scene *scene, RigidBodyWorld *rbw, Object *ob, RigidBodyOb *rbo)
948 {
949         float loc[3];
950         float rot[4];
951         float scale[3];
952
953         /* only update if rigid body exists */
954         if (rbo->physics_object == NULL)
955                 return;
956
957         mat4_decompose(loc, rot, scale, ob->obmat);
958
959         /* update scale for all objects */
960         RB_body_set_scale(rbo->physics_object, scale);
961         /* compensate for embedded convex hull collision margin */
962         if (!(rbo->flag & RBO_FLAG_USE_MARGIN) && rbo->shape == RB_SHAPE_CONVEXH)
963                 RB_shape_set_margin(rbo->physics_shape, RBO_GET_MARGIN(rbo) * MIN3(scale[0], scale[1], scale[2]));
964
965         /* make transformed objects temporarily kinmatic so that they can be moved by the user during simulation */
966         if (ob->flag & SELECT && G.moving & G_TRANSFORM_OBJ) {
967                 RB_body_set_kinematic_state(rbo->physics_object, TRUE);
968                 RB_body_set_mass(rbo->physics_object, 0.0f);
969         }
970
971         /* update rigid body location and rotation for kinematic bodies */
972         if (rbo->flag & RBO_FLAG_KINEMATIC || (ob->flag & SELECT && G.moving & G_TRANSFORM_OBJ)) {
973                 RB_body_activate(rbo->physics_object);
974                 RB_body_set_loc_rot(rbo->physics_object, loc, rot);
975         }
976         /* update influence of effectors - but don't do it on an effector */
977         /* only dynamic bodies need effector update */
978         else if (rbo->type == RBO_TYPE_ACTIVE && ((ob->pd == NULL) || (ob->pd->forcefield == PFIELD_NULL))) {
979                 EffectorWeights *effector_weights = rbw->effector_weights;
980                 EffectedPoint epoint;
981                 ListBase *effectors;
982
983                 /* get effectors present in the group specified by effector_weights */
984                 effectors = pdInitEffectors(scene, ob, NULL, effector_weights);
985                 if (effectors) {
986                         float force[3] = {0.0f, 0.0f, 0.0f};
987                         float loc[3], vel[3];
988
989                         /* create dummy 'point' which represents last known position of object as result of sim */
990                         // XXX: this can create some inaccuracies with sim position, but is probably better than using unsimulated vals?
991                         RB_body_get_position(rbo->physics_object, loc);
992                         RB_body_get_linear_velocity(rbo->physics_object, vel);
993
994                         pd_point_from_loc(scene, loc, vel, 0, &epoint);
995
996                         /* calculate net force of effectors, and apply to sim object
997                          *      - we use 'central force' since apply force requires a "relative position" which we don't have...
998                          */
999                         pdDoEffectors(effectors, NULL, effector_weights, &epoint, force, NULL);
1000                         if (G.f & G_DEBUG)
1001                                 printf("\tapplying force (%f,%f,%f) to '%s'\n", force[0], force[1], force[2], ob->id.name + 2);
1002                         /* activate object in case it is deactivated */
1003                         if (!is_zero_v3(force))
1004                                 RB_body_activate(rbo->physics_object);
1005                         RB_body_apply_central_force(rbo->physics_object, force);
1006                 }
1007                 else if (G.f & G_DEBUG)
1008                         printf("\tno forces to apply to '%s'\n", ob->id.name + 2);
1009
1010                 /* cleanup */
1011                 pdEndEffectors(&effectors);
1012         }
1013         /* NOTE: passive objects don't need to be updated since they don't move */
1014
1015         /* NOTE: no other settings need to be explicitly updated here,
1016          * since RNA setters take care of the rest :)
1017          */
1018 }
1019
1020 /* Updates and validates world, bodies and shapes.
1021  * < rebuild: rebuild entire simulation
1022  */
1023 static void rigidbody_update_simulation(Scene *scene, RigidBodyWorld *rbw, int rebuild)
1024 {
1025         GroupObject *go;
1026
1027         /* update world */
1028         if (rebuild)
1029                 BKE_rigidbody_validate_sim_world(scene, rbw, true);
1030         rigidbody_update_sim_world(scene, rbw);
1031
1032         /* update objects */
1033         for (go = rbw->group->gobject.first; go; go = go->next) {
1034                 Object *ob = go->ob;
1035
1036                 if (ob && ob->type == OB_MESH) {
1037                         /* validate that we've got valid object set up here... */
1038                         RigidBodyOb *rbo = ob->rigidbody_object;
1039                         /* update transformation matrix of the object so we don't get a frame of lag for simple animations */
1040                         BKE_object_where_is_calc(scene, ob);
1041
1042                         if (rbo == NULL) {
1043                                 /* Since this object is included in the sim group but doesn't have
1044                                  * rigid body settings (perhaps it was added manually), add!
1045                                  *      - assume object to be active? That is the default for newly added settings...
1046                                  */
1047                                 ob->rigidbody_object = BKE_rigidbody_create_object(scene, ob, RBO_TYPE_ACTIVE);
1048                                 BKE_rigidbody_validate_sim_object(rbw, ob, true);
1049
1050                                 rbo = ob->rigidbody_object;
1051                         }
1052                         else {
1053                                 /* perform simulation data updates as tagged */
1054                                 /* refresh object... */
1055                                 if (rebuild) {
1056                                         /* World has been rebuilt so rebuild object */
1057                                         BKE_rigidbody_validate_sim_object(rbw, ob, true);
1058                                 }
1059                                 else if (rbo->flag & RBO_FLAG_NEEDS_VALIDATE) {
1060                                         BKE_rigidbody_validate_sim_object(rbw, ob, false);
1061                                 }
1062                                 /* refresh shape... */
1063                                 if (rbo->flag & RBO_FLAG_NEEDS_RESHAPE) {
1064                                         /* mesh/shape data changed, so force shape refresh */
1065                                         BKE_rigidbody_validate_sim_shape(ob, true);
1066                                         /* now tell RB sim about it */
1067                                         // XXX: we assume that this can only get applied for active/passive shapes that will be included as rigidbodies
1068                                         RB_body_set_collision_shape(rbo->physics_object, rbo->physics_shape);
1069                                 }
1070                                 rbo->flag &= ~(RBO_FLAG_NEEDS_VALIDATE | RBO_FLAG_NEEDS_RESHAPE);
1071                         }
1072
1073                         /* update simulation object... */
1074                         rigidbody_update_sim_ob(scene, rbw, ob, rbo);
1075                 }
1076         }
1077         /* update constraints */
1078         if (rbw->constraints == NULL) /* no constraints, move on */
1079                 return;
1080         for (go = rbw->constraints->gobject.first; go; go = go->next) {
1081                 Object *ob = go->ob;
1082
1083                 if (ob) {
1084                         /* validate that we've got valid object set up here... */
1085                         RigidBodyCon *rbc = ob->rigidbody_constraint;
1086                         /* update transformation matrix of the object so we don't get a frame of lag for simple animations */
1087                         BKE_object_where_is_calc(scene, ob);
1088
1089                         if (rbc == NULL) {
1090                                 /* Since this object is included in the group but doesn't have
1091                                  * constraint settings (perhaps it was added manually), add!
1092                                  */
1093                                 ob->rigidbody_constraint = BKE_rigidbody_create_constraint(scene, ob, RBC_TYPE_FIXED);
1094                                 BKE_rigidbody_validate_sim_constraint(rbw, ob, true);
1095
1096                                 rbc = ob->rigidbody_constraint;
1097                         }
1098                         else {
1099                                 /* perform simulation data updates as tagged */
1100                                 if (rebuild) {
1101                                         /* World has been rebuilt so rebuild constraint */
1102                                         BKE_rigidbody_validate_sim_constraint(rbw, ob, true);
1103                                 }
1104                                 else if (rbc->flag & RBC_FLAG_NEEDS_VALIDATE) {
1105                                         BKE_rigidbody_validate_sim_constraint(rbw, ob, false);
1106                                 }
1107                                 rbc->flag &= ~RBC_FLAG_NEEDS_VALIDATE;
1108                         }
1109                 }
1110         }
1111 }
1112
1113 static void rigidbody_update_simulation_post_step(RigidBodyWorld *rbw)
1114 {
1115         GroupObject *go;
1116
1117         for (go = rbw->group->gobject.first; go; go = go->next) {
1118                 Object *ob = go->ob;
1119
1120                 if (ob) {
1121                         RigidBodyOb *rbo = ob->rigidbody_object;
1122                         /* reset kinematic state for transformed objects */
1123                         if (ob->flag & SELECT && G.moving & G_TRANSFORM_OBJ) {
1124                                 RB_body_set_kinematic_state(rbo->physics_object, rbo->flag & RBO_FLAG_KINEMATIC || rbo->flag & RBO_FLAG_DISABLED);
1125                                 RB_body_set_mass(rbo->physics_object, RBO_GET_MASS(rbo));
1126                                 /* deactivate passive objects so they don't interfere with deactivation of active objects */
1127                                 if (rbo->type == RBO_TYPE_PASSIVE)
1128                                         RB_body_deactivate(rbo->physics_object);
1129                         }
1130                 }
1131         }
1132 }
1133
1134 /* Sync rigid body and object transformations */
1135 void BKE_rigidbody_sync_transforms(Scene *scene, Object *ob, float ctime)
1136 {
1137         RigidBodyWorld *rbw = scene->rigidbody_world;
1138         RigidBodyOb *rbo = ob->rigidbody_object;
1139         bool world_ok = true;
1140
1141         /* keep original transform for kinematic and passive objects */
1142         if ((rbo == NULL) || (rbo->flag & RBO_FLAG_KINEMATIC) || (rbo->type == RBO_TYPE_PASSIVE))
1143                 return;
1144                 
1145         /* "scene" may not be the one where object + rigidbody sim actually reside
1146          * due to the quirks of how background-sets eval works [#33970]
1147          */
1148         if (rbw) {
1149                 /* 1) no cache exists before startframe */
1150                 /* 2) keep original transform when simulation is muted */
1151                 world_ok = (ctime > rbw->pointcache->startframe) && !(rbw->flag & RBW_FLAG_MUTED);
1152         }
1153
1154         /* use rigid body transform after cache start frame if objects is not being transformed */
1155         if (world_ok && !((ob->flag & SELECT) && (G.moving & G_TRANSFORM_OBJ))) {
1156                 float mat[4][4], size_mat[4][4], size[3];
1157
1158                 normalize_qt(rbo->orn); // RB_TODO investigate why quaternion isn't normalized at this point
1159                 quat_to_mat4(mat, rbo->orn);
1160                 copy_v3_v3(mat[3], rbo->pos);
1161
1162                 mat4_to_size(size, ob->obmat);
1163                 size_to_mat4(size_mat, size);
1164                 mult_m4_m4m4(mat, mat, size_mat);
1165
1166                 copy_m4_m4(ob->obmat, mat);
1167         }
1168         /* otherwise set rigid body transform to current obmat */
1169         else {
1170                 mat4_to_loc_quat(rbo->pos, rbo->orn, ob->obmat);
1171         }
1172 }
1173
1174 /* Used when cancelling transforms - return rigidbody and object to initial states */
1175 void BKE_rigidbody_aftertrans_update(Object *ob, float loc[3], float rot[3], float quat[4], float rotAxis[3], float rotAngle)
1176 {
1177         RigidBodyOb *rbo = ob->rigidbody_object;
1178
1179         /* return rigid body and object to their initial states */
1180         copy_v3_v3(rbo->pos, ob->loc);
1181         copy_v3_v3(ob->loc, loc);
1182
1183         if (ob->rotmode > 0) {
1184                 eulO_to_quat(rbo->orn, ob->rot, ob->rotmode);
1185                 copy_v3_v3(ob->rot, rot);
1186         }
1187         else if (ob->rotmode == ROT_MODE_AXISANGLE) {
1188                 axis_angle_to_quat(rbo->orn, ob->rotAxis, ob->rotAngle);
1189                 copy_v3_v3(ob->rotAxis, rotAxis);
1190                 ob->rotAngle = rotAngle;
1191         }
1192         else {
1193                 copy_qt_qt(rbo->orn, ob->quat);
1194                 copy_qt_qt(ob->quat, quat);
1195         }
1196         if (rbo->physics_object) {
1197                 /* allow passive objects to return to original transform */
1198                 if (rbo->type == RBO_TYPE_PASSIVE)
1199                         RB_body_set_kinematic_state(rbo->physics_object, TRUE);
1200                 RB_body_set_loc_rot(rbo->physics_object, rbo->pos, rbo->orn);
1201         }
1202         // 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)
1203 }
1204
1205 void BKE_rigidbody_cache_reset(RigidBodyWorld *rbw)
1206 {
1207         if (rbw)
1208                 rbw->pointcache->flag |= PTCACHE_OUTDATED;
1209 }
1210
1211 /* ------------------ */
1212
1213 /* Run RigidBody simulation for the specified physics world */
1214 void BKE_rigidbody_do_simulation(Scene *scene, float ctime)
1215 {
1216         float timestep;
1217         RigidBodyWorld *rbw = scene->rigidbody_world;
1218         PointCache *cache;
1219         PTCacheID pid;
1220         int startframe, endframe;
1221
1222         BKE_ptcache_id_from_rigidbody(&pid, NULL, rbw);
1223         BKE_ptcache_id_time(&pid, scene, ctime, &startframe, &endframe, NULL);
1224         cache = rbw->pointcache;
1225
1226         rbw->flag &= ~RBW_FLAG_FRAME_UPDATE;
1227
1228         /* flag cache as outdated if we don't have a world or number of objects in the simulation has changed */
1229         if (rbw->physics_world == NULL || rbw->numbodies != BLI_countlist(&rbw->group->gobject)) {
1230                 cache->flag |= PTCACHE_OUTDATED;
1231         }
1232
1233         if (ctime <= startframe) {
1234                 rbw->ltime = startframe;
1235                 /* reset and rebuild simulation if necessary */
1236                 if (cache->flag & PTCACHE_OUTDATED) {
1237                         BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
1238                         rigidbody_update_simulation(scene, rbw, true);
1239                         BKE_ptcache_validate(cache, (int)ctime);
1240                         cache->last_exact = 0;
1241                         cache->flag &= ~PTCACHE_REDO_NEEDED;
1242                 }
1243                 return;
1244         }
1245         /* rebuild world if it's outdated on second frame */
1246         else if (ctime == startframe + 1 && rbw->ltime == startframe && cache->flag & PTCACHE_OUTDATED) {
1247                 BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
1248                 rigidbody_update_simulation(scene, rbw, true);
1249         }
1250         /* make sure we don't go out of cache frame range */
1251         else if (ctime > endframe) {
1252                 ctime = endframe;
1253         }
1254
1255         /* don't try to run the simulation if we don't have a world yet but allow reading baked cache */
1256         if (rbw->physics_world == NULL && !(cache->flag & PTCACHE_BAKED))
1257                 return;
1258         else if (rbw->objects == NULL)
1259                 rigidbody_update_ob_array(rbw);
1260
1261         /* try to read from cache */
1262         // RB_TODO deal with interpolated, old and baked results
1263         if (BKE_ptcache_read(&pid, ctime)) {
1264                 BKE_ptcache_validate(cache, (int)ctime);
1265                 rbw->ltime = ctime;
1266                 return;
1267         }
1268
1269         /* advance simulation, we can only step one frame forward */
1270         if (ctime == rbw->ltime + 1) {
1271                 /* write cache for first frame when on second frame */
1272                 if (rbw->ltime == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact == 0)) {
1273                         BKE_ptcache_write(&pid, startframe);
1274                 }
1275
1276                 /* update and validate simulation */
1277                 rigidbody_update_simulation(scene, rbw, false);
1278
1279                 /* calculate how much time elapsed since last step in seconds */
1280                 timestep = 1.0f / (float)FPS * (ctime - rbw->ltime) * rbw->time_scale;
1281                 /* step simulation by the requested timestep, steps per second are adjusted to take time scale into account */
1282                 RB_dworld_step_simulation(rbw->physics_world, timestep, INT_MAX, 1.0f / (float)rbw->steps_per_second * min_ff(rbw->time_scale, 1.0f));
1283
1284                 rigidbody_update_simulation_post_step(rbw);
1285
1286                 /* write cache for current frame */
1287                 BKE_ptcache_validate(cache, (int)ctime);
1288                 BKE_ptcache_write(&pid, (unsigned int)ctime);
1289
1290                 rbw->ltime = ctime;
1291         }
1292 }
1293 /* ************************************** */
1294
1295 #else  /* WITH_BULLET */
1296
1297 /* stubs */
1298 #ifdef __GNUC__
1299 #  pragma GCC diagnostic push
1300 #  pragma GCC diagnostic ignored "-Wunused-parameter"
1301 #endif
1302
1303 void BKE_rigidbody_free_world(RigidBodyWorld *rbw) {}
1304 void BKE_rigidbody_free_object(Object *ob) {}
1305 void BKE_rigidbody_free_constraint(Object *ob) {}
1306 struct RigidBodyOb *BKE_rigidbody_copy_object(Object *ob) { return NULL; }
1307 struct RigidBodyCon *BKE_rigidbody_copy_constraint(Object *ob) { return NULL; }
1308 void BKE_rigidbody_relink_constraint(RigidBodyCon *rbc) {}
1309 void BKE_rigidbody_validate_sim_shape(Object *ob, short rebuild) {}
1310 void BKE_rigidbody_validate_sim_object(RigidBodyWorld *rbw, Object *ob, short rebuild) {}
1311 void BKE_rigidbody_validate_sim_constraint(RigidBodyWorld *rbw, Object *ob, short rebuild) {}
1312 void BKE_rigidbody_validate_sim_world(Scene *scene, RigidBodyWorld *rbw, short rebuild) {}
1313 struct RigidBodyWorld *BKE_rigidbody_create_world(Scene *scene) { return NULL; }
1314 struct RigidBodyOb *BKE_rigidbody_create_object(Scene *scene, Object *ob, short type) { return NULL; }
1315 struct RigidBodyCon *BKE_rigidbody_create_constraint(Scene *scene, Object *ob, short type) { return NULL; }
1316 struct RigidBodyWorld *BKE_rigidbody_get_world(Scene *scene) { return NULL; }
1317 void BKE_rigidbody_remove_object(Scene *scene, Object *ob) {}
1318 void BKE_rigidbody_remove_constraint(Scene *scene, Object *ob) {}
1319 void BKE_rigidbody_sync_transforms(Scene *scene, Object *ob, float ctime) {}
1320 void BKE_rigidbody_aftertrans_update(Object *ob, float loc[3], float rot[3], float quat[4], float rotAxis[3], float rotAngle) {}
1321 void BKE_rigidbody_cache_reset(RigidBodyWorld *rbw) {}
1322 void BKE_rigidbody_do_simulation(Scene *scene, float ctime) {}
1323
1324 #ifdef __GNUC__
1325 #  pragma GCC diagnostic pop
1326 #endif
1327
1328 #endif  /* WITH_BULLET */