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