From e5c3ae31189b3acb54d33061da2bd27c3d0abad5 Mon Sep 17 00:00:00 2001
From: Sergey Sharybin <sergey.vfx@gmail.com>
Date: Wed, 15 May 2019 14:11:13 +0200
Subject: [PATCH] Addons: Adopt for Dependency Graph API changes

Mainly search-and-replace approach.

Tested the enabled-by-default export/import addons. Seems to work with
an exception of X3D which is still referencing Blender Internal material
properties.

Reviewers: brecht

Reviewed By: brecht

Differential Revision: https://developer.blender.org/D4866
---
 add_curve_ivygen.py                           |  3 +-
 animation_add_corrective_shape_key.py         |  6 ++-
 blenderkit/asset_inspector.py                 |  3 +-
 blenderkit/ui.py                              |  4 +-
 blenderkit/utils.py                           | 11 +++--
 .../primitive_exporters/mesh_exporter.py      |  3 +-
 io_export_pc2.py                              | 12 +++++-
 io_export_unreal_psk_psa.py                   |  8 ++--
 io_mesh_ply/export_ply.py                     |  3 +-
 io_mesh_raw/export_raw.py                     |  3 +-
 io_mesh_stl/blender_utils.py                  |  6 ++-
 io_mesh_uv_layout/__init__.py                 |  3 +-
 io_scene_3ds/export_3ds.py                    |  3 +-
 io_scene_fbx/export_fbx_bin.py                | 38 +++++++++++------
 .../blender/exp/gltf2_blender_gather_nodes.py |  6 ++-
 io_scene_ms3d/ms3d_export.py                  |  6 +--
 io_scene_obj/export_obj.py                    |  6 ++-
 io_scene_obj/import_obj.py                    |  2 +-
 io_scene_vrml2/export_vrml2.py                |  7 ++--
 io_scene_x/export_x.py                        |  7 ++--
 io_scene_x3d/export_x3d.py                    |  5 ++-
 io_shape_mdd/export_mdd.py                    |  6 ++-
 mesh_looptools.py                             |  3 +-
 mesh_snap_utilities_line/common_classes.py    |  2 +-
 mesh_snap_utilities_line/widgets.py           |  4 +-
 mesh_tissue/lattice.py                        |  9 ++--
 mesh_tissue/tessellate_numpy.py               | 41 ++++++++-----------
 mesh_tissue/uv_to_mesh.py                     |  7 +++-
 object_carver/carver_utils.py                 |  2 +-
 object_fracture_cell/fracture_cell_setup.py   | 10 ++---
 object_print3d_utils/mesh_helpers.py          | 10 ++---
 object_scatter/operator.py                    |  3 +-
 oscurart_tools/mesh/shapes_to_objects.py      |  3 +-
 render_povray/render.py                       |  5 ++-
 34 files changed, 148 insertions(+), 102 deletions(-)

diff --git a/add_curve_ivygen.py b/add_curve_ivygen.py
index 8e1965f5f..60f6ec596 100644
--- a/add_curve_ivygen.py
+++ b/add_curve_ivygen.py
@@ -438,7 +438,8 @@ def bvhtree_from_object(ob):
     import bmesh
     bm = bmesh.new()
 
-    mesh = ob.to_mesh(bpy.context.depsgraph, True)
+    depsgraph = context.evaluated_depsgraph_get()
+    mesh = ob.evaluated_get(depsgraph).to_mesh()
     bm.from_mesh(mesh)
     bm.transform(ob.matrix_world)
 
diff --git a/animation_add_corrective_shape_key.py b/animation_add_corrective_shape_key.py
index ed72fcae3..e40a7919c 100644
--- a/animation_add_corrective_shape_key.py
+++ b/animation_add_corrective_shape_key.py
@@ -70,7 +70,8 @@ def extract_vert_coords(ob, verts):
 def extract_mapped_coords(ob, shape_verts):
     totvert = len(shape_verts)
 
-    mesh = ob.to_mesh(bpy.context.scene, True, 'PREVIEW')
+    depsgraph = context.evaluated_depsgraph_get()
+    mesh = ob.evaluated_get(depsgraph).to_mesh()
 
     # cheating, the original mapped verts happen
     # to be at the end of the vertex array
@@ -201,7 +202,8 @@ class add_corrective_pose_shape(bpy.types.Operator):
 
 
 def func_object_duplicate_flatten_modifiers(context, obj):
-    mesh = obj.to_mesh(context.scene, True, 'PREVIEW')
+    depsgraph = context.evaluated_depsgraph_get()
+    mesh = obj.evaluated_get(depsgraph).to_mesh()
     name = obj.name + "_clean"
     new_object = bpy.data.objects.new(name, mesh)
     new_object.data = mesh
diff --git a/blenderkit/asset_inspector.py b/blenderkit/asset_inspector.py
index 1db9f6b44..93a39d593 100644
--- a/blenderkit/asset_inspector.py
+++ b/blenderkit/asset_inspector.py
@@ -205,7 +205,8 @@ def check_meshprops(props, obs):
     for ob in obs:
         if ob.type == 'MESH' or ob.type == 'CURVE':
             if ob.type == 'CURVE':
-                mesh = ob.to_mesh(depsgraph=bpy.context.depsgraph, apply_modifiers=True, calc_undeformed=False)
+                depsgraph = bpy.context.evaluated_depsgraph_get()
+                mesh = ob.evaluated_get(depsgraph).to_mesh()
             else:
                 mesh = ob.data
             fco = len(mesh.polygons)
diff --git a/blenderkit/ui.py b/blenderkit/ui.py
index 638909504..fd475af9c 100644
--- a/blenderkit/ui.py
+++ b/blenderkit/ui.py
@@ -1241,8 +1241,8 @@ class AssetBarOperator(bpy.types.Operator):
                             if object is not None and not object.is_library_indirect:
                                 target_object = object.name
                                 # create final mesh to extract correct material slot
-                                temp_mesh = object.to_mesh(depsgraph=bpy.context.depsgraph, apply_modifiers=True,
-                                                           calc_undeformed=False)
+                                depsgraph = bpy.context.evaluated_depsgraph_get()
+                                temp_mesh = object.evaluated_get(depsgraph).to_mesh()
                                 target_slot = temp_mesh.polygons[face_index].material_index
                             else:
                                 self.report({'WARNING'}, "Invalid or library object as input:")
diff --git a/blenderkit/utils.py b/blenderkit/utils.py
index 56e9a0ef7..c6e97fa9b 100644
--- a/blenderkit/utils.py
+++ b/blenderkit/utils.py
@@ -300,9 +300,13 @@ def get_bounds_snappable(obs, use_modifiers=False):
         if ob.type == 'MESH' or ob.type == 'CURVE':
             # If to_mesh() works we can use it on curves and any other ob type almost.
             # disabled to_mesh for 2.8 by now, not wanting to use dependency graph yet.
-            mesh = ob.to_mesh(depsgraph=bpy.context.depsgraph, apply_modifiers=True, calc_undeformed=False)
+            depsgraph = bpy.context.evaluated_depsgraph_get()
+            mesh = ob.evaluated_get(depsgraph).to_mesh()
 
-            # to_mesh(context.depsgraph, apply_modifiers=self.applyModifiers, calc_undeformed=False)
+            # if self.applyModifiers:
+            #     evaluated_get(depsgraph).to_mesh()
+            # else:
+            #     to_mesh()
             obcount += 1
             for c in mesh.vertices:
                 coord = c.co
@@ -339,7 +343,8 @@ def get_bounds_worldspace(obs, use_modifiers=False):
         # bb=ob.bound_box
         mw = ob.matrix_world
         if ob.type == 'MESH' or ob.type == 'CURVE':
-            mesh = ob.to_mesh(depsgraph=bpy.context.depsgraph, apply_modifiers=True, calc_undeformed=False)
+            depsgraph = bpy.context.evaluated_depsgraph_get()
+            mesh = ob.evaluated_get(depsgraph).to_mesh()
             obcount += 1
             for c in mesh.vertices:
                 coord = c.co
diff --git a/io_export_dxf/primitive_exporters/mesh_exporter.py b/io_export_dxf/primitive_exporters/mesh_exporter.py
index 5d29e2cc9..358bc2e3a 100644
--- a/io_export_dxf/primitive_exporters/mesh_exporter.py
+++ b/io_export_dxf/primitive_exporters/mesh_exporter.py
@@ -52,7 +52,8 @@ class MeshDXFExporter(BasePrimitiveDXFExporter):
     def _getMeshData(self, ctx, obj, settings):
         if obj.modifiers and settings['apply_modifiers']:
             #this gets mesh with applied modifiers
-            data = obj.to_mesh(ctx.scene, True, 'PREVIEW')
+            depsgraph = ctx.evaluated_depsgraph_get()
+            data = obj.evaluated_get(depsgraph).to_mesh()
         else:
     #        me = ob.getData(mesh=1) # is a Mesh if mesh>0 (otherwise it is a NMesh)
             data = obj.data
diff --git a/io_export_pc2.py b/io_export_pc2.py
index 7384e21ef..5e69d14ff 100644
--- a/io_export_pc2.py
+++ b/io_export_pc2.py
@@ -63,7 +63,12 @@ def do_export(context, props, filepath):
     end = props.range_end
     sampling = float(props.sampling)
     apply_modifiers = props.apply_modifiers
-    me = ob.to_mesh(context.depsgraph, apply_modifiers)
+    depsgraph = None
+    if apply_modifiers:
+        depsgraph = context.evaluated_depsgraph_get()
+        me = ob.evaluated_get(depsgraph).to_mesh()
+    else:
+        me = ob.to_mesh()
     vertCount = len(me.vertices)
     sampletimes = get_sampled_frames(start, end, sampling)
     sampleCount = len(sampletimes)
@@ -79,7 +84,10 @@ def do_export(context, props, filepath):
     for frame in sampletimes:
         # stupid modf() gives decimal part first!
         sc.frame_set(int(frame[1]), subframe=frame[0])
-        me = ob.to_mesh(context.depsgraph, apply_modifiers)
+        if apply_modifiers:
+            me = ob.evaluated_get(depsgraph).to_mesh()
+        else:
+            me = ob.to_mesh()
 
         if len(me.vertices) != vertCount:
             bpy.data.meshes.remove(me, do_unlink=True)
diff --git a/io_export_unreal_psk_psa.py b/io_export_unreal_psk_psa.py
index c4fb410e5..4851586b7 100644
--- a/io_export_unreal_psk_psa.py
+++ b/io_export_unreal_psk_psa.py
@@ -981,7 +981,8 @@ def triangulate_mesh(object):
     view_layer = bpy.context.view_layer
 
     me_ob = object.copy()
-    me_ob.data = object.to_mesh(bpy.context.scene, True, 'PREVIEW')  # write data object
+    depsgraph = bpy.context.evaluated_depsgraph_get()
+    me_ob.data = object.evaluated_get(depsgraph).to_mesh()  # write data object
     bpy.context.collection.objects.link(me_ob)
     bpy.context.scene.update()
     bpy.ops.object.mode_set(mode='OBJECT')
@@ -1006,7 +1007,7 @@ def triangulate_mesh(object):
 
     verbose("Triangulated mesh")
 
-    me_ob.data = me_ob.to_mesh(bpy.context.scene, True, 'PREVIEW')  # write data object
+    me_ob.data = me_ob.evaluated_get(depsgraph).to_mesh()  # write data object
     bpy.context.scene.update()
     return me_ob
 
@@ -2100,7 +2101,8 @@ def rebuildmesh(obj):
     smoothings = []
     uvfaces = []
     # print("creating array build mesh...")
-    mmesh = obj.to_mesh(bpy.context.scene, True, 'PREVIEW')
+    depsgraph = bpy.context.evaluated_depsgraph_get()
+    mmesh = obj.evaluated_get(depsgraph).to_mesh()
     uv_layer = mmesh.tessface_uv_textures.active
 
     for face in mmesh.tessfaces:
diff --git a/io_mesh_ply/export_ply.py b/io_mesh_ply/export_ply.py
index 3a5ef0ae4..f465ed91d 100644
--- a/io_mesh_ply/export_ply.py
+++ b/io_mesh_ply/export_ply.py
@@ -202,7 +202,8 @@ def save(
         bpy.ops.object.mode_set(mode='OBJECT')
 
     if use_mesh_modifiers and obj.modifiers:
-        mesh = obj.to_mesh(context.depsgraph, True)
+        depsgraph = context.evaluated_depsgraph_get()
+        mesh = obj.evaluated_get(depsgraph).to_mesh()
 
     else:
         mesh = obj.data.copy()
diff --git a/io_mesh_raw/export_raw.py b/io_mesh_raw/export_raw.py
index b5c5ef36f..8672134ad 100644
--- a/io_mesh_raw/export_raw.py
+++ b/io_mesh_raw/export_raw.py
@@ -64,12 +64,13 @@ def write(filepath,
           ):
 
     scene = bpy.context.scene
+    depsgraph = bpy.context.evaluated_depsgraph_get()
 
     faces = []
     for obj in bpy.context.selected_objects:
         if applyMods or obj.type != 'MESH':
             try:
-                me = obj.to_mesh(scene, True, "PREVIEW")
+                me = obj.evaluated_get(depsgraph).to_mesh()
             except:
                 me = None
             is_tmp_mesh = True
diff --git a/io_mesh_stl/blender_utils.py b/io_mesh_stl/blender_utils.py
index fcc4889a4..088caa8e6 100644
--- a/io_mesh_stl/blender_utils.py
+++ b/io_mesh_stl/blender_utils.py
@@ -82,7 +82,11 @@ def faces_from_mesh(ob, global_matrix, use_mesh_modifiers=False):
 
     # get the modifiers
     try:
-        mesh = ob.to_mesh(bpy.context.depsgraph, use_mesh_modifiers)
+        if use_mesh_modifiers:
+            depsgraph = bpy.context.evaluated_depsgraph_get()
+            mesh = ob.evaluated_get(depsgraph).to_mesh()
+        else:
+            mesh = ob.to_mesh()
     except RuntimeError:
         return
 
diff --git a/io_mesh_uv_layout/__init__.py b/io_mesh_uv_layout/__init__.py
index 85d55b287..d068a0085 100644
--- a/io_mesh_uv_layout/__init__.py
+++ b/io_mesh_uv_layout/__init__.py
@@ -152,9 +152,10 @@ class ExportUVLayout(bpy.types.Operator):
         return {'FINISHED'}
 
     def iter_meshes_to_export(self, context):
+        depsgraph = context.evaluated_depsgraph_get()
         for obj in self.iter_objects_to_export(context):
             if self.modified:
-                yield obj.to_mesh(context.depsgraph, apply_modifiers=True)
+                yield obj.evaluated_get(depsgraph).to_mesh()
             else:
                 yield obj.data
 
diff --git a/io_scene_3ds/export_3ds.py b/io_scene_3ds/export_3ds.py
index 9440b14fb..84b7c91a0 100644
--- a/io_scene_3ds/export_3ds.py
+++ b/io_scene_3ds/export_3ds.py
@@ -1021,6 +1021,7 @@ def save(operator,
     mesh_objects = []
 
     scene = context.scene
+    depsgraph = context.evaluated_depsgraph_get()
 
     if use_selection:
         objects = (ob for ob in scene.objects if ob.is_visible(scene) and ob.select)
@@ -1039,7 +1040,7 @@ def save(operator,
                 continue
 
             try:
-                data = ob_derived.to_mesh(scene, True, 'PREVIEW')
+                data = ob_derived.evaluated_get(depsgraph).to_mesh()
             except:
                 data = None
 
diff --git a/io_scene_fbx/export_fbx_bin.py b/io_scene_fbx/export_fbx_bin.py
index af3bc0055..e399c8077 100644
--- a/io_scene_fbx/export_fbx_bin.py
+++ b/io_scene_fbx/export_fbx_bin.py
@@ -1130,7 +1130,9 @@ def fbx_data_mesh_elements(root, me_obj, scene_data, done_meshes):
     # Face's materials.
     me_fbxmaterials_idx = scene_data.mesh_material_indices.get(me)
     if me_fbxmaterials_idx is not None:
-        me_blmaterials = me.materials
+        # Mapping to indices is done using original material pointers, so need to go from evaluated
+        # to original (this is for the case mesh is a result of evaluated modifier stack).
+        me_blmaterials = [material.original for material in  me.materials]
         if me_fbxmaterials_idx and me_blmaterials:
             lay_ma = elem_data_single_int32(geom, b"LayerElementMaterial", 0)
             elem_data_single_int32(lay_ma, b"Version", FBX_GEOMETRY_MATERIAL_VERSION)
@@ -2204,27 +2206,36 @@ def fbx_data_from_scene(scene, depsgraph, settings):
         if settings.use_mesh_modifiers or ob.type in BLENDER_OTHER_OBJECT_TYPES or is_ob_material:
             # We cannot use default mesh in that case, or material would not be the right ones...
             use_org_data = not (is_ob_material or ob.type in BLENDER_OTHER_OBJECT_TYPES)
-            tmp_mods = []
+            backup_pose_positions = []
             if use_org_data and ob.type == 'MESH':
                 # No need to create a new mesh in this case, if no modifier is active!
                 for mod in ob.modifiers:
                     # For meshes, when armature export is enabled, disable Armature modifiers here!
                     # XXX Temp hacks here since currently we only have access to a viewport depsgraph...
+                    #
+                    # NOTE: We put armature to the rest pose instead of disabling it so we still
+                    # have vertex groups in the evaluated mesh.
                     if mod.type == 'ARMATURE' and 'ARMATURE' in settings.object_types:
-                        tmp_mods.append((mod, mod.show_render, mod.show_viewport))
-                        mod.show_render = False
-                        mod.show_viewport = False
+                        object = mod.object
+                        if object and object.type == 'ARMATURE':
+                            armature = object.data
+                            backup_pose_positions.append((armature, armature.pose_position))
+                            armature.pose_position = 'REST'
                     if mod.show_render or mod.show_viewport:
                         use_org_data = False
             if not use_org_data:
-                tmp_me = ob.to_mesh(
-                    depsgraph,
-                    apply_modifiers=settings.use_mesh_modifiers)
+                # If modifiers has been altered need to update dependency graph.
+                if backup_pose_positions:
+                    depsgraph.update()
+                ob_to_convert = ob.evaluated_get(depsgraph) if settings.use_mesh_modifiers else ob
+                tmp_me = ob_to_convert.to_mesh()
                 data_meshes[ob_obj] = (get_blenderID_key(tmp_me), tmp_me, True)
-            # Re-enable temporary disabled modifiers.
-            for mod, show_render, show_viewport in tmp_mods:
-                mod.show_render = show_render
-                mod.show_viewport = show_viewport
+            # Change armatures back.
+            for armature, pose_position in backup_pose_positions:
+                print((armature, pose_position))
+                armature.pose_position = pose_position
+                # Update now, so we don't leave modified state after last object was exported.
+                depsgraph.update()
         if use_org_data:
             data_meshes[ob_obj] = (get_blenderID_key(ob.data), ob.data, False)
 
@@ -3100,7 +3111,8 @@ def save(operator, context,
                 ctx_objects = context.view_layer.objects
         kwargs_mod["context_objects"] = ctx_objects
 
-        ret = save_single(operator, context.scene, context.depsgraph, filepath, **kwargs_mod)
+        depsgraph = context.evaluated_depsgraph_get()
+        ret = save_single(operator, context.scene, depsgraph, filepath, **kwargs_mod)
     else:
         # XXX We need a way to generate a depsgraph for inactive view_layers first...
         # XXX Also, what to do in case of batch-exporting scenes, when there is more than one view layer?
diff --git a/io_scene_gltf2/blender/exp/gltf2_blender_gather_nodes.py b/io_scene_gltf2/blender/exp/gltf2_blender_gather_nodes.py
index 7dfed7383..35785c80a 100755
--- a/io_scene_gltf2/blender/exp/gltf2_blender_gather_nodes.py
+++ b/io_scene_gltf2/blender/exp/gltf2_blender_gather_nodes.py
@@ -226,7 +226,8 @@ def __gather_mesh(blender_object, export_settings):
                     armature_modifiers[idx] = modifier.show_viewport
                     modifier.show_viewport = False
 
-        blender_mesh = blender_object.to_mesh(bpy.context.depsgraph, True)
+        depsgraph = bpy.context.evaluated_depsgraph_get()
+        blender_mesh = blender_object.evaluated_get(depsgraph).to_mesh()
         for prop in blender_object.data.keys():
             blender_mesh[prop] = blender_object.data[prop]
         skip_filter = True
@@ -306,7 +307,8 @@ def __gather_skin(blender_object, export_settings):
         return None
 
     # check if any vertices in the mesh are part of a vertex group
-    blender_mesh = blender_object.to_mesh(bpy.context.depsgraph, True)
+    depsgraph = bpy.context.evaluated_depsgraph_get()
+    blender_mesh = blender_object.evaluated_get(depsgraph).to_mesh()
     if not any(vertex.groups is not None and len(vertex.groups) > 0 for vertex in blender_mesh.vertices):
         return None
 
diff --git a/io_scene_ms3d/ms3d_export.py b/io_scene_ms3d/ms3d_export.py
index 004a0e4ee..ba48e0463 100644
--- a/io_scene_ms3d/ms3d_export.py
+++ b/io_scene_ms3d/ms3d_export.py
@@ -221,6 +221,7 @@ class Ms3dExporter():
     def create_geometry(self, blender_context, ms3d_model, blender_mesh_objects, blender_to_ms3d_bones):
         blender_view_layer = blender_context.view_layer
         blender_scene = blender_context.scene
+        blender_depsgraph = blender_context.evaluated_depsgraph_get()
         blender_collection = blender_context.collection
 
         blender_to_ms3d_vertices = {}
@@ -298,10 +299,7 @@ class Ms3dExporter():
 
             # convert to tris by using the triangulate modifier
             blender_mesh_object_temp.modifiers.new("temp", 'TRIANGULATE')
-            blender_mesh_temp = blender_mesh_object_temp.to_mesh(
-                    blender_scene,
-                    True,
-                    self.options_apply_modifiers_mode)
+            blender_mesh_temp = blender_mesh_object_temp.evaluated_get(blender_depsgraph).to_mesh()
 
             enable_edit_mode(True, blender_context)
             bm = bmesh.new()
diff --git a/io_scene_obj/export_obj.py b/io_scene_obj/export_obj.py
index 5e2121d62..49ec8bc0a 100644
--- a/io_scene_obj/export_obj.py
+++ b/io_scene_obj/export_obj.py
@@ -347,8 +347,10 @@ def write_file(filepath, objects, depsgraph, scene,
                             continue
                         # END NURBS
 
+                        ob_for_convert = ob.evaluated_get(depsgraph) if EXPORT_APPLY_MODIFIERS else ob.original
+
                         try:
-                            me = ob.to_mesh(depsgraph, EXPORT_APPLY_MODIFIERS)
+                            me = ob_for_convert.to_mesh()
                         except RuntimeError:
                             me = None
 
@@ -678,7 +680,7 @@ def _write(context, filepath,
         base_name, ext = os.path.splitext(filepath)
         context_name = [base_name, '', '', ext]  # Base name, scene name, frame number, extension
 
-        depsgraph = context.depsgraph
+        depsgraph = context.evaluated_depsgraph_get()
         scene = context.scene
 
         # Exit edit mode before exporting, so current object states are exported properly.
diff --git a/io_scene_obj/import_obj.py b/io_scene_obj/import_obj.py
index b278c8496..2763f8fe5 100644
--- a/io_scene_obj/import_obj.py
+++ b/io_scene_obj/import_obj.py
@@ -1243,7 +1243,7 @@ def load(context,
             # we could apply this anywhere before scaling.
             obj.matrix_world = global_matrix
 
-        scene.update()
+        view_layer.update()
 
         axis_min = [1000000000] * 3
         axis_max = [-1000000000] * 3
diff --git a/io_scene_vrml2/export_vrml2.py b/io_scene_vrml2/export_vrml2.py
index 221145823..d259e0b5a 100644
--- a/io_scene_vrml2/export_vrml2.py
+++ b/io_scene_vrml2/export_vrml2.py
@@ -150,7 +150,7 @@ def save_bmesh(fw, bm,
 
 
 def save_object(fw, global_matrix,
-                scene, obj,
+                depsgraph, scene, obj,
                 use_mesh_modifiers,
                 use_color, color_type,
                 use_uv,
@@ -163,7 +163,7 @@ def save_object(fw, global_matrix,
         if is_editmode:
             bpy.ops.object.editmode_toggle()
 
-        me = obj.to_mesh(scene, True, 'PREVIEW')
+        me = obj.evaluated_get(depsgraph).to_mesh()
         bm = bmesh.new()
         bm.from_mesh(me)
 
@@ -227,6 +227,7 @@ def save(operator,
          path_mode='AUTO'):
 
     scene = context.scene
+    depsgraph = context.evaluated_depsgraph_get()
 
     # store files to copy
     copy_set = set()
@@ -245,7 +246,7 @@ def save(operator,
         if obj.type == 'MESH':
             fw("\n# %r\n" % obj.name)
             save_object(fw, global_matrix,
-                        scene, obj,
+                        depsgraph, scene, obj,
                         use_mesh_modifiers,
                         use_color, color_type,
                         use_uv,
diff --git a/io_scene_x/export_x.py b/io_scene_x/export_x.py
index 4bde67aae..d2773881b 100644
--- a/io_scene_x/export_x.py
+++ b/io_scene_x/export_x.py
@@ -371,15 +371,14 @@ class MeshExportObject(ExportObject):
                 for Modifier in DeactivatedModifierList:
                     Modifier.show_viewport = False
 
-                Mesh = self.BlenderObject.to_mesh(self.Exporter.context.scene,
-                    True, 'PREVIEW')
+               depsgraph = self.Exporter.context.evaluated_depsgraph_get()
+                Mesh = self.BlenderObject.evaluated_get(depsgraph).to_mesh()
 
                 # Restore the deactivated modifiers
                 for Modifier in DeactivatedModifierList:
                     Modifier.show_viewport = True
             else:
-                Mesh = self.BlenderObject.to_mesh(self.Exporter.context.scene,
-                    False, 'PREVIEW')
+                Mesh = self.BlenderObject.to_mesh()
             self.Exporter.Log("Done")
 
             self.__WriteMesh(Mesh)
diff --git a/io_scene_x3d/export_x3d.py b/io_scene_x3d/export_x3d.py
index ff5ec0a30..491675e73 100644
--- a/io_scene_x3d/export_x3d.py
+++ b/io_scene_x3d/export_x3d.py
@@ -217,6 +217,7 @@ def h3d_is_object_view(scene, obj):
 
 def export(file,
            global_matrix,
+           depsgraph,
            scene,
            view_layer,
            use_mesh_modifiers=False,
@@ -1421,8 +1422,9 @@ def export(file,
 
             elif obj_type in {'MESH', 'CURVE', 'SURFACE', 'FONT'}:
                 if (obj_type != 'MESH') or (use_mesh_modifiers and obj.is_modified(scene, 'PREVIEW')):
+                    obj_for_mesh = obj.evaluated_get(depsgraph) if use_mesh_modifiers else obj
                     try:
-                        me = obj.to_mesh(scene, use_mesh_modifiers, 'PREVIEW')
+                        me = obj_for_mesh.to_mesh()
                     except:
                         me = None
                     do_remove = True
@@ -1588,6 +1590,7 @@ def save(context,
 
     export(file,
            global_matrix,
+           context.evaluated_depsgraph_get(),
            context.scene,
            context.view_layer,
            use_mesh_modifiers=use_mesh_modifiers,
diff --git a/io_shape_mdd/export_mdd.py b/io_shape_mdd/export_mdd.py
index 48e34f298..69b9dbe1a 100644
--- a/io_shape_mdd/export_mdd.py
+++ b/io_shape_mdd/export_mdd.py
@@ -67,7 +67,8 @@ def save(context, filepath="", frame_start=1, frame_end=300, fps=25.0, use_rest_
 
     orig_frame = scene.frame_current
     scene.frame_set(frame_start)
-    me = obj.to_mesh(context.depsgraph, True)
+    depsgraph = context.evaluated_depsgraph_get()
+    me = obj.evaluated_get(depsgraph).to_mesh()
 
     #Flip y and z
     '''
@@ -102,7 +103,8 @@ def save(context, filepath="", frame_start=1, frame_end=300, fps=25.0, use_rest_
 
     for frame in range(frame_start, frame_end + 1):  # in order to start at desired frame
         scene.frame_set(frame)
-        me = obj.to_mesh(context.depsgraph, True)
+        depsgraph = context.evaluated_depsgraph_get()
+        me = obj.evaluated_get(depsgraph).to_mesh()
         check_vertcount(me, numverts)
         me.transform(mat_flip @ obj.matrix_world)
 
diff --git a/mesh_looptools.py b/mesh_looptools.py
index 58aba0bf7..a863218db 100644
--- a/mesh_looptools.py
+++ b/mesh_looptools.py
@@ -526,7 +526,8 @@ def get_derived_bmesh(object, bm):
                 mod.show_viewport = False
         # get derived mesh
         bm_mod = bmesh.new()
-        mesh_mod = object.to_mesh(bpy.context.depsgraph, True)
+        depsgraph = bpy.context.evaluated_depsgraph_get()
+        mesh_mod = object.evaluated_get(depsgraph).to_mesh()
         bm_mod.from_mesh(mesh_mod)
         bpy.context.blend_data.meshes.remove(mesh_mod)
         # re-enable other modifiers
diff --git a/mesh_snap_utilities_line/common_classes.py b/mesh_snap_utilities_line/common_classes.py
index c654cb824..2dac71a07 100644
--- a/mesh_snap_utilities_line/common_classes.py
+++ b/mesh_snap_utilities_line/common_classes.py
@@ -336,7 +336,7 @@ class SnapUtilities:
         from .snap_context_l import global_snap_context_get
 
         #Create Snap Context
-        self.sctx = global_snap_context_get(context.depsgraph, context.region, context.space_data)
+        self.sctx = global_snap_context_get(context.evaluated_depsgraph_get(), context.region, context.space_data)
         self.sctx.set_pixel_dist(12)
         self.sctx.use_clip_planes(True)
 
diff --git a/mesh_snap_utilities_line/widgets.py b/mesh_snap_utilities_line/widgets.py
index 235657b11..9173c264c 100644
--- a/mesh_snap_utilities_line/widgets.py
+++ b/mesh_snap_utilities_line/widgets.py
@@ -66,7 +66,7 @@ class SnapWidgetCommon(SnapUtilities, bpy.types.Gizmo):
         self.last_mval = None
 
         self.wm_operators = context.window_manager.operators
-        self.depsgraph = context.depsgraph
+        self.depsgraph = context.evaluated_depsgraph_get()
         bpy.app.handlers.depsgraph_update_post.append(self.handler)
         SnapWidgetCommon.snap_to_update = False
 
@@ -101,7 +101,7 @@ class SnapWidgetCommon(SnapUtilities, bpy.types.Gizmo):
 
         #print('test_select', mval)
         space = context.space_data
-        self.sctx.update_viewport_context(context.depsgraph, context.region, space, True)
+        self.sctx.update_viewport_context(context.evaluated_depsgraph_get(), context.region, space, True)
 
         shading = space.shading
         snap_face = not ((self.snap_vert or self.snap_edge) and
diff --git a/mesh_tissue/lattice.py b/mesh_tissue/lattice.py
index 4b53afe72..eb1269a30 100644
--- a/mesh_tissue/lattice.py
+++ b/mesh_tissue/lattice.py
@@ -306,6 +306,7 @@ class lattice_along_surface(Operator):
         if len(bpy.context.selected_objects) != 2:
             self.report({'ERROR'}, "Please, select two objects")
             return {'CANCELLED'}
+        depsgraph = context.evaluated_depsgraph_get()
         grid_obj = bpy.context.active_object
         if grid_obj.type not in ('MESH', 'CURVE', 'SURFACE'):
             self.report({'ERROR'}, "The surface object is not valid. Only Mesh,"
@@ -320,10 +321,7 @@ class lattice_along_surface(Operator):
                 break
         try:
             obj_dim = obj.dimensions
-            obj_me = obj.to_mesh(
-                            bpy.context.scene, apply_modifiers=True,
-                            settings='PREVIEW'
-                            )
+            obj_me = obj.evaluated_get(depsgraph).to_mesh()
         except:
             self.report({'ERROR'}, "The object to deform is not valid. Only "
                         "Mesh, Curve, Surface and Font objects are allowed.")
@@ -333,8 +331,7 @@ class lattice_along_surface(Operator):
         grid_obj = bpy.context.active_object
         bpy.ops.object.convert(target='MESH')
         bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
-        grid_mesh = grid_obj.to_mesh(bpy.context.scene, apply_modifiers=True,
-                                     settings='PREVIEW')
+        grid_mesh = grid_obj.evaluated_get(depsgraph).to_mesh()
 
         if len(grid_mesh.polygons) > 64 * 64:
             bpy.ops.object.delete(use_global=False)
diff --git a/mesh_tissue/tessellate_numpy.py b/mesh_tissue/tessellate_numpy.py
index 8803966df..07c4fc87c 100644
--- a/mesh_tissue/tessellate_numpy.py
+++ b/mesh_tissue/tessellate_numpy.py
@@ -72,9 +72,13 @@ def tassellate(ob0, ob1, offset, zscale, gen_modifiers, com_modifiers, mode,
     random.seed(rand_seed)
     old_me0 = ob0.data      # Store generator mesh
 
+    if gen_modifiers or com_modifiers:
+        depsgraph = context.evaluated_depsgraph_get()
+    else:
+        depsgraph = None
+
     if gen_modifiers:       # Apply generator modifiers
-        me0 = ob0.to_mesh(bpy.context.scene, apply_modifiers=True,
-                          settings='PREVIEW')
+        me0 = ob0.evaluated_get(depsgraph).to_mesh()
     else:
         me0 = ob0.data
     ob0.data = me0
@@ -92,8 +96,7 @@ def tassellate(ob0, ob1, offset, zscale, gen_modifiers, com_modifiers, mode,
 
     # Apply component modifiers
     if com_modifiers:
-        me1 = ob1.to_mesh(bpy.context.scene, apply_modifiers=True,
-                          settings='PREVIEW')
+        me1 = ob1.evaluated_get(depsgraph).to_mesh()
     else:
         me1 = ob1.data
 
@@ -666,13 +669,14 @@ class tessellate(Operator):
             col.prop(self, "object_name")
 
             # Count number of faces
+            if self.gen_modifiers or self.com_modifiers:
+                depsgraph = context.evaluated_depsgraph_get()
+            else:
+                depsgraph = None
             try:
                 polygons = 0
                 if self.gen_modifiers:
-                    me_temp = ob0.to_mesh(
-                                    bpy.context.scene,
-                                    apply_modifiers=True, settings='PREVIEW'
-                                    )
+                    me_temp = ob0.evaluated_get(depsgraph).to_mesh()
                 else:
                     me_temp = ob0.data
 
@@ -684,11 +688,7 @@ class tessellate(Operator):
                             polygons += 1
 
                 if self.com_modifiers:
-                    me_temp = bpy.data.objects[self.component].to_mesh(
-                                            bpy.context.scene,
-                                            apply_modifiers=True,
-                                            settings='PREVIEW'
-                                            )
+                    me_temp = bpy.data.objects[self.component].evaluated_get(depsgraph).to_mesh()
                 else:
                     me_temp = bpy.data.objects[self.component].data
                 polygons *= len(me_temp.polygons)
@@ -1233,15 +1233,14 @@ class settings_tessellate(Operator):
         row.prop(self, "bool_selection", text="On selected Faces")
         col.separator()
 
+        if self.gen_modifiers or self.com_modifiers:
+            depsgraph = context.evaluated_depsgraph_get()
+
         # Count number of faces
         try:
             polygons = 0
             if self.gen_modifiers:
-                me_temp = bpy.data.objects[self.generator].to_mesh(
-                                                    bpy.context.scene,
-                                                    apply_modifiers=True,
-                                                    settings='PREVIEW'
-                                                    )
+                me_temp = bpy.data.objects[self.generator].evaluated_get(depsgraph).to_mesh()
             else:
                 me_temp = bpy.data.objects[self.generator].data
 
@@ -1253,11 +1252,7 @@ class settings_tessellate(Operator):
                         polygons += 1
 
             if self.com_modifiers:
-                me_temp = bpy.data.objects[self.component].to_mesh(
-                                                    bpy.context.scene,
-                                                    apply_modifiers=True,
-                                                    settings='PREVIEW'
-                                                    )
+                me_temp = bpy.data.objects[self.component].evaluated_get(depsgraph).to_mesh()
             else:
                 me_temp = bpy.data.objects[self.component].data
             polygons *= len(me_temp.polygons)
diff --git a/mesh_tissue/uv_to_mesh.py b/mesh_tissue/uv_to_mesh.py
index a544ff64c..8a69b4d3f 100644
--- a/mesh_tissue/uv_to_mesh.py
+++ b/mesh_tissue/uv_to_mesh.py
@@ -85,8 +85,11 @@ class uv_to_mesh(Operator):
             bpy.ops.object.convert(target='MESH')
         ob0 = bpy.context.object
 
-        me0 = ob0.to_mesh(bpy.context.scene,
-                    apply_modifiers=self.apply_modifiers, settings='PREVIEW')
+        if self.apply_modifiers:
+            depsgraph = context.evaluated_depsgraph_get()
+            me0 = ob0.evaluated_get(depsgraph).to_mesh()
+        else:
+            me0 = ob0.to_mesh()
         area = 0
 
         verts = []
diff --git a/object_carver/carver_utils.py b/object_carver/carver_utils.py
index 67c5769d8..28dc93c4b 100644
--- a/object_carver/carver_utils.py
+++ b/object_carver/carver_utils.py
@@ -399,7 +399,7 @@ def Picking(context, event):
 	ray_target = ray_origin + view_vector
 
 	def visible_objects_and_duplis():
-		depsgraph = context.depsgraph
+		depsgraph = context.evaluated_depsgraph_get()
 		for dup in depsgraph.object_instances:
 			if dup.is_instance:  # Real dupli instance
 				obj = dup.instance_object.original
diff --git a/object_fracture_cell/fracture_cell_setup.py b/object_fracture_cell/fracture_cell_setup.py
index fcd656811..c3e47bbd5 100644
--- a/object_fracture_cell/fracture_cell_setup.py
+++ b/object_fracture_cell/fracture_cell_setup.py
@@ -65,10 +65,9 @@ def _points_from_object(obj, source):
             matrix = obj.matrix_world.copy()
             points.extend([matrix * v.co for v in mesh.vertices])
         else:
+            depsgraph = bpy.context.evaluated_depsgraph_get()
             try:
-                mesh = ob.to_mesh(scene=bpy.context.scene,
-                                  apply_modifiers=True,
-                                  settings='PREVIEW')
+                mesh = ob.evaluated_get(depsgraph).to_mesh()
             except:
                 mesh = None
 
@@ -324,6 +323,7 @@ def cell_fracture_boolean(context, obj, objects,
     objects_boolean = []
     collection = context.collection
     scene = context.scene
+    depsgraph = context.evaluated_depsgraph_get()
 
     if use_interior_hide and level == 0:
         # only set for level 0
@@ -339,9 +339,7 @@ def cell_fracture_boolean(context, obj, objects,
             if use_interior_hide:
                 obj_cell.data.polygons.foreach_set("hide", [True] * len(obj_cell.data.polygons))
 
-            mesh_new = obj_cell.to_mesh(scene,
-                                        apply_modifiers=True,
-                                        settings='PREVIEW')
+            mesh_new = obj_cell.evaluated_get(depsgraph).to_mesh()
             mesh_old = obj_cell.data
             obj_cell.data = mesh_new
             obj_cell.modifiers.remove(mod)
diff --git a/object_print3d_utils/mesh_helpers.py b/object_print3d_utils/mesh_helpers.py
index 56dbfc651..79e877742 100644
--- a/object_print3d_utils/mesh_helpers.py
+++ b/object_print3d_utils/mesh_helpers.py
@@ -32,7 +32,8 @@ def bmesh_copy_from_object(obj, transform=True, triangulate=True, apply_modifier
 
     if apply_modifiers and obj.modifiers:
         import bpy
-        me = obj.to_mesh(depsgraph=bpy.context.depsgraph, apply_modifiers=True)
+        depsgraph = bpy.context.evaluated_depsgraph_get()
+        me = obj.evaluated_get(depsgraph).to_mesh()
         bm = bmesh.new()
         bm.from_mesh(me)
         bpy.data.meshes.remove(me)
@@ -251,16 +252,15 @@ def object_merge(context, objects):
     layer.objects.active = obj_base
     obj_base.select_set(True)
 
+    depsgraph = context.evaluated_depsgraph_get()
+
     # loop over all meshes
     for obj in objects:
         if obj.type != 'MESH':
             continue
 
         # convert each to a mesh
-        mesh_new = obj.to_mesh(
-            depsgraph=context.depsgraph,
-            apply_modifiers=True,
-        )
+        mesh_new = obj.evaluated_get(depsgraph).to_mesh()
 
         # remove non-active uvs/vcols
         cd_remove_all_but_active(mesh_new.vertex_colors)
diff --git a/object_scatter/operator.py b/object_scatter/operator.py
index 30916ca58..eb5d4f9bf 100644
--- a/object_scatter/operator.py
+++ b/object_scatter/operator.py
@@ -460,7 +460,8 @@ def bvhtree_from_object(object):
     import bmesh
     bm = bmesh.new()
 
-    mesh = object.to_mesh(bpy.context.depsgraph, True)
+    depsgraph = context.evaluated_depsgraph_get()
+    mesh = object.evaluated_get(depsgraph).to_mesh()
     bm.from_mesh(mesh)
     bm.transform(object.matrix_world)
 
diff --git a/oscurart_tools/mesh/shapes_to_objects.py b/oscurart_tools/mesh/shapes_to_objects.py
index 3b9a80a18..c2af30ed5 100644
--- a/oscurart_tools/mesh/shapes_to_objects.py
+++ b/oscurart_tools/mesh/shapes_to_objects.py
@@ -44,11 +44,12 @@ class ShapeToObjects(Operator):
         OBJACT = bpy.context.view_layer.objects.active
         has_keys = hasattr(getattr(OBJACT.data, "shape_keys", None), "key_blocks")
         if has_keys:
+            depsgraph = bpy.context.evaluated_depsgraph_get()
             for SHAPE in OBJACT.data.shape_keys.key_blocks[:]:
                 print(SHAPE.name)
                 bpy.ops.object.shape_key_clear()
                 SHAPE.value = 1
-                mesh = OBJACT.to_mesh(bpy.context.depsgraph, True, calc_undeformed=False)
+                mesh = OBJACT.evaluated_get(depsgraph).to_mesh()
                 object = bpy.data.objects.new(SHAPE.name, mesh)
                 bpy.context.scene.collection.objects.link(object)
         else:
diff --git a/render_povray/render.py b/render_povray/render.py
index fb80f2a2c..02e05641a 100644
--- a/render_povray/render.py
+++ b/render_povray/render.py
@@ -2677,8 +2677,11 @@ def write_pov(filename, scene=None, info_callback=None):
                         tabWrite("\n//dummy sphere to represent Empty location\n")
                         tabWrite("#declare %s =sphere {<0, 0, 0>,0 pigment{rgbt 1} no_image no_reflection no_radiosity photons{pass_through collect off} hollow}\n" % povdataname)
 
+                    # TODO(sergey): PovRay is a render engine, so should be using dependency graph
+                    # which was given to it via render engine API.
+                    depsgraph = bpy.context.evaluated_depsgraph_get()
                     try:
-                        me = ob.to_mesh(bpy.context.depsgraph, True, 'RENDER')
+                        me = ob.evaluated_get(depsgraph).to_mesh()
 
                     #XXX Here? identify the specific exception for mesh object with no data
                     #XXX So that we can write something for the dataname !
-- 
GitLab