removed unused includes, except for physics and particle related files
[blender-staging.git] / source / blender / blenkernel / intern / object.c
1 /* object.c
2  *
3  * 
4  * $Id$
5  *
6  * ***** BEGIN GPL LICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21  *
22  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 #include <string.h>
33 #include <math.h>
34 #include <stdio.h>                      
35
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
39
40 #include "MEM_guardedalloc.h"
41
42 #include "DNA_anim_types.h"
43 #include "DNA_armature_types.h"
44 #include "DNA_camera_types.h"
45 #include "DNA_constraint_types.h"
46 #include "DNA_group_types.h"
47 #include "DNA_key_types.h"
48 #include "DNA_lamp_types.h"
49 #include "DNA_lattice_types.h"
50 #include "DNA_material_types.h"
51 #include "DNA_meta_types.h"
52 #include "DNA_meshdata_types.h"
53 #include "DNA_scene_types.h"
54 #include "DNA_screen_types.h"
55 #include "DNA_sequence_types.h"
56 #include "DNA_space_types.h"
57 #include "DNA_view3d_types.h"
58 #include "DNA_world_types.h"
59
60 #include "BLI_blenlib.h"
61 #include "BLI_math.h"
62 #include "BLI_editVert.h"
63
64 #include "BKE_utildefines.h"
65
66 #include "BKE_main.h"
67 #include "BKE_global.h"
68
69 #include "BKE_armature.h"
70 #include "BKE_action.h"
71 #include "BKE_bullet.h"
72 #include "BKE_colortools.h"
73 #include "BKE_deform.h"
74 #include "BKE_DerivedMesh.h"
75 #include "BKE_animsys.h"
76 #include "BKE_anim.h"
77 #include "BKE_constraint.h"
78 #include "BKE_curve.h"
79 #include "BKE_displist.h"
80 #include "BKE_effect.h"
81 #include "BKE_fcurve.h"
82 #include "BKE_group.h"
83 #include "BKE_icons.h"
84 #include "BKE_key.h"
85 #include "BKE_lattice.h"
86 #include "BKE_library.h"
87 #include "BKE_mesh.h"
88 #include "BKE_mball.h"
89 #include "BKE_modifier.h"
90 #include "BKE_object.h"
91 #include "BKE_paint.h"
92 #include "BKE_particle.h"
93 #include "BKE_pointcache.h"
94 #include "BKE_property.h"
95 #include "BKE_sca.h"
96 #include "BKE_scene.h"
97 #include "BKE_sequencer.h"
98 #include "BKE_softbody.h"
99
100 #include "LBM_fluidsim.h"
101
102 #ifndef DISABLE_PYTHON
103 #include "BPY_extern.h"
104 #endif
105
106 #include "GPU_material.h"
107
108 /* Local function protos */
109 static void solve_parenting (Scene *scene, Object *ob, Object *par, float obmat[][4], float slowmat[][4], int simul);
110
111 float originmat[3][3];  /* after where_is_object(), can be used in other functions (bad!) */
112
113 void clear_workob(Object *workob)
114 {
115         memset(workob, 0, sizeof(Object));
116         
117         workob->size[0]= workob->size[1]= workob->size[2]= 1.0f;
118         workob->rotmode= ROT_MODE_EUL;
119 }
120
121 void copy_baseflags(struct Scene *scene)
122 {
123         Base *base= scene->base.first;
124         
125         while(base) {
126                 base->object->flag= base->flag;
127                 base= base->next;
128         }
129 }
130
131 void copy_objectflags(struct Scene *scene)
132 {
133         Base *base= scene->base.first;
134         
135         while(base) {
136                 base->flag= base->object->flag;
137                 base= base->next;
138         }
139 }
140
141 void update_base_layer(struct Scene *scene, Object *ob)
142 {
143         Base *base= scene->base.first;
144
145         while (base) {
146                 if (base->object == ob) base->lay= ob->lay;
147                 base= base->next;
148         }
149 }
150
151 void object_free_particlesystems(Object *ob)
152 {
153         while(ob->particlesystem.first){
154                 ParticleSystem *psys = ob->particlesystem.first;
155                 
156                 BLI_remlink(&ob->particlesystem,psys);
157                 
158                 psys_free(ob,psys);
159         }
160 }
161
162 void object_free_softbody(Object *ob)
163 {
164         if(ob->soft) {
165                 sbFree(ob->soft);
166                 ob->soft= NULL;
167         }
168 }
169
170 void object_free_bulletsoftbody(Object *ob)
171 {
172         if(ob->bsoft) {
173                 bsbFree(ob->bsoft);
174                 ob->bsoft= NULL;
175         }
176 }
177
178 void object_free_modifiers(Object *ob)
179 {
180         while (ob->modifiers.first) {
181                 ModifierData *md = ob->modifiers.first;
182                 
183                 BLI_remlink(&ob->modifiers, md);
184                 
185                 modifier_free(md);
186         }
187
188         /* particle modifiers were freed, so free the particlesystems as well */
189         object_free_particlesystems(ob);
190
191         /* same for softbody */
192         object_free_softbody(ob);
193 }
194
195 void object_link_modifiers(struct Object *ob, struct Object *from)
196 {
197         ModifierData *md;
198         object_free_modifiers(ob);
199
200         for (md=from->modifiers.first; md; md=md->next) {
201                 ModifierData *nmd = NULL;
202
203                 if(ELEM4(md->type, eModifierType_Hook, eModifierType_Softbody, eModifierType_ParticleInstance, eModifierType_Collision)) continue;
204
205                 nmd = modifier_new(md->type);
206                 modifier_copyData(md, nmd);
207                 BLI_addtail(&ob->modifiers, nmd);
208         }
209
210         copy_object_particlesystems(from, ob);
211         copy_object_softbody(from, ob);
212
213         // TODO: smoke?, cloth?
214 }
215
216 /* here we will collect all local displist stuff */
217 /* also (ab)used in depsgraph */
218 void object_free_display(Object *ob)
219 {
220         if(ob->derivedDeform) {
221                 ob->derivedDeform->needsFree = 1;
222                 ob->derivedDeform->release(ob->derivedDeform);
223                 ob->derivedDeform= NULL;
224         }
225         if(ob->derivedFinal) {
226                 ob->derivedFinal->needsFree = 1;
227                 ob->derivedFinal->release(ob->derivedFinal);
228                 ob->derivedFinal= NULL;
229         }
230         
231         freedisplist(&ob->disp);
232 }
233
234 void free_sculptsession(SculptSession **ssp)
235 {
236         if(ssp && *ssp) {
237                 SculptSession *ss = *ssp;
238
239                 if(ss->texcache)
240                         MEM_freeN(ss->texcache);
241
242                 if(ss->layer_disps)
243                         MEM_freeN(ss->layer_disps);
244
245                 if(ss->layer_co)
246                         MEM_freeN(ss->layer_co);
247
248                 MEM_freeN(ss);
249
250                 *ssp = 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->sculpt);
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                 if(obt->track==ob) {
361                         obt->track= NULL;
362                         obt->recalc |= OB_RECALC_OB;
363                 }
364                 
365                 modifiers_foreachObjectLink(obt, unlink_object__unlinkModifierLinks, ob);
366                 
367                 if ELEM(obt->type, OB_CURVE, OB_FONT) {
368                         cu= obt->data;
369
370                         if(cu->bevobj==ob) {
371                                 cu->bevobj= NULL;
372                                 obt->recalc |= OB_RECALC;
373                         }
374                         if(cu->taperobj==ob) {
375                                 cu->taperobj= NULL;
376                                 obt->recalc |= OB_RECALC;
377                         }
378                         if(cu->textoncurve==ob) {
379                                 cu->textoncurve= NULL;
380                                 obt->recalc |= OB_RECALC;
381                         }
382                 }
383                 else if(obt->type==OB_ARMATURE && obt->pose) {
384                         bPoseChannel *pchan;
385                         for(pchan= obt->pose->chanbase.first; pchan; pchan= pchan->next) {
386                                 for (con = pchan->constraints.first; con; con=con->next) {
387                                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
388                                         ListBase targets = {NULL, NULL};
389                                         bConstraintTarget *ct;
390                                         
391                                         if (cti && cti->get_constraint_targets) {
392                                                 cti->get_constraint_targets(con, &targets);
393                                                 
394                                                 for (ct= targets.first; ct; ct= ct->next) {
395                                                         if (ct->tar == ob) {
396                                                                 ct->tar = NULL;
397                                                                 strcpy(ct->subtarget, "");
398                                                                 obt->recalc |= OB_RECALC_DATA;
399                                                         }
400                                                 }
401                                                 
402                                                 if (cti->flush_constraint_targets)
403                                                         cti->flush_constraint_targets(con, &targets, 0);
404                                         }
405                                 }
406                                 if(pchan->custom==ob)
407                                         pchan->custom= NULL;
408                         }
409                 }
410                 
411                 sca_remove_ob_poin(obt, ob);
412                 
413                 for (con = obt->constraints.first; con; con=con->next) {
414                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
415                         ListBase targets = {NULL, NULL};
416                         bConstraintTarget *ct;
417                         
418                         if (cti && cti->get_constraint_targets) {
419                                 cti->get_constraint_targets(con, &targets);
420                                 
421                                 for (ct= targets.first; ct; ct= ct->next) {
422                                         if (ct->tar == ob) {
423                                                 ct->tar = NULL;
424                                                 strcpy(ct->subtarget, "");
425                                                 obt->recalc |= OB_RECALC_DATA;
426                                         }
427                                 }
428                                 
429                                 if (cti->flush_constraint_targets)
430                                         cti->flush_constraint_targets(con, &targets, 0);
431                         }
432                 }
433                 
434                 /* object is deflector or field */
435                 if(ob->pd) {
436                         if(obt->soft)
437                                 obt->recalc |= OB_RECALC_DATA;
438
439                         /* cloth */
440                         for(md=obt->modifiers.first; md; md=md->next)
441                                 if(md->type == eModifierType_Cloth)
442                                         obt->recalc |= OB_RECALC_DATA;
443                 }
444                 
445                 /* strips */
446 #if 0 // XXX old animation system
447                 for(strip= obt->nlastrips.first; strip; strip= strip->next) {
448                         if(strip->object==ob)
449                                 strip->object= NULL;
450                         
451                         if(strip->modifiers.first) {
452                                 bActionModifier *amod;
453                                 for(amod= strip->modifiers.first; amod; amod= amod->next)
454                                         if(amod->ob==ob)
455                                                 amod->ob= NULL;
456                         }
457                 }
458 #endif // XXX old animation system
459
460                 /* particle systems */
461                 if(obt->particlesystem.first) {
462                         ParticleSystem *tpsys= obt->particlesystem.first;
463                         for(; tpsys; tpsys=tpsys->next) {
464                                 BoidState *state = NULL;
465                                 BoidRule *rule = NULL;
466
467                                 ParticleTarget *pt = tpsys->targets.first;
468                                 for(; pt; pt=pt->next) {
469                                         if(pt->ob==ob) {
470                                                 pt->ob = NULL;
471                                                 obt->recalc |= OB_RECALC_DATA;
472                                                 break;
473                                         }
474                                 }
475
476                                 if(tpsys->target_ob==ob) {
477                                         tpsys->target_ob= NULL;
478                                         obt->recalc |= OB_RECALC_DATA;
479                                 }
480
481                                 if(tpsys->part->dup_ob==ob)
482                                         tpsys->part->dup_ob= NULL;
483
484                                 if(tpsys->part->phystype==PART_PHYS_BOIDS) {
485                                         ParticleData *pa;
486                                         BoidParticle *bpa;
487                                         int p;
488
489                                         for(p=0,pa=tpsys->particles; p<tpsys->totpart; p++,pa++) {
490                                                 bpa = pa->boid;
491                                                 if(bpa->ground == ob)
492                                                         bpa->ground = NULL;
493                                         }
494                                 }
495                                 if(tpsys->part->boids) {
496                                         for(state = tpsys->part->boids->states.first; state; state=state->next) {
497                                                 for(rule = state->rules.first; rule; rule=rule->next) {
498                                                         if(rule->type==eBoidRuleType_Avoid) {
499                                                                 BoidRuleGoalAvoid *gabr = (BoidRuleGoalAvoid*)rule;
500                                                                 if(gabr->ob==ob)
501                                                                         gabr->ob= NULL;
502                                                         }
503                                                         else if(rule->type==eBoidRuleType_FollowLeader) {
504                                                                 BoidRuleFollowLeader *flbr = (BoidRuleFollowLeader*)rule;
505                                                                 if(flbr->ob==ob)
506                                                                         flbr->ob= NULL;
507                                                         }
508                                                 }
509                                         }
510                                 }
511                         }
512                         if(ob->pd)
513                                 obt->recalc |= OB_RECALC_DATA;
514                 }
515
516                 obt= obt->id.next;
517         }
518         
519         /* materials */
520         mat= G.main->mat.first;
521         while(mat) {
522         
523                 for(a=0; a<MAX_MTEX; a++) {
524                         if(mat->mtex[a] && ob==mat->mtex[a]->object) {
525                                 /* actually, test for lib here... to do */
526                                 mat->mtex[a]->object= NULL;
527                         }
528                 }
529
530                 mat= mat->id.next;
531         }
532         
533         /* textures */
534         tex= G.main->tex.first;
535         while(tex) {
536                 if(tex->env) {
537                         if(tex->env->object == ob) tex->env->object= NULL;
538                 }
539                 tex= tex->id.next;
540         }
541         
542         /* mballs (scene==NULL when called from library.c) */
543         if(scene && ob->type==OB_MBALL) {
544                 obt= find_basis_mball(scene, ob);
545                 if(obt) freedisplist(&obt->disp);
546         }
547         
548         /* worlds */
549         wrld= G.main->world.first;
550         while(wrld) {
551                 if(wrld->id.lib==NULL) {
552                         for(a=0; a<MAX_MTEX; a++) {
553                                 if(wrld->mtex[a] && ob==wrld->mtex[a]->object)
554                                         wrld->mtex[a]->object= NULL;
555                         }
556                 }
557                 
558                 wrld= wrld->id.next;
559         }
560                 
561         /* scenes */
562         sce= G.main->scene.first;
563         while(sce) {
564                 if(sce->id.lib==NULL) {
565                         if(sce->camera==ob) sce->camera= NULL;
566                         if(sce->toolsettings->skgen_template==ob) sce->toolsettings->skgen_template = NULL;
567                         if(sce->toolsettings->particle.object==ob) sce->toolsettings->particle.object= NULL;
568
569 #ifdef DURIAN_CAMERA_SWITCH
570                         {
571                                 TimeMarker *m;
572
573                                 for (m= sce->markers.first; m; m= m->next) {
574                                         if(m->camera==ob)
575                                                 m->camera= NULL;
576                                 }
577                         }
578 #endif
579                         if(sce->ed) {
580                                 Sequence *seq;
581                                 SEQ_BEGIN(sce->ed, seq)
582                                         if(seq->scene_camera==ob) {
583                                                 seq->scene_camera= NULL;
584                                         }
585                                 SEQ_END
586                         }
587                 }
588
589                 sce= sce->id.next;
590         }
591         
592 #if 0 // XXX old animation system
593         /* ipos */
594         ipo= G.main->ipo.first;
595         while(ipo) {
596                 if(ipo->id.lib==NULL) {
597                         IpoCurve *icu;
598                         for(icu= ipo->curve.first; icu; icu= icu->next) {
599                                 if(icu->driver && icu->driver->ob==ob)
600                                         icu->driver->ob= NULL;
601                         }
602                 }
603                 ipo= ipo->id.next;
604         }
605 #endif // XXX old animation system
606         
607         /* screens */
608         sc= G.main->screen.first;
609         while(sc) {
610                 ScrArea *sa= sc->areabase.first;
611                 while(sa) {
612                         SpaceLink *sl;
613
614                         for (sl= sa->spacedata.first; sl; sl= sl->next) {
615                                 if(sl->spacetype==SPACE_VIEW3D) {
616                                         View3D *v3d= (View3D*) sl;
617
618                                         if(v3d->camera==ob) {
619                                                 v3d->camera= NULL;
620                                                 // XXX if(v3d->persp==V3D_CAMOB) v3d->persp= V3D_PERSP;
621                                         }
622                                         if(v3d->localvd && v3d->localvd->camera==ob ) {
623                                                 v3d->localvd->camera= NULL;
624                                                 // XXX if(v3d->localvd->persp==V3D_CAMOB) v3d->localvd->persp= V3D_PERSP;
625                                         }
626                                 }
627                                 else if(sl->spacetype==SPACE_OUTLINER) {
628                                         SpaceOops *so= (SpaceOops *)sl;
629
630                                         if(so->treestore) {
631                                                 TreeStoreElem *tselem= so->treestore->data;
632                                                 int a;
633                                                 for(a=0; a<so->treestore->usedelem; a++, tselem++) {
634                                                         if(tselem->id==(ID *)ob) tselem->id= NULL;
635                                                 }
636                                         }
637                                 }
638                         }
639
640                         sa= sa->next;
641                 }
642                 sc= sc->id.next;
643         }
644
645         /* groups */
646         group= G.main->group.first;
647         while(group) {
648                 rem_from_group(group, ob, NULL, NULL);
649                 group= group->id.next;
650         }
651         
652         /* cameras */
653         camera= G.main->camera.first;
654         while(camera) {
655                 if (camera->dof_ob==ob) {
656                         camera->dof_ob = NULL;
657                 }
658                 camera= camera->id.next;
659         }
660 }
661
662 int exist_object(Object *obtest)
663 {
664         Object *ob;
665         
666         if(obtest==NULL) return 0;
667         
668         ob= G.main->object.first;
669         while(ob) {
670                 if(ob==obtest) return 1;
671                 ob= ob->id.next;
672         }
673         return 0;
674 }
675
676 void *add_camera(char *name)
677 {
678         Camera *cam;
679         
680         cam=  alloc_libblock(&G.main->camera, ID_CA, name);
681
682         cam->lens= 35.0f;
683         cam->angle= 49.14f;
684         cam->clipsta= 0.1f;
685         cam->clipend= 100.0f;
686         cam->drawsize= 0.5f;
687         cam->ortho_scale= 6.0;
688         cam->flag |= CAM_SHOWTITLESAFE;
689         cam->passepartalpha = 0.2f;
690         
691         return cam;
692 }
693
694 Camera *copy_camera(Camera *cam)
695 {
696         Camera *camn;
697         
698         camn= copy_libblock(cam);
699         camn->adt= BKE_copy_animdata(cam->adt);
700         
701         return camn;
702 }
703
704
705
706 void make_local_camera(Camera *cam)
707 {
708         Object *ob;
709         Camera *camn;
710         int local=0, lib=0;
711
712         /* - only lib users: do nothing
713             * - only local users: set flag
714             * - mixed: make copy
715             */
716         
717         if(cam->id.lib==0) return;
718         if(cam->id.us==1) {
719                 cam->id.lib= 0;
720                 cam->id.flag= LIB_LOCAL;
721                 new_id(0, (ID *)cam, 0);
722                 return;
723         }
724         
725         ob= G.main->object.first;
726         while(ob) {
727                 if(ob->data==cam) {
728                         if(ob->id.lib) lib= 1;
729                         else local= 1;
730                 }
731                 ob= ob->id.next;
732         }
733         
734         if(local && lib==0) {
735                 cam->id.lib= 0;
736                 cam->id.flag= LIB_LOCAL;
737                 new_id(0, (ID *)cam, 0);
738         }
739         else if(local && lib) {
740                 camn= copy_camera(cam);
741                 camn->id.us= 0;
742                 
743                 ob= G.main->object.first;
744                 while(ob) {
745                         if(ob->data==cam) {
746                                 
747                                 if(ob->id.lib==0) {
748                                         ob->data= camn;
749                                         camn->id.us++;
750                                         cam->id.us--;
751                                 }
752                         }
753                         ob= ob->id.next;
754                 }
755         }
756 }
757
758 /* get the camera's dof value, takes the dof object into account */
759 float dof_camera(Object *ob)
760 {
761         Camera *cam = (Camera *)ob->data; 
762         if (ob->type != OB_CAMERA)
763                 return 0.0f;
764         if (cam->dof_ob) {      
765                 /* too simple, better to return the distance on the view axis only
766                  * return len_v3v3(ob->obmat[3], cam->dof_ob->obmat[3]); */
767                 float mat[4][4], imat[4][4], obmat[4][4];
768                 
769                 copy_m4_m4(obmat, ob->obmat);
770                 normalize_m4(obmat);
771                 invert_m4_m4(imat, obmat);
772                 mul_m4_m4m4(mat, cam->dof_ob->obmat, imat);
773                 return (float)fabs(mat[3][2]);
774         }
775         return cam->YF_dofdist;
776 }
777
778 void *add_lamp(char *name)
779 {
780         Lamp *la;
781         
782         la=  alloc_libblock(&G.main->lamp, ID_LA, name);
783         
784         la->r= la->g= la->b= la->k= 1.0f;
785         la->haint= la->energy= 1.0f;
786         la->dist= 25.0f;
787         la->spotsize= 45.0f;
788         la->spotblend= 0.15f;
789         la->att2= 1.0f;
790         la->mode= LA_SHAD_BUF;
791         la->bufsize= 512;
792         la->clipsta= 0.5f;
793         la->clipend= 40.0f;
794         la->shadspotsize= 45.0f;
795         la->samp= 3;
796         la->bias= 1.0f;
797         la->soft= 3.0f;
798         la->compressthresh= 0.05f;
799         la->ray_samp= la->ray_sampy= la->ray_sampz= 1; 
800         la->area_size=la->area_sizey=la->area_sizez= 1.0f; 
801         la->buffers= 1;
802         la->buftype= LA_SHADBUF_HALFWAY;
803         la->ray_samp_method = LA_SAMP_HALTON;
804         la->adapt_thresh = 0.001f;
805         la->preview=NULL;
806         la->falloff_type = LA_FALLOFF_INVSQUARE;
807         la->curfalloff = curvemapping_add(1, 0.0f, 1.0f, 1.0f, 0.0f);
808         la->sun_effect_type = 0;
809         la->horizon_brightness = 1.0;
810         la->spread = 1.0;
811         la->sun_brightness = 1.0;
812         la->sun_size = 1.0;
813         la->backscattered_light = 1.0f;
814         la->atm_turbidity = 2.0f;
815         la->atm_inscattering_factor = 1.0f;
816         la->atm_extinction_factor = 1.0f;
817         la->atm_distance_factor = 1.0f;
818         la->sun_intensity = 1.0f;
819         la->skyblendtype= MA_RAMP_ADD;
820         la->skyblendfac= 1.0f;
821         la->sky_colorspace= BLI_XYZ_CIE;
822         la->sky_exposure= 1.0f;
823         
824         curvemapping_initialize(la->curfalloff);
825         return la;
826 }
827
828 Lamp *copy_lamp(Lamp *la)
829 {
830         Lamp *lan;
831         int a;
832         
833         lan= copy_libblock(la);
834
835         for(a=0; a<MAX_MTEX; a++) {
836                 if(lan->mtex[a]) {
837                         lan->mtex[a]= MEM_mallocN(sizeof(MTex), "copylamptex");
838                         memcpy(lan->mtex[a], la->mtex[a], sizeof(MTex));
839                         id_us_plus((ID *)lan->mtex[a]->tex);
840                 }
841         }
842         
843         lan->curfalloff = curvemapping_copy(la->curfalloff);
844         
845 #if 0 // XXX old animation system
846         id_us_plus((ID *)lan->ipo);
847 #endif // XXX old animation system
848
849         if (la->preview) lan->preview = BKE_previewimg_copy(la->preview);
850         
851         return lan;
852 }
853
854 void make_local_lamp(Lamp *la)
855 {
856         Object *ob;
857         Lamp *lan;
858         int local=0, lib=0;
859
860         /* - only lib users: do nothing
861             * - only local users: set flag
862             * - mixed: make copy
863             */
864         
865         if(la->id.lib==0) return;
866         if(la->id.us==1) {
867                 la->id.lib= 0;
868                 la->id.flag= LIB_LOCAL;
869                 new_id(0, (ID *)la, 0);
870                 return;
871         }
872         
873         ob= G.main->object.first;
874         while(ob) {
875                 if(ob->data==la) {
876                         if(ob->id.lib) lib= 1;
877                         else local= 1;
878                 }
879                 ob= ob->id.next;
880         }
881         
882         if(local && lib==0) {
883                 la->id.lib= 0;
884                 la->id.flag= LIB_LOCAL;
885                 new_id(0, (ID *)la, 0);
886         }
887         else if(local && lib) {
888                 lan= copy_lamp(la);
889                 lan->id.us= 0;
890                 
891                 ob= G.main->object.first;
892                 while(ob) {
893                         if(ob->data==la) {
894                                 
895                                 if(ob->id.lib==0) {
896                                         ob->data= lan;
897                                         lan->id.us++;
898                                         la->id.us--;
899                                 }
900                         }
901                         ob= ob->id.next;
902                 }
903         }
904 }
905
906 void free_camera(Camera *ca)
907 {
908         BKE_free_animdata((ID *)ca);
909 }
910
911 void free_lamp(Lamp *la)
912 {
913         MTex *mtex;
914         int a;
915
916         for(a=0; a<MAX_MTEX; a++) {
917                 mtex= la->mtex[a];
918                 if(mtex && mtex->tex) mtex->tex->id.us--;
919                 if(mtex) MEM_freeN(mtex);
920         }
921         
922         BKE_free_animdata((ID *)la);
923
924         curvemapping_free(la->curfalloff);
925         
926         BKE_previewimg_free(&la->preview);
927         BKE_icon_delete(&la->id);
928         la->id.icon_id = 0;
929 }
930
931 void *add_wave()
932 {
933         return 0;
934 }
935
936
937 /* *************************************************** */
938
939 static void *add_obdata_from_type(int type)
940 {
941         switch (type) {
942         case OB_MESH: return add_mesh("Mesh");
943         case OB_CURVE: return add_curve("Curve", OB_CURVE);
944         case OB_SURF: return add_curve("Surf", OB_SURF);
945         case OB_FONT: return add_curve("Text", OB_FONT);
946         case OB_MBALL: return add_mball("Meta");
947         case OB_CAMERA: return add_camera("Camera");
948         case OB_LAMP: return add_lamp("Lamp");
949         case OB_LATTICE: return add_lattice("Lattice");
950         case OB_WAVE: return add_wave();
951         case OB_ARMATURE: return add_armature("Armature");
952         case OB_EMPTY: return NULL;
953         default:
954                 printf("add_obdata_from_type: Internal error, bad type: %d\n", type);
955                 return NULL;
956         }
957 }
958
959 static char *get_obdata_defname(int type)
960 {
961         switch (type) {
962         case OB_MESH: return "Mesh";
963         case OB_CURVE: return "Curve";
964         case OB_SURF: return "Surf";
965         case OB_FONT: return "Font";
966         case OB_MBALL: return "Mball";
967         case OB_CAMERA: return "Camera";
968         case OB_LAMP: return "Lamp";
969         case OB_LATTICE: return "Lattice";
970         case OB_WAVE: return "Wave";
971         case OB_ARMATURE: return "Armature";
972         case OB_EMPTY: return "Empty";
973         default:
974                 printf("get_obdata_defname: Internal error, bad type: %d\n", type);
975                 return "Empty";
976         }
977 }
978
979 /* more general add: creates minimum required data, but without vertices etc. */
980 Object *add_only_object(int type, char *name)
981 {
982         Object *ob;
983
984         ob= alloc_libblock(&G.main->object, ID_OB, name);
985
986         /* default object vars */
987         ob->type= type;
988         
989         ob->col[0]= ob->col[1]= ob->col[2]= 1.0;
990         ob->col[3]= 1.0;
991         
992         ob->size[0]= ob->size[1]= ob->size[2]= 1.0;
993         
994         /* objects should default to having Euler XYZ rotations, 
995          * but rotations default to quaternions 
996          */
997         ob->rotmode= ROT_MODE_EUL;
998         /* axis-angle must not have a 0,0,0 axis, so set y-axis as default... */
999         ob->rotAxis[1]= ob->drotAxis[1]= 1.0f;
1000         /* quaternions should be 1,0,0,0 by default.... */
1001         ob->quat[0]= ob->dquat[0]= 1.0f;
1002         /* rotation locks should be 4D for 4 component rotations by default... */
1003         ob->protectflag = OB_LOCK_ROT4D;
1004         
1005         unit_m4(ob->constinv);
1006         unit_m4(ob->parentinv);
1007         unit_m4(ob->obmat);
1008         ob->dt= OB_TEXTURE;
1009         ob->empty_drawtype= OB_ARROWS;
1010         ob->empty_drawsize= 1.0;
1011
1012         if(type==OB_CAMERA || type==OB_LAMP) {
1013                 ob->trackflag= OB_NEGZ;
1014                 ob->upflag= OB_POSY;
1015         }
1016         else {
1017                 ob->trackflag= OB_POSY;
1018                 ob->upflag= OB_POSZ;
1019         }
1020         
1021         ob->dupon= 1; ob->dupoff= 0;
1022         ob->dupsta= 1; ob->dupend= 100;
1023         ob->dupfacesca = 1.0;
1024
1025         /* Game engine defaults*/
1026         ob->mass= ob->inertia= 1.0f;
1027         ob->formfactor= 0.4f;
1028         ob->damping= 0.04f;
1029         ob->rdamping= 0.1f;
1030         ob->anisotropicFriction[0] = 1.0f;
1031         ob->anisotropicFriction[1] = 1.0f;
1032         ob->anisotropicFriction[2] = 1.0f;
1033         ob->gameflag= OB_PROP|OB_COLLISION;
1034         ob->margin = 0.0;
1035         /* ob->pad3 == Contact Processing Threshold */
1036         ob->m_contactProcessingThreshold = 1.;
1037         
1038         /* NT fluid sim defaults */
1039         ob->fluidsimFlag = 0;
1040         ob->fluidsimSettings = NULL;
1041
1042         ob->pc_ids.first = ob->pc_ids.last = NULL;
1043         
1044         /* Animation Visualisation defaults */
1045         animviz_settings_init(&ob->avs);
1046
1047         return ob;
1048 }
1049
1050 /* general add: to scene, with layer from area and default name */
1051 /* creates minimum required data, but without vertices etc. */
1052 Object *add_object(struct Scene *scene, int type)
1053 {
1054         Object *ob;
1055         Base *base;
1056         char name[32];
1057
1058         strcpy(name, get_obdata_defname(type));
1059         ob = add_only_object(type, name);
1060
1061         ob->data= add_obdata_from_type(type);
1062
1063         ob->lay= scene->lay;
1064         
1065         base= scene_add_base(scene, ob);
1066         scene_select_base(scene, base);
1067         ob->recalc |= OB_RECALC;
1068
1069         return ob;
1070 }
1071
1072 SoftBody *copy_softbody(SoftBody *sb)
1073 {
1074         SoftBody *sbn;
1075         
1076         if (sb==NULL) return(NULL);
1077         
1078         sbn= MEM_dupallocN(sb);
1079         sbn->totspring= sbn->totpoint= 0;
1080         sbn->bpoint= NULL;
1081         sbn->bspring= NULL;
1082         
1083         sbn->keys= NULL;
1084         sbn->totkey= sbn->totpointkey= 0;
1085         
1086         sbn->scratch= NULL;
1087
1088         sbn->pointcache= BKE_ptcache_copy_list(&sbn->ptcaches, &sb->ptcaches);
1089
1090         if(sb->effector_weights)
1091                 sbn->effector_weights = MEM_dupallocN(sb->effector_weights);
1092
1093         return sbn;
1094 }
1095
1096 BulletSoftBody *copy_bulletsoftbody(BulletSoftBody *bsb)
1097 {
1098         BulletSoftBody *bsbn;
1099
1100         if (bsb == NULL)
1101                 return NULL;
1102         bsbn = MEM_dupallocN(bsb);
1103         /* no pointer in this structure yet */
1104         return bsbn;
1105 }
1106
1107 ParticleSystem *copy_particlesystem(ParticleSystem *psys)
1108 {
1109         ParticleSystem *psysn;
1110         ParticleData *pa;
1111         int p;
1112
1113         psysn= MEM_dupallocN(psys);
1114         psysn->particles= MEM_dupallocN(psys->particles);
1115         psysn->child= MEM_dupallocN(psys->child);
1116
1117         if(psys->part->type == PART_HAIR) {
1118                 for(p=0, pa=psysn->particles; p<psysn->totpart; p++, pa++)
1119                         pa->hair = MEM_dupallocN(pa->hair);
1120         }
1121
1122         if(psysn->particles && (psysn->particles->keys || psysn->particles->boid)) {
1123                 ParticleKey *key = psysn->particles->keys;
1124                 BoidParticle *boid = psysn->particles->boid;
1125
1126                 if(key)
1127                         key = MEM_dupallocN(key);
1128                 
1129                 if(boid)
1130                         boid = MEM_dupallocN(boid);
1131                 
1132                 for(p=0, pa=psysn->particles; p<psysn->totpart; p++, pa++) {
1133                         if(boid)
1134                                 pa->boid = boid++;
1135                         if(key) {
1136                                 pa->keys = key;
1137                                 key += pa->totkey;
1138                         }
1139                 }
1140         }
1141
1142         if(psys->clmd) {
1143                 psysn->clmd = (ClothModifierData *)modifier_new(eModifierType_Cloth);
1144                 modifier_copyData((ModifierData*)psys->clmd, (ModifierData*)psysn->clmd);
1145                 psys->hair_in_dm = psys->hair_out_dm = NULL;
1146         }
1147
1148         BLI_duplicatelist(&psysn->targets, &psys->targets);
1149         
1150         psysn->pathcache= NULL;
1151         psysn->childcache= NULL;
1152         psysn->edit= NULL;
1153         psysn->frand= NULL;
1154         psysn->pdd= NULL;
1155         
1156         psysn->pathcachebufs.first = psysn->pathcachebufs.last = NULL;
1157         psysn->childcachebufs.first = psysn->childcachebufs.last = NULL;
1158         psysn->renderdata = NULL;
1159         
1160         psysn->pointcache= BKE_ptcache_copy_list(&psysn->ptcaches, &psys->ptcaches);
1161
1162         /* XXX - from reading existing code this seems correct but intended usage of
1163          * pointcache should /w cloth should be added in 'ParticleSystem' - campbell */
1164         if(psysn->clmd) {
1165                 psysn->clmd->point_cache= psysn->pointcache;
1166         }
1167
1168         id_us_plus((ID *)psysn->part);
1169
1170         return psysn;
1171 }
1172
1173 void copy_object_particlesystems(Object *obn, Object *ob)
1174 {
1175         ParticleSystemModifierData *psmd;
1176         ParticleSystem *psys, *npsys;
1177         ModifierData *md;
1178
1179         obn->particlesystem.first= obn->particlesystem.last= NULL;
1180         for(psys=ob->particlesystem.first; psys; psys=psys->next) {
1181                 npsys= copy_particlesystem(psys);
1182
1183                 BLI_addtail(&obn->particlesystem, npsys);
1184
1185                 /* need to update particle modifiers too */
1186                 for(md=obn->modifiers.first; md; md=md->next) {
1187                         if(md->type==eModifierType_ParticleSystem) {
1188                                 psmd= (ParticleSystemModifierData*)md;
1189                                 if(psmd->psys==psys)
1190                                         psmd->psys= npsys;
1191                         }
1192                 }
1193         }
1194 }
1195
1196 void copy_object_softbody(Object *obn, Object *ob)
1197 {
1198         if(ob->soft)
1199                 obn->soft= copy_softbody(ob->soft);
1200 }
1201
1202 static void copy_object_pose(Object *obn, Object *ob)
1203 {
1204         bPoseChannel *chan;
1205         
1206         /* note: need to clear obn->pose pointer first, so that copy_pose works (otherwise there's a crash) */
1207         obn->pose= NULL;
1208         copy_pose(&obn->pose, ob->pose, 1);     /* 1 = copy constraints */
1209
1210         for (chan = obn->pose->chanbase.first; chan; chan=chan->next){
1211                 bConstraint *con;
1212                 
1213                 chan->flag &= ~(POSE_LOC|POSE_ROT|POSE_SIZE);
1214                 
1215                 for (con= chan->constraints.first; con; con= con->next) {
1216                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1217                         ListBase targets = {NULL, NULL};
1218                         bConstraintTarget *ct;
1219                         
1220 #if 0 // XXX old animation system
1221                         /* note that we can't change lib linked ipo blocks. for making
1222                          * proxies this still works correct however because the object
1223                          * is changed to object->proxy_from when evaluating the driver. */
1224                         if(con->ipo && !con->ipo->id.lib) {
1225                                 IpoCurve *icu;
1226                                 
1227                                 con->ipo= copy_ipo(con->ipo);
1228                                 
1229                                 for(icu= con->ipo->curve.first; icu; icu= icu->next) {
1230                                         if(icu->driver && icu->driver->ob==ob)
1231                                                 icu->driver->ob= obn;
1232                                 }
1233                         }
1234 #endif // XXX old animation system
1235                         
1236                         if (cti && cti->get_constraint_targets) {
1237                                 cti->get_constraint_targets(con, &targets);
1238                                 
1239                                 for (ct= targets.first; ct; ct= ct->next) {
1240                                         if (ct->tar == ob)
1241                                                 ct->tar = obn;
1242                                 }
1243                                 
1244                                 if (cti->flush_constraint_targets)
1245                                         cti->flush_constraint_targets(con, &targets, 0);
1246                         }
1247                 }
1248         }
1249 }
1250
1251 Object *copy_object(Object *ob)
1252 {
1253         Object *obn;
1254         ModifierData *md;
1255         int a;
1256
1257         obn= copy_libblock(ob);
1258         
1259         if(ob->totcol) {
1260                 obn->mat= MEM_dupallocN(ob->mat);
1261                 obn->matbits= MEM_dupallocN(ob->matbits);
1262                 obn->totcol= ob->totcol;
1263         }
1264         
1265         if(ob->bb) obn->bb= MEM_dupallocN(ob->bb);
1266         obn->path= NULL;
1267         obn->flag &= ~OB_FROMGROUP;
1268         
1269         obn->modifiers.first = obn->modifiers.last= NULL;
1270         
1271         for (md=ob->modifiers.first; md; md=md->next) {
1272                 ModifierData *nmd = modifier_new(md->type);
1273                 modifier_copyData(md, nmd);
1274                 BLI_addtail(&obn->modifiers, nmd);
1275         }
1276
1277         obn->prop.first = obn->prop.last = NULL;
1278         copy_properties(&obn->prop, &ob->prop);
1279         
1280         copy_sensors(&obn->sensors, &ob->sensors);
1281         copy_controllers(&obn->controllers, &ob->controllers);
1282         copy_actuators(&obn->actuators, &ob->actuators);
1283         
1284         if(ob->pose) {
1285                 copy_object_pose(obn, ob);
1286                 /* backwards compat... non-armatures can get poses in older files? */
1287                 if(ob->type==OB_ARMATURE)
1288                         armature_rebuild_pose(obn, obn->data);
1289         }
1290         defgroup_copy_list(&obn->defbase, &ob->defbase);
1291         copy_constraints(&obn->constraints, &ob->constraints);
1292
1293         obn->mode = 0;
1294         obn->sculpt = NULL;
1295
1296         /* increase user numbers */
1297         id_us_plus((ID *)obn->data);
1298         id_us_plus((ID *)obn->dup_group);
1299         
1300
1301         for(a=0; a<obn->totcol; a++) id_us_plus((ID *)obn->mat[a]);
1302         
1303         obn->disp.first= obn->disp.last= NULL;
1304         
1305         if(ob->pd){
1306                 obn->pd= MEM_dupallocN(ob->pd);
1307                 if(obn->pd->tex)
1308                         id_us_plus(&(obn->pd->tex->id));
1309                 if(obn->pd->rng)
1310                         obn->pd->rng = MEM_dupallocN(ob->pd->rng);
1311         }
1312         obn->soft= copy_softbody(ob->soft);
1313         obn->bsoft = copy_bulletsoftbody(ob->bsoft);
1314
1315         copy_object_particlesystems(obn, ob);
1316         
1317         obn->derivedDeform = NULL;
1318         obn->derivedFinal = NULL;
1319
1320         obn->gpulamp.first = obn->gpulamp.last = NULL;
1321         obn->pc_ids.first = obn->pc_ids.last = NULL;
1322         
1323         return obn;
1324 }
1325
1326 void expand_local_object(Object *ob)
1327 {
1328         //bActionStrip *strip;
1329         ParticleSystem *psys;
1330         int a;
1331
1332 #if 0 // XXX old animation system
1333         id_lib_extern((ID *)ob->action);
1334         id_lib_extern((ID *)ob->ipo);
1335 #endif // XXX old animation system
1336         id_lib_extern((ID *)ob->data);
1337         id_lib_extern((ID *)ob->dup_group);
1338         
1339         for(a=0; a<ob->totcol; a++) {
1340                 id_lib_extern((ID *)ob->mat[a]);
1341         }
1342 #if 0 // XXX old animation system
1343         for (strip=ob->nlastrips.first; strip; strip=strip->next) {
1344                 id_lib_extern((ID *)strip->act);
1345         }
1346 #endif // XXX old animation system
1347         for(psys=ob->particlesystem.first; psys; psys=psys->next)
1348                 id_lib_extern((ID *)psys->part);
1349 }
1350
1351 void make_local_object(Object *ob)
1352 {
1353         Object *obn;
1354         Scene *sce;
1355         Base *base;
1356         int local=0, lib=0;
1357
1358         /* - only lib users: do nothing
1359             * - only local users: set flag
1360             * - mixed: make copy
1361             */
1362         
1363         if(ob->id.lib==NULL) return;
1364         
1365         ob->proxy= ob->proxy_from= NULL;
1366         
1367         if(ob->id.us==1) {
1368                 ob->id.lib= NULL;
1369                 ob->id.flag= LIB_LOCAL;
1370                 new_id(0, (ID *)ob, 0);
1371
1372         }
1373         else {
1374                 sce= G.main->scene.first;
1375                 while(sce) {
1376                         base= sce->base.first;
1377                         while(base) {
1378                                 if(base->object==ob) {
1379                                         if(sce->id.lib) lib++;
1380                                         else local++;
1381                                         break;
1382                                 }
1383                                 base= base->next;
1384                         }
1385                         sce= sce->id.next;
1386                 }
1387                 
1388                 if(local && lib==0) {
1389                         ob->id.lib= 0;
1390                         ob->id.flag= LIB_LOCAL;
1391                         new_id(0, (ID *)ob, 0);
1392                 }
1393                 else if(local && lib) {
1394                         obn= copy_object(ob);
1395                         obn->id.us= 0;
1396                         
1397                         sce= G.main->scene.first;
1398                         while(sce) {
1399                                 if(sce->id.lib==0) {
1400                                         base= sce->base.first;
1401                                         while(base) {
1402                                                 if(base->object==ob) {
1403                                                         base->object= obn;
1404                                                         obn->id.us++;
1405                                                         ob->id.us--;
1406                                                 }
1407                                                 base= base->next;
1408                                         }
1409                                 }
1410                                 sce= sce->id.next;
1411                         }
1412                 }
1413         }
1414         
1415         expand_local_object(ob);
1416 }
1417
1418 /*
1419  * Returns true if the Object is a from an external blend file (libdata)
1420  */
1421 int object_is_libdata(Object *ob)
1422 {
1423         if (!ob) return 0;
1424         if (ob->proxy) return 0;
1425         if (ob->id.lib) return 1;
1426         return 0;
1427 }
1428
1429 /* Returns true if the Object data is a from an external blend file (libdata) */
1430 int object_data_is_libdata(Object *ob)
1431 {
1432         if(!ob) return 0;
1433         if(ob->proxy && (ob->data==NULL || ((ID *)ob->data)->lib==NULL)) return 0;
1434         if(ob->id.lib) return 1;
1435         if(ob->data==NULL) return 0;
1436         if(((ID *)ob->data)->lib) return 1;
1437
1438         return 0;
1439 }
1440
1441 /* *************** PROXY **************** */
1442
1443 /* when you make proxy, ensure the exposed layers are extern */
1444 static void armature_set_id_extern(Object *ob)
1445 {
1446         bArmature *arm= ob->data;
1447         bPoseChannel *pchan;
1448         int lay= arm->layer_protected;
1449         
1450         for (pchan = ob->pose->chanbase.first; pchan; pchan=pchan->next) {
1451                 if(!(pchan->bone->layer & lay))
1452                         id_lib_extern((ID *)pchan->custom);
1453         }
1454                         
1455 }
1456
1457 void object_copy_proxy_drivers(Object *ob, Object *target)
1458 {
1459         if ((target->adt) && (target->adt->drivers.first)) {
1460                 FCurve *fcu;
1461                 
1462                 /* add new animdata block */
1463                 if(!ob->adt)
1464                         ob->adt= BKE_id_add_animdata(&ob->id);
1465                 
1466                 /* make a copy of all the drivers (for now), then correct any links that need fixing */
1467                 free_fcurves(&ob->adt->drivers);
1468                 copy_fcurves(&ob->adt->drivers, &target->adt->drivers);
1469                 
1470                 for (fcu= ob->adt->drivers.first; fcu; fcu= fcu->next) {
1471                         ChannelDriver *driver= fcu->driver;
1472                         DriverVar *dvar;
1473                         
1474                         for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
1475                                 /* all drivers */
1476                                 DRIVER_TARGETS_LOOPER(dvar) 
1477                                 {
1478                                         if ((Object *)dtar->id == target)
1479                                                 dtar->id= (ID *)ob;
1480                                         else
1481                                                 id_lib_extern((ID *)dtar->id);
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) ) {
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_v3v3(mat[3], 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_v3v3(vec, 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_v3v3(mat[3], 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         /* Handle tracking */
2037         if(ob->track) {
2038                 if( ctime != ob->track->ctime) where_is_object_time(scene, ob->track, ctime);
2039                 solve_tracking (ob, ob->track->obmat);
2040         }
2041
2042         /* solve constraints */
2043         if (ob->constraints.first && !(ob->flag & OB_NO_CONSTRAINTS)) {
2044                 bConstraintOb *cob;
2045                 
2046                 cob= constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2047                 
2048                 /* constraints need ctime, not stime. Some call where_is_object_time and bsystem_time */
2049                 solve_constraints (&ob->constraints, cob, ctime);
2050                 
2051                 constraints_clear_evalob(cob);
2052         }
2053         
2054         /* set negative scale flag in object */
2055         if(is_negative_m4(ob->obmat))   ob->transflag |= OB_NEG_SCALE;
2056         else                                                    ob->transflag &= ~OB_NEG_SCALE;
2057 }
2058
2059 static void solve_parenting (Scene *scene, Object *ob, Object *par, float obmat[][4], float slowmat[][4], int simul)
2060 {
2061         float totmat[4][4];
2062         float tmat[4][4];
2063         float locmat[4][4];
2064         float vec[3];
2065         int ok;
2066         
2067         object_to_mat4(ob, locmat);
2068         
2069         if(ob->partype & PARSLOW) copy_m4_m4(slowmat, obmat);
2070
2071         switch(ob->partype & PARTYPE) {
2072         case PAROBJECT:
2073                 ok= 0;
2074                 if(par->type==OB_CURVE) {
2075                         if( ((Curve *)par->data)->flag & CU_PATH ) {
2076                                 ob_parcurve(scene, ob, par, tmat);
2077                                 ok= 1;
2078                         }
2079                 }
2080                 
2081                 if(ok) mul_serie_m4(totmat, par->obmat, tmat, 
2082                         NULL, NULL, NULL, NULL, NULL, NULL);
2083                 else copy_m4_m4(totmat, par->obmat);
2084                 
2085                 break;
2086         case PARBONE:
2087                 ob_parbone(ob, par, tmat);
2088                 mul_serie_m4(totmat, par->obmat, tmat,         
2089                         NULL, NULL, NULL, NULL, NULL, NULL);
2090                 break;
2091                 
2092         case PARVERT1:
2093                 unit_m4(totmat);
2094                 if (simul){
2095                         VECCOPY(totmat[3], par->obmat[3]);
2096                 }
2097                 else{
2098                         give_parvert(par, ob->par1, vec);
2099                         mul_v3_m4v3(totmat[3], par->obmat, vec);
2100                 }
2101                 break;
2102         case PARVERT3:
2103                 ob_parvert3(ob, par, tmat);
2104                 
2105                 mul_serie_m4(totmat, par->obmat, tmat,         
2106                         NULL, NULL, NULL, NULL, NULL, NULL);
2107                 break;
2108                 
2109         case PARSKEL:
2110                 copy_m4_m4(totmat, par->obmat);
2111                 break;
2112         }
2113         
2114         // total 
2115         mul_serie_m4(tmat, totmat, ob->parentinv,         
2116                 NULL, NULL, NULL, NULL, NULL, NULL);
2117         mul_serie_m4(obmat, tmat, locmat,         
2118                 NULL, NULL, NULL, NULL, NULL, NULL);
2119         
2120         if (simul) {
2121
2122         }
2123         else{
2124                 // external usable originmat 
2125                 copy_m3_m4(originmat, tmat);
2126                 
2127                 // origin, voor help line
2128                 if( (ob->partype & 15)==PARSKEL ) {
2129                         VECCOPY(ob->orig, par->obmat[3]);
2130                 }
2131                 else {
2132                         VECCOPY(ob->orig, totmat[3]);
2133                 }
2134         }
2135
2136 }
2137 void solve_tracking (Object *ob, float targetmat[][4])
2138 {
2139         float quat[4];
2140         float vec[3];
2141         float totmat[3][3];
2142         float tmat[4][4];
2143         
2144         sub_v3_v3v3(vec, ob->obmat[3], targetmat[3]);
2145         vec_to_quat( quat,vec, ob->trackflag, ob->upflag);
2146         quat_to_mat3( totmat,quat);
2147         
2148         if(ob->parent && (ob->transflag & OB_POWERTRACK)) {
2149                 /* 'temporal' : clear parent info */
2150                 object_to_mat4(ob, tmat);
2151                 tmat[0][3]= ob->obmat[0][3];
2152                 tmat[1][3]= ob->obmat[1][3];
2153                 tmat[2][3]= ob->obmat[2][3];
2154                 tmat[3][0]= ob->obmat[3][0];
2155                 tmat[3][1]= ob->obmat[3][1];
2156                 tmat[3][2]= ob->obmat[3][2];
2157                 tmat[3][3]= ob->obmat[3][3];
2158         }
2159         else copy_m4_m4(tmat, ob->obmat);
2160         
2161         mul_m4_m3m4(ob->obmat, totmat, tmat);
2162
2163 }
2164
2165 void where_is_object(struct Scene *scene, Object *ob)
2166 {
2167         where_is_object_time(scene, ob, (float)scene->r.cfra);
2168 }
2169
2170
2171 void where_is_object_simul(Scene *scene, Object *ob)
2172 /* was written for the old game engine (until 2.04) */
2173 /* It seems that this function is only called
2174 for a lamp that is the child of another object */
2175 {
2176         Object *par;
2177         //Ipo *ipo;
2178         float *fp1, *fp2;
2179         float slowmat[4][4];
2180         float fac1, fac2;
2181         int a;
2182         
2183         /* NO TIMEOFFS */
2184         
2185         /* no ipo! (because of dloc and realtime-ipos) */
2186                 // XXX old animation system
2187         //ipo= ob->ipo;
2188         //ob->ipo= NULL;
2189
2190         if(ob->parent) {
2191                 par= ob->parent;
2192                 
2193                 solve_parenting(scene, ob, par, ob->obmat, slowmat, 1);
2194
2195                 if(ob->partype & PARSLOW) {
2196
2197                         fac1= (float)(1.0/(1.0+ fabs(give_timeoffset(ob))));
2198                         fac2= 1.0f-fac1;
2199                         fp1= ob->obmat[0];
2200                         fp2= slowmat[0];
2201                         for(a=0; a<16; a++, fp1++, fp2++) {
2202                                 fp1[0]= fac1*fp1[0] + fac2*fp2[0];
2203                         }
2204                 }
2205                 
2206         }
2207         else {
2208                 object_to_mat4(ob, ob->obmat);
2209         }
2210         
2211         if(ob->track) 
2212                 solve_tracking(ob, ob->track->obmat);
2213
2214         /* solve constraints */
2215         if (ob->constraints.first) {
2216                 bConstraintOb *cob;
2217                 
2218                 cob= constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2219                 solve_constraints(&ob->constraints, cob, (float)scene->r.cfra);
2220                 constraints_clear_evalob(cob);
2221         }
2222         
2223         /*  WATCH IT!!! */
2224                 // XXX old animation system
2225         //ob->ipo= ipo;
2226 }
2227
2228 /* for calculation of the inverse parent transform, only used for editor */
2229 void what_does_parent(Scene *scene, Object *ob, Object *workob)
2230 {
2231         clear_workob(workob);
2232         
2233         unit_m4(workob->obmat);
2234         unit_m4(workob->parentinv);
2235         unit_m4(workob->constinv);
2236         workob->parent= ob->parent;
2237         workob->track= ob->track;
2238
2239         workob->trackflag= ob->trackflag;
2240         workob->upflag= ob->upflag;
2241         
2242         workob->partype= ob->partype;
2243         workob->par1= ob->par1;
2244         workob->par2= ob->par2;
2245         workob->par3= ob->par3;
2246
2247         workob->constraints.first = ob->constraints.first;
2248         workob->constraints.last = ob->constraints.last;
2249
2250         strcpy(workob->parsubstr, ob->parsubstr); 
2251
2252         where_is_object(scene, workob);
2253 }
2254
2255 BoundBox *unit_boundbox()
2256 {
2257         BoundBox *bb;
2258         float min[3] = {-1.0f,-1.0f,-1.0f}, max[3] = {-1.0f,-1.0f,-1.0f};
2259
2260         bb= MEM_callocN(sizeof(BoundBox), "bb");
2261         boundbox_set_from_min_max(bb, min, max);
2262         
2263         return bb;
2264 }
2265
2266 void boundbox_set_from_min_max(BoundBox *bb, float min[3], float max[3])
2267 {
2268         bb->vec[0][0]=bb->vec[1][0]=bb->vec[2][0]=bb->vec[3][0]= min[0];
2269         bb->vec[4][0]=bb->vec[5][0]=bb->vec[6][0]=bb->vec[7][0]= max[0];
2270         
2271         bb->vec[0][1]=bb->vec[1][1]=bb->vec[4][1]=bb->vec[5][1]= min[1];
2272         bb->vec[2][1]=bb->vec[3][1]=bb->vec[6][1]=bb->vec[7][1]= max[1];
2273
2274         bb->vec[0][2]=bb->vec[3][2]=bb->vec[4][2]=bb->vec[7][2]= min[2];
2275         bb->vec[1][2]=bb->vec[2][2]=bb->vec[5][2]=bb->vec[6][2]= max[2];
2276 }
2277
2278 BoundBox *object_get_boundbox(Object *ob)
2279 {
2280         BoundBox *bb= NULL;
2281         
2282         if(ob->type==OB_MESH) {
2283                 bb = mesh_get_bb(ob);
2284         }
2285         else if (ELEM3(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2286                 bb= ob->bb ? ob->bb : ( (Curve *)ob->data )->bb;
2287         }
2288         else if(ob->type==OB_MBALL) {
2289                 bb= ob->bb;
2290         }
2291         return bb;
2292 }
2293
2294 /* used to temporally disable/enable boundbox */
2295 void object_boundbox_flag(Object *ob, int flag, int set)
2296 {
2297         BoundBox *bb= object_get_boundbox(ob);
2298         if(bb) {
2299                 if(set) bb->flag |= flag;
2300                 else bb->flag &= ~flag;
2301         }
2302 }
2303
2304 void minmax_object(Object *ob, float *min, float *max)
2305 {
2306         BoundBox bb;
2307         Mesh *me;
2308         Curve *cu;
2309         float vec[3];
2310         int a;
2311         
2312         switch(ob->type) {
2313                 
2314         case OB_CURVE:
2315         case OB_FONT:
2316         case OB_SURF:
2317                 cu= ob->data;
2318                 
2319                 if(cu->bb==NULL) tex_space_curve(cu);
2320                 bb= *(cu->bb);
2321                 
2322                 for(a=0; a<8; a++) {
2323                         mul_m4_v3(ob->obmat, bb.vec[a]);
2324                         DO_MINMAX(bb.vec[a], min, max);
2325                 }
2326                 break;
2327         case OB_ARMATURE:
2328                 if(ob->pose) {
2329                         bPoseChannel *pchan;
2330                         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2331                                 VECCOPY(vec, pchan->pose_head);
2332                                 mul_m4_v3(ob->obmat, vec);
2333                                 DO_MINMAX(vec, min, max);
2334                                 VECCOPY(vec, pchan->pose_tail);
2335                                 mul_m4_v3(ob->obmat, vec);
2336                                 DO_MINMAX(vec, min, max);
2337                         }
2338                         break;
2339                 }
2340                 /* no break, get_mesh will give NULL and it passes on to default */
2341         case OB_MESH:
2342                 me= get_mesh(ob);
2343                 
2344                 if(me) {
2345                         bb = *mesh_get_bb(ob);
2346                         
2347                         for(a=0; a<8; a++) {
2348                                 mul_m4_v3(ob->obmat, bb.vec[a]);
2349                                 DO_MINMAX(bb.vec[a], min, max);
2350                         }
2351                 }
2352                 if(min[0] < max[0] ) break;
2353                 
2354                 /* else here no break!!!, mesh can be zero sized */
2355                 
2356         default:
2357                 DO_MINMAX(ob->obmat[3], min, max);
2358
2359                 VECCOPY(vec, ob->obmat[3]);
2360                 add_v3_v3v3(vec, vec, ob->size);
2361                 DO_MINMAX(vec, min, max);
2362
2363                 VECCOPY(vec, ob->obmat[3]);
2364                 sub_v3_v3v3(vec, vec, ob->size);
2365                 DO_MINMAX(vec, min, max);
2366                 break;
2367         }
2368 }
2369
2370 int minmax_object_duplis(Scene *scene, Object *ob, float *min, float *max)
2371 {
2372         int ok= 0;
2373         if ((ob->transflag & OB_DUPLI)==0) {
2374                 return ok;
2375         } else {
2376                 ListBase *lb;
2377                 DupliObject *dob;
2378                 
2379                 lb= object_duplilist(scene, ob);
2380                 for(dob= lb->first; dob; dob= dob->next) {
2381                         if(dob->no_draw == 0) {
2382                                 BoundBox *bb= object_get_boundbox(dob->ob);
2383
2384                                 if(bb) {
2385                                         int i;
2386                                         for(i=0; i<8; i++) {
2387                                                 float vec[3];
2388                                                 mul_v3_m4v3(vec, dob->mat, bb->vec[i]);
2389                                                 DO_MINMAX(vec, min, max);
2390                                         }
2391
2392                                         ok= 1;
2393                                 }
2394                         }
2395                 }
2396                 free_object_duplilist(lb);      /* does restore */
2397         }
2398
2399         return ok;
2400 }
2401
2402 /* copied from DNA_object_types.h */
2403 typedef struct ObTfmBack {
2404         float loc[3], dloc[3], orig[3];
2405         float size[3], dsize[3];        /* scale and delta scale */
2406         float rot[3], drot[3];          /* euler rotation */
2407         float quat[4], dquat[4];        /* quaternion rotation */
2408         float rotAxis[3], drotAxis[3];  /* axis angle rotation - axis part */
2409         float rotAngle, drotAngle;      /* axis angle rotation - angle part */
2410         float obmat[4][4];              /* final worldspace matrix with constraints & animsys applied */
2411         float parentinv[4][4]; /* inverse result of parent, so that object doesn't 'stick' to parent */
2412         float constinv[4][4]; /* inverse result of constraints. doesn't include effect of parent or object local transform */
2413         float imat[4][4];       /* inverse matrix of 'obmat' for during render, old game engine, temporally: ipokeys of transform  */
2414 } ObTfmBack;
2415
2416 void *object_tfm_backup(Object *ob)
2417 {
2418         ObTfmBack *obtfm= MEM_mallocN(sizeof(ObTfmBack), "ObTfmBack");
2419         copy_v3_v3(obtfm->loc, ob->loc);
2420         copy_v3_v3(obtfm->dloc, ob->dloc);
2421         copy_v3_v3(obtfm->orig, ob->orig);
2422         copy_v3_v3(obtfm->size, ob->size);
2423         copy_v3_v3(obtfm->dsize, ob->dsize);
2424         copy_v3_v3(obtfm->rot, ob->rot);
2425         copy_v3_v3(obtfm->drot, ob->drot);
2426         copy_qt_qt(obtfm->quat, ob->quat);
2427         copy_qt_qt(obtfm->dquat, ob->dquat);
2428         copy_v3_v3(obtfm->rotAxis, ob->rotAxis);
2429         copy_v3_v3(obtfm->drotAxis, ob->drotAxis);
2430         obtfm->rotAngle= ob->rotAngle;
2431         obtfm->drotAngle= ob->drotAngle;
2432         copy_m4_m4(obtfm->obmat, ob->obmat);
2433         copy_m4_m4(obtfm->parentinv, ob->parentinv);
2434         copy_m4_m4(obtfm->constinv, ob->constinv);
2435         copy_m4_m4(obtfm->imat, ob->imat);
2436
2437         return (void *)obtfm;
2438 }
2439
2440 void object_tfm_restore(Object *ob, void *obtfm_pt)
2441 {
2442         ObTfmBack *obtfm= (ObTfmBack *)obtfm_pt;
2443         copy_v3_v3(ob->loc, obtfm->loc);
2444         copy_v3_v3(ob->dloc, obtfm->dloc);
2445         copy_v3_v3(ob->orig, obtfm->orig);
2446         copy_v3_v3(ob->size, obtfm->size);
2447         copy_v3_v3(ob->dsize, obtfm->dsize);
2448         copy_v3_v3(ob->rot, obtfm->rot);
2449         copy_v3_v3(ob->drot, obtfm->drot);
2450         copy_qt_qt(ob->quat, obtfm->quat);
2451         copy_qt_qt(ob->dquat, obtfm->dquat);
2452         copy_v3_v3(ob->rotAxis, obtfm->rotAxis);
2453         copy_v3_v3(ob->drotAxis, obtfm->drotAxis);
2454         ob->rotAngle= obtfm->rotAngle;
2455         ob->drotAngle= obtfm->drotAngle;
2456         copy_m4_m4(ob->obmat, obtfm->obmat);
2457         copy_m4_m4(ob->parentinv, obtfm->parentinv);
2458         copy_m4_m4(ob->constinv, obtfm->constinv);
2459         copy_m4_m4(ob->imat, obtfm->imat);
2460 }
2461
2462 /* proxy rule: lib_object->proxy_from == the one we borrow from, only set temporal and cleared here */
2463 /*           local_object->proxy      == pointer to library object, saved in files and read */
2464
2465 /* function below is polluted with proxy exceptions, cleanup will follow! */
2466
2467 /* the main object update call, for object matrix, constraints, keys and displist (modifiers) */
2468 /* requires flags to be set! */
2469 void object_handle_update(Scene *scene, Object *ob)
2470 {
2471         if(ob->recalc & OB_RECALC) {
2472                 
2473                 /* XXX new animsys warning: depsgraph tag OB_RECALC_DATA should not skip drivers, 
2474                    which is only in where_is_object now */
2475                 if(ob->recalc & OB_RECALC) {
2476                         
2477                         if (G.f & G_DEBUG)
2478                                 printf("recalcob %s\n", ob->id.name+2);
2479                         
2480                         /* handle proxy copy for target */
2481                         if(ob->id.lib && ob->proxy_from) {
2482                                 // printf("ob proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2483                                 if(ob->proxy_from->proxy_group) {/* transform proxy into group space */
2484                                         Object *obg= ob->proxy_from->proxy_group;
2485                                         invert_m4_m4(obg->imat, obg->obmat);
2486                                         mul_m4_m4m4(ob->obmat, ob->proxy_from->obmat, obg->imat);
2487                                 }
2488                                 else
2489                                         copy_m4_m4(ob->obmat, ob->proxy_from->obmat);
2490                         }
2491                         else
2492                                 where_is_object(scene, ob);
2493                 }
2494                 
2495                 if(ob->recalc & OB_RECALC_DATA) {
2496                         ID *data_id= (ID *)ob->data;
2497                         AnimData *adt= BKE_animdata_from_id(data_id);
2498                         float ctime= (float)scene->r.cfra; // XXX this is bad...
2499                         
2500                         if (G.f & G_DEBUG)
2501                                 printf("recalcdata %s\n", ob->id.name+2);
2502                         
2503                         /* includes all keys and modifiers */
2504                         if(ob->type==OB_MESH) {
2505                                 EditMesh *em = BKE_mesh_get_editmesh(ob->data);
2506                                 
2507                                 /* evaluate drivers */
2508                                 // XXX: should we push this to derivedmesh instead?
2509                                 BKE_animsys_evaluate_animdata(data_id, adt, ctime, ADT_RECALC_DRIVERS);
2510                                 
2511                                         // here was vieweditdatamask? XXX
2512                                 if(ob->mode & OB_MODE_EDIT) {
2513                                         makeDerivedMesh(scene, ob, em, CD_MASK_BAREMESH);
2514                                         BKE_mesh_end_editmesh(ob->data, em);
2515                                 } else
2516                                         makeDerivedMesh(scene, ob, NULL, CD_MASK_BAREMESH);
2517                         }
2518                         else if(ob->type==OB_MBALL) {
2519                                 makeDispListMBall(scene, ob);
2520                         } 
2521                         else if(ELEM3(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2522                                 makeDispListCurveTypes(scene, ob, 0);
2523                         }
2524                         else if(ELEM(ob->type, OB_CAMERA, OB_LAMP)) {
2525                                 /* evaluate drivers */
2526                                 BKE_animsys_evaluate_animdata(data_id, adt, ctime, ADT_RECALC_DRIVERS);
2527                         }
2528                         else if(ob->type==OB_LATTICE) {
2529                                 lattice_calc_modifiers(scene, ob);
2530                         }
2531                         else if(ob->type==OB_ARMATURE) {
2532                                 /* this happens for reading old files and to match library armatures with poses */
2533                                 // XXX this won't screw up the pose set already...
2534                                 if(ob->pose==NULL || (ob->pose->flag & POSE_RECALC))
2535                                         armature_rebuild_pose(ob, ob->data);
2536                                 
2537                                 /* evaluate drivers */
2538                                 BKE_animsys_evaluate_animdata(data_id, adt, ctime, ADT_RECALC_DRIVERS);
2539                                 
2540                                 if(ob->id.lib && ob->proxy_from) {
2541                                         copy_pose_result(ob->pose, ob->proxy_from->pose);
2542                                         // printf("pose proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2543                                 }
2544                                 else {
2545                                         where_is_pose(scene, ob);
2546                                 }
2547                         }
2548
2549                         if(ob->particlesystem.first) {
2550                                 ParticleSystem *tpsys, *psys;
2551                                 DerivedMesh *dm;
2552                                 ob->transflag &= ~OB_DUPLIPARTS;
2553                                 
2554                                 psys= ob->particlesystem.first;
2555                                 while(psys) {
2556                                         if(psys_check_enabled(ob, psys)) {
2557                                                 /* check use of dupli objects here */
2558                                                 if(psys->part && psys->part->draw_as == PART_DRAW_REND &&
2559                                                         ((psys->part->ren_as == PART_DRAW_OB && psys->part->dup_ob)
2560                                                         || (psys->part->ren_as == PART_DRAW_GR && psys->part->dup_group)))
2561                                                         ob->transflag |= OB_DUPLIPARTS;
2562
2563                                                 particle_system_update(scene, ob, psys);
2564                                                 psys= psys->next;
2565                                         }
2566                                         else if(psys->flag & PSYS_DELETE) {
2567                                                 tpsys=psys->next;
2568                                                 BLI_remlink(&ob->particlesystem, psys);
2569                                                 psys_free(ob,psys);
2570                                                 psys= tpsys;
2571                                         }
2572                                         else
2573                                                 psys= psys->next;
2574                                 }
2575
2576                                 if(G.rendering && ob->transflag & OB_DUPLIPARTS) {
2577                                         /* this is to make sure we get render level duplis in groups:
2578                                          * the derivedmesh must be created before init_render_mesh,
2579                                          * since object_duplilist does dupliparticles before that */
2580                                         dm = mesh_create_derived_render(scene, ob, CD_MASK_BAREMESH|CD_MASK_MTFACE|CD_MASK_MCOL);
2581                                         dm->release(dm);
2582
2583                                         for(psys=ob->particlesystem.first; psys; psys=psys->next)
2584                                                 psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated;
2585                                 }
2586                         }
2587                 }
2588
2589                 /* the no-group proxy case, we call update */
2590                 if(ob->proxy && ob->proxy_group==NULL) {
2591                         /* set pointer in library proxy target, for copying, but restore it */
2592                         ob->proxy->proxy_from= ob;
2593                         // printf("call update, lib ob %s proxy %s\n", ob->proxy->id.name, ob->id.name);
2594                         object_handle_update(scene, ob->proxy);
2595                 }
2596         
2597                 ob->recalc &= ~OB_RECALC;
2598         }
2599
2600         /* the case when this is a group proxy, object_update is called in group.c */
2601         if(ob->proxy) {
2602                 ob->proxy->proxy_from= ob;
2603                 // printf("set proxy pointer for later group stuff %s\n", ob->id.name);
2604         }
2605 }
2606
2607 float give_timeoffset(Object *ob) {
2608         if ((ob->ipoflag & OB_OFFS_PARENTADD) && ob->parent) {
2609                 return ob->sf + give_timeoffset(ob->parent);
2610         } else {
2611                 return ob->sf;
2612         }
2613 }
2614
2615 int give_obdata_texspace(Object *ob, short **texflag, float **loc, float **size, float **rot) {
2616         
2617         if (ob->data==NULL)
2618                 return 0;
2619         
2620         switch (GS(((ID *)ob->data)->name)) {
2621         case ID_ME:
2622         {
2623                 Mesh *me= ob->data;
2624                 if (texflag)    *texflag = &me->texflag;
2625                 if (loc)                *loc = me->loc;
2626                 if (size)               *size = me->size;
2627                 if (rot)                *rot = me->rot;
2628                 break;
2629         }
2630         case ID_CU:
2631         {
2632                 Curve *cu= ob->data;
2633                 if (texflag)    *texflag = &cu->texflag;
2634                 if (loc)                *loc = cu->loc;
2635                 if (size)               *size = cu->size;
2636                 if (rot)                *rot = cu->rot;
2637                 break;
2638         }
2639         case ID_MB:
2640         {
2641                 MetaBall *mb= ob->data;
2642                 if (texflag)    *texflag = &mb->texflag;
2643                 if (loc)                *loc = mb->loc;
2644                 if (size)               *size = mb->size;
2645                 if (rot)                *rot = mb->rot;
2646                 break;
2647         }
2648         default:
2649                 return 0;
2650         }
2651         return 1;
2652 }
2653
2654 /*
2655  * Test a bounding box for ray intersection
2656  * assumes the ray is already local to the boundbox space
2657  */
2658 int ray_hit_boundbox(struct BoundBox *bb, float ray_start[3], float ray_normal[3])
2659 {
2660         static int triangle_indexes[12][3] = {{0, 1, 2}, {0, 2, 3},
2661                                                                                   {3, 2, 6}, {3, 6, 7},
2662                                                                                   {1, 2, 6}, {1, 6, 5}, 
2663                                                                                   {5, 6, 7}, {4, 5, 7},
2664                                                                                   {0, 3, 7}, {0, 4, 7},
2665                                                                                   {0, 1, 5}, {0, 4, 5}};
2666         int result = 0;
2667         int i;
2668         
2669         for (i = 0; i < 12 && result == 0; i++)
2670         {
2671                 float lambda;
2672                 int v1, v2, v3;
2673                 v1 = triangle_indexes[i][0];
2674                 v2 = triangle_indexes[i][1];
2675                 v3 = triangle_indexes[i][2];
2676                 result = isect_ray_tri_v3(ray_start, ray_normal, bb->vec[v1], bb->vec[v2], bb->vec[v3], &lambda, NULL);
2677         }
2678         
2679         return result;
2680 }
2681
2682 static int pc_cmp(void *a, void *b)
2683 {
2684         LinkData *ad = a, *bd = b;
2685         if(GET_INT_FROM_POINTER(ad->data) > GET_INT_FROM_POINTER(bd->data))
2686                 return 1;
2687         else return 0;
2688 }
2689
2690 int object_insert_ptcache(Object *ob) 
2691 {
2692         LinkData *link = NULL;
2693         int i = 0;
2694
2695         BLI_sortlist(&ob->pc_ids, pc_cmp);
2696
2697         for(link=ob->pc_ids.first, i = 0; link; link=link->next, i++) 
2698         {
2699                 int index = GET_INT_FROM_POINTER(link->data);
2700
2701                 if(i < index)
2702                         break;
2703         }
2704
2705         link = MEM_callocN(sizeof(LinkData), "PCLink");
2706         link->data = SET_INT_IN_POINTER(i);
2707         BLI_addtail(&ob->pc_ids, link);
2708
2709         return i;
2710 }
2711
2712 /* 'lens' may be set for envmap only */
2713 void object_camera_matrix(
2714                 RenderData *rd, Object *camera, int winx, int winy, short field_second,
2715                 float winmat[][4], rctf *viewplane, float *clipsta, float *clipend, float *lens, float *ycor,
2716                 float *viewdx, float *viewdy
2717 ) {
2718         Camera *cam=NULL;
2719         float pixsize;
2720         float shiftx=0.0, shifty=0.0, winside, viewfac;
2721
2722         rd->mode &= ~R_ORTHO;
2723
2724         /* question mark */
2725         (*ycor)= rd->yasp / rd->xasp;
2726         if(rd->mode & R_FIELDS)
2727                 (*ycor) *= 2.0f;
2728
2729         if(camera->type==OB_CAMERA) {
2730                 cam= camera->data;
2731
2732                 if(cam->type==CAM_ORTHO) rd->mode |= R_ORTHO;
2733                 if(cam->flag & CAM_PANORAMA) rd->mode |= R_PANORAMA;
2734
2735                 /* solve this too... all time depending stuff is in convertblender.c?
2736                  * Need to update the camera early because it's used for projection matrices
2737                  * and other stuff BEFORE the animation update loop is done
2738                  * */
2739 #if 0 // XXX old animation system
2740                 if(cam->ipo) {
2741                         calc_ipo(cam->ipo, frame_to_float(re->scene, re->r.cfra));
2742                         execute_ipo(&cam->id, cam->ipo);
2743                 }
2744 #endif // XXX old animation system
2745                 shiftx=cam->shiftx;
2746                 shifty=cam->shifty;
2747                 (*lens)= cam->lens;
2748                 (*clipsta)= cam->clipsta;
2749                 (*clipend)= cam->clipend;
2750         }
2751         else if(camera->type==OB_LAMP) {
2752                 Lamp *la= camera->data;
2753                 float fac= cos( M_PI*la->spotsize/360.0 );
2754                 float phi= acos(fac);
2755
2756                 (*lens)= 16.0*fac/sin(phi);
2757                 if((*lens)==0.0f)
2758                         (*lens)= 35.0;
2759                 (*clipsta)= la->clipsta;
2760                 (*clipend)= la->clipend;
2761         }
2762         else {  /* envmap exception... */;
2763                 if((*lens)==0.0f)
2764                         (*lens)= 16.0;
2765
2766                 if((*clipsta)==0.0f || (*clipend)==0.0f) {
2767                         (*clipsta)= 0.1f;
2768                         (*clipend)= 1000.0f;
2769                 }
2770         }
2771
2772         /* ortho only with camera available */
2773         if(cam && rd->mode & R_ORTHO) {
2774                 if(rd->xasp*winx >= rd->yasp*winy) {
2775                         viewfac= winx;
2776                 }
2777                 else {
2778                         viewfac= (*ycor) * winy;
2779                 }
2780                 /* ortho_scale == 1.0 means exact 1 to 1 mapping */
2781                 pixsize= cam->ortho_scale/viewfac;
2782         }
2783         else {
2784                 if(rd->xasp*winx >= rd->yasp*winy)      viewfac= ((*lens) * winx)/32.0;
2785                 else                                                            viewfac= (*ycor) * ((*lens) * winy)/32.0;
2786                 pixsize= (*clipsta) / viewfac;
2787         }
2788
2789         /* viewplane fully centered, zbuffer fills in jittered between -.5 and +.5 */
2790         winside= MAX2(winx, winy);
2791         viewplane->xmin= -0.5f*(float)winx + shiftx*winside;
2792         viewplane->ymin= -0.5f*(*ycor)*(float)winy + shifty*winside;
2793         viewplane->xmax=  0.5f*(float)winx + shiftx*winside;
2794         viewplane->ymax=  0.5f*(*ycor)*(float)winy + shifty*winside;
2795
2796         if(field_second) {
2797                 if(rd->mode & R_ODDFIELD) {
2798                         viewplane->ymin-= 0.5 * (*ycor);
2799                         viewplane->ymax-= 0.5 * (*ycor);
2800                 }
2801                 else {
2802                         viewplane->ymin+= 0.5 * (*ycor);
2803                         viewplane->ymax+= 0.5 * (*ycor);
2804                 }
2805         }
2806         /* the window matrix is used for clipping, and not changed during OSA steps */
2807         /* using an offset of +0.5 here would give clip errors on edges */
2808         viewplane->xmin *= pixsize;
2809         viewplane->xmax *= pixsize;
2810         viewplane->ymin *= pixsize;
2811         viewplane->ymax *= pixsize;
2812
2813         (*viewdx)= pixsize;
2814         (*viewdy)= (*ycor) * pixsize;
2815
2816         if(rd->mode & R_ORTHO)
2817                 orthographic_m4(winmat, viewplane->xmin, viewplane->xmax, viewplane->ymin, viewplane->ymax, *clipsta, *clipend);
2818         else
2819                 perspective_m4(winmat, viewplane->xmin, viewplane->xmax, viewplane->ymin, viewplane->ymax, *clipsta, *clipend);
2820
2821 }
2822
2823 #if 0
2824 static int pc_findindex(ListBase *listbase, int index)
2825 {
2826         LinkData *link= NULL;
2827         int number= 0;
2828         
2829         if (listbase == NULL) return -1;
2830         
2831         link= listbase->first;
2832         while (link) {
2833                 if ((int)link->data == index)
2834                         return number;
2835                 
2836                 number++;
2837                 link= link->next;
2838         }
2839         
2840         return -1;
2841 }
2842
2843 void object_delete_ptcache(Object *ob, int index) 
2844 {
2845         int list_index = pc_findindex(&ob->pc_ids, index);
2846         LinkData *link = BLI_findlink(&ob->pc_ids, list_index);
2847         BLI_freelinkN(&ob->pc_ids, link);
2848 }
2849 #endif
2850
2851 /* shape key utility function */
2852
2853 /************************* Mesh ************************/
2854 static KeyBlock *insert_meshkey(Scene *scene, Object *ob, char *name, int from_mix)
2855 {
2856         Mesh *me= ob->data;
2857         Key *key= me->key;
2858         KeyBlock *kb;
2859         int newkey= 0;
2860
2861         if(key == NULL) {
2862                 key= me->key= add_key((ID *)me);
2863                 key->type= KEY_RELATIVE;
2864                 newkey= 1;
2865         }
2866
2867         kb= add_keyblock(key, name);
2868
2869         if(newkey || from_mix==FALSE) {
2870                 /* create from mesh */
2871                 mesh_to_key(me, kb);
2872         }
2873         else {
2874                 /* copy from current values */
2875                 kb->data= do_ob_key(scene, ob);
2876                 kb->totelem= me->totvert;
2877         }
2878
2879         return kb;
2880 }
2881 /************************* Lattice ************************/
2882 static KeyBlock *insert_lattkey(Scene *scene, Object *ob, char *name, int from_mix)
2883 {
2884         Lattice *lt= ob->data;
2885         Key *key= lt->key;
2886         KeyBlock *kb;
2887         int newkey= 0;
2888
2889         if(key==NULL) {
2890                 key= lt->key= add_key( (ID *)lt);
2891                 key->type= KEY_RELATIVE;
2892                 newkey= 1;
2893         }
2894
2895         kb= add_keyblock(key, name);
2896
2897         if(newkey || from_mix==FALSE) {
2898                 /* create from lattice */
2899                 latt_to_key(lt, kb);
2900         }
2901         else {
2902                 /* copy from current values */
2903                 kb->totelem= lt->pntsu*lt->pntsv*lt->pntsw;
2904                 kb->data= do_ob_key(scene, ob);
2905         }
2906
2907         return kb;
2908 }
2909 /************************* Curve ************************/
2910 static KeyBlock *insert_curvekey(Scene *scene, Object *ob, char *name, int from_mix)
2911 {
2912         Curve *cu= ob->data;
2913         Key *key= cu->key;
2914         KeyBlock *kb;
2915         ListBase *lb= (cu->editnurb)? cu->editnurb: &cu->nurb;
2916         int newkey= 0;
2917
2918         if(key==NULL) {
2919                 key= cu->key= add_key( (ID *)cu);
2920                 key->type = KEY_RELATIVE;
2921                 newkey= 1;
2922         }
2923
2924         kb= add_keyblock(key, name);
2925
2926         if(newkey || from_mix==FALSE) {
2927                 /* create from curve */
2928                 curve_to_key(cu, kb, lb);
2929         }
2930         else {
2931                 /* copy from current values */
2932                 kb->totelem= count_curveverts(lb);
2933                 kb->data= do_ob_key(scene, ob);
2934         }
2935
2936         return kb;
2937 }
2938
2939 KeyBlock *object_insert_shape_key(Scene *scene, Object *ob, char *name, int from_mix)
2940 {
2941         if(ob->type==OB_MESH)                                    return insert_meshkey(scene, ob, name, from_mix);
2942         else if ELEM(ob->type, OB_CURVE, OB_SURF)return insert_curvekey(scene, ob, name, from_mix);
2943         else if(ob->type==OB_LATTICE)                    return insert_lattkey(scene, ob, name, from_mix);
2944         else                                                                     return NULL;
2945 }
2946