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