Merging r58194 through r58195 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                 }
1623                 break;
1624                 case ROT_MODE_AXISANGLE:
1625                         mat3_to_axis_angle(ob->rotAxis, &ob->rotAngle, mat);
1626                         sub_v3_v3(ob->rotAxis, ob->drotAxis);
1627                         ob->rotAngle -= ob->drotAngle;
1628                         break;
1629                 default: /* euler */
1630                 {
1631                         float quat[4];
1632                         float dquat[4];
1633                         float tmat[3][3];
1634
1635                         /* without drot we could apply 'mat' directly */
1636                         mat3_to_quat(quat, mat);
1637                         eulO_to_quat(dquat, ob->drot, ob->rotmode);
1638                         invert_qt(dquat);
1639                         mul_qt_qtqt(quat, dquat, quat);
1640                         quat_to_mat3(tmat, quat);
1641                         /* end drot correction */
1642
1643                         if (use_compat) mat3_to_compatible_eulO(ob->rot, ob->rot, ob->rotmode, tmat);
1644                         else            mat3_to_eulO(ob->rot, ob->rotmode, tmat);
1645                 }
1646         }
1647 }
1648
1649 void BKE_object_tfm_protected_backup(const Object *ob,
1650                                      ObjectTfmProtectedChannels *obtfm)
1651 {
1652
1653 #define TFMCPY(_v) (obtfm->_v = ob->_v)
1654 #define TFMCPY3D(_v) copy_v3_v3(obtfm->_v, ob->_v)
1655 #define TFMCPY4D(_v) copy_v4_v4(obtfm->_v, ob->_v)
1656
1657         TFMCPY3D(loc);
1658         TFMCPY3D(dloc);
1659         TFMCPY3D(size);
1660         TFMCPY3D(dscale);
1661         TFMCPY3D(rot);
1662         TFMCPY3D(drot);
1663         TFMCPY4D(quat);
1664         TFMCPY4D(dquat);
1665         TFMCPY3D(rotAxis);
1666         TFMCPY3D(drotAxis);
1667         TFMCPY(rotAngle);
1668         TFMCPY(drotAngle);
1669
1670 #undef TFMCPY
1671 #undef TFMCPY3D
1672 #undef TFMCPY4D
1673
1674 }
1675
1676 void BKE_object_tfm_protected_restore(Object *ob,
1677                                       const ObjectTfmProtectedChannels *obtfm,
1678                                       const short protectflag)
1679 {
1680         unsigned int i;
1681
1682         for (i = 0; i < 3; i++) {
1683                 if (protectflag & (OB_LOCK_LOCX << i)) {
1684                         ob->loc[i] =  obtfm->loc[i];
1685                         ob->dloc[i] = obtfm->dloc[i];
1686                 }
1687
1688                 if (protectflag & (OB_LOCK_SCALEX << i)) {
1689                         ob->size[i] =  obtfm->size[i];
1690                         ob->dscale[i] = obtfm->dscale[i];
1691                 }
1692
1693                 if (protectflag & (OB_LOCK_ROTX << i)) {
1694                         ob->rot[i] =  obtfm->rot[i];
1695                         ob->drot[i] = obtfm->drot[i];
1696
1697                         ob->quat[i + 1] =  obtfm->quat[i + 1];
1698                         ob->dquat[i + 1] = obtfm->dquat[i + 1];
1699
1700                         ob->rotAxis[i] =  obtfm->rotAxis[i];
1701                         ob->drotAxis[i] = obtfm->drotAxis[i];
1702                 }
1703         }
1704
1705         if ((protectflag & OB_LOCK_ROT4D) && (protectflag & OB_LOCK_ROTW)) {
1706                 ob->quat[0] =  obtfm->quat[0];
1707                 ob->dquat[0] = obtfm->dquat[0];
1708
1709                 ob->rotAngle =  obtfm->rotAngle;
1710                 ob->drotAngle = obtfm->drotAngle;
1711         }
1712 }
1713
1714 /* see BKE_pchan_apply_mat4() for the equivalent 'pchan' function */
1715 void BKE_object_apply_mat4(Object *ob, float mat[4][4], const bool use_compat, const bool use_parent)
1716 {
1717         float rot[3][3];
1718
1719         if (use_parent && ob->parent) {
1720                 float rmat[4][4], diff_mat[4][4], imat[4][4];
1721                 mul_m4_m4m4(diff_mat, ob->parent->obmat, ob->parentinv);
1722                 invert_m4_m4(imat, diff_mat);
1723                 mul_m4_m4m4(rmat, imat, mat); /* get the parent relative matrix */
1724                 BKE_object_apply_mat4(ob, rmat, use_compat, FALSE);
1725                 
1726                 /* same as below, use rmat rather than mat */
1727                 mat4_to_loc_rot_size(ob->loc, rot, ob->size, rmat);
1728                 BKE_object_mat3_to_rot(ob, rot, use_compat);
1729         }
1730         else {
1731                 mat4_to_loc_rot_size(ob->loc, rot, ob->size, mat);
1732                 BKE_object_mat3_to_rot(ob, rot, use_compat);
1733         }
1734         
1735         sub_v3_v3(ob->loc, ob->dloc);
1736
1737         if (ob->dscale[0] != 0.0f) ob->size[0] /= ob->dscale[0];
1738         if (ob->dscale[1] != 0.0f) ob->size[1] /= ob->dscale[1];
1739         if (ob->dscale[2] != 0.0f) ob->size[2] /= ob->dscale[2];
1740
1741         /* BKE_object_mat3_to_rot handles delta rotations */
1742 }
1743
1744 void BKE_object_to_mat3(Object *ob, float mat[3][3]) /* no parent */
1745 {
1746         float smat[3][3];
1747         float rmat[3][3];
1748         /*float q1[4];*/
1749         
1750         /* size */
1751         BKE_object_scale_to_mat3(ob, smat);
1752
1753         /* rot */
1754         BKE_object_rot_to_mat3(ob, rmat, TRUE);
1755         mul_m3_m3m3(mat, rmat, smat);
1756 }
1757
1758 void BKE_object_to_mat4(Object *ob, float mat[4][4])
1759 {
1760         float tmat[3][3];
1761         
1762         BKE_object_to_mat3(ob, tmat);
1763         
1764         copy_m4_m3(mat, tmat);
1765
1766         add_v3_v3v3(mat[3], ob->loc, ob->dloc);
1767 }
1768
1769 /* extern */
1770 int enable_cu_speed = 1;
1771
1772 static void ob_parcurve(Scene *scene, Object *ob, Object *par, float mat[4][4])
1773 {
1774         Curve *cu;
1775         float vec[4], dir[3], quat[4], radius, ctime;
1776         float timeoffs = 0.0, sf_orig = 0.0;
1777         
1778         unit_m4(mat);
1779         
1780         cu = par->data;
1781         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! */
1782                 BKE_displist_make_curveTypes(scene, par, 0);
1783         if (par->curve_cache->path == NULL) return;
1784         
1785         /* catch exceptions: feature for nla stride editing */
1786         if (ob->ipoflag & OB_DISABLE_PATH) {
1787                 ctime = 0.0f;
1788         }
1789         /* catch exceptions: curve paths used as a duplicator */
1790         else if (enable_cu_speed) {
1791                 /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated,
1792                  * but this will only work if it actually is animated... 
1793                  *
1794                  * we divide the curvetime calculated in the previous step by the length of the path, to get a time
1795                  * factor, which then gets clamped to lie within 0.0 - 1.0 range
1796                  */
1797                 if (IS_EQF(cu->pathlen, 0.0f) == 0)
1798                         ctime = cu->ctime / cu->pathlen;
1799                 else
1800                         ctime = cu->ctime;
1801
1802                 CLAMP(ctime, 0.0f, 1.0f);
1803         }
1804         else {
1805                 ctime = BKE_scene_frame_get(scene);
1806                 if (IS_EQF(cu->pathlen, 0.0f) == 0)
1807                         ctime /= cu->pathlen;
1808                 
1809                 CLAMP(ctime, 0.0f, 1.0f);
1810         }
1811         
1812         /* time calculus is correct, now apply distance offset */
1813         if (cu->flag & CU_OFFS_PATHDIST) {
1814                 ctime += timeoffs / par->curve_cache->path->totdist;
1815
1816                 /* restore */
1817                 SWAP(float, sf_orig, ob->sf);
1818         }
1819         
1820         
1821         /* vec: 4 items! */
1822         if (where_on_path(par, ctime, vec, dir, cu->flag & CU_FOLLOW ? quat : NULL, &radius, NULL)) {
1823
1824                 if (cu->flag & CU_FOLLOW) {
1825 #if 0
1826                         float si, q[4];
1827                         vec_to_quat(quat, dir, ob->trackflag, ob->upflag);
1828                         
1829                         /* the tilt */
1830                         normalize_v3(dir);
1831                         q[0] = cosf(0.5 * vec[3]);
1832                         si = sinf(0.5 * vec[3]);
1833                         q[1] = -si * dir[0];
1834                         q[2] = -si * dir[1];
1835                         q[3] = -si * dir[2];
1836                         mul_qt_qtqt(quat, q, quat);
1837 #else
1838                         quat_apply_track(quat, ob->trackflag, ob->upflag);
1839 #endif
1840                         normalize_qt(quat);
1841                         quat_to_mat4(mat, quat);
1842                 }
1843                 
1844                 if (cu->flag & CU_PATH_RADIUS) {
1845                         float tmat[4][4], rmat[4][4];
1846                         scale_m4_fl(tmat, radius);
1847                         mul_m4_m4m4(rmat, tmat, mat);
1848                         copy_m4_m4(mat, rmat);
1849                 }
1850
1851                 copy_v3_v3(mat[3], vec);
1852                 
1853         }
1854 }
1855
1856 static void ob_parbone(Object *ob, Object *par, float mat[4][4])
1857 {       
1858         bPoseChannel *pchan;
1859         float vec[3];
1860         
1861         if (par->type != OB_ARMATURE) {
1862                 unit_m4(mat);
1863                 return;
1864         }
1865         
1866         /* Make sure the bone is still valid */
1867         pchan = BKE_pose_channel_find_name(par->pose, ob->parsubstr);
1868         if (!pchan || !pchan->bone) {
1869                 printf("Object %s with Bone parent: bone %s doesn't exist\n", ob->id.name + 2, ob->parsubstr);
1870                 unit_m4(mat);
1871                 return;
1872         }
1873
1874         /* get bone transform */
1875         if (pchan->bone->flag & BONE_RELATIVE_PARENTING) {
1876                 /* the new option uses the root - expected bahaviour, but differs from old... */
1877                 /* XXX check on version patching? */
1878                 copy_m4_m4(mat, pchan->chan_mat);
1879         }
1880         else {
1881                 copy_m4_m4(mat, pchan->pose_mat);
1882
1883                 /* but for backwards compatibility, the child has to move to the tail */
1884                 copy_v3_v3(vec, mat[1]);
1885                 mul_v3_fl(vec, pchan->bone->length);
1886                 add_v3_v3(mat[3], vec);
1887         }
1888 }
1889
1890 static void give_parvert(Object *par, int nr, float vec[3])
1891 {
1892         BMEditMesh *em;
1893
1894         zero_v3(vec);
1895         
1896         if (par->type == OB_MESH) {
1897                 Mesh *me = par->data;
1898                 DerivedMesh *dm;
1899
1900                 em = me->edit_btmesh;
1901
1902 #if 0   /* this was bmesh only, better, evaluate why this was needed - campbell*/
1903                 if (em) {
1904                         BMVert *eve;
1905                         BMIter iter;
1906
1907                         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
1908                                 int *keyindex = CustomData_bmesh_get(&em->bm->vdata, eve->head.data, CD_SHAPE_KEYINDEX);
1909                                 
1910                                 if (keyindex && *keyindex == nr) {
1911                                         copy_v3_v3(vec, eve->co);
1912                                         break;
1913                                 }
1914                         }
1915                 }
1916 #endif
1917
1918                 dm = (em) ? em->derivedFinal : par->derivedFinal;
1919                         
1920                 if (dm) {
1921                         int count = 0;
1922                         int numVerts = dm->getNumVerts(dm);
1923
1924                         if (nr < numVerts) {
1925                                 MVert *mvert = dm->getVertArray(dm);
1926                                 int   *index = (int *)dm->getVertDataArray(dm, CD_ORIGINDEX);
1927                                 int i;
1928
1929                                 /* get the average of all verts with (original index == nr) */
1930                                 if (index) {
1931                                         for (i = 0; i < numVerts; i++) {
1932                                                 if (index[i] == nr) {
1933                                                         add_v3_v3(vec, mvert[i].co);
1934                                                         count++;
1935                                                 }
1936                                         }
1937                                 }
1938                                 else {
1939                                         if (nr < numVerts) {
1940                                                 add_v3_v3(vec, mvert[nr].co);
1941                                                 count++;
1942                                         }
1943                                 }
1944                         }
1945
1946                         if (count == 0) {
1947                                 /* keep as 0, 0, 0 */
1948                         }
1949                         else if (count > 0) {
1950                                 mul_v3_fl(vec, 1.0f / count);
1951                         }
1952                         else {
1953                                 /* use first index if its out of range */
1954                                 dm->getVertCo(dm, 0, vec);
1955                         }
1956                 }
1957                 else {
1958                         fprintf(stderr,
1959                                 "%s: DerivedMesh is needed to solve parenting, "
1960                                 "object position can be wrong now\n", __func__);
1961                 }
1962         }
1963         else if (ELEM(par->type, OB_CURVE, OB_SURF)) {
1964                 Curve *cu       = par->data;
1965                 ListBase *nurb  = BKE_curve_nurbs_get(cu);
1966
1967                 BKE_nurbList_index_get_co(nurb, nr, vec);
1968         }
1969         else if (par->type == OB_LATTICE) {
1970                 Lattice *latt  = par->data;
1971                 DispList *dl   = par->curve_cache ? BKE_displist_find(&par->curve_cache->disp, DL_VERTS) : NULL;
1972                 float (*co)[3] = dl ? (float (*)[3])dl->verts : NULL;
1973                 int tot;
1974
1975                 if (latt->editlatt) latt = latt->editlatt->latt;
1976
1977                 tot = latt->pntsu * latt->pntsv * latt->pntsw;
1978
1979                 /* ensure dl is correct size */
1980                 BLI_assert(dl == NULL || dl->nr == tot);
1981
1982                 if (nr < tot) {
1983                         if (co) {
1984                                 copy_v3_v3(vec, co[nr]);
1985                         }
1986                         else {
1987                                 copy_v3_v3(vec, latt->def[nr].vec);
1988                         }
1989                 }
1990         }
1991 }
1992
1993 static void ob_parvert3(Object *ob, Object *par, float mat[4][4])
1994 {
1995         float cmat[3][3], v1[3], v2[3], v3[3], q[4];
1996
1997         /* in local ob space */
1998         unit_m4(mat);
1999         
2000         if (ELEM4(par->type, OB_MESH, OB_SURF, OB_CURVE, OB_LATTICE)) {
2001                 
2002                 give_parvert(par, ob->par1, v1);
2003                 give_parvert(par, ob->par2, v2);
2004                 give_parvert(par, ob->par3, v3);
2005                                 
2006                 tri_to_quat(q, v1, v2, v3);
2007                 quat_to_mat3(cmat, q);
2008                 copy_m4_m3(mat, cmat);
2009                 
2010                 if (ob->type == OB_CURVE) {
2011                         copy_v3_v3(mat[3], v1);
2012                 }
2013                 else {
2014                         add_v3_v3v3(mat[3], v1, v2);
2015                         add_v3_v3(mat[3], v3);
2016                         mul_v3_fl(mat[3], 1.0f / 3.0f);
2017                 }
2018         }
2019 }
2020
2021 /**
2022  * \param r_originmat  Optional matrix that stores the space the object is in (without its own matrix applied)
2023  */
2024 static void solve_parenting(Scene *scene, Object *ob, Object *par, float obmat[4][4], float slowmat[4][4],
2025                             float r_originmat[3][3], const bool simul)
2026 {
2027         float totmat[4][4];
2028         float tmat[4][4];
2029         float locmat[4][4];
2030         float vec[3];
2031         int ok;
2032         
2033         BKE_object_to_mat4(ob, locmat);
2034         
2035         if (ob->partype & PARSLOW) copy_m4_m4(slowmat, obmat);
2036
2037         switch (ob->partype & PARTYPE) {
2038                 case PAROBJECT:
2039                         ok = 0;
2040                         if (par->type == OB_CURVE) {
2041                                 if (((Curve *)par->data)->flag & CU_PATH) {
2042                                         ob_parcurve(scene, ob, par, tmat);
2043                                         ok = 1;
2044                                 }
2045                         }
2046                         
2047                         if (ok) mul_serie_m4(totmat, par->obmat, tmat,
2048                                                  NULL, NULL, NULL, NULL, NULL, NULL);
2049                         else copy_m4_m4(totmat, par->obmat);
2050                         
2051                         break;
2052                 case PARBONE:
2053                         ob_parbone(ob, par, tmat);
2054                         mul_serie_m4(totmat, par->obmat, tmat,
2055                                      NULL, NULL, NULL, NULL, NULL, NULL);
2056                         break;
2057                 
2058                 case PARVERT1:
2059                         unit_m4(totmat);
2060                         if (simul) {
2061                                 copy_v3_v3(totmat[3], par->obmat[3]);
2062                         }
2063                         else {
2064                                 give_parvert(par, ob->par1, vec);
2065                                 mul_v3_m4v3(totmat[3], par->obmat, vec);
2066                         }
2067                         break;
2068                 case PARVERT3:
2069                         ob_parvert3(ob, par, tmat);
2070                         
2071                         mul_serie_m4(totmat, par->obmat, tmat,
2072                                      NULL, NULL, NULL, NULL, NULL, NULL);
2073                         break;
2074                 
2075                 case PARSKEL:
2076                         copy_m4_m4(totmat, par->obmat);
2077                         break;
2078         }
2079         
2080         /* total */
2081         mul_serie_m4(tmat, totmat, ob->parentinv,
2082                      NULL, NULL, NULL, NULL, NULL, NULL);
2083         mul_serie_m4(obmat, tmat, locmat,         
2084                      NULL, NULL, NULL, NULL, NULL, NULL);
2085         
2086         if (simul) {
2087
2088         }
2089         else {
2090                 if (r_originmat) {
2091                         /* usable originmat */
2092                         copy_m3_m4(r_originmat, tmat);
2093                 }
2094                 
2095                 /* origin, for help line */
2096                 if ((ob->partype & PARTYPE) == PARSKEL) {
2097                         copy_v3_v3(ob->orig, par->obmat[3]);
2098                 }
2099                 else {
2100                         copy_v3_v3(ob->orig, totmat[3]);
2101                 }
2102         }
2103 }
2104
2105 static int where_is_object_parslow(Object *ob, float obmat[4][4], float slowmat[4][4])
2106 {
2107         float *fp1, *fp2;
2108         float fac1, fac2;
2109         int a;
2110
2111         /* include framerate */
2112         fac1 = (1.0f / (1.0f + fabsf(ob->sf)) );
2113         if (fac1 >= 1.0f) return 0;
2114         fac2 = 1.0f - fac1;
2115
2116         fp1 = obmat[0];
2117         fp2 = slowmat[0];
2118         for (a = 0; a < 16; a++, fp1++, fp2++) {
2119                 fp1[0] = fac1 * fp1[0] + fac2 * fp2[0];
2120         }
2121
2122         return 1;
2123 }
2124
2125 /* note, scene is the active scene while actual_scene is the scene the object resides in */
2126 void BKE_object_where_is_calc_time_ex(Scene *scene, Object *ob, float ctime,
2127                                       RigidBodyWorld *rbw, float r_originmat[3][3])
2128 {
2129         if (ob == NULL) return;
2130         
2131         /* execute drivers only, as animation has already been done */
2132         BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, ctime, ADT_RECALC_DRIVERS);
2133         
2134         if (ob->parent) {
2135                 Object *par = ob->parent;
2136                 float slowmat[4][4] = MAT4_UNITY;
2137                 
2138                 /* calculate parent matrix */
2139                 solve_parenting(scene, ob, par, ob->obmat, slowmat, r_originmat, false);
2140                 
2141                 /* "slow parent" is definitely not threadsafe, and may also give bad results jumping around 
2142                  * An old-fashioned hack which probably doesn't really cut it anymore
2143                  */
2144                 if (ob->partype & PARSLOW) {
2145                         if (!where_is_object_parslow(ob, ob->obmat, slowmat))
2146                                 return;
2147                 }
2148         }
2149         else {
2150                 BKE_object_to_mat4(ob, ob->obmat);
2151         }
2152
2153         /* try to fall back to the scene rigid body world if none given */
2154         rbw = rbw ? rbw : scene->rigidbody_world;
2155         /* read values pushed into RBO from sim/cache... */
2156         BKE_rigidbody_sync_transforms(rbw, ob, ctime);
2157         
2158         /* solve constraints */
2159         if (ob->constraints.first && !(ob->transflag & OB_NO_CONSTRAINTS)) {
2160                 bConstraintOb *cob;
2161                 
2162                 cob = BKE_constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2163                 BKE_solve_constraints(&ob->constraints, cob, ctime);
2164                 BKE_constraints_clear_evalob(cob);
2165         }
2166         
2167         /* set negative scale flag in object */
2168         if (is_negative_m4(ob->obmat)) ob->transflag |= OB_NEG_SCALE;
2169         else ob->transflag &= ~OB_NEG_SCALE;
2170 }
2171
2172 void BKE_object_where_is_calc_time(Scene *scene, Object *ob, float ctime)
2173 {
2174         BKE_object_where_is_calc_time_ex(scene, ob, ctime, NULL, NULL);
2175 }
2176
2177 /* get object transformation matrix without recalculating dependencies and
2178  * constraints -- assume dependencies are already solved by depsgraph.
2179  * no changes to object and it's parent would be done.
2180  * used for bundles orientation in 3d space relative to parented blender camera */
2181 void BKE_object_where_is_calc_mat4(Scene *scene, Object *ob, float obmat[4][4])
2182 {
2183         float slowmat[4][4] = MAT4_UNITY;
2184
2185         if (ob->parent) {
2186                 Object *par = ob->parent;
2187                 
2188                 solve_parenting(scene, ob, par, obmat, slowmat, NULL, true);
2189                 
2190                 if (ob->partype & PARSLOW)
2191                         where_is_object_parslow(ob, obmat, slowmat);
2192         }
2193         else {
2194                 BKE_object_to_mat4(ob, obmat);
2195         }
2196 }
2197
2198 void BKE_object_where_is_calc_ex(Scene *scene, RigidBodyWorld *rbw, Object *ob, float r_originmat[3][3])
2199 {
2200         BKE_object_where_is_calc_time_ex(scene, ob, BKE_scene_frame_get(scene), rbw, r_originmat);
2201 }
2202 void BKE_object_where_is_calc(Scene *scene, Object *ob)
2203 {
2204         BKE_object_where_is_calc_time_ex(scene, ob, BKE_scene_frame_get(scene), NULL, NULL);
2205 }
2206
2207 /* was written for the old game engine (until 2.04) */
2208 /* It seems that this function is only called
2209  * for a lamp that is the child of another object */
2210 void BKE_object_where_is_calc_simul(Scene *scene, Object *ob)
2211 {
2212         Object *par;
2213         float *fp1, *fp2;
2214         float slowmat[4][4];
2215         float fac1, fac2;
2216         int a;
2217         
2218         /* NO TIMEOFFS */
2219         if (ob->parent) {
2220                 par = ob->parent;
2221                 
2222                 solve_parenting(scene, ob, par, ob->obmat, slowmat, NULL, true);
2223                 
2224                 if (ob->partype & PARSLOW) {
2225                         fac1 = (float)(1.0 / (1.0 + fabs(ob->sf)));
2226                         fac2 = 1.0f - fac1;
2227                         fp1 = ob->obmat[0];
2228                         fp2 = slowmat[0];
2229                         for (a = 0; a < 16; a++, fp1++, fp2++) {
2230                                 fp1[0] = fac1 * fp1[0] + fac2 * fp2[0];
2231                         }
2232                 }
2233         }
2234         else {
2235                 BKE_object_to_mat4(ob, ob->obmat);
2236         }
2237         
2238         /* solve constraints */
2239         if (ob->constraints.first) {
2240                 bConstraintOb *cob;
2241                 
2242                 cob = BKE_constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2243                 BKE_solve_constraints(&ob->constraints, cob, BKE_scene_frame_get(scene));
2244                 BKE_constraints_clear_evalob(cob);
2245         }
2246 }
2247
2248 /* for calculation of the inverse parent transform, only used for editor */
2249 void BKE_object_workob_calc_parent(Scene *scene, Object *ob, Object *workob)
2250 {
2251         BKE_object_workob_clear(workob);
2252         
2253         unit_m4(workob->obmat);
2254         unit_m4(workob->parentinv);
2255         unit_m4(workob->constinv);
2256         workob->parent = ob->parent;
2257
2258         workob->trackflag = ob->trackflag;
2259         workob->upflag = ob->upflag;
2260         
2261         workob->partype = ob->partype;
2262         workob->par1 = ob->par1;
2263         workob->par2 = ob->par2;
2264         workob->par3 = ob->par3;
2265
2266         workob->constraints.first = ob->constraints.first;
2267         workob->constraints.last = ob->constraints.last;
2268
2269         BLI_strncpy(workob->parsubstr, ob->parsubstr, sizeof(workob->parsubstr));
2270
2271         BKE_object_where_is_calc(scene, workob);
2272 }
2273
2274 BoundBox *BKE_boundbox_alloc_unit(void)
2275 {
2276         BoundBox *bb;
2277         const float min[3] = {-1.0f, -1.0f, -1.0f}, max[3] = {-1.0f, -1.0f, -1.0f};
2278
2279         bb = MEM_callocN(sizeof(BoundBox), "OB-BoundBox");
2280         BKE_boundbox_init_from_minmax(bb, min, max);
2281         
2282         return bb;
2283 }
2284
2285 void BKE_boundbox_init_from_minmax(BoundBox *bb, const float min[3], const float max[3])
2286 {
2287         bb->vec[0][0] = bb->vec[1][0] = bb->vec[2][0] = bb->vec[3][0] = min[0];
2288         bb->vec[4][0] = bb->vec[5][0] = bb->vec[6][0] = bb->vec[7][0] = max[0];
2289         
2290         bb->vec[0][1] = bb->vec[1][1] = bb->vec[4][1] = bb->vec[5][1] = min[1];
2291         bb->vec[2][1] = bb->vec[3][1] = bb->vec[6][1] = bb->vec[7][1] = max[1];
2292
2293         bb->vec[0][2] = bb->vec[3][2] = bb->vec[4][2] = bb->vec[7][2] = min[2];
2294         bb->vec[1][2] = bb->vec[2][2] = bb->vec[5][2] = bb->vec[6][2] = max[2];
2295 }
2296
2297 BoundBox *BKE_object_boundbox_get(Object *ob)
2298 {
2299         BoundBox *bb = NULL;
2300         
2301         if (ob->type == OB_MESH) {
2302                 bb = BKE_mesh_boundbox_get(ob);
2303         }
2304         else if (ELEM3(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2305                 bb = BKE_curve_boundbox_get(ob);
2306         }
2307         else if (ob->type == OB_MBALL) {
2308                 bb = ob->bb;
2309         }
2310         return bb;
2311 }
2312
2313 /* used to temporally disable/enable boundbox */
2314 void BKE_object_boundbox_flag(Object *ob, int flag, int set)
2315 {
2316         BoundBox *bb = BKE_object_boundbox_get(ob);
2317         if (bb) {
2318                 if (set) bb->flag |= flag;
2319                 else bb->flag &= ~flag;
2320         }
2321 }
2322
2323 void BKE_object_dimensions_get(Object *ob, float vec[3])
2324 {
2325         BoundBox *bb = NULL;
2326         
2327         bb = BKE_object_boundbox_get(ob);
2328         if (bb) {
2329                 float scale[3];
2330                 
2331                 mat4_to_size(scale, ob->obmat);
2332                 
2333                 vec[0] = fabsf(scale[0]) * (bb->vec[4][0] - bb->vec[0][0]);
2334                 vec[1] = fabsf(scale[1]) * (bb->vec[2][1] - bb->vec[0][1]);
2335                 vec[2] = fabsf(scale[2]) * (bb->vec[1][2] - bb->vec[0][2]);
2336         }
2337         else {
2338                 zero_v3(vec);
2339         }
2340 }
2341
2342 void BKE_object_dimensions_set(Object *ob, const float *value)
2343 {
2344         BoundBox *bb = NULL;
2345         
2346         bb = BKE_object_boundbox_get(ob);
2347         if (bb) {
2348                 float scale[3], len[3];
2349                 
2350                 mat4_to_size(scale, ob->obmat);
2351                 
2352                 len[0] = bb->vec[4][0] - bb->vec[0][0];
2353                 len[1] = bb->vec[2][1] - bb->vec[0][1];
2354                 len[2] = bb->vec[1][2] - bb->vec[0][2];
2355                 
2356                 if (len[0] > 0.f) ob->size[0] = value[0] / len[0];
2357                 if (len[1] > 0.f) ob->size[1] = value[1] / len[1];
2358                 if (len[2] > 0.f) ob->size[2] = value[2] / len[2];
2359         }
2360 }
2361
2362 void BKE_object_minmax(Object *ob, float min_r[3], float max_r[3], const bool use_hidden)
2363 {
2364         BoundBox bb;
2365         float vec[3];
2366         int a;
2367         bool change = false;
2368         
2369         switch (ob->type) {
2370                 case OB_CURVE:
2371                 case OB_FONT:
2372                 case OB_SURF:
2373                 {
2374                         bb = *BKE_curve_boundbox_get(ob);
2375
2376                         for (a = 0; a < 8; a++) {
2377                                 mul_m4_v3(ob->obmat, bb.vec[a]);
2378                                 minmax_v3v3_v3(min_r, max_r, bb.vec[a]);
2379                         }
2380                         change = TRUE;
2381                 }
2382                 break;
2383                 case OB_LATTICE:
2384                 {
2385                         Lattice *lt = ob->data;
2386                         BPoint *bp = lt->def;
2387                         int u, v, w;
2388
2389                         for (w = 0; w < lt->pntsw; w++) {
2390                                 for (v = 0; v < lt->pntsv; v++) {
2391                                         for (u = 0; u < lt->pntsu; u++, bp++) {
2392                                                 mul_v3_m4v3(vec, ob->obmat, bp->vec);
2393                                                 minmax_v3v3_v3(min_r, max_r, vec);
2394                                         }
2395                                 }
2396                         }
2397                         change = TRUE;
2398                 }
2399                 break;
2400                 case OB_ARMATURE:
2401                         if (ob->pose) {
2402                                 bArmature *arm = ob->data;
2403                                 bPoseChannel *pchan;
2404
2405                                 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2406                                         /* XXX pchan->bone may be NULL for duplicated bones, see duplicateEditBoneObjects() comment
2407                                          *     (editarmature.c:2592)... Skip in this case too! */
2408                                         if (pchan->bone && !((use_hidden == FALSE) && (PBONE_VISIBLE(arm, pchan->bone) == FALSE))) {
2409                                                 mul_v3_m4v3(vec, ob->obmat, pchan->pose_head);
2410                                                 minmax_v3v3_v3(min_r, max_r, vec);
2411                                                 mul_v3_m4v3(vec, ob->obmat, pchan->pose_tail);
2412                                                 minmax_v3v3_v3(min_r, max_r, vec);
2413
2414                                                 change = TRUE;
2415                                         }
2416                                 }
2417                         }
2418                         break;
2419                 case OB_MESH:
2420                 {
2421                         Mesh *me = BKE_mesh_from_object(ob);
2422
2423                         if (me) {
2424                                 bb = *BKE_mesh_boundbox_get(ob);
2425
2426                                 for (a = 0; a < 8; a++) {
2427                                         mul_m4_v3(ob->obmat, bb.vec[a]);
2428                                         minmax_v3v3_v3(min_r, max_r, bb.vec[a]);
2429                                 }
2430                                 change = TRUE;
2431                         }
2432                 }
2433                 break;
2434                 case OB_MBALL:
2435                 {
2436                         float ob_min[3], ob_max[3];
2437
2438                         change = BKE_mball_minmax_ex(ob->data, ob_min, ob_max, ob->obmat, 0);
2439                         if (change) {
2440                                 minmax_v3v3_v3(min_r, max_r, ob_min);
2441                                 minmax_v3v3_v3(min_r, max_r, ob_max);
2442                         }
2443                         break;
2444                 }
2445         }
2446
2447         if (change == FALSE) {
2448                 float size[3];
2449
2450                 copy_v3_v3(size, ob->size);
2451                 if (ob->type == OB_EMPTY) {
2452                         mul_v3_fl(size, ob->empty_drawsize);
2453                 }
2454
2455                 minmax_v3v3_v3(min_r, max_r, ob->obmat[3]);
2456
2457                 copy_v3_v3(vec, ob->obmat[3]);
2458                 add_v3_v3(vec, size);
2459                 minmax_v3v3_v3(min_r, max_r, vec);
2460
2461                 copy_v3_v3(vec, ob->obmat[3]);
2462                 sub_v3_v3(vec, size);
2463                 minmax_v3v3_v3(min_r, max_r, vec);
2464         }
2465 }
2466
2467 bool BKE_object_minmax_dupli(Scene *scene, Object *ob, float r_min[3], float r_max[3], const bool use_hidden)
2468 {
2469         bool ok = false;
2470         if ((ob->transflag & OB_DUPLI) == 0) {
2471                 return ok;
2472         }
2473         else {
2474                 ListBase *lb;
2475                 DupliObject *dob;
2476                 
2477                 lb = object_duplilist(scene, ob, FALSE);
2478                 for (dob = lb->first; dob; dob = dob->next) {
2479                         if ((use_hidden == false) && (dob->no_draw != 0)) {
2480                                 /* pass */
2481                         }
2482                         else {
2483                                 BoundBox *bb = BKE_object_boundbox_get(dob->ob);
2484
2485                                 if (bb) {
2486                                         int i;
2487                                         for (i = 0; i < 8; i++) {
2488                                                 float vec[3];
2489                                                 mul_v3_m4v3(vec, dob->mat, bb->vec[i]);
2490                                                 minmax_v3v3_v3(r_min, r_max, vec);
2491                                         }
2492
2493                                         ok = TRUE;
2494                                 }
2495                         }
2496                 }
2497                 free_object_duplilist(lb);  /* does restore */
2498         }
2499
2500         return ok;
2501 }
2502
2503 void BKE_object_foreach_display_point(
2504         Object *ob, float obmat[4][4],
2505         void (*func_cb)(const float[3], void *), void *user_data)
2506 {
2507         float co[3];
2508
2509         if (ob->derivedFinal) {
2510                 DerivedMesh *dm = ob->derivedFinal;
2511                 MVert *mv = dm->getVertArray(dm);
2512                 int totvert = dm->getNumVerts(dm);
2513                 int i;
2514
2515                 for (i = 0; i < totvert; i++, mv++) {
2516                         mul_v3_m4v3(co, obmat, mv->co);
2517                         func_cb(co, user_data);
2518                 }
2519         }
2520         else if (ob->curve_cache && ob->curve_cache->disp.first) {
2521                 DispList *dl;
2522
2523                 for (dl = ob->curve_cache->disp.first; dl; dl = dl->next) {
2524                         float *v3 = dl->verts;
2525                         int totvert = dl->nr;
2526                         int i;
2527
2528                         for (i = 0; i < totvert; i++, v3 += 3) {
2529                                 mul_v3_m4v3(co, obmat, v3);
2530                                 func_cb(co, user_data);
2531                         }
2532                 }
2533         }
2534 }
2535
2536 void BKE_scene_foreach_display_point(
2537         Scene *scene, View3D *v3d, const short flag,
2538         void (*func_cb)(const float[3], void *), void *user_data)
2539 {
2540         Base *base;
2541         Object *ob;
2542
2543         for (base = FIRSTBASE; base; base = base->next) {
2544                 if (BASE_VISIBLE(v3d, base) && (base->flag & flag) == flag) {
2545                         ob = base->object;
2546
2547                         if ((ob->transflag & OB_DUPLI) == 0) {
2548                                 BKE_object_foreach_display_point(ob, ob->obmat, func_cb, user_data);
2549                         }
2550                         else {
2551                                 ListBase *lb;
2552                                 DupliObject *dob;
2553
2554                                 lb = object_duplilist(scene, ob, FALSE);
2555                                 for (dob = lb->first; dob; dob = dob->next) {
2556                                         if (dob->no_draw == 0) {
2557                                                 BKE_object_foreach_display_point(dob->ob, dob->mat, func_cb, user_data);
2558                                         }
2559                                 }
2560                                 free_object_duplilist(lb);  /* does restore */
2561                         }
2562                 }
2563         }
2564 }
2565
2566 /* copied from DNA_object_types.h */
2567 typedef struct ObTfmBack {
2568         float loc[3], dloc[3], orig[3];
2569         float size[3], dscale[3];   /* scale and delta scale */
2570         float rot[3], drot[3];      /* euler rotation */
2571         float quat[4], dquat[4];    /* quaternion rotation */
2572         float rotAxis[3], drotAxis[3];  /* axis angle rotation - axis part */
2573         float rotAngle, drotAngle;  /* axis angle rotation - angle part */
2574         float obmat[4][4];      /* final worldspace matrix with constraints & animsys applied */
2575         float parentinv[4][4]; /* inverse result of parent, so that object doesn't 'stick' to parent */
2576         float constinv[4][4]; /* inverse result of constraints. doesn't include effect of parent or object local transform */
2577         float imat[4][4];   /* inverse matrix of 'obmat' for during render, old game engine, temporally: ipokeys of transform  */
2578 } ObTfmBack;
2579
2580 void *BKE_object_tfm_backup(Object *ob)
2581 {
2582         ObTfmBack *obtfm = MEM_mallocN(sizeof(ObTfmBack), "ObTfmBack");
2583         copy_v3_v3(obtfm->loc, ob->loc);
2584         copy_v3_v3(obtfm->dloc, ob->dloc);
2585         copy_v3_v3(obtfm->orig, ob->orig);
2586         copy_v3_v3(obtfm->size, ob->size);
2587         copy_v3_v3(obtfm->dscale, ob->dscale);
2588         copy_v3_v3(obtfm->rot, ob->rot);
2589         copy_v3_v3(obtfm->drot, ob->drot);
2590         copy_qt_qt(obtfm->quat, ob->quat);
2591         copy_qt_qt(obtfm->dquat, ob->dquat);
2592         copy_v3_v3(obtfm->rotAxis, ob->rotAxis);
2593         copy_v3_v3(obtfm->drotAxis, ob->drotAxis);
2594         obtfm->rotAngle = ob->rotAngle;
2595         obtfm->drotAngle = ob->drotAngle;
2596         copy_m4_m4(obtfm->obmat, ob->obmat);
2597         copy_m4_m4(obtfm->parentinv, ob->parentinv);
2598         copy_m4_m4(obtfm->constinv, ob->constinv);
2599         copy_m4_m4(obtfm->imat, ob->imat);
2600
2601         return (void *)obtfm;
2602 }
2603
2604 void BKE_object_tfm_restore(Object *ob, void *obtfm_pt)
2605 {
2606         ObTfmBack *obtfm = (ObTfmBack *)obtfm_pt;
2607         copy_v3_v3(ob->loc, obtfm->loc);
2608         copy_v3_v3(ob->dloc, obtfm->dloc);
2609         copy_v3_v3(ob->orig, obtfm->orig);
2610         copy_v3_v3(ob->size, obtfm->size);
2611         copy_v3_v3(ob->dscale, obtfm->dscale);
2612         copy_v3_v3(ob->rot, obtfm->rot);
2613         copy_v3_v3(ob->drot, obtfm->drot);
2614         copy_qt_qt(ob->quat, obtfm->quat);
2615         copy_qt_qt(ob->dquat, obtfm->dquat);
2616         copy_v3_v3(ob->rotAxis, obtfm->rotAxis);
2617         copy_v3_v3(ob->drotAxis, obtfm->drotAxis);
2618         ob->rotAngle = obtfm->rotAngle;
2619         ob->drotAngle = obtfm->drotAngle;
2620         copy_m4_m4(ob->obmat, obtfm->obmat);
2621         copy_m4_m4(ob->parentinv, obtfm->parentinv);
2622         copy_m4_m4(ob->constinv, obtfm->constinv);
2623         copy_m4_m4(ob->imat, obtfm->imat);
2624 }
2625
2626 bool BKE_object_parent_loop_check(const Object *par, const Object *ob)
2627 {
2628         /* test if 'ob' is a parent somewhere in par's parents */
2629         if (par == NULL) return false;
2630         if (ob == par) return true;
2631         return BKE_object_parent_loop_check(par->parent, ob);
2632 }
2633
2634 /* proxy rule: lib_object->proxy_from == the one we borrow from, only set temporal and cleared here */
2635 /*           local_object->proxy      == pointer to library object, saved in files and read */
2636
2637 /* function below is polluted with proxy exceptions, cleanup will follow! */
2638
2639 /* the main object update call, for object matrix, constraints, keys and displist (modifiers) */
2640 /* requires flags to be set! */
2641 /* Ideally we shouldn't have to pass the rigid body world, but need bigger restructuring to avoid id */
2642 void BKE_object_handle_update_ex(Scene *scene, Object *ob,
2643                                  RigidBodyWorld *rbw)
2644 {
2645         if (ob->recalc & OB_RECALC_ALL) {
2646                 /* speed optimization for animation lookups */
2647                 if (ob->pose)
2648                         BKE_pose_channels_hash_make(ob->pose);
2649
2650                 if (ob->recalc & OB_RECALC_DATA) {
2651                         if (ob->type == OB_ARMATURE) {
2652                                 /* this happens for reading old files and to match library armatures
2653                                  * with poses we do it ahead of BKE_object_where_is_calc to ensure animation
2654                                  * is evaluated on the rebuilt pose, otherwise we get incorrect poses
2655                                  * on file load */
2656                                 if (ob->pose == NULL || (ob->pose->flag & POSE_RECALC))
2657                                         BKE_pose_rebuild(ob, ob->data);
2658                         }
2659                 }
2660
2661                 /* XXX new animsys warning: depsgraph tag OB_RECALC_DATA should not skip drivers, 
2662                  * which is only in BKE_object_where_is_calc now */
2663                 /* XXX: should this case be OB_RECALC_OB instead? */
2664                 if (ob->recalc & OB_RECALC_ALL) {
2665                         
2666                         if (G.debug & G_DEBUG)
2667                                 printf("recalcob %s\n", ob->id.name + 2);
2668                         
2669                         /* handle proxy copy for target */
2670                         if (ob->id.lib && ob->proxy_from) {
2671                                 // printf("ob proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2672                                 if (ob->proxy_from->proxy_group) { /* transform proxy into group space */
2673                                         Object *obg = ob->proxy_from->proxy_group;
2674                                         invert_m4_m4(obg->imat, obg->obmat);
2675                                         mul_m4_m4m4(ob->obmat, obg->imat, ob->proxy_from->obmat);
2676                                         if (obg->dup_group) { /* should always be true */
2677                                                 add_v3_v3(ob->obmat[3], obg->dup_group->dupli_ofs);
2678                                         }
2679                                 }
2680                                 else
2681                                         copy_m4_m4(ob->obmat, ob->proxy_from->obmat);
2682                         }
2683                         else
2684                                 BKE_object_where_is_calc_ex(scene, rbw, ob, NULL);
2685                 }
2686                 
2687                 if (ob->recalc & OB_RECALC_DATA) {
2688                         ID *data_id = (ID *)ob->data;
2689                         AnimData *adt = BKE_animdata_from_id(data_id);
2690                         Key *key;
2691                         float ctime = BKE_scene_frame_get(scene);
2692                         
2693                         if (G.debug & G_DEBUG)
2694                                 printf("recalcdata %s\n", ob->id.name + 2);
2695
2696                         if (adt) {
2697                                 /* evaluate drivers - datalevel */
2698                                 /* XXX: for mesh types, should we push this to derivedmesh instead? */
2699                                 BKE_animsys_evaluate_animdata(scene, data_id, adt, ctime, ADT_RECALC_DRIVERS);
2700                         }
2701                         
2702                         key = BKE_key_from_object(ob);
2703                         if (key && key->block.first) {
2704                                 if (!(ob->shapeflag & OB_SHAPE_LOCK))
2705                                         BKE_animsys_evaluate_animdata(scene, &key->id, key->adt, ctime, ADT_RECALC_DRIVERS);
2706                         }
2707
2708                         /* includes all keys and modifiers */
2709                         switch (ob->type) {
2710                                 case OB_MESH:
2711                                 {
2712 #if 0               // XXX, comment for 2.56a release, background wont set 'scene->customdata_mask'
2713                                         BMEditMesh *em = (ob == scene->obedit) ? BKE_editmesh_from_object(ob) : NULL;
2714                                         BLI_assert((scene->customdata_mask & CD_MASK_BAREMESH) == CD_MASK_BAREMESH);
2715                                         if (em) {
2716                                                 makeDerivedMesh(scene, ob, em,  scene->customdata_mask, 0); /* was CD_MASK_BAREMESH */
2717                                         }
2718                                         else {
2719                                                 makeDerivedMesh(scene, ob, NULL, scene->customdata_mask, 0);
2720                                         }
2721
2722 #else               /* ensure CD_MASK_BAREMESH for now */
2723                                         BMEditMesh *em = (ob == scene->obedit) ? BKE_editmesh_from_object(ob) : NULL;
2724                                         uint64_t data_mask = scene->customdata_mask | CD_MASK_BAREMESH;
2725                                         if (em) {
2726                                                 makeDerivedMesh(scene, ob, em,  data_mask, 0); /* was CD_MASK_BAREMESH */
2727                                         }
2728                                         else {
2729                                                 makeDerivedMesh(scene, ob, NULL, data_mask, 0);
2730                                         }
2731 #endif
2732
2733                                 }
2734                                 break;
2735
2736                                 case OB_ARMATURE:
2737                                         if (ob->id.lib && ob->proxy_from) {
2738                                                 if (BKE_pose_copy_result(ob->pose, ob->proxy_from->pose) == false) {
2739                                                         printf("Proxy copy error, lib Object: %s proxy Object: %s\n",
2740                                                                ob->id.name + 2, ob->proxy_from->id.name + 2);
2741                                                 }
2742                                         }
2743                                         else {
2744                                                 BKE_pose_where_is(scene, ob);
2745                                         }
2746                                         break;
2747
2748                                 case OB_MBALL:
2749                                         BKE_displist_make_mball(scene, ob);
2750                                         break;
2751
2752                                 case OB_CURVE:
2753                                 case OB_SURF:
2754                                 case OB_FONT:
2755                                         BKE_displist_make_curveTypes(scene, ob, 0);
2756                                         break;
2757                                 
2758                                 case OB_LATTICE:
2759                                         BKE_lattice_modifiers_calc(scene, ob);
2760                                         break;
2761                         }
2762                         
2763                         /* related materials */
2764                         /* XXX: without depsgraph tagging, this will always need to be run, which will be slow! 
2765                          * However, not doing anything (or trying to hack around this lack) is not an option 
2766                          * anymore, especially due to Cycles [#31834] 
2767                          */
2768                         if (ob->totcol) {
2769                                 int a;
2770                                 
2771                                 for (a = 1; a <= ob->totcol; a++) {
2772                                         Material *ma = give_current_material(ob, a);
2773                                         
2774                                         if (ma) {
2775                                                 /* recursively update drivers for this material */
2776                                                 material_drivers_update(scene, ma, ctime);
2777                                         }
2778                                 }
2779                         }
2780                         else if (ob->type == OB_LAMP)
2781                                 lamp_drivers_update(scene, ob->data, ctime);
2782                         
2783                         /* particles */
2784                         if (ob->particlesystem.first) {
2785                                 ParticleSystem *tpsys, *psys;
2786                                 DerivedMesh *dm;
2787                                 ob->transflag &= ~OB_DUPLIPARTS;
2788                                 
2789                                 psys = ob->particlesystem.first;
2790                                 while (psys) {
2791                                         if (psys_check_enabled(ob, psys)) {
2792                                                 /* check use of dupli objects here */
2793                                                 if (psys->part && (psys->part->draw_as == PART_DRAW_REND || G.is_rendering) &&
2794                                                     ((psys->part->ren_as == PART_DRAW_OB && psys->part->dup_ob) ||
2795                                                      (psys->part->ren_as == PART_DRAW_GR && psys->part->dup_group)))
2796                                                 {
2797                                                         ob->transflag |= OB_DUPLIPARTS;
2798                                                 }
2799
2800                                                 particle_system_update(scene, ob, psys);
2801                                                 psys = psys->next;
2802                                         }
2803                                         else if (psys->flag & PSYS_DELETE) {
2804                                                 tpsys = psys->next;
2805                                                 BLI_remlink(&ob->particlesystem, psys);
2806                                                 psys_free(ob, psys);
2807                                                 psys = tpsys;
2808                                         }
2809                                         else
2810                                                 psys = psys->next;
2811                                 }
2812
2813                                 if (G.is_rendering && ob->transflag & OB_DUPLIPARTS) {
2814                                         /* this is to make sure we get render level duplis in groups:
2815                                          * the derivedmesh must be created before init_render_mesh,
2816                                          * since object_duplilist does dupliparticles before that */
2817                                         dm = mesh_create_derived_render(scene, ob, CD_MASK_BAREMESH | CD_MASK_MTFACE | CD_MASK_MCOL);
2818                                         dm->release(dm);
2819
2820                                         for (psys = ob->particlesystem.first; psys; psys = psys->next)
2821                                                 psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated;
2822                                 }
2823                         }
2824                         
2825                         /* quick cache removed */
2826                 }
2827
2828                 /* the no-group proxy case, we call update */
2829                 if (ob->proxy && ob->proxy_group == NULL) {
2830                         /* set pointer in library proxy target, for copying, but restore it */
2831                         ob->proxy->proxy_from = ob;
2832                         // printf("call update, lib ob %s proxy %s\n", ob->proxy->id.name, ob->id.name);
2833                         BKE_object_handle_update(scene, ob->proxy);
2834                 }
2835         
2836                 ob->recalc &= ~OB_RECALC_ALL;
2837         }
2838
2839         /* the case when this is a group proxy, object_update is called in group.c */
2840         if (ob->proxy) {
2841                 ob->proxy->proxy_from = ob;
2842                 // printf("set proxy pointer for later group stuff %s\n", ob->id.name);
2843         }
2844 }
2845 /* WARNING: "scene" here may not be the scene object actually resides in. 
2846  * When dealing with background-sets, "scene" is actually the active scene.
2847  * e.g. "scene" <-- set 1 <-- set 2 ("ob" lives here) <-- set 3 <-- ... <-- set n
2848  * rigid bodies depend on their world so use BKE_object_handle_update_ex() to also pass along the corrent rigid body world
2849  */
2850 void BKE_object_handle_update(Scene *scene, Object *ob)
2851 {
2852         BKE_object_handle_update_ex(scene, ob, NULL);
2853 }
2854
2855 void BKE_object_sculpt_modifiers_changed(Object *ob)
2856 {
2857         SculptSession *ss = ob->sculpt;
2858
2859         if (ss) {
2860                 if (!ss->cache) {
2861                         /* we free pbvh on changes, except during sculpt since it can't deal with
2862                          * changing PVBH node organization, we hope topology does not change in
2863                          * the meantime .. weak */
2864                         if (ss->pbvh) {
2865                                 BKE_pbvh_free(ss->pbvh);
2866                                 ss->pbvh = NULL;
2867                         }
2868
2869                         free_sculptsession_deformMats(ob->sculpt);
2870                 }
2871                 else {
2872                         PBVHNode **nodes;
2873                         int n, totnode;
2874
2875                         BKE_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode);
2876
2877                         for (n = 0; n < totnode; n++)
2878                                 BKE_pbvh_node_mark_update(nodes[n]);
2879
2880                         MEM_freeN(nodes);
2881                 }
2882         }
2883 }
2884
2885 int BKE_object_obdata_texspace_get(Object *ob, short **r_texflag, float **r_loc, float **r_size, float **r_rot)
2886 {
2887         
2888         if (ob->data == NULL)
2889                 return 0;
2890         
2891         switch (GS(((ID *)ob->data)->name)) {
2892                 case ID_ME:
2893                 {
2894                         Mesh *me = ob->data;
2895                         if (r_texflag) *r_texflag = &me->texflag;
2896                         if (r_loc) *r_loc = me->loc;
2897                         if (r_size) *r_size = me->size;
2898                         if (r_rot) *r_rot = me->rot;
2899                         break;
2900                 }
2901                 case ID_CU:
2902                 {
2903                         Curve *cu = ob->data;
2904                         if (r_texflag) *r_texflag = &cu->texflag;
2905                         if (r_loc) *r_loc = cu->loc;
2906                         if (r_size) *r_size = cu->size;
2907                         if (r_rot) *r_rot = cu->rot;
2908                         break;
2909                 }
2910                 case ID_MB:
2911                 {
2912                         MetaBall *mb = ob->data;
2913                         if (r_texflag) *r_texflag = &mb->texflag;
2914                         if (r_loc) *r_loc = mb->loc;
2915                         if (r_size) *r_size = mb->size;
2916                         if (r_rot) *r_rot = mb->rot;
2917                         break;
2918                 }
2919                 default:
2920                         return 0;
2921         }
2922         return 1;
2923 }
2924
2925 /*
2926  * Test a bounding box for ray intersection
2927  * assumes the ray is already local to the boundbox space
2928  */
2929 bool BKE_boundbox_ray_hit_check(struct BoundBox *bb, const float ray_start[3], const float ray_normal[3])
2930 {
2931         const int triangle_indexes[12][3] = {
2932             {0, 1, 2}, {0, 2, 3},
2933             {3, 2, 6}, {3, 6, 7},
2934             {1, 2, 6}, {1, 6, 5},
2935             {5, 6, 7}, {4, 5, 7},
2936             {0, 3, 7}, {0, 4, 7},
2937             {0, 1, 5}, {0, 4, 5}};
2938
2939         bool result = false;
2940         int i;
2941         
2942         for (i = 0; i < 12 && result == 0; i++) {
2943                 float lambda;
2944                 int v1, v2, v3;
2945                 v1 = triangle_indexes[i][0];
2946                 v2 = triangle_indexes[i][1];
2947                 v3 = triangle_indexes[i][2];
2948                 result = isect_ray_tri_v3(ray_start, ray_normal, bb->vec[v1], bb->vec[v2], bb->vec[v3], &lambda, NULL);
2949         }
2950         
2951         return result;
2952 }
2953
2954 static int pc_cmp(void *a, void *b)
2955 {
2956         LinkData *ad = a, *bd = b;
2957         if (GET_INT_FROM_POINTER(ad->data) > GET_INT_FROM_POINTER(bd->data))
2958                 return 1;
2959         else return 0;
2960 }
2961
2962 int BKE_object_insert_ptcache(Object *ob) 
2963 {
2964         LinkData *link = NULL;
2965         int i = 0;
2966
2967         BLI_sortlist(&ob->pc_ids, pc_cmp);
2968
2969         for (link = ob->pc_ids.first, i = 0; link; link = link->next, i++) {
2970                 int index = GET_INT_FROM_POINTER(link->data);
2971
2972                 if (i < index)
2973                         break;
2974         }
2975
2976         link = MEM_callocN(sizeof(LinkData), "PCLink");
2977         link->data = SET_INT_IN_POINTER(i);
2978         BLI_addtail(&ob->pc_ids, link);
2979
2980         return i;
2981 }
2982
2983 #if 0
2984 static int pc_findindex(ListBase *listbase, int index)
2985 {
2986         LinkData *link = NULL;
2987         int number = 0;
2988         
2989         if (listbase == NULL) return -1;
2990         
2991         link = listbase->first;
2992         while (link) {
2993                 if ((int)link->data == index)
2994                         return number;
2995                 
2996                 number++;
2997                 link = link->next;
2998         }
2999         
3000         return -1;
3001 }
3002
3003 void object_delete_ptcache(Object *ob, int index) 
3004 {
3005         int list_index = pc_findindex(&ob->pc_ids, index);
3006         LinkData *link = BLI_findlink(&ob->pc_ids, list_index);
3007         BLI_freelinkN(&ob->pc_ids, link);
3008 }
3009 #endif
3010
3011 /* shape key utility function */
3012
3013 /************************* Mesh ************************/
3014 static KeyBlock *insert_meshkey(Scene *scene, Object *ob, const char *name, int from_mix)
3015 {
3016         Mesh *me = ob->data;
3017         Key *key = me->key;
3018         KeyBlock *kb;
3019         int newkey = 0;
3020
3021         if (key == NULL) {
3022                 key = me->key = BKE_key_add((ID *)me);
3023                 key->type = KEY_RELATIVE;
3024                 newkey = 1;
3025         }
3026
3027         if (newkey || from_mix == FALSE) {
3028                 /* create from mesh */
3029                 kb = BKE_keyblock_add_ctime(key, name, FALSE);
3030                 BKE_key_convert_from_mesh(me, kb);
3031         }
3032         else {
3033                 /* copy from current values */
3034                 int totelem;
3035                 float *data = BKE_key_evaluate_object(scene, ob, &totelem);
3036
3037                 /* create new block with prepared data */
3038                 kb = BKE_keyblock_add_ctime(key, name, FALSE);
3039                 kb->data = data;
3040                 kb->totelem = totelem;
3041         }
3042
3043         return kb;
3044 }
3045 /************************* Lattice ************************/
3046 static KeyBlock *insert_lattkey(Scene *scene, Object *ob, const char *name, int from_mix)
3047 {
3048         Lattice *lt = ob->data;
3049         Key *key = lt->key;
3050         KeyBlock *kb;
3051         int newkey = 0;
3052
3053         if (key == NULL) {
3054                 key = lt->key = BKE_key_add((ID *)lt);
3055                 key->type = KEY_RELATIVE;
3056                 newkey = 1;
3057         }
3058
3059         if (newkey || from_mix == FALSE) {
3060                 kb = BKE_keyblock_add_ctime(key, name, FALSE);
3061                 if (!newkey) {
3062                         KeyBlock *basekb = (KeyBlock *)key->block.first;
3063                         kb->data = MEM_dupallocN(basekb->data);
3064                         kb->totelem = basekb->totelem;
3065                 }
3066                 else {
3067                         BKE_key_convert_from_lattice(lt, kb);
3068                 }
3069         }
3070         else {
3071                 /* copy from current values */
3072                 int totelem;
3073                 float *data = BKE_key_evaluate_object(scene, ob, &totelem);
3074
3075