89f22b8e7428440147cd3255f6d4dd8fa80e4719
[blender.git] / source / blender / blenkernel / intern / object.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) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/object.c
29  *  \ingroup bke
30  */
31
32
33 #include <string.h>
34 #include <math.h>
35 #include <stdio.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "DNA_anim_types.h"
40 #include "DNA_armature_types.h"
41 #include "DNA_camera_types.h"
42 #include "DNA_constraint_types.h"
43 #include "DNA_gpencil_types.h"
44 #include "DNA_group_types.h"
45 #include "DNA_key_types.h"
46 #include "DNA_lamp_types.h"
47 #include "DNA_lattice_types.h"
48 #include "DNA_material_types.h"
49 #include "DNA_meta_types.h"
50 #include "DNA_mesh_types.h"
51 #include "DNA_meshdata_types.h"
52 #include "DNA_movieclip_types.h"
53 #include "DNA_scene_types.h"
54 #include "DNA_screen_types.h"
55 #include "DNA_sequence_types.h"
56 #include "DNA_smoke_types.h"
57 #include "DNA_space_types.h"
58 #include "DNA_view3d_types.h"
59 #include "DNA_world_types.h"
60 #include "DNA_object_types.h"
61 #include "DNA_property_types.h"
62 #include "DNA_rigidbody_types.h"
63
64 #include "BLI_blenlib.h"
65 #include "BLI_math.h"
66 #include "BLI_threads.h"
67 #include "BLI_utildefines.h"
68 #include "BLI_linklist.h"
69 #include "BLI_kdtree.h"
70
71 #include "BLT_translation.h"
72
73 #include "BKE_pbvh.h"
74 #include "BKE_main.h"
75 #include "BKE_global.h"
76 #include "BKE_idprop.h"
77 #include "BKE_armature.h"
78 #include "BKE_action.h"
79 #include "BKE_bullet.h"
80 #include "BKE_deform.h"
81 #include "BKE_depsgraph.h"
82 #include "BKE_DerivedMesh.h"
83 #include "BKE_animsys.h"
84 #include "BKE_anim.h"
85 #include "BKE_constraint.h"
86 #include "BKE_curve.h"
87 #include "BKE_displist.h"
88 #include "BKE_effect.h"
89 #include "BKE_fcurve.h"
90 #include "BKE_group.h"
91 #include "BKE_icons.h"
92 #include "BKE_key.h"
93 #include "BKE_lamp.h"
94 #include "BKE_lattice.h"
95 #include "BKE_library.h"
96 #include "BKE_linestyle.h"
97 #include "BKE_mesh.h"
98 #include "BKE_editmesh.h"
99 #include "BKE_mball.h"
100 #include "BKE_modifier.h"
101 #include "BKE_multires.h"
102 #include "BKE_node.h"
103 #include "BKE_object.h"
104 #include "BKE_paint.h"
105 #include "BKE_particle.h"
106 #include "BKE_pointcache.h"
107 #include "BKE_property.h"
108 #include "BKE_rigidbody.h"
109 #include "BKE_sca.h"
110 #include "BKE_scene.h"
111 #include "BKE_sequencer.h"
112 #include "BKE_speaker.h"
113 #include "BKE_softbody.h"
114 #include "BKE_subsurf.h"
115 #include "BKE_material.h"
116 #include "BKE_camera.h"
117 #include "BKE_image.h"
118
119 #ifdef WITH_MOD_FLUID
120 #include "LBM_fluidsim.h"
121 #endif
122
123 #ifdef WITH_PYTHON
124 #include "BPY_extern.h"
125 #endif
126
127 #include "CCGSubSurf.h"
128
129 #include "GPU_material.h"
130
131 /* Vertex parent modifies original BMesh which is not safe for threading.
132  * Ideally such a modification should be handled as a separate DAG update
133  * callback for mesh datablock, but for until it is actually supported use
134  * simpler solution with a mutex lock.
135  *                                               - sergey -
136  */
137 #define VPARENT_THREADING_HACK
138
139 #ifdef VPARENT_THREADING_HACK
140 static ThreadMutex vparent_lock = BLI_MUTEX_INITIALIZER;
141 #endif
142
143 void BKE_object_workob_clear(Object *workob)
144 {
145         memset(workob, 0, sizeof(Object));
146         
147         workob->size[0] = workob->size[1] = workob->size[2] = 1.0f;
148         workob->dscale[0] = workob->dscale[1] = workob->dscale[2] = 1.0f;
149         workob->rotmode = ROT_MODE_EUL;
150 }
151
152 void BKE_object_update_base_layer(struct Scene *scene, Object *ob)
153 {
154         Base *base = scene->base.first;
155
156         while (base) {
157                 if (base->object == ob) base->lay = ob->lay;
158                 base = base->next;
159         }
160 }
161
162 void BKE_object_free_particlesystems(Object *ob)
163 {
164         ParticleSystem *psys;
165
166         while ((psys = BLI_pophead(&ob->particlesystem))) {
167                 psys_free(ob, psys);
168         }
169 }
170
171 void BKE_object_free_softbody(Object *ob)
172 {
173         if (ob->soft) {
174                 sbFree(ob->soft);
175                 ob->soft = NULL;
176         }
177 }
178
179 void BKE_object_free_bulletsoftbody(Object *ob)
180 {
181         if (ob->bsoft) {
182                 bsbFree(ob->bsoft);
183                 ob->bsoft = NULL;
184         }
185 }
186
187 void BKE_object_free_curve_cache(Object *ob)
188 {
189         if (ob->curve_cache) {
190                 BKE_displist_free(&ob->curve_cache->disp);
191                 BKE_curve_bevelList_free(&ob->curve_cache->bev);
192                 if (ob->curve_cache->path) {
193                         free_path(ob->curve_cache->path);
194                 }
195                 BKE_nurbList_free(&ob->curve_cache->deformed_nurbs);
196                 MEM_freeN(ob->curve_cache);
197                 ob->curve_cache = NULL;
198         }
199 }
200
201 void BKE_object_free_modifiers(Object *ob)
202 {
203         ModifierData *md;
204
205         while ((md = BLI_pophead(&ob->modifiers))) {
206                 modifier_free(md);
207         }
208
209         /* particle modifiers were freed, so free the particlesystems as well */
210         BKE_object_free_particlesystems(ob);
211
212         /* same for softbody */
213         BKE_object_free_softbody(ob);
214
215         /* modifiers may have stored data in the DM cache */
216         BKE_object_free_derived_caches(ob);
217 }
218
219 void BKE_object_modifier_hook_reset(Object *ob, HookModifierData *hmd)
220 {
221         /* reset functionality */
222         if (hmd->object) {
223                 bPoseChannel *pchan = BKE_pose_channel_find_name(hmd->object->pose, hmd->subtarget);
224
225                 if (hmd->subtarget[0] && pchan) {
226                         float imat[4][4], mat[4][4];
227
228                         /* calculate the world-space matrix for the pose-channel target first, then carry on as usual */
229                         mul_m4_m4m4(mat, hmd->object->obmat, pchan->pose_mat);
230
231                         invert_m4_m4(imat, mat);
232                         mul_m4_m4m4(hmd->parentinv, imat, ob->obmat);
233                 }
234                 else {
235                         invert_m4_m4(hmd->object->imat, hmd->object->obmat);
236                         mul_m4_m4m4(hmd->parentinv, hmd->object->imat, ob->obmat);
237                 }
238         }
239 }
240
241 bool BKE_object_support_modifier_type_check(Object *ob, int modifier_type)
242 {
243         const ModifierTypeInfo *mti;
244
245         mti = modifierType_getInfo(modifier_type);
246
247         if (!((mti->flags & eModifierTypeFlag_AcceptsCVs) ||
248               (ob->type == OB_MESH && (mti->flags & eModifierTypeFlag_AcceptsMesh))))
249         {
250                 return false;
251         }
252
253         return true;
254 }
255
256 void BKE_object_link_modifiers(struct Object *ob_dst, const struct Object *ob_src)
257 {
258         ModifierData *md;
259         BKE_object_free_modifiers(ob_dst);
260
261         if (!ELEM(ob_dst->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_LATTICE)) {
262                 /* only objects listed above can have modifiers and linking them to objects
263                  * which doesn't have modifiers stack is quite silly */
264                 return;
265         }
266
267         for (md = ob_src->modifiers.first; md; md = md->next) {
268                 ModifierData *nmd = NULL;
269
270                 if (ELEM(md->type,
271                          eModifierType_Hook,
272                          eModifierType_Collision))
273                 {
274                         continue;
275                 }
276
277                 if (!BKE_object_support_modifier_type_check(ob_dst, md->type))
278                         continue;
279
280                 switch (md->type) {
281                         case eModifierType_Softbody:
282                                 BKE_object_copy_softbody(ob_dst, ob_src);
283                                 break;
284                         case eModifierType_Skin:
285                                 /* ensure skin-node customdata exists */
286                                 BKE_mesh_ensure_skin_customdata(ob_dst->data);
287                                 break;
288                 }
289
290                 nmd = modifier_new(md->type);
291                 BLI_strncpy(nmd->name, md->name, sizeof(nmd->name));
292
293                 if (md->type == eModifierType_Multires) {
294                         /* Has to be done after mod creation, but *before* we actually copy its settings! */
295                         multiresModifier_sync_levels_ex(ob_dst, (MultiresModifierData *)md, (MultiresModifierData *)nmd);
296                 }
297
298                 modifier_copyData(md, nmd);
299                 BLI_addtail(&ob_dst->modifiers, nmd);
300                 modifier_unique_name(&ob_dst->modifiers, nmd);
301         }
302
303         BKE_object_copy_particlesystems(ob_dst, ob_src);
304
305         /* TODO: smoke?, cloth? */
306 }
307
308 /* free data derived from mesh, called when mesh changes or is freed */
309 void BKE_object_free_derived_caches(Object *ob)
310 {
311         /* also serves as signal to remake texspace */
312         if (ob->type == OB_MESH) {
313                 Mesh *me = ob->data;
314
315                 if (me->bb) {
316                         me->bb->flag |= BOUNDBOX_DIRTY;
317                 }
318         }
319         else if (ELEM(ob->type, OB_SURF, OB_CURVE, OB_FONT)) {
320                 Curve *cu = ob->data;
321
322                 if (cu->bb) {
323                         cu->bb->flag |= BOUNDBOX_DIRTY;
324                 }
325         }
326
327         if (ob->bb) {
328                 MEM_freeN(ob->bb);
329                 ob->bb = NULL;
330         }
331
332         if (ob->derivedFinal) {
333                 ob->derivedFinal->needsFree = 1;
334                 ob->derivedFinal->release(ob->derivedFinal);
335                 ob->derivedFinal = NULL;
336         }
337         if (ob->derivedDeform) {
338                 ob->derivedDeform->needsFree = 1;
339                 ob->derivedDeform->release(ob->derivedDeform);
340                 ob->derivedDeform = NULL;
341         }
342         
343         BKE_object_free_curve_cache(ob);
344 }
345
346 void BKE_object_free_caches(Object *object)
347 {
348         ModifierData *md;
349         short update_flag = 0;
350
351         /* Free particle system caches holding paths. */
352         if (object->particlesystem.first) {
353                 ParticleSystem *psys;
354                 for (psys = object->particlesystem.first;
355                      psys != NULL;
356                      psys = psys->next)
357                 {
358                         psys_free_path_cache(psys, psys->edit);
359                         update_flag |= PSYS_RECALC_REDO;
360                 }
361         }
362
363         /* Free memory used by cached derived meshes in the particle system modifiers. */
364         for (md = object->modifiers.first; md != NULL; md = md->next) {
365                 if (md->type == eModifierType_ParticleSystem) {
366                         ParticleSystemModifierData *psmd = (ParticleSystemModifierData *) md;
367                         if (psmd->dm != NULL) {
368                                 psmd->dm->needsFree = 1;
369                                 psmd->dm->release(psmd->dm);
370                                 psmd->dm = NULL;
371                                 psmd->flag |= eParticleSystemFlag_file_loaded;
372                                 update_flag |= OB_RECALC_DATA;
373                         }
374                 }
375         }
376
377         /* Tag object for update, so once memory critical operation is over and
378          * scene update routines are back to it's business the object will be
379          * guaranteed to be in a known state.
380          */
381         if (update_flag != 0) {
382                 DAG_id_tag_update(&object->id, update_flag);
383         }
384 }
385
386 /* do not free object itself */
387 void BKE_object_free_ex(Object *ob, bool do_id_user)
388 {
389         int a;
390         
391         BKE_object_free_modifiers(ob);
392         
393         /* disconnect specific data, but not for lib data (might be indirect data, can get relinked) */
394         if (ob->data) {
395                 ID *id = ob->data;
396                 id_us_min(id);
397                 if (id->us == 0 && id->lib == NULL) {
398                         switch (ob->type) {
399                                 case OB_MESH:
400                                         BKE_mesh_unlink((Mesh *)id);
401                                         break;
402                                 case OB_CURVE:
403                                         BKE_curve_unlink((Curve *)id);
404                                         break;
405                                 case OB_MBALL:
406                                         BKE_mball_unlink((MetaBall *)id);
407                                         break;
408                         }
409                 }
410                 ob->data = NULL;
411         }
412
413         if (ob->mat) {
414                 for (a = 0; a < ob->totcol; a++) {
415                         if (ob->mat[a])
416                                 id_us_min(&ob->mat[a]->id);
417                 }
418                 MEM_freeN(ob->mat);
419         }
420         if (ob->matbits) MEM_freeN(ob->matbits);
421         ob->mat = NULL;
422         ob->matbits = NULL;
423         if (ob->iuser) MEM_freeN(ob->iuser);
424         ob->iuser = NULL;
425         if (ob->bb) MEM_freeN(ob->bb); 
426         ob->bb = NULL;
427         if (ob->adt) BKE_animdata_free((ID *)ob);
428         if (ob->poselib)
429                 id_us_min(&ob->poselib->id);
430         if (ob->gpd)
431                 id_us_min(&ob->gpd->id);
432         if (ob->defbase.first)
433                 BLI_freelistN(&ob->defbase);
434         if (ob->pose)
435                 BKE_pose_free_ex(ob->pose, do_id_user);
436         if (ob->mpath)
437                 animviz_free_motionpath(ob->mpath);
438         BKE_bproperty_free_list(&ob->prop);
439         
440         free_sensors(&ob->sensors);
441         free_controllers(&ob->controllers);
442         free_actuators(&ob->actuators);
443         
444         BKE_constraints_free_ex(&ob->constraints, do_id_user);
445         
446         free_partdeflect(ob->pd);
447         BKE_rigidbody_free_object(ob);
448         BKE_rigidbody_free_constraint(ob);
449
450         if (ob->soft) sbFree(ob->soft);
451         if (ob->bsoft) bsbFree(ob->bsoft);
452         if (ob->gpulamp.first) GPU_lamp_free(ob);
453
454         BKE_sculptsession_free(ob);
455
456         if (ob->pc_ids.first) BLI_freelistN(&ob->pc_ids);
457
458         BLI_freelistN(&ob->lodlevels);
459
460         /* Free runtime curves data. */
461         if (ob->curve_cache) {
462                 BKE_curve_bevelList_free(&ob->curve_cache->bev);
463                 if (ob->curve_cache->path)
464                         free_path(ob->curve_cache->path);
465                 MEM_freeN(ob->curve_cache);
466         }
467
468         BKE_previewimg_free(&ob->preview);
469 }
470
471 void BKE_object_free(Object *ob)
472 {
473         BKE_object_free_ex(ob, true);
474 }
475
476 static void unlink_object__unlinkModifierLinks(void *userData, Object *ob, Object **obpoin, int UNUSED(cd_flag))
477 {
478         Object *unlinkOb = userData;
479
480         if (*obpoin == unlinkOb) {
481                 *obpoin = NULL;
482                 // XXX: should this just be OB_RECALC_DATA?
483                 DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
484         }
485 }
486
487 void BKE_object_unlink(Main *bmain, Object *ob)
488 {
489         Object *obt;
490         Material *mat;
491         World *wrld;
492         bScreen *sc;
493         Scene *sce;
494         SceneRenderLayer *srl;
495         FreestyleLineSet *lineset;
496         bNodeTree *ntree;
497         Curve *cu;
498         Tex *tex;
499         Group *group;
500         Camera *camera;
501         bConstraint *con;
502         //bActionStrip *strip; // XXX animsys 
503         ModifierData *md;
504         ARegion *ar;
505         RegionView3D *rv3d;
506         LodLevel *lod;
507         int a, found;
508         
509         unlink_controllers(&ob->controllers);
510         unlink_actuators(&ob->actuators);
511         
512         /* check all objects: parents en bevels and fields, also from libraries */
513         /* FIXME: need to check all animation blocks (drivers) */
514         obt = bmain->object.first;
515         while (obt) {
516                 if (obt->proxy == ob)
517                         obt->proxy = NULL;
518                 if (obt->proxy_from == ob) {
519                         obt->proxy_from = NULL;
520                         DAG_id_tag_update(&obt->id, OB_RECALC_OB);
521                 }
522                 if (obt->proxy_group == ob)
523                         obt->proxy_group = NULL;
524                 
525                 if (obt->parent == ob) {
526                         obt->parent = NULL;
527                         DAG_id_tag_update(&obt->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
528                 }
529                 
530                 modifiers_foreachObjectLink(obt, unlink_object__unlinkModifierLinks, ob);
531                 
532                 if (ELEM(obt->type, OB_CURVE, OB_FONT)) {
533                         cu = obt->data;
534
535                         if (cu->bevobj == ob) {
536                                 cu->bevobj = NULL;
537                                 DAG_id_tag_update(&obt->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
538                         }
539                         if (cu->taperobj == ob) {
540                                 cu->taperobj = NULL;
541                                 DAG_id_tag_update(&obt->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
542                         }
543                         if (cu->textoncurve == ob) {
544                                 cu->textoncurve = NULL;
545                                 DAG_id_tag_update(&obt->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
546                         }
547                 }
548                 else if (obt->type == OB_ARMATURE && obt->pose) {
549                         bPoseChannel *pchan;
550                         for (pchan = obt->pose->chanbase.first; pchan; pchan = pchan->next) {
551                                 for (con = pchan->constraints.first; con; con = con->next) {
552                                         const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
553                                         ListBase targets = {NULL, NULL};
554                                         bConstraintTarget *ct;
555                                         
556                                         if (cti && cti->get_constraint_targets) {
557                                                 cti->get_constraint_targets(con, &targets);
558                                                 
559                                                 for (ct = targets.first; ct; ct = ct->next) {
560                                                         if (ct->tar == ob) {
561                                                                 ct->tar = NULL;
562                                                                 ct->subtarget[0] = '\0';
563                                                                 DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
564                                                         }
565                                                 }
566                                                 
567                                                 if (cti->flush_constraint_targets)
568                                                         cti->flush_constraint_targets(con, &targets, 0);
569                                         }
570                                 }
571                                 if (pchan->custom == ob)
572                                         pchan->custom = NULL;
573                         }
574                 }
575                 else if (ELEM(OB_MBALL, ob->type, obt->type)) {
576                         if (BKE_mball_is_basis_for(obt, ob))
577                                 DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
578                 }
579                 
580                 sca_remove_ob_poin(obt, ob);
581                 
582                 for (con = obt->constraints.first; con; con = con->next) {
583                         const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
584                         ListBase targets = {NULL, NULL};
585                         bConstraintTarget *ct;
586                         
587                         if (cti && cti->get_constraint_targets) {
588                                 cti->get_constraint_targets(con, &targets);
589                                 
590                                 for (ct = targets.first; ct; ct = ct->next) {
591                                         if (ct->tar == ob) {
592                                                 ct->tar = NULL;
593                                                 ct->subtarget[0] = '\0';
594                                                 DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
595                                         }
596                                 }
597                                 
598                                 if (cti->flush_constraint_targets)
599                                         cti->flush_constraint_targets(con, &targets, 0);
600                         }
601                 }
602                 
603                 /* object is deflector or field */
604                 if (ob->pd) {
605                         if (obt->soft)
606                                 DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
607
608                         /* cloth */
609                         for (md = obt->modifiers.first; md; md = md->next)
610                                 if (md->type == eModifierType_Cloth)
611                                         DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
612                 }
613                 
614                 /* strips */
615 #if 0 // XXX old animation system
616                 for (strip = obt->nlastrips.first; strip; strip = strip->next) {
617                         if (strip->object == ob)
618                                 strip->object = NULL;
619                         
620                         if (strip->modifiers.first) {
621                                 bActionModifier *amod;
622                                 for (amod = strip->modifiers.first; amod; amod = amod->next)
623                                         if (amod->ob == ob)
624                                                 amod->ob = NULL;
625                         }
626                 }
627 #endif // XXX old animation system
628
629                 /* particle systems */
630                 if (obt->particlesystem.first) {
631                         ParticleSystem *tpsys = obt->particlesystem.first;
632                         for (; tpsys; tpsys = tpsys->next) {
633                                 BoidState *state = NULL;
634                                 BoidRule *rule = NULL;
635
636                                 ParticleTarget *pt = tpsys->targets.first;
637                                 for (; pt; pt = pt->next) {
638                                         if (pt->ob == ob) {
639                                                 pt->ob = NULL;
640                                                 DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
641                                                 break;
642                                         }
643                                 }
644
645                                 if (tpsys->target_ob == ob) {
646                                         tpsys->target_ob = NULL;
647                                         DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
648                                 }
649
650                                 if (tpsys->part->dup_ob == ob)
651                                         tpsys->part->dup_ob = NULL;
652
653                                 if (tpsys->part->phystype == PART_PHYS_BOIDS) {
654                                         ParticleData *pa;
655                                         BoidParticle *bpa;
656                                         int p;
657
658                                         for (p = 0, pa = tpsys->particles; p < tpsys->totpart; p++, pa++) {
659                                                 bpa = pa->boid;
660                                                 if (bpa->ground == ob)
661                                                         bpa->ground = NULL;
662                                         }
663                                 }
664                                 if (tpsys->part->boids) {
665                                         for (state = tpsys->part->boids->states.first; state; state = state->next) {
666                                                 for (rule = state->rules.first; rule; rule = rule->next) {
667                                                         if (rule->type == eBoidRuleType_Avoid) {
668                                                                 BoidRuleGoalAvoid *gabr = (BoidRuleGoalAvoid *)rule;
669                                                                 if (gabr->ob == ob)
670                                                                         gabr->ob = NULL;
671                                                         }
672                                                         else if (rule->type == eBoidRuleType_FollowLeader) {
673                                                                 BoidRuleFollowLeader *flbr = (BoidRuleFollowLeader *)rule;
674                                                                 if (flbr->ob == ob)
675                                                                         flbr->ob = NULL;
676                                                         }
677                                                 }
678                                         }
679                                 }
680                                 
681                                 if (tpsys->parent == ob)
682                                         tpsys->parent = NULL;
683                         }
684                         if (ob->pd)
685                                 DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
686                 }
687
688                 /* levels of detail */
689                 for (lod = obt->lodlevels.first; lod; lod = lod->next) {
690                         if (lod->source == ob)
691                                 lod->source = NULL;
692                 }
693
694                 obt = obt->id.next;
695         }
696         
697         /* materials */
698         for (mat = bmain->mat.first; mat; mat = mat->id.next) {
699                 if (mat->nodetree) {
700                         ntreeSwitchID(mat->nodetree, &ob->id, NULL);
701                 }
702                 for (a = 0; a < MAX_MTEX; a++) {
703                         if (mat->mtex[a] && ob == mat->mtex[a]->object) {
704                                 /* actually, test for lib here... to do */
705                                 mat->mtex[a]->object = NULL;
706                         }
707                 }
708         }
709
710         /* node trees */
711         for (ntree = bmain->nodetree.first; ntree; ntree = ntree->id.next) {
712                 if (ntree->type == NTREE_SHADER)
713                         ntreeSwitchID(ntree, &ob->id, NULL);
714         }
715         
716         /* textures */
717         for (tex = bmain->tex.first; tex; tex = tex->id.next) {
718                 if (tex->env && (ob == tex->env->object)) tex->env->object = NULL;
719                 if (tex->pd  && (ob == tex->pd->object)) tex->pd->object = NULL;
720                 if (tex->vd  && (ob == tex->vd->object)) tex->vd->object = NULL;
721         }
722
723         /* worlds */
724         wrld = bmain->world.first;
725         while (wrld) {
726                 if (wrld->id.lib == NULL) {
727                         for (a = 0; a < MAX_MTEX; a++) {
728                                 if (wrld->mtex[a] && ob == wrld->mtex[a]->object)
729                                         wrld->mtex[a]->object = NULL;
730                         }
731                 }
732                 
733                 wrld = wrld->id.next;
734         }
735                 
736         /* scenes */
737         sce = bmain->scene.first;
738         while (sce) {
739                 if (sce->id.lib == NULL) {
740                         if (sce->camera == ob) sce->camera = NULL;
741                         if (sce->toolsettings->skgen_template == ob) sce->toolsettings->skgen_template = NULL;
742                         if (sce->toolsettings->particle.object == ob) sce->toolsettings->particle.object = NULL;
743                         if (sce->toolsettings->particle.shape_object == ob) sce->toolsettings->particle.shape_object = NULL;
744
745 #ifdef DURIAN_CAMERA_SWITCH
746                         {
747                                 TimeMarker *m;
748
749                                 for (m = sce->markers.first; m; m = m->next) {
750                                         if (m->camera == ob)
751                                                 m->camera = NULL;
752                                 }
753                         }
754 #endif
755                         if (sce->ed) {
756                                 Sequence *seq;
757                                 SEQ_BEGIN(sce->ed, seq)
758                                 {
759                                         if (seq->scene_camera == ob) {
760                                                 seq->scene_camera = NULL;
761                                         }
762                                 }
763                                 SEQ_END
764                         }
765
766                         for (srl = sce->r.layers.first; srl; srl = srl->next) {
767                                 for (lineset = (FreestyleLineSet *)srl->freestyleConfig.linesets.first;
768                                      lineset; lineset = lineset->next)
769                                 {
770                                         if (lineset->linestyle) {
771                                                 BKE_linestyle_target_object_unlink(lineset->linestyle, ob);
772                                         }
773                                 }
774                         }
775                 }
776
777                 sce = sce->id.next;
778         }
779         
780         /* screens */
781         sc = bmain->screen.first;
782         while (sc) {
783                 ScrArea *sa = sc->areabase.first;
784                 while (sa) {
785                         SpaceLink *sl;
786
787                         for (sl = sa->spacedata.first; sl; sl = sl->next) {
788                                 if (sl->spacetype == SPACE_VIEW3D) {
789                                         View3D *v3d = (View3D *) sl;
790
791                                         /* found doesn't need to be set here */
792                                         if (v3d->ob_centre == ob) {
793                                                 v3d->ob_centre = NULL;
794                                                 v3d->ob_centre_bone[0] = '\0';
795                                         }
796                                         if (v3d->localvd && v3d->localvd->ob_centre == ob) {
797                                                 v3d->localvd->ob_centre = NULL;
798                                                 v3d->localvd->ob_centre_bone[0] = '\0';
799                                         }
800
801                                         found = 0;
802                                         if (v3d->camera == ob) {
803                                                 v3d->camera = NULL;
804                                                 found = 1;
805                                         }
806                                         if (v3d->localvd && v3d->localvd->camera == ob) {
807                                                 v3d->localvd->camera = NULL;
808                                                 found += 2;
809                                         }
810
811                                         if (found) {
812                                                 if (sa->spacetype == SPACE_VIEW3D) {
813                                                         for (ar = sa->regionbase.first; ar; ar = ar->next) {
814                                                                 if (ar->regiontype == RGN_TYPE_WINDOW) {
815                                                                         rv3d = (RegionView3D *)ar->regiondata;
816                                                                         if (found == 1 || found == 3) {
817                                                                                 if (rv3d->persp == RV3D_CAMOB)
818                                                                                         rv3d->persp = RV3D_PERSP;
819                                                                         }
820                                                                         if (found == 2 || found == 3) {
821                                                                                 if (rv3d->localvd && rv3d->localvd->persp == RV3D_CAMOB)
822                                                                                         rv3d->localvd->persp = RV3D_PERSP;
823                                                                         }
824                                                                 }
825                                                         }
826                                                 }
827                                         }
828                                 }
829 #if 0
830                                 else if (ELEM(sl->spacetype, SPACE_OUTLINER, SPACE_BUTS, SPACE_NODE)) {
831                                         /* now handled by WM_main_remove_editor_id_reference */
832                                 }
833 #endif
834                         }
835
836                         sa = sa->next;
837                 }
838                 sc = sc->id.next;
839         }
840
841         /* groups */
842         group = bmain->group.first;
843         while (group) {
844                 BKE_group_object_unlink(group, ob, NULL, NULL);
845                 group = group->id.next;
846         }
847         
848         /* cameras */
849         camera = bmain->camera.first;
850         while (camera) {
851                 if (camera->dof_ob == ob) {
852                         camera->dof_ob = NULL;
853                 }
854                 camera = camera->id.next;
855         }
856 }
857
858 /* actual check for internal data, not context or flags */
859 bool BKE_object_is_in_editmode(Object *ob)
860 {
861         if (ob->data == NULL)
862                 return false;
863         
864         if (ob->type == OB_MESH) {
865                 Mesh *me = ob->data;
866                 if (me->edit_btmesh)
867                         return true;
868         }
869         else if (ob->type == OB_ARMATURE) {
870                 bArmature *arm = ob->data;
871                 
872                 if (arm->edbo)
873                         return true;
874         }
875         else if (ob->type == OB_FONT) {
876                 Curve *cu = ob->data;
877                 
878                 if (cu->editfont)
879                         return true;
880         }
881         else if (ob->type == OB_MBALL) {
882                 MetaBall *mb = ob->data;
883                 
884                 if (mb->editelems)
885                         return true;
886         }
887         else if (ob->type == OB_LATTICE) {
888                 Lattice *lt = ob->data;
889                 
890                 if (lt->editlatt)
891                         return true;
892         }
893         else if (ob->type == OB_SURF || ob->type == OB_CURVE) {
894                 Curve *cu = ob->data;
895
896                 if (cu->editnurb)
897                         return true;
898         }
899         return false;
900 }
901
902 bool BKE_object_is_in_editmode_vgroup(Object *ob)
903 {
904         return (OB_TYPE_SUPPORT_VGROUP(ob->type) &&
905                 BKE_object_is_in_editmode(ob));
906 }
907
908 bool BKE_object_is_in_wpaint_select_vert(Object *ob)
909 {
910         if (ob->type == OB_MESH) {
911                 Mesh *me = ob->data;
912                 return ((ob->mode & OB_MODE_WEIGHT_PAINT) &&
913                         (me->edit_btmesh == NULL) &&
914                         (ME_EDIT_PAINT_SEL_MODE(me) == SCE_SELECT_VERTEX));
915         }
916
917         return false;
918 }
919
920 bool BKE_object_exists_check(Object *obtest)
921 {
922         Object *ob;
923         
924         if (obtest == NULL) return false;
925         
926         ob = G.main->object.first;
927         while (ob) {
928                 if (ob == obtest) return true;
929                 ob = ob->id.next;
930         }
931         return false;
932 }
933
934 /* *************************************************** */
935
936 static const char *get_obdata_defname(int type)
937 {
938         switch (type) {
939                 case OB_MESH: return DATA_("Mesh");
940                 case OB_CURVE: return DATA_("Curve");
941                 case OB_SURF: return DATA_("Surf");
942                 case OB_FONT: return DATA_("Text");
943                 case OB_MBALL: return DATA_("Mball");
944                 case OB_CAMERA: return DATA_("Camera");
945                 case OB_LAMP: return DATA_("Lamp");
946                 case OB_LATTICE: return DATA_("Lattice");
947                 case OB_ARMATURE: return DATA_("Armature");
948                 case OB_SPEAKER: return DATA_("Speaker");
949                 case OB_EMPTY: return DATA_("Empty");
950                 default:
951                         printf("get_obdata_defname: Internal error, bad type: %d\n", type);
952                         return DATA_("Empty");
953         }
954 }
955
956 void *BKE_object_obdata_add_from_type(Main *bmain, int type, const char *name)
957 {
958         if (name == NULL) {
959                 name = get_obdata_defname(type);
960         }
961
962         switch (type) {
963                 case OB_MESH:      return BKE_mesh_add(bmain, name);
964                 case OB_CURVE:     return BKE_curve_add(bmain, name, OB_CURVE);
965                 case OB_SURF:      return BKE_curve_add(bmain, name, OB_SURF);
966                 case OB_FONT:      return BKE_curve_add(bmain, name, OB_FONT);
967                 case OB_MBALL:     return BKE_mball_add(bmain, name);
968                 case OB_CAMERA:    return BKE_camera_add(bmain, name);
969                 case OB_LAMP:      return BKE_lamp_add(bmain, name);
970                 case OB_LATTICE:   return BKE_lattice_add(bmain, name);
971                 case OB_ARMATURE:  return BKE_armature_add(bmain, name);
972                 case OB_SPEAKER:   return BKE_speaker_add(bmain, name);
973                 case OB_EMPTY:     return NULL;
974                 default:
975                         printf("%s: Internal error, bad type: %d\n", __func__, type);
976                         return NULL;
977         }
978 }
979
980 void BKE_object_init(Object *ob)
981 {
982         /* BLI_assert(MEMCMP_STRUCT_OFS_IS_ZERO(ob, id)); */  /* ob->type is already initialized... */
983
984         ob->col[0] = ob->col[1] = ob->col[2] = 1.0;
985         ob->col[3] = 1.0;
986         
987         ob->size[0] = ob->size[1] = ob->size[2] = 1.0;
988         ob->dscale[0] = ob->dscale[1] = ob->dscale[2] = 1.0;
989         
990         /* objects should default to having Euler XYZ rotations, 
991          * but rotations default to quaternions 
992          */
993         ob->rotmode = ROT_MODE_EUL;
994
995         unit_axis_angle(ob->rotAxis, &ob->rotAngle);
996         unit_axis_angle(ob->drotAxis, &ob->drotAngle);
997
998         unit_qt(ob->quat);
999         unit_qt(ob->dquat);
1000
1001         /* rotation locks should be 4D for 4 component rotations by default... */
1002         ob->protectflag = OB_LOCK_ROT4D;
1003         
1004         unit_m4(ob->constinv);
1005         unit_m4(ob->parentinv);
1006         unit_m4(ob->obmat);
1007         ob->dt = OB_TEXTURE;
1008         ob->empty_drawtype = OB_PLAINAXES;
1009         ob->empty_drawsize = 1.0;
1010
1011         if (ELEM(ob->type, OB_LAMP, OB_CAMERA, OB_SPEAKER)) {
1012                 ob->trackflag = OB_NEGZ;
1013                 ob->upflag = OB_POSY;
1014         }
1015         else {
1016                 ob->trackflag = OB_POSY;
1017                 ob->upflag = OB_POSZ;
1018         }
1019         
1020         ob->dupon = 1; ob->dupoff = 0;
1021         ob->dupsta = 1; ob->dupend = 100;
1022         ob->dupfacesca = 1.0;
1023
1024         /* Game engine defaults*/
1025         ob->mass = ob->inertia = 1.0f;
1026         ob->formfactor = 0.4f;
1027         ob->damping = 0.04f;
1028         ob->rdamping = 0.1f;
1029         ob->anisotropicFriction[0] = 1.0f;
1030         ob->anisotropicFriction[1] = 1.0f;
1031         ob->anisotropicFriction[2] = 1.0f;
1032         ob->gameflag = OB_PROP | OB_COLLISION;
1033         ob->margin = 0.04f;
1034         ob->init_state = 1;
1035         ob->state = 1;
1036         ob->obstacleRad = 1.0f;
1037         ob->step_height = 0.15f;
1038         ob->jump_speed = 10.0f;
1039         ob->fall_speed = 55.0f;
1040         ob->max_jumps = 1;
1041         ob->col_group = 0x01;
1042         ob->col_mask = 0xffff;
1043         ob->preview = NULL;
1044
1045         /* NT fluid sim defaults */
1046         ob->fluidsimSettings = NULL;
1047
1048         BLI_listbase_clear(&ob->pc_ids);
1049         
1050         /* Animation Visualization defaults */
1051         animviz_settings_init(&ob->avs);
1052 }
1053
1054 /* more general add: creates minimum required data, but without vertices etc. */
1055 Object *BKE_object_add_only_object(Main *bmain, int type, const char *name)
1056 {
1057         Object *ob;
1058
1059         if (!name)
1060                 name = get_obdata_defname(type);
1061
1062         ob = BKE_libblock_alloc(bmain, ID_OB, name);
1063
1064         /* default object vars */
1065         ob->type = type;
1066
1067         BKE_object_init(ob);
1068
1069         return ob;
1070 }
1071
1072 /* general add: to scene, with layer from area and default name */
1073 /* creates minimum required data, but without vertices etc. */
1074 Object *BKE_object_add(
1075         Main *bmain, Scene *scene,
1076         int type, const char *name)
1077 {
1078         Object *ob;
1079         Base *base;
1080
1081         ob = BKE_object_add_only_object(bmain, type, name);
1082
1083         ob->data = BKE_object_obdata_add_from_type(bmain, type, name);
1084
1085         ob->lay = scene->lay;
1086         
1087         base = BKE_scene_base_add(scene, ob);
1088         BKE_scene_base_deselect_all(scene);
1089         BKE_scene_base_select(scene, base);
1090         DAG_id_tag_update_ex(bmain, &ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1091
1092         return ob;
1093 }
1094
1095
1096 #ifdef WITH_GAMEENGINE
1097
1098 void BKE_object_lod_add(Object *ob)
1099 {
1100         LodLevel *lod = MEM_callocN(sizeof(LodLevel), "LoD Level");
1101         LodLevel *last = ob->lodlevels.last;
1102
1103         /* If the lod list is empty, initialize it with the base lod level */
1104         if (!last) {
1105                 LodLevel *base = MEM_callocN(sizeof(LodLevel), "Base LoD Level");
1106                 BLI_addtail(&ob->lodlevels, base);
1107                 base->flags = OB_LOD_USE_MESH | OB_LOD_USE_MAT;
1108                 base->source = ob;
1109                 base->obhysteresis = 10;
1110                 last = ob->currentlod = base;
1111         }
1112         
1113         lod->distance = last->distance + 25.0f;
1114         lod->obhysteresis = 10;
1115         lod->flags = OB_LOD_USE_MESH | OB_LOD_USE_MAT;
1116
1117         BLI_addtail(&ob->lodlevels, lod);
1118 }
1119
1120 static int lod_cmp(const void *a, const void *b)
1121 {
1122         const LodLevel *loda = a;
1123         const LodLevel *lodb = b;
1124
1125         if (loda->distance < lodb->distance) return -1;
1126         return loda->distance > lodb->distance;
1127 }
1128
1129 void BKE_object_lod_sort(Object *ob)
1130 {
1131         BLI_listbase_sort(&ob->lodlevels, lod_cmp);
1132 }
1133
1134 bool BKE_object_lod_remove(Object *ob, int level)
1135 {
1136         LodLevel *rem;
1137
1138         if (level < 1 || level > BLI_listbase_count(&ob->lodlevels) - 1)
1139                 return false;
1140
1141         rem = BLI_findlink(&ob->lodlevels, level);
1142
1143         if (rem == ob->currentlod) {
1144                 ob->currentlod = rem->prev;
1145         }
1146
1147         BLI_remlink(&ob->lodlevels, rem);
1148         MEM_freeN(rem);
1149
1150         /* If there are no user defined lods, remove the base lod as well */
1151         if (BLI_listbase_is_single(&ob->lodlevels)) {
1152                 LodLevel *base = ob->lodlevels.first;
1153                 BLI_remlink(&ob->lodlevels, base);
1154                 MEM_freeN(base);
1155                 ob->currentlod = NULL;
1156         }
1157
1158         return true;
1159 }
1160
1161 static LodLevel *lod_level_select(Object *ob, const float camera_position[3])
1162 {
1163         LodLevel *current = ob->currentlod;
1164         float dist_sq;
1165
1166         if (!current) return NULL;
1167
1168         dist_sq = len_squared_v3v3(ob->obmat[3], camera_position);
1169
1170         if (dist_sq < SQUARE(current->distance)) {
1171                 /* check for higher LoD */
1172                 while (current->prev && dist_sq < SQUARE(current->distance)) {
1173                         current = current->prev;
1174                 }
1175         }
1176         else {
1177                 /* check for lower LoD */
1178                 while (current->next && dist_sq > SQUARE(current->next->distance)) {
1179                         current = current->next;
1180                 }
1181         }
1182
1183         return current;
1184 }
1185
1186 bool BKE_object_lod_is_usable(Object *ob, Scene *scene)
1187 {
1188         bool active = (scene) ? ob == OBACT : false;
1189         return (ob->mode == OB_MODE_OBJECT || !active);
1190 }
1191
1192 void BKE_object_lod_update(Object *ob, const float camera_position[3])
1193 {
1194         LodLevel *cur_level = ob->currentlod;
1195         LodLevel *new_level = lod_level_select(ob, camera_position);
1196
1197         if (new_level != cur_level) {
1198                 ob->currentlod = new_level;
1199         }
1200 }
1201
1202 static Object *lod_ob_get(Object *ob, Scene *scene, int flag)
1203 {
1204         LodLevel *current = ob->currentlod;
1205
1206         if (!current || !BKE_object_lod_is_usable(ob, scene))
1207                 return ob;
1208
1209         while (current->prev && (!(current->flags & flag) || !current->source || current->source->type != OB_MESH)) {
1210                 current = current->prev;
1211         }
1212
1213         return current->source;
1214 }
1215
1216 struct Object *BKE_object_lod_meshob_get(Object *ob, Scene *scene)
1217 {
1218         return lod_ob_get(ob, scene, OB_LOD_USE_MESH);
1219 }
1220
1221 struct Object *BKE_object_lod_matob_get(Object *ob, Scene *scene)
1222 {
1223         return lod_ob_get(ob, scene, OB_LOD_USE_MAT);
1224 }
1225
1226 #endif  /* WITH_GAMEENGINE */
1227
1228
1229 SoftBody *copy_softbody(const SoftBody *sb, bool copy_caches)
1230 {
1231         SoftBody *sbn;
1232         
1233         if (sb == NULL) return(NULL);
1234         
1235         sbn = MEM_dupallocN(sb);
1236
1237         if (copy_caches == false) {
1238                 sbn->totspring = sbn->totpoint = 0;
1239                 sbn->bpoint = NULL;
1240                 sbn->bspring = NULL;
1241         }
1242         else {
1243                 sbn->totspring = sb->totspring;
1244                 sbn->totpoint = sb->totpoint;
1245
1246                 if (sbn->bpoint) {
1247                         int i;
1248
1249                         sbn->bpoint = MEM_dupallocN(sbn->bpoint);
1250
1251                         for (i = 0; i < sbn->totpoint; i++) {
1252                                 if (sbn->bpoint[i].springs)
1253                                         sbn->bpoint[i].springs = MEM_dupallocN(sbn->bpoint[i].springs);
1254                         }
1255                 }
1256
1257                 if (sb->bspring)
1258                         sbn->bspring = MEM_dupallocN(sb->bspring);
1259         }
1260         
1261         sbn->keys = NULL;
1262         sbn->totkey = sbn->totpointkey = 0;
1263         
1264         sbn->scratch = NULL;
1265
1266         sbn->pointcache = BKE_ptcache_copy_list(&sbn->ptcaches, &sb->ptcaches, copy_caches);
1267
1268         if (sb->effector_weights)
1269                 sbn->effector_weights = MEM_dupallocN(sb->effector_weights);
1270
1271         return sbn;
1272 }
1273
1274 BulletSoftBody *copy_bulletsoftbody(BulletSoftBody *bsb)
1275 {
1276         BulletSoftBody *bsbn;
1277
1278         if (bsb == NULL)
1279                 return NULL;
1280         bsbn = MEM_dupallocN(bsb);
1281         /* no pointer in this structure yet */
1282         return bsbn;
1283 }
1284
1285 ParticleSystem *BKE_object_copy_particlesystem(ParticleSystem *psys)
1286 {
1287         ParticleSystem *psysn;
1288         ParticleData *pa;
1289         int p;
1290
1291         psysn = MEM_dupallocN(psys);
1292         psysn->particles = MEM_dupallocN(psys->particles);
1293         psysn->child = MEM_dupallocN(psys->child);
1294
1295         if (psys->part->type == PART_HAIR) {
1296                 for (p = 0, pa = psysn->particles; p < psysn->totpart; p++, pa++)
1297                         pa->hair = MEM_dupallocN(pa->hair);
1298         }
1299
1300         if (psysn->particles && (psysn->particles->keys || psysn->particles->boid)) {
1301                 ParticleKey *key = psysn->particles->keys;
1302                 BoidParticle *boid = psysn->particles->boid;
1303
1304                 if (key)
1305                         key = MEM_dupallocN(key);
1306                 
1307                 if (boid)
1308                         boid = MEM_dupallocN(boid);
1309                 
1310                 for (p = 0, pa = psysn->particles; p < psysn->totpart; p++, pa++) {
1311                         if (boid)
1312                                 pa->boid = boid++;
1313                         if (key) {
1314                                 pa->keys = key;
1315                                 key += pa->totkey;
1316                         }
1317                 }
1318         }
1319
1320         if (psys->clmd) {
1321                 psysn->clmd = (ClothModifierData *)modifier_new(eModifierType_Cloth);
1322                 modifier_copyData((ModifierData *)psys->clmd, (ModifierData *)psysn->clmd);
1323                 psys->hair_in_dm = psys->hair_out_dm = NULL;
1324         }
1325
1326         BLI_duplicatelist(&psysn->targets, &psys->targets);
1327
1328         psysn->pathcache = NULL;
1329         psysn->childcache = NULL;
1330         psysn->edit = NULL;
1331         psysn->pdd = NULL;
1332         psysn->effectors = NULL;
1333         psysn->tree = NULL;
1334         psysn->bvhtree = NULL;
1335         
1336         BLI_listbase_clear(&psysn->pathcachebufs);
1337         BLI_listbase_clear(&psysn->childcachebufs);
1338         psysn->renderdata = NULL;
1339         
1340         psysn->pointcache = BKE_ptcache_copy_list(&psysn->ptcaches, &psys->ptcaches, false);
1341
1342         /* XXX - from reading existing code this seems correct but intended usage of
1343          * pointcache should /w cloth should be added in 'ParticleSystem' - campbell */
1344         if (psysn->clmd) {
1345                 psysn->clmd->point_cache = psysn->pointcache;
1346         }
1347
1348         id_us_plus((ID *)psysn->part);
1349
1350         return psysn;
1351 }
1352
1353 void BKE_object_copy_particlesystems(Object *ob_dst, const Object *ob_src)
1354 {
1355         ParticleSystem *psys, *npsys;
1356         ModifierData *md;
1357
1358         if (ob_dst->type != OB_MESH) {
1359                 /* currently only mesh objects can have soft body */
1360                 return;
1361         }
1362
1363         BLI_listbase_clear(&ob_dst->particlesystem);
1364         for (psys = ob_src->particlesystem.first; psys; psys = psys->next) {
1365                 npsys = BKE_object_copy_particlesystem(psys);
1366
1367                 BLI_addtail(&ob_dst->particlesystem, npsys);
1368
1369                 /* need to update particle modifiers too */
1370                 for (md = ob_dst->modifiers.first; md; md = md->next) {
1371                         if (md->type == eModifierType_ParticleSystem) {
1372                                 ParticleSystemModifierData *psmd = (ParticleSystemModifierData *)md;
1373                                 if (psmd->psys == psys)
1374                                         psmd->psys = npsys;
1375                         }
1376                         else if (md->type == eModifierType_DynamicPaint) {
1377                                 DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)md;
1378                                 if (pmd->brush) {
1379                                         if (pmd->brush->psys == psys) {
1380                                                 pmd->brush->psys = npsys;
1381                                         }
1382                                 }
1383                         }
1384                         else if (md->type == eModifierType_Smoke) {
1385                                 SmokeModifierData *smd = (SmokeModifierData *) md;
1386                                 
1387                                 if (smd->type == MOD_SMOKE_TYPE_FLOW) {
1388                                         if (smd->flow) {
1389                                                 if (smd->flow->psys == psys)
1390                                                         smd->flow->psys = npsys;
1391                                         }
1392                                 }
1393                         }
1394                 }
1395         }
1396 }
1397
1398 void BKE_object_copy_softbody(Object *ob_dst, const Object *ob_src)
1399 {
1400         if (ob_src->soft) {
1401                 ob_dst->softflag = ob_src->softflag;
1402                 ob_dst->soft = copy_softbody(ob_src->soft, false);
1403         }
1404 }
1405
1406 static void copy_object_pose(Object *obn, Object *ob)
1407 {
1408         bPoseChannel *chan;
1409         
1410         /* note: need to clear obn->pose pointer first, so that BKE_pose_copy_data works (otherwise there's a crash) */
1411         obn->pose = NULL;
1412         BKE_pose_copy_data(&obn->pose, ob->pose, 1);    /* 1 = copy constraints */
1413
1414         for (chan = obn->pose->chanbase.first; chan; chan = chan->next) {
1415                 bConstraint *con;
1416                 
1417                 chan->flag &= ~(POSE_LOC | POSE_ROT | POSE_SIZE);
1418                 
1419                 for (con = chan->constraints.first; con; con = con->next) {
1420                         const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
1421                         ListBase targets = {NULL, NULL};
1422                         bConstraintTarget *ct;
1423                         
1424                         if (cti && cti->get_constraint_targets) {
1425                                 cti->get_constraint_targets(con, &targets);
1426                                 
1427                                 for (ct = targets.first; ct; ct = ct->next) {
1428                                         if (ct->tar == ob)
1429                                                 ct->tar = obn;
1430                                 }
1431                                 
1432                                 if (cti->flush_constraint_targets)
1433                                         cti->flush_constraint_targets(con, &targets, 0);
1434                         }
1435                 }
1436         }
1437 }
1438
1439 static void copy_object_lod(Object *obn, Object *ob)
1440 {
1441         BLI_duplicatelist(&obn->lodlevels, &ob->lodlevels);
1442
1443         if (obn->lodlevels.first)
1444                 ((LodLevel *)obn->lodlevels.first)->source = obn;
1445
1446         obn->currentlod = (LodLevel *)obn->lodlevels.first;
1447 }
1448
1449 bool BKE_object_pose_context_check(Object *ob)
1450 {
1451         if ((ob) &&
1452             (ob->type == OB_ARMATURE) &&
1453             (ob->pose) &&
1454             (ob->mode & OB_MODE_POSE))
1455         {
1456                 return true;
1457         }
1458         else {
1459                 return false;
1460         }
1461 }
1462
1463 Object *BKE_object_pose_armature_get(Object *ob)
1464 {
1465         if (ob == NULL)
1466                 return NULL;
1467
1468         if (BKE_object_pose_context_check(ob))
1469                 return ob;
1470
1471         ob = modifiers_isDeformedByArmature(ob);
1472
1473         if (BKE_object_pose_context_check(ob))
1474                 return ob;
1475
1476         return NULL;
1477 }
1478
1479 void BKE_object_transform_copy(Object *ob_tar, const Object *ob_src)
1480 {
1481         copy_v3_v3(ob_tar->loc, ob_src->loc);
1482         copy_v3_v3(ob_tar->rot, ob_src->rot);
1483         copy_v3_v3(ob_tar->quat, ob_src->quat);
1484         copy_v3_v3(ob_tar->rotAxis, ob_src->rotAxis);
1485         ob_tar->rotAngle = ob_src->rotAngle;
1486         ob_tar->rotmode = ob_src->rotmode;
1487         copy_v3_v3(ob_tar->size, ob_src->size);
1488 }
1489
1490 Object *BKE_object_copy_ex(Main *bmain, Object *ob, bool copy_caches)
1491 {
1492         Object *obn;
1493         ModifierData *md;
1494         int a;
1495
1496         obn = BKE_libblock_copy_ex(bmain, &ob->id);
1497         
1498         if (ob->totcol) {
1499                 obn->mat = MEM_dupallocN(ob->mat);
1500                 obn->matbits = MEM_dupallocN(ob->matbits);
1501                 obn->totcol = ob->totcol;
1502         }
1503
1504         if (ob->iuser) obn->iuser = MEM_dupallocN(ob->iuser);
1505         
1506         if (ob->bb) obn->bb = MEM_dupallocN(ob->bb);
1507         obn->flag &= ~OB_FROMGROUP;
1508         
1509         BLI_listbase_clear(&obn->modifiers);
1510         
1511         for (md = ob->modifiers.first; md; md = md->next) {
1512                 ModifierData *nmd = modifier_new(md->type);
1513                 BLI_strncpy(nmd->name, md->name, sizeof(nmd->name));
1514                 modifier_copyData(md, nmd);
1515                 BLI_addtail(&obn->modifiers, nmd);
1516         }
1517
1518         BLI_listbase_clear(&obn->prop);
1519         BKE_bproperty_copy_list(&obn->prop, &ob->prop);
1520         
1521         copy_sensors(&obn->sensors, &ob->sensors);
1522         copy_controllers(&obn->controllers, &ob->controllers);
1523         copy_actuators(&obn->actuators, &ob->actuators);
1524         
1525         if (ob->pose) {
1526                 copy_object_pose(obn, ob);
1527                 /* backwards compat... non-armatures can get poses in older files? */
1528                 if (ob->type == OB_ARMATURE)
1529                         BKE_pose_rebuild(obn, obn->data);
1530         }
1531         defgroup_copy_list(&obn->defbase, &ob->defbase);
1532         BKE_constraints_copy(&obn->constraints, &ob->constraints, true);
1533
1534         obn->mode = OB_MODE_OBJECT;
1535         obn->sculpt = NULL;
1536
1537         /* increase user numbers */
1538         id_us_plus((ID *)obn->data);
1539         id_us_plus((ID *)obn->gpd);
1540         id_lib_extern((ID *)obn->dup_group);
1541
1542         for (a = 0; a < obn->totcol; a++) id_us_plus((ID *)obn->mat[a]);
1543         
1544         if (ob->pd) {
1545                 obn->pd = MEM_dupallocN(ob->pd);
1546                 if (obn->pd->tex)
1547                         id_us_plus(&(obn->pd->tex->id));
1548                 if (obn->pd->rng)
1549                         obn->pd->rng = MEM_dupallocN(ob->pd->rng);
1550         }
1551         obn->soft = copy_softbody(ob->soft, copy_caches);
1552         obn->bsoft = copy_bulletsoftbody(ob->bsoft);
1553         obn->rigidbody_object = BKE_rigidbody_copy_object(ob);
1554         obn->rigidbody_constraint = BKE_rigidbody_copy_constraint(ob);
1555
1556         BKE_object_copy_particlesystems(obn, ob);
1557         
1558         obn->derivedDeform = NULL;
1559         obn->derivedFinal = NULL;
1560
1561         BLI_listbase_clear(&obn->gpulamp);
1562         BLI_listbase_clear(&obn->pc_ids);
1563
1564         obn->mpath = NULL;
1565
1566         copy_object_lod(obn, ob);
1567         
1568
1569         /* Copy runtime surve data. */
1570         obn->curve_cache = NULL;
1571
1572         if (ob->id.lib) {
1573                 BKE_id_lib_local_paths(bmain, ob->id.lib, &obn->id);
1574         }
1575
1576         /* Do not copy object's preview (mostly due to the fact renderers create temp copy of objects). */
1577         obn->preview = NULL;
1578
1579         return obn;
1580 }
1581
1582 /* copy objects, will re-initialize cached simulation data */
1583 Object *BKE_object_copy(Object *ob)
1584 {
1585         return BKE_object_copy_ex(G.main, ob, false);
1586 }
1587
1588 static void extern_local_object__modifiersForeachIDLink(
1589         void *UNUSED(userData), Object *UNUSED(ob), ID **idpoin, int UNUSED(cd_flag))
1590 {
1591         if (*idpoin) {
1592                 /* intentionally omit ID_OB */
1593                 if (ELEM(GS((*idpoin)->name), ID_IM, ID_TE)) {
1594                         id_lib_extern(*idpoin);
1595                 }
1596         }
1597 }
1598
1599 static void extern_local_object(Object *ob)
1600 {
1601         ParticleSystem *psys;
1602
1603         id_lib_extern((ID *)ob->data);
1604         id_lib_extern((ID *)ob->dup_group);
1605         id_lib_extern((ID *)ob->poselib);
1606         id_lib_extern((ID *)ob->gpd);
1607
1608         extern_local_matarar(ob->mat, ob->totcol);
1609
1610         for (psys = ob->particlesystem.first; psys; psys = psys->next)
1611                 id_lib_extern((ID *)psys->part);
1612
1613         modifiers_foreachIDLink(ob, extern_local_object__modifiersForeachIDLink, NULL);
1614
1615         ob->preview = NULL;
1616 }
1617
1618 void BKE_object_make_local(Object *ob)
1619 {
1620         Main *bmain = G.main;
1621         Scene *sce;
1622         Base *base;
1623         bool is_local = false, is_lib = false;
1624
1625         /* - only lib users: do nothing
1626          * - only local users: set flag
1627          * - mixed: make copy
1628          */
1629
1630         if (ob->id.lib == NULL) return;
1631         
1632         ob->proxy = ob->proxy_from  = ob->proxy_group = NULL;
1633         
1634         if (ob->id.us == 1) {
1635                 id_clear_lib_data(bmain, &ob->id);
1636                 extern_local_object(ob);
1637         }
1638         else {
1639                 for (sce = bmain->scene.first; sce && ELEM(0, is_lib, is_local); sce = sce->id.next) {
1640                         if (BKE_scene_base_find(sce, ob)) {
1641                                 if (sce->id.lib) is_lib = true;
1642                                 else is_local = true;
1643                         }
1644                 }
1645
1646                 if (is_local && is_lib == false) {
1647                         id_clear_lib_data(bmain, &ob->id);
1648                         extern_local_object(ob);
1649                 }
1650                 else if (is_local && is_lib) {
1651                         Object *ob_new = BKE_object_copy(ob);
1652
1653                         ob_new->id.us = 0;
1654                         
1655                         /* Remap paths of new ID using old library as base. */
1656                         BKE_id_lib_local_paths(bmain, ob->id.lib, &ob_new->id);
1657
1658                         sce = bmain->scene.first;
1659                         while (sce) {
1660                                 if (sce->id.lib == NULL) {
1661                                         base = sce->base.first;
1662                                         while (base) {
1663                                                 if (base->object == ob) {
1664                                                         base->object = ob_new;
1665                                                         id_us_plus(&ob_new->id);
1666                                                         id_us_min(&ob->id);
1667                                                 }
1668                                                 base = base->next;
1669                                         }
1670                                 }
1671                                 sce = sce->id.next;
1672                         }
1673                 }
1674         }
1675 }
1676
1677 /*
1678  * Returns true if the Object is a from an external blend file (libdata)
1679  */
1680 bool BKE_object_is_libdata(Object *ob)
1681 {
1682         if (!ob) return false;
1683         if (ob->proxy) return false;
1684         if (ob->id.lib) return true;
1685         return false;
1686 }
1687
1688 /* Returns true if the Object data is a from an external blend file (libdata) */
1689 bool BKE_object_obdata_is_libdata(Object *ob)
1690 {
1691         if (!ob) return false;
1692         if (ob->proxy && (ob->data == NULL || ((ID *)ob->data)->lib == NULL)) return false;
1693         if (ob->id.lib) return true;
1694         if (ob->data == NULL) return false;
1695         if (((ID *)ob->data)->lib) return true;
1696
1697         return false;
1698 }
1699
1700 /* *************** PROXY **************** */
1701
1702 /* when you make proxy, ensure the exposed layers are extern */
1703 static void armature_set_id_extern(Object *ob)
1704 {
1705         bArmature *arm = ob->data;
1706         bPoseChannel *pchan;
1707         unsigned int lay = arm->layer_protected;
1708         
1709         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
1710                 if (!(pchan->bone->layer & lay))
1711                         id_lib_extern((ID *)pchan->custom);
1712         }
1713                         
1714 }
1715
1716 void BKE_object_copy_proxy_drivers(Object *ob, Object *target)
1717 {
1718         if ((target->adt) && (target->adt->drivers.first)) {
1719                 FCurve *fcu;
1720                 
1721                 /* add new animdata block */
1722                 if (!ob->adt)
1723                         ob->adt = BKE_animdata_add_id(&ob->id);
1724                 
1725                 /* make a copy of all the drivers (for now), then correct any links that need fixing */
1726                 free_fcurves(&ob->adt->drivers);
1727                 copy_fcurves(&ob->adt->drivers, &target->adt->drivers);
1728                 
1729                 for (fcu = ob->adt->drivers.first; fcu; fcu = fcu->next) {
1730                         ChannelDriver *driver = fcu->driver;
1731                         DriverVar *dvar;
1732                         
1733                         for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
1734                                 /* all drivers */
1735                                 DRIVER_TARGETS_LOOPER(dvar) 
1736                                 {
1737                                         if (dtar->id) {
1738                                                 if ((Object *)dtar->id == target)
1739                                                         dtar->id = (ID *)ob;
1740                                                 else {
1741                                                         /* only on local objects because this causes indirect links
1742                                                          * 'a -> b -> c', blend to point directly to a.blend
1743                                                          * when a.blend has a proxy thats linked into c.blend  */
1744                                                         if (ob->id.lib == NULL)
1745                                                                 id_lib_extern((ID *)dtar->id);
1746                                                 }
1747                                         }
1748                                 }
1749                                 DRIVER_TARGETS_LOOPER_END
1750                         }
1751                 }
1752         }
1753 }
1754
1755 /* proxy rule: lib_object->proxy_from == the one we borrow from, set temporally while object_update */
1756 /*             local_object->proxy == pointer to library object, saved in files and read */
1757 /*             local_object->proxy_group == pointer to group dupli-object, saved in files and read */
1758
1759 void BKE_object_make_proxy(Object *ob, Object *target, Object *gob)
1760 {
1761         /* paranoia checks */
1762         if (ob->id.lib || target->id.lib == NULL) {
1763                 printf("cannot make proxy\n");
1764                 return;
1765         }
1766         
1767         ob->proxy = target;
1768         ob->proxy_group = gob;
1769         id_lib_extern(&target->id);
1770         
1771         DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1772         DAG_id_tag_update(&target->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1773         
1774         /* copy transform
1775          * - gob means this proxy comes from a group, just apply the matrix
1776          *   so the object wont move from its dupli-transform.
1777          *
1778          * - no gob means this is being made from a linked object,
1779          *   this is closer to making a copy of the object - in-place. */
1780         if (gob) {
1781                 ob->rotmode = target->rotmode;
1782                 mul_m4_m4m4(ob->obmat, gob->obmat, target->obmat);
1783                 if (gob->dup_group) { /* should always be true */
1784                         float tvec[3];
1785                         mul_v3_mat3_m4v3(tvec, ob->obmat, gob->dup_group->dupli_ofs);
1786                         sub_v3_v3(ob->obmat[3], tvec);
1787                 }
1788                 BKE_object_apply_mat4(ob, ob->obmat, false, true);
1789         }
1790         else {
1791                 BKE_object_transform_copy(ob, target);
1792                 ob->parent = target->parent; /* libdata */
1793                 copy_m4_m4(ob->parentinv, target->parentinv);
1794         }
1795         
1796         /* copy animdata stuff - drivers only for now... */
1797         BKE_object_copy_proxy_drivers(ob, target);
1798
1799         /* skip constraints? */
1800         /* FIXME: this is considered by many as a bug */
1801         
1802         /* set object type and link to data */
1803         ob->type = target->type;
1804         ob->data = target->data;
1805         id_us_plus((ID *)ob->data);     /* ensures lib data becomes LIB_TAG_EXTERN */
1806         
1807         /* copy material and index information */
1808         ob->actcol = ob->totcol = 0;
1809         if (ob->mat) MEM_freeN(ob->mat);
1810         if (ob->matbits) MEM_freeN(ob->matbits);
1811         ob->mat = NULL;
1812         ob->matbits = NULL;
1813         if ((target->totcol) && (target->mat) && OB_TYPE_SUPPORT_MATERIAL(ob->type)) {
1814                 int i;
1815                 
1816                 ob->actcol = target->actcol;
1817                 ob->totcol = target->totcol;
1818                 
1819                 ob->mat = MEM_dupallocN(target->mat);
1820                 ob->matbits = MEM_dupallocN(target->matbits);
1821                 for (i = 0; i < target->totcol; i++) {
1822                         /* don't need to run test_object_materials since we know this object is new and not used elsewhere */
1823                         id_us_plus((ID *)ob->mat[i]); 
1824                 }
1825         }
1826         
1827         /* type conversions */
1828         if (target->type == OB_ARMATURE) {
1829                 copy_object_pose(ob, target);   /* data copy, object pointers in constraints */
1830                 BKE_pose_rest(ob->pose);            /* clear all transforms in channels */
1831                 BKE_pose_rebuild(ob, ob->data); /* set all internal links */
1832                 
1833                 armature_set_id_extern(ob);
1834         }
1835         else if (target->type == OB_EMPTY) {
1836                 ob->empty_drawtype = target->empty_drawtype;
1837                 ob->empty_drawsize = target->empty_drawsize;
1838         }
1839
1840         /* copy IDProperties */
1841         if (ob->id.properties) {
1842                 IDP_FreeProperty(ob->id.properties);
1843                 MEM_freeN(ob->id.properties);
1844                 ob->id.properties = NULL;
1845         }
1846         if (target->id.properties) {
1847                 ob->id.properties = IDP_CopyProperty(target->id.properties);
1848         }
1849
1850         /* copy drawtype info */
1851         ob->dt = target->dt;
1852 }
1853
1854 /**
1855  * Use with newly created objects to set their size
1856  * (used to apply scene-scale).
1857  */
1858 void BKE_object_obdata_size_init(struct Object *ob, const float size)
1859 {
1860         /* apply radius as a scale to types that support it */
1861         switch (ob->type) {
1862                 case OB_EMPTY:
1863                 {
1864                         ob->empty_drawsize *= size;
1865                         break;
1866                 }
1867                 case OB_FONT:
1868                 {
1869                         Curve *cu = ob->data;
1870                         cu->fsize *= size;
1871                         break;
1872                 }
1873                 case OB_CAMERA:
1874                 {
1875                         Camera *cam = ob->data;
1876                         cam->drawsize *= size;
1877                         break;
1878                 }
1879                 case OB_LAMP:
1880                 {
1881                         Lamp *lamp = ob->data;
1882                         lamp->dist *= size;
1883                         lamp->area_size  *= size;
1884                         lamp->area_sizey *= size;
1885                         lamp->area_sizez *= size;
1886                         break;
1887                 }
1888                 /* Only lattice (not mesh, curve, mball...),
1889                  * because its got data when newly added */
1890                 case OB_LATTICE:
1891                 {
1892                         struct Lattice *lt = ob->data;
1893                         float mat[4][4];
1894
1895                         unit_m4(mat);
1896                         scale_m4_fl(mat, size);
1897
1898                         BKE_lattice_transform(lt, (float (*)[4])mat, false);
1899                         break;
1900                 }
1901         }
1902 }
1903
1904 /* *************** CALC ****************** */
1905
1906 void BKE_object_scale_to_mat3(Object *ob, float mat[3][3])
1907 {
1908         float vec[3];
1909         mul_v3_v3v3(vec, ob->size, ob->dscale);
1910         size_to_mat3(mat, vec);
1911 }
1912
1913 void BKE_object_rot_to_mat3(Object *ob, float mat[3][3], bool use_drot)
1914 {
1915         float rmat[3][3], dmat[3][3];
1916         
1917         /* 'dmat' is the delta-rotation matrix, which will get (pre)multiplied
1918          * with the rotation matrix to yield the appropriate rotation
1919          */
1920
1921         /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
1922         if (ob->rotmode > 0) {
1923                 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
1924                 eulO_to_mat3(rmat, ob->rot, ob->rotmode);
1925                 eulO_to_mat3(dmat, ob->drot, ob->rotmode);
1926         }
1927         else if (ob->rotmode == ROT_MODE_AXISANGLE) {
1928                 /* axis-angle - not really that great for 3D-changing orientations */
1929                 axis_angle_to_mat3(rmat, ob->rotAxis, ob->rotAngle);
1930                 axis_angle_to_mat3(dmat, ob->drotAxis, ob->drotAngle);
1931         }
1932         else {
1933                 /* quats are normalized before use to eliminate scaling issues */
1934                 float tquat[4];
1935                 
1936                 normalize_qt_qt(tquat, ob->quat);
1937                 quat_to_mat3(rmat, tquat);
1938                 
1939                 normalize_qt_qt(tquat, ob->dquat);
1940                 quat_to_mat3(dmat, tquat);
1941         }
1942         
1943         /* combine these rotations */
1944         if (use_drot)
1945                 mul_m3_m3m3(mat, dmat, rmat);
1946         else
1947                 copy_m3_m3(mat, rmat);
1948 }
1949
1950 void BKE_object_mat3_to_rot(Object *ob, float mat[3][3], bool use_compat)
1951 {
1952         BLI_ASSERT_UNIT_M3(mat);
1953
1954         switch (ob->rotmode) {
1955                 case ROT_MODE_QUAT:
1956                 {
1957                         float dquat[4];
1958                         mat3_normalized_to_quat(ob->quat, mat);
1959                         normalize_qt_qt(dquat, ob->dquat);
1960                         invert_qt_normalized(dquat);
1961                         mul_qt_qtqt(ob->quat, dquat, ob->quat);
1962                         break;
1963                 }
1964                 case ROT_MODE_AXISANGLE:
1965                 {
1966                         float quat[4];
1967                         float dquat[4];
1968
1969                         /* without drot we could apply 'mat' directly */
1970                         mat3_normalized_to_quat(quat, mat);
1971                         axis_angle_to_quat(dquat, ob->drotAxis, ob->drotAngle);
1972                         invert_qt_normalized(dquat);
1973                         mul_qt_qtqt(quat, dquat, quat);
1974                         quat_to_axis_angle(ob->rotAxis, &ob->rotAngle, quat);
1975                         break;
1976                 }
1977                 default: /* euler */
1978                 {
1979                         float quat[4];
1980                         float dquat[4];
1981
1982                         /* without drot we could apply 'mat' directly */
1983                         mat3_normalized_to_quat(quat, mat);
1984                         eulO_to_quat(dquat, ob->drot, ob->rotmode);
1985                         invert_qt_normalized(dquat);
1986                         mul_qt_qtqt(quat, dquat, quat);
1987                         /* end drot correction */
1988
1989                         if (use_compat) quat_to_compatible_eulO(ob->rot, ob->rot, ob->rotmode, quat);
1990                         else            quat_to_eulO(ob->rot, ob->rotmode, quat);
1991                         break;
1992                 }
1993         }
1994 }
1995
1996 void BKE_object_tfm_protected_backup(const Object *ob,
1997                                      ObjectTfmProtectedChannels *obtfm)
1998 {
1999
2000 #define TFMCPY(_v) (obtfm->_v = ob->_v)
2001 #define TFMCPY3D(_v) copy_v3_v3(obtfm->_v, ob->_v)
2002 #define TFMCPY4D(_v) copy_v4_v4(obtfm->_v, ob->_v)
2003
2004         TFMCPY3D(loc);
2005         TFMCPY3D(dloc);
2006         TFMCPY3D(size);
2007         TFMCPY3D(dscale);
2008         TFMCPY3D(rot);
2009         TFMCPY3D(drot);
2010         TFMCPY4D(quat);
2011         TFMCPY4D(dquat);
2012         TFMCPY3D(rotAxis);
2013         TFMCPY3D(drotAxis);
2014         TFMCPY(rotAngle);
2015         TFMCPY(drotAngle);
2016
2017 #undef TFMCPY
2018 #undef TFMCPY3D
2019 #undef TFMCPY4D
2020
2021 }
2022
2023 void BKE_object_tfm_protected_restore(Object *ob,
2024                                       const ObjectTfmProtectedChannels *obtfm,
2025                                       const short protectflag)
2026 {
2027         unsigned int i;
2028
2029         for (i = 0; i < 3; i++) {
2030                 if (protectflag & (OB_LOCK_LOCX << i)) {
2031                         ob->loc[i] =  obtfm->loc[i];
2032                         ob->dloc[i] = obtfm->dloc[i];
2033                 }
2034
2035                 if (protectflag & (OB_LOCK_SCALEX << i)) {
2036                         ob->size[i] =  obtfm->size[i];
2037                         ob->dscale[i] = obtfm->dscale[i];
2038                 }
2039
2040                 if (protectflag & (OB_LOCK_ROTX << i)) {
2041                         ob->rot[i] =  obtfm->rot[i];
2042                         ob->drot[i] = obtfm->drot[i];
2043
2044                         ob->quat[i + 1] =  obtfm->quat[i + 1];
2045                         ob->dquat[i + 1] = obtfm->dquat[i + 1];
2046
2047                         ob->rotAxis[i] =  obtfm->rotAxis[i];
2048                         ob->drotAxis[i] = obtfm->drotAxis[i];
2049                 }
2050         }
2051
2052         if ((protectflag & OB_LOCK_ROT4D) && (protectflag & OB_LOCK_ROTW)) {
2053                 ob->quat[0] =  obtfm->quat[0];
2054                 ob->dquat[0] = obtfm->dquat[0];
2055
2056                 ob->rotAngle =  obtfm->rotAngle;
2057                 ob->drotAngle = obtfm->drotAngle;
2058         }
2059 }
2060
2061 void BKE_object_to_mat3(Object *ob, float mat[3][3]) /* no parent */
2062 {
2063         float smat[3][3];
2064         float rmat[3][3];
2065         /*float q1[4];*/
2066         
2067         /* size */
2068         BKE_object_scale_to_mat3(ob, smat);
2069
2070         /* rot */
2071         BKE_object_rot_to_mat3(ob, rmat, true);
2072         mul_m3_m3m3(mat, rmat, smat);
2073 }
2074
2075 void BKE_object_to_mat4(Object *ob, float mat[4][4])
2076 {
2077         float tmat[3][3];
2078         
2079         BKE_object_to_mat3(ob, tmat);
2080         
2081         copy_m4_m3(mat, tmat);
2082
2083         add_v3_v3v3(mat[3], ob->loc, ob->dloc);
2084 }
2085
2086 void BKE_object_matrix_local_get(struct Object *ob, float mat[4][4])
2087 {
2088         if (ob->parent) {
2089                 float par_imat[4][4];
2090
2091                 BKE_object_get_parent_matrix(NULL, ob, ob->parent, par_imat);
2092                 invert_m4(par_imat);
2093                 mul_m4_m4m4(mat, par_imat, ob->obmat);
2094         }
2095         else {
2096                 copy_m4_m4(mat, ob->obmat);
2097         }
2098 }
2099
2100 /* extern */
2101 int enable_cu_speed = 1;
2102
2103 /**
2104  * \param scene: Used when curve cache needs to be calculated, or for dupli-frame time.
2105  * \return success if \a mat is set.
2106  */
2107 static bool ob_parcurve(Scene *scene, Object *ob, Object *par, float mat[4][4])
2108 {
2109         Curve *cu = par->data;
2110         float vec[4], dir[3], quat[4], radius, ctime;
2111
2112         /* only happens on reload file, but violates depsgraph still... fix! */
2113         if (par->curve_cache == NULL) {
2114                 if (scene == NULL) {
2115                         return false;
2116                 }
2117                 BKE_displist_make_curveTypes(scene, par, 0);
2118         }
2119
2120         if (par->curve_cache->path == NULL) {
2121                 return false;
2122         }
2123
2124         /* catch exceptions: curve paths used as a duplicator */
2125         if (enable_cu_speed) {
2126                 /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated,
2127                  * but this will only work if it actually is animated... 
2128                  *
2129                  * we divide the curvetime calculated in the previous step by the length of the path, to get a time
2130                  * factor, which then gets clamped to lie within 0.0 - 1.0 range
2131                  */
2132                 if (cu->pathlen) {
2133                         ctime = cu->ctime / cu->pathlen;
2134                 }
2135                 else {
2136                         ctime = cu->ctime;
2137                 }
2138
2139                 CLAMP(ctime, 0.0f, 1.0f);
2140         }
2141         else {
2142                 /* For dupli-frames only */
2143                 if (scene == NULL) {
2144                         return false;
2145                 }
2146
2147                 ctime = BKE_scene_frame_get(scene);
2148                 if (cu->pathlen) {
2149                         ctime /= cu->pathlen;
2150                 }
2151                 
2152                 CLAMP(ctime, 0.0f, 1.0f);
2153         }
2154         
2155         unit_m4(mat);
2156
2157         /* vec: 4 items! */
2158         if (where_on_path(par, ctime, vec, dir, (cu->flag & CU_FOLLOW) ? quat : NULL, &radius, NULL)) {
2159
2160                 if (cu->flag & CU_FOLLOW) {
2161 #if 0
2162                         float si, q[4];
2163                         vec_to_quat(quat, dir, ob->trackflag, ob->upflag);
2164                         
2165                         /* the tilt */
2166                         normalize_v3(dir);
2167                         q[0] = cosf(0.5 * vec[3]);
2168                         si = sinf(0.5 * vec[3]);
2169                         q[1] = -si * dir[0];
2170                         q[2] = -si * dir[1];
2171                         q[3] = -si * dir[2];
2172                         mul_qt_qtqt(quat, q, quat);
2173 #else
2174                         quat_apply_track(quat, ob->trackflag, ob->upflag);
2175 #endif
2176                         normalize_qt(quat);
2177                         quat_to_mat4(mat, quat);
2178                 }
2179                 
2180                 if (cu->flag & CU_PATH_RADIUS) {
2181                         float tmat[4][4], rmat[4][4];
2182                         scale_m4_fl(tmat, radius);
2183                         mul_m4_m4m4(rmat, tmat, mat);
2184                         copy_m4_m4(mat, rmat);
2185                 }
2186
2187                 copy_v3_v3(mat[3], vec);
2188                 
2189         }
2190
2191         return true;
2192 }
2193
2194 static void ob_parbone(Object *ob, Object *par, float mat[4][4])
2195 {       
2196         bPoseChannel *pchan;
2197         float vec[3];
2198         
2199         if (par->type != OB_ARMATURE) {
2200                 unit_m4(mat);
2201                 return;
2202         }
2203         
2204         /* Make sure the bone is still valid */
2205         pchan = BKE_pose_channel_find_name(par->pose, ob->parsubstr);
2206         if (!pchan || !pchan->bone) {
2207                 printf("Object %s with Bone parent: bone %s doesn't exist\n", ob->id.name + 2, ob->parsubstr);
2208                 unit_m4(mat);
2209                 return;
2210         }
2211
2212         /* get bone transform */
2213         if (pchan->bone->flag & BONE_RELATIVE_PARENTING) {
2214                 /* the new option uses the root - expected bahaviour, but differs from old... */
2215                 /* XXX check on version patching? */
2216                 copy_m4_m4(mat, pchan->chan_mat);
2217         }
2218         else {
2219                 copy_m4_m4(mat, pchan->pose_mat);
2220
2221                 /* but for backwards compatibility, the child has to move to the tail */
2222                 copy_v3_v3(vec, mat[1]);
2223                 mul_v3_fl(vec, pchan->bone->length);
2224                 add_v3_v3(mat[3], vec);
2225         }
2226 }
2227
2228 static void give_parvert(Object *par, int nr, float vec[3])
2229 {
2230         zero_v3(vec);
2231         
2232         if (par->type == OB_MESH) {
2233                 Mesh *me = par->data;
2234                 BMEditMesh *em = me->edit_btmesh;
2235                 DerivedMesh *dm;
2236
2237                 dm = (em) ? em->derivedFinal : par->derivedFinal;
2238                         
2239                 if (dm) {
2240                         int count = 0;
2241                         int numVerts = dm->getNumVerts(dm);
2242
2243                         if (nr < numVerts) {
2244                                 bool use_special_ss_case = false;
2245
2246                                 if (dm->type == DM_TYPE_CCGDM) {
2247                                         ModifierData *md;
2248                                         VirtualModifierData virtualModifierData;
2249                                         use_special_ss_case = true;
2250                                         for (md = modifiers_getVirtualModifierList(par, &virtualModifierData);
2251                                              md != NULL;
2252                                              md = md->next)
2253                                         {
2254                                                 const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
2255                                                 /* TODO(sergey): Check for disabled modifiers. */
2256                                                 if (mti->type != eModifierTypeType_OnlyDeform && md->next != NULL) {
2257                                                         use_special_ss_case = false;
2258                                                         break;
2259                                                 }
2260                                         }
2261                                 }
2262
2263                                 if (!use_special_ss_case) {
2264                                         /* avoid dm->getVertDataArray() since it allocates arrays in the dm (not thread safe) */
2265                                         if (em && dm->type == DM_TYPE_EDITBMESH) {
2266                                                 if (em->bm->elem_table_dirty & BM_VERT) {
2267 #ifdef VPARENT_THREADING_HACK
2268                                                         BLI_mutex_lock(&vparent_lock);
2269                                                         if (em->bm->elem_table_dirty & BM_VERT) {
2270                                                                 BM_mesh_elem_table_ensure(em->bm, BM_VERT);
2271                                                         }
2272                                                         BLI_mutex_unlock(&vparent_lock);
2273 #else
2274                                                         BLI_assert(!"Not safe for threading");
2275                                                         BM_mesh_elem_table_ensure(em->bm, BM_VERT);
2276 #endif
2277                                                 }
2278                                         }
2279                                 }
2280
2281                                 if (use_special_ss_case) {
2282                                         /* Special case if the last modifier is SS and no constructive modifier are in front of it. */
2283                                         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2284                                         CCGVert *ccg_vert = ccgSubSurf_getVert(ccgdm->ss, SET_INT_IN_POINTER(nr));
2285                                         /* In case we deleted some verts, nr may refer to inexistent one now, see T42557. */
2286                                         if (ccg_vert) {
2287                                                 float *co = ccgSubSurf_getVertData(ccgdm->ss, ccg_vert);
2288                                                 add_v3_v3(vec, co);
2289                                                 count++;
2290                                         }
2291                                 }
2292                                 else if (CustomData_has_layer(&dm->vertData, CD_ORIGINDEX) &&
2293                                          !(em && dm->type == DM_TYPE_EDITBMESH))
2294                                 {
2295                                         int i;
2296
2297                                         /* Get the average of all verts with (original index == nr). */
2298                                         for (i = 0; i < numVerts; i++) {
2299                                                 const int *index = dm->getVertData(dm, i, CD_ORIGINDEX);
2300                                                 if (*index == nr) {
2301                                                         float co[3];
2302                                                         dm->getVertCo(dm, i, co);
2303                                                         add_v3_v3(vec, co);
2304                                                         count++;
2305                                                 }
2306                                         }
2307                                 }
2308                                 else {
2309                                         if (nr < numVerts) {
2310                                                 float co[3];
2311                                                 dm->getVertCo(dm, nr, co);
2312                                                 add_v3_v3(vec, co);
2313                                                 count++;
2314                                         }
2315                                 }
2316                         }
2317
2318                         if (count == 0) {
2319                                 /* keep as 0, 0, 0 */
2320                         }
2321                         else if (count > 0) {
2322                                 mul_v3_fl(vec, 1.0f / count);
2323                         }
2324                         else {
2325                                 /* use first index if its out of range */
2326                                 dm->getVertCo(dm, 0, vec);
2327                         }
2328                 }
2329                 else {
2330                         fprintf(stderr,
2331                                 "%s: DerivedMesh is needed to solve parenting, "
2332                                 "object position can be wrong now\n", __func__);
2333                 }
2334         }
2335         else if (ELEM(par->type, OB_CURVE, OB_SURF)) {
2336                 ListBase *nurb;
2337
2338                 /* Unless there's some weird depsgraph failure the cache should exist. */
2339                 BLI_assert(par->curve_cache != NULL);
2340
2341                 if (par->curve_cache->deformed_nurbs.first != NULL) {
2342                         nurb = &par->curve_cache->deformed_nurbs;
2343                 }
2344                 else {
2345                         Curve *cu = par->data;
2346                         nurb = BKE_curve_nurbs_get(cu);
2347                 }
2348
2349                 BKE_nurbList_index_get_co(nurb, nr, vec);
2350         }
2351         else if (par->type == OB_LATTICE) {
2352                 Lattice *latt  = par->data;
2353                 DispList *dl   = par->curve_cache ? BKE_displist_find(&par->curve_cache->disp, DL_VERTS) : NULL;
2354                 float (*co)[3] = dl ? (float (*)[3])dl->verts : NULL;
2355                 int tot;
2356
2357                 if (latt->editlatt) latt = latt->editlatt->latt;
2358
2359                 tot = latt->pntsu * latt->pntsv * latt->pntsw;
2360
2361                 /* ensure dl is correct size */
2362                 BLI_assert(dl == NULL || dl->nr == tot);
2363
2364                 if (nr < tot) {
2365                         if (co) {
2366                                 copy_v3_v3(vec, co[nr]);
2367                         }
2368                         else {
2369                                 copy_v3_v3(vec, latt->def[nr].vec);
2370                         }
2371                 }
2372         }
2373 }
2374
2375 static void ob_parvert3(Object *ob, Object *par, float mat[4][4])
2376 {
2377
2378         /* in local ob space */
2379         if (OB_TYPE_SUPPORT_PARVERT(par->type)) {
2380                 float cmat[3][3], v1[3], v2[3], v3[3], q[4];
2381
2382                 give_parvert(par, ob->par1, v1);
2383                 give_parvert(par, ob->par2, v2);
2384                 give_parvert(par, ob->par3, v3);
2385
2386                 tri_to_quat(q, v1, v2, v3);
2387                 quat_to_mat3(cmat, q);
2388                 copy_m4_m3(mat, cmat);
2389
2390                 mid_v3_v3v3v3(mat[3], v1, v2, v3);
2391         }
2392         else {
2393                 unit_m4(mat);
2394         }
2395 }
2396
2397
2398 void BKE_object_get_parent_matrix(Scene *scene, Object *ob, Object *par, float parentmat[4][4])
2399 {
2400         float tmat[4][4];
2401         float vec[3];
2402         bool ok;
2403
2404         switch (ob->partype & PARTYPE) {
2405                 case PAROBJECT:
2406                         ok = 0;
2407                         if (par->type == OB_CURVE) {
2408                                 if ((((Curve *)par->data)->flag & CU_PATH) &&
2409                                     (ob_parcurve(scene, ob, par, tmat)))
2410                                 {
2411                                         ok = 1;
2412                                 }
2413                         }
2414                         
2415                         if (ok) mul_m4_m4m4(parentmat, par->obmat, tmat);
2416                         else copy_m4_m4(parentmat, par->obmat);
2417                         
2418                         break;
2419                 case PARBONE:
2420                         ob_parbone(ob, par, tmat);
2421                         mul_m4_m4m4(parentmat, par->obmat, tmat);
2422                         break;
2423                 
2424                 case PARVERT1:
2425                         unit_m4(parentmat);
2426                         give_parvert(par, ob->par1, vec);
2427                         mul_v3_m4v3(parentmat[3], par->obmat, vec);
2428                         break;
2429                 case PARVERT3:
2430                         ob_parvert3(ob, par, tmat);
2431                         
2432                         mul_m4_m4m4(parentmat, par->obmat, tmat);
2433                         break;
2434                 
2435                 case PARSKEL:
2436                         copy_m4_m4(parentmat, par->obmat);
2437                         break;
2438         }
2439
2440 }
2441
2442 /**
2443  * \param r_originmat  Optional matrix that stores the space the object is in (without its own matrix applied)
2444  */
2445 static void solve_parenting(Scene *scene, Object *ob, Object *par, float obmat[4][4], float slowmat[4][4],
2446                             float r_originmat[3][3], const bool set_origin)
2447 {
2448         float totmat[4][4];
2449         float tmat[4][4];
2450         float locmat[4][4];
2451         
2452         BKE_object_to_mat4(ob, locmat);
2453         
2454         if (ob->partype & PARSLOW) copy_m4_m4(slowmat, obmat);
2455
2456         BKE_object_get_parent_matrix(scene, ob, par, totmat);
2457         
2458         /* total */
2459         mul_m4_m4m4(tmat, totmat, ob->parentinv);
2460         mul_m4_m4m4(obmat, tmat, locmat);
2461         
2462         if (r_originmat) {
2463                 /* usable originmat */
2464                 copy_m3_m4(r_originmat, tmat);
2465         }
2466         
2467         /* origin, for help line */
2468         if (set_origin) {
2469                 if ((ob->partype & PARTYPE) == PARSKEL) {
2470                         copy_v3_v3(ob->orig, par->obmat[3]);
2471                 }
2472                 else {
2473                         copy_v3_v3(ob->orig, totmat[3]);
2474                 }
2475         }
2476 }
2477
2478 static bool where_is_object_parslow(Object *ob, float obmat[4][4], float slowmat[4][4])
2479 {
2480         float *fp1, *fp2;
2481         float fac1, fac2;
2482         int a;
2483
2484         /* include framerate */
2485         fac1 = (1.0f / (1.0f + fabsf(ob->sf)));
2486         if (fac1 >= 1.0f) return false;
2487         fac2 = 1.0f - fac1;
2488
2489         fp1 = obmat[0];
2490         fp2 = slowmat[0];
2491         for (a = 0; a < 16; a++, fp1++, fp2++) {
2492                 fp1[0] = fac1 * fp1[0] + fac2 * fp2[0];
2493         }
2494
2495         return true;
2496 }
2497
2498 /* note, scene is the active scene while actual_scene is the scene the object resides in */
2499 void BKE_object_where_is_calc_time_ex(Scene *scene, Object *ob, float ctime,
2500                                       RigidBodyWorld *rbw, float r_originmat[3][3])
2501 {
2502         if (ob == NULL) return;
2503         
2504         /* execute drivers only, as animation has already been done */
2505         BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, ctime, ADT_RECALC_DRIVERS);
2506         
2507         if (ob->parent) {
2508                 Object *par = ob->parent;
2509                 float slowmat[4][4];
2510                 
2511                 /* calculate parent matrix */
2512                 solve_parenting(scene, ob, par, ob->obmat, slowmat, r_originmat, true);
2513                 
2514                 /* "slow parent" is definitely not threadsafe, and may also give bad results jumping around 
2515                  * An old-fashioned hack which probably doesn't really cut it anymore
2516                  */
2517                 if (ob->partype & PARSLOW) {
2518                         if (!where_is_object_parslow(ob, ob->obmat, slowmat))
2519                                 return;
2520                 }
2521         }
2522         else {
2523                 BKE_object_to_mat4(ob, ob->obmat);
2524         }
2525
2526         /* try to fall back to the scene rigid body world if none given */
2527         rbw = rbw ? rbw : scene->rigidbody_world;
2528         /* read values pushed into RBO from sim/cache... */
2529         BKE_rigidbody_sync_transforms(rbw, ob, ctime);
2530         
2531         /* solve constraints */
2532         if (ob->constraints.first && !(ob->transflag & OB_NO_CONSTRAINTS)) {
2533                 bConstraintOb *cob;
2534                 cob = BKE_constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2535                 BKE_constraints_solve(&ob->constraints, cob, ctime);
2536                 BKE_constraints_clear_evalob(cob);
2537         }
2538         
2539         /* set negative scale flag in object */
2540         if (is_negative_m4(ob->obmat)) ob->transflag |= OB_NEG_SCALE;
2541         else ob->transflag &= ~OB_NEG_SCALE;
2542 }
2543
2544 void BKE_object_where_is_calc_time(Scene *scene, Object *ob, float ctime)
2545 {
2546         BKE_object_where_is_calc_time_ex(scene, ob, ctime, NULL, NULL);
2547 }
2548
2549 /* get object transformation matrix without recalculating dependencies and
2550  * constraints -- assume dependencies are already solved by depsgraph.
2551  * no changes to object and it's parent would be done.
2552  * used for bundles orientation in 3d space relative to parented blender camera */
2553 void BKE_object_where_is_calc_mat4(Scene *scene, Object *ob, float obmat[4][4])
2554 {
2555
2556         if (ob->parent) {
2557                 float slowmat[4][4];
2558
2559                 Object *par = ob->parent;
2560                 
2561                 solve_parenting(scene, ob, par, obmat, slowmat, NULL, false);
2562                 
2563                 if (ob->partype & PARSLOW)
2564                         where_is_object_parslow(ob, obmat, slowmat);
2565         }
2566         else {
2567                 BKE_object_to_mat4(ob, obmat);
2568         }
2569 }
2570
2571 void BKE_object_where_is_calc_ex(Scene *scene, RigidBodyWorld *rbw, Object *ob, float r_originmat[3][3])
2572 {
2573         BKE_object_where_is_calc_time_ex(scene, ob, BKE_scene_frame_get(scene), rbw, r_originmat);
2574 }
2575 void BKE_object_where_is_calc(Scene *scene, Object *ob)
2576 {
2577         BKE_object_where_is_calc_time_ex(scene, ob, BKE_scene_frame_get(scene), NULL, NULL);
2578 }
2579
2580 /* for calculation of the inverse parent transform, only used for editor */
2581 void BKE_object_workob_calc_parent(Scene *scene, Object *ob, Object *workob)
2582 {
2583         BKE_object_workob_clear(workob);
2584         
2585         unit_m4(workob->obmat);
2586         unit_m4(workob->parentinv);
2587         unit_m4(workob->constinv);
2588         workob->parent = ob->parent;
2589
2590         workob->trackflag = ob->trackflag;
2591         workob->upflag = ob->upflag;
2592         
2593         workob->partype = ob->partype;
2594         workob->par1 = ob->par1;
2595         workob->par2 = ob->par2;
2596         workob->par3 = ob->par3;
2597
2598         workob->constraints.first = ob->constraints.first;
2599         workob->constraints.last = ob->constraints.last;
2600
2601         BLI_strncpy(workob->parsubstr, ob->parsubstr, sizeof(workob->parsubstr));
2602
2603         BKE_object_where_is_calc(scene, workob);
2604 }
2605
2606 /* see BKE_pchan_apply_mat4() for the equivalent 'pchan' function */
2607 void BKE_object_apply_mat4(Object *ob, float mat[4][4], const bool use_compat, const bool use_parent)
2608 {
2609         float rot[3][3];
2610
2611         if (use_parent && ob->parent) {
2612                 float rmat[4][4], diff_mat[4][4], imat[4][4], parent_mat[4][4];
2613
2614                 BKE_object_get_parent_matrix(NULL, ob, ob->parent, parent_mat);
2615
2616                 mul_m4_m4m4(diff_mat, parent_mat, ob->parentinv);
2617                 invert_m4_m4(imat, diff_mat);
2618                 mul_m4_m4m4(rmat, imat, mat); /* get the parent relative matrix */
2619
2620                 /* same as below, use rmat rather than mat */
2621                 mat4_to_loc_rot_size(ob->loc, rot, ob->size, rmat);
2622         }
2623         else {
2624                 mat4_to_loc_rot_size(ob->loc, rot, ob->size, mat);
2625         }
2626
2627         BKE_object_mat3_to_rot(ob, rot, use_compat);
2628
2629         sub_v3_v3(ob->loc, ob->dloc);
2630
2631         if (ob->dscale[0] != 0.0f) ob->size[0] /= ob->dscale[0];
2632         if (ob->dscale[1] != 0.0f) ob->size[1] /= ob->dscale[1];
2633         if (ob->dscale[2] != 0.0f) ob->size[2] /= ob->dscale[2];
2634
2635         /* BKE_object_mat3_to_rot handles delta rotations */
2636 }
2637
2638 BoundBox *BKE_boundbox_alloc_unit(void)
2639 {
2640         BoundBox *bb;
2641         const float min[3] = {-1.0f, -1.0f, -1.0f}, max[3] = {-1.0f, -1.0f, -1.0f};
2642
2643         bb = MEM_callocN(sizeof(BoundBox), "OB-BoundBox");
2644         BKE_boundbox_init_from_minmax(bb, min, max);
2645         
2646         return bb;
2647 }
2648
2649 void BKE_boundbox_init_from_minmax(BoundBox *bb, const float min[3], const float max[3])
2650 {
2651         bb->vec[0][0] = bb->vec[1][0] = bb->vec[2][0] = bb->vec[3][0] = min[0];
2652         bb->vec[4][0] = bb->vec[5][0] = bb->vec[6][0] = bb->vec[7][0] = max[0];
2653         
2654         bb->vec[0][1] = bb->vec[1][1] = bb->vec[4][1] = bb->vec[5][1] = min[1];
2655         bb->vec[2][1] = bb->vec[3][1] = bb->vec[6][1] = bb->vec[7][1] = max[1];
2656
2657         bb->vec[0][2] = bb->vec[3][2] = bb->vec[4][2] = bb->vec[7][2] = min[2];
2658         bb->vec[1][2] = bb->vec[2][2] = bb->vec[5][2] = bb->vec[6][2] = max[2];
2659 }
2660
2661 void BKE_boundbox_calc_center_aabb(const BoundBox *bb, float r_cent[3])
2662 {
2663         r_cent[0] = 0.5f * (bb->vec[0][0] + bb->vec[4][0]);
2664         r_cent[1] = 0.5f * (bb->vec[0][1] + bb->vec[2][1]);
2665         r_cent[2] = 0.5f * (bb->vec[0][2] + bb->vec[1][2]);
2666 }
2667
2668 void BKE_boundbox_calc_size_aabb(const BoundBox *bb, float r_size[3])
2669 {
2670         r_size[0] = 0.5f * fabsf(bb->vec[0][0] - bb->vec[4][0]);
2671         r_size[1] = 0.5f * fabsf(bb->vec[0][1] - bb->vec[2][1]);
2672         r_size[2] = 0.5f * fabsf(bb->vec[0][2] - bb->vec[1][2]);
2673 }
2674
2675 void BKE_boundbox_minmax(const BoundBox *bb, float obmat[4][4], float r_min[3], float r_max[3])
2676 {
2677         int i;
2678         for (i = 0; i < 8; i++) {
2679                 float vec[3];
2680                 mul_v3_m4v3(vec, obmat, bb->vec[i]);
2681                 minmax_v3v3_v3(r_min, r_max, vec);
2682         }
2683 }
2684
2685 void BKE_boundbox_scale(struct BoundBox *bb_dst, const struct BoundBox *bb_src, float scale)
2686 {
2687         float cent[3];
2688         BKE_boundbox_calc_center_aabb(bb_src, cent);
2689
2690         for (int i = 0; i < ARRAY_SIZE(bb_dst->vec); i++) {
2691                 bb_dst->vec[i][0] = ((bb_src->vec[i][0] - cent[0]) * scale) + cent[0];
2692                 bb_dst->vec[i][1] = ((bb_src->vec[i][1] - cent[1]) * scale) + cent[1];
2693                 bb_dst->vec[i][2] = ((bb_src->vec[i][2] - cent[2]) * scale) + cent[2];
2694         }
2695 }
2696
2697 /**
2698  * Returns a BBox which each dimensions are at least epsilon.
2699  * \note In case a given dimension needs to be enlarged, its final value will be in [epsilon, 3 * epsilon] range.
2700  *
2701  * \param bb the input bbox to check.
2702  * \param bb_temp the temp bbox to modify (\a bb content is never changed).
2703  * \param epsilon the minimum dimension to ensure.
2704  * \return either bb (if nothing needed to be changed) or bb_temp.
2705  */
2706 BoundBox *BKE_boundbox_ensure_minimum_dimensions(BoundBox *bb, BoundBox *bb_temp, const float epsilon)
2707 {
2708         if (fabsf(bb->vec[0][0] - bb->vec[4][0]) < epsilon) {
2709                 /* Flat along X axis... */
2710                 *bb_temp = *bb;
2711                 bb = bb_temp;
2712                 bb->vec[0][0] -= epsilon;
2713                 bb->vec[1][0] -= epsilon;
2714                 bb->vec[2][0] -= epsilon;
2715                 bb->vec[3][0] -= epsilon;
2716                 bb->vec[4][0] += epsilon;
2717                 bb->vec[5][0] += epsilon;
2718                 bb->vec[6][0] += epsilon;
2719                 bb->vec[7][0] += epsilon;
2720         }
2721
2722         if (fabsf(bb->vec[0][1] - bb->vec[3][1]) < epsilon) {
2723                 /* Flat along Y axis... */
2724                 if (bb != bb_temp) {
2725                         *bb_temp = *bb;
2726                         bb = bb_temp;
2727                 }
2728                 bb->vec[0][1] -= epsilon;
2729                 bb->vec[1][1] -= epsilon;
2730                 bb->vec[4][1] -= epsilon;
2731                 bb->vec[5][1] -= epsilon;
2732                 bb->vec[2][1] += epsilon;
2733                 bb->vec[3][1] += epsilon;
2734                 bb->vec[6][1] += epsilon;
2735                 bb->vec[7][1] += epsilon;
2736         }
2737
2738         if (fabsf(bb->vec[0][2] - bb->vec[1][2]) < epsilon) {
2739                 /* Flat along Z axis... */
2740                 if (bb != bb_temp) {
2741                         *bb_temp = *bb;
2742                         bb = bb_temp;
2743                 }
2744                 bb->vec[0][2] -= epsilon;
2745                 bb->vec[3][2] -= epsilon;
2746                 bb->vec[4][2] -= epsilon;
2747                 bb->vec[7][2] -= epsilon;
2748                 bb->vec[1][2] += epsilon;
2749                 bb->vec[2][2] += epsilon;
2750                 bb->vec[5][2] += epsilon;
2751                 bb->vec[6][2] += epsilon;
2752         }
2753
2754         return bb;
2755 }
2756
2757 BoundBox *BKE_object_boundbox_get(Object *ob)
2758 {
2759         BoundBox *bb = NULL;
2760         
2761         if (ob->type == OB_MESH) {
2762                 bb = BKE_mesh_boundbox_get(ob);
2763         }
2764         else if (ELEM(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2765                 bb = BKE_curve_boundbox_get(ob);
2766         }
2767         else if (ob->type == OB_MBALL) {
2768                 bb = ob->bb;
2769         }
2770         else if (ob->type == OB_LATTICE) {
2771                 bb = BKE_lattice_boundbox_get(ob);
2772         }
2773         else if (ob->type == OB_ARMATURE) {
2774                 bb = BKE_armature_boundbox_get(ob);
2775         }
2776         return bb;
2777 }
2778
2779 /* used to temporally disable/enable boundbox */
2780 void BKE_object_boundbox_flag(Object *ob, int flag, const bool set)
2781 {
2782         BoundBox *bb = BKE_object_boundbox_get(ob);
2783         if (bb) {
2784                 if (set) bb->flag |= flag;
2785                 else bb->flag &= ~flag;
2786         }
2787 }
2788
2789 void BKE_object_dimensions_get(Object *ob, float vec[3])
2790 {
2791         BoundBox *bb = NULL;
2792         
2793         bb = BKE_object_boundbox_get(ob);
2794         if (bb) {
2795                 float scale[3];
2796                 
2797                 mat4_to_size(scale, ob->obmat);
2798                 
2799                 vec[0] = fabsf(scale[0]) * (bb->vec[4][0] - bb->vec[0][0]);
2800                 vec[1] = fabsf(scale[1]) * (bb->vec[2][1] - bb->vec[0][1]);
2801                 vec[2] = fabsf(scale[2]) * (bb->vec[1][2] - bb->vec[0][2]);
2802         }
2803         else {
2804                 zero_v3(vec);
2805         }
2806 }
2807
2808 void BKE_object_dimensions_set(Object *ob, const float value[3])
2809 {
2810         BoundBox *bb = NULL;
2811         
2812         bb = BKE_object_boundbox_get(ob);
2813         if (bb) {
2814                 float scale[3], len[3];
2815                 
2816                 mat4_to_size(scale, ob->obmat);
2817                 
2818                 len[0] = bb->vec[4][0] - bb->vec[0][0];
2819                 len[1] = bb->vec[2][1] - bb->vec[0][1];
2820                 len[2] = bb->vec[1][2] - bb->vec[0][2];
2821                 
2822                 if (len[0] > 0.f) ob->size[0] = value[0] / len[0];
2823                 if (len[1] > 0.f) ob->size[1] = value[1] / len[1];
2824                 if (len[2] > 0.f) ob->size[2] = value[2] / len[2];
2825         }
2826 }
2827
2828 void BKE_object_minmax(Object *ob, float min_r[3], float max_r[3], const bool use_hidden)
2829 {
2830         BoundBox bb;
2831         float vec[3];
2832         bool changed = false;
2833         
2834         switch (ob->type) {
2835                 case OB_CURVE:
2836                 case OB_FONT:
2837                 case OB_SURF:
2838                 {
2839                         bb = *BKE_curve_boundbox_get(ob);
2840                         BKE_boundbox_minmax(&bb, ob->obmat, min_r, max_r);
2841                         changed = true;
2842                         break;
2843                 }
2844                 case OB_LATTICE:
2845                 {
2846                         Lattice *lt = ob->data;
2847                         BPoint *bp = lt->def;
2848                         int u, v, w;
2849
2850                         for (w = 0; w < lt->pntsw; w++) {
2851                                 for (v = 0; v < lt->pntsv; v++) {
2852                                         for (u = 0; u < lt->pntsu; u++, bp++) {
2853                                                 mul_v3_m4v3(vec, ob->obmat, bp->vec);
2854                                                 minmax_v3v3_v3(min_r, max_r, vec);
2855                                         }
2856                                 }
2857                         }
2858                         changed = true;
2859                         break;
2860                 }
2861                 case OB_ARMATURE:
2862                 {
2863                         changed = BKE_pose_minmax(ob, min_r, max_r, use_hidden, false);
2864                         break;
2865                 }
2866                 case OB_MESH:
2867                 {
2868                         Mesh *me = BKE_mesh_from_object(ob);
2869
2870                         if (me) {
2871                                 bb = *BKE_mesh_boundbox_get(ob);
2872                                 BKE_boundbox_minmax(&bb, ob->obmat, min_r, max_r);
2873                                 changed = true;
2874                         }
2875                         break;
2876                 }
2877                 case OB_MBALL:
2878                 {
2879                         float ob_min[3], ob_max[3];
2880
2881                         changed = BKE_mball_minmax_ex(ob->data, ob_min, ob_max, ob->obmat, 0);
2882                         if (changed) {
2883                                 minmax_v3v3_v3(min_r, max_r, ob_min);
2884                                 minmax_v3v3_v3(min_r, max_r, ob_max);
2885                         }
2886                         break;
2887                 }
2888         }
2889
2890         if (changed == false) {
2891                 float size[3];
2892
2893                 copy_v3_v3(size, ob->size);
2894                 if (ob->type == OB_EMPTY) {
2895                         mul_v3_fl(size, ob->empty_drawsize);
2896                 }
2897
2898                 minmax_v3v3_v3(min_r, max_r, ob->obmat[3]);
2899
2900                 copy_v3_v3(vec, ob->obmat[3]);
2901                 add_v3_v3(vec, size);
2902                 minmax_v3v3_v3(min_r, max_r, vec);
2903
2904                 copy_v3_v3(vec, ob->obmat[3]);
2905                 sub_v3_v3(vec, size);
2906                 minmax_v3v3_v3(min_r, max_r, vec);
2907         }
2908 }
2909
2910 void BKE_object_empty_draw_type_set(Object *ob, const int value)
2911 {
2912         ob->empty_drawtype = value;
2913
2914         if (ob->type == OB_EMPTY && ob->empty_drawtype == OB_EMPTY_IMAGE) {
2915                 if (!ob->iuser) {
2916                         ob->iuser = MEM_callocN(sizeof(ImageUser), "image user");
2917                         ob->iuser->ok = 1;
2918                         ob->iuser->frames = 100;
2919                         ob->iuser->sfra = 1;
2920                         ob->iuser->fie_ima = 2;
2921                 }
2922         }
2923         else {
2924                 if (ob->iuser) {
2925                         MEM_freeN(ob->iuser);
2926                         ob->iuser = NULL;
2927                 }
2928         }
2929 }
2930
2931 bool BKE_object_minmax_dupli(Scene *scene, Object *ob, float r_min[3], float r_max[3], const bool use_hidden)
2932 {
2933         bool ok = false;
2934         if ((ob->transflag & OB_DUPLI) == 0) {
2935                 return ok;
2936         }
2937         else {
2938                 ListBase *lb;
2939                 DupliObject *dob;
2940                 lb = object_duplilist(G.main->eval_ctx, scene, ob);
2941                 for (dob = lb->first; dob; dob = dob->next) {
2942                         if ((use_hidden == false) && (dob->no_draw != 0)) {
2943                                 /* pass */
2944                         }
2945                         else {
2946                                 BoundBox *bb = BKE_object_boundbox_get(dob->ob);
2947
2948                                 if (bb) {
2949                                         int i;
2950                                         for (i = 0; i < 8; i++) {
2951                                                 float vec[3];
2952                                                 mul_v3_m4v3(vec, dob->mat, bb->vec[i]);
2953                                                 minmax_v3v3_v3(r_min, r_max, vec);
2954                                         }
2955
2956                                         ok = true;
2957                                 }
2958                         }
2959                 }
2960                 free_object_duplilist(lb);  /* does restore */
2961         }
2962
2963         return ok;
2964 }
2965
2966 void BKE_object_foreach_display_point(
2967         Object *ob, float obmat[4][4],
2968         void (*func_cb)(const float[3], void *), void *user_data)
2969 {
2970         float co[3];
2971
2972         if (ob->derivedFinal) {
2973                 DerivedMesh *dm = ob->derivedFinal;
2974                 MVert *mv = dm->getVertArray(dm);
2975                 int totvert = dm->getNumVerts(dm);
2976                 int i;
2977
2978                 for (i = 0; i < totvert; i++, mv++) {
2979                         mul_v3_m4v3(co, obmat, mv->co);
2980                         func_cb(co, user_data);
2981                 }
2982         }
2983         else if (ob->curve_cache && ob->curve_cache->disp.first) {
2984                 DispList *dl;
2985
2986                 for (dl = ob->curve_cache->disp.first; dl; dl = dl->next) {
2987                         const float *v3 = dl->verts;
2988                         int totvert = dl->nr;
2989                         int i;
2990
2991                         for (i = 0; i < totvert; i++, v3 += 3) {
2992                                 mul_v3_m4v3(co, obmat, v3);
2993                                 func_cb(co, user_data);
2994                         }
2995                 }
2996         }
2997 }
2998
2999 void BKE_scene_foreach_display_point(
3000         Scene *scene, View3D *v3d, const short flag,
3001         void (*func_cb)(const float[3], void *), void *user_data)
3002 {
3003         Base *base;
3004         Object *ob;
3005
3006         for (base = FIRSTBASE; base; base = base->next) {
3007                 if (BASE_VISIBLE_BGMODE(v3d, scene, base) && (base->flag & flag) == flag) {
3008                         ob = base->object;
3009
3010                         if ((ob->transflag & OB_DUPLI) == 0) {
3011                                 BKE_object_foreach_display_point(ob, ob->obmat, func_cb, user_data);
3012                         }
3013                         else {
3014                                 ListBase *lb;
3015                                 DupliObject *dob;
3016
3017                                 lb = object_duplilist(G.main->eval_ctx, scene, ob);
3018                                 for (dob = lb->first; dob; dob = dob->next) {
3019                                         if (dob->no_draw == 0) {
3020                                                 BKE_object_foreach_display_point(dob->ob, dob->mat, func_cb, user_data);
3021                                         }
3022                                 }
3023                                 free_object_duplilist(lb);  /* does restore */
3024                         }
3025                 }
3026         }
3027 }
3028
3029 /* copied from DNA_object_types.h */
3030 typedef struct ObTfmBack {
3031         float loc[3], dloc[3], orig[3];
3032         float size[3], dscale[3];   /* scale and delta scale */
3033         float rot[3], drot[3];      /* euler rotation */
3034         float quat[4], dquat[4];    /* quaternion rotation */
3035         float rotAxis[3], drotAxis[3];  /* axis angle rotation - axis part */
3036         float rotAngle, drotAngle;  /* axis angle rotation - angle part */
3037         float obmat[4][4];      /* final worldspace matrix with constraints & animsys applied */
3038         float parentinv[4][4]; /* inverse result of parent, so that object doesn't 'stick' to parent */
3039         float constinv[4][4]; /* inverse result of constraints. doesn't include effect of parent or object local transform */
3040         float imat[4][4];   /* inverse matrix of 'obmat' for during render, old game engine, temporally: ipokeys of transform  */
3041 } ObTfmBack;
3042
3043 void *BKE_object_tfm_backup(Object *ob)
3044 {
3045         ObTfmBack *obtfm = MEM_mallocN(sizeof(ObTfmBack), "ObTfmBack");
3046         copy_v3_v3(obtfm->loc, ob->loc);
3047         copy_v3_v3(obtfm->dloc, ob->dloc);
3048         copy_v3_v3(obtfm->orig, ob->orig);
3049         copy_v3_v3(obtfm->size, ob->size);
3050         copy_v3_v3(obtfm->dscale, ob->dscale);
3051         copy_v3_v3(obtfm->rot, ob->rot);
3052         copy_v3_v3(obtfm->drot, ob->drot);
3053         copy_qt_qt(obtfm->quat, ob->quat);
3054         copy_qt_qt(obtfm->dquat, ob->dquat);
3055         copy_v3_v3(obtfm->rotAxis, ob->rotAxis);
3056         copy_v3_v3(obtfm->drotAxis, ob->drotAxis);
3057         obtfm->rotAngle = ob->rotAngle;
3058         obtfm->drotAngle = ob->drotAngle;
3059         copy_m4_m4(obtfm->obmat, ob->obmat);
3060         copy_m4_m4(obtfm->parentinv, ob->parentinv);
3061         copy_m4_m4(obtfm->constinv, ob->constinv);
3062         copy_m4_m4(obtfm->imat, ob->imat);
3063
3064         return (void *)obtfm;
3065 }
3066
3067 void BKE_object_tfm_restore(Object *ob, void *obtfm_pt)
3068 {
3069         ObTfmBack *obtfm = (ObTfmBack *)obtfm_pt;
3070         copy_v3_v3(ob->loc, obtfm->loc);
3071         copy_v3_v3(ob->dloc, obtfm->dloc);
3072         copy_v3_v3(ob->orig, obtfm->orig);
3073         copy_v3_v3(ob->size, obtfm->size);
3074         copy_v3_v3(ob->dscale, obtfm->dscale);
3075         copy_v3_v3(ob->rot, obtfm->rot);
3076         copy_v3_v3(ob->drot, obtfm->drot);
3077         copy_qt_qt(ob->quat, obtfm->quat);
3078         copy_qt_qt(ob->dquat, obtfm->dquat);
3079         copy_v3_v3(ob->rotAxis, obtfm->rotAxis);
3080         copy_v3_v3(ob->drotAxis, obtfm->drotAxis);
3081         ob->rotAngle = obtfm->rotAngle;
3082         ob->drotAngle = obtfm->drotAngle;
3083         copy_m4_m4(ob->obmat, obtfm->obmat);
3084         copy_m4_m4(ob->parentinv, obtfm->parentinv);
3085         copy_m4_m4(ob->constinv, obtfm->constinv);
3086         copy_m4_m4(ob->imat, obtfm->imat);
3087 }
3088
3089 bool BKE_object_parent_loop_check(const Object *par, const Object *ob)
3090 {
3091         /* test if 'ob' is a parent somewhere in par's parents */
3092         if (par == NULL) return false;
3093         if (ob == par) return true;
3094         return BKE_object_parent_loop_check(par->parent, ob);
3095 }
3096
3097 /* proxy rule: lib_object->proxy_from == the one we borrow from, only set temporal and cleared here */
3098 /*           local_object->proxy      == pointer to library object, saved in files and read */
3099
3100 /* function below is polluted with proxy exceptions, cleanup will follow! */
3101
3102 /* the main object update call, for object matrix, constraints, keys and displist (modifiers) */
3103 /* requires flags to be set! */
3104 /* Ideally we shouldn't have to pass the rigid body world, but need bigger restructuring to avoid id */
3105 void BKE_object_handle_update_ex(EvaluationContext *eval_ctx,
3106                                  Scene *scene, Object *ob,
3107                                  RigidBodyWorld *rbw,
3108                                  const bool do_proxy_update)
3109 {
3110         if (ob->recalc & OB_RECALC_ALL) {
3111                 /* speed optimization for animation lookups */
3112                 if (ob->pose) {
3113                         BKE_pose_channels_hash_make(ob->pose);
3114                         if (ob->pose->flag & POSE_CONSTRAINTS_NEED_UPDATE_FLAGS) {
3115                                 BKE_pose_update_constraint_flags(ob->pose);
3116                         }
3117                 }
3118
3119                 if (ob->recalc & OB_RECALC_DATA) {
3120                         if (ob->type == OB_ARMATURE) {
3121                                 /* this happens for reading old files and to match library armatures
3122                                  * with poses we do it ahead of BKE_object_where_is_calc to ensure animation
3123                                  * is evaluated on the rebuilt pose, otherwise we get incorrect poses
3124                                  * on file load */
3125                                 if (ob->pose == NULL || (ob->pose->flag & POSE_RECALC))
3126                                         BKE_pose_rebuild(ob, ob->data);
3127                         }
3128                 }
3129
3130                 /* XXX new animsys warning: depsgraph tag OB_RECALC_DATA should not skip drivers, 
3131                  * which is only in BKE_object_where_is_calc now */
3132                 /* XXX: should this case be OB_RECALC_OB instead? */
3133                 if (ob->recalc & OB_RECALC_ALL) {
3134                         
3135                         if (G.debug & G_DEBUG_DEPSGRAPH)
3136                                 printf("recalcob %s\n", ob->id.name + 2);
3137                         
3138                         /* handle proxy copy for target */
3139                         if (ob->id.lib && ob->proxy_from) {
3140                                 // printf("ob proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
3141                                 if (ob->proxy_from->proxy_group) { /* transform proxy into group space */
3142                                         Object *obg = ob->proxy_from->proxy_group;
3143                                         float imat[4][4];
3144                                         invert_m4_m4(imat, obg->obmat);