Merge branch 'master' into blender2.8
[blender.git] / source / blender / depsgraph / intern / builder / deg_builder_relations.cc
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) 2013 Blender Foundation.
19  * All rights reserved.
20  *
21  * Original Author: Joshua Leung
22  * Contributor(s): Based on original depsgraph.c code - Blender Foundation (2005-2013)
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/depsgraph/intern/builder/deg_builder_relations.cc
28  *  \ingroup depsgraph
29  *
30  * Methods for constructing depsgraph
31  */
32
33 #include "intern/builder/deg_builder_relations.h"
34
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <cstring>  /* required for STREQ later on. */
38
39 #include "MEM_guardedalloc.h"
40
41 #include "BLI_utildefines.h"
42 #include "BLI_blenlib.h"
43
44 extern "C" {
45 #include "DNA_action_types.h"
46 #include "DNA_anim_types.h"
47 #include "DNA_armature_types.h"
48 #include "DNA_camera_types.h"
49 #include "DNA_cachefile_types.h"
50 #include "DNA_collection_types.h"
51 #include "DNA_constraint_types.h"
52 #include "DNA_curve_types.h"
53 #include "DNA_effect_types.h"
54 #include "DNA_gpencil_types.h"
55 #include "DNA_key_types.h"
56 #include "DNA_lamp_types.h"
57 #include "DNA_material_types.h"
58 #include "DNA_mask_types.h"
59 #include "DNA_mesh_types.h"
60 #include "DNA_meta_types.h"
61 #include "DNA_movieclip_types.h"
62 #include "DNA_node_types.h"
63 #include "DNA_particle_types.h"
64 #include "DNA_lightprobe_types.h"
65 #include "DNA_object_types.h"
66 #include "DNA_rigidbody_types.h"
67 #include "DNA_scene_types.h"
68 #include "DNA_speaker_types.h"
69 #include "DNA_texture_types.h"
70 #include "DNA_world_types.h"
71 #include "DNA_object_force_types.h"
72
73 #include "BKE_action.h"
74 #include "BKE_armature.h"
75 #include "BKE_animsys.h"
76 #include "BKE_collection.h"
77 #include "BKE_constraint.h"
78 #include "BKE_curve.h"
79 #include "BKE_effect.h"
80 #include "BKE_collision.h"
81 #include "BKE_fcurve.h"
82 #include "BKE_key.h"
83 #include "BKE_material.h"
84 #include "BKE_mball.h"
85 #include "BKE_modifier.h"
86 #include "BKE_gpencil_modifier.h"
87 #include "BKE_node.h"
88 #include "BKE_object.h"
89 #include "BKE_particle.h"
90 #include "BKE_pointcache.h"
91 #include "BKE_rigidbody.h"
92 #include "BKE_shader_fx.h"
93 #include "BKE_shrinkwrap.h"
94 #include "BKE_sound.h"
95 #include "BKE_tracking.h"
96 #include "BKE_world.h"
97
98 #include "RNA_access.h"
99 #include "RNA_types.h"
100 } /* extern "C" */
101
102 #include "DEG_depsgraph.h"
103 #include "DEG_depsgraph_build.h"
104
105 #include "intern/builder/deg_builder.h"
106 #include "intern/builder/deg_builder_pchanmap.h"
107 #include "intern/eval/deg_eval_copy_on_write.h"
108
109 #include "intern/nodes/deg_node.h"
110 #include "intern/nodes/deg_node_component.h"
111 #include "intern/nodes/deg_node_id.h"
112 #include "intern/nodes/deg_node_operation.h"
113 #include "intern/nodes/deg_node_time.h"
114
115 #include "intern/depsgraph_intern.h"
116 #include "intern/depsgraph_types.h"
117
118 #include "util/deg_util_foreach.h"
119
120 namespace DEG {
121
122 /* ***************** */
123 /* Relations Builder */
124
125 /* TODO(sergey): This is somewhat weak, but we don't want neither false-positive
126  * time dependencies nor special exceptions in the depsgraph evaluation.
127  */
128 static bool python_driver_depends_on_time(ChannelDriver *driver)
129 {
130         if (driver->expression[0] == '\0') {
131                 /* Empty expression depends on nothing. */
132                 return false;
133         }
134         if (strchr(driver->expression, '(') != NULL) {
135                 /* Function calls are considered dependent on a time. */
136                 return true;
137         }
138         if (strstr(driver->expression, "frame") != NULL) {
139                 /* Variable `frame` depends on time. */
140                 /* TODO(sergey): This is a bit weak, but not sure about better way of
141                  * handling this.
142                  */
143                 return true;
144         }
145         /* Possible indirect time relation s should be handled via variable
146          * targets.
147          */
148         return false;
149 }
150
151 static bool particle_system_depends_on_time(ParticleSystem *psys)
152 {
153         ParticleSettings *part = psys->part;
154         /* Non-hair particles we always consider dependent on time. */
155         if (part->type != PART_HAIR) {
156                 return true;
157         }
158         /* Dynamics always depends on time. */
159         if (psys->flag & PSYS_HAIR_DYNAMICS) {
160                 return true;
161         }
162         /* TODO(sergey): Check what else makes hair dependent on time. */
163         return false;
164 }
165
166 static bool object_particles_depends_on_time(Object *object)
167 {
168         if (object->type != OB_MESH) {
169                 return false;
170         }
171         LISTBASE_FOREACH (ParticleSystem *, psys, &object->particlesystem) {
172                 if (particle_system_depends_on_time(psys)) {
173                         return true;
174                 }
175         }
176         return false;
177 }
178
179 static bool check_id_has_anim_component(ID *id)
180 {
181         AnimData *adt = BKE_animdata_from_id(id);
182         if (adt == NULL) {
183                 return false;
184         }
185         return (adt->action != NULL) ||
186                (!BLI_listbase_is_empty(&adt->nla_tracks));
187 }
188
189 static eDepsOperation_Code bone_target_opcode(ID *target,
190                                               const char *subtarget,
191                                               ID *id,
192                                               const char *component_subdata,
193                                               RootPChanMap *root_map)
194 {
195         /* Same armature.  */
196         if (target == id) {
197                 /* Using "done" here breaks in-chain deps, while using
198                  * "ready" here breaks most production rigs instead.
199                  * So, we do a compromise here, and only do this when an
200                  * IK chain conflict may occur.
201                  */
202                 if (root_map->has_common_root(component_subdata, subtarget)) {
203                         return DEG_OPCODE_BONE_READY;
204                 }
205         }
206         return DEG_OPCODE_BONE_DONE;
207 }
208
209 static bool bone_has_segments(Object *object, const char *bone_name)
210 {
211         /* Proxies don't have BONE_SEGMENTS */
212         if (ID_IS_LINKED(object) && object->proxy_from != NULL) {
213                 return false;
214         }
215         /* Only B-Bones have segments. */
216         bPoseChannel *pchan = BKE_pose_channel_find_name(object->pose, bone_name);
217         return pchan && pchan->bone && pchan->bone->segments > 1;
218 }
219
220 /* **** General purpose functions ****  */
221
222 DepsgraphRelationBuilder::DepsgraphRelationBuilder(Main *bmain,
223                                                    Depsgraph *graph)
224     : bmain_(bmain),
225       graph_(graph),
226       scene_(NULL)
227 {
228 }
229
230 TimeSourceDepsNode *DepsgraphRelationBuilder::get_node(
231         const TimeSourceKey &key) const
232 {
233         if (key.id) {
234                 /* XXX TODO */
235                 return NULL;
236         }
237         else {
238                 return graph_->time_source;
239         }
240 }
241
242 ComponentDepsNode *DepsgraphRelationBuilder::get_node(
243         const ComponentKey &key) const
244 {
245         IDDepsNode *id_node = graph_->find_id_node(key.id);
246         if (!id_node) {
247                 fprintf(stderr, "find_node component: Could not find ID %s\n",
248                         (key.id != NULL) ? key.id->name : "<null>");
249                 return NULL;
250         }
251
252         ComponentDepsNode *node = id_node->find_component(key.type, key.name);
253         return node;
254 }
255
256 OperationDepsNode *DepsgraphRelationBuilder::get_node(
257         const OperationKey &key) const
258 {
259         OperationDepsNode *op_node = find_node(key);
260         if (op_node == NULL) {
261                 fprintf(stderr, "find_node_operation: Failed for (%s, '%s')\n",
262                         operationCodeAsString(key.opcode), key.name);
263         }
264         return op_node;
265 }
266
267 DepsNode *DepsgraphRelationBuilder::get_node(const RNAPathKey &key) const
268 {
269         return graph_->find_node_from_pointer(&key.ptr, key.prop);
270 }
271
272 OperationDepsNode *DepsgraphRelationBuilder::find_node(
273         const OperationKey &key) const
274 {
275         IDDepsNode *id_node = graph_->find_id_node(key.id);
276         if (!id_node) {
277                 return NULL;
278         }
279         ComponentDepsNode *comp_node = id_node->find_component(key.component_type,
280                                                                key.component_name);
281         if (!comp_node) {
282                 return NULL;
283         }
284         return comp_node->find_operation(key.opcode, key.name, key.name_tag);
285 }
286
287 bool DepsgraphRelationBuilder::has_node(const OperationKey &key) const
288 {
289         return find_node(key) != NULL;
290 }
291
292 void DepsgraphRelationBuilder::add_customdata_mask(Object *object, uint64_t mask)
293 {
294         if (mask != 0 && object != NULL && object->type == OB_MESH) {
295                 DEG::IDDepsNode *id_node = graph_->find_id_node(&object->id);
296
297                 if (id_node == NULL) {
298                         BLI_assert(!"ID should always be valid");
299                 }
300                 else {
301                         id_node->customdata_mask |= mask;
302                 }
303         }
304 }
305
306 void DepsgraphRelationBuilder::add_special_eval_flag(ID *id, uint32_t flag)
307 {
308         DEG::IDDepsNode *id_node = graph_->find_id_node(id);
309         if (id_node == NULL) {
310                 BLI_assert(!"ID should always be valid");
311         }
312         else {
313                 id_node->eval_flags |= flag;
314         }
315 }
316
317 DepsRelation *DepsgraphRelationBuilder::add_time_relation(
318         TimeSourceDepsNode *timesrc,
319         DepsNode *node_to,
320         const char *description,
321         bool check_unique,
322         int flags)
323 {
324         if (timesrc && node_to) {
325                 return graph_->add_new_relation(
326                         timesrc, node_to, description, check_unique, flags);
327         }
328         else {
329                 DEG_DEBUG_PRINTF((::Depsgraph *)graph_,
330                                  BUILD, "add_time_relation(%p = %s, %p = %s, %s) Failed\n",
331                                  timesrc,   (timesrc) ? timesrc->identifier().c_str() : "<None>",
332                                  node_to,   (node_to) ? node_to->identifier().c_str() : "<None>",
333                                  description);
334         }
335         return NULL;
336 }
337
338 DepsRelation *DepsgraphRelationBuilder::add_operation_relation(
339         OperationDepsNode *node_from,
340         OperationDepsNode *node_to,
341         const char *description,
342         bool check_unique,
343         int flags)
344 {
345         if (node_from && node_to) {
346                 return graph_->add_new_relation(node_from,
347                                                 node_to,
348                                                 description,
349                                                 check_unique,
350                                                 flags);
351         }
352         else {
353                 DEG_DEBUG_PRINTF((::Depsgraph *)graph_,
354                                  BUILD, "add_operation_relation(%p = %s, %p = %s, %s) Failed\n",
355                                  node_from, (node_from) ? node_from->identifier().c_str() : "<None>",
356                                  node_to,   (node_to)   ? node_to->identifier().c_str() : "<None>",
357                                  description);
358         }
359         return NULL;
360 }
361
362 void DepsgraphRelationBuilder::add_collision_relations(
363         const OperationKey &key,
364         Object *object,
365         Collection *collection,
366         const char *name)
367 {
368         ListBase *relations = deg_build_collision_relations(graph_, collection, eModifierType_Collision);
369
370         LISTBASE_FOREACH (CollisionRelation *, relation, relations) {
371                 if (relation->ob != object) {
372                         ComponentKey trf_key(&relation->ob->id, DEG_NODE_TYPE_TRANSFORM);
373                         add_relation(trf_key, key, name);
374
375                         ComponentKey coll_key(&relation->ob->id, DEG_NODE_TYPE_GEOMETRY);
376                         add_relation(coll_key, key, name);
377                 }
378         }
379 }
380
381 void DepsgraphRelationBuilder::add_forcefield_relations(
382         const OperationKey &key,
383         Object *object,
384         ParticleSystem *psys,
385         EffectorWeights *eff,
386         bool add_absorption,
387         const char *name)
388 {
389         ListBase *relations = deg_build_effector_relations(graph_, eff->group);
390
391         LISTBASE_FOREACH (EffectorRelation *, relation, relations) {
392                 if (relation->ob != object) {
393                         ComponentKey eff_key(&relation->ob->id, DEG_NODE_TYPE_TRANSFORM);
394                         add_relation(eff_key, key, name);
395
396                         if (relation->pd->forcefield == PFIELD_SMOKEFLOW && relation->pd->f_source) {
397                                 ComponentKey trf_key(&relation->pd->f_source->id,
398                                                      DEG_NODE_TYPE_TRANSFORM);
399                                 add_relation(trf_key, key, "Smoke Force Domain");
400                                 ComponentKey eff_key(&relation->pd->f_source->id,
401                                                      DEG_NODE_TYPE_GEOMETRY);
402                                 add_relation(eff_key, key, "Smoke Force Domain");
403                         }
404                         if (add_absorption && (relation->pd->flag & PFIELD_VISIBILITY)) {
405                                 add_collision_relations(key,
406                                                         object,
407                                                         NULL,
408                                                         "Force Absorption");
409                         }
410                 }
411                 if (relation->psys) {
412                         if (relation->ob != object) {
413                                 ComponentKey eff_key(&relation->ob->id,
414                                                      DEG_NODE_TYPE_PARTICLE_SYSTEM);
415                                 add_relation(eff_key, key, name);
416                                 /* TODO: remove this when/if EVAL_PARTICLES is sufficient
417                                  * for up to date particles.
418                                  */
419                                 ComponentKey mod_key(&relation->ob->id, DEG_NODE_TYPE_GEOMETRY);
420                                 add_relation(mod_key, key, name);
421                         }
422                         else if (relation->psys != psys) {
423                                 OperationKey eff_key(&relation->ob->id,
424                                                      DEG_NODE_TYPE_PARTICLE_SYSTEM,
425                                                      DEG_OPCODE_PARTICLE_SYSTEM_EVAL,
426                                                      relation->psys->name);
427                                 add_relation(eff_key, key, name);
428                         }
429                 }
430         }
431 }
432
433 Depsgraph *DepsgraphRelationBuilder::getGraph()
434 {
435         return graph_;
436 }
437
438 /* **** Functions to build relations between entities  **** */
439
440 void DepsgraphRelationBuilder::begin_build()
441 {
442 }
443
444 void DepsgraphRelationBuilder::build_id(ID *id)
445 {
446         if (id == NULL) {
447                 return;
448         }
449         switch (GS(id->name)) {
450                 case ID_AC:
451                         build_action((bAction *)id);
452                         break;
453                 case ID_AR:
454                         build_armature((bArmature *)id);
455                         break;
456                 case ID_CA:
457                         build_camera((Camera *)id);
458                         break;
459                 case ID_GR:
460                         build_collection(NULL, NULL, (Collection *)id);
461                         break;
462                 case ID_OB:
463                         build_object(NULL, (Object *)id);
464                         break;
465                 case ID_KE:
466                         build_shapekeys((Key *)id);
467                         break;
468                 case ID_LA:
469                         build_lamp((Lamp *)id);
470                         break;
471                 case ID_LP:
472                         build_lightprobe((LightProbe *)id);
473                         break;
474                 case ID_NT:
475                         build_nodetree((bNodeTree *)id);
476                         break;
477                 case ID_MA:
478                         build_material((Material *)id);
479                         break;
480                 case ID_TE:
481                         build_texture((Tex *)id);
482                         break;
483                 case ID_WO:
484                         build_world((World *)id);
485                         break;
486                 case ID_MSK:
487                         build_mask((Mask *)id);
488                         break;
489                 case ID_MC:
490                         build_movieclip((MovieClip *)id);
491                         break;
492                 case ID_ME:
493                 case ID_CU:
494                 case ID_MB:
495                 case ID_LT:
496                         build_object_data_geometry_datablock(id);
497                         break;
498                 case ID_SPK:
499                         build_speaker((Speaker *)id);
500                         break;
501                 case ID_TXT:
502                         /* Not a part of dependency graph. */
503                         break;
504                 case ID_CF:
505                         build_cachefile((CacheFile *)id);
506                         break;
507                 default:
508                         fprintf(stderr, "Unhandled ID %s\n", id->name);
509                         BLI_assert(!"Should never happen");
510                         break;
511         }
512 }
513
514 void DepsgraphRelationBuilder::build_collection(
515         LayerCollection *from_layer_collection,
516         Object *object,
517         Collection *collection)
518 {
519         if (from_layer_collection != NULL) {
520                 /* If we came from layer collection we don't go deeper, view layer
521                  * builder takes care of going deeper.
522                  *
523                  * NOTE: Do early output before tagging build as done, so possbile
524                  * subsequent builds from outside of the layer collection properly
525                  * recurses into all the nested objects and collections. */
526                 return;
527         }
528         const bool group_done = built_map_.checkIsBuiltAndTag(collection);
529         OperationKey object_transform_final_key(object != NULL ? &object->id : NULL,
530                                                 DEG_NODE_TYPE_TRANSFORM,
531                                                 DEG_OPCODE_TRANSFORM_FINAL);
532         ComponentKey duplicator_key(object != NULL ? &object->id : NULL,
533                                     DEG_NODE_TYPE_DUPLI);
534         if (!group_done) {
535                 LISTBASE_FOREACH (CollectionObject *, cob, &collection->gobject) {
536                         build_object(NULL, cob->ob);
537                 }
538                 LISTBASE_FOREACH (CollectionChild *, child, &collection->children) {
539                         build_collection(NULL, NULL, child->collection);
540                 }
541         }
542         if (object != NULL) {
543                 FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_BEGIN(collection, ob, graph_->mode)
544                 {
545                         ComponentKey dupli_transform_key(&ob->id, DEG_NODE_TYPE_TRANSFORM);
546                         add_relation(dupli_transform_key,
547                                      object_transform_final_key,
548                                      "Dupligroup");
549                         /* Hook to special component, to ensure proper visibility/evaluation
550                          * optimizations.
551                          */
552                         add_relation(dupli_transform_key, duplicator_key, "Dupligroup");
553                         const eDepsNode_Type dupli_geometry_component_type =
554                                 deg_geometry_tag_to_component(&ob->id);
555                         if (dupli_geometry_component_type != DEG_NODE_TYPE_UNDEFINED) {
556                                 ComponentKey dupli_geometry_component_key(
557                                         &ob->id, dupli_geometry_component_type);
558                                 add_relation(dupli_geometry_component_key,
559                                              duplicator_key,
560                                              "Dupligroup");
561                         }
562                 }
563                 FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_END;
564         }
565 }
566
567 void DepsgraphRelationBuilder::build_object(Base *base, Object *object)
568 {
569         if (built_map_.checkIsBuiltAndTag(object)) {
570                 if (base != NULL) {
571                         build_object_flags(base, object);
572                 }
573                 return;
574         }
575         /* Object Transforms */
576         eDepsOperation_Code base_op = (object->parent) ? DEG_OPCODE_TRANSFORM_PARENT
577                                                        : DEG_OPCODE_TRANSFORM_LOCAL;
578         OperationKey base_op_key(&object->id, DEG_NODE_TYPE_TRANSFORM, base_op);
579         OperationKey local_transform_key(&object->id,
580                                          DEG_NODE_TYPE_TRANSFORM,
581                                          DEG_OPCODE_TRANSFORM_LOCAL);
582         OperationKey parent_transform_key(&object->id,
583                                           DEG_NODE_TYPE_TRANSFORM,
584                                           DEG_OPCODE_TRANSFORM_PARENT);
585         OperationKey final_transform_key(&object->id,
586                                          DEG_NODE_TYPE_TRANSFORM,
587                                          DEG_OPCODE_TRANSFORM_FINAL);
588         OperationKey ob_ubereval_key(&object->id,
589                                      DEG_NODE_TYPE_TRANSFORM,
590                                      DEG_OPCODE_TRANSFORM_OBJECT_UBEREVAL);
591         /* Various flags, flushing from bases/collections. */
592         build_object_flags(base, object);
593         /* Parenting. */
594         if (object->parent != NULL) {
595                 /* Make sure parent object's relations are built. */
596                 build_object(NULL, object->parent);
597                 /* Parent relationship. */
598                 build_object_parent(object);
599                 /* Local -> parent. */
600                 add_relation(local_transform_key,
601                              parent_transform_key,
602                              "ObLocal -> ObParent");
603         }
604         /* Modifiers. */
605         if (object->modifiers.first != NULL) {
606                 BuilderWalkUserData data;
607                 data.builder = this;
608                 modifiers_foreachIDLink(object, modifier_walk, &data);
609         }
610         /* Grease Pencil Modifiers. */
611         if (object->greasepencil_modifiers.first != NULL) {
612                 BuilderWalkUserData data;
613                 data.builder = this;
614                 BKE_gpencil_modifiers_foreachIDLink(object, modifier_walk, &data);
615         }
616         /* Shader FX. */
617         if (object->shader_fx.first != NULL) {
618                 BuilderWalkUserData data;
619                 data.builder = this;
620                 BKE_shaderfx_foreachIDLink(object, modifier_walk, &data);
621         }
622         /* Constraints. */
623         if (object->constraints.first != NULL) {
624                 BuilderWalkUserData data;
625                 data.builder = this;
626                 BKE_constraints_id_loop(&object->constraints, constraint_walk, &data);
627         }
628         /* Object constraints. */
629         if (object->constraints.first != NULL) {
630                 OperationKey constraint_key(&object->id,
631                                             DEG_NODE_TYPE_TRANSFORM,
632                                             DEG_OPCODE_TRANSFORM_CONSTRAINTS);
633                 /* Constraint relations. */
634                 build_constraints(&object->id,
635                                   DEG_NODE_TYPE_TRANSFORM,
636                                   "",
637                                   &object->constraints,
638                                   NULL);
639                 /* operation order */
640                 add_relation(base_op_key, constraint_key, "ObBase-> Constraint Stack");
641                 add_relation(constraint_key, final_transform_key, "ObConstraints -> Done");
642                 // XXX
643                 add_relation(constraint_key, ob_ubereval_key, "Temp Ubereval");
644                 add_relation(ob_ubereval_key, final_transform_key, "Temp Ubereval");
645         }
646         else {
647                 /* NOTE: Keep an eye here, we skip some relations here to "streamline"
648                  * dependencies and avoid transitive relations which causes overhead.
649                  * But once we get rid of uber eval node this will need reconsideration.
650                  */
651                 if (object->rigidbody_object == NULL) {
652                         /* Rigid body will hook up another node inbetween, so skip
653                          * relation here to avoid transitive relation.
654                          */
655                         add_relation(base_op_key, ob_ubereval_key, "Temp Ubereval");
656                 }
657                 add_relation(ob_ubereval_key, final_transform_key, "Temp Ubereval");
658         }
659         /* Animation data */
660         build_animdata(&object->id);
661         /* Object data. */
662         build_object_data(object);
663         /* Particle systems. */
664         if (object->particlesystem.first != NULL) {
665                 build_particle_systems(object);
666         }
667         /* Proxy object to copy from. */
668         if (object->proxy_from != NULL) {
669                 build_object(NULL, object->proxy_from);
670                 ComponentKey ob_transform_key(&object->proxy_from->id, DEG_NODE_TYPE_TRANSFORM);
671                 ComponentKey proxy_transform_key(&object->id, DEG_NODE_TYPE_TRANSFORM);
672                 add_relation(ob_transform_key, proxy_transform_key, "Proxy Transform");
673         }
674         if (object->proxy_group != NULL) {
675                 build_object(NULL, object->proxy_group);
676                 OperationKey proxy_group_ubereval_key(&object->proxy_group->id,
677                                                       DEG_NODE_TYPE_TRANSFORM,
678                                                       DEG_OPCODE_TRANSFORM_OBJECT_UBEREVAL);
679                 add_relation(proxy_group_ubereval_key, final_transform_key, "Proxy Group Transform");
680         }
681         /* Object dupligroup. */
682         if (object->dup_group != NULL) {
683                 build_collection(NULL, object, object->dup_group);
684         }
685         /* Point caches. */
686         build_object_pointcache(object);
687         /* Syncronization back to original object. */
688         OperationKey synchronize_key(&object->id,
689                                      DEG_NODE_TYPE_SYNCHRONIZE,
690                                      DEG_OPCODE_SYNCHRONIZE_TO_ORIGINAL);
691         add_relation(
692                 final_transform_key, synchronize_key, "Synchronize to Original");
693 }
694
695 void DepsgraphRelationBuilder::build_object_flags(Base *base, Object *object)
696 {
697         if (base == NULL) {
698                 return;
699         }
700         OperationKey view_layer_done_key(&scene_->id,
701                                          DEG_NODE_TYPE_LAYER_COLLECTIONS,
702                                          DEG_OPCODE_VIEW_LAYER_EVAL);
703         OperationKey object_flags_key(&object->id,
704                                       DEG_NODE_TYPE_OBJECT_FROM_LAYER,
705                                       DEG_OPCODE_OBJECT_BASE_FLAGS);
706         add_relation(view_layer_done_key, object_flags_key, "Base flags flush");
707         /* Syncronization back to original object. */
708         OperationKey synchronize_key(&object->id,
709                                      DEG_NODE_TYPE_SYNCHRONIZE,
710                                      DEG_OPCODE_SYNCHRONIZE_TO_ORIGINAL);
711         add_relation(
712                 object_flags_key, synchronize_key, "Synchronize to Original");
713 }
714
715 void DepsgraphRelationBuilder::build_object_data(Object *object)
716 {
717         if (object->data == NULL) {
718                 return;
719         }
720         ID *obdata_id = (ID *)object->data;
721         /* Object data animation. */
722         if (!built_map_.checkIsBuilt(obdata_id)) {
723                 build_animdata(obdata_id);
724         }
725         /* type-specific data. */
726         switch (object->type) {
727                 case OB_MESH:
728                 case OB_CURVE:
729                 case OB_FONT:
730                 case OB_SURF:
731                 case OB_MBALL:
732                 case OB_LATTICE:
733                 case OB_GPENCIL:
734                 {
735                         build_object_data_geometry(object);
736                         /* TODO(sergey): Only for until we support granular
737                          * update of curves.
738                          */
739                         if (object->type == OB_FONT) {
740                                 Curve *curve = (Curve *)object->data;
741                                 if (curve->textoncurve) {
742                                         add_special_eval_flag(&curve->textoncurve->id, DAG_EVAL_NEED_CURVE_PATH);
743                                 }
744                         }
745                         break;
746                 }
747                 case OB_ARMATURE:
748                         if (ID_IS_LINKED(object) && object->proxy_from != NULL) {
749                                 build_proxy_rig(object);
750                         }
751                         else {
752                                  build_rig(object);
753                         }
754                         break;
755                 case OB_LAMP:
756                         build_object_data_lamp(object);
757                         break;
758                 case OB_CAMERA:
759                         build_object_data_camera(object);
760                         break;
761                 case OB_LIGHTPROBE:
762                         build_object_data_lightprobe(object);
763                         break;
764                 case OB_SPEAKER:
765                         build_object_data_speaker(object);
766                         break;
767         }
768         Key *key = BKE_key_from_object(object);
769         if (key != NULL) {
770                 ComponentKey geometry_key((ID *)object->data, DEG_NODE_TYPE_GEOMETRY);
771                 ComponentKey key_key(&key->id, DEG_NODE_TYPE_GEOMETRY);
772                 add_relation(key_key, geometry_key, "Shapekeys");
773                 build_nested_shapekey(&object->id, key);
774         }
775 }
776
777 void DepsgraphRelationBuilder::build_object_data_camera(Object *object)
778 {
779         Camera *camera = (Camera *)object->data;
780         build_camera(camera);
781         ComponentKey object_parameters_key(&object->id, DEG_NODE_TYPE_PARAMETERS);
782         ComponentKey camera_parameters_key(&camera->id, DEG_NODE_TYPE_PARAMETERS);
783         add_relation(camera_parameters_key, object_parameters_key, "Camera -> Object");
784 }
785
786 void DepsgraphRelationBuilder::build_object_data_lamp(Object *object)
787 {
788         Lamp *lamp = (Lamp *)object->data;
789         build_lamp(lamp);
790         ComponentKey object_parameters_key(&object->id, DEG_NODE_TYPE_PARAMETERS);
791         ComponentKey lamp_parameters_key(&lamp->id, DEG_NODE_TYPE_PARAMETERS);
792         add_relation(lamp_parameters_key, object_parameters_key, "Light -> Object");
793 }
794
795 void DepsgraphRelationBuilder::build_object_data_lightprobe(Object *object)
796 {
797         LightProbe *probe = (LightProbe *)object->data;
798         build_lightprobe(probe);
799         OperationKey probe_key(&probe->id,
800                                DEG_NODE_TYPE_PARAMETERS,
801                                DEG_OPCODE_LIGHT_PROBE_EVAL);
802         OperationKey object_key(&object->id,
803                                 DEG_NODE_TYPE_PARAMETERS,
804                                 DEG_OPCODE_LIGHT_PROBE_EVAL);
805         add_relation(probe_key, object_key, "LightProbe Update");
806 }
807
808 void DepsgraphRelationBuilder::build_object_data_speaker(Object *object)
809 {
810         Speaker *speaker = (Speaker *)object->data;
811         build_speaker(speaker);
812         OperationKey probe_key(&speaker->id,
813                                DEG_NODE_TYPE_PARAMETERS,
814                                DEG_OPCODE_SPEAKER_EVAL);
815         OperationKey object_key(&object->id,
816                                 DEG_NODE_TYPE_PARAMETERS,
817                                 DEG_OPCODE_SPEAKER_EVAL);
818         add_relation(probe_key, object_key, "Speaker Update");
819 }
820
821 void DepsgraphRelationBuilder::build_object_parent(Object *object)
822 {
823         /* XXX: for now, need to use the component key (not just direct to the parent op),
824          * or else the matrix doesn't get reset/
825          */
826         // XXX: @sergey - it would be good if we got that backwards flushing working
827         // when tagging for updates.
828         //OperationKey ob_key(&object->id, DEG_NODE_TYPE_TRANSFORM, DEG_OPCODE_TRANSFORM_PARENT);
829         ComponentKey ob_key(&object->id, DEG_NODE_TYPE_TRANSFORM);
830
831         /* type-specific links */
832         switch (object->partype) {
833                 case PARSKEL:  /* Armature Deform (Virtual Modifier) */
834                 {
835                         ComponentKey parent_key(&object->parent->id, DEG_NODE_TYPE_TRANSFORM);
836                         add_relation(parent_key, ob_key, "Armature Deform Parent");
837                         break;
838                 }
839
840                 case PARVERT1: /* Vertex Parent */
841                 case PARVERT3:
842                 {
843                         ComponentKey parent_key(&object->parent->id, DEG_NODE_TYPE_GEOMETRY);
844                         add_relation(parent_key, ob_key, "Vertex Parent");
845
846                         /* XXX not sure what this is for or how you could be done properly - lukas */
847                         add_customdata_mask(object->parent, CD_MASK_ORIGINDEX);
848
849                         ComponentKey transform_key(&object->parent->id, DEG_NODE_TYPE_TRANSFORM);
850                         add_relation(transform_key, ob_key, "Vertex Parent TFM");
851                         break;
852                 }
853
854                 case PARBONE: /* Bone Parent */
855                 {
856                         ComponentKey parent_bone_key(&object->parent->id,
857                                                      DEG_NODE_TYPE_BONE,
858                                                      object->parsubstr);
859                         OperationKey parent_transform_key(&object->parent->id,
860                                                           DEG_NODE_TYPE_TRANSFORM,
861                                                           DEG_OPCODE_TRANSFORM_FINAL);
862                         add_relation(parent_bone_key, ob_key, "Bone Parent");
863                         add_relation(parent_transform_key, ob_key, "Armature Parent");
864                         break;
865                 }
866
867                 default:
868                 {
869                         if (object->parent->type == OB_LATTICE) {
870                                 /* Lattice Deform Parent - Virtual Modifier */
871                                 // XXX: no virtual modifiers should be left!
872                                 ComponentKey parent_key(&object->parent->id, DEG_NODE_TYPE_TRANSFORM);
873                                 ComponentKey geom_key(&object->parent->id, DEG_NODE_TYPE_GEOMETRY);
874
875                                 add_relation(parent_key, ob_key, "Lattice Deform Parent");
876                                 add_relation(geom_key, ob_key, "Lattice Deform Parent Geom");
877                         }
878                         else if (object->parent->type == OB_CURVE) {
879                                 Curve *cu = (Curve *)object->parent->data;
880
881                                 if (cu->flag & CU_PATH) {
882                                         /* Follow Path */
883                                         ComponentKey parent_key(&object->parent->id, DEG_NODE_TYPE_GEOMETRY);
884                                         add_relation(parent_key, ob_key, "Curve Follow Parent");
885
886                                         ComponentKey transform_key(&object->parent->id, DEG_NODE_TYPE_TRANSFORM);
887                                         add_relation(transform_key, ob_key, "Curve Follow TFM");
888                                 }
889                                 else {
890                                         /* Standard Parent */
891                                         ComponentKey parent_key(&object->parent->id, DEG_NODE_TYPE_TRANSFORM);
892                                         add_relation(parent_key, ob_key, "Curve Parent");
893                                 }
894                         }
895                         else {
896                                 /* Standard Parent */
897                                 ComponentKey parent_key(&object->parent->id, DEG_NODE_TYPE_TRANSFORM);
898                                 add_relation(parent_key, ob_key, "Parent");
899                         }
900                         break;
901                 }
902         }
903 }
904
905 void DepsgraphRelationBuilder::build_object_pointcache(Object *object)
906 {
907         ComponentKey point_cache_key(&object->id, DEG_NODE_TYPE_POINT_CACHE);
908         /* Different point caches are affecting different aspects of life of the
909          * object. We keep track of those aspects and avoid duplicate relations. */
910         enum {
911                 FLAG_TRANSFORM = (1 << 0),
912                 FLAG_GEOMETRY = (1 << 1),
913                 FLAG_ALL = (FLAG_TRANSFORM | FLAG_GEOMETRY),
914         };
915         ListBase ptcache_id_list;
916         BKE_ptcache_ids_from_object(&ptcache_id_list, object, scene_, 0);
917         int handled_components = 0;
918         LISTBASE_FOREACH (PTCacheID *, ptcache_id, &ptcache_id_list) {
919                 /* Check which components needs the point cache. */
920                 int flag;
921                 if (ptcache_id->type == PTCACHE_TYPE_RIGIDBODY) {
922                         flag = FLAG_TRANSFORM;
923                         ComponentKey transform_key(&object->id,
924                                                    DEG_NODE_TYPE_TRANSFORM);
925                         add_relation(point_cache_key,
926                                      transform_key,
927                                      "Point Cache -> Rigid Body");
928                 }
929                 else {
930                         flag = FLAG_GEOMETRY;
931                         ComponentKey geometry_key(&object->id,
932                                                    DEG_NODE_TYPE_GEOMETRY);
933                         add_relation(point_cache_key,
934                                      geometry_key,
935                                      "Point Cache -> Geometry");
936                 }
937                 /* Tag that we did handle that component. */
938                 handled_components |= flag;
939                 if (handled_components == FLAG_ALL) {
940                         break;
941                 }
942         }
943         BLI_freelistN(&ptcache_id_list);
944 }
945
946 void DepsgraphRelationBuilder::build_constraints(ID *id,
947                                                  eDepsNode_Type component_type,
948                                                  const char *component_subdata,
949                                                  ListBase *constraints,
950                                                  RootPChanMap *root_map)
951 {
952         OperationKey constraint_op_key(
953                 id,
954                 component_type,
955                 component_subdata,
956                 (component_type == DEG_NODE_TYPE_BONE)
957                         ? DEG_OPCODE_BONE_CONSTRAINTS
958                         : DEG_OPCODE_TRANSFORM_CONSTRAINTS);
959         /* Add dependencies for each constraint in turn. */
960         for (bConstraint *con = (bConstraint *)constraints->first; con; con = con->next) {
961                 const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
962                 /* Invalid constraint type. */
963                 if (cti == NULL) {
964                         continue;
965                 }
966                 /* Special case for camera tracking -- it doesn't use targets to
967                  * define relations.
968                  */
969                 /* TODO: we can now represent dependencies in a much richer manner,
970                  * so review how this is done.
971                  */
972                 if (ELEM(cti->type,
973                          CONSTRAINT_TYPE_FOLLOWTRACK,
974                          CONSTRAINT_TYPE_CAMERASOLVER,
975                          CONSTRAINT_TYPE_OBJECTSOLVER))
976                 {
977                         bool depends_on_camera = false;
978                         if (cti->type == CONSTRAINT_TYPE_FOLLOWTRACK) {
979                                 bFollowTrackConstraint *data = (bFollowTrackConstraint *)con->data;
980                                 if (((data->clip) ||
981                                      (data->flag & FOLLOWTRACK_ACTIVECLIP)) && data->track[0])
982                                 {
983                                         depends_on_camera = true;
984                                 }
985                                 if (data->depth_ob) {
986                                         ComponentKey depth_transform_key(&data->depth_ob->id,
987                                                                          DEG_NODE_TYPE_TRANSFORM);
988                                         ComponentKey depth_geometry_key(&data->depth_ob->id,
989                                                                         DEG_NODE_TYPE_GEOMETRY);
990                                         add_relation(depth_transform_key, constraint_op_key, cti->name);
991                                         add_relation(depth_geometry_key, constraint_op_key, cti->name);
992                                 }
993                         }
994                         else if (cti->type == CONSTRAINT_TYPE_OBJECTSOLVER) {
995                                 depends_on_camera = true;
996                         }
997                         if (depends_on_camera && scene_->camera != NULL) {
998                                 ComponentKey camera_key(&scene_->camera->id, DEG_NODE_TYPE_TRANSFORM);
999                                 add_relation(camera_key, constraint_op_key, cti->name);
1000                         }
1001                         /* TODO(sergey): This is more a TimeSource -> MovieClip ->
1002                          * Constraint dependency chain.
1003                          */
1004                         TimeSourceKey time_src_key;
1005                         add_relation(time_src_key, constraint_op_key, "TimeSrc -> Animation");
1006                 }
1007                 else if (cti->type == CONSTRAINT_TYPE_TRANSFORM_CACHE) {
1008                         /* TODO(kevin): This is more a TimeSource -> CacheFile -> Constraint
1009                          * dependency chain.
1010                          */
1011                         TimeSourceKey time_src_key;
1012                         add_relation(time_src_key, constraint_op_key, "TimeSrc -> Animation");
1013                         bTransformCacheConstraint *data = (bTransformCacheConstraint *)con->data;
1014                         if (data->cache_file) {
1015                                 ComponentKey cache_key(&data->cache_file->id, DEG_NODE_TYPE_CACHE);
1016                                 add_relation(cache_key, constraint_op_key, cti->name);
1017                         }
1018                 }
1019                 else if (cti->get_constraint_targets) {
1020                         ListBase targets = {NULL, NULL};
1021                         cti->get_constraint_targets(con, &targets);
1022                         LISTBASE_FOREACH (bConstraintTarget *, ct, &targets) {
1023                                 if (ct->tar == NULL) {
1024                                         continue;
1025                                 }
1026                                 if (ELEM(con->type,
1027                                          CONSTRAINT_TYPE_KINEMATIC,
1028                                          CONSTRAINT_TYPE_SPLINEIK))
1029                                 {
1030                                         /* Ignore IK constraints - these are handled separately
1031                                          * (on pose level).
1032                                          */
1033                                 }
1034                                 else if (ELEM(con->type,
1035                                               CONSTRAINT_TYPE_FOLLOWPATH,
1036                                               CONSTRAINT_TYPE_CLAMPTO))
1037                                 {
1038                                         /* These constraints require path geometry data. */
1039                                         ComponentKey target_key(&ct->tar->id, DEG_NODE_TYPE_GEOMETRY);
1040                                         add_relation(target_key, constraint_op_key, cti->name);
1041                                         ComponentKey target_transform_key(&ct->tar->id,
1042                                                                           DEG_NODE_TYPE_TRANSFORM);
1043                                         add_relation(target_transform_key, constraint_op_key, cti->name);
1044                                 }
1045                                 else if ((ct->tar->type == OB_ARMATURE) && (ct->subtarget[0])) {
1046                                         eDepsOperation_Code opcode;
1047                                         /* relation to bone */
1048                                         opcode = bone_target_opcode(&ct->tar->id, ct->subtarget,
1049                                                                     id, component_subdata, root_map);
1050                                         /* Armature constraint always wants the final position and chan_mat. */
1051                                         if (ELEM(con->type, CONSTRAINT_TYPE_ARMATURE)) {
1052                                                 opcode = DEG_OPCODE_BONE_DONE;
1053                                         }
1054                                         /* if needs bbone shape, reference the segment computation */
1055                                         if (BKE_constraint_target_uses_bbone(con, ct) &&
1056                                             bone_has_segments(ct->tar, ct->subtarget))
1057                                         {
1058                                                 opcode = DEG_OPCODE_BONE_SEGMENTS;
1059                                         }
1060                                         OperationKey target_key(&ct->tar->id,
1061                                                                 DEG_NODE_TYPE_BONE,
1062                                                                 ct->subtarget,
1063                                                                 opcode);
1064                                         add_relation(target_key, constraint_op_key, cti->name);
1065                                 }
1066                                 else if (ELEM(ct->tar->type, OB_MESH, OB_LATTICE) &&
1067                                          (ct->subtarget[0]))
1068                                 {
1069                                         /* Vertex group. */
1070                                         /* NOTE: for now, we don't need to represent vertex groups
1071                                          * separately.
1072                                          */
1073                                         ComponentKey target_key(&ct->tar->id, DEG_NODE_TYPE_GEOMETRY);
1074                                         add_relation(target_key, constraint_op_key, cti->name);
1075                                         add_customdata_mask(ct->tar, CD_MASK_MDEFORMVERT);
1076                                 }
1077                                 else if (con->type == CONSTRAINT_TYPE_SHRINKWRAP) {
1078                                         bShrinkwrapConstraint *scon = (bShrinkwrapConstraint *) con->data;
1079
1080                                         /* Constraints which requires the target object surface. */
1081                                         ComponentKey target_key(&ct->tar->id, DEG_NODE_TYPE_GEOMETRY);
1082                                         add_relation(target_key, constraint_op_key, cti->name);
1083
1084                                         /* Add dependency on normal layers if necessary. */
1085                                         if (ct->tar->type == OB_MESH && scon->shrinkType != MOD_SHRINKWRAP_NEAREST_VERTEX) {
1086                                                 bool track = (scon->flag & CON_SHRINKWRAP_TRACK_NORMAL) != 0;
1087                                                 if (track || BKE_shrinkwrap_needs_normals(scon->shrinkType, scon->shrinkMode)) {
1088                                                         add_customdata_mask(ct->tar, CD_MASK_NORMAL | CD_MASK_CUSTOMLOOPNORMAL);
1089                                                 }
1090                                                 if (scon->shrinkType == MOD_SHRINKWRAP_TARGET_PROJECT) {
1091                                                         add_special_eval_flag(&ct->tar->id, DAG_EVAL_NEED_SHRINKWRAP_BOUNDARY);
1092                                                 }
1093                                         }
1094
1095                                         /* NOTE: obdata eval now doesn't necessarily depend on the
1096                                          * object's transform.
1097                                          */
1098                                         ComponentKey target_transform_key(&ct->tar->id,
1099                                                                           DEG_NODE_TYPE_TRANSFORM);
1100                                         add_relation(target_transform_key, constraint_op_key, cti->name);
1101                                 }
1102                                 else {
1103                                         /* Standard object relation. */
1104                                         // TODO: loc vs rot vs scale?
1105                                         if (&ct->tar->id == id) {
1106                                                 /* Constraint targeting own object:
1107                                                  * - This case is fine IFF we're dealing with a bone
1108                                                  *   constraint pointing to its own armature. In that
1109                                                  *   case, it's just transform -> bone.
1110                                                  * - If however it is a real self targeting case, just
1111                                                  *   make it depend on the previous constraint (or the
1112                                                  *   pre-constraint state).
1113                                                  */
1114                                                 if ((ct->tar->type == OB_ARMATURE) &&
1115                                                     (component_type == DEG_NODE_TYPE_BONE))
1116                                                 {
1117                                                         OperationKey target_key(&ct->tar->id,
1118                                                                                 DEG_NODE_TYPE_TRANSFORM,
1119                                                                                 DEG_OPCODE_TRANSFORM_FINAL);
1120                                                         add_relation(target_key, constraint_op_key, cti->name);
1121                                                 }
1122                                                 else {
1123                                                         OperationKey target_key(&ct->tar->id,
1124                                                                                 DEG_NODE_TYPE_TRANSFORM,
1125                                                                                 DEG_OPCODE_TRANSFORM_LOCAL);
1126                                                         add_relation(target_key, constraint_op_key, cti->name);
1127                                                 }
1128                                         }
1129                                         else {
1130                                                 /* Normal object dependency. */
1131                                                 OperationKey target_key(&ct->tar->id,
1132                                                                         DEG_NODE_TYPE_TRANSFORM,
1133                                                                         DEG_OPCODE_TRANSFORM_FINAL);
1134                                                 add_relation(target_key, constraint_op_key, cti->name);
1135                                         }
1136                                 }
1137                                 /* Constraints which needs world's matrix for transform.
1138                                  * TODO(sergey): More constraints here?
1139                                  */
1140                                 if (ELEM(con->type,
1141                                          CONSTRAINT_TYPE_ROTLIKE,
1142                                          CONSTRAINT_TYPE_SIZELIKE,
1143                                          CONSTRAINT_TYPE_LOCLIKE,
1144                                          CONSTRAINT_TYPE_TRANSLIKE))
1145                                 {
1146                                         /* TODO(sergey): Add used space check. */
1147                                         ComponentKey target_transform_key(&ct->tar->id,
1148                                                                           DEG_NODE_TYPE_TRANSFORM);
1149                                         add_relation(target_transform_key, constraint_op_key, cti->name);
1150                                 }
1151                         }
1152                         if (cti->flush_constraint_targets) {
1153                                 cti->flush_constraint_targets(con, &targets, 1);
1154                         }
1155                 }
1156         }
1157 }
1158
1159 void DepsgraphRelationBuilder::build_animdata(ID *id)
1160 {
1161         /* Animation curves and NLA. */
1162         build_animdata_curves(id);
1163         /* Drivers. */
1164         build_animdata_drivers(id);
1165 }
1166
1167 void DepsgraphRelationBuilder::build_animdata_curves(ID *id)
1168 {
1169         AnimData *adt = BKE_animdata_from_id(id);
1170         if (adt == NULL) {
1171                 return;
1172         }
1173         if (adt->action != NULL) {
1174                 build_action(adt->action);
1175         }
1176         if (adt->action == NULL && adt->nla_tracks.first == NULL) {
1177                 return;
1178         }
1179         /* Wire up dependency to time source. */
1180         ComponentKey adt_key(id, DEG_NODE_TYPE_ANIMATION);
1181         /* Relation from action itself. */
1182         if (adt->action != NULL) {
1183                 ComponentKey action_key(&adt->action->id, DEG_NODE_TYPE_ANIMATION);
1184                 add_relation(action_key, adt_key, "Action -> Animation");
1185         }
1186         /* Get source operations. */
1187         DepsNode *node_from = get_node(adt_key);
1188         BLI_assert(node_from != NULL);
1189         if (node_from == NULL) {
1190                 return;
1191         }
1192         OperationDepsNode *operation_from = node_from->get_exit_operation();
1193         BLI_assert(operation_from != NULL);
1194         /* Build relations from animation operation to properties it changes. */
1195         if (adt->action != NULL) {
1196                 build_animdata_curves_targets(id, adt_key,
1197                                       operation_from,
1198                                       &adt->action->curves);
1199         }
1200         LISTBASE_FOREACH(NlaTrack *, nlt, &adt->nla_tracks) {
1201                 build_animdata_nlastrip_targets(id, adt_key,
1202                                                 operation_from,
1203                                                 &nlt->strips);
1204         }
1205 }
1206
1207 void DepsgraphRelationBuilder::build_animdata_curves_targets(
1208         ID *id, ComponentKey &adt_key,
1209         OperationDepsNode *operation_from,
1210         ListBase *curves)
1211 {
1212         /* Iterate over all curves and build relations. */
1213         PointerRNA id_ptr;
1214         RNA_id_pointer_create(id, &id_ptr);
1215         LISTBASE_FOREACH(FCurve *, fcu, curves) {
1216                 PointerRNA ptr;
1217                 PropertyRNA *prop;
1218                 int index;
1219                 if (!RNA_path_resolve_full(&id_ptr, fcu->rna_path,
1220                                            &ptr, &prop, &index))
1221                 {
1222                         continue;
1223                 }
1224                 DepsNode *node_to = graph_->find_node_from_pointer(&ptr, prop);
1225                 if (node_to == NULL) {
1226                         continue;
1227                 }
1228                 OperationDepsNode *operation_to = node_to->get_entry_operation();
1229                 /* NOTE: Special case for bones, avoid relation from animation to
1230                  * each of the bones. Bone evaluation could only start from pose
1231                  * init anyway.
1232                  */
1233                 if (operation_to->opcode == DEG_OPCODE_BONE_LOCAL) {
1234                         OperationKey pose_init_key(id,
1235                                                    DEG_NODE_TYPE_EVAL_POSE,
1236                                                    DEG_OPCODE_POSE_INIT);
1237                         add_relation(adt_key, pose_init_key, "Animation -> Prop", true);
1238                         continue;
1239                 }
1240                 graph_->add_new_relation(operation_from, operation_to,
1241                                          "Animation -> Prop",
1242                                          true);
1243                 /* It is possible that animation is writing to a nested ID datablock,
1244                  * need to make sure animation is evaluated after target ID is copied.
1245                  */
1246                 const IDDepsNode *id_node_from = operation_from->owner->owner;
1247                 const IDDepsNode *id_node_to = operation_to->owner->owner;
1248                 if (id_node_from != id_node_to) {
1249                         ComponentKey cow_key(id_node_to->id_orig,
1250                                              DEG_NODE_TYPE_COPY_ON_WRITE);
1251                         add_relation(cow_key, adt_key, "Target CoW -> Animation", true);
1252                 }
1253         }
1254 }
1255
1256 void DepsgraphRelationBuilder::build_animdata_nlastrip_targets(
1257         ID *id, ComponentKey &adt_key,
1258         OperationDepsNode *operation_from,
1259         ListBase *strips)
1260 {
1261         LISTBASE_FOREACH(NlaStrip *, strip, strips) {
1262                 if (strip->act != NULL) {
1263                         build_action(strip->act);
1264
1265                         ComponentKey action_key(&strip->act->id, DEG_NODE_TYPE_ANIMATION);
1266                         add_relation(action_key, adt_key, "Action -> Animation");
1267
1268                         build_animdata_curves_targets(id, adt_key,
1269                                                       operation_from,
1270                                                       &strip->act->curves);
1271                 }
1272                 else if (strip->strips.first != NULL) {
1273                         build_animdata_nlastrip_targets(id, adt_key,
1274                                                         operation_from,
1275                                                         &strip->strips);
1276                 }
1277         }
1278 }
1279
1280 void DepsgraphRelationBuilder::build_animdata_drivers(ID *id)
1281 {
1282         AnimData *adt = BKE_animdata_from_id(id);
1283         if (adt == NULL) {
1284                 return;
1285         }
1286         ComponentKey adt_key(id, DEG_NODE_TYPE_ANIMATION);
1287         LISTBASE_FOREACH (FCurve *, fcu, &adt->drivers) {
1288                 OperationKey driver_key(id,
1289                                         DEG_NODE_TYPE_PARAMETERS,
1290                                         DEG_OPCODE_DRIVER,
1291                                         fcu->rna_path ? fcu->rna_path : "",
1292                                         fcu->array_index);
1293
1294                 /* create the driver's relations to targets */
1295                 build_driver(id, fcu);
1296                 /* Special case for array drivers: we can not multithread them because
1297                  * of the way how they work internally: animation system will write the
1298                  * whole array back to RNA even when changing individual array value.
1299                  *
1300                  * Some tricky things here:
1301                  * - array_index is -1 for single channel drivers, meaning we only have
1302                  *   to do some magic when array_index is not -1.
1303                  * - We do relation from next array index to a previous one, so we don't
1304                  *   have to deal with array index 0.
1305                  *
1306                  * TODO(sergey): Avoid liner lookup somehow.
1307                  */
1308                 if (fcu->array_index > 0) {
1309                         FCurve *fcu_prev = NULL;
1310                         LISTBASE_FOREACH (FCurve *, fcu_candidate, &adt->drivers) {
1311                                 /* Writing to different RNA paths is  */
1312                                 const char *rna_path = fcu->rna_path ? fcu->rna_path : "";
1313                                 if (!STREQ(fcu_candidate->rna_path, rna_path)) {
1314                                         continue;
1315                                 }
1316                                 /* We only do relation from previous fcurve to previous one. */
1317                                 if (fcu_candidate->array_index >= fcu->array_index) {
1318                                         continue;
1319                                 }
1320                                 /* Choose fcurve with highest possible array index. */
1321                                 if (fcu_prev == NULL ||
1322                                     fcu_candidate->array_index > fcu_prev->array_index)
1323                                 {
1324                                         fcu_prev = fcu_candidate;
1325                                 }
1326                         }
1327                         if (fcu_prev != NULL) {
1328                                 OperationKey prev_driver_key(id,
1329                                                              DEG_NODE_TYPE_PARAMETERS,
1330                                                              DEG_OPCODE_DRIVER,
1331                                                              fcu_prev->rna_path ? fcu_prev->rna_path : "",
1332                                                              fcu_prev->array_index);
1333                                 OperationKey driver_key(id,
1334                                                         DEG_NODE_TYPE_PARAMETERS,
1335                                                         DEG_OPCODE_DRIVER,
1336                                                         fcu->rna_path ? fcu->rna_path : "",
1337                                                         fcu->array_index);
1338                                 add_relation(prev_driver_key, driver_key, "Driver Order");
1339                         }
1340                 }
1341
1342                 /* prevent driver from occurring before own animation... */
1343                 if (adt->action || adt->nla_tracks.first) {
1344                         add_relation(adt_key, driver_key, "AnimData Before Drivers");
1345                 }
1346         }
1347 }
1348
1349 void DepsgraphRelationBuilder::build_action(bAction *action)
1350 {
1351         if (built_map_.checkIsBuiltAndTag(action)) {
1352                 return;
1353         }
1354         TimeSourceKey time_src_key;
1355         ComponentKey animation_key(&action->id, DEG_NODE_TYPE_ANIMATION);
1356         add_relation(time_src_key, animation_key, "TimeSrc -> Animation");
1357 }
1358
1359 void DepsgraphRelationBuilder::build_driver(ID *id, FCurve *fcu)
1360 {
1361         ChannelDriver *driver = fcu->driver;
1362         OperationKey driver_key(id,
1363                                 DEG_NODE_TYPE_PARAMETERS,
1364                                 DEG_OPCODE_DRIVER,
1365                                 fcu->rna_path ? fcu->rna_path : "",
1366                                 fcu->array_index);
1367         /* Driver -> data components (for interleaved evaluation
1368          * bones/constraints/modifiers).
1369          */
1370         build_driver_data(id, fcu);
1371         /* Loop over variables to get the target relationships. */
1372         build_driver_variables(id, fcu);
1373         /* It's quite tricky to detect if the driver actually depends on time or
1374          * not, so for now we'll be quite conservative here about optimization and
1375          * consider all python drivers to be depending on time.
1376          */
1377         if ((driver->type == DRIVER_TYPE_PYTHON) &&
1378             python_driver_depends_on_time(driver))
1379         {
1380                 TimeSourceKey time_src_key;
1381                 add_relation(time_src_key, driver_key, "TimeSrc -> Driver");
1382         }
1383 }
1384
1385 void DepsgraphRelationBuilder::build_driver_data(ID *id, FCurve *fcu)
1386 {
1387         OperationKey driver_key(id,
1388                                 DEG_NODE_TYPE_PARAMETERS,
1389                                 DEG_OPCODE_DRIVER,
1390                                 fcu->rna_path ? fcu->rna_path : "",
1391                                 fcu->array_index);
1392         const char *rna_path = fcu->rna_path ? fcu->rna_path : "";
1393         const RNAPathKey self_key(id, rna_path);
1394         if (GS(id->name) == ID_AR && strstr(rna_path, "bones[")) {
1395                 /* Drivers on armature-level bone settings (i.e. bbone stuff),
1396                  * which will affect the evaluation of corresponding pose bones.
1397                  */
1398                 IDDepsNode *arm_node = graph_->find_id_node(id);
1399                 char *bone_name = BLI_str_quoted_substrN(rna_path, "bones[");
1400                 if (arm_node != NULL && bone_name != NULL) {
1401                         /* Find objects which use this, and make their eval callbacks
1402                          * depend on this.
1403                          */
1404                         foreach (DepsRelation *rel, arm_node->outlinks) {
1405                                 IDDepsNode *to_node = (IDDepsNode *)rel->to;
1406                                 /* We only care about objects with pose data which use this. */
1407                                 if (GS(to_node->id_orig->name) == ID_OB) {
1408                                         Object *object = (Object *)to_node->id_orig;
1409                                         // NOTE: object->pose may be NULL
1410                                         bPoseChannel *pchan = BKE_pose_channel_find_name(object->pose,
1411                                                                                          bone_name);
1412                                         if (pchan != NULL) {
1413                                                 OperationKey bone_key(&object->id,
1414                                                                       DEG_NODE_TYPE_BONE,
1415                                                                       pchan->name,
1416                                                                       DEG_OPCODE_BONE_LOCAL);
1417                                                 add_relation(driver_key,
1418                                                              bone_key,
1419                                                              "Arm Bone -> Driver -> Bone");
1420                                         }
1421                                 }
1422                         }
1423                         /* Free temp data. */
1424                         MEM_freeN(bone_name);
1425                         bone_name = NULL;
1426                 }
1427                 else {
1428                         fprintf(stderr,
1429                                 "Couldn't find armature bone name for driver path - '%s'\n",
1430                                 rna_path);
1431                 }
1432         }
1433         else if (rna_path != NULL && rna_path[0] != '\0') {
1434                 RNAPathKey target_key(id, rna_path);
1435                 if (RNA_pointer_is_null(&target_key.ptr)) {
1436                         /* TODO(sergey): This would only mean that driver is broken.
1437                          * so we can't create relation anyway. However, we need to avoid
1438                          * adding drivers which are known to be buggy to a dependency
1439                          * graph, in order to save computational power.
1440                          */
1441                         return;
1442                 }
1443                 add_relation(driver_key, target_key, "Driver -> Target");
1444                 /* Similar to the case with f-curves, driver might drive a nested
1445                  * datablock, which means driver execution should wait for that
1446                  * datablock to be copied.
1447                  */
1448                 {
1449                         PointerRNA id_ptr;
1450                         PointerRNA ptr;
1451                         RNA_id_pointer_create(id, &id_ptr);
1452                         if (RNA_path_resolve_full(&id_ptr, fcu->rna_path, &ptr, NULL, NULL)) {
1453                                 if (id_ptr.id.data != ptr.id.data) {
1454                                         ComponentKey cow_key((ID *)ptr.id.data,
1455                                                              DEG_NODE_TYPE_COPY_ON_WRITE);
1456                                         add_relation(cow_key,
1457                                                      driver_key,
1458                                                      "Target CoW -> Driver",
1459                                                      true);
1460                                 }
1461                         }
1462                 }
1463                 if (target_key.prop != NULL &&
1464                     RNA_property_is_idprop(target_key.prop))
1465                 {
1466                         OperationKey parameters_key(id,
1467                                                     DEG_NODE_TYPE_PARAMETERS,
1468                                                     DEG_OPCODE_PARAMETERS_EVAL);
1469                         add_relation(target_key,
1470                                      parameters_key,
1471                                      "Driver Target -> Properties");
1472                 }
1473         }
1474 }
1475
1476 void DepsgraphRelationBuilder::build_driver_variables(ID *id, FCurve *fcu)
1477 {
1478         ChannelDriver *driver = fcu->driver;
1479         OperationKey driver_key(id,
1480                                 DEG_NODE_TYPE_PARAMETERS,
1481                                 DEG_OPCODE_DRIVER,
1482                                 fcu->rna_path ? fcu->rna_path : "",
1483                                 fcu->array_index);
1484         const char *rna_path = fcu->rna_path ? fcu->rna_path : "";
1485         const RNAPathKey self_key(id, rna_path);
1486
1487         LISTBASE_FOREACH (DriverVar *, dvar, &driver->variables) {
1488                 /* Only used targets. */
1489                 DRIVER_TARGETS_USED_LOOPER_BEGIN(dvar)
1490                 {
1491                         if (dtar->id == NULL) {
1492                                 continue;
1493                         }
1494                         build_id(dtar->id);
1495                         /* Initialize relations coming to proxy_from. */
1496                         Object *proxy_from = NULL;
1497                         if ((GS(dtar->id->name) == ID_OB) &&
1498                             (((Object *)dtar->id)->proxy_from != NULL))
1499                         {
1500                                 proxy_from = ((Object *)dtar->id)->proxy_from;
1501                                 build_id(&proxy_from->id);
1502                         }
1503                         /* Special handling for directly-named bones. */
1504                         if ((dtar->flag & DTAR_FLAG_STRUCT_REF) &&
1505                             (((Object *)dtar->id)->type == OB_ARMATURE) &&
1506                             (dtar->pchan_name[0]))
1507                         {
1508                                 Object *object = (Object *)dtar->id;
1509                                 bPoseChannel *target_pchan =
1510                                         BKE_pose_channel_find_name(object->pose,
1511                                                                    dtar->pchan_name);
1512                                 if (target_pchan == NULL) {
1513                                         continue;
1514                                 }
1515                                 OperationKey variable_key(dtar->id,
1516                                                           DEG_NODE_TYPE_BONE,
1517                                                           target_pchan->name,
1518                                                           DEG_OPCODE_BONE_DONE);
1519                                 if (is_same_bone_dependency(variable_key, self_key)) {
1520                                         continue;
1521                                 }
1522                                 add_relation(variable_key, driver_key, "Bone Target -> Driver");
1523                         }
1524                         else if (dtar->flag & DTAR_FLAG_STRUCT_REF) {
1525                                 /* Get node associated with the object's transforms. */
1526                                 if (dtar->id == id) {
1527                                         /* Ignore input dependency if we're driving properties of
1528                                          * the same ID, otherwise we'll be ending up in a cyclic
1529                                          * dependency here.
1530                                          */
1531                                         continue;
1532                                 }
1533                                 OperationKey target_key(dtar->id,
1534                                                         DEG_NODE_TYPE_TRANSFORM,
1535                                                         DEG_OPCODE_TRANSFORM_FINAL);
1536                                 add_relation(target_key, driver_key, "Target -> Driver");
1537                         }
1538                         else if (dtar->rna_path != NULL && dtar->rna_path[0] != '\0') {
1539                                 RNAPathKey variable_key(dtar->id, dtar->rna_path);
1540                                 if (RNA_pointer_is_null(&variable_key.ptr)) {
1541                                         continue;
1542                                 }
1543                                 if (is_same_bone_dependency(variable_key, self_key) ||
1544                                     is_same_nodetree_node_dependency(variable_key, self_key) ||
1545                                     is_same_shapekey_dependency(variable_key, self_key))
1546                                 {
1547                                         continue;
1548                                 }
1549                                 add_relation(variable_key, driver_key, "RNA Target -> Driver");
1550                                 if (proxy_from != NULL) {
1551                                         RNAPathKey proxy_from_variable_key(&proxy_from->id,
1552                                                                            dtar->rna_path);
1553                                         add_relation(proxy_from_variable_key,
1554                                                      variable_key,
1555                                                      "Proxy From -> Variable");
1556                                 }
1557                         }
1558                         else {
1559                                 /* If rna_path is NULL, and DTAR_FLAG_STRUCT_REF isn't set, this
1560                                  * is an incomplete target reference, so nothing to do here. */
1561                         }
1562                 }
1563                 DRIVER_TARGETS_LOOPER_END;
1564         }
1565 }
1566
1567 void DepsgraphRelationBuilder::build_world(World *world)
1568 {
1569         if (built_map_.checkIsBuiltAndTag(world)) {
1570                 return;
1571         }
1572         /* animation */
1573         build_animdata(&world->id);
1574         /* world's nodetree */
1575         if (world->nodetree != NULL) {
1576                 build_nodetree(world->nodetree);
1577                 OperationKey ntree_key(&world->nodetree->id,
1578                                        DEG_NODE_TYPE_SHADING,
1579                                        DEG_OPCODE_MATERIAL_UPDATE);
1580                 OperationKey world_key(&world->id,
1581                                           DEG_NODE_TYPE_SHADING,
1582                                           DEG_OPCODE_WORLD_UPDATE);
1583                 add_relation(ntree_key, world_key, "World's NTree");
1584                 build_nested_nodetree(&world->id, world->nodetree);
1585         }
1586 }
1587
1588 void DepsgraphRelationBuilder::build_rigidbody(Scene *scene)
1589 {
1590         RigidBodyWorld *rbw = scene->rigidbody_world;
1591
1592         OperationKey init_key(&scene->id, DEG_NODE_TYPE_TRANSFORM, DEG_OPCODE_RIGIDBODY_REBUILD);
1593         OperationKey sim_key(&scene->id, DEG_NODE_TYPE_TRANSFORM, DEG_OPCODE_RIGIDBODY_SIM);
1594
1595         /* rel between the two sim-nodes */
1596         add_relation(init_key, sim_key, "Rigidbody [Init -> SimStep]");
1597
1598         /* set up dependencies between these operations and other builtin nodes --------------- */
1599
1600         /* time dependency */
1601         TimeSourceKey time_src_key;
1602         add_relation(time_src_key, init_key, "TimeSrc -> Rigidbody Reset/Rebuild (Optional)");
1603
1604         /* objects - simulation participants */
1605         if (rbw->group) {
1606                 build_collection(NULL, NULL, rbw->group);
1607
1608                 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, object)
1609                 {
1610                         if (object->type != OB_MESH) {
1611                                 continue;
1612                         }
1613
1614                         /* hook up evaluation order...
1615                          * 1) flushing rigidbody results follows base transforms being applied
1616                          * 2) rigidbody flushing can only be performed after simulation has been run
1617                          *
1618                          * 3) simulation needs to know base transforms to figure out what to do
1619                          *    XXX: there's probably a difference between passive and active
1620                          *         - passive don't change, so may need to know full transform...
1621                          */
1622                         OperationKey rbo_key(&object->id, DEG_NODE_TYPE_TRANSFORM, DEG_OPCODE_RIGIDBODY_TRANSFORM_COPY);
1623
1624                         eDepsOperation_Code trans_opcode = object->parent ? DEG_OPCODE_TRANSFORM_PARENT : DEG_OPCODE_TRANSFORM_LOCAL;
1625                         OperationKey trans_op(&object->id, DEG_NODE_TYPE_TRANSFORM, trans_opcode);
1626
1627                         add_relation(sim_key, rbo_key, "Rigidbody Sim Eval -> RBO Sync");
1628
1629                         /* Geometry must be known to create the rigid body. RBO_MESH_BASE uses the non-evaluated
1630                          * mesh, so then the evaluation is unnecessary. */
1631                         if (object->rigidbody_object != NULL && object->rigidbody_object->mesh_source != RBO_MESH_BASE) {
1632                                 ComponentKey geom_key(&object->id, DEG_NODE_TYPE_GEOMETRY);
1633                                 add_relation(geom_key, init_key, "Object Geom Eval -> Rigidbody Rebuild");
1634                         }
1635
1636                         /* if constraints exist, those depend on the result of the rigidbody sim
1637                          * - This allows constraints to modify the result of the sim (i.e. clamping)
1638                          *   while still allowing the sim to depend on some changes to the objects.
1639                          *   Also, since constraints are hooked up to the final nodes, this link
1640                          *   means that we can also fit in there too...
1641                          * - Later, it might be good to include a constraint in the stack allowing us
1642                          *   to control whether rigidbody eval gets interleaved into the constraint stack
1643                          */
1644                         if (object->constraints.first) {
1645                                 OperationKey constraint_key(&object->id,
1646                                                             DEG_NODE_TYPE_TRANSFORM,
1647                                                             DEG_OPCODE_TRANSFORM_CONSTRAINTS);
1648                                 add_relation(rbo_key, constraint_key, "RBO Sync -> Ob Constraints");
1649                         }
1650                         else {
1651                                 /* Final object transform depends on rigidbody.
1652                                  *
1653                                  * NOTE: Currently we consider final here an ubereval node.
1654                                  * If it is gone we'll need to reconsider relation here.
1655                                  */
1656                                 OperationKey uber_key(&object->id,
1657                                                       DEG_NODE_TYPE_TRANSFORM,
1658                                                       DEG_OPCODE_TRANSFORM_OBJECT_UBEREVAL);
1659                                 add_relation(rbo_key, uber_key, "RBO Sync -> Uber (Temp)");
1660                         }
1661
1662                         /* Needed to get correct base values. */
1663                         add_relation(trans_op, sim_key, "Base Ob Transform -> Rigidbody Sim Eval");
1664                 }
1665                 FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
1666         }
1667
1668         /* constraints */
1669         if (rbw->constraints) {
1670                 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->constraints, object)
1671                 {
1672                         RigidBodyCon *rbc = object->rigidbody_constraint;
1673                         if (rbc == NULL || rbc->ob1 == NULL || rbc->ob2 == NULL) {
1674                                 /* When either ob1 or ob2 is NULL, the constraint doesn't work. */
1675                                 continue;
1676                         }
1677
1678                         /* final result of the constraint object's transform controls how the
1679                          * constraint affects the physics sim for these objects
1680                          */
1681                         ComponentKey trans_key(&object->id, DEG_NODE_TYPE_TRANSFORM);
1682                         OperationKey ob1_key(&rbc->ob1->id, DEG_NODE_TYPE_TRANSFORM, DEG_OPCODE_RIGIDBODY_TRANSFORM_COPY);
1683                         OperationKey ob2_key(&rbc->ob2->id, DEG_NODE_TYPE_TRANSFORM, DEG_OPCODE_RIGIDBODY_TRANSFORM_COPY);
1684
1685                         /* - constrained-objects sync depends on the constraint-holder */
1686                         add_relation(trans_key, ob1_key, "RigidBodyConstraint -> RBC.Object_1");
1687                         add_relation(trans_key, ob2_key, "RigidBodyConstraint -> RBC.Object_2");
1688
1689                         /* - ensure that sim depends on this constraint's transform */
1690                         add_relation(trans_key, sim_key, "RigidBodyConstraint Transform -> RB Simulation");
1691                 }
1692                 FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
1693         }
1694 }
1695
1696 void DepsgraphRelationBuilder::build_particle_systems(Object *object)
1697 {
1698         TimeSourceKey time_src_key;
1699         OperationKey obdata_ubereval_key(&object->id,
1700                                          DEG_NODE_TYPE_GEOMETRY,
1701                                          DEG_OPCODE_GEOMETRY_UBEREVAL);
1702         OperationKey eval_init_key(&object->id,
1703                                    DEG_NODE_TYPE_PARTICLE_SYSTEM,
1704                                    DEG_OPCODE_PARTICLE_SYSTEM_INIT);
1705         OperationKey eval_done_key(&object->id,
1706                                    DEG_NODE_TYPE_PARTICLE_SYSTEM,
1707                                    DEG_OPCODE_PARTICLE_SYSTEM_DONE);
1708         ComponentKey eval_key(&object->id, DEG_NODE_TYPE_PARTICLE_SYSTEM);
1709         ComponentKey point_cache_key(&object->id, DEG_NODE_TYPE_POINT_CACHE);
1710         add_relation(eval_key, point_cache_key, "Particle Point Cache");
1711         /* Particle systems. */
1712         LISTBASE_FOREACH (ParticleSystem *, psys, &object->particlesystem) {
1713                 ParticleSettings *part = psys->part;
1714
1715                 /* Build particle settings relations.
1716                  *
1717                  * NOTE: The call itself ensures settings are only build once.
1718                  */
1719                 build_particle_settings(part);
1720
1721                 /* This particle system. */
1722                 OperationKey psys_key(&object->id,
1723                                       DEG_NODE_TYPE_PARTICLE_SYSTEM,
1724                                       DEG_OPCODE_PARTICLE_SYSTEM_EVAL,
1725                                       psys->name);
1726
1727                 /* Update particle system when settings changes. */
1728                 OperationKey particle_settings_key(&part->id,
1729                                                    DEG_NODE_TYPE_PARTICLE_SETTINGS,
1730                                                    DEG_OPCODE_PARTICLE_SETTINGS_EVAL);
1731                 add_relation(particle_settings_key, eval_init_key, "Particle Settings Change");
1732                 add_relation(eval_init_key, psys_key, "Init -> PSys");
1733                 add_relation(psys_key, eval_done_key, "PSys -> Done");
1734                 /* TODO(sergey): Currently particle update is just a placeholder,
1735                  * hook it to the ubereval node so particle system is getting updated
1736                  * on playback.
1737                  */
1738                 add_relation(psys_key, obdata_ubereval_key, "PSys -> UberEval");
1739                 /* Collisions */
1740                 if (part->type != PART_HAIR) {
1741                         add_collision_relations(psys_key,
1742                                                 object,
1743                                                 part->collision_group,
1744                                                 "Particle Collision");
1745                 }
1746                 else if ((psys->flag & PSYS_HAIR_DYNAMICS) &&
1747                          psys->clmd != NULL &&
1748                          psys->clmd->coll_parms != NULL)
1749                 {
1750                         add_collision_relations(psys_key,
1751                                                 object,
1752                                                 psys->clmd->coll_parms->group,
1753                                                 "Hair Collision");
1754                 }
1755                 /* Effectors. */
1756                 add_forcefield_relations(psys_key,
1757                                          object,
1758                                          psys,
1759                                          part->effector_weights,
1760                                          part->type == PART_HAIR,
1761                                          "Particle Field");
1762                 /* Boids .*/
1763                 if (part->boids) {
1764                         LISTBASE_FOREACH (BoidState *, state, &part->boids->states) {
1765                                 LISTBASE_FOREACH (BoidRule *, rule, &state->rules) {
1766                                         Object *ruleob = NULL;
1767                                         if (rule->type == eBoidRuleType_Avoid) {
1768                                                 ruleob = ((BoidRuleGoalAvoid *)rule)->ob;
1769                                         }
1770                                         else if (rule->type == eBoidRuleType_FollowLeader) {
1771                                                 ruleob = ((BoidRuleFollowLeader *)rule)->ob;
1772                                         }
1773                                         if (ruleob) {
1774                                                 ComponentKey ruleob_key(&ruleob->id,
1775                                                                         DEG_NODE_TYPE_TRANSFORM);
1776                                                 add_relation(ruleob_key, psys_key, "Boid Rule");
1777                                         }
1778                                 }
1779                         }
1780                 }
1781                 switch (part->ren_as) {
1782                         case PART_DRAW_OB:
1783                                 if (part->dup_ob != NULL) {
1784                                         /* Make sure object's relations are all built.  */
1785                                         build_object(NULL, part->dup_ob);
1786                                         /* Build relation for the particle visualization. */
1787                                         build_particle_system_visualization_object(
1788                                                 object,  psys, part->dup_ob);
1789                                 }
1790                                 break;
1791                         case PART_DRAW_GR:
1792                                 if (part->dup_group != NULL) {
1793                                         build_collection(NULL, NULL, part->dup_group);
1794                                         LISTBASE_FOREACH (CollectionObject *, go, &part->dup_group->gobject) {
1795                                                 build_particle_system_visualization_object(
1796                                                         object, psys, go->ob);
1797                                         }
1798                                 }
1799                                 break;
1800                 }
1801         }
1802
1803         /* Particle depends on the object transform, so that channel is to be ready
1804          * first.
1805          *
1806          * TODO(sergey): This relation should be altered once real granular update
1807          * is implemented.
1808          */
1809         ComponentKey transform_key(&object->id, DEG_NODE_TYPE_TRANSFORM);
1810         add_relation(transform_key, obdata_ubereval_key, "Particle Eval");
1811 }
1812
1813 void DepsgraphRelationBuilder::build_particle_settings(ParticleSettings *part)
1814 {
1815         if (built_map_.checkIsBuiltAndTag(part)) {
1816                 return;
1817         }
1818         /* Animation data relations. */
1819         build_animdata(&part->id);
1820         OperationKey particle_settings_init_key(&part->id,
1821                                                 DEG_NODE_TYPE_PARTICLE_SETTINGS,
1822                                                 DEG_OPCODE_PARTICLE_SETTINGS_INIT);
1823         OperationKey particle_settings_eval_key(&part->id,
1824                                                 DEG_NODE_TYPE_PARTICLE_SETTINGS,
1825                                                 DEG_OPCODE_PARTICLE_SETTINGS_EVAL);
1826         OperationKey particle_settings_reset_key(
1827                 &part->id,
1828                 DEG_NODE_TYPE_PARTICLE_SETTINGS,
1829                 DEG_OPCODE_PARTICLE_SETTINGS_RESET);
1830         add_relation(particle_settings_init_key,
1831                      particle_settings_eval_key,
1832                      "Particle Settings Init Order");
1833         add_relation(particle_settings_reset_key,
1834                      particle_settings_eval_key,
1835                      "Particle Settings Reset");
1836         /* Texture slots. */
1837         for (int mtex_index = 0; mtex_index < MAX_MTEX; ++mtex_index) {
1838                 MTex *mtex = part->mtex[mtex_index];
1839                 if (mtex == NULL || mtex->tex == NULL) {
1840                         continue;
1841                 }
1842                 build_texture(mtex->tex);
1843                 ComponentKey texture_key(&mtex->tex->id,
1844                                          DEG_NODE_TYPE_GENERIC_DATABLOCK);
1845                 add_relation(texture_key,
1846                              particle_settings_reset_key,
1847                              "Particle Texture",
1848                              DEPSREL_FLAG_FLUSH_USER_EDIT_ONLY);
1849         }
1850         if (check_id_has_anim_component(&part->id)) {
1851                 ComponentKey animation_key(&part->id, DEG_NODE_TYPE_ANIMATION);
1852                 add_relation(animation_key,
1853                              particle_settings_eval_key,
1854                              "Particle Settings Animation");
1855         }
1856 }
1857
1858 void DepsgraphRelationBuilder::build_particle_system_visualization_object(
1859         Object *object,
1860         ParticleSystem *psys,
1861         Object *draw_object)
1862 {
1863         OperationKey psys_key(&object->id,
1864                               DEG_NODE_TYPE_PARTICLE_SYSTEM,
1865                               DEG_OPCODE_PARTICLE_SYSTEM_EVAL,
1866                               psys->name);
1867         OperationKey obdata_ubereval_key(&object->id,
1868                                          DEG_NODE_TYPE_GEOMETRY,
1869                                          DEG_OPCODE_GEOMETRY_UBEREVAL);
1870         ComponentKey dup_ob_key(&draw_object->id, DEG_NODE_TYPE_TRANSFORM);
1871         add_relation(dup_ob_key, psys_key, "Particle Object Visualization");
1872         if (draw_object->type == OB_MBALL) {
1873                 ComponentKey dup_geometry_key(&draw_object->id, DEG_NODE_TYPE_GEOMETRY);
1874                 add_relation(obdata_ubereval_key,
1875                              dup_geometry_key,
1876                              "Particle MBall Visualization");
1877         }
1878 }
1879
1880 /* Shapekeys */
1881 void DepsgraphRelationBuilder::build_shapekeys(Key *key)
1882 {
1883         if (built_map_.checkIsBuiltAndTag(key)) {
1884                 return;
1885         }
1886         /* attach animdata to geometry */
1887         build_animdata(&key->id);
1888 }
1889
1890 /**
1891  * ObData Geometry Evaluation
1892  * ==========================
1893  *
1894  * The evaluation of geometry on objects is as follows:
1895  * - The actual evaluated of the derived geometry (e.g. Mesh, DispList)
1896  *   occurs in the Geometry component of the object which references this.
1897  *   This includes modifiers, and the temporary "ubereval" for geometry.
1898  *   Therefore, each user of a piece of shared geometry data ends up evaluating
1899  *   its own version of the stuff, complete with whatever modifiers it may use.
1900  *
1901  * - The datablocks for the geometry data - "obdata" (e.g. ID_ME, ID_CU, ID_LT.)
1902  *   are used for
1903  *     1) calculating the bounding boxes of the geometry data,
1904  *     2) aggregating inward links from other objects (e.g. for text on curve)
1905  *        and also for the links coming from the shapekey datablocks
1906  * - Animation/Drivers affecting the parameters of the geometry are made to
1907  *   trigger updates on the obdata geometry component, which then trigger
1908  *   downstream re-evaluation of the individual instances of this geometry.
1909  */
1910 void DepsgraphRelationBuilder::build_object_data_geometry(Object *object)
1911 {
1912         ID *obdata = (ID *)object->data;
1913         /* Init operation of object-level geometry evaluation. */
1914         OperationKey geom_init_key(&object->id,
1915                                    DEG_NODE_TYPE_GEOMETRY,
1916                                    DEG_OPCODE_PLACEHOLDER,
1917                                    "Eval Init");
1918         /* Get nodes for result of obdata's evaluation, and geometry evaluation
1919          * on object.
1920          */
1921         ComponentKey obdata_geom_key(obdata, DEG_NODE_TYPE_GEOMETRY);
1922         ComponentKey geom_key(&object->id, DEG_NODE_TYPE_GEOMETRY);
1923         /* Link components to each other. */
1924         add_relation(obdata_geom_key, geom_key, "Object Geometry Base Data");
1925         OperationKey obdata_ubereval_key(&object->id,
1926                                          DEG_NODE_TYPE_GEOMETRY,
1927                                          DEG_OPCODE_GEOMETRY_UBEREVAL);
1928         /* Special case: modifiers evaluation queries scene for various things like
1929          * data mask to be used. We add relation here to ensure object is never
1930          * evaluated prior to Scene's CoW is ready.
1931          */
1932         OperationKey scene_key(&scene_->id,
1933                                DEG_NODE_TYPE_LAYER_COLLECTIONS,
1934                                DEG_OPCODE_VIEW_LAYER_EVAL);
1935         DepsRelation *rel = add_relation(scene_key, obdata_ubereval_key, "CoW Relation");
1936         rel->flag |= DEPSREL_FLAG_NO_FLUSH;
1937         /* Modifiers */
1938         if (object->modifiers.first != NULL) {
1939                 ModifierUpdateDepsgraphContext ctx = {};
1940                 ctx.scene = scene_;
1941                 ctx.object = object;
1942                 LISTBASE_FOREACH (ModifierData *, md, &object->modifiers) {
1943                         const ModifierTypeInfo *mti = modifierType_getInfo((ModifierType)md->type);
1944                         if (mti->updateDepsgraph) {
1945                                 DepsNodeHandle handle = create_node_handle(obdata_ubereval_key);
1946                                 ctx.node = reinterpret_cast< ::DepsNodeHandle* >(&handle);
1947                                 mti->updateDepsgraph(md, &ctx);
1948                         }
1949                         if (BKE_object_modifier_use_time(object, md)) {
1950                                 TimeSourceKey time_src_key;
1951                                 add_relation(time_src_key, obdata_ubereval_key, "Time Source");
1952                         }
1953                 }
1954         }
1955         /* Grease Pencil Modifiers */
1956         if (object->greasepencil_modifiers.first != NULL) {
1957                 ModifierUpdateDepsgraphContext ctx = {};
1958                 ctx.scene = scene_;
1959                 ctx.object = object;
1960                 LISTBASE_FOREACH(GpencilModifierData *, md, &object->greasepencil_modifiers) {
1961                         const GpencilModifierTypeInfo *mti = BKE_gpencil_modifierType_getInfo((GpencilModifierType)md->type);
1962                         if (mti->updateDepsgraph) {
1963                                 DepsNodeHandle handle = create_node_handle(obdata_ubereval_key);
1964                                 ctx.node = reinterpret_cast< ::DepsNodeHandle* >(&handle);
1965                                 mti->updateDepsgraph(md, &ctx);
1966                         }
1967                         if (BKE_object_modifier_gpencil_use_time(object, md)) {
1968                                 TimeSourceKey time_src_key;
1969                                 add_relation(time_src_key, obdata_ubereval_key, "Time Source");
1970                         }
1971                 }
1972         }
1973         /* Shader FX */
1974         if (object->shader_fx.first != NULL) {
1975                 ModifierUpdateDepsgraphContext ctx = {};
1976                 ctx.scene = scene_;
1977                 ctx.object = object;
1978                 LISTBASE_FOREACH(ShaderFxData *, fx, &object->shader_fx) {
1979                         const ShaderFxTypeInfo *fxi = BKE_shaderfxType_getInfo((ShaderFxType)fx->type);
1980                         if (fxi->updateDepsgraph) {
1981                                 DepsNodeHandle handle = create_node_handle(obdata_ubereval_key);
1982                                 ctx.node = reinterpret_cast< ::DepsNodeHandle* >(&handle);
1983                                 fxi->updateDepsgraph(fx, &ctx);
1984                         }
1985                         if (BKE_object_shaderfx_use_time(object, fx)) {
1986                                 TimeSourceKey time_src_key;
1987                                 add_relation(time_src_key, obdata_ubereval_key, "Time Source");
1988                         }
1989                 }
1990         }
1991         /* Materials. */
1992         if (object->totcol) {
1993                 for (int a = 1; a <= object->totcol; a++) {
1994                         Material *ma = give_current_material(object, a);
1995                         if (ma != NULL) {
1996                                 build_material(ma);
1997
1998                                 if (object->type == OB_MESH) {
1999                                         OperationKey material_key(&ma->id,
2000                                                                   DEG_NODE_TYPE_SHADING,
2001                                                                   DEG_OPCODE_MATERIAL_UPDATE);
2002                                         OperationKey shading_key(&object->id,
2003                                                                  DEG_NODE_TYPE_SHADING,
2004                                                                  DEG_OPCODE_SHADING);
2005                                         add_relation(material_key, shading_key, "Material Update");
2006                                 }
2007                         }
2008                 }
2009         }
2010         /* Geometry collision. */
2011         if (ELEM(object->type, OB_MESH, OB_CURVE, OB_LATTICE)) {
2012                 // add geometry collider relations
2013         }
2014         /* Make sure uber update is the last in the dependencies.
2015          *
2016          * TODO(sergey): Get rid of this node.
2017          */
2018         if (object->type != OB_ARMATURE) {
2019                 /* Armatures does no longer require uber node. */
2020                 OperationKey obdata_ubereval_key(&object->id,
2021                                                  DEG_NODE_TYPE_GEOMETRY,
2022                                                  DEG_OPCODE_GEOMETRY_UBEREVAL);
2023                 add_relation(geom_init_key,
2024                              obdata_ubereval_key,
2025                              "Object Geometry UberEval");
2026                 if (object->totcol != 0 && object->type == OB_MESH) {
2027                         ComponentKey object_shading_key(&object->id, DEG_NODE_TYPE_SHADING);
2028                         DepsRelation *rel = add_relation(obdata_ubereval_key,
2029                                                          object_shading_key,
2030                                                          "Object Geometry batch Update");
2031                         rel->flag |= DEPSREL_FLAG_NO_FLUSH;
2032                 }
2033         }
2034         if (object->type == OB_MBALL) {
2035                 Object *mom = BKE_mball_basis_find(scene_, object);
2036                 ComponentKey mom_geom_key(&mom->id, DEG_NODE_TYPE_GEOMETRY);
2037                 /* motherball - mom depends on children! */
2038                 if (mom == object) {
2039                         ComponentKey mom_transform_key(&mom->id,
2040                                                        DEG_NODE_TYPE_TRANSFORM);
2041                         add_relation(mom_transform_key,
2042                                      mom_geom_key,
2043                                      "Metaball Motherball Transform -> Geometry");
2044                 }
2045                 else {
2046                         ComponentKey transform_key(&object->id, DEG_NODE_TYPE_TRANSFORM);
2047                         add_relation(geom_key, mom_geom_key, "Metaball Motherball");
2048                         add_relation(transform_key, mom_geom_key, "Metaball Motherball");
2049                 }
2050         }
2051         /* NOTE: This is compatibility code to support particle systems
2052          *
2053          * for viewport being properly rendered in final render mode.
2054          * This relation is similar to what dag_object_time_update_flags()
2055          * was doing for mesh objects with particle system.
2056          *
2057          * Ideally we need to get rid of this relation.
2058          */
2059         if (object_particles_depends_on_time(object)) {
2060                 TimeSourceKey time_key;
2061                 OperationKey obdata_ubereval_key(&object->id,
2062                                                  DEG_NODE_TYPE_GEOMETRY,
2063                                                  DEG_OPCODE_GEOMETRY_UBEREVAL);
2064                 add_relation(time_key, obdata_ubereval_key, "Legacy particle time");
2065         }
2066         /* Object data datablock. */
2067         build_object_data_geometry_datablock((ID *)object->data);
2068         Key *key = BKE_key_from_object(object);
2069         if (key != NULL) {
2070                 if (key->adt != NULL) {
2071                         if (key->adt->action || key->adt->nla_tracks.first) {
2072                                 ComponentKey obdata_key((ID *)object->data,
2073                                                         DEG_NODE_TYPE_GEOMETRY);
2074                                 ComponentKey adt_key(&key->id, DEG_NODE_TYPE_ANIMATION);
2075                                 add_relation(adt_key, obdata_key, "Animation");
2076                         }
2077                 }
2078         }
2079         /* Syncronization back to original object. */
2080         ComponentKey final_geometry_jey(&object->id, DEG_NODE_TYPE_GEOMETRY);
2081         OperationKey synchronize_key(&object->id,
2082                                      DEG_NODE_TYPE_SYNCHRONIZE,
2083                                      DEG_OPCODE_SYNCHRONIZE_TO_ORIGINAL);
2084         add_relation(
2085                 final_geometry_jey, synchronize_key, "Synchronize to Original");
2086 }
2087
2088 void DepsgraphRelationBuilder::build_object_data_geometry_datablock(ID *obdata)
2089 {
2090         if (built_map_.checkIsBuiltAndTag(obdata)) {
2091                 return;
2092         }
2093         /* Animation. */
2094         build_animdata(obdata);
2095         /* ShapeKeys. */
2096         Key *key = BKE_key_from_id(obdata);
2097         if (key != NULL) {
2098                 build_shapekeys(key);
2099         }
2100         /* Link object data evaluation node to exit operation. */
2101         OperationKey obdata_geom_eval_key(obdata,
2102                 DEG_NODE_TYPE_GEOMETRY,
2103                 DEG_OPCODE_PLACEHOLDER,
2104                 "Geometry Eval");
2105         OperationKey obdata_geom_done_key(obdata,
2106                 DEG_NODE_TYPE_GEOMETRY,
2107                 DEG_OPCODE_PLACEHOLDER,
2108                 "Eval Done");
2109         add_relation(obdata_geom_eval_key,
2110                      obdata_geom_done_key,
2111                      "ObData Geom Eval Done");
2112         /* Type-specific links. */
2113         const ID_Type id_type = GS(obdata->name);
2114         switch (id_type) {
2115                 case ID_ME:
2116                         break;
2117                 case ID_MB:
2118                         break;
2119                 case ID_CU:
2120                 {
2121                         Curve *cu = (Curve *)obdata;
2122                         if (cu->bevobj != NULL) {
2123                                 ComponentKey bevob_geom_key(&cu->bevobj->id,
2124                                         DEG_NODE_TYPE_GEOMETRY);
2125                                 add_relation(bevob_geom_key,
2126                                         obdata_geom_eval_key,
2127                                         "Curve Bevel Geometry");
2128                                 ComponentKey bevob_key(&cu->bevobj->id,
2129                                         DEG_NODE_TYPE_TRANSFORM);
2130                                 add_relation(bevob_key,
2131                                         obdata_geom_eval_key,
2132                                         "Curve Bevel Transform");
2133                                 build_object(NULL, cu->bevobj);
2134                         }
2135                         if (cu->taperobj != NULL) {
2136                                 ComponentKey taperob_key(&cu->taperobj->id,
2137                                         DEG_NODE_TYPE_GEOMETRY);
2138                                 add_relation(taperob_key, obdata_geom_eval_key, "Curve Taper");
2139                                 build_object(NULL, cu->taperobj);
2140                         }
2141                         if (cu->textoncurve != NULL) {
2142                                 ComponentKey textoncurve_key(&cu->textoncurve->id,
2143                                         DEG_NODE_TYPE_GEOMETRY);
2144                                 add_relation(textoncurve_key,
2145                                         obdata_geom_eval_key,
2146                                         "Text on Curve");
2147                                 build_object(NULL, cu->textoncurve);
2148                         }
2149                         break;
2150                 }
2151                 case ID_LT:
2152                         break;
2153                 case ID_GD: /* Grease Pencil */
2154                 {
2155                         bGPdata *gpd = (bGPdata *)obdata;
2156
2157                         /* Geometry cache needs to be recalculated on frame change
2158                          * (e.g. to fix crashes after scrubbing the timeline when
2159                          * onion skinning is enabled, since the ghosts need to be
2160                          * re-added to the cache once scrubbing ends)
2161                          */
2162                         TimeSourceKey time_key;
2163                         ComponentKey geometry_key(obdata, DEG_NODE_TYPE_GEOMETRY);
2164                         add_relation(time_key,
2165                                      geometry_key,
2166                                      "GP Frame Change");
2167
2168                         /* Geometry cache also needs to be recalculated when Material
2169                          * settings change (e.g. when fill.opacity changes on/off,
2170                          * we need to rebuild the bGPDstroke->triangles caches)
2171                          */
2172                         for (int i = 0; i < gpd->totcol; i++) {
2173                                 Material *ma = gpd->mat[i];
2174                                 if ((ma != NULL) && (ma->gp_style != NULL)) {
2175                                         OperationKey material_key(&ma->id,
2176                                                                   DEG_NODE_TYPE_SHADING,
2177                                                                   DEG_OPCODE_MATERIAL_UPDATE);
2178                                         add_relation(material_key,
2179                                                      geometry_key,
2180                                                      "Material -> GP Data");
2181                                 }
2182                         }
2183                         break;
2184                 }
2185                 default:
2186                         BLI_assert(!"Should not happen");
2187                         break;
2188         }
2189 }
2190
2191 void DepsgraphRelationBuilder::build_armature(bArmature *armature)
2192 {
2193         if (built_map_.checkIsBuiltAndTag(armature)) {
2194                 return;
2195         }
2196         build_animdata(&armature->id);
2197 }
2198
2199 void DepsgraphRelationBuilder::build_camera(Camera *camera)
2200 {
2201         if (built_map_.checkIsBuiltAndTag(camera)) {
2202                 return;
2203         }
2204         if (camera->dof_ob != NULL) {
2205                 ComponentKey camera_parameters_key(&camera->id, DEG_NODE_TYPE_PARAMETERS);
2206                 ComponentKey dof_ob_key(&camera->dof_ob->id, DEG_NODE_TYPE_TRANSFORM);
2207                 add_relation(dof_ob_key, camera_parameters_key, "Camera DOF");
2208         }
2209 }
2210
2211 /* Lamps */
2212 void DepsgraphRelationBuilder::build_lamp(Lamp *lamp)
2213 {
2214         if (built_map_.checkIsBuiltAndTag(lamp)) {
2215                 return;
2216         }
2217         /* lamp's nodetree */
2218         if (lamp->nodetree != NULL) {
2219                 build_nodetree(lamp->nodetree);
2220                 ComponentKey lamp_parameters_key(&lamp->id, DEG_NODE_TYPE_PARAMETERS);
2221                 ComponentKey nodetree_key(&lamp->nodetree->id, DEG_NODE_TYPE_SHADING);
2222                 add_relation(nodetree_key, lamp_parameters_key, "NTree->Light Parameters");
2223                 build_nested_nodetree(&lamp->id, lamp->nodetree);
2224         }
2225 }
2226
2227 void DepsgraphRelationBuilder::build_nodetree(bNodeTree *ntree)
2228 {
2229         if (ntree == NULL) {
2230                 return;
2231         }
2232         if (built_map_.checkIsBuiltAndTag(ntree)) {
2233                 return;
2234         }
2235         build_animdata(&ntree->id);
2236         ComponentKey shading_key(&ntree->id, DEG_NODE_TYPE_SHADING);
2237         /* nodetree's nodes... */
2238         LISTBASE_FOREACH (bNode *, bnode, &ntree->nodes) {
2239                 ID *id = bnode->id;
2240                 if (id == NULL) {
2241                         continue;
2242                 }
2243                 ID_Type id_type = GS(id->name);
2244                 if (id_type == ID_MA) {
2245                         build_material((Material *)bnode->id);
2246                 }
2247                 else if (id_type == ID_TE) {
2248                         build_texture((Tex *)bnode->id);
2249                 }
2250                 else if (id_type == ID_IM) {
2251                         /* nothing for now. */
2252                 }
2253                 else if (id_type == ID_OB) {
2254                         build_object(NULL, (Object *)id);
2255                 }
2256                 else if (id_type == ID_SCE) {
2257                         /* Scenes are used by compositor trees, and handled by render
2258                          * pipeline. No need to build dependencies for them here.
2259                          */
2260                 }
2261                 else if (id_type == ID_TXT) {
2262                         /* Ignore script nodes. */
2263                 }
2264                 else if (id_type == ID_MSK) {
2265                         build_mask((Mask *)id);
2266                 }
2267                 else if (id_type == ID_MC) {
2268                         build_movieclip((MovieClip *)id);
2269                 }
2270                 else if (bnode->type == NODE_GROUP) {
2271                         bNodeTree *group_ntree = (bNodeTree *)id;
2272                         build_nodetree(group_ntree);
2273                         ComponentKey group_shading_key(&group_ntree->id,
2274                                                        DEG_NODE_TYPE_SHADING);
2275                         add_relation(group_shading_key, shading_key, "Group Node");
2276                 }
2277                 else {
2278                         BLI_assert(!"Unknown ID type used for node");
2279                 }
2280         }
2281
2282         OperationKey shading_update_key(&ntree->id,
2283                                         DEG_NODE_TYPE_SHADING,
2284                                         DEG_OPCODE_MATERIAL_UPDATE);
2285         OperationKey shading_parameters_key(&ntree->id,
2286                                             DEG_NODE_TYPE_SHADING_PARAMETERS,
2287                                             DEG_OPCODE_MATERIAL_UPDATE);
2288         add_relation(shading_parameters_key, shading_update_key, "NTree Shading Parameters");
2289
2290         if (check_id_has_anim_component(&ntree->id)) {
2291                 ComponentKey animation_key(&ntree->id, DEG_NODE_TYPE_ANIMATION);
2292                 add_relation(animation_key, shading_parameters_key, "NTree Shading Parameters");
2293         }
2294 }
2295
2296 /* Recursively build graph for material */
2297 void DepsgraphRelationBuilder::build_material(Material *material)
2298 {
2299         if (built_map_.checkIsBuiltAndTag(material)) {
2300                 return;
2301         }
2302         /* animation */
2303         build_animdata(&material->id);
2304         /* material's nodetree */
2305         if (material->nodetree != NULL) {
2306                 build_nodetree(material->nodetree);
2307                 OperationKey ntree_key(&material->nodetree->id,
2308                                        DEG_NODE_TYPE_SHADING,
2309                                        DEG_OPCODE_MATERIAL_UPDATE);
2310                 OperationKey material_key(&material->id,
2311                                           DEG_NODE_TYPE_SHADING,
2312                                           DEG_OPCODE_MATERIAL_UPDATE);
2313                 add_relation(ntree_key, material_key, "Material's NTree");
2314                 build_nested_nodetree(&material->id, material->nodetree);
2315         }
2316 }
2317
2318 /* Recursively build graph for texture */
2319 void DepsgraphRelationBuilder::build_texture(Tex *texture)
2320 {
2321         if (built_map_.checkIsBuiltAndTag(texture)) {
2322                 return;
2323         }
2324         /* texture itself */
2325         build_animdata(&texture->id);
2326         /* texture's nodetree */
2327         build_nodetree(texture->nodetree);
2328         build_nested_nodetree(&texture->id, texture->nodetree);
2329         if (check_id_has_anim_component(&texture->id)) {
2330                 ComponentKey animation_key(&texture->id, DEG_NODE_TYPE_ANIMATION);
2331                 ComponentKey datablock_key(&texture->id,
2332                                            DEG_NODE_TYPE_GENERIC_DATABLOCK);
2333                 add_relation(animation_key, datablock_key, "Datablock Animation");
2334         }
2335 }
2336
2337 void DepsgraphRelationBuilder::build_compositor(Scene *scene)
2338 {
2339         /* For now, just a plain wrapper? */
2340         build_nodetree(scene->nodetree);
2341 }
2342
2343 void DepsgraphRelationBuilder::build_gpencil(bGPdata *gpd)
2344 {
2345         if (built_map_.checkIsBuiltAndTag(gpd)) {
2346                 return;
2347         }
2348         /* animation */
2349         build_animdata(&gpd->id);
2350
2351         // TODO: parent object (when that feature is implemented)
2352 }
2353
2354 void DepsgraphRelationBuilder::build_cachefile(CacheFile *cache_file)
2355 {
2356         if (built_map_.checkIsBuiltAndTag(cache_file)) {
2357                 return;
2358         }
2359         /* Animation. */
2360         build_animdata(&cache_file->id);
2361 }
2362
2363 void DepsgraphRelationBuilder::build_mask(Mask *mask)
2364 {
2365         if (built_map_.checkIsBuiltAndTag(mask)) {
2366                 return;
2367         }
2368         ID *mask_id = &mask->id;
2369         /* F-Curve animation. */
2370         build_animdata(mask_id);
2371         /* Own mask animation. */
2372         OperationKey mask_animation_key(mask_id,
2373                                         DEG_NODE_TYPE_ANIMATION,
2374                                         DEG_OPCODE_MASK_ANIMATION);
2375         TimeSourceKey time_src_key;
2376         add_relation(time_src_key, mask_animation_key, "TimeSrc -> Mask Animation");
2377         /* Final mask evaluation. */
2378         ComponentKey parameters_key(mask_id, DEG_NODE_TYPE_PARAMETERS);
2379         add_relation(mask_animation_key, parameters_key, "Mask Animation -> Mask Eval");
2380 }
2381
2382 void DepsgraphRelationBuilder::build_movieclip(MovieClip *clip)
2383 {
2384         if (built_map_.checkIsBuiltAndTag(clip)) {
2385                 return;
2386         }
2387         /* Animation. */
2388         build_animdata(&clip->id);
2389 }
2390
2391 void DepsgraphRelationBuilder::build_lightprobe(LightProbe *probe)
2392 {
2393         if (built_map_.checkIsBuiltAndTag(probe)) {
2394                 return;
2395         }
2396         build_animdata(&probe->id);
2397 }
2398
2399 void DepsgraphRelationBuilder::build_speaker(Speaker *speaker)
2400 {
2401         if (built_map_.checkIsBuiltAndTag(speaker)) {
2402                 return;
2403         }
2404         build_animdata(&speaker->id);
2405 }
2406
2407 void DepsgraphRelationBuilder::build_copy_on_write_relations()
2408 {
2409         foreach (IDDepsNode *id_node, graph_->id_nodes) {
2410                 build_copy_on_write_relations(id_node);
2411         }
2412 }
2413
2414 /* Nested datablocks (node trees, shape keys) requires special relation to
2415  * ensure owner's datablock remapping happens after node tree itself is ready.
2416  *
2417  * This is similar to what happens in ntree_hack_remap_pointers().
2418  */
2419 void DepsgraphRelationBuilder::build_nested_datablock(ID *owner, ID *id)
2420 {
2421         OperationKey owner_copy_on_write_key(owner,
2422                                              DEG_NODE_TYPE_COPY_ON_WRITE,
2423                                              DEG_OPCODE_COPY_ON_WRITE);
2424         OperationKey id_copy_on_write_key(id,
2425                                           DEG_NODE_TYPE_COPY_ON_WRITE,
2426                                           DEG_OPCODE_COPY_ON_WRITE);
2427         add_relation(id_copy_on_write_key,
2428                      owner_copy_on_write_key,
2429                      "Eval Order");
2430 }
2431
2432 void DepsgraphRelationBuilder::build_nested_nodetree(ID *owner,
2433                                                      bNodeTree *ntree)
2434 {
2435         if (ntree == NULL) {
2436                 return;
2437         }
2438         build_nested_datablock(owner, &ntree->id);
2439 }
2440
2441 void DepsgraphRelationBuilder::build_nested_shapekey(ID *owner, Key *key)
2442 {
2443         if (key == NULL) {
2444                 return;
2445         }
2446         build_nested_datablock(owner, &key->id);
2447 }
2448
2449 void DepsgraphRelationBuilder::build_copy_on_write_relations(IDDepsNode *id_node)
2450 {
2451         ID *id_orig = id_node->id_orig;
2452         const ID_Type id_type = GS(id_orig->name);
2453         TimeSourceKey time_source_key;
2454         OperationKey copy_on_write_key(id_orig,
2455                                        DEG_NODE_TYPE_COPY_ON_WRITE,
2456                                        DEG_OPCODE_COPY_ON_WRITE);
2457         /* XXX: This is a quick hack to make Alt-A to work. */
2458         // add_relation(time_source_key, copy_on_write_key, "Fluxgate capacitor hack");
2459         /* Resat of code is using rather low level trickery, so need to get some
2460          * explicit pointers. */
2461         DepsNode *node_cow = find_node(copy_on_write_key);
2462         OperationDepsNode *op_cow = node_cow->get_exit_operation();
2463         /* Plug any other components to this one. */
2464         GHASH_FOREACH_BEGIN(ComponentDepsNode *, comp_node, id_node->components)
2465         {
2466                 if (comp_node->type == DEG_NODE_TYPE_COPY_ON_WRITE) {
2467                         /* Copy-on-write component never depends on itself. */
2468                         continue;
2469                 }
2470                 if (!comp_node->depends_on_cow()) {
2471                         /* Component explicitly requests to not add relation. */
2472                         continue;
2473                 }
2474                 int rel_flag = (DEPSREL_FLAG_NO_FLUSH | DEPSREL_FLAG_GODMODE);
2475                 if (id_type == ID_ME && comp_node->type == DEG_NODE_TYPE_GEOMETRY) {
2476                         rel_flag &= ~DEPSREL_FLAG_NO_FLUSH;
2477                 }
2478                 /* materials need update grease pencil objects */
2479                 if (id_type == ID_MA) {
2480                         rel_flag &= ~DEPSREL_FLAG_NO_FLUSH;
2481                 }
2482                 /* Notes on exceptions:
2483                  * - Parameters component is where drivers are living. Changing any
2484                  *   of the (custom) properties in the original datablock (even the
2485                  *   ones which do not imply other component update) need to make
2486                  *   sure drivers are properly updated.
2487                  *   This way, for example, changing ID property will properly poke
2488                  *   all drivers to be updated.
2489                  *
2490                  * - View layers have cached array of bases in them, which is not
2491                  *   copied by copy-on-write, and not preserved. PROBABLY it is better
2492                  *   to preserve that cache in copy-on-write, but for the time being
2493                  *   we allow flush to layer collections component which will ensure
2494                  *   that cached array fo bases exists and is up-to-date.
2495                  *
2496                  * - Action is allowed to flush as well, this way it's possible to
2497                  *   keep current tagging in animation editors (which tags action for
2498                  *   CoW update when it's changed) but yet guarantee evaluation order
2499                  *   with objects which are using that action.
2500                  */
2501                 if (comp_node->type == DEG_NODE_TYPE_PARAMETERS ||
2502                     comp_node->type == DEG_NODE_TYPE_LAYER_COLLECTIONS ||
2503                     (comp_node->type == DEG_NODE_TYPE_ANIMATION && id_type == ID_AC))
2504                 {
2505                         rel_flag &= ~DEPSREL_FLAG_NO_FLUSH;
2506                 }
2507                 /* All entry operations of each component should wait for a proper
2508                  * copy of ID.
2509                  */
2510                 OperationDepsNode *op_entry = comp_node->get_entry_operation();
2511                 if (op_entry != NULL) {
2512                         DepsRelation *rel = graph_->add_new_relation(
2513                                 op_cow, op_entry, "CoW Dependency");
2514                         rel->flag |= rel_flag;
2515                 }
2516                 /* All dangling operations should also be executed after copy-on-write. */
2517                 GHASH_FOREACH_BEGIN(OperationDepsNode *, op_node, comp_node->operations_map)
2518                 {
2519                         if (op_node == op_entry) {
2520                                 continue;
2521                         }
2522                         if (op_node->inlinks.size() == 0) {
2523                                 DepsRelation *rel = graph_->add_new_relation(
2524                                         op_cow, op_node, "CoW Dependency");
2525                                 rel->flag |= rel_flag;
2526                         }
2527                         else {
2528                                 bool has_same_comp_dependency = false;
2529                                 foreach (DepsRelation *rel_current, op_node->inlinks) {
2530                                         if (rel_current->from->type != DEG_NODE_TYPE_OPERATION) {
2531                                                 continue;
2532                                         }
2533                                         OperationDepsNode *op_node_from =
2534                                                 (OperationDepsNode *)rel_current->from;
2535                                         if (op_node_from->owner == op_node->owner) {
2536                                                 has_same_comp_dependency = true;
2537                                                 break;
2538                                         }
2539                                 }
2540                                 if (!has_same_comp_dependency) {
2541                                         DepsRelation *rel = graph_->add_new_relation(
2542                                                 op_cow, op_node, "CoW Dependency");
2543                                         rel->flag |= rel_flag;
2544                                 }
2545                         }
2546                 }
2547                 GHASH_FOREACH_END();
2548                 /* NOTE: We currently ignore implicit relations to an external
2549                  * datablocks for copy-on-write operations. This means, for example,
2550                  * copy-on-write component of Object will not wait for copy-on-write
2551                  * component of it's Mesh. This is because pointers are all known
2552                  * already so remapping will happen all correct. And then If some object
2553                  * evaluation step needs geometry, it will have transitive dependency
2554                  * to Mesh copy-on-write already.
2555                  */
2556         }
2557         GHASH_FOREACH_END();
2558         /* TODO(sergey): This solves crash for now, but causes too many
2559          * updates potentially.
2560          */
2561         if (GS(id_orig->name) == ID_OB) {
2562                 Object *object = (Object *)id_orig;
2563                 ID *object_data_id = (ID *)object->data;
2564                 if (object_data_id != NULL) {
2565                         if (deg_copy_on_write_is_needed(object_data_id)) {
2566                                 OperationKey data_copy_on_write_key(object_data_id,
2567                                                                     DEG_NODE_TYPE_COPY_ON_WRITE,
2568                                                                     DEG_OPCODE_COPY_ON_WRITE);
2569                                 add_relation(data_copy_on_write_key,
2570                                              copy_on_write_key,
2571                                              "Eval Order",
2572                                              DEPSREL_FLAG_GODMODE);
2573                         }
2574                 }
2575                 else {
2576                         BLI_assert(object->type == OB_EMPTY);
2577                 }
2578         }
2579 }
2580
2581 /* **** ID traversal callbacks functions **** */
2582
2583 void DepsgraphRelationBuilder::modifier_walk(void *user_data,
2584                                              struct Object * /*object*/,
2585                                              struct ID **idpoin,
2586                                              int /*cb_flag*/)
2587 {
2588         BuilderWalkUserData *data = (BuilderWalkUserData *)user_data;
2589         ID *id = *idpoin;
2590         if (id == NULL) {
2591                 return;
2592         }
2593         data->builder->build_id(id);
2594 }
2595
2596 void DepsgraphRelationBuilder::constraint_walk(bConstraint * /*con*/,
2597                                                ID **idpoin,
2598                                                bool /*is_reference*/,
2599                                                void *user_data)
2600 {
2601         BuilderWalkUserData *data = (BuilderWalkUserData *)user_data;
2602         ID *id = *idpoin;
2603         if (id == NULL) {
2604                 return;
2605         }
2606         data->builder->build_id(id);
2607 }
2608
2609 }  // namespace DEG