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