style cleanup
[blender.git] / source / blender / blenkernel / intern / object.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/object.c
29  *  \ingroup bke
30  */
31
32
33 #include <string.h>
34 #include <math.h>
35 #include <stdio.h>                      
36
37 #include "MEM_guardedalloc.h"
38
39 #include "DNA_anim_types.h"
40 #include "DNA_armature_types.h"
41 #include "DNA_camera_types.h"
42 #include "DNA_constraint_types.h"
43 #include "DNA_group_types.h"
44 #include "DNA_key_types.h"
45 #include "DNA_lattice_types.h"
46 #include "DNA_material_types.h"
47 #include "DNA_meta_types.h"
48 #include "DNA_mesh_types.h"
49 #include "DNA_meshdata_types.h"
50 #include "DNA_movieclip_types.h"
51 #include "DNA_scene_types.h"
52 #include "DNA_screen_types.h"
53 #include "DNA_sequence_types.h"
54 #include "DNA_smoke_types.h"
55 #include "DNA_sound_types.h"
56 #include "DNA_space_types.h"
57 #include "DNA_view3d_types.h"
58 #include "DNA_world_types.h"
59 #include "DNA_object_types.h"
60 #include "DNA_property_types.h"
61
62 #include "BLI_blenlib.h"
63 #include "BLI_math.h"
64 #include "BLI_utildefines.h"
65 #include "BLI_linklist.h"
66
67 #include "BKE_pbvh.h"
68 #include "BKE_main.h"
69 #include "BKE_global.h"
70 #include "BKE_idprop.h"
71 #include "BKE_armature.h"
72 #include "BKE_action.h"
73 #include "BKE_bullet.h"
74 #include "BKE_colortools.h"
75 #include "BKE_deform.h"
76 #include "BKE_DerivedMesh.h"
77 #include "BKE_animsys.h"
78 #include "BKE_anim.h"
79 #include "BKE_constraint.h"
80 #include "BKE_curve.h"
81 #include "BKE_displist.h"
82 #include "BKE_effect.h"
83 #include "BKE_fcurve.h"
84 #include "BKE_group.h"
85 #include "BKE_icons.h"
86 #include "BKE_key.h"
87 #include "BKE_lamp.h"
88 #include "BKE_lattice.h"
89 #include "BKE_library.h"
90 #include "BKE_mesh.h"
91 #include "BKE_tessmesh.h"
92 #include "BKE_mball.h"
93 #include "BKE_modifier.h"
94 #include "BKE_node.h"
95 #include "BKE_object.h"
96 #include "BKE_paint.h"
97 #include "BKE_particle.h"
98 #include "BKE_pointcache.h"
99 #include "BKE_property.h"
100 #include "BKE_sca.h"
101 #include "BKE_scene.h"
102 #include "BKE_sequencer.h"
103 #include "BKE_speaker.h"
104 #include "BKE_softbody.h"
105 #include "BKE_material.h"
106 #include "BKE_camera.h"
107
108 #ifdef WITH_MOD_FLUID
109 #include "LBM_fluidsim.h"
110 #endif
111
112 #ifdef WITH_PYTHON
113 #include "BPY_extern.h"
114 #endif
115
116 #include "GPU_material.h"
117
118 /* Local function protos */
119 float originmat[3][3];  /* after BKE_object_where_is_calc(), can be used in other functions (bad!) */
120
121 void BKE_object_workob_clear(Object *workob)
122 {
123         memset(workob, 0, sizeof(Object));
124         
125         workob->size[0] = workob->size[1] = workob->size[2] = 1.0f;
126         workob->dscale[0] = workob->dscale[1] = workob->dscale[2] = 1.0f;
127         workob->rotmode = ROT_MODE_EUL;
128 }
129
130 void BKE_object_update_base_layer(struct Scene *scene, Object *ob)
131 {
132         Base *base = scene->base.first;
133
134         while (base) {
135                 if (base->object == ob) base->lay = ob->lay;
136                 base = base->next;
137         }
138 }
139
140 void BKE_object_free_particlesystems(Object *ob)
141 {
142         while (ob->particlesystem.first) {
143                 ParticleSystem *psys = ob->particlesystem.first;
144                 
145                 BLI_remlink(&ob->particlesystem, psys);
146                 
147                 psys_free(ob, psys);
148         }
149 }
150
151 void BKE_object_free_softbody(Object *ob)
152 {
153         if (ob->soft) {
154                 sbFree(ob->soft);
155                 ob->soft = NULL;
156         }
157 }
158
159 void BKE_object_free_bulletsoftbody(Object *ob)
160 {
161         if (ob->bsoft) {
162                 bsbFree(ob->bsoft);
163                 ob->bsoft = NULL;
164         }
165 }
166
167 void BKE_object_free_modifiers(Object *ob)
168 {
169         while (ob->modifiers.first) {
170                 ModifierData *md = ob->modifiers.first;
171                 
172                 BLI_remlink(&ob->modifiers, md);
173                 
174                 modifier_free(md);
175         }
176
177         /* particle modifiers were freed, so free the particlesystems as well */
178         BKE_object_free_particlesystems(ob);
179
180         /* same for softbody */
181         BKE_object_free_softbody(ob);
182 }
183
184 int BKE_object_support_modifier_type_check(Object *ob, int modifier_type)
185 {
186         ModifierTypeInfo *mti;
187
188         mti = modifierType_getInfo(modifier_type);
189
190         if (!((mti->flags & eModifierTypeFlag_AcceptsCVs) ||
191               (ob->type == OB_MESH && (mti->flags & eModifierTypeFlag_AcceptsMesh))))
192         {
193                 return FALSE;
194         }
195
196         return TRUE;
197 }
198
199 void BKE_object_link_modifiers(struct Object *ob_dst, struct Object *ob_src)
200 {
201         ModifierData *md;
202         BKE_object_free_modifiers(ob_dst);
203
204         if (!ELEM5(ob_dst->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_LATTICE)) {
205                 /* only objects listed above can have modifiers and linking them to objects
206                  * which doesn't have modifiers stack is quite silly */
207                 return;
208         }
209
210         for (md = ob_src->modifiers.first; md; md = md->next) {
211                 ModifierData *nmd = NULL;
212
213                 if (ELEM4(md->type,
214                           eModifierType_Hook,
215                           eModifierType_Softbody,
216                           eModifierType_ParticleInstance,
217                           eModifierType_Collision))
218                 {
219                         continue;
220                 }
221
222                 if (!BKE_object_support_modifier_type_check(ob_dst, md->type))
223                         continue;
224
225                 nmd = modifier_new(md->type);
226                 BLI_strncpy(nmd->name, md->name, sizeof(nmd->name));
227                 modifier_copyData(md, nmd);
228                 BLI_addtail(&ob_dst->modifiers, nmd);
229                 modifier_unique_name(&ob_dst->modifiers, nmd);
230         }
231
232         BKE_object_copy_particlesystems(ob_dst, ob_src);
233         BKE_object_copy_softbody(ob_dst, ob_src);
234
235         /* TODO: smoke?, cloth? */
236 }
237
238 /* here we will collect all local displist stuff */
239 /* also (ab)used in depsgraph */
240 void BKE_object_free_display(Object *ob)
241 {
242         if (ob->derivedDeform) {
243                 ob->derivedDeform->needsFree = 1;
244                 ob->derivedDeform->release(ob->derivedDeform);
245                 ob->derivedDeform = NULL;
246         }
247         if (ob->derivedFinal) {
248                 ob->derivedFinal->needsFree = 1;
249                 ob->derivedFinal->release(ob->derivedFinal);
250                 ob->derivedFinal = NULL;
251         }
252         
253         BKE_displist_free(&ob->disp);
254 }
255
256 void free_sculptsession_deformMats(SculptSession *ss)
257 {
258         if (ss->orig_cos) MEM_freeN(ss->orig_cos);
259         if (ss->deform_cos) MEM_freeN(ss->deform_cos);
260         if (ss->deform_imats) MEM_freeN(ss->deform_imats);
261
262         ss->orig_cos = NULL;
263         ss->deform_cos = NULL;
264         ss->deform_imats = NULL;
265 }
266
267 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], short use_drot)
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         if (use_drot)
1574                 mul_m3_m3m3(mat, dmat, rmat);
1575         else
1576                 copy_m3_m3(mat, rmat);
1577 }
1578
1579 void BKE_object_mat3_to_rot(Object *ob, float mat[3][3], short use_compat)
1580 {
1581         switch (ob->rotmode) {
1582                 case ROT_MODE_QUAT:
1583                 {
1584                         float dquat[4];
1585                         mat3_to_quat(ob->quat, mat);
1586                         normalize_qt_qt(dquat, ob->dquat);
1587                         invert_qt(dquat);
1588                         mul_qt_qtqt(ob->quat, dquat, ob->quat);
1589                 }
1590                 break;
1591                 case ROT_MODE_AXISANGLE:
1592                         mat3_to_axis_angle(ob->rotAxis, &ob->rotAngle, mat);
1593                         sub_v3_v3(ob->rotAxis, ob->drotAxis);
1594                         ob->rotAngle -= ob->drotAngle;
1595                         break;
1596                 default: /* euler */
1597                 {
1598                         float quat[4];
1599                         float dquat[4];
1600                         float tmat[3][3];
1601
1602                         /* without drot we could apply 'mat' directly */
1603                         mat3_to_quat(quat, mat);
1604                         eulO_to_quat(dquat, ob->drot, ob->rotmode);
1605                         invert_qt(dquat);
1606                         mul_qt_qtqt(quat, dquat, quat);
1607                         quat_to_mat3(tmat, quat);
1608                         /* end drot correction */
1609
1610                         if (use_compat) mat3_to_compatible_eulO(ob->rot, ob->rot, ob->rotmode, tmat);
1611                         else            mat3_to_eulO(ob->rot, ob->rotmode, tmat);
1612                 }
1613         }
1614 }
1615
1616 void BKE_object_tfm_protected_backup(const Object *ob,
1617                                      ObjectTfmProtectedChannels *obtfm)
1618 {
1619
1620 #define TFMCPY(_v) (obtfm->_v = ob->_v)
1621 #define TFMCPY3D(_v) copy_v3_v3(obtfm->_v, ob->_v)
1622 #define TFMCPY4D(_v) copy_v4_v4(obtfm->_v, ob->_v)
1623
1624         TFMCPY3D(loc);
1625         TFMCPY3D(dloc);
1626         TFMCPY3D(size);
1627         TFMCPY3D(dscale);
1628         TFMCPY3D(rot);
1629         TFMCPY3D(drot);
1630         TFMCPY4D(quat);
1631         TFMCPY4D(dquat);
1632         TFMCPY3D(rotAxis);
1633         TFMCPY3D(drotAxis);
1634         TFMCPY(rotAngle);
1635         TFMCPY(drotAngle);
1636
1637 #undef TFMCPY
1638 #undef TFMCPY3D
1639 #undef TFMCPY4D
1640
1641 }
1642
1643 void BKE_object_tfm_protected_restore(Object *ob,
1644                                       const ObjectTfmProtectedChannels *obtfm,
1645                                       const short protectflag)
1646 {
1647         unsigned int i;
1648
1649         for (i = 0; i < 3; i++) {
1650                 if (protectflag & (OB_LOCK_LOCX << i)) {
1651                         ob->loc[i] =  obtfm->loc[i];
1652                         ob->dloc[i] = obtfm->dloc[i];
1653                 }
1654
1655                 if (protectflag & (OB_LOCK_SCALEX << i)) {
1656                         ob->size[i] =  obtfm->size[i];
1657                         ob->dscale[i] = obtfm->dscale[i];
1658                 }
1659
1660                 if (protectflag & (OB_LOCK_ROTX << i)) {
1661                         ob->rot[i] =  obtfm->rot[i];
1662                         ob->drot[i] = obtfm->drot[i];
1663
1664                         ob->quat[i + 1] =  obtfm->quat[i + 1];
1665                         ob->dquat[i + 1] = obtfm->dquat[i + 1];
1666
1667                         ob->rotAxis[i] =  obtfm->rotAxis[i];
1668                         ob->drotAxis[i] = obtfm->drotAxis[i];
1669                 }
1670         }
1671
1672         if ((protectflag & OB_LOCK_ROT4D) && (protectflag & OB_LOCK_ROTW)) {
1673                 ob->quat[0] =  obtfm->quat[0];
1674                 ob->dquat[0] = obtfm->dquat[0];
1675
1676                 ob->rotAngle =  obtfm->rotAngle;
1677                 ob->drotAngle = obtfm->drotAngle;
1678         }
1679 }
1680
1681 /* see BKE_pchan_apply_mat4() for the equivalent 'pchan' function */
1682 void BKE_object_apply_mat4(Object *ob, float mat[4][4], const short use_compat, const short use_parent)
1683 {
1684         float rot[3][3];
1685
1686         if (use_parent && ob->parent) {
1687                 float rmat[4][4], diff_mat[4][4], imat[4][4];
1688                 mult_m4_m4m4(diff_mat, ob->parent->obmat, ob->parentinv);
1689                 invert_m4_m4(imat, diff_mat);
1690                 mult_m4_m4m4(rmat, imat, mat); /* get the parent relative matrix */
1691                 BKE_object_apply_mat4(ob, rmat, use_compat, FALSE);
1692                 
1693                 /* same as below, use rmat rather than mat */
1694                 mat4_to_loc_rot_size(ob->loc, rot, ob->size, rmat);
1695                 BKE_object_mat3_to_rot(ob, rot, use_compat);
1696         }
1697         else {
1698                 mat4_to_loc_rot_size(ob->loc, rot, ob->size, mat);
1699                 BKE_object_mat3_to_rot(ob, rot, use_compat);
1700         }
1701         
1702         sub_v3_v3(ob->loc, ob->dloc);
1703
1704         if (ob->dscale[0] != 0.0f) ob->size[0] /= ob->dscale[0];
1705         if (ob->dscale[1] != 0.0f) ob->size[1] /= ob->dscale[1];
1706         if (ob->dscale[2] != 0.0f) ob->size[2] /= ob->dscale[2];
1707
1708         /* BKE_object_mat3_to_rot handles delta rotations */
1709 }
1710
1711 void BKE_object_to_mat3(Object *ob, float mat[3][3]) /* no parent */
1712 {
1713         float smat[3][3];
1714         float rmat[3][3];
1715         /*float q1[4];*/
1716         
1717         /* size */
1718         BKE_object_scale_to_mat3(ob, smat);
1719
1720         /* rot */
1721         BKE_object_rot_to_mat3(ob, rmat, TRUE);
1722         mul_m3_m3m3(mat, rmat, smat);
1723 }
1724
1725 void BKE_object_to_mat4(Object *ob, float mat[4][4])
1726 {
1727         float tmat[3][3];
1728         
1729         BKE_object_to_mat3(ob, tmat);
1730         
1731         copy_m4_m3(mat, tmat);
1732
1733         add_v3_v3v3(mat[3], ob->loc, ob->dloc);
1734 }
1735
1736 /* extern */
1737 int enable_cu_speed = 1;
1738
1739 static void ob_parcurve(Scene *scene, Object *ob, Object *par, float mat[4][4])
1740 {
1741         Curve *cu;
1742         float vec[4], dir[3], quat[4], radius, ctime;
1743         float timeoffs = 0.0, sf_orig = 0.0;
1744         
1745         unit_m4(mat);
1746         
1747         cu = par->data;
1748         if (cu->path == NULL || cu->path->data == NULL) /* only happens on reload file, but violates depsgraph still... fix! */
1749                 BKE_displist_make_curveTypes(scene, par, 0);
1750         if (cu->path == NULL) return;
1751         
1752         /* catch exceptions: feature for nla stride editing */
1753         if (ob->ipoflag & OB_DISABLE_PATH) {
1754                 ctime = 0.0f;
1755         }
1756         /* catch exceptions: curve paths used as a duplicator */
1757         else if (enable_cu_speed) {
1758                 /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated,
1759                  * but this will only work if it actually is animated... 
1760                  *
1761                  * we divide the curvetime calculated in the previous step by the length of the path, to get a time
1762                  * factor, which then gets clamped to lie within 0.0 - 1.0 range
1763                  */
1764                 if (IS_EQF(cu->pathlen, 0.0f) == 0)
1765                         ctime = cu->ctime / cu->pathlen;
1766                 else
1767                         ctime = cu->ctime;
1768
1769                 CLAMP(ctime, 0.0f, 1.0f);
1770         }
1771         else {
1772                 ctime = scene->r.cfra;
1773                 if (IS_EQF(cu->pathlen, 0.0f) == 0)
1774                         ctime /= cu->pathlen;
1775                 
1776                 CLAMP(ctime, 0.0f, 1.0f);
1777         }
1778         
1779         /* time calculus is correct, now apply distance offset */
1780         if (cu->flag & CU_OFFS_PATHDIST) {
1781                 ctime += timeoffs / cu->path->totdist;
1782
1783                 /* restore */
1784                 SWAP(float, sf_orig, ob->sf);
1785         }
1786         
1787         
1788         /* vec: 4 items! */
1789         if (where_on_path(par, ctime, vec, dir, cu->flag & CU_FOLLOW ? quat : NULL, &radius, NULL)) {
1790
1791                 if (cu->flag & CU_FOLLOW) {
1792 #if 0
1793                         float si, q[4];
1794                         vec_to_quat(quat, dir, ob->trackflag, ob->upflag);
1795                         
1796                         /* the tilt */
1797                         normalize_v3(dir);
1798                         q[0] = (float)cos(0.5 * vec[3]);
1799                         si = (float)sin(0.5 * vec[3]);
1800                         q[1] = -si * dir[0];
1801                         q[2] = -si * dir[1];
1802                         q[3] = -si * dir[2];
1803                         mul_qt_qtqt(quat, q, quat);
1804 #else
1805                         quat_apply_track(quat, ob->trackflag, ob->upflag);
1806 #endif
1807                         normalize_qt(quat);
1808                         quat_to_mat4(mat, quat);
1809                 }
1810                 
1811                 if (cu->flag & CU_PATH_RADIUS) {
1812                         float tmat[4][4], rmat[4][4];
1813                         scale_m4_fl(tmat, radius);
1814                         mult_m4_m4m4(rmat, tmat, mat);
1815                         copy_m4_m4(mat, rmat);
1816                 }
1817
1818                 copy_v3_v3(mat[3], vec);
1819                 
1820         }
1821 }
1822
1823 static void ob_parbone(Object *ob, Object *par, float mat[4][4])
1824 {       
1825         bPoseChannel *pchan;
1826         float vec[3];
1827         
1828         if (par->type != OB_ARMATURE) {
1829                 unit_m4(mat);
1830                 return;
1831         }
1832         
1833         /* Make sure the bone is still valid */
1834         pchan = BKE_pose_channel_find_name(par->pose, ob->parsubstr);
1835         if (!pchan || !pchan->bone) {
1836                 printf("Object %s with Bone parent: bone %s doesn't exist\n", ob->id.name + 2, ob->parsubstr);
1837                 unit_m4(mat);
1838                 return;
1839         }
1840
1841         /* get bone transform */
1842         copy_m4_m4(mat, pchan->pose_mat);
1843
1844         /* but for backwards compatibility, the child has to move to the tail */
1845         copy_v3_v3(vec, mat[1]);
1846         mul_v3_fl(vec, pchan->bone->length);
1847         add_v3_v3(mat[3], vec);
1848 }
1849
1850 static void give_parvert(Object *par, int nr, float vec[3])
1851 {
1852         BMEditMesh *em;
1853
1854         zero_v3(vec);
1855         
1856         if (par->type == OB_MESH) {
1857                 Mesh *me = par->data;
1858                 DerivedMesh *dm;
1859
1860                 em = me->edit_btmesh;
1861
1862 #if 0   /* this was bmesh only, better, evaluate why this was needed - campbell*/
1863                 if (em) {
1864                         BMVert *eve;
1865                         BMIter iter;
1866
1867                         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
1868                                 int *keyindex = CustomData_bmesh_get(&em->bm->vdata, eve->head.data, CD_SHAPE_KEYINDEX);
1869                                 
1870                                 if (keyindex && *keyindex == nr) {
1871                                         copy_v3_v3(vec, eve->co);
1872                                         break;
1873                                 }
1874                         }
1875                 }
1876 #endif
1877
1878                 dm = (em) ? em->derivedFinal : par->derivedFinal;
1879                         
1880                 if (dm) {
1881                         int count = 0;
1882                         int numVerts = dm->getNumVerts(dm);
1883
1884                         if (nr < numVerts) {
1885                                 MVert *mvert = dm->getVertArray(dm);
1886                                 int   *index = (int *)dm->getVertDataArray(dm, CD_ORIGINDEX);
1887                                 int i;
1888
1889                                 /* get the average of all verts with (original index == nr) */
1890                                 if (index) {
1891                                         for (i = 0; i < numVerts; i++) {
1892                                                 if (index[i] == nr) {
1893                                                         add_v3_v3(vec, mvert[i].co);
1894                                                         count++;
1895                                                 }
1896                                         }
1897                                 }
1898                                 else {
1899                                         if (nr < numVerts) {
1900                                                 add_v3_v3(vec, mvert[nr].co);
1901                                                 count++;
1902                                         }
1903                                 }
1904                         }
1905
1906                         if (count == 0) {
1907                                 /* keep as 0, 0, 0 */
1908                         }
1909                         else if (count > 0) {
1910                                 mul_v3_fl(vec, 1.0f / count);
1911                         }
1912                         else {
1913                                 /* use first index if its out of range */
1914                                 dm->getVertCo(dm, 0, vec);
1915                         }
1916                 }
1917                 else {
1918                         fprintf(stderr,
1919                                 "%s: DerivedMesh is needed to solve parenting, "
1920                                 "object position can be wrong now\n", __func__);
1921                 }
1922         }
1923         else if (ELEM(par->type, OB_CURVE, OB_SURF)) {
1924                 Curve *cu       = par->data;
1925                 ListBase *nurb  = BKE_curve_nurbs_get(cu);;
1926
1927                 BKE_nurbList_index_get_co(nurb, nr, vec);
1928         }
1929         else if (par->type == OB_LATTICE) {
1930                 Lattice *latt  = par->data;
1931                 DispList *dl   = BKE_displist_find(&par->disp, DL_VERTS);
1932                 float (*co)[3] = dl ? (float (*)[3])dl->verts : NULL;
1933                 int tot;
1934
1935                 if (latt->editlatt) latt = latt->editlatt->latt;
1936
1937                 tot = latt->pntsu * latt->pntsv * latt->pntsw;
1938
1939                 /* ensure dl is correct size */
1940                 BLI_assert(dl == NULL || dl->nr == tot);
1941
1942                 if (nr < tot) {
1943                         if (co) {
1944                                 copy_v3_v3(vec, co[nr]);
1945                         }
1946                         else {
1947                                 copy_v3_v3(vec, latt->def[nr].vec);
1948                         }
1949                 }
1950         }
1951 }
1952
1953 static void ob_parvert3(Object *ob, Object *par, float mat[4][4])
1954 {
1955         float cmat[3][3], v1[3], v2[3], v3[3], q[4];
1956
1957         /* in local ob space */
1958         unit_m4(mat);
1959         
1960         if (ELEM4(par->type, OB_MESH, OB_SURF, OB_CURVE, OB_LATTICE)) {
1961                 
1962                 give_parvert(par, ob->par1, v1);
1963                 give_parvert(par, ob->par2, v2);
1964                 give_parvert(par, ob->par3, v3);
1965                                 
1966                 tri_to_quat(q, v1, v2, v3);
1967                 quat_to_mat3(cmat, q);
1968                 copy_m4_m3(mat, cmat);
1969                 
1970                 if (ob->type == OB_CURVE) {
1971                         copy_v3_v3(mat[3], v1);
1972                 }
1973                 else {
1974                         add_v3_v3v3(mat[3], v1, v2);
1975                         add_v3_v3(mat[3], v3);
1976                         mul_v3_fl(mat[3], 0.3333333f);
1977                 }
1978         }
1979 }
1980
1981 static void solve_parenting(Scene *scene, Object *ob, Object *par, float obmat[4][4], float slowmat[4][4], int simul)
1982 {
1983         float totmat[4][4];
1984         float tmat[4][4];
1985         float locmat[4][4];
1986         float vec[3];
1987         int ok;
1988         
1989         BKE_object_to_mat4(ob, locmat);
1990         
1991         if (ob->partype & PARSLOW) copy_m4_m4(slowmat, obmat);
1992
1993         switch (ob->partype & PARTYPE) {
1994                 case PAROBJECT:
1995                         ok = 0;
1996                         if (par->type == OB_CURVE) {
1997                                 if (((Curve *)par->data)->flag & CU_PATH) {
1998                                         ob_parcurve(scene, ob, par, tmat);
1999                                         ok = 1;
2000                                 }
2001                         }
2002                         
2003                         if (ok) mul_serie_m4(totmat, par->obmat, tmat,
2004                                                  NULL, NULL, NULL, NULL, NULL, NULL);
2005                         else copy_m4_m4(totmat, par->obmat);
2006                         
2007                         break;
2008                 case PARBONE:
2009                         ob_parbone(ob, par, tmat);
2010                         mul_serie_m4(totmat, par->obmat, tmat,
2011                                      NULL, NULL, NULL, NULL, NULL, NULL);
2012                         break;
2013                 
2014                 case PARVERT1:
2015                         unit_m4(totmat);
2016                         if (simul) {
2017                                 copy_v3_v3(totmat[3], par->obmat[3]);
2018                         }
2019                         else {
2020                                 give_parvert(par, ob->par1, vec);
2021                                 mul_v3_m4v3(totmat[3], par->obmat, vec);
2022                         }
2023                         break;
2024                 case PARVERT3:
2025                         ob_parvert3(ob, par, tmat);
2026                         
2027                         mul_serie_m4(totmat, par->obmat, tmat,
2028                                      NULL, NULL, NULL, NULL, NULL, NULL);
2029                         break;
2030                 
2031                 case PARSKEL:
2032                         copy_m4_m4(totmat, par->obmat);
2033                         break;
2034         }
2035         
2036         /* total */
2037         mul_serie_m4(tmat, totmat, ob->parentinv,
2038                      NULL, NULL, NULL, NULL, NULL, NULL);
2039         mul_serie_m4(obmat, tmat, locmat,         
2040                      NULL, NULL, NULL, NULL, NULL, NULL);
2041         
2042         if (simul) {
2043
2044         }
2045         else {
2046                 /* external usable originmat */
2047                 copy_m3_m4(originmat, tmat);
2048                 
2049                 /* origin, for help line */
2050                 if ((ob->partype & PARTYPE) == PARSKEL) {
2051                         copy_v3_v3(ob->orig, par->obmat[3]);
2052                 }
2053                 else {
2054                         copy_v3_v3(ob->orig, totmat[3]);
2055                 }
2056         }
2057 }
2058
2059 static int where_is_object_parslow(Object *ob, float obmat[4][4], float slowmat[4][4])
2060 {
2061         float *fp1, *fp2;
2062         float fac1, fac2;
2063         int a;
2064
2065         /* include framerate */
2066         fac1 = (1.0f / (1.0f + fabsf(ob->sf)) );
2067         if (fac1 >= 1.0f) return 0;
2068         fac2 = 1.0f - fac1;
2069
2070         fp1 = obmat[0];
2071         fp2 = slowmat[0];
2072         for (a = 0; a < 16; a++, fp1++, fp2++) {
2073                 fp1[0] = fac1 * fp1[0] + fac2 * fp2[0];
2074         }
2075
2076         return 1;
2077 }
2078
2079 void BKE_object_where_is_calc_time(Scene *scene, Object *ob, float ctime)
2080 {
2081         if (ob == NULL) return;
2082         
2083         /* execute drivers only, as animation has already been done */
2084         BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, ctime, ADT_RECALC_DRIVERS);
2085         
2086         if (ob->parent) {
2087                 Object *par = ob->parent;
2088                 float slowmat[4][4] = MAT4_UNITY;
2089                 
2090                 /* calculate parent matrix */
2091                 solve_parenting(scene, ob, par, ob->obmat, slowmat, 0);
2092                 
2093                 /* "slow parent" is definitely not threadsafe, and may also give bad results jumping around 
2094                  * An old-fashioned hack which probably doesn't really cut it anymore
2095                  */
2096                 if (ob->partype & PARSLOW) {
2097                         if (!where_is_object_parslow(ob, ob->obmat, slowmat))
2098                                 return;
2099                 }
2100         }
2101         else {
2102                 BKE_object_to_mat4(ob, ob->obmat);
2103         }
2104         
2105         /* solve constraints */
2106         if (ob->constraints.first && !(ob->transflag & OB_NO_CONSTRAINTS)) {
2107                 bConstraintOb *cob;
2108                 
2109                 cob = constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2110                 solve_constraints(&ob->constraints, cob, ctime);
2111                 constraints_clear_evalob(cob);
2112         }
2113         
2114         /* set negative scale flag in object */
2115         if (is_negative_m4(ob->obmat)) ob->transflag |= OB_NEG_SCALE;
2116         else ob->transflag &= ~OB_NEG_SCALE;
2117 }
2118
2119 /* get object transformation matrix without recalculating dependencies and
2120  * constraints -- assume dependencies are already solved by depsgraph.
2121  * no changes to object and it's parent would be done.
2122  * used for bundles orientation in 3d space relative to parented blender camera */
2123 void BKE_object_where_is_calc_mat4(Scene *scene, Object *ob, float obmat[4][4])
2124 {
2125         float slowmat[4][4] = MAT4_UNITY;
2126
2127         if (ob->parent) {
2128                 Object *par = ob->parent;
2129                 
2130                 solve_parenting(scene, ob, par, obmat, slowmat, 1);
2131                 
2132                 if (ob->partype & PARSLOW)
2133                         where_is_object_parslow(ob, obmat, slowmat);
2134         }
2135         else {
2136                 BKE_object_to_mat4(ob, obmat);
2137         }
2138 }
2139
2140 void BKE_object_where_is_calc(struct Scene *scene, Object *ob)
2141 {
2142         BKE_object_where_is_calc_time(scene, ob, (float)scene->r.cfra);
2143 }
2144
2145 void BKE_object_where_is_calc_simul(Scene *scene, Object *ob)
2146 /* was written for the old game engine (until 2.04) */
2147 /* It seems that this function is only called
2148  * for a lamp that is the child of another object */
2149 {
2150         Object *par;
2151         float *fp1, *fp2;
2152         float slowmat[4][4];
2153         float fac1, fac2;
2154         int a;
2155         
2156         /* NO TIMEOFFS */
2157         if (ob->parent) {
2158                 par = ob->parent;
2159                 
2160                 solve_parenting(scene, ob, par, ob->obmat, slowmat, 1);
2161                 
2162                 if (ob->partype & PARSLOW) {
2163                         fac1 = (float)(1.0 / (1.0 + fabs(ob->sf)));
2164                         fac2 = 1.0f - fac1;
2165                         fp1 = ob->obmat[0];
2166                         fp2 = slowmat[0];
2167                         for (a = 0; a < 16; a++, fp1++, fp2++) {
2168                                 fp1[0] = fac1 * fp1[0] + fac2 * fp2[0];
2169                         }
2170                 }
2171         }
2172         else {
2173                 BKE_object_to_mat4(ob, ob->obmat);
2174         }
2175         
2176         /* solve constraints */
2177         if (ob->constraints.first) {
2178                 bConstraintOb *cob;
2179                 
2180                 cob = constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2181                 solve_constraints(&ob->constraints, cob, (float)scene->r.cfra);
2182                 constraints_clear_evalob(cob);
2183         }
2184 }
2185
2186 /* for calculation of the inverse parent transform, only used for editor */
2187 void BKE_object_workob_calc_parent(Scene *scene, Object *ob, Object *workob)
2188 {
2189         BKE_object_workob_clear(workob);
2190         
2191         unit_m4(workob->obmat);
2192         unit_m4(workob->parentinv);
2193         unit_m4(workob->constinv);
2194         workob->parent = ob->parent;
2195
2196         workob->trackflag = ob->trackflag;
2197         workob->upflag = ob->upflag;
2198         
2199         workob->partype = ob->partype;
2200         workob->par1 = ob->par1;
2201         workob->par2 = ob->par2;
2202         workob->par3 = ob->par3;
2203
2204         workob->constraints.first = ob->constraints.first;
2205         workob->constraints.last = ob->constraints.last;
2206
2207         BLI_strncpy(workob->parsubstr, ob->parsubstr, sizeof(workob->parsubstr));
2208
2209         BKE_object_where_is_calc(scene, workob);
2210 }
2211
2212 BoundBox *BKE_boundbox_alloc_unit(void)
2213 {
2214         BoundBox *bb;
2215         float min[3] = {-1.0f, -1.0f, -1.0f}, max[3] = {-1.0f, -1.0f, -1.0f};
2216
2217         bb = MEM_callocN(sizeof(BoundBox), "OB-BoundBox");
2218         BKE_boundbox_init_from_minmax(bb, min, max);
2219         
2220         return bb;
2221 }
2222
2223 void BKE_boundbox_init_from_minmax(BoundBox *bb, float min[3], float max[3])
2224 {
2225         bb->vec[0][0] = bb->vec[1][0] = bb->vec[2][0] = bb->vec[3][0] = min[0];
2226         bb->vec[4][0] = bb->vec[5][0] = bb->vec[6][0] = bb->vec[7][0] = max[0];
2227         
2228         bb->vec[0][1] = bb->vec[1][1] = bb->vec[4][1] = bb->vec[5][1] = min[1];
2229         bb->vec[2][1] = bb->vec[3][1] = bb->vec[6][1] = bb->vec[7][1] = max[1];
2230
2231         bb->vec[0][2] = bb->vec[3][2] = bb->vec[4][2] = bb->vec[7][2] = min[2];
2232         bb->vec[1][2] = bb->vec[2][2] = bb->vec[5][2] = bb->vec[6][2] = max[2];
2233 }
2234
2235 BoundBox *BKE_object_boundbox_get(Object *ob)
2236 {
2237         BoundBox *bb = NULL;
2238         
2239         if (ob->type == OB_MESH) {
2240                 bb = BKE_mesh_boundbox_get(ob);
2241         }
2242         else if (ELEM3(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2243                 bb = ob->bb ? ob->bb : ((Curve *)ob->data)->bb;
2244         }
2245         else if (ob->type == OB_MBALL) {
2246                 bb = ob->bb;
2247         }
2248         return bb;
2249 }
2250
2251 /* used to temporally disable/enable boundbox */
2252 void BKE_object_boundbox_flag(Object *ob, int flag, int set)
2253 {
2254         BoundBox *bb = BKE_object_boundbox_get(ob);
2255         if (bb) {
2256                 if (set) bb->flag |= flag;
2257                 else bb->flag &= ~flag;
2258         }
2259 }
2260
2261 void BKE_object_dimensions_get(Object *ob, float vec[3])
2262 {
2263         BoundBox *bb = NULL;
2264         
2265         bb = BKE_object_boundbox_get(ob);
2266         if (bb) {
2267                 float scale[3];
2268                 
2269                 mat4_to_size(scale, ob->obmat);
2270                 
2271                 vec[0] = fabsf(scale[0]) * (bb->vec[4][0] - bb->vec[0][0]);
2272                 vec[1] = fabsf(scale[1]) * (bb->vec[2][1] - bb->vec[0][1]);
2273                 vec[2] = fabsf(scale[2]) * (bb->vec[1][2] - bb->vec[0][2]);
2274         }
2275         else {
2276                 zero_v3(vec);
2277         }
2278 }
2279
2280 void BKE_object_dimensions_set(Object *ob, const float *value)
2281 {
2282         BoundBox *bb = NULL;
2283         
2284         bb = BKE_object_boundbox_get(ob);
2285         if (bb) {
2286                 float scale[3], len[3];
2287                 
2288                 mat4_to_size(scale, ob->obmat);
2289                 
2290                 len[0] = bb->vec[4][0] - bb->vec[0][0];
2291                 len[1] = bb->vec[2][1] - bb->vec[0][1];
2292                 len[2] = bb->vec[1][2] - bb->vec[0][2];
2293                 
2294                 if (len[0] > 0.f) ob->size[0] = value[0] / len[0];
2295                 if (len[1] > 0.f) ob->size[1] = value[1] / len[1];
2296                 if (len[2] > 0.f) ob->size[2] = value[2] / len[2];
2297         }
2298 }
2299
2300 void BKE_object_minmax(Object *ob, float min_r[3], float max_r[3], const short use_hidden)
2301 {
2302         BoundBox bb;
2303         float vec[3];
2304         int a;
2305         short change = FALSE;
2306         
2307         switch (ob->type) {
2308                 case OB_CURVE:
2309                 case OB_FONT:
2310                 case OB_SURF:
2311                 {
2312                         Curve *cu = ob->data;
2313
2314                         /* Use the object bounding box so that modifier output
2315                          * gets taken into account */
2316                         if (ob->bb)
2317                                 bb = *(ob->bb);
2318                         else {
2319                                 if (cu->bb == NULL)
2320                                         BKE_curve_texspace_calc(cu);
2321                                 bb = *(cu->bb);
2322                         }
2323
2324                         for (a = 0; a < 8; a++) {
2325                                 mul_m4_v3(ob->obmat, bb.vec[a]);
2326                                 minmax_v3v3_v3(min_r, max_r, bb.vec[a]);
2327                         }
2328                         change = TRUE;
2329                 }
2330                 break;
2331                 case OB_LATTICE:
2332                 {
2333                         Lattice *lt = ob->data;
2334                         BPoint *bp = lt->def;
2335                         int u, v, w;
2336
2337                         for (w = 0; w < lt->pntsw; w++) {
2338                                 for (v = 0; v < lt->pntsv; v++) {
2339                                         for (u = 0; u < lt->pntsu; u++, bp++) {
2340                                                 mul_v3_m4v3(vec, ob->obmat, bp->vec);
2341                                                 minmax_v3v3_v3(min_r, max_r, vec);
2342                                         }
2343                                 }
2344                         }
2345                         change = TRUE;
2346                 }
2347                 break;
2348                 case OB_ARMATURE:
2349                         if (ob->pose) {
2350                                 bArmature *arm = ob->data;
2351                                 bPoseChannel *pchan;
2352
2353                                 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2354                                         /* XXX pchan->bone may be NULL for duplicated bones, see duplicateEditBoneObjects() comment
2355                                          *     (editarmature.c:2592)... Skip in this case too! */
2356                                         if (pchan->bone && !((use_hidden == FALSE) && (PBONE_VISIBLE(arm, pchan->bone) == FALSE))) {
2357                                                 mul_v3_m4v3(vec, ob->obmat, pchan->pose_head);
2358                                                 minmax_v3v3_v3(min_r, max_r, vec);
2359                                                 mul_v3_m4v3(vec, ob->obmat, pchan->pose_tail);
2360                                                 minmax_v3v3_v3(min_r, max_r, vec);
2361
2362                                                 change = TRUE;
2363                                         }
2364                                 }
2365                         }
2366                         break;
2367                 case OB_MESH:
2368                 {
2369                         Mesh *me = BKE_mesh_from_object(ob);
2370
2371                         if (me) {
2372                                 bb = *BKE_mesh_boundbox_get(ob);
2373
2374                                 for (a = 0; a < 8; a++) {
2375                                         mul_m4_v3(ob->obmat, bb.vec[a]);
2376                                         minmax_v3v3_v3(min_r, max_r, bb.vec[a]);
2377                                 }
2378                                 change = TRUE;
2379                         }
2380                 }
2381                 break;
2382         }
2383
2384         if (change == FALSE) {
2385                 float size[3];
2386
2387                 copy_v3_v3(size, ob->size);
2388                 if (ob->type == OB_EMPTY) {
2389                         mul_v3_fl(size, ob->empty_drawsize);
2390                 }
2391
2392                 minmax_v3v3_v3(min_r, max_r, ob->obmat[3]);
2393
2394                 copy_v3_v3(vec, ob->obmat[3]);
2395                 add_v3_v3(vec, size);
2396                 minmax_v3v3_v3(min_r, max_r, vec);
2397
2398                 copy_v3_v3(vec, ob->obmat[3]);
2399                 sub_v3_v3(vec, size);
2400                 minmax_v3v3_v3(min_r, max_r, vec);
2401         }
2402 }
2403
2404 int BKE_object_minmax_dupli(Scene *scene, Object *ob, float r_min[3], float r_max[3], const short use_hidden)
2405 {
2406         int ok = FALSE;
2407         if ((ob->transflag & OB_DUPLI) == 0) {
2408                 return ok;
2409         }
2410         else {
2411                 ListBase *lb;
2412                 DupliObject *dob;
2413                 
2414                 lb = object_duplilist(scene, ob, FALSE);
2415                 for (dob = lb->first; dob; dob = dob->next) {
2416                         if ((use_hidden == FALSE) && (dob->no_draw != 0)) {
2417                                 /* pass */
2418                         }
2419                         else {
2420                                 BoundBox *bb = BKE_object_boundbox_get(dob->ob);
2421
2422                                 if (bb) {
2423                                         int i;
2424                                         for (i = 0; i < 8; i++) {
2425                                                 float vec[3];
2426                                                 mul_v3_m4v3(vec, dob->mat, bb->vec[i]);
2427                                                 minmax_v3v3_v3(r_min, r_max, vec);
2428                                         }
2429
2430                                         ok = TRUE;
2431                                 }
2432                         }
2433                 }
2434                 free_object_duplilist(lb);  /* does restore */
2435         }
2436
2437         return ok;
2438 }
2439
2440 void BKE_object_foreach_display_point(
2441         Object *ob, float obmat[4][4],
2442         void (*func_cb)(const float[3], void *), void *user_data)
2443 {
2444         float co[3];
2445
2446         if (ob->derivedFinal) {
2447                 DerivedMesh *dm = ob->derivedFinal;
2448                 MVert *mv = dm->getVertArray(dm);
2449                 int totvert = dm->getNumVerts(dm);
2450                 int i;
2451
2452                 for (i = 0; i < totvert; i++, mv++) {
2453                         mul_v3_m4v3(co, obmat, mv->co);
2454                         func_cb(co, user_data);
2455                 }
2456         }
2457         else if (ob->disp.first) {
2458                 DispList *dl;
2459
2460                 for (dl = ob->disp.first; dl; dl = dl->next) {
2461                         float *v3 = dl->verts;
2462                         int totvert = dl->nr;
2463                         int i;
2464
2465                         for (i = 0; i < totvert; i++, v3 += 3) {
2466                                 mul_v3_m4v3(co, obmat, v3);
2467                                 func_cb(co, user_data);
2468                         }
2469                 }
2470         }
2471 }
2472
2473 void BKE_scene_foreach_display_point(
2474         Scene *scene, View3D *v3d, const short flag,
2475         void (*func_cb)(const float[3], void *), void *user_data)
2476 {
2477         Base *base;
2478         Object *ob;
2479
2480         for (base = FIRSTBASE; base; base = base->next) {
2481                 if (BASE_VISIBLE(v3d, base) && (base->flag & flag) == flag) {
2482                         ob = base->object;
2483
2484                         if ((ob->transflag & OB_DUPLI) == 0) {
2485                                 BKE_object_foreach_display_point(ob, ob->obmat, func_cb, user_data);
2486                         }
2487                         else {
2488                                 ListBase *lb;
2489                                 DupliObject *dob;
2490
2491                                 lb = object_duplilist(scene, ob, FALSE);
2492                                 for (dob = lb->first; dob; dob = dob->next) {
2493                                         if (dob->no_draw == 0) {
2494                                                 BKE_object_foreach_display_point(dob->ob, dob->mat, func_cb, user_data);
2495                                         }
2496                                 }
2497                                 free_object_duplilist(lb);  /* does restore */
2498                         }
2499                 }
2500         }
2501 }
2502
2503 /* copied from DNA_object_types.h */
2504 typedef struct ObTfmBack {
2505         float loc[3], dloc[3], orig[3];
2506         float size[3], dscale[3];   /* scale and delta scale */
2507         float rot[3], drot[3];      /* euler rotation */
2508         float quat[4], dquat[4];    /* quaternion rotation */
2509         float rotAxis[3], drotAxis[3];  /* axis angle rotation - axis part */
2510         float rotAngle, drotAngle;  /* axis angle rotation - angle part */
2511         float obmat[4][4];      /* final worldspace matrix with constraints & animsys applied */
2512         float parentinv[4][4]; /* inverse result of parent, so that object doesn't 'stick' to parent */
2513         float constinv[4][4]; /* inverse result of constraints. doesn't include effect of parent or object local transform */
2514         float imat[4][4];   /* inverse matrix of 'obmat' for during render, old game engine, temporally: ipokeys of transform  */
2515 } ObTfmBack;
2516
2517 void *BKE_object_tfm_backup(Object *ob)
2518 {
2519         ObTfmBack *obtfm = MEM_mallocN(sizeof(ObTfmBack), "ObTfmBack");
2520         copy_v3_v3(obtfm->loc, ob->loc);
2521         copy_v3_v3(obtfm->dloc, ob->dloc);
2522         copy_v3_v3(obtfm->orig, ob->orig);
2523         copy_v3_v3(obtfm->size, ob->size);
2524         copy_v3_v3(obtfm->dscale, ob->dscale);
2525         copy_v3_v3(obtfm->rot, ob->rot);
2526         copy_v3_v3(obtfm->drot, ob->drot);
2527         copy_qt_qt(obtfm->quat, ob->quat);
2528         copy_qt_qt(obtfm->dquat, ob->dquat);
2529         copy_v3_v3(obtfm->rotAxis, ob->rotAxis);
2530         copy_v3_v3(obtfm->drotAxis, ob->drotAxis);
2531         obtfm->rotAngle = ob->rotAngle;
2532         obtfm->drotAngle = ob->drotAngle;
2533         copy_m4_m4(obtfm->obmat, ob->obmat);
2534         copy_m4_m4(obtfm->parentinv, ob->parentinv);
2535         copy_m4_m4(obtfm->constinv, ob->constinv);
2536         copy_m4_m4(obtfm->imat, ob->imat);
2537
2538         return (void *)obtfm;
2539 }
2540
2541 void BKE_object_tfm_restore(Object *ob, void *obtfm_pt)
2542 {
2543         ObTfmBack *obtfm = (ObTfmBack *)obtfm_pt;
2544         copy_v3_v3(ob->loc, obtfm->loc);
2545         copy_v3_v3(ob->dloc, obtfm->dloc);
2546         copy_v3_v3(ob->orig, obtfm->orig);
2547         copy_v3_v3(ob->size, obtfm->size);
2548         copy_v3_v3(ob->dscale, obtfm->dscale);
2549         copy_v3_v3(ob->rot, obtfm->rot);
2550         copy_v3_v3(ob->drot, obtfm->drot);
2551         copy_qt_qt(ob->quat, obtfm->quat);
2552         copy_qt_qt(ob->dquat, obtfm->dquat);
2553         copy_v3_v3(ob->rotAxis, obtfm->rotAxis);
2554         copy_v3_v3(ob->drotAxis, obtfm->drotAxis);
2555         ob->rotAngle = obtfm->rotAngle;
2556         ob->drotAngle = obtfm->drotAngle;
2557         copy_m4_m4(ob->obmat, obtfm->obmat);
2558         copy_m4_m4(ob->parentinv, obtfm->parentinv);
2559         copy_m4_m4(ob->constinv, obtfm->constinv);
2560         copy_m4_m4(ob->imat, obtfm->imat);
2561 }
2562
2563 int BKE_object_parent_loop_check(const Object *par, const Object *ob)
2564 {
2565         /* test if 'ob' is a parent somewhere in par's parents */
2566         if (par == NULL) return 0;
2567         if (ob == par) return 1;
2568         return BKE_object_parent_loop_check(par->parent, ob);
2569 }
2570
2571 /* proxy rule: lib_object->proxy_from == the one we borrow from, only set temporal and cleared here */
2572 /*           local_object->proxy      == pointer to library object, saved in files and read */
2573
2574 /* function below is polluted with proxy exceptions, cleanup will follow! */
2575
2576 /* the main object update call, for object matrix, constraints, keys and displist (modifiers) */
2577 /* requires flags to be set! */
2578 void BKE_object_handle_update(Scene *scene, Object *ob)
2579 {
2580         if (ob->recalc & OB_RECALC_ALL) {
2581                 /* speed optimization for animation lookups */
2582                 if (ob->pose)
2583                         BKE_pose_channels_hash_make(ob->pose);
2584
2585                 if (ob->recalc & OB_RECALC_DATA) {
2586                         if (ob->type == OB_ARMATURE) {
2587                                 /* this happens for reading old files and to match library armatures
2588                                  * with poses we do it ahead of BKE_object_where_is_calc to ensure animation
2589                                  * is evaluated on the rebuilt pose, otherwise we get incorrect poses
2590                                  * on file load */
2591                                 if (ob->pose == NULL || (ob->pose->flag & POSE_RECALC))
2592                                         BKE_pose_rebuild(ob, ob->data);
2593                         }
2594                 }
2595
2596                 /* XXX new animsys warning: depsgraph tag OB_RECALC_DATA should not skip drivers, 
2597                  * which is only in BKE_object_where_is_calc now */
2598                 /* XXX: should this case be OB_RECALC_OB instead? */
2599                 if (ob->recalc & OB_RECALC_ALL) {
2600                         
2601                         if (G.debug & G_DEBUG)
2602                                 printf("recalcob %s\n", ob->id.name + 2);
2603                         
2604                         /* handle proxy copy for target */
2605                         if (ob->id.lib && ob->proxy_from) {
2606                                 // printf("ob proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2607                                 if (ob->proxy_from->proxy_group) { /* transform proxy into group space */
2608                                         Object *obg = ob->proxy_from->proxy_group;
2609                                         invert_m4_m4(obg->imat, obg->obmat);
2610                                         mult_m4_m4m4(ob->obmat, obg->imat, ob->proxy_from->obmat);
2611                                         if (obg->dup_group) { /* should always be true */
2612                                                 add_v3_v3(ob->obmat[3], obg->dup_group->dupli_ofs);
2613                                         }
2614                                 }
2615                                 else
2616                                         copy_m4_m4(ob->obmat, ob->proxy_from->obmat);
2617                         }
2618                         else
2619                                 BKE_object_where_is_calc(scene, ob);
2620                 }
2621                 
2622                 if (ob->recalc & OB_RECALC_DATA) {
2623                         ID *data_id = (ID *)ob->data;
2624                         AnimData *adt = BKE_animdata_from_id(data_id);
2625                         float ctime = (float)scene->r.cfra;  /* XXX this is bad... */
2626                         
2627                         if (G.debug & G_DEBUG)
2628                                 printf("recalcdata %s\n", ob->id.name + 2);
2629
2630                         if (adt) {
2631                                 /* evaluate drivers - datalevel */
2632                                 /* XXX: for mesh types, should we push this to derivedmesh instead? */
2633                                 BKE_animsys_evaluate_animdata(scene, data_id, adt, ctime, ADT_RECALC_DRIVERS);
2634                         }
2635
2636                         /* includes all keys and modifiers */
2637                         switch (ob->type) {
2638                                 case OB_MESH:
2639                                 {
2640 #if 0               // XXX, comment for 2.56a release, background wont set 'scene->customdata_mask'
2641                                         BMEditMesh *em = (ob == scene->obedit) ? BMEdit_FromObject(ob) : NULL;
2642                                         BLI_assert((scene->customdata_mask & CD_MASK_BAREMESH) == CD_MASK_BAREMESH);
2643                                         if (em) {
2644                                                 makeDerivedMesh(scene, ob, em,  scene->customdata_mask, 0); /* was CD_MASK_BAREMESH */
2645                                         }
2646                                         else {
2647                                                 makeDerivedMesh(scene, ob, NULL, scene->customdata_mask, 0);
2648                                         }
2649
2650 #else               /* ensure CD_MASK_BAREMESH for now */
2651                                         BMEditMesh *em = (ob == scene->obedit) ? BMEdit_FromObject(ob) : NULL;
2652                                         uint64_t data_mask = scene->customdata_mask | ob->customdata_mask | CD_MASK_BAREMESH;
2653                                         if (em) {
2654                                                 makeDerivedMesh(scene, ob, em,  data_mask, 0); /* was CD_MASK_BAREMESH */
2655                                         }
2656                                         else {
2657                                                 makeDerivedMesh(scene, ob, NULL, data_mask, 0);
2658                                         }
2659 #endif
2660
2661                                 }
2662                                 break;
2663
2664                                 case OB_ARMATURE:
2665                                         if (ob->id.lib && ob->proxy_from) {
2666                                                 // printf("pose proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2667                                                 BKE_pose_copy_result(ob->pose, ob->proxy_from->pose);
2668                                         }
2669                                         else {
2670                                                 BKE_pose_where_is(scene, ob);
2671                                         }
2672                                         break;
2673
2674                                 case OB_MBALL:
2675                                         BKE_displist_make_mball(scene, ob);
2676                                         break;
2677
2678                                 case OB_CURVE:
2679                                 case OB_SURF:
2680                                 case OB_FONT:
2681                                         BKE_displist_make_curveTypes(scene, ob, 0);
2682                                         break;
2683                                 
2684                                 case OB_LATTICE:
2685                                         BKE_lattice_modifiers_calc(scene, ob);
2686                                         break;
2687                         }
2688                         
2689                         /* related materials */
2690                         /* XXX: without depsgraph tagging, this will always need to be run, which will be slow! 
2691                          * However, not doing anything (or trying to hack around this lack) is not an option 
2692                          * anymore, especially due to Cycles [#31834] 
2693                          */
2694                         if (ob->totcol) {
2695                                 int a;
2696                                 
2697                                 for (a = 1; a <= ob->totcol; a++) {
2698                                         Material *ma = give_current_material(ob, a);
2699                                         
2700                                         if (ma) {
2701                                                 /* recursively update drivers for this material */
2702                                                 material_drivers_update(scene, ma, ctime);
2703                                         }
2704                                 }
2705                         }
2706                         else if (ob->type == OB_LAMP)
2707                                 lamp_drivers_update(scene, ob->data, ctime);
2708                         
2709                         /* particles */
2710                         if (ob->particlesystem.first) {
2711                                 ParticleSystem *tpsys, *psys;
2712                                 DerivedMesh *dm;
2713                                 ob->transflag &= ~OB_DUPLIPARTS;
2714                                 
2715                                 psys = ob->particlesystem.first;
2716                                 while (psys) {
2717                                         if (psys_check_enabled(ob, psys)) {
2718                                                 /* check use of dupli objects here */
2719                                                 if (psys->part && (psys->part->draw_as == PART_DRAW_REND || G.is_rendering) &&
2720                                                     ((psys->part->ren_as == PART_DRAW_OB && psys->part->dup_ob) ||
2721                                                      (psys->part->ren_as == PART_DRAW_GR && psys->part->dup_group)))
2722                                                 {
2723                                                         ob->transflag |= OB_DUPLIPARTS;
2724                                                 }
2725
2726                                                 particle_system_update(scene, ob, psys);
2727                                                 psys = psys->next;
2728                                         }
2729                                         else if (psys->flag & PSYS_DELETE) {
2730                                                 tpsys = psys->next;
2731                                                 BLI_remlink(&ob->particlesystem, psys);
2732                                                 psys_free(ob, psys);
2733                                                 psys = tpsys;
2734                                         }
2735                                         else
2736                                                 psys = psys->next;
2737                                 }
2738
2739                                 if (G.is_rendering && ob->transflag & OB_DUPLIPARTS) {
2740                                         /* this is to make sure we get render level duplis in groups:
2741                                          * the derivedmesh must be created before init_render_mesh,
2742                                          * since object_duplilist does dupliparticles before that */
2743                                         dm = mesh_create_derived_render(scene, ob, CD_MASK_BAREMESH | CD_MASK_MTFACE | CD_MASK_MCOL);
2744                                         dm->release(dm);
2745
2746                                         for (psys = ob->particlesystem.first; psys; psys = psys->next)
2747                                                 psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated;
2748                                 }
2749                         }
2750                         
2751                         /* quick cache removed */
2752                 }
2753
2754                 /* the no-group proxy case, we call update */
2755                 if (ob->proxy && ob->proxy_group == NULL) {
2756                         /* set pointer in library proxy target, for copying, but restore it */
2757                         ob->proxy->proxy_from = ob;
2758                         // printf("call update, lib ob %s proxy %s\n", ob->proxy->id.name, ob->id.name);
2759                         BKE_object_handle_update(scene, ob->proxy);
2760                 }
2761         
2762                 ob->recalc &= ~OB_RECALC_ALL;
2763         }
2764
2765         /* the case when this is a group proxy, object_update is called in group.c */
2766         if (ob->proxy) {
2767                 ob->proxy->proxy_from = ob;
2768                 // printf("set proxy pointer for later group stuff %s\n", ob->id.name);
2769         }
2770 }
2771
2772 void BKE_object_sculpt_modifiers_changed(Object *ob)
2773 {
2774         SculptSession *ss = ob->sculpt;
2775
2776         if (!ss->cache) {
2777                 /* we free pbvh on changes, except during sculpt since it can't deal with
2778                  * changing PVBH node organization, we hope topology does not change in
2779                  * the meantime .. weak */
2780                 if (ss->pbvh) {
2781                         BLI_pbvh_free(ss->pbvh);
2782                         ss->pbvh = NULL;
2783                 }
2784
2785                 free_sculptsession_deformMats(ob->sculpt);
2786         }
2787         else {
2788                 PBVHNode **nodes;
2789                 int n, totnode;
2790
2791                 BLI_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode);
2792
2793                 for (n = 0; n < totnode; n++)
2794                         BLI_pbvh_node_mark_update(nodes[n]);
2795
2796                 MEM_freeN(nodes);
2797         }
2798 }
2799
2800 int BKE_object_obdata_texspace_get(Object *ob, short **r_texflag, float **r_loc, float **r_size, float **r_rot)
2801 {
2802         
2803         if (ob->data == NULL)
2804                 return 0;
2805         
2806         switch (GS(((ID *)ob->data)->name)) {
2807                 case ID_ME:
2808                 {
2809                         Mesh *me = ob->data;
2810                         if (r_texflag) *r_texflag = &me->texflag;
2811                         if (r_loc) *r_loc = me->loc;
2812                         if (r_size) *r_size = me->size;
2813                         if (r_rot) *r_rot = me->rot;
2814                         break;
2815                 }
2816                 case ID_CU:
2817                 {
2818                         Curve *cu = ob->data;
2819                         if (r_texflag) *r_texflag = &cu->texflag;
2820                         if (r_loc) *r_loc = cu->loc;
2821                         if (r_size) *r_size = cu->size;
2822                         if (r_rot) *r_rot = cu->rot;
2823                         break;
2824                 }
2825                 case ID_MB:
2826                 {
2827                         MetaBall *mb = ob->data;
2828                         if (r_texflag) *r_texflag = &mb->texflag;
2829                         if (r_loc) *r_loc = mb->loc;
2830                         if (r_size) *r_size = mb->size;
2831                         if (r_rot) *r_rot = mb->rot;
2832                         break;
2833                 }
2834                 default:
2835                         return 0;
2836         }
2837         return 1;
2838 }
2839
2840 /*
2841  * Test a bounding box for ray intersection
2842  * assumes the ray is already local to the boundbox space
2843  */
2844 int BKE_boundbox_ray_hit_check(struct BoundBox *bb, float ray_start[3], float ray_normal[3])
2845 {
2846         static int triangle_indexes[12][3] = {{0, 1, 2}, {0, 2, 3},
2847                                               {3, 2, 6}, {3, 6, 7},
2848                                               {1, 2, 6}, {1, 6, 5},
2849                                               {5, 6, 7}, {4, 5, 7},
2850                                               {0, 3, 7}, {0, 4, 7},
2851                                               {0, 1, 5}, {0, 4, 5}};
2852         int result = 0;
2853         int i;
2854         
2855         for (i = 0; i < 12 && result == 0; i++) {
2856                 float lambda;
2857                 int v1, v2, v3;
2858                 v1 = triangle_indexes[i][0];
2859                 v2 = triangle_indexes[i][1];
2860                 v3 = triangle_indexes[i][2];
2861                 result = isect_ray_tri_v3(ray_start, ray_normal, bb->vec[v1], bb->vec[v2], bb->vec[v3], &lambda, NULL);
2862         }
2863         
2864         return result;
2865 }
2866
2867 static int pc_cmp(void *a, void *b)
2868 {
2869         LinkData *ad = a, *bd = b;
2870         if (GET_INT_FROM_POINTER(ad->data) > GET_INT_FROM_POINTER(bd->data))
2871                 return 1;
2872         else return 0;
2873 }
2874
2875 int BKE_object_insert_ptcache(Object *ob) 
2876 {
2877         LinkData *link = NULL;
2878         int i = 0;
2879
2880         BLI_sortlist(&ob->pc_ids, pc_cmp);
2881
2882         for (link = ob->pc_ids.first, i = 0; link; link = link->next, i++) {
2883                 int index = GET_INT_FROM_POINTER(link->data);
2884
2885                 if (i < index)
2886                         break;
2887         }
2888
2889         link = MEM_callocN(sizeof(LinkData), "PCLink");
2890         link->data = SET_INT_IN_POINTER(i);
2891         BLI_addtail(&ob->pc_ids, link);
2892
2893         return i;
2894 }
2895
2896 #if 0
2897 static int pc_findindex(ListBase *listbase, int index)
2898 {
2899         LinkData *link = NULL;
2900         int number = 0;
2901         
2902         if (listbase == NULL) return -1;
2903         
2904         link = listbase->first;
2905         while (link) {
2906                 if ((int)link->data == index)
2907                         return number;
2908                 
2909                 number++;
2910                 link = link->next;
2911         }
2912         
2913         return -1;
2914 }
2915
2916 void object_delete_ptcache(Object *ob, int index) 
2917 {
2918         int list_index = pc_findindex(&ob->pc_ids, index);
2919         LinkData *link = BLI_findlink(&ob->pc_ids, list_index);
2920         BLI_freelinkN(&ob->pc_ids, link);
2921 }
2922 #endif
2923
2924 /* shape key utility function */
2925
2926 /************************* Mesh ************************/
2927 static KeyBlock *insert_meshkey(Scene *scene, Object *ob, const char *name, int from_mix)
2928 {
2929         Mesh *me = ob->data;
2930         Key *key = me->key;
2931         KeyBlock *kb;
2932         int newkey = 0;
2933
2934         if (key == NULL) {
2935                 key = me->key = BKE_key_add((ID *)me);
2936                 key->type = KEY_RELATIVE;
2937                 newkey = 1;
2938         }
2939
2940         if (newkey || from_mix == FALSE) {
2941                 /* create from mesh */
2942                 kb = BKE_keyblock_add_ctime(key, name, FALSE);
2943                 BKE_key_convert_from_mesh(me, kb);
2944         }
2945         else {
2946                 /* copy from current values */
2947                 float *data = do_ob_key(scene, ob);
2948
2949                 /* create new block with prepared data */
2950                 kb = BKE_keyblock_add_ctime(key, name, FALSE);
2951                 kb->data = data;
2952                 kb->totelem = me->totvert;
2953         }
2954
2955         return kb;
2956 }
2957 /************************* Lattice ************************/
2958 static KeyBlock *insert_lattkey(Scene *scene, Object *ob, const char *name, int from_mix)
2959 {
2960         Lattice *lt = ob->data;
2961         Key *key = lt->key;
2962         KeyBlock *kb;
2963         int newkey = 0;
2964
2965         if (key == NULL) {
2966                 key = lt->key = BKE_key_add((ID *)lt);
2967                 key->type = KEY_RELATIVE;
2968                 newkey = 1;
2969         }
2970
2971         if (newkey || from_mix == FALSE) {
2972                 kb = BKE_keyblock_add_ctime(key, name, FALSE);
2973                 if (!newkey) {
2974                         KeyBlock *basekb = (KeyBlock *)key->block.first;
2975                         kb->data = MEM_dupallocN(basekb->data);
2976                         kb->totelem = basekb->totelem;
2977                 }
2978                 else {
2979                         BKE_key_convert_from_lattice(lt, kb);
2980                 }
2981         }
2982         else {
2983                 /* copy from current values */
2984                 float *data = do_ob_key(scene, ob);
2985
2986                 /* create new block with prepared data */
2987                 kb = BKE_keyblock_add_ctime(key, name, FALSE);
2988                 kb->totelem = lt->pntsu * lt->pntsv * lt->pntsw;
2989                 kb->data = data;
2990         }
2991
2992         return kb;
2993 }
2994 /************************* Curve ************************/
2995 static KeyBlock *insert_curvekey(Scene *scene, Object *ob, const char *name, int from_mix)
2996 {
2997         Curve *cu = ob->data;
2998         Key *key = cu->key;
2999         KeyBlock *kb;
3000         ListBase *lb = BKE_curve_nurbs_get(cu);
3001         int newkey = 0;
3002
3003         if (key == NULL) {
3004                 key = cu->key = BKE_key_add((ID *)cu);
3005                 key->type = KEY_RELATIVE;
3006                 newkey = 1;
3007         }
3008
3009         if (newkey || from_mix == FALSE) {
3010                 /* create from curve */
3011                 kb = BKE_keyblock_add_ctime(key, name, FALSE);
3012                 if (!newkey) {
3013                         KeyBlock *basekb = (KeyBlock *)key->block.first;
3014                         kb->data = MEM_dupallocN(basekb->data);
3015                         kb->totelem = basekb->totelem;
3016                 }
3017                 else {
3018                         BKE_key_convert_from_curve(cu, kb, lb);
3019                 }
3020         }
3021         else {
3022                 /* copy from current values */
3023                 float *data = do_ob_key(scene, ob);
3024
3025                 /* create new block with prepared data */
3026                 kb = BKE_keyblock_add_ctime(key, name, FALSE);
3027                 kb->totelem = BKE_nurbList_verts_count(lb);
3028                 kb->data = data;
3029         }
3030
3031         return kb;
3032 }
3033
3034 KeyBlock *BKE_object_insert_shape_key(Scene *scene, Object *ob, const char *name, int from_mix)
3035 {       
3036         switch (ob->type) {
3037                 case OB_MESH:
3038                         return insert_meshkey(scene, ob, name, from_mix);
3039                 case OB_CURVE:
3040                 case OB_SURF:
3041                         return insert_curvekey(scene, ob, name, from_mix);
3042                 case OB_LATTICE:
3043                         return insert_lattkey(scene, ob, name, from_mix);
3044                 default:
3045                         return NULL;
3046         }
3047
3048 }
3049
3050 /* most important if this is modified it should _always_ return True, in certain
3051  * cases false positives are hard to avoid (shape keys for example) */
3052 int BKE_object_is_modified(Scene *scene, Object *ob)
3053 {
3054         int flag = 0;
3055
3056         if (BKE_key_from_object(ob)) {
3057                 flag |= eModifierMode_Render;
3058         }
3059         else {
3060                 ModifierData *md;
3061                 /* cloth */
3062                 for (md = modifiers_getVirtualModifierList(ob);
3063                      md && (flag != (eModifierMode_Render | eModifierMode_Realtime));
3064                      md = md->next)
3065                 {
3066                         if ((flag & eModifierMode_Render) == 0 && modifier_isEnabled(scene, md, eModifierMode_Render))
3067                                 flag |= eModifierMode_Render;
3068
3069                         if ((flag & eModifierMode_Realtime) == 0 && modifier_isEnabled(scene, md, eModifierMode_Realtime))
3070                                 flag |= eModifierMode_Realtime;
3071                 }
3072         }
3073
3074         return flag;
3075 }
3076
3077 /* test if object is affected by deforming modifiers (for motion blur). again
3078  * most important is to avoid false positives, this is to skip computations
3079  * and we can still if there was actual deformation afterwards */
3080 int BKE_object_is_deform_modified(Scene *scene, Object *ob)
3081 {
3082         ModifierData *md;
3083         int flag = 0;
3084
3085