869404ae4a612dc2d1620f642c92f8c6c647b9b4
[blender.git] / source / blender / blenkernel / intern / depsgraph.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2004 Blender Foundation.
19  * All rights reserved.
20  *
21  * Contributor(s): none yet.
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/blenkernel/intern/depsgraph.c
27  *  \ingroup bke
28  */
29
30  
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <math.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #ifdef WIN32
39 #  include "BLI_winstuff.h"
40 #endif
41
42 #include "BLI_utildefines.h"
43 #include "BLI_listbase.h"
44 #include "BLI_ghash.h"
45 #include "BLI_threads.h"
46
47 #include "DNA_anim_types.h"
48 #include "DNA_camera_types.h"
49 #include "DNA_group_types.h"
50 #include "DNA_lamp_types.h"
51 #include "DNA_lattice_types.h"
52 #include "DNA_key_types.h"
53 #include "DNA_material_types.h"
54 #include "DNA_mesh_types.h"
55 #include "DNA_node_types.h"
56 #include "DNA_scene_types.h"
57 #include "DNA_screen_types.h"
58 #include "DNA_windowmanager_types.h"
59 #include "DNA_movieclip_types.h"
60 #include "DNA_mask_types.h"
61
62 #include "BKE_anim.h"
63 #include "BKE_animsys.h"
64 #include "BKE_action.h"
65 #include "BKE_DerivedMesh.h"
66 #include "BKE_effect.h"
67 #include "BKE_fcurve.h"
68 #include "BKE_global.h"
69 #include "BKE_image.h"
70 #include "BKE_key.h"
71 #include "BKE_library.h"
72 #include "BKE_main.h"
73 #include "BKE_node.h"
74 #include "BKE_material.h"
75 #include "BKE_mball.h"
76 #include "BKE_modifier.h"
77 #include "BKE_object.h"
78 #include "BKE_paint.h"
79 #include "BKE_particle.h"
80 #include "BKE_pointcache.h"
81 #include "BKE_scene.h"
82 #include "BKE_screen.h"
83 #include "BKE_tracking.h"
84
85 #include "GPU_buffers.h"
86
87 #include "atomic_ops.h"
88
89 #include "depsgraph_private.h"
90
91 static SpinLock threaded_update_lock;
92
93 void DAG_init(void)
94 {
95         BLI_spin_init(&threaded_update_lock);
96 }
97
98 void DAG_exit(void)
99 {
100         BLI_spin_end(&threaded_update_lock);
101 }
102
103 /* Queue and stack operations for dag traversal 
104  *
105  * the queue store a list of freenodes to avoid successive alloc/dealloc
106  */
107
108 DagNodeQueue *queue_create(int slots)
109 {
110         DagNodeQueue *queue;
111         DagNodeQueueElem *elem;
112         int i;
113         
114         queue = MEM_mallocN(sizeof(DagNodeQueue), "DAG queue");
115         queue->freenodes = MEM_mallocN(sizeof(DagNodeQueue), "DAG queue");
116         queue->count = 0;
117         queue->maxlevel = 0;
118         queue->first = queue->last = NULL;
119         elem = MEM_mallocN(sizeof(DagNodeQueueElem), "DAG queue elem3");
120         elem->node = NULL;
121         elem->next = NULL;
122         queue->freenodes->first = queue->freenodes->last = elem;
123         
124         for (i = 1; i < slots; i++) {
125                 elem = MEM_mallocN(sizeof(DagNodeQueueElem), "DAG queue elem4");
126                 elem->node = NULL;
127                 elem->next = NULL;
128                 queue->freenodes->last->next = elem;
129                 queue->freenodes->last = elem;
130         }
131         queue->freenodes->count = slots;
132         return queue;
133 }
134
135 void queue_raz(DagNodeQueue *queue)
136 {
137         DagNodeQueueElem *elem;
138         
139         elem = queue->first;
140         if (queue->freenodes->last)
141                 queue->freenodes->last->next = elem;
142         else
143                 queue->freenodes->first = queue->freenodes->last = elem;
144         
145         elem->node = NULL;
146         queue->freenodes->count++;
147         while (elem->next) {
148                 elem = elem->next;
149                 elem->node = NULL;
150                 queue->freenodes->count++;
151         }
152         queue->freenodes->last = elem;
153         queue->count = 0;
154 }
155
156 void queue_delete(DagNodeQueue *queue)
157 {
158         DagNodeQueueElem *elem;
159         DagNodeQueueElem *temp;
160         
161         elem = queue->first;
162         while (elem) {
163                 temp = elem;
164                 elem = elem->next;
165                 MEM_freeN(temp);
166         }
167         
168         elem = queue->freenodes->first;
169         while (elem) {
170                 temp = elem;
171                 elem = elem->next;
172                 MEM_freeN(temp);
173         }
174         
175         MEM_freeN(queue->freenodes);
176         MEM_freeN(queue);
177 }
178
179 /* insert in queue, remove in front */
180 void push_queue(DagNodeQueue *queue, DagNode *node)
181 {
182         DagNodeQueueElem *elem;
183         int i;
184
185         if (node == NULL) {
186                 fprintf(stderr, "pushing null node\n");
187                 return;
188         }
189         /*fprintf(stderr, "BFS push : %s %d\n", ((ID *) node->ob)->name, queue->count);*/
190
191         elem = queue->freenodes->first;
192         if (elem != NULL) {
193                 queue->freenodes->first = elem->next;
194                 if (queue->freenodes->last == elem) {
195                         queue->freenodes->last = NULL;
196                         queue->freenodes->first = NULL;
197                 }
198                 queue->freenodes->count--;
199         }
200         else { /* alllocating more */
201                 elem = MEM_mallocN(sizeof(DagNodeQueueElem), "DAG queue elem1");
202                 elem->node = NULL;
203                 elem->next = NULL;
204                 queue->freenodes->first = queue->freenodes->last = elem;
205
206                 for (i = 1; i < DAGQUEUEALLOC; i++) {
207                         elem = MEM_mallocN(sizeof(DagNodeQueueElem), "DAG queue elem2");
208                         elem->node = NULL;
209                         elem->next = NULL;
210                         queue->freenodes->last->next = elem;
211                         queue->freenodes->last = elem;
212                 }
213                 queue->freenodes->count = DAGQUEUEALLOC;
214                         
215                 elem = queue->freenodes->first;
216                 queue->freenodes->first = elem->next;
217         }
218         elem->next = NULL;
219         elem->node = node;
220         if (queue->last != NULL)
221                 queue->last->next = elem;
222         queue->last = elem;
223         if (queue->first == NULL) {
224                 queue->first = elem;
225         }
226         queue->count++;
227 }
228
229
230 /* insert in front, remove in front */
231 void push_stack(DagNodeQueue *queue, DagNode *node)
232 {
233         DagNodeQueueElem *elem;
234         int i;
235
236         elem = queue->freenodes->first;
237         if (elem != NULL) {
238                 queue->freenodes->first = elem->next;
239                 if (queue->freenodes->last == elem) {
240                         queue->freenodes->last = NULL;
241                         queue->freenodes->first = NULL;
242                 }
243                 queue->freenodes->count--;
244         }
245         else { /* alllocating more */
246                 elem = MEM_mallocN(sizeof(DagNodeQueueElem), "DAG queue elem1");
247                 elem->node = NULL;
248                 elem->next = NULL;
249                 queue->freenodes->first = queue->freenodes->last = elem;
250
251                 for (i = 1; i < DAGQUEUEALLOC; i++) {
252                         elem = MEM_mallocN(sizeof(DagNodeQueueElem), "DAG queue elem2");
253                         elem->node = NULL;
254                         elem->next = NULL;
255                         queue->freenodes->last->next = elem;
256                         queue->freenodes->last = elem;
257                 }
258                 queue->freenodes->count = DAGQUEUEALLOC;
259                         
260                 elem = queue->freenodes->first;
261                 queue->freenodes->first = elem->next;
262         }
263         elem->next = queue->first;
264         elem->node = node;
265         queue->first = elem;
266         if (queue->last == NULL)
267                 queue->last = elem;
268         queue->count++;
269 }
270
271
272 DagNode *pop_queue(DagNodeQueue *queue)
273 {
274         DagNodeQueueElem *elem;
275         DagNode *node;
276
277         elem = queue->first;
278         if (elem) {
279                 queue->first = elem->next;
280                 if (queue->last == elem) {
281                         queue->last = NULL;
282                         queue->first = NULL;
283                 }
284                 queue->count--;
285                 if (queue->freenodes->last)
286                         queue->freenodes->last->next = elem;
287                 queue->freenodes->last = elem;
288                 if (queue->freenodes->first == NULL)
289                         queue->freenodes->first = elem;
290                 node = elem->node;
291                 elem->node = NULL;
292                 elem->next = NULL;
293                 queue->freenodes->count++;
294                 return node;
295         }
296         else {
297                 fprintf(stderr, "return null\n");
298                 return NULL;
299         }
300 }
301
302 DagNode *get_top_node_queue(DagNodeQueue *queue)
303 {
304         return queue->first->node;
305 }
306
307 DagForest *dag_init(void)
308 {
309         DagForest *forest;
310         /* use callocN to init all zero */
311         forest = MEM_callocN(sizeof(DagForest), "DAG root");
312         forest->ugly_hack_sorry = true;
313         return forest;
314 }
315
316 /* isdata = object data... */
317 /* XXX this needs to be extended to be more flexible (so that not only objects are evaluated via depsgraph)... */
318 static void dag_add_driver_relation(AnimData *adt, DagForest *dag, DagNode *node, int isdata)
319 {
320         FCurve *fcu;
321         DagNode *node1;
322         
323         for (fcu = adt->drivers.first; fcu; fcu = fcu->next) {
324                 ChannelDriver *driver = fcu->driver;
325                 DriverVar *dvar;
326                 int isdata_fcu = (isdata) || (fcu->rna_path && strstr(fcu->rna_path, "modifiers["));
327                 
328                 /* loop over variables to get the target relationships */
329                 for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
330                         /* only used targets */
331                         DRIVER_TARGETS_USED_LOOPER(dvar) 
332                         {
333                                 if (dtar->id) {
334                                         /* FIXME: other data types need to be added here so that they can work! */
335                                         if (GS(dtar->id->name) == ID_OB) {
336                                                 Object *ob = (Object *)dtar->id;
337                                                 
338                                                 /* normal channel-drives-channel */
339                                                 node1 = dag_get_node(dag, dtar->id);
340                                                 
341                                                 /* check if bone... */
342                                                 if ((ob->type == OB_ARMATURE) &&
343                                                     ( ((dtar->rna_path) && strstr(dtar->rna_path, "pose.bones[")) ||
344                                                       ((dtar->flag & DTAR_FLAG_STRUCT_REF) && (dtar->pchan_name[0])) ))
345                                                 {
346                                                         dag_add_relation(dag, node1, node, isdata_fcu ? DAG_RL_DATA_DATA : DAG_RL_DATA_OB, "Driver");
347                                                 }
348                                                 /* check if ob data */
349                                                 else if (dtar->rna_path && strstr(dtar->rna_path, "data."))
350                                                         dag_add_relation(dag, node1, node, isdata_fcu ? DAG_RL_DATA_DATA : DAG_RL_DATA_OB, "Driver");
351                                                 /* normal */
352                                                 else
353                                                         dag_add_relation(dag, node1, node, isdata_fcu ? DAG_RL_OB_DATA : DAG_RL_OB_OB, "Driver");
354                                         }
355                                 }
356                         }
357                         DRIVER_TARGETS_LOOPER_END
358                 }
359         }
360 }
361
362 /* XXX: forward def for material driver handling... */
363 static void dag_add_material_driver_relations(DagForest *dag, DagNode *node, Material *ma);
364
365 /* recursive handling for shader nodetree drivers */
366 static void dag_add_shader_nodetree_driver_relations(DagForest *dag, DagNode *node, bNodeTree *ntree)
367 {
368         bNode *n;
369
370         /* nodetree itself */
371         if (ntree->adt) {
372                 dag_add_driver_relation(ntree->adt, dag, node, 1);
373         }
374         
375         /* nodetree's nodes... */
376         for (n = ntree->nodes.first; n; n = n->next) {
377                 if (n->id) {
378                         if (GS(n->id->name) == ID_MA) {
379                                 dag_add_material_driver_relations(dag, node, (Material *)n->id);
380                         }
381                         else if (n->type == NODE_GROUP) {
382                                 dag_add_shader_nodetree_driver_relations(dag, node, (bNodeTree *)n->id);
383                         }
384                 }
385         }
386 }
387
388 /* recursive handling for material drivers */
389 static void dag_add_material_driver_relations(DagForest *dag, DagNode *node, Material *ma)
390 {
391         /* Prevent infinite recursion by checking (and tagging the material) as having been visited 
392          * already (see build_dag()). This assumes ma->id.flag & LIB_DOIT isn't set by anything else
393          * in the meantime... [#32017]
394          */
395         if (ma->id.flag & LIB_DOIT)
396                 return;
397
398         ma->id.flag |= LIB_DOIT;
399         
400         /* material itself */
401         if (ma->adt)
402                 dag_add_driver_relation(ma->adt, dag, node, 1);
403
404         /* textures */
405         // TODO...
406         //dag_add_texture_driver_relations(DagForest *dag, DagNode *node, ID *id);
407
408         /* material's nodetree */
409         if (ma->nodetree)
410                 dag_add_shader_nodetree_driver_relations(dag, node, ma->nodetree);
411
412         ma->id.flag &= ~LIB_DOIT;
413 }
414
415 /* recursive handling for lamp drivers */
416 static void dag_add_lamp_driver_relations(DagForest *dag, DagNode *node, Lamp *la)
417 {
418         /* Prevent infinite recursion by checking (and tagging the lamp) as having been visited 
419          * already (see build_dag()). This assumes la->id.flag & LIB_DOIT isn't set by anything else
420          * in the meantime... [#32017]
421          */
422         if (la->id.flag & LIB_DOIT)
423                 return;
424
425         la->id.flag |= LIB_DOIT;
426         
427         /* lamp itself */
428         if (la->adt)
429                 dag_add_driver_relation(la->adt, dag, node, 1);
430
431         /* textures */
432         // TODO...
433         //dag_add_texture_driver_relations(DagForest *dag, DagNode *node, ID *id);
434
435         /* lamp's nodetree */
436         if (la->nodetree)
437                 dag_add_shader_nodetree_driver_relations(dag, node, la->nodetree);
438
439         la->id.flag &= ~LIB_DOIT;
440 }
441
442 static void check_and_create_collision_relation(DagForest *dag, Object *ob, DagNode *node, Object *ob1, int skip_forcefield, bool no_collision)
443 {
444         DagNode *node2;
445         if (ob1->pd && (ob1->pd->deflect || ob1->pd->forcefield) && (ob1 != ob)) {
446                 if ((skip_forcefield && ob1->pd->forcefield == skip_forcefield) || (no_collision && ob1->pd->forcefield == 0))
447                         return;
448                 node2 = dag_get_node(dag, ob1);
449                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Field Collision");
450         }
451 }
452
453 static void dag_add_collision_field_relation(DagForest *dag, Scene *scene, Object *ob, DagNode *node, int skip_forcefield, bool no_collision)
454 {
455         Base *base;
456         ParticleSystem *particle_system;
457
458         for (particle_system = ob->particlesystem.first;
459              particle_system;
460              particle_system = particle_system->next)
461         {
462                 EffectorWeights *effector_weights = particle_system->part->effector_weights;
463                 if (effector_weights->group) {
464                         GroupObject *group_object;
465
466                         for (group_object = effector_weights->group->gobject.first;
467                              group_object;
468                              group_object = group_object->next)
469                         {
470                                 if ((group_object->ob->lay & ob->lay)) {
471                                         check_and_create_collision_relation(dag, ob, node, group_object->ob, skip_forcefield, no_collision);
472                                 }
473                         }
474                 }
475         }
476
477         /* would be nice to have a list of colliders here
478          * so for now walk all objects in scene check 'same layer rule' */
479         for (base = scene->base.first; base; base = base->next) {
480                 if ((base->lay & ob->lay)) {
481                         Object *ob1 = base->object;
482                         check_and_create_collision_relation(dag, ob, node, ob1, skip_forcefield, no_collision);
483                 }
484         }
485 }
486
487 static void build_dag_object(DagForest *dag, DagNode *scenenode, Main *bmain, Scene *scene, Object *ob, int mask)
488 {
489         bConstraint *con;
490         DagNode *node;
491         DagNode *node2;
492         DagNode *node3;
493         Key *key;
494         ParticleSystem *psys;
495         int addtoroot = 1;
496         
497         node = dag_get_node(dag, ob);
498         
499         if ((ob->data) && (mask & DAG_RL_DATA)) {
500                 node2 = dag_get_node(dag, ob->data);
501                 dag_add_relation(dag, node, node2, DAG_RL_DATA, "Object-Data Relation");
502                 node2->first_ancestor = ob;
503                 node2->ancestor_count += 1;
504         }
505
506         /* also build a custom data mask for dependencies that need certain layers */
507         node->customdata_mask = 0;
508         
509         if (ob->type == OB_ARMATURE) {
510                 if (ob->pose) {
511                         bPoseChannel *pchan;
512                         
513                         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
514                                 for (con = pchan->constraints.first; con; con = con->next) {
515                                         const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
516                                         ListBase targets = {NULL, NULL};
517                                         bConstraintTarget *ct;
518                                         
519                                         if (cti && cti->get_constraint_targets) {
520                                                 cti->get_constraint_targets(con, &targets);
521                                                 
522                                                 for (ct = targets.first; ct; ct = ct->next) {
523                                                         if (ct->tar && ct->tar != ob) {
524                                                                 // fprintf(stderr, "armature %s target :%s\n", ob->id.name, target->id.name);
525                                                                 node3 = dag_get_node(dag, ct->tar);
526                                                                 
527                                                                 if (ct->subtarget[0]) {
528                                                                         dag_add_relation(dag, node3, node, DAG_RL_OB_DATA | DAG_RL_DATA_DATA, cti->name);
529                                                                         if (ct->tar->type == OB_MESH)
530                                                                                 node3->customdata_mask |= CD_MASK_MDEFORMVERT;
531                                                                 }
532                                                                 else if (ELEM(con->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO, CONSTRAINT_TYPE_SPLINEIK))
533                                                                         dag_add_relation(dag, node3, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, cti->name);
534                                                                 else
535                                                                         dag_add_relation(dag, node3, node, DAG_RL_OB_DATA, cti->name);
536                                                         }
537                                                 }
538                                                 
539                                                 if (cti->flush_constraint_targets)
540                                                         cti->flush_constraint_targets(con, &targets, 1);
541                                         }
542                                         
543                                 }
544                         }
545                 }
546         }
547         
548         /* driver dependencies, nla modifiers */
549 #if 0 // XXX old animation system
550         if (ob->nlastrips.first) {
551                 bActionStrip *strip;
552                 bActionChannel *chan;
553                 for (strip = ob->nlastrips.first; strip; strip = strip->next) {
554                         if (strip->modifiers.first) {
555                                 bActionModifier *amod;
556                                 for (amod = strip->modifiers.first; amod; amod = amod->next) {
557                                         if (amod->ob) {
558                                                 node2 = dag_get_node(dag, amod->ob);
559                                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "NLA Strip Modifier");
560                                         }
561                                 }
562                         }
563                 }
564         }
565 #endif // XXX old animation system
566         if (ob->adt)
567                 dag_add_driver_relation(ob->adt, dag, node, (ob->type == OB_ARMATURE));  // XXX isdata arg here doesn't give an accurate picture of situation
568                 
569         key = BKE_key_from_object(ob);
570         if (key && key->adt)
571                 dag_add_driver_relation(key->adt, dag, node, 1);
572
573         if (ob->modifiers.first) {
574                 ModifierData *md;
575                 
576                 for (md = ob->modifiers.first; md; md = md->next) {
577                         const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
578                         
579                         if (mti->updateDepgraph) mti->updateDepgraph(md, dag, bmain, scene, ob, node);
580                 }
581         }
582         if (ob->parent) {
583                 node2 = dag_get_node(dag, ob->parent);
584                 
585                 switch (ob->partype) {
586                         case PARSKEL:
587                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_OB, "Parent");
588                                 break;
589                         case PARVERT1: case PARVERT3:
590                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_OB | DAG_RL_OB_OB, "Vertex Parent");
591                                 node2->customdata_mask |= CD_MASK_ORIGINDEX;
592                                 break;
593                         case PARBONE:
594                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_OB | DAG_RL_OB_OB, "Bone Parent");
595                                 break;
596                         default:
597                                 if (ob->parent->type == OB_LATTICE)
598                                         dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_OB, "Lattice Parent");
599                                 else if (ob->parent->type == OB_CURVE) {
600                                         Curve *cu = ob->parent->data;
601                                         if (cu->flag & CU_PATH) 
602                                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_OB | DAG_RL_OB_OB, "Curve Parent");
603                                         else
604                                                 dag_add_relation(dag, node2, node, DAG_RL_OB_OB, "Curve Parent");
605                                 }
606                                 else
607                                         dag_add_relation(dag, node2, node, DAG_RL_OB_OB, "Parent");
608                                 break;
609                 }
610                 /* exception case: parent is duplivert */
611                 if (ob->type == OB_MBALL && (ob->parent->transflag & OB_DUPLIVERTS)) {
612                         dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_OB, "Duplivert");
613                 }
614                 
615                 addtoroot = 0;
616         }
617         if (ob->proxy) {
618                 node2 = dag_get_node(dag, ob->proxy);
619                 dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA | DAG_RL_OB_OB, "Proxy");
620                 /* inverted relation, so addtoroot shouldn't be set to zero */
621         }
622         
623         if (ob->transflag & OB_DUPLI) {
624                 if ((ob->transflag & OB_DUPLIGROUP) && ob->dup_group) {
625                         GroupObject *go;
626                         for (go = ob->dup_group->gobject.first; go; go = go->next) {
627                                 if (go->ob) {
628                                         node2 = dag_get_node(dag, go->ob);
629                                         /* node2 changes node1, this keeps animations updated in groups?? not logical? */
630                                         dag_add_relation(dag, node2, node, DAG_RL_OB_OB, "Dupligroup");
631                                 }
632                         }
633                 }
634         }
635
636         /* softbody collision  */
637         if ((ob->type == OB_MESH) || (ob->type == OB_CURVE) || (ob->type == OB_LATTICE)) {
638                 if (ob->particlesystem.first ||
639                     modifiers_isModifierEnabled(ob, eModifierType_Softbody) ||
640                     modifiers_isModifierEnabled(ob, eModifierType_Cloth) ||
641                     modifiers_isModifierEnabled(ob, eModifierType_DynamicPaint))
642                 {
643                         dag_add_collision_field_relation(dag, scene, ob, node, 0, false);  /* TODO: use effectorweight->group */
644                 }
645                 else if (modifiers_isModifierEnabled(ob, eModifierType_Smoke)) {
646                         dag_add_collision_field_relation(dag, scene, ob, node, PFIELD_SMOKEFLOW, false);
647                 }
648                 else if (ob->rigidbody_object) {
649                         dag_add_collision_field_relation(dag, scene, ob, node, 0, true);
650                 }
651         }
652         
653         /* object data drivers */
654         if (ob->data) {
655                 AnimData *adt = BKE_animdata_from_id((ID *)ob->data);
656                 if (adt)
657                         dag_add_driver_relation(adt, dag, node, 1);
658         }
659         
660         /* object type/data relationships */
661         switch (ob->type) {
662                 case OB_CAMERA:
663                 {
664                         Camera *cam = (Camera *)ob->data;
665                         
666                         if (cam->dof_ob) {
667                                 node2 = dag_get_node(dag, cam->dof_ob);
668                                 dag_add_relation(dag, node2, node, DAG_RL_OB_OB, "Camera DoF");
669                         }
670                         break;
671                 }
672                 case OB_MBALL: 
673                 {
674                         Object *mom = BKE_mball_basis_find(scene, ob);
675                         
676                         if (mom != ob) {
677                                 node2 = dag_get_node(dag, mom);
678                                 dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Metaball");  /* mom depends on children! */
679                         }
680                         break;
681                 }
682                 case OB_CURVE:
683                 case OB_FONT:
684                 {
685                         Curve *cu = ob->data;
686                         
687                         if (cu->bevobj) {
688                                 node2 = dag_get_node(dag, cu->bevobj);
689                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Curve Bevel");
690                         }
691                         if (cu->taperobj) {
692                                 node2 = dag_get_node(dag, cu->taperobj);
693                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Curve Taper");
694                         }
695                         if (ob->type == OB_FONT) {
696                                 /* Really rather dirty hack. needs to support font family to work
697                                  * reliably on render export.
698                                  *
699                                  * This totally mimics behavior of regular verts duplication with
700                                  * parenting. The only tricky thing here is to get list of objects
701                                  * used for the custom "font".
702                                  *
703                                  * This shouldn't harm so much because this code only runs on DAG
704                                  * rebuild and this feature is not that commonly used.
705                                  *
706                                  *                                                 - sergey -
707                                  */
708                                 if (cu->family[0] != '\n') {
709                                         ListBase *duplilist;
710                                         DupliObject *dob;
711                                         duplilist = object_duplilist(G.main->eval_ctx, scene, ob);
712                                         for (dob = duplilist->first; dob; dob = dob->next) {
713                                                 node2 = dag_get_node(dag, dob->ob);
714                                                 dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Object Font");
715                                         }
716                                         free_object_duplilist(duplilist);
717                                 }
718
719                                 if (cu->textoncurve) {
720                                         node2 = dag_get_node(dag, cu->textoncurve);
721                                         /* Text on curve requires path to be evaluated for the target curve. */
722                                         node2->eval_flags |= DAG_EVAL_NEED_CURVE_PATH;
723                                         dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Texture On Curve");
724                                 }
725                         }
726                         break;
727                 }
728         }
729         
730         /* material drivers */
731         if (ob->totcol) {
732                 int a;
733                 
734                 for (a = 1; a <= ob->totcol; a++) {
735                         Material *ma = give_current_material(ob, a);
736                         
737                         if (ma) {
738                                 /* recursively figure out if there are drivers, and hook these up to this object */
739                                 dag_add_material_driver_relations(dag, node, ma);
740                         }
741                 }
742         }
743         else if (ob->type == OB_LAMP) {
744                 dag_add_lamp_driver_relations(dag, node, ob->data);
745         }
746         
747         /* particles */
748         psys = ob->particlesystem.first;
749         if (psys) {
750                 GroupObject *go;
751
752                 for (; psys; psys = psys->next) {
753                         BoidRule *rule = NULL;
754                         BoidState *state = NULL;
755                         ParticleSettings *part = psys->part;
756                         ListBase *effectors = NULL;
757                         EffectorCache *eff;
758
759                         dag_add_relation(dag, node, node, DAG_RL_OB_DATA, "Particle-Object Relation");
760
761                         if (!psys_check_enabled(ob, psys))
762                                 continue;
763
764                         if (ELEM(part->phystype, PART_PHYS_KEYED, PART_PHYS_BOIDS)) {
765                                 ParticleTarget *pt = psys->targets.first;
766
767                                 for (; pt; pt = pt->next) {
768                                         if (pt->ob && BLI_findlink(&pt->ob->particlesystem, pt->psys - 1)) {
769                                                 node2 = dag_get_node(dag, pt->ob);
770                                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Particle Targets");
771                                         }
772                                 }
773                         }
774
775                         if (part->ren_as == PART_DRAW_OB && part->dup_ob) {
776                                 node2 = dag_get_node(dag, part->dup_ob);
777                                 /* note that this relation actually runs in the wrong direction, the problem
778                                  * is that dupli system all have this (due to parenting), and the render
779                                  * engine instancing assumes particular ordering of objects in list */
780                                 dag_add_relation(dag, node, node2, DAG_RL_OB_OB, "Particle Object Visualization");
781                                 if (part->dup_ob->type == OB_MBALL)
782                                         dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA, "Particle Object Visualization");
783                         }
784
785                         if (part->ren_as == PART_DRAW_GR && part->dup_group) {
786                                 for (go = part->dup_group->gobject.first; go; go = go->next) {
787                                         node2 = dag_get_node(dag, go->ob);
788                                         dag_add_relation(dag, node2, node, DAG_RL_OB_OB, "Particle Group Visualization");
789                                 }
790                         }
791
792                         effectors = pdInitEffectors(scene, ob, psys, part->effector_weights, false);
793
794                         if (effectors) {
795                                 for (eff = effectors->first; eff; eff = eff->next) {
796                                         if (eff->psys) {
797                                                 node2 = dag_get_node(dag, eff->ob);
798                                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Particle Field");
799                                         }
800                                 }
801                         }
802
803                         pdEndEffectors(&effectors);
804
805                         if (part->boids) {
806                                 for (state = part->boids->states.first; state; state = state->next) {
807                                         for (rule = state->rules.first; rule; rule = rule->next) {
808                                                 Object *ruleob = NULL;
809                                                 if (rule->type == eBoidRuleType_Avoid)
810                                                         ruleob = ((BoidRuleGoalAvoid *)rule)->ob;
811                                                 else if (rule->type == eBoidRuleType_FollowLeader)
812                                                         ruleob = ((BoidRuleFollowLeader *)rule)->ob;
813
814                                                 if (ruleob) {
815                                                         node2 = dag_get_node(dag, ruleob);
816                                                         dag_add_relation(dag, node2, node, DAG_RL_OB_DATA, "Boid Rule");
817                                                 }
818                                         }
819                                 }
820                         }
821                 }
822         }
823         
824         /* object constraints */
825         for (con = ob->constraints.first; con; con = con->next) {
826                 const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
827                 ListBase targets = {NULL, NULL};
828                 bConstraintTarget *ct;
829                 
830                 if (!cti)
831                         continue;
832
833                 /* special case for camera tracking -- it doesn't use targets to define relations */
834                 if (ELEM(cti->type, CONSTRAINT_TYPE_FOLLOWTRACK, CONSTRAINT_TYPE_CAMERASOLVER, CONSTRAINT_TYPE_OBJECTSOLVER)) {
835                         int depends_on_camera = 0;
836
837                         if (cti->type == CONSTRAINT_TYPE_FOLLOWTRACK) {
838                                 bFollowTrackConstraint *data = (bFollowTrackConstraint *)con->data;
839
840                                 if ((data->clip || data->flag & FOLLOWTRACK_ACTIVECLIP) && data->track[0])
841                                         depends_on_camera = 1;
842
843                                 if (data->depth_ob) {
844                                         node2 = dag_get_node(dag, data->depth_ob);
845                                         dag_add_relation(dag, node2, node, DAG_RL_DATA_OB | DAG_RL_OB_OB, cti->name);
846                                 }
847                         }
848                         else if (cti->type == CONSTRAINT_TYPE_OBJECTSOLVER)
849                                 depends_on_camera = 1;
850
851                         if (depends_on_camera && scene->camera) {
852                                 node2 = dag_get_node(dag, scene->camera);
853                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_OB | DAG_RL_OB_OB, cti->name);
854                         }
855
856                         dag_add_relation(dag, scenenode, node, DAG_RL_SCENE, "Scene Relation");
857                         addtoroot = 0;
858                 }
859                 else if (cti->get_constraint_targets) {
860                         cti->get_constraint_targets(con, &targets);
861                         
862                         for (ct = targets.first; ct; ct = ct->next) {
863                                 Object *obt;
864                                 
865                                 if (ct->tar)
866                                         obt = ct->tar;
867                                 else
868                                         continue;
869                                 
870                                 node2 = dag_get_node(dag, obt);
871                                 if (ELEM(con->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO))
872                                         dag_add_relation(dag, node2, node, DAG_RL_DATA_OB | DAG_RL_OB_OB, cti->name);
873                                 else {
874                                         if (ELEM(obt->type, OB_ARMATURE, OB_MESH, OB_LATTICE) && (ct->subtarget[0])) {
875                                                 dag_add_relation(dag, node2, node, DAG_RL_DATA_OB | DAG_RL_OB_OB, cti->name);
876                                                 if (obt->type == OB_MESH)
877                                                         node2->customdata_mask |= CD_MASK_MDEFORMVERT;
878                                         }
879                                         else
880                                                 dag_add_relation(dag, node2, node, DAG_RL_OB_OB, cti->name);
881                                 }
882                                 addtoroot = 0;
883                         }
884                         
885                         if (cti->flush_constraint_targets)
886                                 cti->flush_constraint_targets(con, &targets, 1);
887                 }
888         }
889
890         if (addtoroot == 1)
891                 dag_add_relation(dag, scenenode, node, DAG_RL_SCENE, "Scene Relation");
892 }
893
894 static void build_dag_group(DagForest *dag, DagNode *scenenode, Main *bmain, Scene *scene, Group *group, short mask)
895 {
896         GroupObject *go;
897
898         if (group->id.flag & LIB_DOIT)
899                 return;
900         
901         group->id.flag |= LIB_DOIT;
902
903         for (go = group->gobject.first; go; go = go->next) {
904                 build_dag_object(dag, scenenode, bmain, scene, go->ob, mask);
905                 if (go->ob->dup_group)
906                         build_dag_group(dag, scenenode, bmain, scene, go->ob->dup_group, mask);
907         }
908 }
909
910 DagForest *build_dag(Main *bmain, Scene *sce, short mask)
911 {
912         Base *base;
913         Object *ob;
914         DagNode *node;
915         DagNode *scenenode;
916         DagForest *dag;
917         DagAdjList *itA;
918
919         dag = sce->theDag;
920         if (dag)
921                 free_forest(dag);
922         else {
923                 dag = dag_init();
924                 sce->theDag = dag;
925         }
926         
927         /* clear "LIB_DOIT" flag from all materials, to prevent infinite recursion problems later [#32017] */
928         BKE_main_id_tag_idcode(bmain, ID_MA, false);
929         BKE_main_id_tag_idcode(bmain, ID_LA, false);
930         BKE_main_id_tag_idcode(bmain, ID_GR, false);
931         
932         /* add base node for scene. scene is always the first node in DAG */
933         scenenode = dag_add_node(dag, sce);
934         
935         /* add current scene objects */
936         for (base = sce->base.first; base; base = base->next) {
937                 ob = base->object;
938                 
939                 build_dag_object(dag, scenenode, bmain, sce, ob, mask);
940                 if (ob->proxy)
941                         build_dag_object(dag, scenenode, bmain, sce, ob->proxy, mask);
942                 if (ob->dup_group) 
943                         build_dag_group(dag, scenenode, bmain, sce, ob->dup_group, mask);
944         }
945         
946         BKE_main_id_tag_idcode(bmain, ID_GR, false);
947         
948         /* Now all relations were built, but we need to solve 1 exceptional case;
949          * When objects have multiple "parents" (for example parent + constraint working on same object)
950          * the relation type has to be synced. One of the parents can change, and should give same event to child */
951         
952         /* nodes were callocced, so we can use node->color for temporal storage */
953         for (node = sce->theDag->DagNode.first; node; node = node->next) {
954                 if (node->type == ID_OB) {
955                         for (itA = node->child; itA; itA = itA->next) {
956                                 if (itA->node->type == ID_OB) {
957                                         itA->node->color |= itA->type;
958                                 }
959                         }
960
961                         /* also flush custom data mask */
962                         ((Object *)node->ob)->customdata_mask = node->customdata_mask;
963
964                         if (node->parent == NULL) {
965                                 dag_add_relation(dag, scenenode, node, DAG_RL_SCENE, "Scene Relation");
966                         }
967                 }
968         }
969         /* now set relations equal, so that when only one parent changes, the correct recalcs are found */
970         for (node = sce->theDag->DagNode.first; node; node = node->next) {
971                 if (node->type == ID_OB) {
972                         for (itA = node->child; itA; itA = itA->next) {
973                                 if (itA->node->type == ID_OB) {
974                                         itA->type |= itA->node->color;
975                                 }
976                         }
977                 }
978         }
979         
980         /* cycle detection and solving */
981         // solve_cycles(dag);
982         
983         return dag;
984 }
985
986
987 void free_forest(DagForest *Dag) 
988 {  /* remove all nodes and deps */
989         DagNode *tempN;
990         DagAdjList *tempA;
991         DagAdjList *itA;
992         DagNode *itN = Dag->DagNode.first;
993         
994         while (itN) {
995                 itA = itN->child;
996                 while (itA) {
997                         tempA = itA;
998                         itA = itA->next;
999                         MEM_freeN(tempA);
1000                 }
1001                 
1002                 itA = itN->parent;
1003                 while (itA) {
1004                         tempA = itA;
1005                         itA = itA->next;
1006                         MEM_freeN(tempA);
1007                 }
1008                 
1009                 tempN = itN;
1010                 itN = itN->next;
1011                 MEM_freeN(tempN);
1012         }
1013
1014         BLI_ghash_free(Dag->nodeHash, NULL, NULL);
1015         Dag->nodeHash = NULL;
1016         Dag->DagNode.first = NULL;
1017         Dag->DagNode.last = NULL;
1018         Dag->numNodes = 0;
1019
1020 }
1021
1022 DagNode *dag_find_node(DagForest *forest, void *fob)
1023 {
1024         if (forest->nodeHash)
1025                 return BLI_ghash_lookup(forest->nodeHash, fob);
1026
1027         return NULL;
1028 }
1029
1030 static int dag_print_dependencies = 0;  /* debugging */
1031
1032 /* no checking of existence, use dag_find_node first or dag_get_node */
1033 DagNode *dag_add_node(DagForest *forest, void *fob)
1034 {
1035         DagNode *node;
1036                 
1037         node = MEM_callocN(sizeof(DagNode), "DAG node");
1038         if (node) {
1039                 node->ob = fob;
1040                 node->color = DAG_WHITE;
1041
1042                 if (forest->ugly_hack_sorry) node->type = GS(((ID *) fob)->name);  /* sorry, done for pose sorting */
1043                 if (forest->numNodes) {
1044                         ((DagNode *) forest->DagNode.last)->next = node;
1045                         forest->DagNode.last = node;
1046                         forest->numNodes++;
1047                 }
1048                 else {
1049                         forest->DagNode.last = node;
1050                         forest->DagNode.first = node;
1051                         forest->numNodes = 1;
1052                 }
1053
1054                 if (!forest->nodeHash)
1055                         forest->nodeHash = BLI_ghash_ptr_new("dag_add_node gh");
1056                 BLI_ghash_insert(forest->nodeHash, fob, node);
1057         }
1058
1059         return node;
1060 }
1061
1062 DagNode *dag_get_node(DagForest *forest, void *fob)
1063 {
1064         DagNode *node;
1065         
1066         node = dag_find_node(forest, fob);
1067         if (!node) 
1068                 node = dag_add_node(forest, fob);
1069         return node;
1070 }
1071
1072
1073
1074 DagNode *dag_get_sub_node(DagForest *forest, void *fob)
1075 {
1076         DagNode *node;
1077         DagAdjList *mainchild, *prev = NULL;
1078         
1079         mainchild = ((DagNode *) forest->DagNode.first)->child;
1080         /* remove from first node (scene) adj list if present */
1081         while (mainchild) {
1082                 if (mainchild->node == fob) {
1083                         if (prev) {
1084                                 prev->next = mainchild->next;
1085                                 MEM_freeN(mainchild);
1086                                 break;
1087                         }
1088                         else {
1089                                 ((DagNode *) forest->DagNode.first)->child = mainchild->next;
1090                                 MEM_freeN(mainchild);
1091                                 break;
1092                         }
1093                 }
1094                 prev = mainchild;
1095                 mainchild = mainchild->next;
1096         }
1097         node = dag_find_node(forest, fob);
1098         if (!node) 
1099                 node = dag_add_node(forest, fob);
1100         return node;
1101 }
1102
1103 static void dag_add_parent_relation(DagForest *UNUSED(forest), DagNode *fob1, DagNode *fob2, short rel, const char *name) 
1104 {
1105         DagAdjList *itA = fob2->parent;
1106         
1107         while (itA) { /* search if relation exist already */
1108                 if (itA->node == fob1) {
1109                         itA->type |= rel;
1110                         itA->count += 1;
1111                         return;
1112                 }
1113                 itA = itA->next;
1114         }
1115         /* create new relation and insert at head. MALLOC alert! */
1116         itA = MEM_mallocN(sizeof(DagAdjList), "DAG adj list");
1117         itA->node = fob1;
1118         itA->type = rel;
1119         itA->count = 1;
1120         itA->next = fob2->parent;
1121         itA->name = name;
1122         fob2->parent = itA;
1123 }
1124
1125 void dag_add_relation(DagForest *forest, DagNode *fob1, DagNode *fob2, short rel, const char *name) 
1126 {
1127         DagAdjList *itA = fob1->child;
1128         
1129         /* parent relation is for cycle checking */
1130         dag_add_parent_relation(forest, fob1, fob2, rel, name);
1131
1132         while (itA) { /* search if relation exist already */
1133                 if (itA->node == fob2) {
1134                         itA->type |= rel;
1135                         itA->count += 1;
1136                         return;
1137                 }
1138                 itA = itA->next;
1139         }
1140         /* create new relation and insert at head. MALLOC alert! */
1141         itA = MEM_mallocN(sizeof(DagAdjList), "DAG adj list");
1142         itA->node = fob2;
1143         itA->type = rel;
1144         itA->count = 1;
1145         itA->next = fob1->child;
1146         itA->name = name;
1147         fob1->child = itA;
1148 }
1149
1150 static const char *dag_node_name(DagForest *dag, DagNode *node)
1151 {
1152         if (node->ob == NULL)
1153                 return "null";
1154         else if (dag->ugly_hack_sorry)
1155                 return ((ID *)(node->ob))->name + 2;
1156         else
1157                 return ((bPoseChannel *)(node->ob))->name;
1158 }
1159
1160 static void dag_node_print_dependencies(DagForest *dag, DagNode *node)
1161 {
1162         DagAdjList *itA;
1163
1164         printf("%s depends on:\n", dag_node_name(dag, node));
1165
1166         for (itA = node->parent; itA; itA = itA->next)
1167                 printf("  %s through %s\n", dag_node_name(dag, itA->node), itA->name);
1168         printf("\n");
1169 }
1170
1171 static int dag_node_print_dependency_recurs(DagForest *dag, DagNode *node, DagNode *endnode)
1172 {
1173         DagAdjList *itA;
1174
1175         if (node->color == DAG_BLACK)
1176                 return 0;
1177
1178         node->color = DAG_BLACK;
1179
1180         if (node == endnode)
1181                 return 1;
1182
1183         for (itA = node->parent; itA; itA = itA->next) {
1184                 if (dag_node_print_dependency_recurs(dag, itA->node, endnode)) {
1185                         printf("  %s depends on %s through %s.\n", dag_node_name(dag, node), dag_node_name(dag, itA->node), itA->name);
1186                         return 1;
1187                 }
1188         }
1189
1190         return 0;
1191 }
1192
1193 static void dag_node_print_dependency_cycle(DagForest *dag, DagNode *startnode, DagNode *endnode, const char *name)
1194 {
1195         DagNode *node;
1196
1197         for (node = dag->DagNode.first; node; node = node->next)
1198                 node->color = DAG_WHITE;
1199
1200         printf("  %s depends on %s through %s.\n", dag_node_name(dag, endnode), dag_node_name(dag, startnode), name);
1201         dag_node_print_dependency_recurs(dag, startnode, endnode);
1202         printf("\n");
1203 }
1204
1205 static int dag_node_recurs_level(DagNode *node, int level)
1206 {
1207         DagAdjList *itA;
1208         int newlevel;
1209
1210         node->color = DAG_BLACK; /* done */
1211         newlevel = ++level;
1212         
1213         for (itA = node->parent; itA; itA = itA->next) {
1214                 if (itA->node->color == DAG_WHITE) {
1215                         itA->node->ancestor_count = dag_node_recurs_level(itA->node, level);
1216                         newlevel = MAX2(newlevel, level + itA->node->ancestor_count);
1217                 }
1218                 else
1219                         newlevel = MAX2(newlevel, level + itA->node->ancestor_count);
1220         }
1221         
1222         return newlevel;
1223 }
1224
1225 static void dag_check_cycle(DagForest *dag)
1226 {
1227         DagNode *node;
1228         DagAdjList *itA;
1229
1230         dag->is_acyclic = true;
1231
1232         /* debugging print */
1233         if (dag_print_dependencies)
1234                 for (node = dag->DagNode.first; node; node = node->next)
1235                         dag_node_print_dependencies(dag, node);
1236
1237         /* tag nodes unchecked */
1238         for (node = dag->DagNode.first; node; node = node->next)
1239                 node->color = DAG_WHITE;
1240         
1241         for (node = dag->DagNode.first; node; node = node->next) {
1242                 if (node->color == DAG_WHITE) {
1243                         node->ancestor_count = dag_node_recurs_level(node, 0);
1244                 }
1245         }
1246         
1247         /* check relations, and print errors */
1248         for (node = dag->DagNode.first; node; node = node->next) {
1249                 for (itA = node->parent; itA; itA = itA->next) {
1250                         if (itA->node->ancestor_count > node->ancestor_count) {
1251                                 if (node->ob && itA->node->ob) {
1252                                         dag->is_acyclic = false;
1253                                         printf("Dependency cycle detected:\n");
1254                                         dag_node_print_dependency_cycle(dag, itA->node, node, itA->name);
1255                                 }
1256                         }
1257                 }
1258         }
1259
1260         /* parent relations are only needed for cycle checking, so free now */
1261         for (node = dag->DagNode.first; node; node = node->next) {
1262                 while (node->parent) {
1263                         itA = node->parent->next;
1264                         MEM_freeN(node->parent);
1265                         node->parent = itA;
1266                 }
1267         }
1268 }
1269
1270 /* debug test functions */
1271
1272 void graph_print_queue(DagNodeQueue *nqueue)
1273 {       
1274         DagNodeQueueElem *queueElem;
1275         
1276         queueElem = nqueue->first;
1277         while (queueElem) {
1278                 fprintf(stderr, "** %s %i %i-%i ", ((ID *) queueElem->node->ob)->name, queueElem->node->color, queueElem->node->DFS_dvtm, queueElem->node->DFS_fntm);
1279                 queueElem = queueElem->next;
1280         }
1281         fprintf(stderr, "\n");
1282 }
1283
1284 void graph_print_queue_dist(DagNodeQueue *nqueue)
1285 {       
1286         DagNodeQueueElem *queueElem;
1287         int count;
1288         
1289         queueElem = nqueue->first;
1290         count = 0;
1291         while (queueElem) {
1292                 fprintf(stderr, "** %25s %2.2i-%2.2i ", ((ID *) queueElem->node->ob)->name, queueElem->node->DFS_dvtm, queueElem->node->DFS_fntm);
1293                 while (count < queueElem->node->DFS_dvtm - 1) { fputc(' ', stderr); count++; }
1294                 fputc('|', stderr);
1295                 while (count < queueElem->node->DFS_fntm - 2) { fputc('-', stderr); count++; }
1296                 fputc('|', stderr);
1297                 fputc('\n', stderr);
1298                 count = 0;
1299                 queueElem = queueElem->next;
1300         }
1301         fprintf(stderr, "\n");
1302 }
1303
1304 void graph_print_adj_list(DagForest *dag)
1305 {
1306         DagNode *node;
1307         DagAdjList *itA;
1308         
1309         node = dag->DagNode.first;
1310         while (node) {
1311                 fprintf(stderr, "node : %s col: %i", ((ID *) node->ob)->name, node->color);
1312                 itA = node->child;
1313                 while (itA) {
1314                         fprintf(stderr, "-- %s ", ((ID *) itA->node->ob)->name);
1315                         
1316                         itA = itA->next;
1317                 }
1318                 fprintf(stderr, "\n");
1319                 node = node->next;
1320         }
1321 }
1322
1323 /* ************************ API *********************** */
1324
1325 /* mechanism to allow editors to be informed of depsgraph updates,
1326  * to do their own updates based on changes... */
1327 static void (*EditorsUpdateIDCb)(Main *bmain, ID *id) = NULL;
1328 static void (*EditorsUpdateSceneCb)(Main *bmain, Scene *scene, int updated) = NULL;
1329
1330 void DAG_editors_update_cb(void (*id_func)(Main *bmain, ID *id), void (*scene_func)(Main *bmain, Scene *scene, int updated))
1331 {
1332         EditorsUpdateIDCb = id_func;
1333         EditorsUpdateSceneCb = scene_func;
1334 }
1335
1336 static void dag_editors_id_update(Main *bmain, ID *id)
1337 {
1338         if (EditorsUpdateIDCb)
1339                 EditorsUpdateIDCb(bmain, id);
1340 }
1341
1342 static void dag_editors_scene_update(Main *bmain, Scene *scene, int updated)
1343 {
1344         if (EditorsUpdateSceneCb)
1345                 EditorsUpdateSceneCb(bmain, scene, updated);
1346 }
1347
1348 /* groups with objects in this scene need to be put in the right order as well */
1349 static void scene_sort_groups(Main *bmain, Scene *sce)
1350 {
1351         Base *base;
1352         Group *group;
1353         GroupObject *go;
1354         Object *ob;
1355         
1356         /* test; are group objects all in this scene? */
1357         for (ob = bmain->object.first; ob; ob = ob->id.next) {
1358                 ob->id.flag &= ~LIB_DOIT;
1359                 ob->id.newid = NULL; /* newid abuse for GroupObject */
1360         }
1361         for (base = sce->base.first; base; base = base->next)
1362                 base->object->id.flag |= LIB_DOIT;
1363         
1364         for (group = bmain->group.first; group; group = group->id.next) {
1365                 for (go = group->gobject.first; go; go = go->next) {
1366                         if ((go->ob->id.flag & LIB_DOIT) == 0)
1367                                 break;
1368                 }
1369                 /* this group is entirely in this scene */
1370                 if (go == NULL) {
1371                         ListBase listb = {NULL, NULL};
1372                         
1373                         for (go = group->gobject.first; go; go = go->next)
1374                                 go->ob->id.newid = (ID *)go;
1375                         
1376                         /* in order of sorted bases we reinsert group objects */
1377                         for (base = sce->base.first; base; base = base->next) {
1378                                 
1379                                 if (base->object->id.newid) {
1380                                         go = (GroupObject *)base->object->id.newid;
1381                                         base->object->id.newid = NULL;
1382                                         BLI_remlink(&group->gobject, go);
1383                                         BLI_addtail(&listb, go);
1384                                 }
1385                         }
1386                         /* copy the newly sorted listbase */
1387                         group->gobject = listb;
1388                 }
1389         }
1390 }
1391
1392 /* free the depency graph */
1393 static void dag_scene_free(Scene *sce)
1394 {
1395         if (sce->theDag) {
1396                 free_forest(sce->theDag);
1397                 MEM_freeN(sce->theDag);
1398                 sce->theDag = NULL;
1399         }
1400 }
1401
1402 /* Chech whether object data needs to be evaluated before it
1403  * might be used by others.
1404  *
1405  * Means that mesh object needs to have proper derivedFinal,
1406  * curves-typed objects are to have proper curve cache.
1407  *
1408  * Other objects or objects which are tagged for data update are
1409  * not considered to be in need of evaluation.
1410  */
1411 static bool check_object_needs_evaluation(Object *object)
1412 {
1413         if (object->recalc & OB_RECALC_ALL) {
1414                 /* Object is tagged for update anyway, no need to re-tag it. */
1415                 return false;
1416         }
1417
1418         if (object->type == OB_MESH) {
1419                 return object->derivedFinal == NULL;
1420         }
1421         else if (ELEM(object->type, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL, OB_LATTICE)) {
1422                 return object->curve_cache == NULL;
1423         }
1424
1425         return false;
1426 }
1427
1428 /* Check whether object data is tagged for update. */
1429 static bool check_object_tagged_for_update(Object *object)
1430 {
1431         if (object->recalc & OB_RECALC_ALL) {
1432                 return true;
1433         }
1434
1435         if (ELEM(object->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL, OB_LATTICE)) {
1436                 ID *data_id = object->data;
1437                 return (data_id->flag & (LIB_ID_RECALC_DATA | LIB_ID_RECALC)) != 0;
1438         }
1439
1440         return false;
1441 }
1442
1443 /* Flush changes from tagged objects in the scene to their
1444  * dependencies which are not evaluated yet.
1445  *
1446  * This is needed to ensure all the dependencies are met
1447  * before objects gets handled by object_handle_update(),
1448  *
1449  * This is needed when visible layers are changed or changing
1450  * scene graph layout which involved usage of objects which
1451  * aren't in the scene or weren't visible yet.
1452  */
1453 static void dag_invisible_dependencies_flush(Scene *scene)
1454 {
1455         DagNode *root_node = scene->theDag->DagNode.first, *node;
1456         DagNodeQueue *queue;
1457
1458         for (node = root_node; node != NULL; node = node->next) {
1459                 node->color = DAG_WHITE;
1460         }
1461
1462         queue = queue_create(DAGQUEUEALLOC);
1463
1464         for (node = root_node; node != NULL; node = node->next) {
1465                 if (node->color == DAG_WHITE) {
1466                         push_stack(queue, node);
1467                         node->color = DAG_GRAY;
1468
1469                         while (queue->count) {
1470                                 DagNode *current_node = get_top_node_queue(queue);
1471                                 DagAdjList *itA;
1472                                 bool skip = false;
1473
1474                                 for (itA = current_node->child; itA; itA = itA->next) {
1475                                         if (itA->node->color == DAG_WHITE) {
1476                                                 itA->node->color = DAG_GRAY;
1477                                                 push_stack(queue, itA->node);
1478                                                 skip = true;
1479                                                 break;
1480                                         }
1481                                 }
1482
1483                                 if (!skip) {
1484                                         current_node = pop_queue(queue);
1485
1486                                         if (current_node->type == ID_OB) {
1487                                                 Object *current_object = current_node->ob;
1488                                                 if (check_object_needs_evaluation(current_object)) {
1489                                                         for (itA = current_node->child; itA; itA = itA->next) {
1490                                                                 if (itA->node->type == ID_OB) {
1491                                                                         Object *object = itA->node->ob;
1492                                                                         if (check_object_tagged_for_update(object)) {
1493                                                                                 current_object->recalc |= OB_RECALC_OB | OB_RECALC_DATA;
1494                                                                         }
1495                                                                 }
1496                                                         }
1497                                                 }
1498                                         }
1499                                         node->color = DAG_BLACK;
1500                                 }
1501                         }
1502                 }
1503         }
1504
1505         queue_delete(queue);
1506 }
1507
1508 static void dag_invisible_dependencies_check_flush(Main *bmain, Scene *scene)
1509 {
1510         if (DAG_id_type_tagged(bmain, ID_OB) ||
1511             DAG_id_type_tagged(bmain, ID_ME) ||  /* Mesh */
1512             DAG_id_type_tagged(bmain, ID_CU) ||  /* Curve */
1513             DAG_id_type_tagged(bmain, ID_MB) ||  /* MetaBall */
1514             DAG_id_type_tagged(bmain, ID_LT))    /* Lattice */
1515         {
1516                 dag_invisible_dependencies_flush(scene);
1517         }
1518 }
1519
1520 /* sort the base list on dependency order */
1521 static void dag_scene_build(Main *bmain, Scene *sce)
1522 {
1523         DagNode *node, *rootnode;
1524         DagNodeQueue *nqueue;
1525         DagAdjList *itA;
1526         int time;
1527         int skip = 0;
1528         ListBase tempbase;
1529         Base *base;
1530
1531         BLI_listbase_clear(&tempbase);
1532         
1533         build_dag(bmain, sce, DAG_RL_ALL_BUT_DATA);
1534         
1535         dag_check_cycle(sce->theDag);
1536
1537         nqueue = queue_create(DAGQUEUEALLOC);
1538         
1539         for (node = sce->theDag->DagNode.first; node; node = node->next) {
1540                 node->color = DAG_WHITE;
1541         }
1542         
1543         time = 1;
1544         
1545         rootnode = sce->theDag->DagNode.first;
1546         rootnode->color = DAG_GRAY;
1547         time++;
1548         push_stack(nqueue, rootnode);
1549         
1550         while (nqueue->count) {
1551                 
1552                 skip = 0;
1553                 node = get_top_node_queue(nqueue);
1554                 
1555                 itA = node->child;
1556                 while (itA != NULL) {
1557                         if (itA->node->color == DAG_WHITE) {
1558                                 itA->node->DFS_dvtm = time;
1559                                 itA->node->color = DAG_GRAY;
1560                                 
1561                                 time++;
1562                                 push_stack(nqueue, itA->node);
1563                                 skip = 1;
1564                                 break;
1565                         }
1566                         itA = itA->next;
1567                 }
1568                 
1569                 if (!skip) {
1570                         if (node) {
1571                                 node = pop_queue(nqueue);
1572                                 if (node->ob == sce)  /* we are done */
1573                                         break;
1574                                 node->color = DAG_BLACK;
1575                                 
1576                                 time++;
1577                                 base = sce->base.first;
1578                                 while (base && base->object != node->ob)
1579                                         base = base->next;
1580                                 if (base) {
1581                                         BLI_remlink(&sce->base, base);
1582                                         BLI_addhead(&tempbase, base);
1583                                 }
1584                         }
1585                 }
1586         }
1587         
1588         /* temporal correction for circular dependencies */
1589         base = sce->base.first;
1590         while (base) {
1591                 BLI_remlink(&sce->base, base);
1592                 BLI_addhead(&tempbase, base);
1593                 //if (G.debug & G_DEBUG)
1594                 printf("cyclic %s\n", base->object->id.name);
1595                 base = sce->base.first;
1596         }
1597         
1598         sce->base = tempbase;
1599         queue_delete(nqueue);
1600         
1601         /* all groups with objects in this scene gets resorted too */
1602         scene_sort_groups(bmain, sce);
1603         
1604         if (G.debug & G_DEBUG) {
1605                 printf("\nordered\n");
1606                 for (base = sce->base.first; base; base = base->next) {
1607                         printf(" %s\n", base->object->id.name);
1608                 }
1609         }
1610
1611         /* temporal...? */
1612         sce->recalc |= SCE_PRV_CHANGED; /* test for 3d preview */
1613
1614         /* Make sure that new dependencies which came from invisble layers
1615          * are tagged for update (if they're needed for objects which were
1616          * tagged for update).
1617          */
1618         dag_invisible_dependencies_check_flush(bmain, sce);
1619 }
1620
1621 /* clear all dependency graphs */
1622 void DAG_relations_tag_update(Main *bmain)
1623 {
1624         Scene *sce;
1625
1626         for (sce = bmain->scene.first; sce; sce = sce->id.next)
1627                 dag_scene_free(sce);
1628 }
1629
1630 /* rebuild dependency graph only for a given scene */
1631 void DAG_scene_relations_rebuild(Main *bmain, Scene *sce)
1632 {
1633         dag_scene_free(sce);
1634         DAG_scene_relations_update(bmain, sce);
1635 }
1636
1637 /* create dependency graph if it was cleared or didn't exist yet */
1638 void DAG_scene_relations_update(Main *bmain, Scene *sce)
1639 {
1640         if (!sce->theDag)
1641                 dag_scene_build(bmain, sce);
1642 }
1643
1644 void DAG_scene_free(Scene *sce)
1645 {
1646         if (sce->theDag) {
1647                 free_forest(sce->theDag);
1648                 MEM_freeN(sce->theDag);
1649                 sce->theDag = NULL;
1650         }
1651 }
1652
1653 static void lib_id_recalc_tag(Main *bmain, ID *id)
1654 {
1655         id->flag |= LIB_ID_RECALC;
1656         DAG_id_type_tag(bmain, GS(id->name));
1657 }
1658
1659 static void lib_id_recalc_data_tag(Main *bmain, ID *id)
1660 {
1661         id->flag |= LIB_ID_RECALC_DATA;
1662         DAG_id_type_tag(bmain, GS(id->name));
1663 }
1664
1665 /* node was checked to have lasttime != curtime and is if type ID_OB */
1666 static void flush_update_node(Main *bmain, DagNode *node, unsigned int layer, int curtime)
1667 {
1668         DagAdjList *itA;
1669         Object *ob, *obc;
1670         int oldflag;
1671         bool changed = false;
1672         unsigned int all_layer;
1673         
1674         node->lasttime = curtime;
1675         
1676         ob = node->ob;
1677         if (ob && (ob->recalc & OB_RECALC_ALL)) {
1678                 all_layer = node->scelay;
1679
1680                 /* got an object node that changes, now check relations */
1681                 for (itA = node->child; itA; itA = itA->next) {
1682                         all_layer |= itA->lay;
1683                         /* the relationship is visible */
1684                         if ((itA->lay & layer)) { // XXX || (itA->node->ob == obedit)
1685                                 if (itA->node->type == ID_OB) {
1686                                         obc = itA->node->ob;
1687                                         oldflag = obc->recalc;
1688                                         
1689                                         /* got a ob->obc relation, now check if flag needs flush */
1690                                         if (ob->recalc & OB_RECALC_OB) {
1691                                                 if (itA->type & DAG_RL_OB_OB) {
1692                                                         //printf("ob %s changes ob %s\n", ob->id.name, obc->id.name);
1693                                                         obc->recalc |= OB_RECALC_OB;
1694                                                         lib_id_recalc_tag(bmain, &obc->id);
1695                                                 }
1696                                                 if (itA->type & DAG_RL_OB_DATA) {
1697                                                         //printf("ob %s changes obdata %s\n", ob->id.name, obc->id.name);
1698                                                         obc->recalc |= OB_RECALC_DATA;
1699                                                         lib_id_recalc_data_tag(bmain, &obc->id);
1700                                                 }
1701                                         }
1702                                         if (ob->recalc & OB_RECALC_DATA) {
1703                                                 if (itA->type & DAG_RL_DATA_OB) {
1704                                                         //printf("obdata %s changes ob %s\n", ob->id.name, obc->id.name);
1705                                                         obc->recalc |= OB_RECALC_OB;
1706                                                         lib_id_recalc_tag(bmain, &obc->id);
1707                                                 }
1708                                                 if (itA->type & DAG_RL_DATA_DATA) {
1709                                                         //printf("obdata %s changes obdata %s\n", ob->id.name, obc->id.name);
1710                                                         obc->recalc |= OB_RECALC_DATA;
1711                                                         lib_id_recalc_data_tag(bmain, &obc->id);
1712                                                 }
1713                                         }
1714                                         if (oldflag != obc->recalc) changed = 1;
1715                                 }
1716                         }
1717                 }
1718                 /* even nicer, we can clear recalc flags...  */
1719                 if ((all_layer & layer) == 0) { // XXX && (ob != obedit)) {
1720                         /* but existing displaylists or derivedmesh should be freed */
1721                         if (ob->recalc & OB_RECALC_DATA)
1722                                 BKE_object_free_derived_caches(ob);
1723                         
1724                         ob->recalc &= ~OB_RECALC_ALL;
1725                 }
1726         }
1727         
1728         /* check case where child changes and parent forcing obdata to change */
1729         /* should be done regardless if this ob has recalc set */
1730         /* could merge this in with loop above...? (ton) */
1731         for (itA = node->child; itA; itA = itA->next) {
1732                 /* the relationship is visible */
1733                 if ((itA->lay & layer)) {       // XXX  || (itA->node->ob == obedit)
1734                         if (itA->node->type == ID_OB) {
1735                                 obc = itA->node->ob;
1736                                 /* child moves */
1737                                 if ((obc->recalc & OB_RECALC_ALL) == OB_RECALC_OB) {
1738                                         /* parent has deforming info */
1739                                         if (itA->type & (DAG_RL_OB_DATA | DAG_RL_DATA_DATA)) {
1740                                                 // printf("parent %s changes ob %s\n", ob->id.name, obc->id.name);
1741                                                 obc->recalc |= OB_RECALC_DATA;
1742                                                 lib_id_recalc_data_tag(bmain, &obc->id);
1743                                         }
1744                                 }
1745                         }
1746                 }
1747         }
1748         
1749         /* we only go deeper if node not checked or something changed  */
1750         for (itA = node->child; itA; itA = itA->next) {
1751                 if (changed || itA->node->lasttime != curtime)
1752                         flush_update_node(bmain, itA->node, layer, curtime);
1753         }
1754         
1755 }
1756
1757 /* node was checked to have lasttime != curtime, and is of type ID_OB */
1758 static unsigned int flush_layer_node(Scene *sce, DagNode *node, int curtime)
1759 {
1760         DagAdjList *itA;
1761         
1762         node->lasttime = curtime;
1763         node->lay = node->scelay;
1764         
1765         for (itA = node->child; itA; itA = itA->next) {
1766                 if (itA->node->type == ID_OB) {
1767                         if (itA->node->lasttime != curtime) {
1768                                 itA->lay = flush_layer_node(sce, itA->node, curtime);  /* lay is only set once for each relation */
1769                         }
1770                         else {
1771                                 itA->lay = itA->node->lay;
1772                         }
1773                         
1774                         node->lay |= itA->lay;
1775                 }
1776         }
1777
1778         return node->lay;
1779 }
1780
1781 /* node was checked to have lasttime != curtime, and is of type ID_OB */
1782 static void flush_pointcache_reset(Main *bmain, Scene *scene, DagNode *node,
1783                                    int curtime, unsigned int lay, bool reset)
1784 {
1785         DagAdjList *itA;
1786         Object *ob;
1787         
1788         node->lasttime = curtime;
1789         
1790         for (itA = node->child; itA; itA = itA->next) {
1791                 if (itA->node->type == ID_OB) {
1792                         if (itA->node->lasttime != curtime) {
1793                                 ob = (Object *)(itA->node->ob);
1794
1795                                 if (reset || (ob->recalc & OB_RECALC_ALL)) {
1796                                         if (BKE_ptcache_object_reset(scene, ob, PTCACHE_RESET_DEPSGRAPH)) {
1797                                                 /* Don't tag nodes which are on invisible layer. */
1798                                                 if (itA->node->lay & lay) {
1799                                                         ob->recalc |= OB_RECALC_DATA;
1800                                                         lib_id_recalc_data_tag(bmain, &ob->id);
1801                                                 }
1802                                         }
1803
1804                                         flush_pointcache_reset(bmain, scene, itA->node, curtime, lay, true);
1805                                 }
1806                                 else
1807                                         flush_pointcache_reset(bmain, scene, itA->node, curtime, lay, false);
1808                         }
1809                 }
1810         }
1811 }
1812
1813 /* flush layer flags to dependencies */
1814 static void dag_scene_flush_layers(Scene *sce, int lay)
1815 {
1816         DagNode *node, *firstnode;
1817         DagAdjList *itA;
1818         Base *base;
1819         int lasttime;
1820
1821         firstnode = sce->theDag->DagNode.first;  /* always scene node */
1822
1823         for (itA = firstnode->child; itA; itA = itA->next)
1824                 itA->lay = 0;
1825
1826         sce->theDag->time++;  /* so we know which nodes were accessed */
1827         lasttime = sce->theDag->time;
1828
1829         /* update layer flags in nodes */
1830         for (base = sce->base.first; base; base = base->next) {
1831                 node = dag_get_node(sce->theDag, base->object);
1832                 node->scelay = base->object->lay;
1833         }
1834
1835         /* ensure cameras are set as if they are on a visible layer, because
1836          * they ared still used for rendering or setting the camera view
1837          *
1838          * XXX, this wont work for local view / unlocked camera's */
1839         if (sce->camera) {
1840                 node = dag_get_node(sce->theDag, sce->camera);
1841                 node->scelay |= lay;
1842         }
1843
1844 #ifdef DURIAN_CAMERA_SWITCH
1845         {
1846                 TimeMarker *m;
1847
1848                 for (m = sce->markers.first; m; m = m->next) {
1849                         if (m->camera) {
1850                                 node = dag_get_node(sce->theDag, m->camera);
1851                                 node->scelay |= lay;
1852                         }
1853                 }
1854         }
1855 #endif
1856
1857         /* flush layer nodes to dependencies */
1858         for (itA = firstnode->child; itA; itA = itA->next)
1859                 if (itA->node->lasttime != lasttime && itA->node->type == ID_OB)
1860                         flush_layer_node(sce, itA->node, lasttime);
1861 }
1862
1863 static void dag_tag_renderlayers(Scene *sce, unsigned int lay)
1864 {
1865         if (sce->nodetree) {
1866                 bNode *node;
1867                 Base *base;
1868                 unsigned int lay_changed = 0;
1869                 
1870                 for (base = sce->base.first; base; base = base->next)
1871                         if (base->lay & lay)
1872                                 if (base->object->recalc)
1873                                         lay_changed |= base->lay;
1874                         
1875                 for (node = sce->nodetree->nodes.first; node; node = node->next) {
1876                         if (node->id == (ID *)sce) {
1877                                 SceneRenderLayer *srl = BLI_findlink(&sce->r.layers, node->custom1);
1878                                 if (srl && (srl->lay & lay_changed))
1879                                         nodeUpdate(sce->nodetree, node);
1880                         }
1881                 }
1882         }
1883 }
1884
1885 /* flushes all recalc flags in objects down the dependency tree */
1886 void DAG_scene_flush_update(Main *bmain, Scene *sce, unsigned int lay, const short time)
1887 {
1888         DagNode *firstnode;
1889         DagAdjList *itA;
1890         Object *ob;
1891         int lasttime;
1892         
1893         if (sce->theDag == NULL) {
1894                 printf("DAG zero... not allowed to happen!\n");
1895                 DAG_scene_relations_update(bmain, sce);
1896         }
1897         
1898         firstnode = sce->theDag->DagNode.first;  /* always scene node */
1899
1900         /* first we flush the layer flags */
1901         dag_scene_flush_layers(sce, lay);
1902
1903         /* then we use the relationships + layer info to flush update events */
1904         sce->theDag->time++;  /* so we know which nodes were accessed */
1905         lasttime = sce->theDag->time;
1906         for (itA = firstnode->child; itA; itA = itA->next)
1907                 if (itA->node->lasttime != lasttime && itA->node->type == ID_OB)
1908                         flush_update_node(bmain, itA->node, lay, lasttime);
1909
1910         /* if update is not due to time change, do pointcache clears */
1911         if (!time) {
1912                 sce->theDag->time++;  /* so we know which nodes were accessed */
1913                 lasttime = sce->theDag->time;
1914                 for (itA = firstnode->child; itA; itA = itA->next) {
1915                         if (itA->node->lasttime != lasttime && itA->node->type == ID_OB) {
1916                                 ob = (Object *)(itA->node->ob);
1917
1918                                 if (ob->recalc & OB_RECALC_ALL) {
1919                                         if (BKE_ptcache_object_reset(sce, ob, PTCACHE_RESET_DEPSGRAPH)) {
1920                                                 ob->recalc |= OB_RECALC_DATA;
1921                                                 lib_id_recalc_data_tag(bmain, &ob->id);
1922                                         }
1923
1924                                         flush_pointcache_reset(bmain, sce, itA->node, lasttime,
1925                                                                lay, true);
1926                                 }
1927                                 else
1928                                         flush_pointcache_reset(bmain, sce, itA->node, lasttime,
1929                                                                lay, false);
1930                         }
1931                 }
1932         }
1933         
1934         dag_tag_renderlayers(sce, lay);
1935 }
1936
1937 static int object_modifiers_use_time(Object *ob)
1938 {
1939         ModifierData *md;
1940         
1941         /* check if a modifier in modifier stack needs time input */
1942         for (md = ob->modifiers.first; md; md = md->next)
1943                 if (modifier_dependsOnTime(md))
1944                         return 1;
1945         
1946         /* check whether any modifiers are animated */
1947         if (ob->adt) {
1948                 AnimData *adt = ob->adt;
1949                 FCurve *fcu;
1950                 
1951                 /* action - check for F-Curves with paths containing 'modifiers[' */
1952                 if (adt->action) {
1953                         for (fcu = adt->action->curves.first; fcu; fcu = fcu->next) {
1954                                 if (fcu->rna_path && strstr(fcu->rna_path, "modifiers["))
1955                                         return 1;
1956                         }
1957                 }
1958                 
1959                 /* This here allows modifier properties to get driven and still update properly
1960                  *
1961                  * Workaround to get [#26764] (e.g. subsurf levels not updating when animated/driven)
1962                  * working, without the updating problems ([#28525] [#28690] [#28774] [#28777]) caused
1963                  * by the RNA updates cache introduced in r.38649
1964                  */
1965                 for (fcu = adt->drivers.first; fcu; fcu = fcu->next) {
1966                         if (fcu->rna_path && strstr(fcu->rna_path, "modifiers["))
1967                                 return 1;
1968                 }
1969                 
1970                 /* XXX: also, should check NLA strips, though for now assume that nobody uses
1971                  * that and we can omit that for performance reasons... */
1972         }
1973         
1974         return 0;
1975 }
1976
1977 static short animdata_use_time(AnimData *adt)
1978 {
1979         NlaTrack *nlt;
1980         
1981         if (adt == NULL) return 0;
1982         
1983         /* check action - only if assigned, and it has anim curves */
1984         if (adt->action && adt->action->curves.first)
1985                 return 1;
1986         
1987         /* check NLA tracks + strips */
1988         for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) {
1989                 if (nlt->strips.first)
1990                         return 1;
1991         }
1992         
1993         /* If we have drivers, more likely than not, on a frame change
1994          * they'll need updating because their owner changed
1995          * 
1996          * This is kindof a hack to get around a whole host of problems
1997          * involving drivers using non-object datablock data (which the 
1998          * depsgraph currently has no way of representing let alone correctly
1999          * dependency sort+tagging). By doing this, at least we ensure that 
2000          * some commonly attempted drivers (such as scene -> current frame;
2001          * see "Driver updates fail" thread on Bf-committers dated July 2)
2002          * will work correctly, and that other non-object datablocks will have
2003          * their drivers update at least on frame change.
2004          *
2005          * -- Aligorith, July 4 2011
2006          */
2007         if (adt->drivers.first)
2008                 return 1;
2009         
2010         return 0;
2011 }
2012
2013 static void dag_object_time_update_flags(Main *bmain, Scene *scene, Object *ob)
2014 {
2015         if (ob->constraints.first) {
2016                 bConstraint *con;
2017                 for (con = ob->constraints.first; con; con = con->next) {
2018                         const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
2019                         ListBase targets = {NULL, NULL};
2020                         bConstraintTarget *ct;
2021                         
2022                         if (cti) {
2023                                 /* special case for camera tracking -- it doesn't use targets to define relations */
2024                                 if (ELEM(cti->type, CONSTRAINT_TYPE_FOLLOWTRACK, CONSTRAINT_TYPE_CAMERASOLVER, CONSTRAINT_TYPE_OBJECTSOLVER)) {
2025                                         ob->recalc |= OB_RECALC_OB;
2026                                 }
2027                                 else if (cti->get_constraint_targets) {
2028                                         cti->get_constraint_targets(con, &targets);
2029                                         
2030                                         for (ct = targets.first; ct; ct = ct->next) {
2031                                                 if (ct->tar) {
2032                                                         ob->recalc |= OB_RECALC_OB;
2033                                                         break;
2034                                                 }
2035                                         }
2036                                         
2037                                         if (cti->flush_constraint_targets)
2038                                                 cti->flush_constraint_targets(con, &targets, 1);
2039                                 }
2040                                 
2041                         }
2042                 }
2043         }
2044         
2045         if (ob->parent) {
2046                 /* motion path or bone child */
2047                 if (ob->parent->type == OB_CURVE || ob->parent->type == OB_ARMATURE) ob->recalc |= OB_RECALC_OB;
2048         }
2049         
2050 #if 0 // XXX old animation system
2051         if (ob->nlastrips.first) {
2052                 if (ob->dup_group) {
2053                         bActionStrip *strip;
2054                         /* this case is for groups with nla, whilst nla target has no action or nla */
2055                         for (strip = ob->nlastrips.first; strip; strip = strip->next) {
2056                                 if (strip->object)
2057                                         strip->object->recalc |= OB_RECALC_ALL;
2058                         }
2059                 }
2060         }
2061 #endif // XXX old animation system
2062         
2063         if (animdata_use_time(ob->adt)) {
2064                 ob->recalc |= OB_RECALC_OB;
2065                 ob->adt->recalc |= ADT_RECALC_ANIM;
2066         }
2067         
2068         if ((ob->adt) && (ob->type == OB_ARMATURE)) ob->recalc |= OB_RECALC_DATA;
2069         
2070         if (object_modifiers_use_time(ob)) ob->recalc |= OB_RECALC_DATA;
2071         if ((ob->pose) && (ob->pose->flag & POSE_CONSTRAINTS_TIMEDEPEND)) ob->recalc |= OB_RECALC_DATA;
2072         
2073         // XXX: scene here may not be the scene that contains the rigidbody world affecting this!
2074         if (ob->rigidbody_object && BKE_scene_check_rigidbody_active(scene))
2075                 ob->recalc |= OB_RECALC_OB;
2076         
2077         {
2078                 AnimData *adt = BKE_animdata_from_id((ID *)ob->data);
2079                 Mesh *me;
2080                 Curve *cu;
2081                 Lattice *lt;
2082                 
2083                 switch (ob->type) {
2084                         case OB_MESH:
2085                                 me = ob->data;
2086                                 if (me->key) {
2087                                         if (!(ob->shapeflag & OB_SHAPE_LOCK)) {
2088                                                 ob->recalc |= OB_RECALC_DATA;
2089                                         }
2090                                 }
2091                                 if (ob->particlesystem.first)
2092                                         ob->recalc |= OB_RECALC_DATA;
2093                                 break;
2094                         case OB_CURVE:
2095                         case OB_SURF:
2096                                 cu = ob->data;
2097                                 if (cu->key) {
2098                                         if (!(ob->shapeflag & OB_SHAPE_LOCK)) {
2099                                                 ob->recalc |= OB_RECALC_DATA;
2100                                         }
2101                                 }
2102                                 break;
2103                         case OB_FONT:
2104                                 cu = ob->data;
2105                                 if (BLI_listbase_is_empty(&cu->nurb) && cu->str && cu->vfont)
2106                                         ob->recalc |= OB_RECALC_DATA;
2107                                 break;
2108                         case OB_LATTICE:
2109                                 lt = ob->data;
2110                                 if (lt->key) {
2111                                         if (!(ob->shapeflag & OB_SHAPE_LOCK)) {
2112                                                 ob->recalc |= OB_RECALC_DATA;
2113                                         }
2114                                 }
2115                                 break;
2116                         case OB_MBALL:
2117                                 if (ob->transflag & OB_DUPLI) ob->recalc |= OB_RECALC_DATA;
2118                                 break;
2119                         case OB_EMPTY:
2120                                 /* update animated images */
2121                                 if (ob->empty_drawtype == OB_EMPTY_IMAGE && ob->data)
2122                                         if (BKE_image_is_animated(ob->data))
2123                                                 ob->recalc |= OB_RECALC_DATA;
2124                                 break;
2125                 }
2126                 
2127                 if (animdata_use_time(adt)) {
2128                         ob->recalc |= OB_RECALC_DATA;
2129                         adt->recalc |= ADT_RECALC_ANIM;
2130                 }
2131
2132                 if (ob->particlesystem.first) {
2133                         ParticleSystem *psys = ob->particlesystem.first;
2134
2135                         for (; psys; psys = psys->next) {
2136                                 if (psys_check_enabled(ob, psys)) {
2137                                         ob->recalc |= OB_RECALC_DATA;
2138                                         break;
2139                                 }
2140                         }
2141                 }
2142         }
2143
2144         if (ob->recalc & OB_RECALC_OB)
2145                 lib_id_recalc_tag(bmain, &ob->id);
2146         if (ob->recalc & OB_RECALC_DATA)
2147                 lib_id_recalc_data_tag(bmain, &ob->id);
2148
2149 }
2150
2151 /* recursively update objects in groups, each group is done at most once */
2152 static void dag_group_update_flags(Main *bmain, Scene *scene, Group *group, const bool do_time)
2153 {
2154         GroupObject *go;
2155
2156         if (group->id.flag & LIB_DOIT)
2157                 return;
2158         
2159         group->id.flag |= LIB_DOIT;
2160
2161         for (go = group->gobject.first; go; go = go->next) {
2162                 if (do_time)
2163                         dag_object_time_update_flags(bmain, scene, go->ob);
2164                 if (go->ob->dup_group)
2165                         dag_group_update_flags(bmain, scene, go->ob->dup_group, do_time);
2166         }
2167 }
2168
2169 /* flag all objects that need recalc, for changes in time for example */
2170 /* do_time: make this optional because undo resets objects to their animated locations without this */
2171 void DAG_scene_update_flags(Main *bmain, Scene *scene, unsigned int lay, const bool do_time, const bool do_invisible_flush)
2172 {
2173         Base *base;
2174         Object *ob;
2175         Group *group;
2176         GroupObject *go;
2177         Scene *sce_iter;
2178
2179         BKE_main_id_tag_idcode(bmain, ID_GR, false);
2180
2181         /* set ob flags where animated systems are */
2182         for (SETLOOPER(scene, sce_iter, base)) {
2183                 ob = base->object;
2184
2185                 if (do_time) {
2186                         /* now if DagNode were part of base, the node->lay could be checked... */
2187                         /* we do all now, since the scene_flush checks layers and clears recalc flags even */
2188                         
2189                         /* NOTE: "sce_iter" not "scene" so that rigidbodies in background scenes work 
2190                          * (i.e. muting + rbw availability can be checked and tagged properly) [#33970] 
2191                          */
2192                         dag_object_time_update_flags(bmain, sce_iter, ob);
2193                 }
2194
2195                 /* recursively tag groups with LIB_DOIT, and update flags for objects */
2196                 if (ob->dup_group)
2197                         dag_group_update_flags(bmain, scene, ob->dup_group, do_time);
2198         }
2199
2200         for (sce_iter = scene; sce_iter; sce_iter = sce_iter->set)
2201                 DAG_scene_flush_update(bmain, sce_iter, lay, 1);
2202         
2203         if (do_time) {
2204                 /* test: set time flag, to disable baked systems to update */
2205                 for (SETLOOPER(scene, sce_iter, base)) {
2206                         ob = base->object;
2207                         if (ob->recalc & OB_RECALC_ALL)
2208                                 ob->recalc |= OB_RECALC_TIME;
2209                 }
2210
2211                 /* hrmf... an exception to look at once, for invisible camera object we do it over */
2212                 if (scene->camera)
2213                         dag_object_time_update_flags(bmain, scene, scene->camera);
2214         }
2215
2216         /* and store the info in groupobject */
2217         for (group = bmain->group.first; group; group = group->id.next) {
2218                 if (group->id.flag & LIB_DOIT) {
2219                         for (go = group->gobject.first; go; go = go->next) {
2220                                 go->recalc = go->ob->recalc;
2221                                 // printf("ob %s recalc %d\n", go->ob->id.name, go->recalc);
2222                         }
2223                         group->id.flag &= ~LIB_DOIT;
2224                 }
2225         }
2226
2227         if (do_invisible_flush) {
2228                 dag_invisible_dependencies_check_flush(bmain, scene);
2229         }
2230 }
2231
2232 /* struct returned by DagSceneLayer */
2233 typedef struct DagSceneLayer {
2234         struct DagSceneLayer *next, *prev;
2235         Scene *scene;
2236         unsigned int layer;
2237 } DagSceneLayer;
2238
2239 /* returns visible scenes with valid DAG */
2240 static void dag_current_scene_layers(Main *bmain, ListBase *lb)
2241 {
2242         wmWindowManager *wm;
2243         wmWindow *win;
2244         
2245         BLI_listbase_clear(lb);
2246
2247         /* if we have a windowmanager, look into windows */
2248         if ((wm = bmain->wm.first)) {
2249                 
2250                 BKE_main_id_flag_listbase(&bmain->scene, LIB_DOIT, 1);
2251
2252                 for (win = wm->windows.first; win; win = win->next) {
2253                         if (win->screen && win->screen->scene->theDag) {
2254                                 Scene *scene = win->screen->scene;
2255                                 DagSceneLayer *dsl;
2256
2257                                 if (scene->id.flag & LIB_DOIT) {
2258                                         dsl = MEM_mallocN(sizeof(DagSceneLayer), "dag scene layer");
2259
2260                                         BLI_addtail(lb, dsl);
2261
2262                                         dsl->scene = scene;
2263                                         dsl->layer = BKE_screen_visible_layers(win->screen, scene);
2264
2265                                         scene->id.flag &= ~LIB_DOIT;
2266                                 }
2267                                 else {
2268                                         /* It is possible that multiple windows shares the same scene
2269                                          * and have different layers visible.
2270                                          *
2271                                          * Here we deal with such cases by squashing layers bits from
2272                                          * multiple windoew to the DagSceneLayer.
2273                                          *
2274                                          * TODO(sergey): Such a lookup could be optimized perhaps,
2275                                          * however should be fine for now since we usually have only
2276                                          * few open windows.
2277                                          */
2278                                         for (dsl = lb->first; dsl; dsl = dsl->next) {
2279                                                 if (dsl->scene == scene) {
2280                                                         dsl->layer |= BKE_screen_visible_layers(win->screen, scene);
2281                                                         break;
2282                                                 }
2283                                         }
2284                                 }
2285                         }
2286                 }
2287         }
2288         else {
2289                 /* if not, use the first sce */
2290                 DagSceneLayer *dsl = MEM_mallocN(sizeof(DagSceneLayer), "dag scene layer");
2291                 
2292                 BLI_addtail(lb, dsl);
2293                 
2294                 dsl->scene = bmain->scene.first;
2295                 dsl->layer = dsl->scene->lay;
2296
2297                 /* XXX for background mode, we should get the scene
2298                  * from somewhere, for the -S option, but it's in
2299                  * the context, how to get it here? */
2300         }
2301 }
2302
2303 static void dag_group_on_visible_update(Group *group)
2304 {
2305         GroupObject *go;
2306
2307         if (group->id.flag & LIB_DOIT)
2308                 return;
2309         
2310         group->id.flag |= LIB_DOIT;
2311
2312         for (go = group->gobject.first; go; go = go->next) {
2313                 if (ELEM(go->ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL, OB_LATTICE)) {
2314                         go->ob->recalc |= OB_RECALC_DATA;
2315                         go->ob->id.flag |= LIB_DOIT;
2316                         lib_id_recalc_tag(G.main, &go->ob->id);
2317                 }
2318                 if (go->ob->proxy_from) {
2319                         go->ob->recalc |= OB_RECALC_OB;
2320                         go->ob->id.flag |= LIB_DOIT;
2321                         lib_id_recalc_tag(G.main, &go->ob->id);
2322                 }
2323
2324                 if (go->ob->dup_group)
2325                         dag_group_on_visible_update(go->ob->dup_group);
2326         }
2327 }
2328
2329 void DAG_on_visible_update(Main *bmain, const bool do_time)
2330 {
2331         ListBase listbase;
2332         DagSceneLayer *dsl;
2333         
2334         /* get list of visible scenes and layers */
2335         dag_current_scene_layers(bmain, &listbase);
2336         
2337         for (dsl = listbase.first; dsl; dsl = dsl->next) {
2338                 Scene *scene = dsl->scene;
2339                 Scene *sce_iter;
2340                 Base *base;
2341                 Object *ob;
2342                 DagNode *node;
2343                 unsigned int lay = dsl->layer, oblay;
2344
2345                 /* derivedmeshes and displists are not saved to file so need to be
2346                  * remade, tag them so they get remade in the scene update loop,
2347                  * note armature poses or object matrices are preserved and do not
2348                  * require updates, so we skip those */
2349                 for (sce_iter = scene; sce_iter; sce_iter = sce_iter->set)
2350                         dag_scene_flush_layers(sce_iter, lay);
2351
2352                 BKE_main_id_tag_idcode(bmain, ID_GR, false);
2353
2354                 for (SETLOOPER(scene, sce_iter, base)) {
2355                         ob = base->object;
2356                         node = (sce_iter->theDag) ? dag_get_node(sce_iter->theDag, ob) : NULL;
2357                         oblay = (node) ? node->lay : ob->lay;
2358
2359                         if ((oblay & lay) & ~scene->lay_updated) {
2360                                 if (ELEM(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL, OB_LATTICE)) {
2361                                         ob->recalc |= OB_RECALC_DATA;
2362                                         lib_id_recalc_tag(bmain, &ob->id);
2363                                 }
2364                                 /* This should not be needed here, but in some cases, like after a redo, we can end up with
2365                                  * a wrong final matrix (see T42472).
2366                                  * Quoting Sergey, this comes from BKE_object_handle_update_ex, which is calling
2367                                  * BKE_object_where_is_calc_ex when it shouldn't, but that issue is not easily fixable.
2368                                  */
2369                                 else {
2370                                         ob->recalc |= OB_RECALC_OB;
2371                                         lib_id_recalc_tag(bmain, &ob->id);
2372                                 }
2373                                 if (ob->proxy && (ob->proxy_group == NULL)) {
2374                                         ob->proxy->recalc |= OB_RECALC_DATA;
2375                                         lib_id_recalc_tag(bmain, &ob->id);
2376                                 }
2377                                 if (ob->dup_group)
2378                                         dag_group_on_visible_update(ob->dup_group);
2379                         }
2380                 }
2381
2382                 BKE_main_id_tag_idcode(bmain, ID_GR, false);
2383
2384                 /* now tag update flags, to ensure deformers get calculated on redraw */
2385                 DAG_scene_update_flags(bmain, scene, lay, do_time, true);
2386                 scene->lay_updated |= lay;
2387         }
2388         
2389         BLI_freelistN(&listbase);
2390
2391         /* hack to get objects updating on layer changes */
2392         DAG_id_type_tag(bmain, ID_OB);
2393
2394         /* so masks update on load */
2395         if (bmain->mask.first) {
2396                 Mask *mask;
2397
2398                 for (mask = bmain->mask.first; mask; mask = mask->id.next) {
2399                         DAG_id_tag_update(&mask->id, 0);
2400                 }
2401         }
2402 }
2403
2404 static void dag_id_flush_update__isDependentTexture(void *userData, Object *UNUSED(ob), ID **idpoin)
2405 {
2406         struct { ID *id; bool is_dependent; } *data = userData;
2407         
2408         if (*idpoin && GS((*idpoin)->name) == ID_TE) {
2409                 if (data->id == (*idpoin))
2410                         data->is_dependent = 1;
2411         }
2412 }
2413
2414 static void dag_id_flush_update(Main *bmain, Scene *sce, ID *id)
2415 {
2416         Object *obt, *ob = NULL;
2417         short idtype;
2418
2419         /* here we flush a few things before actual scene wide flush, mostly
2420          * due to only objects and not other datablocks being in the depsgraph */
2421
2422         /* set flags & pointcache for object */
2423         if (GS(id->name) == ID_OB) {
2424                 ob = (Object *)id;
2425                 BKE_ptcache_object_reset(sce, ob, PTCACHE_RESET_DEPSGRAPH);
2426
2427                 /* So if someone tagged object recalc directly,
2428                  * id_tag_update bit-field stays relevant
2429                  */
2430                 if (ob->recalc & OB_RECALC_ALL) {
2431                         DAG_id_type_tag(bmain, GS(id->name));
2432                 }
2433
2434                 if (ob->recalc & OB_RECALC_DATA) {
2435                         /* all users of this ob->data should be checked */
2436                         id = ob->data;
2437
2438                         /* no point in trying in this cases */
2439                         if (id && id->us <= 1) {
2440                                 dag_editors_id_update(bmain, id);
2441                                 id = NULL;
2442                         }
2443                 }
2444         }
2445
2446         /* set flags & pointcache for object data */
2447         if (id) {
2448                 idtype = GS(id->name);
2449
2450
2451                 if (OB_DATA_SUPPORT_ID(idtype)) {
2452                         for (obt = bmain->object.first; obt; obt = obt->id.next) {
2453                                 if (!(ob && obt == ob) && obt->data == id) {
2454                                         obt->recalc |= OB_RECALC_DATA;
2455                                         lib_id_recalc_data_tag(bmain, &obt->id);
2456                                         BKE_ptcache_object_reset(sce, obt, PTCACHE_RESET_DEPSGRAPH);
2457                                 }
2458                         }
2459                 }
2460                 
2461                 /* set flags based on textures - can influence depgraph via modifiers */
2462                 if (idtype == ID_TE) {
2463                         for (obt = bmain->object.first; obt; obt = obt->id.next) {
2464                                 struct { ID *id; bool is_dependent; } data;
2465                                 data.id = id;
2466                                 data.is_dependent = 0;
2467
2468                                 modifiers_foreachIDLink(obt, dag_id_flush_update__isDependentTexture, &data);
2469                                 if (data.is_dependent) {
2470                                         obt->recalc |= OB_RECALC_DATA;
2471                                         lib_id_recalc_data_tag(bmain, &obt->id);
2472                                 }
2473
2474                                 /* particle settings can use the texture as well */
2475                                 if (obt->particlesystem.first) {
2476                                         ParticleSystem *psys = obt->particlesystem.first;
2477                                         MTex **mtexp, *mtex;
2478                                         int a;
2479                                         for (; psys; psys = psys->next) {
2480                                                 mtexp = psys->part->mtex;
2481                                                 for (a = 0; a < MAX_MTEX; a++, mtexp++) {
2482                                                         mtex = *mtexp;
2483                                                         if (mtex && mtex->tex == (Tex *)id) {
2484                                                                 obt->recalc |= OB_RECALC_DATA;
2485                                                                 lib_id_recalc_data_tag(bmain, &obt->id);
2486
2487                                                                 if (mtex->mapto & PAMAP_INIT)
2488                                                                         psys->recalc |= PSYS_RECALC_RESET;
2489                                                                 if (mtex->mapto & PAMAP_CHILD)
2490                                                                         psys->recalc |= PSYS_RECALC_CHILD;
2491
2492                                                                 BKE_ptcache_object_reset(sce, obt, PTCACHE_RESET_DEPSGRAPH);
2493                                                         }
2494                                                 }
2495                                         }
2496                                 }
2497                         }
2498                 }
2499                 
2500                 /* set flags based on ShapeKey */
2501                 if (idtype == ID_KE) {
2502                         for (obt = bmain->object.first; obt; obt = obt->id.next) {
2503                                 Key *key = BKE_key_from_object(obt);
2504                                 if (!(ob && obt == ob) && ((ID *)key == id)) {
2505                                         obt->flag |= (OB_RECALC_OB | OB_RECALC_DATA);
2506                                         lib_id_recalc_tag(bmain, &obt->id);
2507                                         lib_id_recalc_data_tag(bmain, &obt->id);
2508                                         BKE_ptcache_object_reset(sce, obt, PTCACHE_RESET_DEPSGRAPH);
2509                                 }
2510                         }
2511                 }
2512                 
2513                 /* set flags based on particle settings */
2514                 if (idtype == ID_PA) {
2515                         ParticleSystem *psys;
2516                         for (obt = bmain->object.first; obt; obt = obt->id.next)
2517                                 for (psys = obt->particlesystem.first; psys; psys = psys->next)
2518                                         if (&psys->part->id == id)
2519                                                 BKE_ptcache_object_reset(sce, obt, PTCACHE_RESET_DEPSGRAPH);
2520                 }
2521
2522                 if (ELEM(idtype, ID_MA, ID_TE)) {
2523                         obt = sce->basact ? sce->basact->object : NULL;
2524                         if (obt && obt->mode & OB_MODE_TEXTURE_PAINT) {
2525                                 BKE_texpaint_slots_refresh_object(sce, obt);
2526                                 BKE_paint_proj_mesh_data_check(sce, obt, NULL, NULL, NULL, NULL);
2527                                 GPU_drawobject_free(obt->derivedFinal);
2528                         }
2529                 }
2530
2531                 if (idtype == ID_MC) {
2532                         MovieClip *clip = (MovieClip *) id;
2533
2534                         BKE_tracking_dopesheet_tag_update(&clip->tracking);
2535
2536                         for (obt = bmain->object.first; obt; obt = obt->id.next) {
2537                                 bConstraint *con;
2538                                 for (con = obt->constraints.first; con; con = con->next) {
2539                                         const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
2540                                         if (ELEM(cti->type, CONSTRAINT_TYPE_FOLLOWTRACK, CONSTRAINT_TYPE_CAMERASOLVER,
2541                                                   CONSTRAINT_TYPE_OBJECTSOLVER))
2542                                         {
2543                                                 obt->recalc |= OB_RECALC_OB;
2544                                                 lib_id_recalc_tag(bmain, &obt->id);
2545                                                 break;
2546                                         }
2547                                 }
2548                         }
2549
2550                         if (sce->nodetree) {
2551                                 bNode *node;
2552
2553                                 for (node = sce->nodetree->nodes.first; node; node = node->next) {
2554                                         if (node->id == id) {
2555                                                 nodeUpdate(sce->nodetree, node);
2556                                         }
2557                                 }
2558                         }
2559                 }
2560
2561                 /* Not pretty to iterate all the nodes here, but it's as good as it
2562                  * could be with the current depsgraph design/
2563                  */
2564                 if (idtype == ID_IM) {
2565                         FOREACH_NODETREE(bmain, ntree, parent_id) {
2566                                 if (ntree->type == NTREE_SHADER) {
2567                                         bNode *node;
2568                                         for (node = ntree->nodes.first; node; node = node->next) {
2569                                                 if (node->id == id) {
2570                                                         lib_id_recalc_tag(bmain, &ntree->id);
2571                                                         break;
2572                                                 }
2573                                         }
2574                                 }
2575                         } FOREACH_NODETREE_END
2576                 }
2577
2578                 if (idtype == ID_MSK) {
2579                         if (sce->nodetree) {
2580                                 bNode *node;
2581
2582                                 for (node = sce->nodetree->nodes.first; node; node = node->next) {
2583                                         if (node->id == id) {
2584                                                 nodeUpdate(sce->nodetree, node);
2585                                         }
2586                                 }
2587                         }
2588                 }
2589
2590                 /* camera's matrix is used to orient reconstructed stuff,
2591                  * so it should happen tracking-related constraints recalculation
2592                  * when camera is changing (sergey) */
2593                 if (sce->camera && &sce->camera->id == id) {
2594                         MovieClip *clip = BKE_object_movieclip_get(sce, sce->camera, true);
2595
2596                         if (clip)
2597                                 dag_id_flush_update(bmain, sce, &clip->id);
2598                 }
2599
2600                 /* update editors */
2601                 dag_editors_id_update(bmain, id);
2602         }
2603 }
2604
2605 void DAG_ids_flush_tagged(Main *bmain)
2606 {
2607         ListBase listbase;
2608         DagSceneLayer *dsl;
2609         ListBase *lbarray[MAX_LIBARRAY];
2610         int a;
2611         bool do_flush = false;
2612         
2613         /* get list of visible scenes and layers */
2614         dag_current_scene_layers(bmain, &listbase);
2615
2616         if (BLI_listbase_is_empty(&listbase))
2617                 return;
2618
2619         /* loop over all ID types */
2620         a  = set_listbasepointers(bmain, lbarray);
2621
2622         while (a--) {
2623                 ListBase *lb = lbarray[a];
2624                 ID *id = lb->first;
2625
2626                 /* we tag based on first ID type character to avoid 
2627                  * looping over all ID's in case there are no tags */
2628                 if (id && bmain->id_tag_update[id->name[0]]) {
2629                         for (; id; id = id->next) {
2630                                 if (id->flag & (LIB_ID_RECALC | LIB_ID_RECALC_DATA)) {
2631                                         
2632                                         for (dsl = listbase.first; dsl; dsl = dsl->next)
2633                                                 dag_id_flush_update(bmain, dsl->scene, id);
2634                                         
2635                                         do_flush = true;
2636                                 }
2637                         }
2638                 }
2639         }
2640
2641         /* flush changes to other objects */
2642         if (do_flush) {
2643                 for (dsl = listbase.first; dsl; dsl = dsl->next)
2644                         DAG_scene_flush_update(bmain, dsl->scene, dsl->layer, 0);
2645         }
2646         
2647         BLI_freelistN(&listbase);
2648 }
2649
2650 void DAG_ids_check_recalc(Main *bmain, Scene *scene, bool time)
2651 {
2652         ListBase *lbarray[MAX_LIBARRAY];
2653         int a;
2654         bool updated = false;
2655
2656         /* loop over all ID types */
2657         a  = set_listbasepointers(bmain, lbarray);
2658
2659         while (a--) {
2660                 ListBase *lb = lbarray[a];
2661                 ID *id = lb->first;
2662
2663                 /* we tag based on first ID type character to avoid 
2664                  * looping over all ID's in case there are no tags */
2665                 if (id && bmain->id_tag_update[id->name[0]]) {
2666                         updated = true;
2667                         break;
2668                 }
2669         }
2670
2671         dag_editors_scene_update(bmain, scene, (updated || time));
2672 }
2673
2674 /* It is possible that scene_update_post and frame_update_post handlers
2675  * will modify objects. The issue is that DAG_ids_clear_recalc is called
2676  * just after callbacks, which leaves objects with recalc flags but no
2677  * corresponding bit in ID recalc bitfield. This leads to some kind of
2678  * regression when using ID type tag fields to check whether there objects
2679  * to be updated internally comparing threaded DAG with legacy one.
2680  *
2681  * For now let's have a workaround which will preserve tag for ID_OB
2682  * if there're objects with OB_RECALC_ALL bits. This keeps behavior
2683  * unchanged comparing with 2.69 release.
2684  *
2685  * TODO(sergey): Need to get rid of such a workaround.
2686  *
2687  *                                                 - sergey -
2688  */
2689
2690 #define POST_UPDATE_HANDLER_WORKAROUND
2691
2692 void DAG_ids_clear_recalc(Main *bmain)
2693 {
2694         ListBase *lbarray[MAX_LIBARRAY];
2695         bNodeTree *ntree;
2696         int a;
2697
2698 #ifdef POST_UPDATE_HANDLER_WORKAROUND
2699         bool have_updated_objects = false;
2700
2701         if (DAG_id_type_tagged(bmain, ID_OB)) {
2702                 ListBase listbase;
2703                 DagSceneLayer *dsl;
2704
2705                 /* We need to check all visible scenes, otherwise resetting
2706                  * OB_ID changed flag will only work fine for first scene of
2707                  * multiple visible and all the rest will skip update.
2708                  *
2709                  * This could also lead to wrong behavior scene update handlers
2710                  * because of missing ID datablock changed flags.
2711                  *
2712                  * This is a bit of a bummer to allocate list here, but likely
2713                  * it wouldn't become too much bad because it only happens when
2714                  * objects were actually changed.
2715                  */
2716                 dag_current_scene_layers(bmain, &listbase);
2717
2718                 for (dsl = listbase.first; dsl; dsl = dsl->next) {
2719                         Scene *scene = dsl->scene;
2720                         DagNode *node;
2721                         for (node = scene->theDag->DagNode.first;
2722                              node != NULL && have_updated_objects == false;
2723                              node = node->next)
2724                         {
2725                                 if (node->type == ID_OB) {
2726                                         Object *object = (Object *) node->ob;
2727                                         if (object->recalc & OB_RECALC_ALL) {
2728                                                 have_updated_objects = true;
2729                                                 break;
2730                                         }
2731                                 }
2732                         }
2733                 }
2734
2735                 BLI_freelistN(&listbase);
2736         }
2737 #endif
2738
2739         /* loop over all ID types */
2740         a  = set_listbasepointers(bmain, lbarray);
2741
2742         while (a--) {
2743                 ListBase *lb = lbarray[a];
2744                 ID *id = lb->first;
2745
2746                 /* we tag based on first ID type character to avoid 
2747                  * looping over all ID's in case there are no tags */
2748                 if (id && bmain->id_tag_update[id->name[0]]) {
2749                         for (; id; id = id->next) {
2750                                 if (id->flag & (LIB_ID_RECALC | LIB_ID_RECALC_DATA))
2751                                         id->flag &= ~(LIB_ID_RECALC | LIB_ID_RECALC_DATA);
2752
2753                                 /* some ID's contain semi-datablock nodetree */
2754                                 ntree = ntreeFromID(id);
2755                                 if (ntree && (ntree->id.flag & (LIB_ID_RECALC | LIB_ID_RECALC_DATA)))
2756                                         ntree->id.flag &= ~(LIB_ID_RECALC | LIB_ID_RECALC_DATA);
2757                         }
2758                 }
2759         }
2760
2761         memset(bmain->id_tag_update, 0, sizeof(bmain->id_tag_update));
2762
2763 #ifdef POST_UPDATE_HANDLER_WORKAROUND
2764         if (have_updated_objects) {
2765                 DAG_id_type_tag(bmain, ID_OB);
2766         }
2767 #endif
2768 }
2769
2770 void DAG_id_tag_update_ex(Main *bmain, ID *id, short flag)
2771 {
2772         if (id == NULL) return;
2773
2774         if (G.debug & G_DEBUG_DEPSGRAPH) {
2775                 printf("%s: id=%s flag=%d\n", __func__, id->name, flag);
2776         }
2777
2778         /* tag ID for update */
2779         if (flag) {
2780                 if (flag & OB_RECALC_OB)
2781                         lib_id_recalc_tag(bmain, id);
2782                 if (flag & (OB_RECALC_DATA | PSYS_RECALC))
2783                         lib_id_recalc_data_tag(bmain, id);
2784         }
2785         else
2786                 lib_id_recalc_tag(bmain, id);
2787
2788         /* flag is for objects and particle systems */
2789         if (flag) {
2790                 Object *ob;
2791                 short idtype = GS(id->name);
2792
2793                 if (idtype == ID_OB) {
2794                         /* only quick tag */
2795                         ob = (Object *)id;
2796                         ob->recalc |= (flag & OB_RECALC_ALL);
2797                 }
2798                 else if (idtype == ID_PA) {
2799                         ParticleSystem *psys;
2800                         /* this is weak still, should be done delayed as well */
2801                         for (ob = bmain->object.first; ob; ob = ob->id.next) {
2802                                 for (psys = ob->particlesystem.first; psys; psys = psys->next) {
2803                                         if (&psys->part->id == id) {
2804                                                 ob->recalc |= (flag & OB_RECALC_ALL);
2805                                                 psys->recalc |= (flag & PSYS_RECALC);
2806                                                 lib_id_recalc_tag(bmain, &ob->id);
2807                                                 lib_id_recalc_data_tag(bmain, &ob->id);
2808                                         }
2809                                 }
2810                         }
2811                 }
2812                 else if (idtype == ID_VF) {
2813                         /* this is weak still, should be done delayed as well */
2814                         for (ob = bmain->object.first; ob; ob = ob->id.next) {
2815                                 if (ob->type == OB_FONT) {
2816                                         Curve *cu = ob->data;
2817
2818                                         if (ELEM((struct VFont *)id, cu->vfont, cu->vfontb, cu->vfonti, cu->vfontbi)) {
2819                                                 ob->recalc |= (flag & OB_RECALC_ALL);
2820                                         }
2821                                 }
2822                         }
2823                 }
2824                 else {
2825                         /* disable because this is called on various ID types automatically.
2826                          * where printing warning is not useful. for now just ignore */
2827                         /* BLI_assert(!"invalid flag for this 'idtype'"); */
2828                 }
2829         }
2830 }
2831
2832 void DAG_id_tag_update(ID *id, short flag)
2833 {
2834         DAG_id_tag_update_ex(G.main, id, flag);
2835 }
2836
2837 void DAG_id_type_tag(Main *bmain, short idtype)
2838 {
2839         if (idtype == ID_NT) {
2840                 /* stupid workaround so parent datablocks of nested nodetree get looped
2841                  * over when we loop over tagged datablock types */
2842                 DAG_id_type_tag(bmain, ID_MA);
2843                 DAG_id_type_tag(bmain, ID_TE);
2844                 DAG_id_type_tag(bmain, ID_LA);
2845                 DAG_id_type_tag(bmain, ID_WO);
2846                 DAG_id_type_tag(bmain, ID_SCE);
2847         }
2848
2849         bmain->id_tag_update[((char *)&idtype)[0]] = 1;
2850 }
2851
2852 int DAG_id_type_tagged(Main *bmain, short idtype)
2853 {
2854         return bmain->id_tag_update[((char *)&idtype)[0]];
2855 }
2856
2857 #if 0 // UNUSED
2858 /* recursively descends tree, each node only checked once */
2859 /* node is checked to be of type object */
2860 static int parent_check_node(DagNode *node, int curtime)
2861 {
2862         DagAdjList *itA;
2863         
2864         node->lasttime = curtime;
2865         
2866         if (node->color == DAG_GRAY)
2867                 return DAG_GRAY;
2868         
2869         for (itA = node->child; itA; itA = itA->next) {
2870                 if (itA->node->type == ID_OB) {
2871                         
2872                         if (itA->node->color == DAG_GRAY)
2873                                 return DAG_GRAY;
2874
2875                         /* descend if not done */
2876                         if (itA->node->lasttime != curtime) {
2877                                 itA->node->color = parent_check_node(itA->node, curtime);
2878                         
2879                                 if (itA->node->color == DAG_GRAY)
2880                                         return DAG_GRAY;
2881                         }
2882                 }
2883         }
2884         
2885         return DAG_WHITE;
2886 }
2887 #endif
2888
2889 /* ******************* DAG FOR ARMATURE POSE ***************** */
2890
2891 /* we assume its an armature with pose */
2892 void DAG_pose_sort(Object *ob)
2893 {
2894         bPose *pose = ob->pose;
2895         bPoseChannel *pchan;
2896         bConstraint *con;
2897         DagNode *node;
2898         DagNode *node2, *node3;
2899         DagNode *rootnode;
2900         DagForest *dag;
2901         DagNodeQueue *nqueue;
2902         DagAdjList *itA;
2903         ListBase tempbase;
2904         int skip = 0;
2905         
2906         dag = dag_init();
2907         dag->ugly_hack_sorry = false;  /* no ID structs */
2908
2909         rootnode = dag_add_node(dag, NULL);  /* node->ob becomes NULL */
2910         
2911         /* we add the hierarchy and the constraints */
2912         for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
2913                 int addtoroot = 1;
2914                 
2915                 node = dag_get_node(dag, pchan);
2916                 
2917                 if (pchan->parent) {
2918                         node2 = dag_get_node(dag, pchan->parent);
2919                         dag_add_relation(dag, node2, node, 0, "Parent Relation");
2920                         addtoroot = 0;
2921                 }
2922                 for (con = pchan->constraints.first; con; con = con->next) {
2923                         const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
2924                         ListBase targets = {NULL, NULL};
2925                         bConstraintTarget *ct;
2926                         
2927                         if (cti && cti->get_constraint_targets) {
2928                                 cti->get_constraint_targets(con, &targets);
2929                                 
2930                                 for (ct = targets.first; ct; ct = ct->next) {
2931                                         if (ct->tar == ob && ct->subtarget[0]) {