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