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