Skip to content

lib

comp_lock_and_undo_chunk(comp, undo_queue_name='Script CMD', keep_undo=True)

Lock comp and open an undo chunk during the context

Source code in client/ayon_fusion/api/lib.py
301
302
303
304
305
306
307
308
309
310
311
312
313
314
@contextlib.contextmanager
def comp_lock_and_undo_chunk(
    comp,
    undo_queue_name="Script CMD",
    keep_undo=True,
):
    """Lock comp and open an undo chunk during the context"""
    try:
        comp.Lock()
        comp.StartUndo(undo_queue_name)
        yield
    finally:
        comp.Unlock()
        comp.EndUndo(keep_undo)

get_bmd_library()

Get bmd library

Source code in client/ayon_fusion/api/lib.py
287
288
289
290
def get_bmd_library():
    """Get bmd library"""
    bmd = getattr(sys.modules["__main__"], "bmd", None)
    return bmd

get_current_comp()

Get current comp in this session

Source code in client/ayon_fusion/api/lib.py
293
294
295
296
297
298
def get_current_comp():
    """Get current comp in this session"""
    fusion = get_fusion_module()
    if fusion is not None:
        comp = fusion.CurrentComp
        return comp

get_frame_path(path)

Get filename for the Fusion Saver with padded number as '#'

get_frame_path("C:/test.exr") ('C:/test', 4, '.exr')

get_frame_path("filename.00.tif") ('filename.', 2, '.tif')

get_frame_path("foobar35.tif") ('foobar', 2, '.tif')

Parameters:

Name Type Description Default
path str

The path to render to.

required

Returns:

Name Type Description
tuple

head, padding, tail (extension)

Source code in client/ayon_fusion/api/lib.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
def get_frame_path(path):
    """Get filename for the Fusion Saver with padded number as '#'

    >>> get_frame_path("C:/test.exr")
    ('C:/test', 4, '.exr')

    >>> get_frame_path("filename.00.tif")
    ('filename.', 2, '.tif')

    >>> get_frame_path("foobar35.tif")
    ('foobar', 2, '.tif')

    Args:
        path (str): The path to render to.

    Returns:
        tuple: head, padding, tail (extension)

    """
    filename, ext = os.path.splitext(path)

    # Find a final number group
    match = re.match('.*?([0-9]+)$', filename)
    if match:
        padding = len(match.group(1))
        # remove number from end since fusion
        # will swap it with the frame number
        filename = filename[:-padding]
    else:
        padding = 4  # default Fusion padding

    return filename, padding, ext

get_fusion_module()

Get current Fusion instance

Source code in client/ayon_fusion/api/lib.py
281
282
283
284
def get_fusion_module():
    """Get current Fusion instance"""
    fusion = getattr(sys.modules["__main__"], "fusion", None)
    return fusion

get_tool_resolution(tool, frame)

Return the 2D input resolution to a Fusion tool

If the current tool hasn't been rendered its input resolution hasn't been saved. To combat this, add an expression in the comments field to read the resolution

Args tool (Fusion Tool): The tool to query input resolution frame (int): The frame to query the resolution on.

Returns:

Name Type Description
tuple

width, height as 2-tuple of integers

Raises:

Type Description
ValueError

Unable to retrieve comp resolution.

Source code in client/ayon_fusion/api/lib.py
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
def get_tool_resolution(tool, frame):
    """Return the 2D input resolution to a Fusion tool

    If the current tool hasn't been rendered its input resolution
    hasn't been saved. To combat this, add an expression in
    the comments field to read the resolution

    Args
        tool (Fusion Tool): The tool to query input resolution
        frame (int): The frame to query the resolution on.

    Returns:
        tuple: width, height as 2-tuple of integers

    Raises:
        ValueError: Unable to retrieve comp resolution.

    """
    comp = tool.Composition
    attribute = tool["Comments"]

    # False undo removes the undo-stack from the undo list
    with comp_lock_and_undo_chunk(comp, "Read resolution", False):

        # Get width
        with temp_expression(attribute, frame, "self.Input.OriginalWidth"):
            value = attribute[frame]
            if value is None:
                raise ValueError("Failed to read input width")
            width = int(value)

        # Get height
        with temp_expression(attribute, frame, "self.Input.OriginalHeight"):
            value = attribute[frame]
            if value is None:
                raise ValueError("Failed to read input height")
            height = int(value)

        return width, height

maintained_comp_range(comp=None, global_start=True, global_end=True, render_start=True, render_end=True)

Reset comp frame ranges from before the context after the context

Source code in client/ayon_fusion/api/lib.py
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
@contextlib.contextmanager
def maintained_comp_range(comp=None,
                          global_start=True,
                          global_end=True,
                          render_start=True,
                          render_end=True):
    """Reset comp frame ranges from before the context after the context"""
    if comp is None:
        comp = get_current_comp()

    comp_attrs = comp.GetAttrs()
    preserve_attrs = {}
    if global_start:
        preserve_attrs["COMPN_GlobalStart"] = comp_attrs["COMPN_GlobalStart"]
    if global_end:
        preserve_attrs["COMPN_GlobalEnd"] = comp_attrs["COMPN_GlobalEnd"]
    if render_start:
        preserve_attrs["COMPN_RenderStart"] = comp_attrs["COMPN_RenderStart"]
    if render_end:
        preserve_attrs["COMPN_RenderEnd"] = comp_attrs["COMPN_RenderEnd"]

    try:
        yield
    finally:
        comp.SetAttrs(preserve_attrs)

maintained_selection(comp=None)

Reset comp selection from before the context after the context

Source code in client/ayon_fusion/api/lib.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
@contextlib.contextmanager
def maintained_selection(comp=None):
    """Reset comp selection from before the context after the context"""
    if comp is None:
        comp = get_current_comp()

    previous_selection = comp.GetToolList(True).values()
    try:
        yield
    finally:
        flow = comp.CurrentFrame.FlowView
        flow.Select()  # No args equals clearing selection
        if previous_selection:
            for tool in previous_selection:
                flow.Select(tool, True)

prompt_reset_context()

Prompt the user what context settings to reset. This prompt is used on saving to a different task to allow the scene to get matched to the new context.

Source code in client/ayon_fusion/api/lib.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
def prompt_reset_context():
    """Prompt the user what context settings to reset.
    This prompt is used on saving to a different task to allow the scene to
    get matched to the new context.
    """
    # TODO: Cleanup this prototyped mess of imports and odd dialog
    from ayon_core.tools.attribute_defs.dialog import (
        AttributeDefinitionsDialog
    )
    from qtpy import QtCore

    definitions = [
        UILabelDef(
            label=(
                "You are saving your workfile into a different folder or task."
                "\n\n"
                "Would you like to update some settings to the new context?\n"
            )
        ),
        BoolDef(
            "fps", 
            label="FPS", 
            tooltip="Reset Comp FPS",
            default=True
        ),
        BoolDef(
            "frame_range", 
            label="Frame Range",
            tooltip="Reset Comp start and end frame ranges",
            default=True
        ),
        BoolDef(
            "resolution", 
            label="Comp Resolution", 
            tooltip="Reset Comp resolution",
            default=True
        ),
        BoolDef(
            "instances", 
            label="Publish instances", 
            tooltip="Update all publish instance's folder and task to match "
                    "the new folder and task", 
            default=True
        ),
    ]

    dialog = AttributeDefinitionsDialog(definitions)
    dialog.setWindowFlags(
        dialog.windowFlags() | QtCore.Qt.WindowStaysOnTopHint
    )
    dialog.setWindowTitle("Saving to different context.")
    dialog.setStyleSheet(load_stylesheet())
    if not dialog.exec_():
        return None

    options = dialog.get_values()
    task_entity = get_current_task_entity()
    if options["frame_range"]:
        set_current_context_framerange(task_entity)

    if options["fps"]:
        set_current_context_fps(task_entity)

    if options["resolution"]:
        set_current_context_resolution(task_entity)

    if options["instances"]:
        update_content_on_context_change()

    dialog.deleteLater()

set_current_context_fps(task_entity=None)

Set Comp's frame rate (FPS) to based on current task

Source code in client/ayon_fusion/api/lib.py
79
80
81
82
83
84
85
86
87
88
def set_current_context_fps(task_entity=None):
    """Set Comp's frame rate (FPS) to based on current task"""
    if task_entity is None:
        task_entity = get_current_task_entity(fields={"attrib.fps"})

    fps = float(task_entity["attrib"].get("fps", 24.0))
    comp = get_current_comp()
    comp.SetPrefs({
        "Comp.FrameFormat.Rate": fps,
    })

set_current_context_framerange(task_entity=None)

Set Comp's frame range based on current task.

Source code in client/ayon_fusion/api/lib.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def set_current_context_framerange(task_entity=None):
    """Set Comp's frame range based on current task."""
    if task_entity is None:
        task_entity = get_current_task_entity(
            fields={"attrib.frameStart",
                    "attrib.frameEnd",
                    "attrib.handleStart",
                    "attrib.handleEnd"})

    task_attributes = task_entity["attrib"]
    start = task_attributes["frameStart"]
    end = task_attributes["frameEnd"]
    handle_start = task_attributes["handleStart"]
    handle_end = task_attributes["handleEnd"]
    update_frame_range(start, end, set_render_range=True,
                       handle_start=handle_start,
                       handle_end=handle_end)

set_current_context_resolution(task_entity=None)

Set Comp's resolution width x height default based on current task

Source code in client/ayon_fusion/api/lib.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def set_current_context_resolution(task_entity=None):
    """Set Comp's resolution width x height default based on current task"""
    if task_entity is None:
        task_entity = get_current_task_entity(
            fields={"attrib.resolutionWidth", "attrib.resolutionHeight"})

    task_attributes = task_entity["attrib"]
    width = task_attributes["resolutionWidth"]
    height = task_attributes["resolutionHeight"]
    comp = get_current_comp()

    print("Setting comp frame format resolution to {}x{}".format(width,
                                                                 height))
    comp.SetPrefs({
        "Comp.FrameFormat.Width": width,
        "Comp.FrameFormat.Height": height,
    })

temp_expression(attribute, frame, expression)

Temporarily set an expression on an attribute during context

Source code in client/ayon_fusion/api/lib.py
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
@contextlib.contextmanager
def temp_expression(attribute, frame, expression):
    """Temporarily set an expression on an attribute during context"""
    # Save old comment
    old_comment = ""
    has_expression = False

    if attribute[frame] not in ["", None]:
        if attribute.GetExpression() is not None:
            has_expression = True
            old_comment = attribute.GetExpression()
            attribute.SetExpression(None)
        else:
            old_comment = attribute[frame]
            attribute[frame] = ""

    try:
        attribute.SetExpression(expression)
        yield
    finally:
        # Reset old comment
        attribute.SetExpression(None)
        if has_expression:
            attribute.SetExpression(old_comment)
        else:
            attribute[frame] = old_comment

update_content_on_context_change()

Update all Creator instances to current asset

Source code in client/ayon_fusion/api/lib.py
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
def update_content_on_context_change():
    """Update all Creator instances to current asset"""
    host = registered_host()
    context = host.get_current_context()

    folder_path = context["folder_path"]
    task = context["task_name"]

    create_context = CreateContext(host, reset=True)

    for instance in create_context.instances:
        instance_folder_path = instance.get("folderPath")
        if instance_folder_path and instance_folder_path != folder_path:
            instance["folderPath"] = folder_path
        instance_task = instance.get("task")
        if instance_task and instance_task != task:
            instance["task"] = task

    create_context.save_changes()

update_frame_range(start, end, comp=None, set_render_range=True, handle_start=0, handle_end=0)

Set Fusion comp's start and end frame range

Parameters:

Name Type Description Default
start (float, int)

start frame

required
end (float, int)

end frame

required
comp (object, Optional)

comp object from fusion

None
set_render_range (bool, Optional)

When True this will also set the composition's render start and end frame.

True
handle_start (float, int, Optional)

frame handles before start frame

0
handle_end (float, int, Optional)

frame handles after end frame

0

Returns:

Type Description

None

Source code in client/ayon_fusion/api/lib.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def update_frame_range(start, end, comp=None, set_render_range=True,
                       handle_start=0, handle_end=0):
    """Set Fusion comp's start and end frame range

    Args:
        start (float, int): start frame
        end (float, int): end frame
        comp (object, Optional): comp object from fusion
        set_render_range (bool, Optional): When True this will also set the
            composition's render start and end frame.
        handle_start (float, int, Optional): frame handles before start frame
        handle_end (float, int, Optional): frame handles after end frame

    Returns:
        None

    """

    if not comp:
        comp = get_current_comp()

    # Convert any potential none type to zero
    handle_start = handle_start or 0
    handle_end = handle_end or 0

    attrs = {
        "COMPN_GlobalStart": start - handle_start,
        "COMPN_GlobalEnd": end + handle_end
    }

    # set frame range
    if set_render_range:
        attrs.update({
            "COMPN_RenderStart": start,
            "COMPN_RenderEnd": end
        })

    with comp_lock_and_undo_chunk(comp):
        comp.SetAttrs(attrs)

validate_comp_prefs(comp=None, force_repair=False)

Validate current comp defaults with task settings.

Validates fps, resolutionWidth, resolutionHeight, aspectRatio.

This does not validate frameStart, frameEnd, handleStart and handleEnd.

Source code in client/ayon_fusion/api/lib.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
def validate_comp_prefs(comp=None, force_repair=False):
    """Validate current comp defaults with task settings.

    Validates fps, resolutionWidth, resolutionHeight, aspectRatio.

    This does *not* validate frameStart, frameEnd, handleStart and handleEnd.
    """

    if comp is None:
        comp = get_current_comp()

    log = Logger.get_logger("validate_comp_prefs")

    fields = {
        "name",
        "attrib.fps",
        "attrib.resolutionWidth",
        "attrib.resolutionHeight",
        "attrib.pixelAspect",
    }
    task_entity = get_current_task_entity(fields=fields)
    folder_path = get_current_folder_path()
    context_path = "{} > {}".format(folder_path, task_entity["name"])

    task_attributes = task_entity["attrib"]

    comp_frame_format_prefs = comp.GetPrefs("Comp.FrameFormat")

    # Pixel aspect ratio in Fusion is set as AspectX and AspectY so we convert
    # the data to something that is more sensible to Fusion
    task_attributes["pixelAspectX"] = task_attributes.pop("pixelAspect")
    task_attributes["pixelAspectY"] = 1.0

    validations = [
        ("fps", "Rate", "FPS"),
        ("resolutionWidth", "Width", "Resolution Width"),
        ("resolutionHeight", "Height", "Resolution Height"),
        ("pixelAspectX", "AspectX", "Pixel Aspect Ratio X"),
        ("pixelAspectY", "AspectY", "Pixel Aspect Ratio Y")
    ]

    invalid = []
    for key, comp_key, label in validations:
        task_value = task_attributes[key]
        comp_value = comp_frame_format_prefs.get(comp_key)
        if task_value != comp_value:
            invalid_msg = "{} {} should be {}".format(label,
                                                      comp_value,
                                                      task_value)
            invalid.append(invalid_msg)

            if not force_repair:
                # Do not log warning if we force repair anyway
                log.warning(
                    "Comp {pref} {value} does not match "
                    "{context_path} {pref} {task_value}".format(
                        pref=label,
                        value=comp_value,
                        context_path=context_path,
                        task_value=task_value)
                )

    if invalid:

        def _on_repair():
            attributes = dict()
            for key, comp_key, _label in validations:
                value = task_attributes[key]
                comp_key_full = "Comp.FrameFormat.{}".format(comp_key)
                attributes[comp_key_full] = value
            comp.SetPrefs(attributes)

        if force_repair:
            log.info("Applying default Comp preferences..")
            _on_repair()
            return

        from . import menu
        from ayon_core.tools.utils import SimplePopup
        dialog = SimplePopup(parent=menu.menu)
        dialog.setWindowTitle("Fusion comp has invalid configuration")

        msg = "Comp preferences mismatches '{}'".format(context_path)
        msg += "\n" + "\n".join(invalid)
        dialog.set_message(msg)
        dialog.set_button_text("Repair")
        dialog.on_clicked.connect(_on_repair)
        dialog.show()
        dialog.raise_()
        dialog.activateWindow()
        dialog.setStyleSheet(load_stylesheet())