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