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