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