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