Fix for [#27038] Bugs when linking particles/collision/softbody modifiers
[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(ob, from);
212         copy_object_softbody(ob, from);
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                 if(gob->dup_group) { /* should always be true */
1567                         sub_v3_v3(ob->obmat[3], gob->dup_group->dupli_ofs);
1568                 }
1569                 object_apply_mat4(ob, ob->obmat, FALSE, TRUE);
1570         }
1571         else {
1572                 copy_object_transform(ob, target);
1573                 ob->parent= target->parent;     /* libdata */
1574                 copy_m4_m4(ob->parentinv, target->parentinv);
1575         }
1576         
1577         /* copy animdata stuff - drivers only for now... */
1578         object_copy_proxy_drivers(ob, target);
1579
1580         /* skip constraints? */
1581         // FIXME: this is considered by many as a bug
1582         
1583         /* set object type and link to data */
1584         ob->type= target->type;
1585         ob->data= target->data;
1586         id_us_plus((ID *)ob->data);             /* ensures lib data becomes LIB_EXTERN */
1587         
1588         /* copy material and index information */
1589         ob->actcol= ob->totcol= 0;
1590         if(ob->mat) MEM_freeN(ob->mat);
1591         if(ob->matbits) MEM_freeN(ob->matbits);
1592         ob->mat = NULL;
1593         ob->matbits= NULL;
1594         if ((target->totcol) && (target->mat) && ELEM5(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL)) { //XXX OB_SUPPORT_MATERIAL
1595                 int i;
1596                 ob->colbits = target->colbits;
1597                 
1598                 ob->actcol= target->actcol;
1599                 ob->totcol= target->totcol;
1600                 
1601                 ob->mat = MEM_dupallocN(target->mat);
1602                 ob->matbits = MEM_dupallocN(target->matbits);
1603                 for(i=0; i<target->totcol; i++) {
1604                         /* dont need to run test_object_materials since we know this object is new and not used elsewhere */
1605                         id_us_plus((ID *)ob->mat[i]); 
1606                 }
1607         }
1608         
1609         /* type conversions */
1610         if(target->type == OB_ARMATURE) {
1611                 copy_object_pose(ob, target);   /* data copy, object pointers in constraints */
1612                 rest_pose(ob->pose);                    /* clear all transforms in channels */
1613                 armature_rebuild_pose(ob, ob->data);    /* set all internal links */
1614                 
1615                 armature_set_id_extern(ob);
1616         }
1617
1618         /* copy IDProperties */
1619         if(ob->id.properties) {
1620                 IDP_FreeProperty(ob->id.properties);
1621                 MEM_freeN(ob->id.properties);
1622                 ob->id.properties= NULL;
1623         }
1624         if(target->id.properties) {
1625                 ob->id.properties= IDP_CopyProperty(target->id.properties);
1626         }
1627
1628         /* copy drawtype info */
1629         ob->dt= target->dt;
1630 }
1631
1632
1633 /* *************** CALC ****************** */
1634
1635 /* there is also a timing calculation in drawobject() */
1636
1637 static int no_speed_curve= 0;
1638
1639 void disable_speed_curve(int val)
1640 {
1641         no_speed_curve= val;
1642 }
1643
1644 // XXX THIS CRUFT NEEDS SERIOUS RECODING ASAP!
1645 /* ob can be NULL */
1646 float bsystem_time(struct Scene *scene, Object *UNUSED(ob), float cfra, float ofs)
1647 {
1648         /* returns float ( see BKE_curframe in scene.c) */
1649         cfra += scene->r.subframe;
1650         
1651         /* global time */
1652         if (scene)
1653                 cfra*= scene->r.framelen;       
1654         
1655 #if 0 // XXX old animation system
1656         if (ob) {
1657                 /* ofset frames */
1658                 if ((ob->ipoflag & OB_OFFS_PARENT) && (ob->partype & PARSLOW)==0) 
1659                         cfra-= give_timeoffset(ob);
1660         }
1661 #endif // XXX old animation system
1662         
1663         cfra-= ofs;
1664
1665         return cfra;
1666 }
1667
1668 void object_scale_to_mat3(Object *ob, float mat[][3])
1669 {
1670         float vec[3];
1671         add_v3_v3v3(vec, ob->size, ob->dsize);
1672         size_to_mat3( mat,vec);
1673 }
1674
1675
1676 void object_rot_to_mat3(Object *ob, float mat[][3])
1677 {
1678         float rmat[3][3], dmat[3][3];
1679         
1680         /* initialise the delta-rotation matrix, which will get (pre)multiplied 
1681          * with the rotation matrix to yield the appropriate rotation
1682          */
1683         unit_m3(dmat);
1684         
1685         /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
1686         if (ob->rotmode > 0) {
1687                 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
1688                 eulO_to_mat3( rmat,ob->rot, ob->rotmode);
1689                 eulO_to_mat3( dmat,ob->drot, ob->rotmode);
1690         }
1691         else if (ob->rotmode == ROT_MODE_AXISANGLE) {
1692                 /* axis-angle -  not really that great for 3D-changing orientations */
1693                 axis_angle_to_mat3( rmat,ob->rotAxis, ob->rotAngle);
1694                 axis_angle_to_mat3( dmat,ob->drotAxis, ob->drotAngle);
1695         }
1696         else {
1697                 /* quats are normalised before use to eliminate scaling issues */
1698                 float tquat[4];
1699                 
1700                 normalize_qt_qt(tquat, ob->quat);
1701                 quat_to_mat3(rmat, tquat);
1702                 
1703                 normalize_qt_qt(tquat, ob->dquat);
1704                 quat_to_mat3(dmat, tquat);
1705         }
1706         
1707         /* combine these rotations */
1708         mul_m3_m3m3(mat, dmat, rmat);
1709 }
1710
1711 void object_mat3_to_rot(Object *ob, float mat[][3], short use_compat)
1712 {
1713         switch(ob->rotmode) {
1714         case ROT_MODE_QUAT:
1715                 {
1716                         float dquat[4];
1717                         mat3_to_quat(ob->quat, mat);
1718                         normalize_qt_qt(dquat, ob->dquat);
1719                         invert_qt(dquat);
1720                         mul_qt_qtqt(ob->quat, dquat, ob->quat);
1721                 }
1722                 break;
1723         case ROT_MODE_AXISANGLE:
1724                 mat3_to_axis_angle(ob->rotAxis, &ob->rotAngle, mat);
1725                 sub_v3_v3(ob->rotAxis, ob->drotAxis);
1726                 ob->rotAngle -= ob->drotAngle;
1727                 break;
1728         default: /* euler */
1729                 if(use_compat)  mat3_to_compatible_eulO(ob->rot, ob->rot, ob->rotmode, mat);
1730                 else                    mat3_to_eulO(ob->rot, ob->rotmode, mat);
1731                 sub_v3_v3(ob->rot, ob->drot);
1732         }
1733 }
1734
1735 /* see pchan_apply_mat4() for the equivalent 'pchan' function */
1736 void object_apply_mat4(Object *ob, float mat[][4], const short use_compat, const short use_parent)
1737 {
1738         float rot[3][3];
1739
1740         if(use_parent && ob->parent) {
1741                 float rmat[4][4], diff_mat[4][4], imat[4][4];
1742                 mul_m4_m4m4(diff_mat, ob->parentinv, ob->parent->obmat);
1743                 invert_m4_m4(imat, diff_mat);
1744                 mul_m4_m4m4(rmat, mat, imat); /* get the parent relative matrix */
1745                 object_apply_mat4(ob, rmat, use_compat, FALSE);
1746                 
1747                 /* same as below, use rmat rather then mat */
1748                 mat4_to_loc_rot_size(ob->loc, rot, ob->size, rmat);
1749                 object_mat3_to_rot(ob, rot, use_compat);
1750         }
1751         else {
1752                 mat4_to_loc_rot_size(ob->loc, rot, ob->size, mat);
1753                 object_mat3_to_rot(ob, rot, use_compat);
1754         }
1755         
1756         sub_v3_v3(ob->loc, ob->dloc);
1757         sub_v3_v3(ob->size, ob->dsize);
1758         /* object_mat3_to_rot handles delta rotations */
1759 }
1760
1761 void object_to_mat3(Object *ob, float mat[][3]) /* no parent */
1762 {
1763         float smat[3][3];
1764         float rmat[3][3];
1765         /*float q1[4];*/
1766         
1767         /* size */
1768         object_scale_to_mat3(ob, smat);
1769
1770         /* rot */
1771         object_rot_to_mat3(ob, rmat);
1772         mul_m3_m3m3(mat, rmat, smat);
1773 }
1774
1775 void object_to_mat4(Object *ob, float mat[][4])
1776 {
1777         float tmat[3][3];
1778         
1779         object_to_mat3(ob, tmat);
1780         
1781         copy_m4_m3(mat, tmat);
1782
1783         add_v3_v3v3(mat[3], ob->loc, ob->dloc);
1784 }
1785
1786 /* extern */
1787 int enable_cu_speed= 1;
1788
1789 static void ob_parcurve(Scene *scene, Object *ob, Object *par, float mat[][4])
1790 {
1791         Curve *cu;
1792         float vec[4], dir[3], quat[4], radius, ctime;
1793         float timeoffs = 0.0, sf_orig = 0.0;
1794         
1795         unit_m4(mat);
1796         
1797         cu= par->data;
1798         if(cu->path==NULL || cu->path->data==NULL) /* only happens on reload file, but violates depsgraph still... fix! */
1799                 makeDispListCurveTypes(scene, par, 0);
1800         if(cu->path==NULL) return;
1801         
1802         /* exception, timeoffset is regarded as distance offset */
1803         if(cu->flag & CU_OFFS_PATHDIST) {
1804                 timeoffs = give_timeoffset(ob);
1805                 SWAP(float, sf_orig, ob->sf);
1806         }
1807         
1808         /* catch exceptions: feature for nla stride editing */
1809         if(ob->ipoflag & OB_DISABLE_PATH) {
1810                 ctime= 0.0f;
1811         }
1812         /* catch exceptions: curve paths used as a duplicator */
1813         else if(enable_cu_speed) {
1814                 /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated,
1815                  * but this will only work if it actually is animated... 
1816                  *
1817                  * we divide the curvetime calculated in the previous step by the length of the path, to get a time
1818                  * factor, which then gets clamped to lie within 0.0 - 1.0 range
1819                  */
1820                 if (IS_EQF(cu->pathlen, 0.0f) == 0)
1821                         ctime= cu->ctime / cu->pathlen;
1822                 else
1823                         ctime= cu->ctime;
1824
1825                 CLAMP(ctime, 0.0f, 1.0f);
1826         }
1827         else {
1828                 ctime= scene->r.cfra - give_timeoffset(ob);
1829                 if (IS_EQF(cu->pathlen, 0.0f) == 0)
1830                         ctime /= cu->pathlen;
1831                 
1832                 CLAMP(ctime, 0.0f, 1.0f);
1833         }
1834         
1835         /* time calculus is correct, now apply distance offset */
1836         if(cu->flag & CU_OFFS_PATHDIST) {
1837                 ctime += timeoffs/cu->path->totdist;
1838
1839                 /* restore */
1840                 SWAP(float, sf_orig, ob->sf);
1841         }
1842         
1843         
1844         /* vec: 4 items! */
1845         if( where_on_path(par, ctime, vec, dir, cu->flag & CU_FOLLOW ? quat:NULL, &radius, NULL) ) {
1846
1847                 if(cu->flag & CU_FOLLOW) {
1848 #if 0
1849                         float x1, q[4];
1850                         vec_to_quat( quat,dir, ob->trackflag, ob->upflag);
1851                         
1852                         /* the tilt */
1853                         normalize_v3(dir);
1854                         q[0]= (float)cos(0.5*vec[3]);
1855                         x1= (float)sin(0.5*vec[3]);
1856                         q[1]= -x1*dir[0];
1857                         q[2]= -x1*dir[1];
1858                         q[3]= -x1*dir[2];
1859                         mul_qt_qtqt(quat, q, quat);
1860 #else
1861                         quat_apply_track(quat, ob->trackflag, ob->upflag);
1862 #endif
1863                         normalize_qt(quat);
1864                         quat_to_mat4(mat, quat);
1865                 }
1866                 
1867                 if(cu->flag & CU_PATH_RADIUS) {
1868                         float tmat[4][4], rmat[4][4];
1869                         scale_m4_fl(tmat, radius);
1870                         mul_m4_m4m4(rmat, mat, tmat);
1871                         copy_m4_m4(mat, rmat);
1872                 }
1873
1874                 copy_v3_v3(mat[3], vec);
1875                 
1876         }
1877 }
1878
1879 static void ob_parbone(Object *ob, Object *par, float mat[][4])
1880 {       
1881         bPoseChannel *pchan;
1882         float vec[3];
1883         
1884         if (par->type!=OB_ARMATURE) {
1885                 unit_m4(mat);
1886                 return;
1887         }
1888         
1889         /* Make sure the bone is still valid */
1890         pchan= get_pose_channel(par->pose, ob->parsubstr);
1891         if (!pchan){
1892                 printf ("Object %s with Bone parent: bone %s doesn't exist\n", ob->id.name+2, ob->parsubstr);
1893                 unit_m4(mat);
1894                 return;
1895         }
1896
1897         /* get bone transform */
1898         copy_m4_m4(mat, pchan->pose_mat);
1899
1900         /* but for backwards compatibility, the child has to move to the tail */
1901         copy_v3_v3(vec, mat[1]);
1902         mul_v3_fl(vec, pchan->bone->length);
1903         add_v3_v3(mat[3], vec);
1904 }
1905
1906 static void give_parvert(Object *par, int nr, float *vec)
1907 {
1908         EditMesh *em;
1909         int a, count;
1910         
1911         vec[0]=vec[1]=vec[2]= 0.0f;
1912         
1913         if(par->type==OB_MESH) {
1914                 Mesh *me= par->data;
1915                 DerivedMesh *dm;
1916
1917                 em = BKE_mesh_get_editmesh(me);
1918                 dm = (em)? em->derivedFinal: par->derivedFinal;
1919                         
1920                 if(dm) {
1921                         MVert *mvert= dm->getVertArray(dm);
1922                         int *index = (int *)dm->getVertDataArray(dm, CD_ORIGINDEX);
1923                         int i, count = 0, vindex, numVerts = dm->getNumVerts(dm);
1924
1925                         /* get the average of all verts with (original index == nr) */
1926                         for(i = 0; i < numVerts; i++) {
1927                                 vindex= (index)? index[i]: i;
1928
1929                                 if(vindex == nr) {
1930                                         add_v3_v3(vec, mvert[i].co);
1931                                         count++;
1932                                 }
1933                         }
1934
1935                         if (count==0) {
1936                                 /* keep as 0,0,0 */
1937                         } else if(count > 0) {
1938                                 mul_v3_fl(vec, 1.0f / count);
1939                         } else {
1940                                 /* use first index if its out of range */
1941                                 dm->getVertCo(dm, 0, vec);
1942                         }
1943                 }
1944
1945                 if(em)
1946                         BKE_mesh_end_editmesh(me, em);
1947         }
1948         else if (ELEM(par->type, OB_CURVE, OB_SURF)) {
1949                 Nurb *nu;
1950                 Curve *cu;
1951                 BPoint *bp;
1952                 BezTriple *bezt;
1953                 int found= 0;
1954                 ListBase *nurbs;
1955
1956                 cu= par->data;
1957                 nurbs= BKE_curve_nurbs(cu);
1958                 nu= nurbs->first;
1959
1960                 count= 0;
1961                 while(nu && !found) {
1962                         if(nu->type == CU_BEZIER) {
1963                                 bezt= nu->bezt;
1964                                 a= nu->pntsu;
1965                                 while(a--) {
1966                                         if(count==nr) {
1967                                                 found= 1;
1968                                                 VECCOPY(vec, bezt->vec[1]);
1969                                                 break;
1970                                         }
1971                                         count++;
1972                                         bezt++;
1973                                 }
1974                         }
1975                         else {
1976                                 bp= nu->bp;
1977                                 a= nu->pntsu*nu->pntsv;
1978                                 while(a--) {
1979                                         if(count==nr) {
1980                                                 found= 1;
1981                                                 memcpy(vec, bp->vec, sizeof(float)*3);
1982                                                 break;
1983                                         }
1984                                         count++;
1985                                         bp++;
1986                                 }
1987                         }
1988                         nu= nu->next;
1989                 }
1990
1991         }
1992         else if(par->type==OB_LATTICE) {
1993                 Lattice *latt= par->data;
1994                 BPoint *bp;
1995                 DispList *dl = find_displist(&par->disp, DL_VERTS);
1996                 float *co = dl?dl->verts:NULL;
1997                 
1998                 if(latt->editlatt) latt= latt->editlatt->latt;
1999                 
2000                 a= latt->pntsu*latt->pntsv*latt->pntsw;
2001                 count= 0;
2002                 bp= latt->def;
2003                 while(a--) {
2004                         if(count==nr) {
2005                                 if(co)
2006                                         memcpy(vec, co, 3*sizeof(float));
2007                                 else
2008                                         memcpy(vec, bp->vec, 3*sizeof(float));
2009                                 break;
2010                         }
2011                         count++;
2012                         if(co) co+= 3;
2013                         else bp++;
2014                 }
2015         }
2016 }
2017
2018 static void ob_parvert3(Object *ob, Object *par, float mat[][4])
2019 {
2020         float cmat[3][3], v1[3], v2[3], v3[3], q[4];
2021
2022         /* in local ob space */
2023         unit_m4(mat);
2024         
2025         if (ELEM4(par->type, OB_MESH, OB_SURF, OB_CURVE, OB_LATTICE)) {
2026                 
2027                 give_parvert(par, ob->par1, v1);
2028                 give_parvert(par, ob->par2, v2);
2029                 give_parvert(par, ob->par3, v3);
2030                                 
2031                 tri_to_quat( q,v1, v2, v3);
2032                 quat_to_mat3( cmat,q);
2033                 copy_m4_m3(mat, cmat);
2034                 
2035                 if(ob->type==OB_CURVE) {
2036                         VECCOPY(mat[3], v1);
2037                 }
2038                 else {
2039                         add_v3_v3v3(mat[3], v1, v2);
2040                         add_v3_v3(mat[3], v3);
2041                         mul_v3_fl(mat[3], 0.3333333f);
2042                 }
2043         }
2044 }
2045
2046 // XXX what the hell is this?
2047 static int no_parent_ipo=0;
2048 void set_no_parent_ipo(int val)
2049 {
2050         no_parent_ipo= val;
2051 }
2052
2053 void where_is_object_time(Scene *scene, Object *ob, float ctime)
2054 {
2055         float *fp1, *fp2, slowmat[4][4] = MAT4_UNITY;
2056         float stime=ctime, fac1, fac2;
2057         int a;
2058         
2059         /* new version: correct parent+vertexparent and track+parent */
2060         /* this one only calculates direct attached parent and track */
2061         /* is faster, but should keep track of timeoffs */
2062         
2063         if(ob==NULL) return;
2064         
2065         /* execute drivers only, as animation has already been done */
2066         BKE_animsys_evaluate_animdata(&ob->id, ob->adt, ctime, ADT_RECALC_DRIVERS);
2067         
2068         if(ob->parent) {
2069                 Object *par= ob->parent;
2070                 
2071                 // XXX depreceated - animsys
2072                 if(ob->ipoflag & OB_OFFS_PARENT) ctime-= give_timeoffset(ob);
2073                 
2074                 /* hurms, code below conflicts with depgraph... (ton) */
2075                 /* and even worse, it gives bad effects for NLA stride too (try ctime != par->ctime, with MBlur) */
2076                 if(no_parent_ipo==0 && stime != par->ctime) {
2077                         // only for ipo systems? 
2078                         Object tmp= *par;
2079                         
2080                         if(par->proxy_from);    // was a copied matrix, no where_is! bad...
2081                         else where_is_object_time(scene, par, ctime);
2082
2083                         solve_parenting(scene, ob, par, ob->obmat, slowmat, 0);
2084
2085                         *par= tmp;
2086                 }
2087                 else
2088                         solve_parenting(scene, ob, par, ob->obmat, slowmat, 0);
2089                 
2090                 if(ob->partype & PARSLOW) {
2091                         // include framerate
2092                         fac1= ( 1.0f / (1.0f + (float)fabs(give_timeoffset(ob))) );
2093                         if(fac1 >= 1.0f) return;
2094                         fac2= 1.0f-fac1;
2095                         
2096                         fp1= ob->obmat[0];
2097                         fp2= slowmat[0];
2098                         for(a=0; a<16; a++, fp1++, fp2++) {
2099                                 fp1[0]= fac1*fp1[0] + fac2*fp2[0];
2100                         }
2101                 }
2102         }
2103         else {
2104                 object_to_mat4(ob, ob->obmat);
2105         }
2106
2107         /* solve constraints */
2108         if (ob->constraints.first && !(ob->transflag & OB_NO_CONSTRAINTS)) {
2109                 bConstraintOb *cob;
2110                 
2111                 cob= constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2112                 
2113                 /* constraints need ctime, not stime. Some call where_is_object_time and bsystem_time */
2114                 solve_constraints (&ob->constraints, cob, ctime);
2115                 
2116                 constraints_clear_evalob(cob);
2117         }
2118         
2119         /* set negative scale flag in object */
2120         if(is_negative_m4(ob->obmat))   ob->transflag |= OB_NEG_SCALE;
2121         else                                                    ob->transflag &= ~OB_NEG_SCALE;
2122 }
2123
2124 static void solve_parenting (Scene *scene, Object *ob, Object *par, float obmat[][4], float slowmat[][4], int simul)
2125 {
2126         float totmat[4][4];
2127         float tmat[4][4];
2128         float locmat[4][4];
2129         float vec[3];
2130         int ok;
2131         
2132         object_to_mat4(ob, locmat);
2133         
2134         if(ob->partype & PARSLOW) copy_m4_m4(slowmat, obmat);
2135
2136         switch(ob->partype & PARTYPE) {
2137         case PAROBJECT:
2138                 ok= 0;
2139                 if(par->type==OB_CURVE) {
2140                         if( ((Curve *)par->data)->flag & CU_PATH ) {
2141                                 ob_parcurve(scene, ob, par, tmat);
2142                                 ok= 1;
2143                         }
2144                 }
2145                 
2146                 if(ok) mul_serie_m4(totmat, par->obmat, tmat, 
2147                         NULL, NULL, NULL, NULL, NULL, NULL);
2148                 else copy_m4_m4(totmat, par->obmat);
2149                 
2150                 break;
2151         case PARBONE:
2152                 ob_parbone(ob, par, tmat);
2153                 mul_serie_m4(totmat, par->obmat, tmat,         
2154                         NULL, NULL, NULL, NULL, NULL, NULL);
2155                 break;
2156                 
2157         case PARVERT1:
2158                 unit_m4(totmat);
2159                 if (simul){
2160                         VECCOPY(totmat[3], par->obmat[3]);
2161                 }
2162                 else{
2163                         give_parvert(par, ob->par1, vec);
2164                         mul_v3_m4v3(totmat[3], par->obmat, vec);
2165                 }
2166                 break;
2167         case PARVERT3:
2168                 ob_parvert3(ob, par, tmat);
2169                 
2170                 mul_serie_m4(totmat, par->obmat, tmat,         
2171                         NULL, NULL, NULL, NULL, NULL, NULL);
2172                 break;
2173                 
2174         case PARSKEL:
2175                 copy_m4_m4(totmat, par->obmat);
2176                 break;
2177         }
2178         
2179         // total 
2180         mul_serie_m4(tmat, totmat, ob->parentinv,         
2181                 NULL, NULL, NULL, NULL, NULL, NULL);
2182         mul_serie_m4(obmat, tmat, locmat,         
2183                 NULL, NULL, NULL, NULL, NULL, NULL);
2184         
2185         if (simul) {
2186
2187         }
2188         else{
2189                 // external usable originmat 
2190                 copy_m3_m4(originmat, tmat);
2191                 
2192                 // origin, voor help line
2193                 if( (ob->partype & PARTYPE)==PARSKEL ) {
2194                         VECCOPY(ob->orig, par->obmat[3]);
2195                 }
2196                 else {
2197                         VECCOPY(ob->orig, totmat[3]);
2198                 }
2199         }
2200
2201 }
2202
2203 void where_is_object(struct Scene *scene, Object *ob)
2204 {
2205         where_is_object_time(scene, ob, (float)scene->r.cfra);
2206 }
2207
2208
2209 void where_is_object_simul(Scene *scene, Object *ob)
2210 /* was written for the old game engine (until 2.04) */
2211 /* It seems that this function is only called
2212 for a lamp that is the child of another object */
2213 {
2214         Object *par;
2215         //Ipo *ipo;
2216         float *fp1, *fp2;
2217         float slowmat[4][4];
2218         float fac1, fac2;
2219         int a;
2220         
2221         /* NO TIMEOFFS */
2222         if(ob->parent) {
2223                 par= ob->parent;
2224                 
2225                 solve_parenting(scene, ob, par, ob->obmat, slowmat, 1);
2226
2227                 if(ob->partype & PARSLOW) {
2228
2229                         fac1= (float)(1.0/(1.0+ fabs(give_timeoffset(ob))));
2230                         fac2= 1.0f-fac1;
2231                         fp1= ob->obmat[0];
2232                         fp2= slowmat[0];
2233                         for(a=0; a<16; a++, fp1++, fp2++) {
2234                                 fp1[0]= fac1*fp1[0] + fac2*fp2[0];
2235                         }
2236                 }
2237                 
2238         }
2239         else {
2240                 object_to_mat4(ob, ob->obmat);
2241         }
2242         
2243         /* solve constraints */
2244         if (ob->constraints.first) {
2245                 bConstraintOb *cob;
2246                 
2247                 cob= constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2248                 solve_constraints(&ob->constraints, cob, (float)scene->r.cfra);
2249                 constraints_clear_evalob(cob);
2250         }
2251 }
2252
2253 /* for calculation of the inverse parent transform, only used for editor */
2254 void what_does_parent(Scene *scene, Object *ob, Object *workob)
2255 {
2256         clear_workob(workob);
2257         
2258         unit_m4(workob->obmat);
2259         unit_m4(workob->parentinv);
2260         unit_m4(workob->constinv);
2261         workob->parent= ob->parent;
2262
2263         workob->trackflag= ob->trackflag;
2264         workob->upflag= ob->upflag;
2265         
2266         workob->partype= ob->partype;
2267         workob->par1= ob->par1;
2268         workob->par2= ob->par2;
2269         workob->par3= ob->par3;
2270
2271         workob->constraints.first = ob->constraints.first;
2272         workob->constraints.last = ob->constraints.last;
2273
2274         strcpy(workob->parsubstr, ob->parsubstr); 
2275
2276         where_is_object(scene, workob);
2277 }
2278
2279 BoundBox *unit_boundbox(void)
2280 {
2281         BoundBox *bb;
2282         float min[3] = {-1.0f,-1.0f,-1.0f}, max[3] = {-1.0f,-1.0f,-1.0f};
2283
2284         bb= MEM_callocN(sizeof(BoundBox), "bb");
2285         boundbox_set_from_min_max(bb, min, max);
2286         
2287         return bb;
2288 }
2289
2290 void boundbox_set_from_min_max(BoundBox *bb, float min[3], float max[3])
2291 {
2292         bb->vec[0][0]=bb->vec[1][0]=bb->vec[2][0]=bb->vec[3][0]= min[0];
2293         bb->vec[4][0]=bb->vec[5][0]=bb->vec[6][0]=bb->vec[7][0]= max[0];
2294         
2295         bb->vec[0][1]=bb->vec[1][1]=bb->vec[4][1]=bb->vec[5][1]= min[1];
2296         bb->vec[2][1]=bb->vec[3][1]=bb->vec[6][1]=bb->vec[7][1]= max[1];
2297
2298         bb->vec[0][2]=bb->vec[3][2]=bb->vec[4][2]=bb->vec[7][2]= min[2];
2299         bb->vec[1][2]=bb->vec[2][2]=bb->vec[5][2]=bb->vec[6][2]= max[2];
2300 }
2301
2302 BoundBox *object_get_boundbox(Object *ob)
2303 {
2304         BoundBox *bb= NULL;
2305         
2306         if(ob->type==OB_MESH) {
2307                 bb = mesh_get_bb(ob);
2308         }
2309         else if (ELEM3(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2310                 bb= ob->bb ? ob->bb : ( (Curve *)ob->data )->bb;
2311         }
2312         else if(ob->type==OB_MBALL) {
2313                 bb= ob->bb;
2314         }
2315         return bb;
2316 }
2317
2318 /* used to temporally disable/enable boundbox */
2319 void object_boundbox_flag(Object *ob, int flag, int set)
2320 {
2321         BoundBox *bb= object_get_boundbox(ob);
2322         if(bb) {
2323                 if(set) bb->flag |= flag;
2324                 else bb->flag &= ~flag;
2325         }
2326 }
2327
2328 void object_get_dimensions(Object *ob, float *value)
2329 {
2330         BoundBox *bb = NULL;
2331         
2332         bb= object_get_boundbox(ob);
2333         if (bb) {
2334                 float scale[3];
2335                 
2336                 mat4_to_size( scale,ob->obmat);
2337                 
2338                 value[0] = fabsf(scale[0]) * (bb->vec[4][0] - bb->vec[0][0]);
2339                 value[1] = fabsf(scale[1]) * (bb->vec[2][1] - bb->vec[0][1]);
2340                 value[2] = fabsf(scale[2]) * (bb->vec[1][2] - bb->vec[0][2]);
2341         } else {
2342                 value[0] = value[1] = value[2] = 0.f;
2343         }
2344 }
2345
2346 void object_set_dimensions(Object *ob, const float *value)
2347 {
2348         BoundBox *bb = NULL;
2349         
2350         bb= object_get_boundbox(ob);
2351         if (bb) {
2352                 float scale[3], len[3];
2353                 
2354                 mat4_to_size( scale,ob->obmat);
2355                 
2356                 len[0] = bb->vec[4][0] - bb->vec[0][0];
2357                 len[1] = bb->vec[2][1] - bb->vec[0][1];
2358                 len[2] = bb->vec[1][2] - bb->vec[0][2];
2359                 
2360                 if (len[0] > 0.f) ob->size[0] = value[0] / len[0];
2361                 if (len[1] > 0.f) ob->size[1] = value[1] / len[1];
2362                 if (len[2] > 0.f) ob->size[2] = value[2] / len[2];
2363         }
2364 }
2365
2366 void minmax_object(Object *ob, float *min, float *max)
2367 {
2368         BoundBox bb;
2369         Mesh *me;
2370         Curve *cu;
2371         float vec[3];
2372         int a;
2373         
2374         switch(ob->type) {
2375                 
2376         case OB_CURVE:
2377         case OB_FONT:
2378         case OB_SURF:
2379                 cu= ob->data;
2380                 
2381                 if(cu->bb==NULL) tex_space_curve(cu);
2382                 bb= *(cu->bb);
2383                 
2384                 for(a=0; a<8; a++) {
2385                         mul_m4_v3(ob->obmat, bb.vec[a]);
2386                         DO_MINMAX(bb.vec[a], min, max);
2387                 }
2388                 break;
2389         case OB_ARMATURE:
2390                 if(ob->pose) {
2391                         bPoseChannel *pchan;
2392                         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2393                                 mul_v3_m4v3(vec, ob->obmat, pchan->pose_head);
2394                                 DO_MINMAX(vec, min, max);
2395                                 mul_v3_m4v3(vec, ob->obmat, pchan->pose_tail);
2396                                 DO_MINMAX(vec, min, max);
2397                         }
2398                         break;
2399                 }
2400                 /* no break, get_mesh will give NULL and it passes on to default */
2401         case OB_MESH:
2402                 me= get_mesh(ob);
2403                 
2404                 if(me) {
2405                         bb = *mesh_get_bb(ob);
2406                         
2407                         for(a=0; a<8; a++) {
2408                                 mul_m4_v3(ob->obmat, bb.vec[a]);
2409                                 DO_MINMAX(bb.vec[a], min, max);
2410                         }
2411                 }
2412                 if(min[0] < max[0] ) break;
2413                 
2414                 /* else here no break!!!, mesh can be zero sized */
2415                 
2416         default:
2417                 DO_MINMAX(ob->obmat[3], min, max);
2418
2419                 copy_v3_v3(vec, ob->obmat[3]);
2420                 add_v3_v3(vec, ob->size);
2421                 DO_MINMAX(vec, min, max);
2422
2423                 copy_v3_v3(vec, ob->obmat[3]);
2424                 sub_v3_v3(vec, ob->size);
2425                 DO_MINMAX(vec, min, max);
2426                 break;
2427         }
2428 }
2429
2430 int minmax_object_duplis(Scene *scene, Object *ob, float *min, float *max)
2431 {
2432         int ok= 0;
2433         if ((ob->transflag & OB_DUPLI)==0) {
2434                 return ok;
2435         } else {
2436                 ListBase *lb;
2437                 DupliObject *dob;
2438                 
2439                 lb= object_duplilist(scene, ob);
2440                 for(dob= lb->first; dob; dob= dob->next) {
2441                         if(dob->no_draw == 0) {
2442                                 BoundBox *bb= object_get_boundbox(dob->ob);
2443
2444                                 if(bb) {
2445                                         int i;
2446                                         for(i=0; i<8; i++) {
2447                                                 float vec[3];
2448                                                 mul_v3_m4v3(vec, dob->mat, bb->vec[i]);
2449                                                 DO_MINMAX(vec, min, max);
2450                                         }
2451
2452                                         ok= 1;
2453                                 }
2454                         }
2455                 }
2456                 free_object_duplilist(lb);      /* does restore */
2457         }
2458
2459         return ok;
2460 }
2461
2462 /* copied from DNA_object_types.h */
2463 typedef struct ObTfmBack {
2464         float loc[3], dloc[3], orig[3];
2465         float size[3], dsize[3];        /* scale and delta scale */
2466         float rot[3], drot[3];          /* euler rotation */
2467         float quat[4], dquat[4];        /* quaternion rotation */
2468         float rotAxis[3], drotAxis[3];  /* axis angle rotation - axis part */
2469         float rotAngle, drotAngle;      /* axis angle rotation - angle part */
2470         float obmat[4][4];              /* final worldspace matrix with constraints & animsys applied */
2471         float parentinv[4][4]; /* inverse result of parent, so that object doesn't 'stick' to parent */
2472         float constinv[4][4]; /* inverse result of constraints. doesn't include effect of parent or object local transform */
2473         float imat[4][4];       /* inverse matrix of 'obmat' for during render, old game engine, temporally: ipokeys of transform  */
2474 } ObTfmBack;
2475
2476 void *object_tfm_backup(Object *ob)
2477 {
2478         ObTfmBack *obtfm= MEM_mallocN(sizeof(ObTfmBack), "ObTfmBack");
2479         copy_v3_v3(obtfm->loc, ob->loc);
2480         copy_v3_v3(obtfm->dloc, ob->dloc);
2481         copy_v3_v3(obtfm->orig, ob->orig);
2482         copy_v3_v3(obtfm->size, ob->size);
2483         copy_v3_v3(obtfm->dsize, ob->dsize);
2484         copy_v3_v3(obtfm->rot, ob->rot);
2485         copy_v3_v3(obtfm->drot, ob->drot);
2486         copy_qt_qt(obtfm->quat, ob->quat);
2487         copy_qt_qt(obtfm->dquat, ob->dquat);
2488         copy_v3_v3(obtfm->rotAxis, ob->rotAxis);
2489         copy_v3_v3(obtfm->drotAxis, ob->drotAxis);
2490         obtfm->rotAngle= ob->rotAngle;
2491         obtfm->drotAngle= ob->drotAngle;
2492         copy_m4_m4(obtfm->obmat, ob->obmat);
2493         copy_m4_m4(obtfm->parentinv, ob->parentinv);
2494         copy_m4_m4(obtfm->constinv, ob->constinv);
2495         copy_m4_m4(obtfm->imat, ob->imat);
2496
2497         return (void *)obtfm;
2498 }
2499
2500 void object_tfm_restore(Object *ob, void *obtfm_pt)
2501 {
2502         ObTfmBack *obtfm= (ObTfmBack *)obtfm_pt;
2503         copy_v3_v3(ob->loc, obtfm->loc);
2504         copy_v3_v3(ob->dloc, obtfm->dloc);
2505         copy_v3_v3(ob->orig, obtfm->orig);
2506         copy_v3_v3(ob->size, obtfm->size);
2507         copy_v3_v3(ob->dsize, obtfm->dsize);
2508         copy_v3_v3(ob->rot, obtfm->rot);
2509         copy_v3_v3(ob->drot, obtfm->drot);
2510         copy_qt_qt(ob->quat, obtfm->quat);
2511         copy_qt_qt(ob->dquat, obtfm->dquat);
2512         copy_v3_v3(ob->rotAxis, obtfm->rotAxis);
2513         copy_v3_v3(ob->drotAxis, obtfm->drotAxis);
2514         ob->rotAngle= obtfm->rotAngle;
2515         ob->drotAngle= obtfm->drotAngle;
2516         copy_m4_m4(ob->obmat, obtfm->obmat);
2517         copy_m4_m4(ob->parentinv, obtfm->parentinv);
2518         copy_m4_m4(ob->constinv, obtfm->constinv);
2519         copy_m4_m4(ob->imat, obtfm->imat);
2520 }
2521
2522 /* proxy rule: lib_object->proxy_from == the one we borrow from, only set temporal and cleared here */
2523 /*           local_object->proxy      == pointer to library object, saved in files and read */
2524
2525 /* function below is polluted with proxy exceptions, cleanup will follow! */
2526
2527 /* the main object update call, for object matrix, constraints, keys and displist (modifiers) */
2528 /* requires flags to be set! */
2529 void object_handle_update(Scene *scene, Object *ob)
2530 {
2531         if(ob->recalc & OB_RECALC_ALL) {
2532                 /* speed optimization for animation lookups */
2533                 if(ob->pose)
2534                         make_pose_channels_hash(ob->pose);
2535
2536                 if(ob->recalc & OB_RECALC_DATA) {
2537                         if(ob->type==OB_ARMATURE) {
2538                                 /* this happens for reading old files and to match library armatures
2539                                    with poses we do it ahead of where_is_object to ensure animation
2540                                    is evaluated on the rebuilt pose, otherwise we get incorrect poses
2541                                    on file load */
2542                                 if(ob->pose==NULL || (ob->pose->flag & POSE_RECALC))
2543                                         armature_rebuild_pose(ob, ob->data);
2544                         }
2545                 }
2546
2547                 /* XXX new animsys warning: depsgraph tag OB_RECALC_DATA should not skip drivers, 
2548                    which is only in where_is_object now */
2549                 // XXX: should this case be OB_RECALC_OB instead?
2550                 if(ob->recalc & OB_RECALC_ALL) {
2551                         
2552                         if (G.f & G_DEBUG)
2553                                 printf("recalcob %s\n", ob->id.name+2);
2554                         
2555                         /* handle proxy copy for target */
2556                         if(ob->id.lib && ob->proxy_from) {
2557                                 // printf("ob proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2558                                 if(ob->proxy_from->proxy_group) {/* transform proxy into group space */
2559                                         Object *obg= ob->proxy_from->proxy_group;
2560                                         invert_m4_m4(obg->imat, obg->obmat);
2561                                         mul_m4_m4m4(ob->obmat, ob->proxy_from->obmat, obg->imat);
2562                                         if(obg->dup_group) { /* should always be true */
2563                                                 add_v3_v3(ob->obmat[3], obg->dup_group->dupli_ofs);
2564                                         }
2565                                 }
2566                                 else
2567                                         copy_m4_m4(ob->obmat, ob->proxy_from->obmat);
2568                         }
2569                         else
2570                                 where_is_object(scene, ob);
2571                 }
2572                 
2573                 if(ob->recalc & OB_RECALC_DATA) {
2574                         ID *data_id= (ID *)ob->data;
2575                         AnimData *adt= BKE_animdata_from_id(data_id);
2576                         float ctime= (float)scene->r.cfra; // XXX this is bad...
2577                         ListBase pidlist;
2578                         PTCacheID *pid;
2579                         
2580                         if (G.f & G_DEBUG)
2581                                 printf("recalcdata %s\n", ob->id.name+2);
2582
2583                         if(adt) {
2584                                 /* evaluate drivers */
2585                                 // XXX: for mesh types, should we push this to derivedmesh instead?
2586                                 BKE_animsys_evaluate_animdata(data_id, adt, ctime, ADT_RECALC_DRIVERS);
2587                         }
2588
2589                         /* includes all keys and modifiers */
2590                         switch(ob->type) {
2591                         case OB_MESH:
2592                                 {
2593 #if 0                           // XXX, comment for 2.56a release, background wont set 'scene->customdata_mask'
2594                                         EditMesh *em = (ob == scene->obedit)? BKE_mesh_get_editmesh(ob->data): NULL;
2595                                         BLI_assert((scene->customdata_mask & CD_MASK_BAREMESH) == CD_MASK_BAREMESH);
2596                                         if(em) {
2597                                                 makeDerivedMesh(scene, ob, em,  scene->customdata_mask); /* was CD_MASK_BAREMESH */
2598                                                 BKE_mesh_end_editmesh(ob->data, em);
2599                                         } else
2600                                                 makeDerivedMesh(scene, ob, NULL, scene->customdata_mask);
2601
2602 #else                           /* ensure CD_MASK_BAREMESH for now */
2603                                         EditMesh *em = (ob == scene->obedit)? BKE_mesh_get_editmesh(ob->data): NULL;
2604                                         if(em) {
2605                                                 makeDerivedMesh(scene, ob, em,  scene->customdata_mask | CD_MASK_BAREMESH); /* was CD_MASK_BAREMESH */
2606                                                 BKE_mesh_end_editmesh(ob->data, em);
2607                                         } else
2608                                                 makeDerivedMesh(scene, ob, NULL, scene->customdata_mask | CD_MASK_BAREMESH);
2609 #endif
2610
2611                                 }
2612                                 break;
2613
2614                         case OB_ARMATURE:
2615                                 if(ob->id.lib && ob->proxy_from) {
2616                                         // printf("pose proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2617                                         copy_pose_result(ob->pose, ob->proxy_from->pose);
2618                                 }
2619                                 else {
2620                                         where_is_pose(scene, ob);
2621                                 }
2622                                 break;
2623
2624                         case OB_MBALL:
2625                                 makeDispListMBall(scene, ob);
2626                                 break;
2627
2628                         case OB_CURVE:
2629                         case OB_SURF:
2630                         case OB_FONT:
2631                                 makeDispListCurveTypes(scene, ob, 0);
2632                                 break;
2633                                 
2634                         case OB_LATTICE:
2635                                 lattice_calc_modifiers(scene, ob);
2636                                 break;
2637                         }
2638
2639
2640                         if(ob->particlesystem.first) {
2641                                 ParticleSystem *tpsys, *psys;
2642                                 DerivedMesh *dm;
2643                                 ob->transflag &= ~OB_DUPLIPARTS;
2644                                 
2645                                 psys= ob->particlesystem.first;
2646                                 while(psys) {
2647                                         if(psys_check_enabled(ob, psys)) {
2648                                                 /* check use of dupli objects here */
2649                                                 if(psys->part && (psys->part->draw_as == PART_DRAW_REND || G.rendering) &&
2650                                                         ((psys->part->ren_as == PART_DRAW_OB && psys->part->dup_ob)
2651                                                         || (psys->part->ren_as == PART_DRAW_GR && psys->part->dup_group)))
2652                                                         ob->transflag |= OB_DUPLIPARTS;
2653
2654                                                 particle_system_update(scene, ob, psys);
2655                                                 psys= psys->next;
2656                                         }
2657                                         else if(psys->flag & PSYS_DELETE) {
2658                                                 tpsys=psys->next;
2659                                                 BLI_remlink(&ob->particlesystem, psys);
2660                                                 psys_free(ob,psys);
2661                                                 psys= tpsys;
2662                                         }
2663                                         else
2664                                                 psys= psys->next;
2665                                 }
2666
2667                                 if(G.rendering && ob->transflag & OB_DUPLIPARTS) {
2668                                         /* this is to make sure we get render level duplis in groups:
2669                                          * the derivedmesh must be created before init_render_mesh,
2670                                          * since object_duplilist does dupliparticles before that */
2671                                         dm = mesh_create_derived_render(scene, ob, CD_MASK_BAREMESH|CD_MASK_MTFACE|CD_MASK_MCOL);
2672                                         dm->release(dm);
2673
2674                                         for(psys=ob->particlesystem.first; psys; psys=psys->next)
2675                                                 psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated;
2676                                 }
2677                         }
2678
2679                         /* check if quick cache is needed */
2680                         BKE_ptcache_ids_from_object(&pidlist, ob, scene, MAX_DUPLI_RECUR);
2681
2682                         for(pid=pidlist.first; pid; pid=pid->next) {
2683                                 if((pid->cache->flag & PTCACHE_BAKED)
2684                                         || (pid->cache->flag & PTCACHE_QUICK_CACHE)==0)
2685                                         continue;
2686
2687                                 if(pid->cache->flag & PTCACHE_OUTDATED || (pid->cache->flag & PTCACHE_SIMULATION_VALID)==0) {
2688                                         scene->physics_settings.quick_cache_step =
2689                                                 scene->physics_settings.quick_cache_step ?
2690                                                 MIN2(scene->physics_settings.quick_cache_step, pid->cache->step) :
2691                                                 pid->cache->step;
2692                                 }
2693                         }
2694
2695                         BLI_freelistN(&pidlist);
2696                 }
2697
2698                 /* the no-group proxy case, we call update */
2699                 if(ob->proxy && ob->proxy_group==NULL) {
2700                         /* set pointer in library proxy target, for copying, but restore it */
2701                         ob->proxy->proxy_from= ob;
2702                         // printf("call update, lib ob %s proxy %s\n", ob->proxy->id.name, ob->id.name);
2703                         object_handle_update(scene, ob->proxy);
2704                 }
2705         
2706                 ob->recalc &= ~OB_RECALC_ALL;
2707         }
2708
2709         /* the case when this is a group proxy, object_update is called in group.c */
2710         if(ob->proxy) {
2711                 ob->proxy->proxy_from= ob;
2712                 // printf("set proxy pointer for later group stuff %s\n", ob->id.name);
2713         }
2714 }
2715
2716 float give_timeoffset(Object *ob) {
2717         if ((ob->ipoflag & OB_OFFS_PARENTADD) && ob->parent) {
2718                 return ob->sf + give_timeoffset(ob->parent);
2719         } else {
2720                 return ob->sf;
2721         }
2722 }
2723
2724 int give_obdata_texspace(Object *ob, short **texflag, float **loc, float **size, float **rot) {
2725         
2726         if (ob->data==NULL)
2727                 return 0;
2728         
2729         switch (GS(((ID *)ob->data)->name)) {
2730         case ID_ME:
2731         {
2732                 Mesh *me= ob->data;
2733                 if (texflag)    *texflag = &me->texflag;
2734                 if (loc)                *loc = me->loc;
2735                 if (size)               *size = me->size;
2736                 if (rot)                *rot = me->rot;
2737                 break;
2738         }
2739         case ID_CU:
2740         {
2741                 Curve *cu= ob->data;
2742                 if (texflag)    *texflag = &cu->texflag;
2743                 if (loc)                *loc = cu->loc;
2744                 if (size)               *size = cu->size;
2745                 if (rot)                *rot = cu->rot;
2746                 break;
2747         }
2748         case ID_MB:
2749         {
2750                 MetaBall *mb= ob->data;
2751                 if (texflag)    *texflag = &mb->texflag;
2752                 if (loc)                *loc = mb->loc;
2753                 if (size)               *size = mb->size;
2754                 if (rot)                *rot = mb->rot;
2755                 break;
2756         }
2757         default:
2758                 return 0;
2759         }
2760         return 1;
2761 }
2762
2763 /*
2764  * Test a bounding box for ray intersection
2765  * assumes the ray is already local to the boundbox space
2766  */
2767 int ray_hit_boundbox(struct BoundBox *bb, float ray_start[3], float ray_normal[3])
2768 {
2769         static int triangle_indexes[12][3] = {{0, 1, 2}, {0, 2, 3},
2770                                                                                   {3, 2, 6}, {3, 6, 7},
2771                                                                                   {1, 2, 6}, {1, 6, 5}, 
2772                                                                                   {5, 6, 7}, {4, 5, 7},
2773                                                                                   {0, 3, 7}, {0, 4, 7},
2774                                                                                   {0, 1, 5}, {0, 4, 5}};
2775         int result = 0;
2776         int i;
2777         
2778         for (i = 0; i < 12 && result == 0; i++)
2779         {
2780                 float lambda;
2781                 int v1, v2, v3;
2782                 v1 = triangle_indexes[i][0];
2783                 v2 = triangle_indexes[i][1];
2784                 v3 = triangle_indexes[i][2];
2785                 result = isect_ray_tri_v3(ray_start, ray_normal, bb->vec[v1], bb->vec[v2], bb->vec[v3], &lambda, NULL);
2786         }
2787         
2788         return result;
2789 }
2790
2791 static int pc_cmp(void *a, void *b)
2792 {
2793         LinkData *ad = a, *bd = b;
2794         if(GET_INT_FROM_POINTER(ad->data) > GET_INT_FROM_POINTER(bd->data))
2795                 return 1;
2796         else return 0;
2797 }
2798
2799 int object_insert_ptcache(Object *ob) 
2800 {
2801         LinkData *link = NULL;
2802         int i = 0;
2803
2804         BLI_sortlist(&ob->pc_ids, pc_cmp);
2805
2806         for(link=ob->pc_ids.first, i = 0; link; link=link->next, i++) 
2807         {
2808                 int index = GET_INT_FROM_POINTER(link->data);
2809
2810                 if(i < index)
2811                         break;
2812         }
2813
2814         link = MEM_callocN(sizeof(LinkData), "PCLink");
2815         link->data = SET_INT_IN_POINTER(i);
2816         BLI_addtail(&ob->pc_ids, link);
2817
2818         return i;
2819 }
2820
2821 void object_camera_mode(RenderData *rd, Object *camera)
2822 {
2823         rd->mode &= ~(R_ORTHO|R_PANORAMA);
2824         if(camera && camera->type==OB_CAMERA) {
2825                 Camera *cam= camera->data;
2826                 if(cam->type == CAM_ORTHO) rd->mode |= R_ORTHO;
2827                 if(cam->flag & CAM_PANORAMA) rd->mode |= R_PANORAMA;
2828         }
2829 }
2830
2831 /* 'lens' may be set for envmap only */
2832 void object_camera_matrix(
2833                 RenderData *rd, Object *camera, int winx, int winy, short field_second,
2834                 float winmat[][4], rctf *viewplane, float *clipsta, float *clipend, float *lens, float *ycor,
2835                 float *viewdx, float *viewdy
2836 ) {
2837         Camera *cam=NULL;
2838         float pixsize;
2839         float shiftx=0.0, shifty=0.0, winside, viewfac;
2840         short is_ortho= FALSE;
2841
2842         /* question mark */
2843         (*ycor)= rd->yasp / rd->xasp;
2844         if(rd->mode & R_FIELDS)
2845                 (*ycor) *= 2.0f;
2846
2847         if(camera->type==OB_CAMERA) {
2848                 cam= camera->data;
2849
2850                 if(cam->type == CAM_ORTHO) {
2851                         is_ortho= TRUE;
2852                 }
2853
2854                 /* solve this too... all time depending stuff is in convertblender.c?
2855                  * Need to update the camera early because it's used for projection matrices
2856                  * and other stuff BEFORE the animation update loop is done
2857                  * */
2858 #if 0 // XXX old animation system
2859                 if(cam->ipo) {
2860                         calc_ipo(cam->ipo, frame_to_float(re->scene, re->r.cfra));
2861                         execute_ipo(&cam->id, cam->ipo);
2862                 }
2863 #endif // XXX old animation system
2864                 shiftx=cam->shiftx;
2865                 shifty=cam->shifty;
2866                 (*lens)= cam->lens;
2867                 (*clipsta)= cam->clipsta;
2868                 (*clipend)= cam->clipend;
2869         }
2870         else if(camera->type==OB_LAMP) {
2871                 Lamp *la= camera->data;
2872                 float fac= cosf((float)M_PI*la->spotsize/360.0f);
2873                 float phi= acos(fac);
2874
2875                 (*lens)= 16.0f*fac/sinf(phi);
2876                 if((*lens)==0.0f)
2877                         (*lens)= 35.0f;
2878                 (*clipsta)= la->clipsta;
2879                 (*clipend)= la->clipend;
2880         }
2881         else {  /* envmap exception... */;
2882                 if((*lens)==0.0f)
2883                         (*lens)= 16.0f;
2884
2885                 if((*clipsta)==0.0f || (*clipend)==0.0f) {
2886                         (*clipsta)= 0.1f;
2887                         (*clipend)= 1000.0f;
2888                 }
2889         }
2890
2891         /* ortho only with camera available */
2892         if(cam && is_ortho) {
2893                 if(rd->xasp*winx >= rd->yasp*winy) {
2894                         viewfac= winx;
2895                 }
2896                 else {
2897                         viewfac= (*ycor) * winy;
2898                 }
2899                 /* ortho_scale == 1.0 means exact 1 to 1 mapping */
2900                 pixsize= cam->ortho_scale/viewfac;
2901         }
2902         else {
2903                 if(rd->xasp*winx >= rd->yasp*winy)      viewfac= ((*lens) * winx)/32.0f;
2904                 else                                                            viewfac= (*ycor) * ((*lens) * winy)/32.0f;
2905                 pixsize= (*clipsta) / viewfac;
2906         }
2907
2908         /* viewplane fully centered, zbuffer fills in jittered between -.5 and +.5 */
2909         winside= MAX2(winx, winy);
2910         viewplane->xmin= -0.5f*(float)winx + shiftx*winside;
2911         viewplane->ymin= -0.5f*(*ycor)*(float)winy + shifty*winside;
2912         viewplane->xmax=  0.5f*(float)winx + shiftx*winside;
2913         viewplane->ymax=  0.5f*(*ycor)*(float)winy + shifty*winside;
2914
2915         if(field_second) {
2916                 if(rd->mode & R_ODDFIELD) {
2917                         viewplane->ymin-= 0.5f * (*ycor);
2918                         viewplane->ymax-= 0.5f * (*ycor);
2919                 }
2920                 else {
2921                         viewplane->ymin+= 0.5f * (*ycor);
2922                         viewplane->ymax+= 0.5f * (*ycor);
2923                 }
2924         }
2925         /* the window matrix is used for clipping, and not changed during OSA steps */
2926         /* using an offset of +0.5 here would give clip errors on edges */
2927         viewplane->xmin *= pixsize;
2928         viewplane->xmax *= pixsize;
2929         viewplane->ymin *= pixsize;
2930         viewplane->ymax *= pixsize;
2931
2932         (*viewdx)= pixsize;
2933         (*viewdy)= (*ycor) * pixsize;
2934
2935         if(is_ortho)
2936                 orthographic_m4(winmat, viewplane->xmin, viewplane->xmax, viewplane->ymin, viewplane->ymax, *clipsta, *clipend);
2937         else
2938                 perspective_m4(winmat, viewplane->xmin, viewplane->xmax, viewplane->ymin, viewplane->ymax, *clipsta, *clipend);
2939
2940 }
2941
2942 #if 0
2943 static int pc_findindex(ListBase *listbase, int index)
2944 {
2945         LinkData *link= NULL;
2946         int number= 0;
2947         
2948         if (listbase == NULL) return -1;
2949         
2950         link= listbase->first;
2951         while (link) {
2952                 if ((int)link->data == index)
2953                         return number;
2954                 
2955                 number++;
2956                 link= link->next;
2957         }
2958         
2959         return -1;
2960 }
2961
2962 void object_delete_ptcache(Object *ob, int index) 
2963 {
2964         int list_index = pc_findindex(&ob->pc_ids, index);
2965         LinkData *link = BLI_findlink(&ob->pc_ids, list_index);
2966         BLI_freelinkN(&ob->pc_ids, link);
2967 }
2968 #endif
2969
2970 /* shape key utility function */
2971
2972 /************************* Mesh ************************/
2973 static KeyBlock *insert_meshkey(Scene *scene, Object *ob, const char *name, int from_mix)
2974 {
2975         Mesh *me= ob->data;
2976         Key *key= me->key;
2977         KeyBlock *kb;
2978         int newkey= 0;
2979
2980         if(key == NULL) {
2981                 key= me->key= add_key((ID *)me);
2982                 key->type= KEY_RELATIVE;
2983                 newkey= 1;
2984         }
2985
2986         if(newkey || from_mix==FALSE) {
2987                 /* create from mesh */
2988                 kb= add_keyblock(key, name);
2989                 mesh_to_key(me, kb);
2990         }
2991         else {
2992                 /* copy from current values */
2993                 float *data= do_ob_key(scene, ob);
2994
2995                 /* create new block with prepared data */
2996                 kb= add_keyblock(key, name);
2997                 kb->data= data;
2998                 kb->totelem= me->totvert;
2999         }
3000
3001         return kb;
3002 }
3003 /************************* Lattice ************************/
3004 static KeyBlock *insert_lattkey(Scene *scene, Object *ob, const char *name, int from_mix)
3005 {
3006         Lattice *lt= ob->data;
3007         Key *key= lt->key;
3008         KeyBlock *kb;
3009         int newkey= 0;
3010
3011         if(key==NULL) {
3012                 key= lt->key= add_key( (ID *)lt);
3013                 key->type= KEY_RELATIVE;
3014                 newkey= 1;
3015         }
3016
3017         if(newkey || from_mix==FALSE) {
3018                 kb= add_keyblock(key, name);
3019
3020                 /* create from lattice */
3021                 latt_to_key(lt, kb);
3022         }
3023         else {
3024                 /* copy from current values */
3025                 float *data= do_ob_key(scene, ob);
3026
3027                 /* create new block with prepared data */
3028                 kb= add_keyblock(key, name);
3029                 kb->totelem= lt->pntsu*lt->pntsv*lt->pntsw;
3030                 kb->data= data;
3031         }
3032
3033         return kb;
3034 }
3035 /************************* Curve ************************/
3036 static KeyBlock *insert_curvekey(Scene *scene, Object *ob, const char *name, int from_mix)
3037 {
3038         Curve *cu= ob->data;
3039         Key *key= cu->key;
3040         KeyBlock *kb;
3041         ListBase *lb= BKE_curve_nurbs(cu);
3042         int newkey= 0;
3043
3044         if(key==NULL) {
3045                 key= cu->key= add_key( (ID *)cu);
3046                 key->type = KEY_RELATIVE;
3047                 newkey= 1;
3048         }
3049
3050         if(newkey || from_mix==FALSE) {
3051                 /* create from curve */
3052                 kb= add_keyblock(key, name);
3053                 if (!newkey) {
3054                         KeyBlock *basekb= (KeyBlock *)key->block.first;
3055                         kb->data= MEM_dupallocN(basekb->data);
3056                         kb->totelem= basekb->totelem;
3057                 } else curve_to_key(cu, kb, lb);
3058         }
3059         else {
3060                 /* copy from current values */
3061                 float *data= do_ob_key(scene, ob);
3062
3063                 /* create new block with prepared data */
3064                 kb= add_keyblock(key, name);
3065                 kb->totelem= count_curveverts(lb);
3066                 kb->data= data;
3067         }
3068
3069         return kb;
3070 }
3071
3072 KeyBlock *object_insert_shape_key(Scene *scene, Object *ob, const char *name, int from_mix)
3073 {
3074         if(ob->type==OB_MESH)                                    return insert_meshkey(scene, ob, name, from_mix);
3075         else if ELEM(ob->type, OB_CURVE, OB_SURF)return insert_curvekey(scene, ob, name, from_mix);
3076         else if(ob->type==OB_LATTICE)                    return insert_lattkey(scene, ob, name, from_mix);
3077         else                                                                     return NULL;
3078 }
3079
3080 /* most important if this is modified it should _always_ return True, in certain
3081  * cases false positives are hard to avoid (shape keys for eg)
3082  */
3083 int object_is_modified(Scene *scene, Object *ob)
3084 {
3085         int flag= 0;
3086
3087         if(ob_get_key(ob)) {
3088                 flag |= eModifierMode_Render | eModifierMode_Render;
3089         }
3090         else {
3091                 ModifierData *md;
3092                 /* cloth */
3093                 for(md=modifiers_getVirtualModifierList(ob); md && (flag != (eModifierMode_Render | eModifierMode_Realtime)); md=md->next) {
3094                         if((flag & eModifierMode_Render) == 0   && modifier_isEnabled(scene, md, eModifierMode_Render))         flag |= eModifierMode_Render;
3095                         if((flag & eModifierMode_Realtime) == 0 && modifier_isEnabled(scene, md, eModifierMode_Realtime))       flag |= eModifierMode_Realtime;
3096                 }
3097         }
3098
3099         return flag;
3100 }
3101
3102 static void copy_object__forwardModifierLinks(void *UNUSED(userData), Object *UNUSED(ob), ID **idpoin)
3103 {
3104         /* this is copied from ID_NEW; it might be better to have a macro */
3105         if(*idpoin && (*idpoin)->newid) *idpoin = (*idpoin)->newid;
3106 }
3107
3108 void object_relink(Object *ob)
3109 {
3110         if(ob->id.lib)
3111                 return;
3112
3113         relink_constraints(&ob->constraints);
3114         if (ob->pose){
3115                 bPoseChannel *chan;
3116                 for (chan = ob->pose->chanbase.first; chan; chan=chan->next){
3117                         relink_constraints(&chan->constraints);
3118                 }
3119         }
3120         modifiers_foreachIDLink(ob, copy_object__forwardModifierLinks, NULL);
3121
3122         if(ob->adt)
3123                 BKE_relink_animdata(ob->adt);
3124
3125         ID_NEW(ob->parent);
3126
3127         ID_NEW(ob->proxy);
3128         ID_NEW(ob->proxy_group);
3129 }