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