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