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