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