26ea17a296ad6cbedba9649809a3da8d886a8e37
[blender-staging.git] / source / blender / blenkernel / intern / depsgraph.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2004 Blender Foundation.
21  * All rights reserved.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27  
28 #include <stdio.h>
29 #include <string.h>
30 #include <math.h>
31
32 #ifdef _WIN32
33 #include "BLI_winstuff.h"
34 #endif
35
36 #include "BLI_blenlib.h"
37 #include "BLI_arithb.h"
38
39 #include "DNA_anim_types.h"
40 #include "DNA_action_types.h"
41 #include "DNA_armature_types.h"
42 #include "DNA_boid_types.h"
43 #include "DNA_curve_types.h"
44 #include "DNA_camera_types.h"
45 #include "DNA_ID.h"
46 #include "DNA_effect_types.h"
47 #include "DNA_group_types.h"
48 #include "DNA_lattice_types.h"
49 #include "DNA_lamp_types.h"
50 #include "DNA_key_types.h"
51 #include "DNA_mesh_types.h"
52 #include "DNA_modifier_types.h"
53 #include "DNA_nla_types.h"
54 #include "DNA_object_types.h"
55 #include "DNA_object_force.h"
56 #include "DNA_object_fluidsim.h"
57 #include "DNA_outliner_types.h"
58 #include "DNA_particle_types.h"
59 #include "DNA_scene_types.h"
60 #include "DNA_screen_types.h"
61 #include "DNA_space_types.h"
62 #include "DNA_view2d_types.h"
63 #include "DNA_view3d_types.h"
64 #include "DNA_windowmanager_types.h"
65
66 #include "BLI_ghash.h"
67
68 #include "BKE_action.h"
69 #include "BKE_effect.h"
70 #include "BKE_global.h"
71 #include "BKE_group.h"
72 #include "BKE_key.h"
73 #include "BKE_main.h"
74 #include "BKE_mball.h"
75 #include "BKE_modifier.h"
76 #include "BKE_object.h"
77 #include "BKE_particle.h"
78 #include "BKE_pointcache.h"
79 #include "BKE_utildefines.h"
80 #include "BKE_scene.h"
81 #include "BKE_screen.h"
82
83 #include "MEM_guardedalloc.h"
84
85 #ifndef DISABLE_PYTHON
86 #include "BPY_extern.h"
87 #endif
88
89  #include "depsgraph_private.h"
90  
91 /* Queue and stack operations for dag traversal 
92  *
93  * the queue store a list of freenodes to avoid successives alloc/dealloc
94  */
95
96 DagNodeQueue * queue_create (int slots) 
97 {
98         DagNodeQueue * queue;
99         DagNodeQueueElem * elem;
100         int i;
101         
102         queue = MEM_mallocN(sizeof(DagNodeQueue),"DAG queue");
103         queue->freenodes = MEM_mallocN(sizeof(DagNodeQueue),"DAG queue");
104         queue->count = 0;
105         queue->maxlevel = 0;
106         queue->first = queue->last = NULL;
107         elem = MEM_mallocN(sizeof(DagNodeQueueElem),"DAG queue elem3");
108         elem->node = NULL;
109         elem->next = NULL;
110         queue->freenodes->first = queue->freenodes->last = elem;
111         
112         for (i = 1; i <slots;i++) {
113                 elem = MEM_mallocN(sizeof(DagNodeQueueElem),"DAG queue elem4");
114                 elem->node = NULL;
115                 elem->next = NULL;
116                 queue->freenodes->last->next = elem;
117                 queue->freenodes->last = elem;
118         }
119         queue->freenodes->count = slots;
120         return queue;
121 }
122
123 void queue_raz(DagNodeQueue *queue)
124 {
125         DagNodeQueueElem * elem;
126         
127         elem = queue->first;
128         if (queue->freenodes->last)
129                 queue->freenodes->last->next = elem;
130         else
131                 queue->freenodes->first = queue->freenodes->last = elem;
132         
133         elem->node = NULL;
134         queue->freenodes->count++;
135         while (elem->next) {
136                 elem = elem->next;
137                 elem->node = NULL;
138                 queue->freenodes->count++;
139         }
140         queue->freenodes->last = elem;
141         queue->count = 0;
142 }
143
144 void queue_delete(DagNodeQueue *queue)
145 {
146         DagNodeQueueElem * elem;
147         DagNodeQueueElem * temp;
148         
149         elem = queue->first;
150         while (elem) {
151                 temp = elem;
152                 elem = elem->next;
153                 MEM_freeN(temp);
154         }
155         
156         elem = queue->freenodes->first;
157         while (elem) {
158                 temp = elem;
159                 elem = elem->next;
160                 MEM_freeN(temp);
161         }
162         
163         MEM_freeN(queue->freenodes);                    
164         MEM_freeN(queue);                       
165 }
166
167 /* insert in queue, remove in front */
168 void push_queue(DagNodeQueue *queue, DagNode *node)
169 {
170         DagNodeQueueElem * elem;
171         int i;
172
173         if (node == NULL) {
174                 fprintf(stderr,"pushing null node \n");
175                 return;
176         }
177         /*fprintf(stderr,"BFS push : %s %d\n",((ID *) node->ob)->name, queue->count);*/
178
179         elem = queue->freenodes->first;
180         if (elem != NULL) {
181                 queue->freenodes->first = elem->next;
182                 if ( queue->freenodes->last == elem) {
183                         queue->freenodes->last = NULL;
184                         queue->freenodes->first = NULL;
185                 }
186                 queue->freenodes->count--;
187         } else { /* alllocating more */         
188                 elem = MEM_mallocN(sizeof(DagNodeQueueElem),"DAG queue elem1");
189                 elem->node = NULL;
190                 elem->next = NULL;
191                 queue->freenodes->first = queue->freenodes->last = elem;
192
193                 for (i = 1; i <DAGQUEUEALLOC;i++) {
194                         elem = MEM_mallocN(sizeof(DagNodeQueueElem),"DAG queue elem2");
195                         elem->node = NULL;
196                         elem->next = NULL;
197                         queue->freenodes->last->next = elem;
198                         queue->freenodes->last = elem;
199                 }
200                 queue->freenodes->count = DAGQUEUEALLOC;
201                         
202                 elem = queue->freenodes->first; 
203                 queue->freenodes->first = elem->next;   
204         }
205         elem->next = NULL;
206         elem->node = node;
207         if (queue->last != NULL)
208                 queue->last->next = elem;
209         queue->last = elem;
210         if (queue->first == NULL) {
211                 queue->first = elem;
212         }
213         queue->count++;
214 }
215
216
217 /* insert in front, remove in front */
218 void push_stack(DagNodeQueue *queue, DagNode *node)
219 {
220         DagNodeQueueElem * elem;
221         int i;
222
223         elem = queue->freenodes->first; 
224         if (elem != NULL) {
225                 queue->freenodes->first = elem->next;
226                 if ( queue->freenodes->last == elem) {
227                         queue->freenodes->last = NULL;
228                         queue->freenodes->first = NULL;
229                 }
230                 queue->freenodes->count--;
231         } else { /* alllocating more */
232                 elem = MEM_mallocN(sizeof(DagNodeQueueElem),"DAG queue elem1");
233                 elem->node = NULL;
234                 elem->next = NULL;
235                 queue->freenodes->first = queue->freenodes->last = elem;
236
237                 for (i = 1; i <DAGQUEUEALLOC;i++) {
238                         elem = MEM_mallocN(sizeof(DagNodeQueueElem),"DAG queue elem2");
239                         elem->node = NULL;
240                         elem->next = NULL;
241                         queue->freenodes->last->next = elem;
242                         queue->freenodes->last = elem;
243                 }
244                 queue->freenodes->count = DAGQUEUEALLOC;
245                         
246                 elem = queue->freenodes->first; 
247                 queue->freenodes->first = elem->next;   
248         }
249         elem->next = queue->first;
250         elem->node = node;
251         queue->first = elem;
252         if (queue->last == NULL)
253                 queue->last = elem;
254         queue->count++;
255 }
256
257
258 DagNode * pop_queue(DagNodeQueue *queue)
259 {
260         DagNodeQueueElem * elem;
261         DagNode *node;
262
263         elem = queue->first;
264         if (elem) {
265                 queue->first = elem->next;
266                 if (queue->last == elem) {
267                         queue->last=NULL;
268                         queue->first=NULL;
269                 }
270                 queue->count--;
271                 if (queue->freenodes->last)
272                         queue->freenodes->last->next=elem;
273                 queue->freenodes->last=elem;
274                 if (queue->freenodes->first == NULL)
275                         queue->freenodes->first=elem;
276                 node = elem->node;
277                 elem->node = NULL;
278                 elem->next = NULL;
279                 queue->freenodes->count++;
280                 return node;
281         } else {
282                 fprintf(stderr,"return null \n");
283                 return NULL;
284         }
285 }
286
287 void    *pop_ob_queue(struct DagNodeQueue *queue) {
288         return(pop_queue(queue)->ob);
289 }
290
291 DagNode * get_top_node_queue(DagNodeQueue *queue) 
292 {
293         return queue->first->node;
294 }
295
296 int             queue_count(struct DagNodeQueue *queue){
297         return queue->count;
298 }
299
300
301 DagForest * dag_init()
302 {
303         DagForest *forest;
304         /* use callocN to init all zero */
305         forest = MEM_callocN(sizeof(DagForest),"DAG root");
306         return forest;
307 }
308
309 /* isdata = object data... */
310 // XXX this needs to be extended to be more flexible (so that not only objects are evaluated via depsgraph)...
311 static void dag_add_driver_relation(AnimData *adt, DagForest *dag, DagNode *node, int isdata)
312 {
313         FCurve *fcu;
314         DagNode *node1;
315         
316         for (fcu= adt->drivers.first; fcu; fcu= fcu->next) {
317                 ChannelDriver *driver= fcu->driver;
318                 DriverTarget *dtar;
319                 
320                 /* loop over targets, adding relationships as appropriate */
321                 for (dtar= driver->targets.first; dtar; dtar= dtar->next) {
322                         if (dtar->id) {
323                                 if (GS(dtar->id->name)==ID_OB) {
324                                         Object *ob= (Object *)dtar->id;
325                                         
326                                         /* normal channel-drives-channel */
327                                         node1 = dag_get_node(dag, dtar->id);
328                                         
329                                         /* check if bone... */
330                                         if ((ob->type==OB_ARMATURE) && dtar->rna_path && strstr(dtar->rna_path, "pose.pose_channels["))
331                                                 dag_add_relation(dag, node1, node, isdata?DAG_RL_DATA_DATA:DAG_RL_DATA_OB, "Driver");
332                                         /* check if ob data */
333                                         else if (dtar->rna_path && strstr(dtar->rna_path, "data."))
334                                                 dag_add_relation(dag, node1, node, isdata?DAG_RL_DATA_DATA:DAG_RL_DATA_OB, "Driver");
335                                         /* normal */
336                                         else
337                                                 dag_add_relation(dag, node1, node, isdata?DAG_RL_OB_DATA:DAG_RL_OB_OB, "Driver");
338                                 }
339                         }
340                 }
341         }
342 }
343
344 static void dag_add_collision_field_relation(DagForest *dag, Scene *scene, Object *ob, DagNode *node)
345 {
346         Base *base;
347         DagNode *node2;
348
349         // would be nice to have a list of colliders here
350         // so for now walk all objects in scene check 'same layer rule'
351         for(base = scene->base.first; base; base= base->next) {
352                 if((base->lay & ob->lay) && base->object->pd) {
353                         Object *ob1= base->object;
354                         if((ob1->pd->deflect || ob1->pd->forcefield) && (ob1 != ob))  {
355                                 node2 = dag_get_node(dag, ob1);                                 
356                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Field Collision");
357                         }
358                 }
359         }
360 }
361
362 static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, Object *ob, int mask)
363 {
364         bConstraint *con;
365         DagNode * node;
366         DagNode * node2;
367         DagNode * node3;
368         Key *key;
369         ParticleSystem *psys;
370         int addtoroot= 1;
371         
372         node = dag_get_node(dag, ob);
373         
374         if ((ob->data) && (mask&DAG_RL_DATA)) {
375                 node2 = dag_get_node(dag,ob->data);
376                 dag_add_relation(dag,node,node2,DAG_RL_DATA, "Object-Data Relation");
377                 node2->first_ancestor = ob;
378                 node2->ancestor_count += 1;
379         }
380         
381         if (ob->type == OB_ARMATURE) {
382                 if (ob->pose){
383                         bPoseChannel *pchan;
384                         bConstraint *con;
385                         
386                         for (pchan = ob->pose->chanbase.first; pchan; pchan=pchan->next) {
387                                 for (con = pchan->constraints.first; con; con=con->next) {
388                                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
389                                         ListBase targets = {NULL, NULL};
390                                         bConstraintTarget *ct;
391                                         
392                                         if (cti && cti->get_constraint_targets) {
393                                                 cti->get_constraint_targets(con, &targets);
394                                                 
395                                                 for (ct= targets.first; ct; ct= ct->next) {
396                                                         if (ct->tar && ct->tar != ob) {
397                                                                 // fprintf(stderr,"armature %s target :%s \n", ob->id.name, target->id.name);
398                                                                 node3 = dag_get_node(dag, ct->tar);
399                                                                 
400                                                                 if (ct->subtarget[0])
401                                                                         dag_add_relation(dag,node3,node, DAG_RL_OB_DATA|DAG_RL_DATA_DATA, cti->name);
402                                                                 else if(ELEM(con->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO))   
403                                                                         dag_add_relation(dag,node3,node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA, cti->name);
404                                                                 else
405                                                                         dag_add_relation(dag,node3,node, DAG_RL_OB_DATA, cti->name);
406                                                         }
407                                                 }
408                                                 
409                                                 if (cti->flush_constraint_targets)
410                                                         cti->flush_constraint_targets(con, &targets, 1);
411                                         }
412                                         
413                                 }
414                         }
415                 }
416         }
417         
418         /* driver dependencies, nla modifiers */
419 #if 0 // XXX old animation system
420         if(ob->nlastrips.first) {
421                 bActionStrip *strip;
422                 bActionChannel *chan;
423                 for(strip= ob->nlastrips.first; strip; strip= strip->next) {
424                         if(strip->modifiers.first) {
425                                 bActionModifier *amod;
426                                 for(amod= strip->modifiers.first; amod; amod= amod->next) {
427                                         if(amod->ob) {
428                                                 node2 = dag_get_node(dag, amod->ob);
429                                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "NLA Strip Modifier");
430                                         }
431                                 }
432                         }
433                 }
434         }
435 #endif // XXX old animation system
436         if (ob->adt)
437                 dag_add_driver_relation(ob->adt, dag, node, (ob->type == OB_ARMATURE)); // XXX isdata arg here doesn't give an accurate picture of situation
438                 
439         key= ob_get_key(ob);
440         if (key && key->adt)
441                 dag_add_driver_relation(key->adt, dag, node, 1);
442
443         if (ob->modifiers.first) {
444                 ModifierData *md;
445                 
446                 for(md=ob->modifiers.first; md; md=md->next) {
447                         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
448                         
449                         if (mti->updateDepgraph) mti->updateDepgraph(md, dag, scene, ob, node);
450                 }
451         }
452         if (ob->parent) {
453                 node2 = dag_get_node(dag,ob->parent);
454                 
455                 switch(ob->partype) {
456                         case PARSKEL:
457                                 dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_OB, "Parent");
458                                 break;
459                         case PARVERT1: case PARVERT3: case PARBONE:
460                                 dag_add_relation(dag,node2,node,DAG_RL_DATA_OB|DAG_RL_OB_OB, "Vertex Parent");
461                                 break;
462                         default:
463                                 if(ob->parent->type==OB_LATTICE) 
464                                         dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_OB, "Lattice Parent");
465                                 else if(ob->parent->type==OB_CURVE) {
466                                         Curve *cu= ob->parent->data;
467                                         if(cu->flag & CU_PATH) 
468                                                 dag_add_relation(dag,node2,node,DAG_RL_DATA_OB|DAG_RL_OB_OB, "Curve Parent");
469                                         else
470                                                 dag_add_relation(dag,node2,node,DAG_RL_OB_OB, "Curve Parent");
471                                 }
472                                 else
473                                         dag_add_relation(dag,node2,node,DAG_RL_OB_OB, "Parent");
474                 }
475                 /* exception case: parent is duplivert */
476                 if(ob->type==OB_MBALL && (ob->parent->transflag & OB_DUPLIVERTS)) {
477                         dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_OB, "Duplivert");
478                 }
479                 
480                 addtoroot = 0;
481         }
482         if (ob->track) {
483                 node2 = dag_get_node(dag,ob->track);
484                 dag_add_relation(dag,node2,node,DAG_RL_OB_OB, "Track To");
485                 addtoroot = 0;
486         }
487         if (ob->proxy) {
488                 node2 = dag_get_node(dag, ob->proxy);
489                 dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA|DAG_RL_OB_OB, "Proxy");
490                 /* inverted relation, so addtoroot shouldn't be set to zero */
491         }
492         
493
494         if (ob->type==OB_CAMERA) {
495                 Camera *cam = (Camera *)ob->data;
496                 if (cam->adt)
497                         dag_add_driver_relation(cam->adt, dag, node, 1);
498                 if (cam->dof_ob) {
499                         node2 = dag_get_node(dag, cam->dof_ob);
500                         dag_add_relation(dag,node2,node,DAG_RL_OB_OB, "Camera DoF");
501                 }
502         }
503         if (ob->type==OB_LAMP) {
504                 Lamp *la = (Lamp *)ob->data;
505                 if (la->adt)
506                         dag_add_driver_relation(la->adt, dag, node, 1);
507         }
508         
509         if (ob->transflag & OB_DUPLI) {
510                 if((ob->transflag & OB_DUPLIGROUP) && ob->dup_group) {
511                         GroupObject *go;
512                         for(go= ob->dup_group->gobject.first; go; go= go->next) {
513                                 if(go->ob) {
514                                         node2 = dag_get_node(dag, go->ob);
515                                         /* node2 changes node1, this keeps animations updated in groups?? not logical? */
516                                         dag_add_relation(dag, node2, node, DAG_RL_OB_OB, "Dupligroup");
517                                 }
518                         }
519                 }
520         }
521     
522         /* softbody collision  */
523         if((ob->type==OB_MESH) || (ob->type==OB_CURVE) || (ob->type==OB_LATTICE))
524                 if(modifiers_isSoftbodyEnabled(ob) || modifiers_isClothEnabled(ob) || ob->particlesystem.first)
525                         dag_add_collision_field_relation(dag, scene, ob, node); /* TODO: use effectorweight->group */
526                 
527         if (ob->type==OB_MBALL) {
528                 Object *mom= find_basis_mball(scene, ob);
529                 if(mom!=ob) {
530                         node2 = dag_get_node(dag, mom);
531                         dag_add_relation(dag,node,node2,DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Metaball");  // mom depends on children!
532                 }
533         }
534         else if (ob->type==OB_CURVE) {
535                 Curve *cu= ob->data;
536                 if(cu->bevobj) {
537                         node2 = dag_get_node(dag, cu->bevobj);
538                         dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Curve Bevel");
539                 }
540                 if(cu->taperobj) {
541                         node2 = dag_get_node(dag, cu->taperobj);
542                         dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Curve Taper");
543                 }
544                 if (cu->adt)
545                         dag_add_driver_relation(cu->adt, dag, node, 1);
546         }
547         else if(ob->type==OB_FONT) {
548                 Curve *cu= ob->data;
549                 if(cu->textoncurve) {
550                         node2 = dag_get_node(dag, cu->textoncurve);
551                         dag_add_relation(dag,node2,node,DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Texture On Curve");
552                 }
553         }
554         
555         psys= ob->particlesystem.first;
556         if(psys) {
557                 GroupObject *go;
558
559                 for(; psys; psys=psys->next) {
560                         BoidRule *rule = NULL;
561                         BoidState *state = NULL;
562                         ParticleSettings *part= psys->part;
563                         ListBase *effectors = NULL;
564                         EffectorCache *eff;
565
566                         dag_add_relation(dag, node, node, DAG_RL_OB_DATA, "Particle-Object Relation");
567
568                         if(!psys_check_enabled(ob, psys))
569                                 continue;
570
571                         if(ELEM(part->phystype,PART_PHYS_KEYED,PART_PHYS_BOIDS)) {
572                                 ParticleTarget *pt = psys->targets.first;
573
574                                 for(; pt; pt=pt->next) {
575                                         if(pt->ob && BLI_findlink(&pt->ob->particlesystem, pt->psys-1)) {
576                                                 node2 = dag_get_node(dag, pt->ob);
577                                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Particle Targets");
578                                         }
579                            }
580                         }
581
582                         if(part->ren_as == PART_DRAW_OB && part->dup_ob) {
583                                 node2 = dag_get_node(dag, part->dup_ob);
584                                 dag_add_relation(dag, node, node2, DAG_RL_OB_OB, "Particle Object Visualisation");
585                                 if(part->dup_ob->type == OB_MBALL)
586                                         dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA, "Particle Object Visualisation");
587                         }
588
589                         if(part->ren_as == PART_DRAW_GR && part->dup_group) {
590                                 for(go=part->dup_group->gobject.first; go; go=go->next) {
591                                         node2 = dag_get_node(dag, go->ob);
592                                         dag_add_relation(dag, node, node2, DAG_RL_OB_OB, "Particle Group Visualisation");
593                                 }
594                         }
595
596                         effectors = pdInitEffectors(scene, ob, psys, part->effector_weights);
597
598                         if(effectors) for(eff = effectors->first; eff; eff=eff->next) {
599                                 if(eff->psys) {
600                                         node2 = dag_get_node(dag, eff->ob);
601                                         dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA|DAG_RL_OB_DATA, "Particle Field");
602                                 }
603                         }
604
605                         pdEndEffectors(&effectors);
606
607                         if(part->boids) {
608                                 for(state = part->boids->states.first; state; state=state->next) {
609                                         for(rule = state->rules.first; rule; rule=rule->next) {
610                                                 Object *ruleob = NULL;
611                                                 if(rule->type==eBoidRuleType_Avoid)
612                                                         ruleob = ((BoidRuleGoalAvoid*)rule)->ob;
613                                                 else if(rule->type==eBoidRuleType_FollowLeader)
614                                                         ruleob = ((BoidRuleFollowLeader*)rule)->ob;
615
616                                                 if(ruleob) {
617                                                         node2 = dag_get_node(dag, ruleob);
618                                                         dag_add_relation(dag, node2, node, DAG_RL_OB_DATA, "Boid Rule");
619                                                 }
620                                         }
621                                 }
622                         }
623                 }
624         }
625         
626         for (con = ob->constraints.first; con; con=con->next) {
627                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
628                 ListBase targets = {NULL, NULL};
629                 bConstraintTarget *ct;
630                 
631                 if (cti && cti->get_constraint_targets) {
632                         cti->get_constraint_targets(con, &targets);
633                         
634                         for (ct= targets.first; ct; ct= ct->next) {
635                                 Object *obt;
636                                 
637                                 if (ct->tar)
638                                         obt= ct->tar;
639                                 else
640                                         continue;
641                                 
642                                 node2 = dag_get_node(dag, obt);
643                                 if (ELEM(con->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO))
644                                         dag_add_relation(dag, node2, node, DAG_RL_DATA_OB|DAG_RL_OB_OB, cti->name);
645                                 else {
646                                         if (ELEM3(obt->type, OB_ARMATURE, OB_MESH, OB_LATTICE) && (ct->subtarget[0]))
647                                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_OB|DAG_RL_OB_OB, cti->name);
648                                         else
649                                                 dag_add_relation(dag, node2, node, DAG_RL_OB_OB, cti->name);
650                                 }
651                                 addtoroot = 0;
652                         }
653                         
654                         if (cti->flush_constraint_targets)
655                                 cti->flush_constraint_targets(con, &targets, 1);
656                 }
657         }
658
659         if (addtoroot == 1 )
660                 dag_add_relation(dag,scenenode,node,DAG_RL_SCENE, "Scene Relation");
661 }
662
663 struct DagForest *build_dag(struct Scene *sce, short mask) 
664 {
665         Base *base;
666         Object *ob;
667         Group *group;
668         GroupObject *go;
669         DagNode *node;
670         DagNode *scenenode;
671         DagForest *dag;
672         DagAdjList *itA;
673
674         dag = sce->theDag;
675         sce->dagisvalid=1;
676         if ( dag)
677                 free_forest( dag ); 
678         else {
679                 dag = dag_init();
680                 sce->theDag = dag;
681         }
682         
683         /* add base node for scene. scene is always the first node in DAG */
684         scenenode = dag_add_node(dag, sce);     
685         
686         /* add current scene objects */
687         for(base = sce->base.first; base; base= base->next) {
688                 ob= base->object;
689                 
690                 build_dag_object(dag, scenenode, sce, ob, mask);
691                 if(ob->proxy)
692                         build_dag_object(dag, scenenode, sce, ob->proxy, mask);
693                 
694                 /* handled in next loop */
695                 if(ob->dup_group) 
696                         ob->dup_group->id.flag |= LIB_DOIT;
697         }
698         
699         /* add groups used in current scene objects */
700         for(group= G.main->group.first; group; group= group->id.next) {
701                 if(group->id.flag & LIB_DOIT) {
702                         for(go= group->gobject.first; go; go= go->next) {
703                                 build_dag_object(dag, scenenode, sce, go->ob, mask);
704                         }
705                         group->id.flag &= ~LIB_DOIT;
706                 }
707         }
708         
709         /* Now all relations were built, but we need to solve 1 exceptional case;
710            When objects have multiple "parents" (for example parent + constraint working on same object)
711            the relation type has to be synced. One of the parents can change, and should give same event to child */
712         
713         /* nodes were callocced, so we can use node->color for temporal storage */
714         for(node = sce->theDag->DagNode.first; node; node= node->next) {
715                 if(node->type==ID_OB) {
716                         for(itA = node->child; itA; itA= itA->next) {
717                                 if(itA->node->type==ID_OB) {
718                                         itA->node->color |= itA->type;
719                                 }
720                         }
721                 }
722         }
723         /* now set relations equal, so that when only one parent changes, the correct recalcs are found */
724         for(node = sce->theDag->DagNode.first; node; node= node->next) {
725                 if(node->type==ID_OB) {
726                         for(itA = node->child; itA; itA= itA->next) {
727                                 if(itA->node->type==ID_OB) {
728                                         itA->type |= itA->node->color;
729                                 }
730                         }
731                 }
732         }
733         
734         // cycle detection and solving
735         // solve_cycles(dag);   
736         
737         return dag;
738 }
739
740
741 void free_forest(DagForest *Dag) 
742 {  /* remove all nodes and deps */
743         DagNode *tempN;
744         DagAdjList *tempA;      
745         DagAdjList *itA;
746         DagNode *itN = Dag->DagNode.first;
747         
748         while (itN) {
749                 itA = itN->child;       
750                 while (itA) {
751                         tempA = itA;
752                         itA = itA->next;
753                         MEM_freeN(tempA);                       
754                 }
755                 
756                 itA = itN->parent;      
757                 while (itA) {
758                         tempA = itA;
759                         itA = itA->next;
760                         MEM_freeN(tempA);                       
761                 }
762                 
763                 tempN = itN;
764                 itN = itN->next;
765                 MEM_freeN(tempN);
766         }
767
768         BLI_ghash_free(Dag->nodeHash, NULL, NULL);
769         Dag->nodeHash= NULL;
770         Dag->DagNode.first = NULL;
771         Dag->DagNode.last = NULL;
772         Dag->numNodes = 0;
773
774 }
775
776 DagNode * dag_find_node (DagForest *forest,void * fob)
777 {
778         if(forest->nodeHash)
779                 return BLI_ghash_lookup(forest->nodeHash, fob);
780
781         return NULL;
782 }
783
784 static int ugly_hack_sorry= 1;  // prevent type check
785
786 /* no checking of existance, use dag_find_node first or dag_get_node */
787 DagNode * dag_add_node (DagForest *forest, void * fob)
788 {
789         DagNode *node;
790                 
791         node = MEM_callocN(sizeof(DagNode),"DAG node");
792         if (node) {
793                 node->ob = fob;
794                 node->color = DAG_WHITE;
795
796                 if(ugly_hack_sorry) node->type = GS(((ID *) fob)->name);        // sorry, done for pose sorting
797                 if (forest->numNodes) {
798                         ((DagNode *) forest->DagNode.last)->next = node;
799                         forest->DagNode.last = node;
800                         forest->numNodes++;
801                 } else {
802                         forest->DagNode.last = node;
803                         forest->DagNode.first = node;
804                         forest->numNodes = 1;
805                 }
806
807                 if(!forest->nodeHash)
808                         forest->nodeHash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp);
809                 BLI_ghash_insert(forest->nodeHash, fob, node);
810         }
811
812         return node;
813 }
814
815 DagNode * dag_get_node (DagForest *forest,void * fob)
816 {
817         DagNode *node;
818         
819         node = dag_find_node (forest, fob);     
820         if (!node) 
821                 node = dag_add_node(forest, fob);
822         return node;
823 }
824
825
826
827 DagNode * dag_get_sub_node (DagForest *forest,void * fob)
828 {
829         DagNode *node;
830         DagAdjList *mainchild, *prev=NULL;
831         
832         mainchild = ((DagNode *) forest->DagNode.first)->child;
833         /* remove from first node (scene) adj list if present */
834         while (mainchild) {
835                 if (mainchild->node == fob) {
836                         if (prev) {
837                                 prev->next = mainchild->next;
838                                 MEM_freeN(mainchild);
839                                 break;
840                         } else {
841                                 ((DagNode *) forest->DagNode.first)->child = mainchild->next;
842                                 MEM_freeN(mainchild);
843                                 break;
844                         }
845                 }
846                 prev = mainchild;
847                 mainchild = mainchild->next;
848         }
849         node = dag_find_node (forest, fob);     
850         if (!node) 
851                 node = dag_add_node(forest, fob);
852         return node;
853 }
854
855 static void dag_add_parent_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel, char *name) 
856 {
857         DagAdjList *itA = fob2->parent;
858         
859         while (itA) { /* search if relation exist already */
860                 if (itA->node == fob1) {
861                         itA->type |= rel;
862                         itA->count += 1;
863                         return;
864                 }
865                 itA = itA->next;
866         }
867         /* create new relation and insert at head. MALLOC alert! */
868         itA = MEM_mallocN(sizeof(DagAdjList),"DAG adj list");
869         itA->node = fob1;
870         itA->type = rel;
871         itA->count = 1;
872         itA->next = fob2->parent;
873         itA->name = name;
874         fob2->parent = itA;
875 }
876
877 void dag_add_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel, char *name) 
878 {
879         DagAdjList *itA = fob1->child;
880         
881         /* parent relation is for cycle checking */
882         dag_add_parent_relation(forest, fob1, fob2, rel, name);
883
884         while (itA) { /* search if relation exist already */
885                 if (itA->node == fob2) {
886                         itA->type |= rel;
887                         itA->count += 1;
888                         return;
889                 }
890                 itA = itA->next;
891         }
892         /* create new relation and insert at head. MALLOC alert! */
893         itA = MEM_mallocN(sizeof(DagAdjList),"DAG adj list");
894         itA->node = fob2;
895         itA->type = rel;
896         itA->count = 1;
897         itA->next = fob1->child;
898         itA->name = name;
899         fob1->child = itA;
900 }
901
902 static char *dag_node_name(DagNode *node)
903 {
904         if(node->ob == NULL)
905                 return "null";
906         else if(ugly_hack_sorry)
907                 return ((ID*)(node->ob))->name+2;
908         else
909                 return ((bPoseChannel*)(node->ob))->name;
910 }
911
912 #if 0
913 static void dag_node_print_dependencies(DagNode *node)
914 {
915         DagAdjList *itA;
916
917         printf("%s depends on:\n", dag_node_name(node));
918
919         for(itA= node->parent; itA; itA= itA->next)
920                 printf("  %s through %s\n", dag_node_name(itA->node), itA->name);
921         printf("\n");
922 }
923 #endif
924
925 static int dag_node_print_dependency_recurs(DagNode *node, DagNode *endnode)
926 {
927         DagAdjList *itA;
928
929         if(node->color == DAG_BLACK)
930                 return 0;
931
932         node->color= DAG_BLACK;
933
934         if(node == endnode)
935                 return 1;
936
937         for(itA= node->parent; itA; itA= itA->next) {
938                 if(dag_node_print_dependency_recurs(itA->node, endnode)) {
939                         printf("  %s depends on %s through %s.\n", dag_node_name(node), dag_node_name(itA->node), itA->name);
940                         return 1;
941                 }
942         }
943
944         return 0;
945 }
946
947 static void dag_node_print_dependency_cycle(DagForest *dag, DagNode *startnode, DagNode *endnode, char *name)
948 {
949         DagNode *node;
950
951     for(node = dag->DagNode.first; node; node= node->next)
952                 node->color= DAG_WHITE;
953
954         printf("  %s depends on %s through %s.\n", dag_node_name(endnode), dag_node_name(startnode), name);
955         dag_node_print_dependency_recurs(startnode, endnode);
956         printf("\n");
957 }
958
959 static int dag_node_recurs_level(DagNode *node, int level)
960 {
961         DagAdjList *itA;
962         int newlevel;
963
964         node->color= DAG_BLACK; /* done */
965         newlevel= ++level;
966         
967         for(itA= node->parent; itA; itA= itA->next) {
968                 if(itA->node->color==DAG_WHITE) {
969                         itA->node->ancestor_count= dag_node_recurs_level(itA->node, level);
970                         newlevel= MAX2(newlevel, level+itA->node->ancestor_count);
971                 }
972                 else
973                         newlevel= MAX2(newlevel, level+itA->node->ancestor_count);
974         }
975         
976         return newlevel;
977 }
978
979 static void dag_check_cycle(DagForest *dag)
980 {
981         DagNode *node;
982         DagAdjList *itA;
983
984         /* tag nodes unchecked */
985         for(node = dag->DagNode.first; node; node= node->next)
986                 node->color= DAG_WHITE;
987         
988         for(node = dag->DagNode.first; node; node= node->next) {
989                 if(node->color==DAG_WHITE) {
990                         node->ancestor_count= dag_node_recurs_level(node, 0);
991                 }
992         }
993         
994         /* check relations, and print errors */
995         for(node = dag->DagNode.first; node; node= node->next) {
996                 for(itA= node->parent; itA; itA= itA->next) {
997                         if(itA->node->ancestor_count > node->ancestor_count) {
998                                 if(node->ob && itA->node->ob) {
999                                         printf("Dependency cycle detected:\n");
1000                                         dag_node_print_dependency_cycle(dag, itA->node, node, itA->name);
1001                                 }
1002                         }
1003                 }
1004         }
1005
1006         /* parent relations are only needed for cycle checking, so free now */
1007         for(node = dag->DagNode.first; node; node= node->next) {
1008                 while (node->parent) {
1009                         itA = node->parent->next;
1010                         MEM_freeN(node->parent);                        
1011                         node->parent = itA;
1012                 }
1013         }
1014 }
1015
1016 /*
1017  * MainDAG is the DAG of all objects in current scene
1018  * used only for drawing there is one also in each scene
1019  */
1020 static DagForest * MainDag = NULL;
1021
1022 DagForest *getMainDag(void)
1023 {
1024         return MainDag;
1025 }
1026
1027
1028 void setMainDag(DagForest *dag)
1029 {
1030         MainDag = dag;
1031 }
1032
1033
1034 /*
1035  * note for BFS/DFS
1036  * in theory we should sweep the whole array
1037  * but in our case the first node is the scene
1038  * and is linked to every other object
1039  *
1040  * for general case we will need to add outer loop
1041  */
1042
1043 /*
1044  * ToDo : change pos kludge
1045  */
1046
1047 /* adjust levels for drawing in oops space */
1048 void graph_bfs(void)
1049 {
1050         DagNode *node;
1051         DagNodeQueue *nqueue;
1052         int pos[50];
1053         int i;
1054         DagAdjList *itA;
1055         int minheight;
1056         
1057         /* fprintf(stderr,"starting BFS \n ------------\n"); */ 
1058         nqueue = queue_create(DAGQUEUEALLOC);
1059         for ( i=0; i<50; i++)
1060                 pos[i] = 0;
1061         
1062         /* Init
1063          * dagnode.first is alway the root (scene) 
1064          */
1065         node = MainDag->DagNode.first;
1066         while(node) {
1067                 node->color = DAG_WHITE;
1068                 node->BFS_dist = 9999;
1069                 node->k = 0;
1070                 node = node->next;
1071         }
1072         
1073         node = MainDag->DagNode.first;
1074         if (node->color == DAG_WHITE) {
1075                 node->color = DAG_GRAY;
1076                 node->BFS_dist = 1;
1077                 push_queue(nqueue,node);  
1078                 while(nqueue->count) {
1079                         node = pop_queue(nqueue);
1080                         
1081                         minheight = pos[node->BFS_dist];
1082                         itA = node->child;
1083                         while(itA != NULL) {
1084                                 if((itA->node->color == DAG_WHITE) ) {
1085                                         itA->node->color = DAG_GRAY;
1086                                         itA->node->BFS_dist = node->BFS_dist + 1;
1087                                         itA->node->k = (float) minheight;
1088                                         push_queue(nqueue,itA->node);
1089                                 }
1090                                 
1091                                  else {
1092                                         fprintf(stderr,"bfs not dag tree edge color :%i \n",itA->node->color);
1093                                 }
1094                                  
1095                                 
1096                                 itA = itA->next;
1097                         }
1098                         if (pos[node->BFS_dist] > node->k ) {
1099                                 pos[node->BFS_dist] += 1;                               
1100                                 node->k = (float) pos[node->BFS_dist];
1101                         } else {
1102                                 pos[node->BFS_dist] = (int) node->k +1;
1103                         }
1104                         set_node_xy(node, node->BFS_dist*DEPSX*2, pos[node->BFS_dist]*DEPSY*2);
1105                         node->color = DAG_BLACK;
1106                         /*
1107                          fprintf(stderr,"BFS node : %20s %i %5.0f %5.0f\n",((ID *) node->ob)->name,node->BFS_dist, node->x, node->y);   
1108                          */
1109                 }
1110         }
1111         queue_delete(nqueue);
1112 }
1113
1114 int pre_and_post_BFS(DagForest *dag, short mask, graph_action_func pre_func, graph_action_func post_func, void **data) {
1115         DagNode *node;
1116         
1117         node = dag->DagNode.first;
1118         return pre_and_post_source_BFS(dag, mask,  node,  pre_func,  post_func, data);
1119 }
1120
1121
1122 int pre_and_post_source_BFS(DagForest *dag, short mask, DagNode *source, graph_action_func pre_func, graph_action_func post_func, void **data)
1123 {
1124         DagNode *node;
1125         DagNodeQueue *nqueue;
1126         DagAdjList *itA;
1127         int     retval = 0;
1128         /* fprintf(stderr,"starting BFS \n ------------\n"); */ 
1129         
1130         /* Init
1131                 * dagnode.first is alway the root (scene) 
1132                 */
1133         node = dag->DagNode.first;
1134         nqueue = queue_create(DAGQUEUEALLOC);
1135         while(node) {
1136                 node->color = DAG_WHITE;
1137                 node->BFS_dist = 9999;
1138                 node = node->next;
1139         }
1140         
1141         node = source;
1142         if (node->color == DAG_WHITE) {
1143                 node->color = DAG_GRAY;
1144                 node->BFS_dist = 1;
1145                 pre_func(node->ob,data);
1146                 
1147                 while(nqueue->count) {
1148                         node = pop_queue(nqueue);
1149                         
1150                         itA = node->child;
1151                         while(itA != NULL) {
1152                                 if((itA->node->color == DAG_WHITE) && (itA->type & mask)) {
1153                                         itA->node->color = DAG_GRAY;
1154                                         itA->node->BFS_dist = node->BFS_dist + 1;
1155                                         push_queue(nqueue,itA->node);
1156                                         pre_func(node->ob,data);
1157                                 }
1158                                 
1159                                 else { // back or cross edge
1160                                         retval = 1;
1161                                 }
1162                                 itA = itA->next;
1163                         }
1164                         post_func(node->ob,data);
1165                         node->color = DAG_BLACK;
1166                         /*
1167                          fprintf(stderr,"BFS node : %20s %i %5.0f %5.0f\n",((ID *) node->ob)->name,node->BFS_dist, node->x, node->y);   
1168                          */
1169                 }
1170         }
1171         queue_delete(nqueue);
1172         return retval;
1173 }
1174
1175 /* non recursive version of DFS, return queue -- outer loop present to catch odd cases (first level cycles)*/
1176 DagNodeQueue * graph_dfs(void)
1177 {
1178         DagNode *node;
1179         DagNodeQueue *nqueue;
1180         DagNodeQueue *retqueue;
1181         int pos[50];
1182         int i;
1183         DagAdjList *itA;
1184         int time;
1185         int skip = 0;
1186         int minheight;
1187         int maxpos=0;
1188         int     is_cycle = 0;
1189         /*
1190          *fprintf(stderr,"starting DFS \n ------------\n");
1191          */     
1192         nqueue = queue_create(DAGQUEUEALLOC);
1193         retqueue = queue_create(MainDag->numNodes);
1194         for ( i=0; i<50; i++)
1195                 pos[i] = 0;
1196         
1197         /* Init
1198          * dagnode.first is alway the root (scene) 
1199          */
1200         node = MainDag->DagNode.first;
1201         while(node) {
1202                 node->color = DAG_WHITE;
1203                 node->DFS_dist = 9999;
1204                 node->DFS_dvtm = node->DFS_fntm = 9999;
1205                 node->k = 0;
1206                 node =  node->next;
1207         }
1208         
1209         time = 1;
1210         
1211         node = MainDag->DagNode.first;
1212
1213         do {
1214         if (node->color == DAG_WHITE) {
1215                 node->color = DAG_GRAY;
1216                 node->DFS_dist = 1;
1217                 node->DFS_dvtm = time;
1218                 time++;
1219                 push_stack(nqueue,node);  
1220                         
1221                 while(nqueue->count) {
1222                         //graph_print_queue(nqueue);
1223
1224                          skip = 0;
1225                         node = get_top_node_queue(nqueue);
1226                         
1227                         minheight = pos[node->DFS_dist];
1228
1229                         itA = node->child;
1230                         while(itA != NULL) {
1231                                 if((itA->node->color == DAG_WHITE) ) {
1232                                         itA->node->DFS_dvtm = time;
1233                                         itA->node->color = DAG_GRAY;
1234
1235                                         time++;
1236                                         itA->node->DFS_dist = node->DFS_dist + 1;
1237                                         itA->node->k = (float) minheight;
1238                                         push_stack(nqueue,itA->node);
1239                                         skip = 1;
1240                                         break;
1241                                 } else { 
1242                                         if (itA->node->color == DAG_GRAY) { // back edge
1243                                                 fprintf(stderr,"dfs back edge :%15s %15s \n",((ID *) node->ob)->name, ((ID *) itA->node->ob)->name);
1244                                                 is_cycle = 1;
1245                                         } else if (itA->node->color == DAG_BLACK) {
1246                                                 ;
1247                                                 /* already processed node but we may want later to change distance either to shorter to longer.
1248                                                  * DFS_dist is the first encounter  
1249                                                 */
1250                                                 /*if (node->DFS_dist >= itA->node->DFS_dist)
1251                                                         itA->node->DFS_dist = node->DFS_dist + 1;
1252                                                         
1253                                                         fprintf(stderr,"dfs forward or cross edge :%15s %i-%i %15s %i-%i \n",
1254                                                                 ((ID *) node->ob)->name,
1255                                                                 node->DFS_dvtm, 
1256                                                                 node->DFS_fntm, 
1257                                                                 ((ID *) itA->node->ob)->name, 
1258                                                                 itA->node->DFS_dvtm,
1259                                                                 itA->node->DFS_fntm);
1260                                         */
1261                                         } else 
1262                                                 fprintf(stderr,"dfs unknown edge \n");
1263                                 }
1264                                 itA = itA->next;
1265                         }                       
1266
1267                         if (!skip) {
1268                                 node = pop_queue(nqueue);
1269                                 node->color = DAG_BLACK;
1270
1271                                 node->DFS_fntm = time;
1272                                 time++;
1273                                 if (node->DFS_dist > maxpos)
1274                                         maxpos = node->DFS_dist;
1275                                 if (pos[node->DFS_dist] > node->k ) {
1276                                         pos[node->DFS_dist] += 1;                               
1277                                         node->k = (float) pos[node->DFS_dist];
1278                                 } else {
1279                                         pos[node->DFS_dist] = (int) node->k +1;
1280                                 }
1281                                 set_node_xy(node, node->DFS_dist*DEPSX*2, pos[node->DFS_dist]*DEPSY*2);
1282                                 
1283                                 /*
1284                                  fprintf(stderr,"DFS node : %20s %i %i %i %i\n",((ID *) node->ob)->name,node->BFS_dist, node->DFS_dist, node->DFS_dvtm, node->DFS_fntm );       
1285                                 */
1286                                  push_stack(retqueue,node);
1287                                 
1288                         }
1289                 }
1290         }
1291                 node = node->next;
1292         } while (node);
1293 //        fprintf(stderr,"i size : %i \n", maxpos);
1294           
1295         queue_delete(nqueue);
1296           return(retqueue);
1297 }
1298
1299 /* unused */
1300 int pre_and_post_DFS(DagForest *dag, short mask, graph_action_func pre_func, graph_action_func post_func, void **data) {
1301         DagNode *node;
1302
1303         node = dag->DagNode.first;
1304         return pre_and_post_source_DFS(dag, mask,  node,  pre_func,  post_func, data);
1305 }
1306
1307 int pre_and_post_source_DFS(DagForest *dag, short mask, DagNode *source, graph_action_func pre_func, graph_action_func post_func, void **data)
1308 {
1309         DagNode *node;
1310         DagNodeQueue *nqueue;
1311         DagAdjList *itA;
1312         int time;
1313         int skip = 0;
1314         int retval = 0;
1315         /*
1316          *fprintf(stderr,"starting DFS \n ------------\n");
1317          */     
1318         nqueue = queue_create(DAGQUEUEALLOC);
1319         
1320         /* Init
1321                 * dagnode.first is alway the root (scene) 
1322                 */
1323         node = dag->DagNode.first;
1324         while(node) {
1325                 node->color = DAG_WHITE;
1326                 node->DFS_dist = 9999;
1327                 node->DFS_dvtm = node->DFS_fntm = 9999;
1328                 node->k = 0;
1329                 node =  node->next;
1330         }
1331         
1332         time = 1;
1333         
1334         node = source;
1335         do {
1336                 if (node->color == DAG_WHITE) {
1337                         node->color = DAG_GRAY;
1338                         node->DFS_dist = 1;
1339                         node->DFS_dvtm = time;
1340                         time++;
1341                         push_stack(nqueue,node);  
1342                         pre_func(node->ob,data);
1343
1344                         while(nqueue->count) {
1345                                 skip = 0;
1346                                 node = get_top_node_queue(nqueue);
1347                                                                 
1348                                 itA = node->child;
1349                                 while(itA != NULL) {
1350                                         if((itA->node->color == DAG_WHITE) && (itA->type & mask) ) {
1351                                                 itA->node->DFS_dvtm = time;
1352                                                 itA->node->color = DAG_GRAY;
1353                                                 
1354                                                 time++;
1355                                                 itA->node->DFS_dist = node->DFS_dist + 1;
1356                                                 push_stack(nqueue,itA->node);
1357                                                 pre_func(node->ob,data);
1358
1359                                                 skip = 1;
1360                                                 break;
1361                                         } else {
1362                                                 if (itA->node->color == DAG_GRAY) {// back edge
1363                                                         retval = 1;
1364                                                 }
1365 //                                              else if (itA->node->color == DAG_BLACK) { // cross or forward
1366 //                                                      ;
1367                                         }
1368                                         itA = itA->next;
1369                                 }                       
1370                                 
1371                                 if (!skip) {
1372                                         node = pop_queue(nqueue);
1373                                         node->color = DAG_BLACK;
1374                                         
1375                                         node->DFS_fntm = time;
1376                                         time++;
1377                                         post_func(node->ob,data);
1378                                 }
1379                         }
1380                 }
1381                 node = node->next;
1382         } while (node);
1383         queue_delete(nqueue);
1384         return(retval);
1385 }
1386
1387
1388 // used to get the obs owning a datablock
1389 struct DagNodeQueue *get_obparents(struct DagForest     *dag, void *ob) 
1390 {
1391         DagNode * node, *node1;
1392         DagNodeQueue *nqueue;
1393         DagAdjList *itA;
1394
1395         node = dag_find_node(dag,ob);
1396         if(node==NULL) {
1397                 return NULL;
1398         }
1399         else if (node->ancestor_count == 1) { // simple case
1400                 nqueue = queue_create(1);
1401                 push_queue(nqueue,node);
1402         } else {        // need to go over the whole dag for adj list
1403                 nqueue = queue_create(node->ancestor_count);
1404                 
1405                 node1 = dag->DagNode.first;
1406                 do {
1407                         if (node1->DFS_fntm > node->DFS_fntm) { // a parent is finished after child. must check adj list
1408                                 itA = node->child;
1409                                 while(itA != NULL) {
1410                                         if ((itA->node == node) && (itA->type == DAG_RL_DATA)) {
1411                                                 push_queue(nqueue,node);
1412                                         }
1413                                         itA = itA->next;
1414                                 }
1415                         }
1416                         node1 = node1->next;
1417                 } while (node1);
1418         }
1419         return nqueue;
1420 }
1421
1422 struct DagNodeQueue *get_first_ancestors(struct DagForest       *dag, void *ob)
1423 {
1424         DagNode * node, *node1;
1425         DagNodeQueue *nqueue;
1426         DagAdjList *itA;
1427         
1428         node = dag_find_node(dag,ob);
1429         
1430         // need to go over the whole dag for adj list
1431         nqueue = queue_create(node->ancestor_count);
1432         
1433         node1 = dag->DagNode.first;
1434         do {
1435                 if (node1->DFS_fntm > node->DFS_fntm) { 
1436                         itA = node->child;
1437                         while(itA != NULL) {
1438                                 if (itA->node == node) {
1439                                         push_queue(nqueue,node);
1440                                 }
1441                                 itA = itA->next;
1442                         }
1443                 }
1444                 node1 = node1->next;
1445         } while (node1);
1446         
1447         return nqueue;  
1448 }
1449
1450 // standard DFS list
1451 struct DagNodeQueue *get_all_childs(struct DagForest    *dag, void *ob)
1452 {
1453         DagNode *node;
1454         DagNodeQueue *nqueue;
1455         DagNodeQueue *retqueue;
1456         DagAdjList *itA;
1457         int time;
1458         int skip = 0;
1459
1460         nqueue = queue_create(DAGQUEUEALLOC);
1461         retqueue = queue_create(dag->numNodes); // was MainDag... why? (ton)
1462         
1463         node = dag->DagNode.first;
1464         while(node) {
1465                 node->color = DAG_WHITE;
1466                 node =  node->next;
1467         }
1468         
1469         time = 1;
1470         
1471         node = dag_find_node(dag, ob);   // could be done in loop above (ton)
1472         if(node) { // can be null for newly added objects
1473                 
1474                 node->color = DAG_GRAY;
1475                 time++;
1476                 push_stack(nqueue,node);  
1477                 
1478                 while(nqueue->count) {
1479                         
1480                         skip = 0;
1481                         node = get_top_node_queue(nqueue);
1482                                         
1483                         itA = node->child;
1484                         while(itA != NULL) {
1485                                 if((itA->node->color == DAG_WHITE) ) {
1486                                         itA->node->DFS_dvtm = time;
1487                                         itA->node->color = DAG_GRAY;
1488                                         
1489                                         time++;
1490                                         push_stack(nqueue,itA->node);
1491                                         skip = 1;
1492                                         break;
1493                                 } 
1494                                 itA = itA->next;
1495                         }                       
1496                         
1497                         if (!skip) {
1498                                 node = pop_queue(nqueue);
1499                                 node->color = DAG_BLACK;
1500                                 
1501                                 time++;
1502                                 push_stack(retqueue,node);                      
1503                         }
1504                 }
1505         }
1506         queue_delete(nqueue);
1507         return(retqueue);
1508 }
1509
1510 /* unused */
1511 short   are_obs_related(struct DagForest        *dag, void *ob1, void *ob2) {
1512         DagNode * node;
1513         DagAdjList *itA;
1514         
1515         node = dag_find_node(dag, ob1);
1516         
1517         itA = node->child;
1518         while(itA != NULL) {
1519                 if((itA->node->ob == ob2) ) {
1520                         return itA->node->type;
1521                 } 
1522                 itA = itA->next;
1523         }
1524         return DAG_NO_RELATION;
1525 }
1526
1527 int     is_acyclic( DagForest   *dag) {
1528         return dag->is_acyclic;
1529 }
1530
1531 void set_node_xy(DagNode *node, float x, float y)
1532 {
1533         node->x = x;
1534         node->y = y;
1535 }
1536
1537
1538 /* debug test functions */
1539
1540 void graph_print_queue(DagNodeQueue *nqueue)
1541 {       
1542         DagNodeQueueElem *queueElem;
1543         
1544         queueElem = nqueue->first;
1545         while(queueElem) {
1546                 fprintf(stderr,"** %s %i %i-%i ",((ID *) queueElem->node->ob)->name,queueElem->node->color,queueElem->node->DFS_dvtm,queueElem->node->DFS_fntm);
1547                 queueElem = queueElem->next;            
1548         }
1549         fprintf(stderr,"\n");
1550 }
1551
1552 void graph_print_queue_dist(DagNodeQueue *nqueue)
1553 {       
1554         DagNodeQueueElem *queueElem;
1555         int max, count;
1556         
1557         queueElem = nqueue->first;
1558         max = queueElem->node->DFS_fntm;
1559         count = 0;
1560         while(queueElem) {
1561                 fprintf(stderr,"** %25s %2.2i-%2.2i ",((ID *) queueElem->node->ob)->name,queueElem->node->DFS_dvtm,queueElem->node->DFS_fntm);
1562                 while (count < queueElem->node->DFS_dvtm-1) { fputc(' ',stderr); count++;}
1563                 fputc('|',stderr); 
1564                 while (count < queueElem->node->DFS_fntm-2) { fputc('-',stderr); count++;}
1565                 fputc('|',stderr);
1566                 fputc('\n',stderr);
1567                 count = 0;
1568                 queueElem = queueElem->next;            
1569         }
1570         fprintf(stderr,"\n");
1571 }
1572
1573 void graph_print_adj_list(void)
1574 {
1575         DagNode *node;
1576         DagAdjList *itA;
1577         
1578         node = (getMainDag())->DagNode.first;
1579         while(node) {
1580                 fprintf(stderr,"node : %s col: %i",((ID *) node->ob)->name, node->color);               
1581                 itA = node->child;
1582                 while (itA) {
1583                         fprintf(stderr,"-- %s ",((ID *) itA->node->ob)->name);
1584                         
1585                         itA = itA->next;
1586                 }
1587                 fprintf(stderr,"\n");
1588                 node = node->next;
1589         }
1590 }
1591
1592 /* ************************ API *********************** */
1593
1594 /* mechanism to allow editors to be informed of depsgraph updates,
1595    to do their own updates based on changes... */
1596 static void (*EditorsUpdateCb)(Main *bmain, ID *id)= NULL;
1597
1598 void DAG_editors_update_cb(void (*func)(Main *bmain, ID *id))
1599 {
1600         EditorsUpdateCb= func;
1601 }
1602
1603 static void dag_editors_update(Main *bmain, ID *id)
1604 {
1605         if(EditorsUpdateCb)
1606                 EditorsUpdateCb(bmain, id);
1607 }
1608
1609 /* groups with objects in this scene need to be put in the right order as well */
1610 static void scene_sort_groups(Scene *sce)
1611 {
1612         Base *base;
1613         Group *group;
1614         GroupObject *go;
1615         Object *ob;
1616         
1617         /* test; are group objects all in this scene? */
1618         for(ob= G.main->object.first; ob; ob= ob->id.next) {
1619                 ob->id.flag &= ~LIB_DOIT;
1620                 ob->id.newid= NULL;     /* newid abuse for GroupObject */
1621         }
1622         for(base = sce->base.first; base; base= base->next)
1623                 base->object->id.flag |= LIB_DOIT;
1624         
1625         for(group= G.main->group.first; group; group= group->id.next) {
1626                 for(go= group->gobject.first; go; go= go->next) {
1627                         if((go->ob->id.flag & LIB_DOIT)==0)
1628                                 break;
1629                 }
1630                 /* this group is entirely in this scene */
1631                 if(go==NULL) {
1632                         ListBase listb= {NULL, NULL};
1633                         
1634                         for(go= group->gobject.first; go; go= go->next)
1635                                 go->ob->id.newid= (ID *)go;
1636                         
1637                         /* in order of sorted bases we reinsert group objects */
1638                         for(base = sce->base.first; base; base= base->next) {
1639                                 
1640                                 if(base->object->id.newid) {
1641                                         go= (GroupObject *)base->object->id.newid;
1642                                         base->object->id.newid= NULL;
1643                                         BLI_remlink( &group->gobject, go);
1644                                         BLI_addtail( &listb, go);
1645                                 }
1646                         }
1647                         /* copy the newly sorted listbase */
1648                         group->gobject= listb;
1649                 }
1650         }
1651 }
1652
1653 /* sort the base list on dependency order */
1654 void DAG_scene_sort(struct Scene *sce)
1655 {
1656         DagNode *node;
1657         DagNodeQueue *nqueue;
1658         DagAdjList *itA;
1659         int time;
1660         int skip = 0;
1661         ListBase tempbase;
1662         Base *base;
1663         
1664         tempbase.first= tempbase.last= NULL;
1665         
1666         build_dag(sce, DAG_RL_ALL_BUT_DATA);
1667         
1668         dag_check_cycle(sce->theDag);
1669
1670         nqueue = queue_create(DAGQUEUEALLOC);
1671         
1672         for(node = sce->theDag->DagNode.first; node; node= node->next) {
1673                 node->color = DAG_WHITE;
1674         }
1675         
1676         time = 1;
1677         
1678         node = sce->theDag->DagNode.first;
1679         
1680         node->color = DAG_GRAY;
1681         time++;
1682         push_stack(nqueue,node);  
1683         
1684         while(nqueue->count) {
1685                 
1686                 skip = 0;
1687                 node = get_top_node_queue(nqueue);
1688                 
1689                 itA = node->child;
1690                 while(itA != NULL) {
1691                         if((itA->node->color == DAG_WHITE) ) {
1692                                 itA->node->DFS_dvtm = time;
1693                                 itA->node->color = DAG_GRAY;
1694                                 
1695                                 time++;
1696                                 push_stack(nqueue,itA->node);
1697                                 skip = 1;
1698                                 break;
1699                         } 
1700                         itA = itA->next;
1701                 }                       
1702                 
1703                 if (!skip) {
1704                         if (node) {
1705                                 node = pop_queue(nqueue);
1706                                 if (node->ob == sce)    // we are done
1707                                         break ;
1708                                 node->color = DAG_BLACK;
1709                                 
1710                                 time++;
1711                                 base = sce->base.first;
1712                                 while (base && base->object != node->ob)
1713                                         base = base->next;
1714                                 if(base) {
1715                                         BLI_remlink(&sce->base,base);
1716                                         BLI_addhead(&tempbase,base);
1717                                 }
1718                         }       
1719                 }
1720         }
1721         
1722         // temporal correction for circular dependancies
1723         base = sce->base.first;
1724         while (base) {
1725                 BLI_remlink(&sce->base,base);
1726                 BLI_addhead(&tempbase,base);
1727                 //if(G.f & G_DEBUG) 
1728                         printf("cyclic %s\n", base->object->id.name);
1729                 base = sce->base.first;
1730         }
1731         
1732         sce->base = tempbase;
1733         queue_delete(nqueue);
1734         
1735         /* all groups with objects in this scene gets resorted too */
1736         scene_sort_groups(sce);
1737         
1738         if(G.f & G_DEBUG) {
1739                 printf("\nordered\n");
1740                 for(base = sce->base.first; base; base= base->next) {
1741                         printf(" %s\n", base->object->id.name);
1742                 }
1743         }
1744         /* temporal...? */
1745         sce->recalc |= SCE_PRV_CHANGED; /* test for 3d preview */
1746 }
1747
1748 /* node was checked to have lasttime != curtime and is if type ID_OB */
1749 static void flush_update_node(DagNode *node, unsigned int layer, int curtime)
1750 {
1751         DagAdjList *itA;
1752         Object *ob, *obc;
1753         int oldflag, changed=0;
1754         unsigned int all_layer;
1755         
1756         node->lasttime= curtime;
1757         
1758         ob= node->ob;
1759         if(ob && (ob->recalc & OB_RECALC)) {
1760                 all_layer= ob->lay;
1761
1762                 /* got an object node that changes, now check relations */
1763                 for(itA = node->child; itA; itA= itA->next) {
1764                         all_layer |= itA->lay;
1765                         /* the relationship is visible */
1766                         if((itA->lay & layer)) { // XXX || (itA->node->ob == obedit)
1767                                 if(itA->node->type==ID_OB) {
1768                                         obc= itA->node->ob;
1769                                         oldflag= obc->recalc;
1770                                         
1771                                         /* got a ob->obc relation, now check if flag needs flush */
1772                                         if(ob->recalc & OB_RECALC_OB) {
1773                                                 if(itA->type & DAG_RL_OB_OB) {
1774                                                         //printf("ob %s changes ob %s\n", ob->id.name, obc->id.name);
1775                                                         obc->recalc |= OB_RECALC_OB;
1776                                                 }
1777                                                 if(itA->type & DAG_RL_OB_DATA) {
1778                                                         //printf("ob %s changes obdata %s\n", ob->id.name, obc->id.name);
1779                                                         obc->recalc |= OB_RECALC_DATA;
1780                                                 }
1781                                         }
1782                                         if(ob->recalc & OB_RECALC_DATA) {
1783                                                 if(itA->type & DAG_RL_DATA_OB) {
1784                                                         //printf("obdata %s changes ob %s\n", ob->id.name, obc->id.name);
1785                                                         obc->recalc |= OB_RECALC_OB;
1786                                                 }
1787                                                 if(itA->type & DAG_RL_DATA_DATA) {
1788                                                         //printf("obdata %s changes obdata %s\n", ob->id.name, obc->id.name);
1789                                                         obc->recalc |= OB_RECALC_DATA;
1790                                                 }
1791                                         }
1792                                         if(oldflag!=obc->recalc) changed= 1;
1793                                 }
1794                         }
1795                 }
1796                 /* even nicer, we can clear recalc flags...  */
1797                 if((all_layer & layer)==0) { // XXX && (ob != obedit)) {
1798                         /* but existing displaylists or derivedmesh should be freed */
1799                         if(ob->recalc & OB_RECALC_DATA)
1800                                 object_free_display(ob);
1801                         
1802                         ob->recalc &= ~OB_RECALC;
1803                 }
1804         }
1805         
1806         /* check case where child changes and parent forcing obdata to change */
1807         /* should be done regardless if this ob has recalc set */
1808         /* could merge this in with loop above...? (ton) */
1809         for(itA = node->child; itA; itA= itA->next) {
1810                 /* the relationship is visible */
1811                 if((itA->lay & layer)) {                // XXX  || (itA->node->ob == obedit)
1812                         if(itA->node->type==ID_OB) {
1813                                 obc= itA->node->ob;
1814                                 /* child moves */
1815                                 if((obc->recalc & OB_RECALC)==OB_RECALC_OB) {
1816                                         /* parent has deforming info */
1817                                         if(itA->type & (DAG_RL_OB_DATA|DAG_RL_DATA_DATA)) {
1818                                                 // printf("parent %s changes ob %s\n", ob->id.name, obc->id.name);
1819                                                 obc->recalc |= OB_RECALC_DATA;
1820                                         }
1821                                 }
1822                         }
1823                 }
1824         }
1825         
1826         /* we only go deeper if node not checked or something changed  */
1827         for(itA = node->child; itA; itA= itA->next) {
1828                 if(changed || itA->node->lasttime!=curtime) 
1829                         flush_update_node(itA->node, layer, curtime);
1830         }
1831         
1832 }
1833
1834 /* node was checked to have lasttime != curtime , and is of type ID_OB */
1835 static unsigned int flush_layer_node(Scene *sce, DagNode *node, int curtime)
1836 {
1837         DagAdjList *itA;
1838         
1839         node->lasttime= curtime;
1840         node->lay= node->scelay;
1841         
1842         for(itA = node->child; itA; itA= itA->next) {
1843                 if(itA->node->type==ID_OB) {
1844                         if(itA->node->lasttime!=curtime) {
1845                                 itA->lay= flush_layer_node(sce, itA->node, curtime);  // lay is only set once for each relation
1846                         }
1847                         else itA->lay= itA->node->lay;
1848                         
1849                         node->lay |= itA->lay;
1850                 }
1851         }
1852
1853         return node->lay;
1854 }
1855
1856 /* node was checked to have lasttime != curtime , and is of type ID_OB */
1857 static void flush_pointcache_reset(Scene *scene, DagNode *node, int curtime, int reset)
1858 {
1859         DagAdjList *itA;
1860         Object *ob;
1861         
1862         node->lasttime= curtime;
1863         
1864         for(itA = node->child; itA; itA= itA->next) {
1865                 if(itA->node->type==ID_OB) {
1866                         if(itA->node->lasttime!=curtime) {
1867                                 ob= (Object*)(node->ob);
1868
1869                                 if(reset || (ob->recalc & OB_RECALC)) {
1870                                         if(BKE_ptcache_object_reset(scene, ob, PTCACHE_RESET_DEPSGRAPH))
1871                                                 ob->recalc |= OB_RECALC_DATA;
1872
1873                                         flush_pointcache_reset(scene, itA->node, curtime, 1);
1874                                 }
1875                                 else
1876                                         flush_pointcache_reset(scene, itA->node, curtime, 0);
1877                         }
1878                 }
1879         }
1880 }
1881
1882 /* flushes all recalc flags in objects down the dependency tree */
1883 void DAG_scene_flush_update(Scene *sce, unsigned int lay, int time)
1884 {
1885         DagNode *firstnode, *node;
1886         DagAdjList *itA;
1887         Object *ob;
1888         Base *base;
1889         int lasttime;
1890         
1891         if(sce->theDag==NULL) {
1892                 printf("DAG zero... not allowed to happen!\n");
1893                 DAG_scene_sort(sce);
1894         }
1895         
1896         firstnode= sce->theDag->DagNode.first;  // always scene node
1897
1898         for(itA = firstnode->child; itA; itA= itA->next)
1899                 itA->lay= 0;
1900         
1901         /* first we flush the layer flags */
1902         sce->theDag->time++;    // so we know which nodes were accessed
1903         lasttime= sce->theDag->time;
1904
1905
1906         for(base= sce->base.first; base; base= base->next) {
1907                 node= dag_get_node(sce->theDag, base->object);
1908                 if(node)
1909                         node->scelay= base->object->lay;
1910                 else
1911                         node->scelay= 0;
1912         }
1913
1914         for(itA = firstnode->child; itA; itA= itA->next)
1915                 if(itA->node->lasttime!=lasttime && itA->node->type==ID_OB) 
1916                         flush_layer_node(sce, itA->node, lasttime);
1917         
1918         /* then we use the relationships + layer info to flush update events */
1919         sce->theDag->time++;    // so we know which nodes were accessed
1920         lasttime= sce->theDag->time;
1921         for(itA = firstnode->child; itA; itA= itA->next)
1922                 if(itA->node->lasttime!=lasttime && itA->node->type==ID_OB)
1923                         flush_update_node(itA->node, lay, lasttime);
1924
1925         /* if update is not due to time change, do pointcache clears */
1926         if(!time) {
1927                 sce->theDag->time++;    // so we know which nodes were accessed
1928                 lasttime= sce->theDag->time;
1929                 for(itA = firstnode->child; itA; itA= itA->next) {
1930                         if(itA->node->lasttime!=lasttime && itA->node->type==ID_OB)  {
1931                                 ob= (Object*)(itA->node->ob);
1932
1933                                 if(ob->recalc & OB_RECALC) {
1934                                         if(BKE_ptcache_object_reset(sce, ob, PTCACHE_RESET_DEPSGRAPH))
1935                                                 ob->recalc |= OB_RECALC_DATA;
1936
1937                                         flush_pointcache_reset(sce, itA->node, lasttime, 1);
1938                                 }
1939                                 else
1940                                         flush_pointcache_reset(sce, itA->node, lasttime, 0);
1941                         }
1942                 }
1943         }
1944 }
1945
1946 static int object_modifiers_use_time(Object *ob)
1947 {
1948         ModifierData *md;
1949
1950         for (md=ob->modifiers.first; md; md=md->next)
1951                 if (modifier_dependsOnTime(md))
1952                         return 1;
1953
1954         return 0;
1955 }
1956
1957 static short animdata_use_time(AnimData *adt)
1958 {
1959         NlaTrack *nlt;
1960         
1961         if(adt==NULL) return 0;
1962         
1963         /* check action - only if assigned, and it has anim curves */
1964         if (adt->action && adt->action->curves.first)
1965                 return 1;
1966         
1967         /* check NLA tracks + strips */
1968         for (nlt= adt->nla_tracks.first; nlt; nlt= nlt->next) {
1969                 if (nlt->strips.first)
1970                         return 1;
1971         }
1972         
1973         return 0;
1974 }
1975
1976 static void dag_object_time_update_flags(Object *ob)
1977 {
1978         if(ob->constraints.first) {
1979                 bConstraint *con;
1980                 for (con = ob->constraints.first; con; con=con->next) {
1981                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1982                         ListBase targets = {NULL, NULL};
1983                         bConstraintTarget *ct;
1984                         
1985                         if (cti && cti->get_constraint_targets) {
1986                                 cti->get_constraint_targets(con, &targets);
1987                                 
1988                                 for (ct= targets.first; ct; ct= ct->next) {
1989                                         if (ct->tar) {
1990                                                 ob->recalc |= OB_RECALC_OB;
1991                                                 break;
1992                                         }
1993                                 }
1994                                 
1995                                 if (cti->flush_constraint_targets)
1996                                         cti->flush_constraint_targets(con, &targets, 1);
1997                         }
1998                 }
1999         }
2000         
2001         if(ob->parent) {
2002                 /* motion path or bone child */
2003                 if(ob->parent->type==OB_CURVE || ob->parent->type==OB_ARMATURE) ob->recalc |= OB_RECALC_OB;
2004         }
2005         
2006 #if 0 // XXX old animation system
2007         if(ob->nlastrips.first) {
2008                 if(ob->dup_group) {
2009                         bActionStrip *strip;
2010                         /* this case is for groups with nla, whilst nla target has no action or nla */
2011                         for(strip= ob->nlastrips.first; strip; strip= strip->next) {
2012                                 if(strip->object)
2013                                         strip->object->recalc |= OB_RECALC;
2014                         }
2015                 }
2016         }
2017 #endif // XXX old animation system
2018         
2019         if(animdata_use_time(ob->adt)) {
2020                 ob->recalc |= OB_RECALC;
2021                 ob->adt->recalc |= ADT_RECALC_ANIM;
2022         }
2023         
2024         if((ob->adt) && (ob->type==OB_ARMATURE)) ob->recalc |= OB_RECALC_DATA;
2025         
2026         if(object_modifiers_use_time(ob)) ob->recalc |= OB_RECALC_DATA;
2027         if((ob->pose) && (ob->pose->flag & POSE_CONSTRAINTS_TIMEDEPEND)) ob->recalc |= OB_RECALC_DATA;
2028         
2029         {
2030                 Mesh *me;
2031                 Curve *cu;
2032                 Lattice *lt;
2033                 
2034                 switch(ob->type) {
2035                         case OB_MESH:
2036                                 me= ob->data;
2037                                 if(me->key) {
2038                                         if(!(ob->shapeflag & OB_SHAPE_LOCK)) {
2039                                                 ob->recalc |= OB_RECALC_DATA;
2040                                         }
2041                                 }
2042                                 if(ob->particlesystem.first)
2043                                         ob->recalc |= OB_RECALC_DATA;
2044                                 break;
2045                         case OB_CURVE:
2046                         case OB_SURF:
2047                                 cu= ob->data;
2048                                 if(cu->key) {
2049                                         if(!(ob->shapeflag & OB_SHAPE_LOCK)) {
2050                                                 ob->recalc |= OB_RECALC_DATA;
2051                                         }
2052                                 }
2053                                 break;
2054                         case OB_FONT:
2055                                 cu= ob->data;
2056                                 if(cu->nurb.first==NULL && cu->str && cu->vfont)
2057                                         ob->recalc |= OB_RECALC_DATA;
2058                                 break;
2059                         case OB_LATTICE:
2060                                 lt= ob->data;
2061                                 if(lt->key) {
2062                                         if(!(ob->shapeflag & OB_SHAPE_LOCK)) {
2063                                                 ob->recalc |= OB_RECALC_DATA;
2064                                         }
2065                                 }
2066                                         break;
2067                         case OB_MBALL:
2068                                 if(ob->transflag & OB_DUPLI) ob->recalc |= OB_RECALC_DATA;
2069                                 break;
2070                 }
2071
2072                 if(ob->particlesystem.first) {
2073                         ParticleSystem *psys= ob->particlesystem.first;
2074
2075                         for(; psys; psys=psys->next) {
2076                                 if(psys_check_enabled(ob, psys)) {
2077                                         ob->recalc |= OB_RECALC_DATA;
2078                                         break;
2079                                 }
2080                         }
2081                 }
2082         }               
2083 }
2084 /* flag all objects that need recalc, for changes in time for example */
2085 void DAG_scene_update_flags(Scene *scene, unsigned int lay)
2086 {
2087         Base *base;
2088         Object *ob;
2089         Group *group;
2090         GroupObject *go;
2091         Scene *sce;
2092         
2093         /* set ob flags where animated systems are */
2094         for(SETLOOPER(scene, base)) {
2095                 ob= base->object;
2096                 
2097                 /* now if DagNode were part of base, the node->lay could be checked... */
2098                 /* we do all now, since the scene_flush checks layers and clears recalc flags even */
2099                 dag_object_time_update_flags(ob);
2100                 
2101                 /* handled in next loop */
2102                 if(ob->dup_group) 
2103                         ob->dup_group->id.flag |= LIB_DOIT;
2104         }       
2105         
2106         /* we do groups each once */
2107         for(group= G.main->group.first; group; group= group->id.next) {
2108                 if(group->id.flag & LIB_DOIT) {
2109                         for(go= group->gobject.first; go; go= go->next) {
2110                                 dag_object_time_update_flags(go->ob);
2111                         }
2112                 }
2113         }
2114         
2115         for(sce= scene; sce; sce= sce->set)
2116                 DAG_scene_flush_update(sce, lay, 1);
2117         
2118         /* test: set time flag, to disable baked systems to update */
2119         for(SETLOOPER(scene, base)) {
2120                 ob= base->object;
2121                 if(ob->recalc)
2122                         ob->recalc |= OB_RECALC_TIME;
2123         }
2124         
2125         /* hrmf... an exception to look at once, for invisible camera object we do it over */
2126         if(scene->camera)
2127                 dag_object_time_update_flags(scene->camera);
2128         
2129         /* and store the info in groupobject */
2130         for(group= G.main->group.first; group; group= group->id.next) {
2131                 if(group->id.flag & LIB_DOIT) {
2132                         for(go= group->gobject.first; go; go= go->next) {
2133                                 go->recalc= go->ob->recalc;
2134                                 // printf("ob %s recalc %d\n", go->ob->id.name, go->recalc);
2135                         }
2136                         group->id.flag &= ~LIB_DOIT;
2137                 }
2138         }
2139         
2140 }
2141
2142 static void dag_current_scene_layers(Main *bmain, Scene **sce, unsigned int *lay)
2143 {
2144         wmWindowManager *wm;
2145         wmWindow *win;
2146
2147         /* only one scene supported currently, making more scenes work
2148            correctly requires changes beyond just the dependency graph */
2149
2150         *sce= NULL;
2151         *lay= 0;
2152
2153         if((wm= bmain->wm.first)) {
2154                 /* if we have a windowmanager, look into windows */
2155                 for(win=wm->windows.first; win; win=win->next) {
2156                         if(win->screen) {
2157                                 if(!*sce) *sce= win->screen->scene;
2158                                 *lay |= BKE_screen_visible_layers(win->screen);
2159                         }
2160                 }
2161         }
2162         else {
2163                 /* if not, use the first sce */
2164                 *sce= bmain->scene.first;
2165                 if(*sce) *lay= (*sce)->lay;
2166
2167                 /* XXX for background mode, we should get the scen
2168                    from somewhere, for the -S option, but it's in
2169                    the context, how to get it here? */
2170         }
2171 }
2172
2173 void DAG_ids_flush_update(int time)
2174 {
2175         Main *bmain= G.main;
2176         Scene *sce;
2177         unsigned int lay;
2178
2179         dag_current_scene_layers(bmain, &sce, &lay);
2180
2181         if(sce)
2182                 DAG_scene_flush_update(sce, lay, time);
2183 }
2184
2185 void DAG_id_flush_update(ID *id, short flag)
2186 {
2187         Main *bmain= G.main;
2188         Scene *sce;
2189         Object *obt, *ob= NULL;
2190         short idtype;
2191         unsigned int lay;
2192
2193         dag_current_scene_layers(bmain, &sce, &lay);
2194
2195         if(!id || !sce || !sce->theDag)
2196                 return;
2197
2198         /* set flags & pointcache for object */
2199         if(GS(id->name) == ID_OB) {
2200                 ob= (Object*)id;
2201                 ob->recalc |= (flag & OB_RECALC);
2202                 BKE_ptcache_object_reset(sce, ob, PTCACHE_RESET_DEPSGRAPH);
2203
2204                 if(flag & OB_RECALC_DATA) {
2205                         /* all users of this ob->data should be checked */
2206                         id= ob->data;
2207
2208                         /* no point in trying in this cases */
2209                         if(!id || id->us <= 1)
2210                                 id= NULL;
2211                         /* curves and surfaces only need to mark one object, since
2212                            otherwise cu->displist would be computed multiple times */
2213                         else if(ob->type==OB_CURVE || ob->type==OB_SURF)
2214                                 id= NULL;
2215                         /* also for locked shape keys we make an exception */
2216                         else if(ob_get_key(ob) && (ob->shapeflag & OB_SHAPE_LOCK))
2217                                 id= NULL;
2218                 }
2219         }
2220
2221         /* set flags & pointcache for object data */
2222         if(id) {
2223                 idtype= GS(id->name);
2224
2225                 if(ELEM7(idtype, ID_ME, ID_CU, ID_MB, ID_LA, ID_LT, ID_CA, ID_AR)) {
2226                         for(obt=bmain->object.first; obt; obt= obt->id.next) {
2227                                 if(!(ob && obt == ob) && obt->data == id) {
2228                                         obt->recalc |= OB_RECALC_DATA;
2229                                         BKE_ptcache_object_reset(sce, obt, PTCACHE_RESET_DEPSGRAPH);
2230
2231                                         /* for these we only flag one object, otherwise cu->displist
2232                                            would be computed multiple times */
2233                                         if(obt->type==OB_CURVE || obt->type==OB_SURF)
2234                                                 break;
2235                                 }
2236                         }
2237                 }
2238
2239                 /* set flags based on particle settings */
2240                 if(idtype == ID_PA) {
2241                         ParticleSystem *psys;
2242                         for(obt=bmain->object.first; obt; obt= obt->id.next) {
2243                                 for(psys=obt->particlesystem.first; psys; psys=psys->next) {
2244                                         if(&psys->part->id == id) {
2245                                                 BKE_ptcache_object_reset(sce, obt, PTCACHE_RESET_DEPSGRAPH);
2246                                                 obt->recalc |= (flag & OB_RECALC);
2247                                                 psys->recalc |= (flag & PSYS_RECALC);
2248                                         }
2249                                 }
2250                         }
2251                 }
2252
2253                 /* update editors */
2254                 dag_editors_update(bmain, id);
2255         }
2256
2257         /* flush to other objects that depend on this one */
2258         DAG_scene_flush_update(sce, lay, 0);
2259 }
2260
2261 /* recursively descends tree, each node only checked once */
2262 /* node is checked to be of type object */
2263 static int parent_check_node(DagNode *node, int curtime)
2264 {
2265         DagAdjList *itA;
2266         
2267         node->lasttime= curtime;
2268         
2269         if(node->color==DAG_GRAY)
2270                 return DAG_GRAY;
2271         
2272         for(itA = node->child; itA; itA= itA->next) {
2273                 if(itA->node->type==ID_OB) {
2274                         
2275                         if(itA->node->color==DAG_GRAY)
2276                                 return DAG_GRAY;
2277
2278                         /* descend if not done */
2279                         if(itA->node->lasttime!=curtime) {
2280                                 itA->node->color= parent_check_node(itA->node, curtime);
2281                         
2282                                 if(itA->node->color==DAG_GRAY)
2283                                         return DAG_GRAY;
2284                         }
2285                 }
2286         }
2287         
2288         return DAG_WHITE;
2289 }
2290
2291 /* all nodes that influence this object get tagged, for calculating the exact
2292    position of this object at a given timeframe */
2293 void DAG_id_update_flags(ID *id)
2294 {
2295         Main *bmain= G.main;
2296         Scene *sce;
2297         DagNode *node;
2298         DagAdjList *itA;
2299         Object *ob;
2300         unsigned int lay;
2301
2302         dag_current_scene_layers(bmain, &sce, &lay);
2303
2304         if(!id || !sce || !sce->theDag)
2305                 return;
2306         
2307         /* objects only currently */
2308         if(GS(id->name) != ID_OB)
2309                 return;
2310         
2311         ob= (Object*)id;
2312         
2313         /* tag nodes unchecked */
2314         for(node = sce->theDag->DagNode.first; node; node= node->next) 
2315                 node->color = DAG_WHITE;
2316         
2317         node= dag_find_node(sce->theDag, ob);
2318         
2319         /* object not in scene? then handle group exception. needs to be dagged once too */
2320         if(node==NULL) {
2321                 Group *group= NULL;
2322                 while( (group = find_group(ob, group)) ) {
2323                         GroupObject *go;
2324                         /* primitive; tag all... this call helps building groups for particles */
2325                         for(go= group->gobject.first; go; go= go->next)
2326                                 go->ob->recalc= OB_RECALC;
2327                 }
2328         }
2329         else {
2330                 
2331                 node->color = DAG_GRAY;
2332                 
2333                 sce->theDag->time++;
2334                 node= sce->theDag->DagNode.first;
2335                 for(itA = node->child; itA; itA= itA->next) {
2336                         if(itA->node->type==ID_OB && itA->node->lasttime!=sce->theDag->time)
2337                                 itA->node->color= parent_check_node(itA->node, sce->theDag->time);
2338                 }
2339                 
2340                 /* set recalcs and flushes */
2341                 DAG_scene_update_flags(sce, lay);
2342                 
2343                 /* now we clear recalcs, unless color is set */
2344                 for(node = sce->theDag->DagNode.first; node; node= node->next) {
2345                         if(node->type==ID_OB && node->color==DAG_WHITE) {
2346                                 Object *ob= node->ob;
2347                                 ob->recalc= 0;
2348                         }
2349                 }
2350         }
2351 }
2352
2353 /* ******************* DAG FOR ARMATURE POSE ***************** */
2354
2355 /* we assume its an armature with pose */
2356 void DAG_pose_sort(Object *ob)
2357 {
2358         bPose *pose= ob->pose;
2359         bPoseChannel *pchan;
2360         bConstraint *con;
2361         DagNode *node;
2362         DagNode *node2, *node3;
2363         DagNode *rootnode;
2364         DagForest *dag;
2365         DagNodeQueue *nqueue;
2366         DagAdjList *itA;
2367         ListBase tempbase;
2368         int skip = 0;
2369         
2370         dag = dag_init();
2371         ugly_hack_sorry= 0;     // no ID structs
2372
2373         rootnode = dag_add_node(dag, NULL);     // node->ob becomes NULL
2374         
2375         /* we add the hierarchy and the constraints */
2376         for(pchan = pose->chanbase.first; pchan; pchan= pchan->next) {
2377                 int addtoroot = 1;
2378                 
2379                 node = dag_get_node(dag, pchan);
2380                 
2381                 if(pchan->parent) {
2382                         node2 = dag_get_node(dag, pchan->parent);
2383                         dag_add_relation(dag, node2, node, 0, "Parent Relation");
2384                         addtoroot = 0;
2385                 }
2386                 for (con = pchan->constraints.first; con; con=con->next) {
2387                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
2388                         ListBase targets = {NULL, NULL};
2389                         bConstraintTarget *ct;
2390                         
2391                         if (cti && cti->get_constraint_targets) {
2392                                 cti->get_constraint_targets(con, &targets);
2393                                 
2394                                 for (ct= targets.first; ct; ct= ct->next) {
2395                                         if (ct->tar==ob && ct->subtarget[0]) {
2396                                                 bPoseChannel *target= get_pose_channel(ob->pose, ct->subtarget);
2397                                                 if (target) {
2398                                                         node2= dag_get_node(dag, target);
2399                                                         dag_add_relation(dag, node2, node, 0, "IK Constraint");
2400                                                         
2401                                                         if (con->type==CONSTRAINT_TYPE_KINEMATIC) {
2402                                                                 bKinematicConstraint *data = (bKinematicConstraint *)con->data;
2403                                                                 bPoseChannel *parchan;
2404                                                                 int segcount= 0;
2405                                                                 
2406                                                                 /* exclude tip from chain? */
2407                                                                 if(!(data->flag & CONSTRAINT_IK_TIP))
2408                                                                         parchan= pchan->parent;
2409                                                                 else
2410                                                                         parchan= pchan;
2411                                                                 
2412                                                                 /* Walk to the chain's root */
2413                                                                 while (parchan) {
2414                                                                         node3= dag_get_node(dag, parchan);
2415                                                                         dag_add_relation(dag, node2, node3, 0, "IK Constraint");
2416                                                                         
2417                                                                         segcount++;
2418                                                                         if (segcount==data->rootbone || segcount>255) break; // 255 is weak
2419                                                                         parchan= parchan->parent;
2420                                                                 }
2421                                                         }
2422                                                 }
2423                                         }
2424                                 }
2425                                 
2426                                 if (cti->flush_constraint_targets)
2427                                         cti->flush_constraint_targets(con, &targets, 1);
2428                         }
2429                 }
2430                 if (addtoroot == 1 ) {
2431                         dag_add_relation(dag, rootnode, node, 0, "Root Bone Relation");
2432                 }
2433         }
2434
2435         dag_check_cycle(dag);
2436         
2437         /* now we try to sort... */
2438         tempbase.first= tempbase.last= NULL;
2439
2440         nqueue = queue_create(DAGQUEUEALLOC);
2441         
2442         /* tag nodes unchecked */
2443         for(node = dag->DagNode.first; node; node= node->next) 
2444                 node->color = DAG_WHITE;
2445         
2446         node = dag->DagNode.first;
2447         
2448         node->color = DAG_GRAY;
2449         push_stack(nqueue, node);  
2450         
2451         while(nqueue->count) {
2452                 
2453                 skip = 0;
2454                 node = get_top_node_queue(nqueue);
2455                 
2456                 itA = node->child;
2457                 while(itA != NULL) {
2458                         if((itA->node->color == DAG_WHITE) ) {
2459                                 itA->node->color = DAG_GRAY;
2460                                 push_stack(nqueue,itA->node);
2461                                 skip = 1;
2462                                 break;
2463                         } 
2464                         itA = itA->next;
2465                 }                       
2466                 
2467                 if (!skip) {
2468                         if (node) {
2469                                 node = pop_queue(nqueue);
2470                                 if (node->ob == NULL)   // we are done
2471                                         break ;
2472                                 node->color = DAG_BLACK;
2473                                 
2474                                 /* put node in new list */
2475                                 BLI_remlink(&pose->chanbase, node->ob);
2476                                 BLI_addhead(&tempbase, node->ob);
2477                         }       
2478                 }
2479         }
2480         
2481         // temporal correction for circular dependancies
2482         while(pose->chanbase.first) {
2483                 pchan= pose->chanbase.first;
2484                 BLI_remlink(&pose->chanbase, pchan);
2485                 BLI_addhead(&tempbase, pchan);
2486
2487                 printf("cyclic %s\n", pchan->name);
2488         }
2489         
2490         pose->chanbase = tempbase;
2491         queue_delete(nqueue);
2492         
2493 //      printf("\nordered\n");
2494 //      for(pchan = pose->chanbase.first; pchan; pchan= pchan->next) {
2495 //              printf(" %s\n", pchan->name);
2496 //      }
2497         
2498         free_forest( dag );
2499         MEM_freeN( dag );
2500         
2501         ugly_hack_sorry= 1;
2502 }
2503
2504
2505