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