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