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