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