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