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