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