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