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