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