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