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