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