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