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