diff --git a/.gitignore b/.gitignore index acbc3e2572..41389755f1 100644 --- a/.gitignore +++ b/.gitignore @@ -34,7 +34,6 @@ Temporary Items # Package dirs ########### -/server_addon/packages/* /package/* /.venv diff --git a/client/ayon_core/addon/README.md b/client/ayon_core/addon/README.md index e1c04ea0d6..ded2d50e9c 100644 --- a/client/ayon_core/addon/README.md +++ b/client/ayon_core/addon/README.md @@ -86,7 +86,3 @@ AYON addons should contain separated logic of specific kind of implementation, s "inventory": [] } ``` - -### TrayAddonsManager -- inherits from `AddonsManager` -- has specific implementation for AYON Tray and handle `ITrayAddon` methods diff --git a/client/ayon_core/addon/__init__.py b/client/ayon_core/addon/__init__.py index fe8865c730..c7eccd7b6c 100644 --- a/client/ayon_core/addon/__init__.py +++ b/client/ayon_core/addon/__init__.py @@ -11,7 +11,6 @@ from .interfaces import ( from .base import ( AYONAddon, AddonsManager, - TrayAddonsManager, load_addons, ) @@ -27,6 +26,5 @@ __all__ = ( "AYONAddon", "AddonsManager", - "TrayAddonsManager", "load_addons", ) diff --git a/client/ayon_core/addon/base.py b/client/ayon_core/addon/base.py index b9ecff4233..0ffad2045e 100644 --- a/client/ayon_core/addon/base.py +++ b/client/ayon_core/addon/base.py @@ -9,9 +9,8 @@ import logging import threading import collections from uuid import uuid4 -from abc import ABCMeta, abstractmethod +from abc import ABC, abstractmethod -import six import appdirs import ayon_api from semver import VersionInfo @@ -23,8 +22,6 @@ from ayon_core.settings import get_studio_settings from .interfaces import ( IPluginPaths, IHostAddon, - ITrayAddon, - ITrayService ) # Files that will be always ignored on addons import @@ -499,8 +496,7 @@ def is_func_marked(func): return getattr(func, _MARKING_ATTR, False) -@six.add_metaclass(ABCMeta) -class AYONAddon(object): +class AYONAddon(ABC): """Base class of AYON addon. Attributes: @@ -925,20 +921,20 @@ class AddonsManager: report = {} time_start = time.time() prev_start_time = time_start - enabled_modules = self.get_enabled_addons() - self.log.debug("Has {} enabled modules.".format(len(enabled_modules))) - for module in enabled_modules: + enabled_addons = self.get_enabled_addons() + self.log.debug("Has {} enabled addons.".format(len(enabled_addons))) + for addon in enabled_addons: try: - if not is_func_marked(module.connect_with_addons): - module.connect_with_addons(enabled_modules) + if not is_func_marked(addon.connect_with_addons): + addon.connect_with_addons(enabled_addons) - elif hasattr(module, "connect_with_modules"): + elif hasattr(addon, "connect_with_modules"): self.log.warning(( "DEPRECATION WARNING: Addon '{}' still uses" " 'connect_with_modules' method. Please switch to use" " 'connect_with_addons' method." - ).format(module.name)) - module.connect_with_modules(enabled_modules) + ).format(addon.name)) + addon.connect_with_modules(enabled_addons) except Exception: self.log.error( @@ -947,7 +943,7 @@ class AddonsManager: ) now = time.time() - report[module.__class__.__name__] = now - prev_start_time + report[addon.__class__.__name__] = now - prev_start_time prev_start_time = now if self._report is not None: @@ -1340,185 +1336,3 @@ class AddonsManager: " 'get_host_module' please use 'get_host_addon' instead." ) return self.get_host_addon(host_name) - - -class TrayAddonsManager(AddonsManager): - # Define order of addons in menu - # TODO find better way how to define order - addons_menu_order = ( - "user", - "ftrack", - "kitsu", - "launcher_tool", - "avalon", - "clockify", - "traypublish_tool", - "log_viewer", - ) - - def __init__(self, settings=None): - super(TrayAddonsManager, self).__init__(settings, initialize=False) - - self.tray_manager = None - - self.doubleclick_callbacks = {} - self.doubleclick_callback = None - - def add_doubleclick_callback(self, addon, callback): - """Register double-click callbacks on tray icon. - - Currently, there is no way how to determine which is launched. Name of - callback can be defined with `doubleclick_callback` attribute. - - Missing feature how to define default callback. - - Args: - addon (AYONAddon): Addon object. - callback (FunctionType): Function callback. - """ - - callback_name = "_".join([addon.name, callback.__name__]) - if callback_name not in self.doubleclick_callbacks: - self.doubleclick_callbacks[callback_name] = callback - if self.doubleclick_callback is None: - self.doubleclick_callback = callback_name - return - - self.log.warning(( - "Callback with name \"{}\" is already registered." - ).format(callback_name)) - - def initialize(self, tray_manager, tray_menu): - self.tray_manager = tray_manager - self.initialize_addons() - self.tray_init() - self.connect_addons() - self.tray_menu(tray_menu) - - def get_enabled_tray_addons(self): - """Enabled tray addons. - - Returns: - list[AYONAddon]: Enabled addons that inherit from tray interface. - """ - - return [ - addon - for addon in self.get_enabled_addons() - if isinstance(addon, ITrayAddon) - ] - - def restart_tray(self): - if self.tray_manager: - self.tray_manager.restart() - - def tray_init(self): - report = {} - time_start = time.time() - prev_start_time = time_start - for addon in self.get_enabled_tray_addons(): - try: - addon._tray_manager = self.tray_manager - addon.tray_init() - addon.tray_initialized = True - except Exception: - self.log.warning( - "Addon \"{}\" crashed on `tray_init`.".format( - addon.name - ), - exc_info=True - ) - - now = time.time() - report[addon.__class__.__name__] = now - prev_start_time - prev_start_time = now - - if self._report is not None: - report[self._report_total_key] = time.time() - time_start - self._report["Tray init"] = report - - def tray_menu(self, tray_menu): - ordered_addons = [] - enabled_by_name = { - addon.name: addon - for addon in self.get_enabled_tray_addons() - } - - for name in self.addons_menu_order: - addon_by_name = enabled_by_name.pop(name, None) - if addon_by_name: - ordered_addons.append(addon_by_name) - ordered_addons.extend(enabled_by_name.values()) - - report = {} - time_start = time.time() - prev_start_time = time_start - for addon in ordered_addons: - if not addon.tray_initialized: - continue - - try: - addon.tray_menu(tray_menu) - except Exception: - # Unset initialized mark - addon.tray_initialized = False - self.log.warning( - "Addon \"{}\" crashed on `tray_menu`.".format( - addon.name - ), - exc_info=True - ) - now = time.time() - report[addon.__class__.__name__] = now - prev_start_time - prev_start_time = now - - if self._report is not None: - report[self._report_total_key] = time.time() - time_start - self._report["Tray menu"] = report - - def start_addons(self): - report = {} - time_start = time.time() - prev_start_time = time_start - for addon in self.get_enabled_tray_addons(): - if not addon.tray_initialized: - if isinstance(addon, ITrayService): - addon.set_service_failed_icon() - continue - - try: - addon.tray_start() - except Exception: - self.log.warning( - "Addon \"{}\" crashed on `tray_start`.".format( - addon.name - ), - exc_info=True - ) - now = time.time() - report[addon.__class__.__name__] = now - prev_start_time - prev_start_time = now - - if self._report is not None: - report[self._report_total_key] = time.time() - time_start - self._report["Addons start"] = report - - def on_exit(self): - for addon in self.get_enabled_tray_addons(): - if addon.tray_initialized: - try: - addon.tray_exit() - except Exception: - self.log.warning( - "Addon \"{}\" crashed on `tray_exit`.".format( - addon.name - ), - exc_info=True - ) - - # DEPRECATED - def get_enabled_tray_modules(self): - return self.get_enabled_tray_addons() - - def start_modules(self): - self.start_addons() diff --git a/client/ayon_core/addon/interfaces.py b/client/ayon_core/addon/interfaces.py index 86e0c6e060..b273e7839b 100644 --- a/client/ayon_core/addon/interfaces.py +++ b/client/ayon_core/addon/interfaces.py @@ -1,7 +1,5 @@ from abc import ABCMeta, abstractmethod -import six - from ayon_core import resources @@ -15,8 +13,7 @@ class _AYONInterfaceMeta(ABCMeta): return str(self) -@six.add_metaclass(_AYONInterfaceMeta) -class AYONInterface: +class AYONInterface(metaclass=_AYONInterfaceMeta): """Base class of Interface that can be used as Mixin with abstract parts. This is way how AYON addon can define that contains specific predefined diff --git a/client/ayon_core/cli.py b/client/ayon_core/cli.py index 60cf5624b0..0a9bb2aa9c 100644 --- a/client/ayon_core/cli.py +++ b/client/ayon_core/cli.py @@ -12,7 +12,11 @@ import acre from ayon_core import AYON_CORE_ROOT from ayon_core.addon import AddonsManager from ayon_core.settings import get_general_environments -from ayon_core.lib import initialize_ayon_connection, is_running_from_build +from ayon_core.lib import ( + initialize_ayon_connection, + is_running_from_build, + Logger, +) from .cli_commands import Commands @@ -39,7 +43,8 @@ class AliasedGroup(click.Group): help="Enable debug") @click.option("--verbose", expose_value=False, help=("Change AYON log level (debug - critical or 0-50)")) -def main_cli(ctx): +@click.option("--force", is_flag=True, hidden=True) +def main_cli(ctx, force): """AYON is main command serving as entry point to pipeline system. It wraps different commands together. @@ -51,20 +56,26 @@ def main_cli(ctx): print(ctx.get_help()) sys.exit(0) else: - ctx.invoke(tray) + ctx.forward(tray) @main_cli.command() -def tray(): +@click.option( + "--force", + is_flag=True, + help="Force to start tray and close any existing one.") +def tray(force): """Launch AYON tray. Default action of AYON command is to launch tray widget to control basic aspects of AYON. See documentation for more information. """ - Commands.launch_tray() + + from ayon_core.tools.tray import main + + main(force) -@Commands.add_addons @main_cli.group(help="Run command line arguments of AYON addons") @click.pass_context def addon(ctx): @@ -80,6 +91,7 @@ main_cli.set_alias("addon", "module") @main_cli.command() +@click.pass_context @click.argument("output_json_path") @click.option("--project", help="Project name", default=None) @click.option("--asset", help="Folder path", default=None) @@ -88,7 +100,9 @@ main_cli.set_alias("addon", "module") @click.option( "--envgroup", help="Environment group (e.g. \"farm\")", default=None ) -def extractenvironments(output_json_path, project, asset, task, app, envgroup): +def extractenvironments( + ctx, output_json_path, project, asset, task, app, envgroup +): """Extract environment variables for entered context to a json file. Entered output filepath will be created if does not exists. @@ -103,23 +117,30 @@ def extractenvironments(output_json_path, project, asset, task, app, envgroup): 'addon applications extractenvironments ...' instead. """ Commands.extractenvironments( - output_json_path, project, asset, task, app, envgroup + output_json_path, + project, + asset, + task, + app, + envgroup, + ctx.obj["addons_manager"] ) @main_cli.command() +@click.pass_context @click.argument("path", required=True) @click.option("-t", "--targets", help="Targets", default=None, multiple=True) @click.option("-g", "--gui", is_flag=True, help="Show Publish UI", default=False) -def publish(path, targets, gui): +def publish(ctx, path, targets, gui): """Start CLI publishing. Publish collects json from path provided as an argument. -S + """ - Commands.publish(path, targets, gui) + Commands.publish(path, targets, gui, ctx.obj["addons_manager"]) @main_cli.command(context_settings={"ignore_unknown_options": True}) @@ -245,11 +266,9 @@ def _set_global_environments() -> None: os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1" -def _set_addons_environments(): +def _set_addons_environments(addons_manager): """Set global environments for AYON addons.""" - addons_manager = AddonsManager() - # Merge environments with current environments and update values if module_envs := addons_manager.collect_global_environments(): parsed_envs = acre.parse(module_envs) @@ -258,6 +277,21 @@ def _set_addons_environments(): os.environ.update(env) +def _add_addons(addons_manager): + """Modules/Addons can add their cli commands dynamically.""" + log = Logger.get_logger("CLI-AddAddons") + for addon_obj in addons_manager.addons: + try: + addon_obj.cli(addon) + + except Exception: + log.warning( + "Failed to add cli command for module \"{}\"".format( + addon_obj.name + ), exc_info=True + ) + + def main(*args, **kwargs): initialize_ayon_connection() python_path = os.getenv("PYTHONPATH", "") @@ -281,10 +315,14 @@ def main(*args, **kwargs): print(" - global AYON ...") _set_global_environments() print(" - for addons ...") - _set_addons_environments() - + addons_manager = AddonsManager() + _set_addons_environments(addons_manager) + _add_addons(addons_manager) try: - main_cli(obj={}, prog_name="ayon") + main_cli( + prog_name="ayon", + obj={"addons_manager": addons_manager}, + ) except Exception: # noqa exc_info = sys.exc_info() print("!!! AYON crashed:") diff --git a/client/ayon_core/cli_commands.py b/client/ayon_core/cli_commands.py index 35b7e294de..8ae1ebb3ba 100644 --- a/client/ayon_core/cli_commands.py +++ b/client/ayon_core/cli_commands.py @@ -3,6 +3,9 @@ import os import sys import warnings +from typing import Optional, List + +from ayon_core.addon import AddonsManager class Commands: @@ -11,45 +14,21 @@ class Commands: Most of its methods are called by :mod:`cli` module. """ @staticmethod - def launch_tray(): - from ayon_core.lib import Logger - from ayon_core.tools import tray - - Logger.set_process_name("Tray") - - tray.main() - - @staticmethod - def add_addons(click_func): - """Modules/Addons can add their cli commands dynamically.""" - - from ayon_core.lib import Logger - from ayon_core.addon import AddonsManager - - manager = AddonsManager() - log = Logger.get_logger("CLI-AddModules") - for addon in manager.addons: - try: - addon.cli(click_func) - - except Exception: - log.warning( - "Failed to add cli command for module \"{}\"".format( - addon.name - ), exc_info=True - ) - return click_func - - @staticmethod - def publish(path: str, targets: list=None, gui:bool=False) -> None: + def publish( + path: str, + targets: Optional[List[str]] = None, + gui: Optional[bool] = False, + addons_manager: Optional[AddonsManager] = None, + ) -> None: """Start headless publishing. Publish use json from passed path argument. Args: path (str): Path to JSON. - targets (list of str): List of pyblish targets. - gui (bool): Show publish UI. + targets (Optional[List[str]]): List of pyblish targets. + gui (Optional[bool]): Show publish UI. + addons_manager (Optional[AddonsManager]): Addons manager instance. Raises: RuntimeError: When there is no path to process. @@ -102,14 +81,15 @@ class Commands: install_ayon_plugins() - manager = AddonsManager() + if addons_manager is None: + addons_manager = AddonsManager() - publish_paths = manager.collect_plugin_paths()["publish"] + publish_paths = addons_manager.collect_plugin_paths()["publish"] for plugin_path in publish_paths: pyblish.api.register_plugin_path(plugin_path) - applications_addon = manager.get_enabled_addon("applications") + applications_addon = addons_manager.get_enabled_addon("applications") if applications_addon is not None: context = get_global_context() env = applications_addon.get_farm_publish_environment_variables( @@ -158,15 +138,12 @@ class Commands: @staticmethod def extractenvironments( - output_json_path, project, asset, task, app, env_group + output_json_path, project, asset, task, app, env_group, addons_manager ): """Produces json file with environment based on project and app. Called by Deadline plugin to propagate environment into render jobs. """ - - from ayon_core.addon import AddonsManager - warnings.warn( ( "Command 'extractenvironments' is deprecated and will be" @@ -176,7 +153,6 @@ class Commands: DeprecationWarning ) - addons_manager = AddonsManager() applications_addon = addons_manager.get_enabled_addon("applications") if applications_addon is None: raise RuntimeError( diff --git a/client/ayon_core/host/dirmap.py b/client/ayon_core/host/dirmap.py index 8766e7485d..19841845e7 100644 --- a/client/ayon_core/host/dirmap.py +++ b/client/ayon_core/host/dirmap.py @@ -7,18 +7,15 @@ exists is used. """ import os -from abc import ABCMeta, abstractmethod +from abc import ABC, abstractmethod import platform -import six - from ayon_core.lib import Logger from ayon_core.addon import AddonsManager from ayon_core.settings import get_project_settings -@six.add_metaclass(ABCMeta) -class HostDirmap(object): +class HostDirmap(ABC): """Abstract class for running dirmap on a workfile in a host. Dirmap is used to translate paths inside of host workfile from one @@ -181,25 +178,23 @@ class HostDirmap(object): cached=False) # overrides for roots set in `Site Settings` - active_roots = sitesync_addon.get_site_root_overrides( - project_name, active_site) - remote_roots = sitesync_addon.get_site_root_overrides( - project_name, remote_site) + active_roots_overrides = self._get_site_root_overrides( + sitesync_addon, project_name, active_site) - self.log.debug("active roots overrides {}".format(active_roots)) - self.log.debug("remote roots overrides {}".format(remote_roots)) + remote_roots_overrides = self._get_site_root_overrides( + sitesync_addon, project_name, remote_site) current_platform = platform.system().lower() remote_provider = sitesync_addon.get_provider_for_site( project_name, remote_site ) # dirmap has sense only with regular disk provider, in the workfile - # won't be root on cloud or sftp provider + # won't be root on cloud or sftp provider so fallback to studio if remote_provider != "local_drive": remote_site = "studio" - for root_name, active_site_dir in active_roots.items(): + for root_name, active_site_dir in active_roots_overrides.items(): remote_site_dir = ( - remote_roots.get(root_name) + remote_roots_overrides.get(root_name) or sync_settings["sites"][remote_site]["root"][root_name] ) @@ -220,3 +215,22 @@ class HostDirmap(object): self.log.debug("local sync mapping:: {}".format(mapping)) return mapping + + def _get_site_root_overrides( + self, sitesync_addon, project_name, site_name + ): + """Safely handle root overrides. + + SiteSync raises ValueError for non local or studio sites. + """ + # TODO: could be removed when `get_site_root_overrides` is not raising + # an Error but just returns {} + try: + site_roots_overrides = sitesync_addon.get_site_root_overrides( + project_name, site_name) + except ValueError: + site_roots_overrides = {} + self.log.debug("{} roots overrides {}".format( + site_name, site_roots_overrides)) + + return site_roots_overrides diff --git a/client/ayon_core/host/host.py b/client/ayon_core/host/host.py index 081aafdbe3..5a29de6cd7 100644 --- a/client/ayon_core/host/host.py +++ b/client/ayon_core/host/host.py @@ -1,15 +1,13 @@ import os import logging import contextlib -from abc import ABCMeta, abstractproperty -import six +from abc import ABC, abstractproperty # NOTE can't import 'typing' because of issues in Maya 2020 # - shiboken crashes on 'typing' module import -@six.add_metaclass(ABCMeta) -class HostBase(object): +class HostBase(ABC): """Base of host implementation class. Host is pipeline implementation of DCC application. This class should help diff --git a/client/ayon_core/host/interfaces.py b/client/ayon_core/host/interfaces.py index 7157ad6f7e..c077dfeae9 100644 --- a/client/ayon_core/host/interfaces.py +++ b/client/ayon_core/host/interfaces.py @@ -1,5 +1,4 @@ -from abc import ABCMeta, abstractmethod -import six +from abc import ABC, abstractmethod class MissingMethodsError(ValueError): @@ -106,8 +105,7 @@ class ILoadHost: return self.get_containers() -@six.add_metaclass(ABCMeta) -class IWorkfileHost: +class IWorkfileHost(ABC): """Implementation requirements to be able use workfile utils and tool.""" @staticmethod diff --git a/client/ayon_core/lib/attribute_definitions.py b/client/ayon_core/lib/attribute_definitions.py index 0a9d38ab65..360d47ea17 100644 --- a/client/ayon_core/lib/attribute_definitions.py +++ b/client/ayon_core/lib/attribute_definitions.py @@ -6,7 +6,6 @@ import json import copy from abc import ABCMeta, abstractmethod, abstractproperty -import six import clique # Global variable which store attribute definitions by type @@ -91,8 +90,7 @@ class AbstractAttrDefMeta(ABCMeta): return obj -@six.add_metaclass(AbstractAttrDefMeta) -class AbstractAttrDef(object): +class AbstractAttrDef(metaclass=AbstractAttrDefMeta): """Abstraction of attribute definition. Each attribute definition must have implemented validation and @@ -349,7 +347,7 @@ class NumberDef(AbstractAttrDef): ) def convert_value(self, value): - if isinstance(value, six.string_types): + if isinstance(value, str): try: value = float(value) except Exception: @@ -396,12 +394,12 @@ class TextDef(AbstractAttrDef): if multiline is None: multiline = False - elif not isinstance(default, six.string_types): + elif not isinstance(default, str): raise TypeError(( - "'default' argument must be a {}, not '{}'" - ).format(six.string_types, type(default))) + f"'default' argument must be a str, not '{type(default)}'" + )) - if isinstance(regex, six.string_types): + if isinstance(regex, str): regex = re.compile(regex) self.multiline = multiline @@ -418,7 +416,7 @@ class TextDef(AbstractAttrDef): ) def convert_value(self, value): - if isinstance(value, six.string_types): + if isinstance(value, str): return value return self.default @@ -736,7 +734,7 @@ class FileDefItem(object): else: output.append(item) - elif isinstance(item, six.string_types): + elif isinstance(item, str): str_filepaths.append(item) else: raise TypeError( @@ -844,7 +842,7 @@ class FileDef(AbstractAttrDef): if isinstance(default, dict): FileDefItem.from_dict(default) - elif isinstance(default, six.string_types): + elif isinstance(default, str): default = FileDefItem.from_paths([default.strip()])[0] else: @@ -883,14 +881,14 @@ class FileDef(AbstractAttrDef): ) def convert_value(self, value): - if isinstance(value, six.string_types) or isinstance(value, dict): + if isinstance(value, (str, dict)): value = [value] if isinstance(value, (tuple, list, set)): string_paths = [] dict_items = [] for item in value: - if isinstance(item, six.string_types): + if isinstance(item, str): string_paths.append(item.strip()) elif isinstance(item, dict): try: diff --git a/client/ayon_core/lib/file_transaction.py b/client/ayon_core/lib/file_transaction.py index 81a3b386f6..47b10dd994 100644 --- a/client/ayon_core/lib/file_transaction.py +++ b/client/ayon_core/lib/file_transaction.py @@ -2,7 +2,6 @@ import os import logging import sys import errno -import six from ayon_core.lib import create_hard_link @@ -158,11 +157,13 @@ class FileTransaction(object): def rollback(self): errors = 0 + last_exc = None # Rollback any transferred files for path in self._transferred: try: os.remove(path) - except OSError: + except OSError as exc: + last_exc = exc errors += 1 self.log.error( "Failed to rollback created file: {}".format(path), @@ -172,7 +173,8 @@ class FileTransaction(object): for backup, original in self._backup_to_original.items(): try: os.rename(backup, original) - except OSError: + except OSError as exc: + last_exc = exc errors += 1 self.log.error( "Failed to restore original file: {} -> {}".format( @@ -183,7 +185,7 @@ class FileTransaction(object): self.log.error( "{} errors occurred during rollback.".format(errors), exc_info=True) - six.reraise(*sys.exc_info()) + raise last_exc @property def transferred(self): @@ -200,11 +202,9 @@ class FileTransaction(object): try: os.makedirs(dirname) except OSError as e: - if e.errno == errno.EEXIST: - pass - else: + if e.errno != errno.EEXIST: self.log.critical("An unexpected error occurred.") - six.reraise(*sys.exc_info()) + raise e def _same_paths(self, src, dst): # handles same paths but with C:/project vs c:/project diff --git a/client/ayon_core/lib/local_settings.py b/client/ayon_core/lib/local_settings.py index fd255c997f..54432265d9 100644 --- a/client/ayon_core/lib/local_settings.py +++ b/client/ayon_core/lib/local_settings.py @@ -4,7 +4,7 @@ import os import json import platform from datetime import datetime -from abc import ABCMeta, abstractmethod +from abc import ABC, abstractmethod # disable lru cache in Python 2 try: @@ -24,7 +24,6 @@ try: except ImportError: import ConfigParser as configparser -import six import appdirs import ayon_api @@ -133,8 +132,7 @@ class AYONSecureRegistry: keyring.delete_password(self._name, name) -@six.add_metaclass(ABCMeta) -class ASettingRegistry(): +class ASettingRegistry(ABC): """Abstract class defining structure of **SettingRegistry** class. It is implementing methods to store secure items into keyring, otherwise diff --git a/client/ayon_core/lib/path_templates.py b/client/ayon_core/lib/path_templates.py index a766dbd9c1..01a6985a25 100644 --- a/client/ayon_core/lib/path_templates.py +++ b/client/ayon_core/lib/path_templates.py @@ -2,8 +2,6 @@ import os import re import numbers -import six - KEY_PATTERN = re.compile(r"(\{.*?[^{0]*\})") KEY_PADDING_PATTERN = re.compile(r"([^:]+)\S+[><]\S+") SUB_DICT_PATTERN = re.compile(r"([^\[\]]+)") @@ -14,7 +12,7 @@ class TemplateUnsolved(Exception): """Exception for unsolved template when strict is set to True.""" msg = "Template \"{0}\" is unsolved.{1}{2}" - invalid_types_msg = " Keys with invalid DataType: `{0}`." + invalid_types_msg = " Keys with invalid data type: `{0}`." missing_keys_msg = " Missing keys: \"{0}\"." def __init__(self, template, missing_keys, invalid_types): @@ -43,7 +41,7 @@ class TemplateUnsolved(Exception): class StringTemplate(object): """String that can be formatted.""" def __init__(self, template): - if not isinstance(template, six.string_types): + if not isinstance(template, str): raise TypeError("<{}> argument must be a string, not {}.".format( self.__class__.__name__, str(type(template)) )) @@ -63,7 +61,7 @@ class StringTemplate(object): new_parts = [] for part in parts: - if not isinstance(part, six.string_types): + if not isinstance(part, str): new_parts.append(part) continue @@ -113,7 +111,7 @@ class StringTemplate(object): """ result = TemplatePartResult() for part in self._parts: - if isinstance(part, six.string_types): + if isinstance(part, str): result.add_output(part) else: part.format(data, result) @@ -176,7 +174,7 @@ class StringTemplate(object): value = "<>" elif ( len(parts) == 1 - and isinstance(parts[0], six.string_types) + and isinstance(parts[0], str) ): value = "<{}>".format(parts[0]) else: @@ -200,8 +198,9 @@ class StringTemplate(object): new_parts.extend(tmp_parts[idx]) return new_parts + class TemplateResult(str): - """Result of template format with most of information in. + """Result of template format with most of the information in. Args: used_values (dict): Dictionary of template filling data with @@ -299,7 +298,7 @@ class TemplatePartResult: self._optional = True def add_output(self, other): - if isinstance(other, six.string_types): + if isinstance(other, str): self._output += other elif isinstance(other, TemplatePartResult): @@ -457,7 +456,7 @@ class FormattingPart: return True for inh_class in type(value).mro(): - if inh_class in six.string_types: + if inh_class is str: return True return False @@ -568,7 +567,7 @@ class OptionalPart: def format(self, data, result): new_result = TemplatePartResult(True) for part in self._parts: - if isinstance(part, six.string_types): + if isinstance(part, str): new_result.add_output(part) else: part.format(data, new_result) diff --git a/client/ayon_core/lib/transcoding.py b/client/ayon_core/lib/transcoding.py index 4d778c2091..bff28614ea 100644 --- a/client/ayon_core/lib/transcoding.py +++ b/client/ayon_core/lib/transcoding.py @@ -978,7 +978,7 @@ def _ffmpeg_h264_codec_args(stream_data, source_ffmpeg_cmd): if pix_fmt: output.extend(["-pix_fmt", pix_fmt]) - output.extend(["-intra", "-g", "1"]) + output.extend(["-g", "1"]) return output diff --git a/client/ayon_core/modules/__init__.py b/client/ayon_core/modules/__init__.py index 0dfd7d663c..f4e381f4a0 100644 --- a/client/ayon_core/modules/__init__.py +++ b/client/ayon_core/modules/__init__.py @@ -17,7 +17,6 @@ from .base import ( load_modules, ModulesManager, - TrayModulesManager, ) @@ -38,5 +37,4 @@ __all__ = ( "load_modules", "ModulesManager", - "TrayModulesManager", ) diff --git a/client/ayon_core/modules/base.py b/client/ayon_core/modules/base.py index 3f2a7d4ea5..df412d141e 100644 --- a/client/ayon_core/modules/base.py +++ b/client/ayon_core/modules/base.py @@ -3,7 +3,6 @@ from ayon_core.addon import ( AYONAddon, AddonsManager, - TrayAddonsManager, load_addons, ) from ayon_core.addon.base import ( @@ -12,18 +11,15 @@ from ayon_core.addon.base import ( ) ModulesManager = AddonsManager -TrayModulesManager = TrayAddonsManager load_modules = load_addons __all__ = ( "AYONAddon", "AddonsManager", - "TrayAddonsManager", "load_addons", "OpenPypeModule", "OpenPypeAddOn", "ModulesManager", - "TrayModulesManager", "load_modules", ) diff --git a/client/ayon_core/modules/webserver/__init__.py b/client/ayon_core/modules/webserver/__init__.py deleted file mode 100644 index 32f2c55f65..0000000000 --- a/client/ayon_core/modules/webserver/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -from .version import __version__ -from .structures import HostMsgAction -from .webserver_module import ( - WebServerAddon -) - - -__all__ = ( - "__version__", - - "HostMsgAction", - "WebServerAddon", -) diff --git a/client/ayon_core/modules/webserver/version.py b/client/ayon_core/modules/webserver/version.py deleted file mode 100644 index 5becc17c04..0000000000 --- a/client/ayon_core/modules/webserver/version.py +++ /dev/null @@ -1 +0,0 @@ -__version__ = "1.0.0" diff --git a/client/ayon_core/modules/webserver/webserver_module.py b/client/ayon_core/modules/webserver/webserver_module.py deleted file mode 100644 index 997b6f754c..0000000000 --- a/client/ayon_core/modules/webserver/webserver_module.py +++ /dev/null @@ -1,212 +0,0 @@ -"""WebServerAddon spawns aiohttp server in asyncio loop. - -Main usage of the module is in AYON tray where make sense to add ability -of other modules to add theirs routes. Module which would want use that -option must have implemented method `webserver_initialization` which must -expect `WebServerManager` object where is possible to add routes or paths -with handlers. - -WebServerManager is by default created only in tray. - -It is possible to create server manager without using module logic at all -using `create_new_server_manager`. That can be handy for standalone scripts -with predefined host and port and separated routes and logic. - -Running multiple servers in one process is not recommended and probably won't -work as expected. It is because of few limitations connected to asyncio module. - -When module's `create_server_manager` is called it is also set environment -variable "AYON_WEBSERVER_URL". Which should lead to root access point -of server. -""" - -import os -import socket - -from ayon_core import resources -from ayon_core.addon import AYONAddon, ITrayService - -from .version import __version__ - - -class WebServerAddon(AYONAddon, ITrayService): - name = "webserver" - version = __version__ - label = "WebServer" - - webserver_url_env = "AYON_WEBSERVER_URL" - - def initialize(self, settings): - self._server_manager = None - self._host_listener = None - - self._port = self.find_free_port() - self._webserver_url = None - - @property - def server_manager(self): - """ - - Returns: - Union[WebServerManager, None]: Server manager instance. - - """ - return self._server_manager - - @property - def port(self): - """ - - Returns: - int: Port on which is webserver running. - - """ - return self._port - - @property - def webserver_url(self): - """ - - Returns: - str: URL to webserver. - - """ - return self._webserver_url - - def connect_with_addons(self, enabled_modules): - if not self._server_manager: - return - - for module in enabled_modules: - if not hasattr(module, "webserver_initialization"): - continue - - try: - module.webserver_initialization(self._server_manager) - except Exception: - self.log.warning( - ( - "Failed to connect module \"{}\" to webserver." - ).format(module.name), - exc_info=True - ) - - def tray_init(self): - self.create_server_manager() - self._add_resources_statics() - self._add_listeners() - - def tray_start(self): - self.start_server() - - def tray_exit(self): - self.stop_server() - - def start_server(self): - if self._server_manager is not None: - self._server_manager.start_server() - - def stop_server(self): - if self._server_manager is not None: - self._server_manager.stop_server() - - @staticmethod - def create_new_server_manager(port=None, host=None): - """Create webserver manager for passed port and host. - - Args: - port(int): Port on which wil webserver listen. - host(str): Host name or IP address. Default is 'localhost'. - - Returns: - WebServerManager: Prepared manager. - """ - from .server import WebServerManager - - return WebServerManager(port, host) - - def create_server_manager(self): - if self._server_manager is not None: - return - - self._server_manager = self.create_new_server_manager(self._port) - self._server_manager.on_stop_callbacks.append( - self.set_service_failed_icon - ) - - webserver_url = self._server_manager.url - os.environ["OPENPYPE_WEBSERVER_URL"] = str(webserver_url) - os.environ[self.webserver_url_env] = str(webserver_url) - self._webserver_url = webserver_url - - @staticmethod - def find_free_port( - port_from=None, port_to=None, exclude_ports=None, host=None - ): - """Find available socket port from entered range. - - It is also possible to only check if entered port is available. - - Args: - port_from (int): Port number which is checked as first. - port_to (int): Last port that is checked in sequence from entered - `port_from`. Only `port_from` is checked if is not entered. - Nothing is processed if is equeal to `port_from`! - exclude_ports (list, tuple, set): List of ports that won't be - checked form entered range. - host (str): Host where will check for free ports. Set to - "localhost" by default. - """ - if port_from is None: - port_from = 8079 - - if port_to is None: - port_to = 65535 - - # Excluded ports (e.g. reserved for other servers/clients) - if exclude_ports is None: - exclude_ports = [] - - # Default host is localhost but it is possible to look for other hosts - if host is None: - host = "localhost" - - found_port = None - for port in range(port_from, port_to + 1): - if port in exclude_ports: - continue - - sock = None - try: - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.bind((host, port)) - found_port = port - - except socket.error: - continue - - finally: - if sock: - sock.close() - - if found_port is not None: - break - - return found_port - - def _add_resources_statics(self): - static_prefix = "/res" - self._server_manager.add_static(static_prefix, resources.RESOURCES_DIR) - statisc_url = "{}{}".format( - self._webserver_url, static_prefix - ) - - os.environ["AYON_STATICS_SERVER"] = statisc_url - os.environ["OPENPYPE_STATICS_SERVER"] = statisc_url - - def _add_listeners(self): - from . import host_console_listener - - self._host_listener = host_console_listener.HostListener( - self._server_manager, self - ) diff --git a/client/ayon_core/pipeline/create/context.py b/client/ayon_core/pipeline/create/context.py index 0d8722dab1..1c64d22733 100644 --- a/client/ayon_core/pipeline/create/context.py +++ b/client/ayon_core/pipeline/create/context.py @@ -7,12 +7,14 @@ import collections import inspect from uuid import uuid4 from contextlib import contextmanager +from typing import Optional import pyblish.logic import pyblish.api import ayon_api from ayon_core.settings import get_project_settings +from ayon_core.lib import is_func_signature_supported from ayon_core.lib.attribute_definitions import ( UnknownDef, serialize_attr_defs, @@ -46,7 +48,7 @@ class UnavailableSharedData(Exception): class ImmutableKeyError(TypeError): - """Accessed key is immutable so does not allow changes or removements.""" + """Accessed key is immutable so does not allow changes or removals.""" def __init__(self, key, msg=None): self.immutable_key = key @@ -1404,6 +1406,7 @@ class CreateContext: self._current_workfile_path = None self._current_project_settings = None + self._current_project_entity = _NOT_SET self._current_folder_entity = _NOT_SET self._current_task_entity = _NOT_SET self._current_task_type = _NOT_SET @@ -1431,7 +1434,7 @@ class CreateContext: self.convertors_plugins = {} self.convertor_items_by_id = {} - self.publish_discover_result = None + self.publish_discover_result: Optional[DiscoverResult] = None self.publish_plugins_mismatch_targets = [] self.publish_plugins = [] self.plugins_with_defs = [] @@ -1592,6 +1595,22 @@ class CreateContext: self._current_task_type = task_type return self._current_task_type + def get_current_project_entity(self): + """Project entity for current context project. + + Returns: + Union[dict[str, Any], None]: Folder entity. + + """ + if self._current_project_entity is not _NOT_SET: + return copy.deepcopy(self._current_project_entity) + project_entity = None + project_name = self.get_current_project_name() + if project_name: + project_entity = ayon_api.get_project(project_name) + self._current_project_entity = project_entity + return copy.deepcopy(self._current_project_entity) + def get_current_folder_entity(self): """Folder entity for current context folder. @@ -1788,6 +1807,7 @@ class CreateContext: self._current_task_name = task_name self._current_workfile_path = workfile_path + self._current_project_entity = _NOT_SET self._current_folder_entity = _NOT_SET self._current_task_entity = _NOT_SET self._current_task_type = _NOT_SET @@ -2023,7 +2043,8 @@ class CreateContext: variant, folder_entity=None, task_entity=None, - pre_create_data=None + pre_create_data=None, + active=None ): """Trigger create of plugins with standartized arguments. @@ -2041,6 +2062,8 @@ class CreateContext: of creation (possible context of created instance/s). task_entity (Dict[str, Any]): Task entity. pre_create_data (Dict[str, Any]): Pre-create attribute values. + active (Optional[bool]): Whether the created instance defaults + to be active or not. Returns: Any: Output of triggered creator's 'create' method. @@ -2083,13 +2106,22 @@ class CreateContext: # TODO validate types _pre_create_data.update(pre_create_data) - product_name = creator.get_product_name( + project_entity = self.get_current_project_entity() + args = ( project_name, folder_entity, task_entity, variant, self.host_name, ) + kwargs = {"project_entity": project_entity} + # Backwards compatibility for 'project_entity' argument + # - 'get_product_name' signature changed 24/07/08 + if not is_func_signature_supported( + creator.get_product_name, *args, **kwargs + ): + kwargs.pop("project_entity") + product_name = creator.get_product_name(*args, **kwargs) instance_data = { "folderPath": folder_entity["path"], @@ -2097,6 +2129,14 @@ class CreateContext: "productType": creator.product_type, "variant": variant } + if active is not None: + if not isinstance(active, bool): + self.log.warning( + "CreateContext.create 'active' argument is not a bool. " + f"Converting {active} {type(active)} to bool.") + active = bool(active) + instance_data["active"] = active + return creator.create( product_name, instance_data, @@ -2576,7 +2616,7 @@ class CreateContext: def collection_shared_data(self): """Access to shared data that can be used during creator's collection. - Retruns: + Returns: Dict[str, Any]: Shared data. Raises: diff --git a/client/ayon_core/pipeline/create/creator_plugins.py b/client/ayon_core/pipeline/create/creator_plugins.py index e0b30763d0..624f1c9588 100644 --- a/client/ayon_core/pipeline/create/creator_plugins.py +++ b/client/ayon_core/pipeline/create/creator_plugins.py @@ -1,10 +1,9 @@ # -*- coding: utf-8 -*- import copy import collections +from typing import TYPE_CHECKING, Optional -from abc import ABCMeta, abstractmethod - -import six +from abc import ABC, abstractmethod from ayon_core.settings import get_project_settings from ayon_core.lib import Logger @@ -21,6 +20,11 @@ from .product_name import get_product_name from .utils import get_next_versions_for_instances from .legacy_create import LegacyCreator +if TYPE_CHECKING: + from ayon_core.lib import AbstractAttrDef + # Avoid cyclic imports + from .context import CreateContext, CreatedInstance, UpdateData # noqa: F401 + class CreatorError(Exception): """Should be raised when creator failed because of known issue. @@ -32,19 +36,18 @@ class CreatorError(Exception): super(CreatorError, self).__init__(message) -@six.add_metaclass(ABCMeta) -class ProductConvertorPlugin(object): +class ProductConvertorPlugin(ABC): """Helper for conversion of instances created using legacy creators. - Conversion from legacy creators would mean to loose legacy instances, + Conversion from legacy creators would mean to lose legacy instances, convert them automatically or write a script which must user run. All of - these solutions are workign but will happen without asking or user must + these solutions are working but will happen without asking or user must know about them. This plugin can be used to show legacy instances in Publisher and give user ability to run conversion script. Convertor logic should be very simple. Method 'find_instances' is to - look for legacy instances in scene a possibly call - pre-implemented 'add_convertor_item'. + look for legacy instances in scene and possibly call pre-implemented + 'add_convertor_item'. User will have ability to trigger conversion which is executed by calling 'convert' which should call 'remove_convertor_item' when is done. @@ -57,7 +60,7 @@ class ProductConvertorPlugin(object): can store any information to it's object for conversion purposes. Args: - create_context + create_context (CreateContext): Context which initialized the plugin. """ _log = None @@ -122,8 +125,8 @@ class ProductConvertorPlugin(object): def collection_shared_data(self): """Access to shared data that can be used during 'find_instances'. - Retruns: - Dict[str, Any]: Shared data. + Returns: + dict[str, Any]: Shared data. Raises: UnavailableSharedData: When called out of collection phase. @@ -146,11 +149,10 @@ class ProductConvertorPlugin(object): self._create_context.remove_convertor_item(self.identifier) -@six.add_metaclass(ABCMeta) -class BaseCreator: +class BaseCreator(ABC): """Plugin that create and modify instance data before publishing process. - We should maybe find better name as creation is only one part of it's logic + We should maybe find better name as creation is only one part of its logic and to avoid expectations that it is the same as `avalon.api.Creator`. Single object should be used for multiple instances instead of single @@ -158,7 +160,7 @@ class BaseCreator: to `self` if it's not Plugin specific. Args: - project_settings (Dict[str, Any]): Project settings. + project_settings (dict[str, Any]): Project settings. create_context (CreateContext): Context which initialized creator. headless (bool): Running in headless mode. """ @@ -185,20 +187,20 @@ class BaseCreator: # Instance attribute definitions that can be changed per instance # - returns list of attribute definitions from - # `ayon_core.pipeline.attribute_definitions` - instance_attr_defs = [] + # `ayon_core.lib.attribute_definitions` + instance_attr_defs: "list[AbstractAttrDef]" = [] # Filtering by host name - can be used to be filtered by host name # - used on all hosts when set to 'None' for Backwards compatibility # - was added afterwards # QUESTION make this required? - host_name = None + host_name: Optional[str] = None # Settings auto-apply helpers # Root key in project settings (mandatory for auto-apply to work) - settings_category = None + settings_category: Optional[str] = None # Name of plugin in create settings > class name is used if not set - settings_name = None + settings_name: Optional[str] = None def __init__( self, project_settings, create_context, headless=False @@ -207,7 +209,7 @@ class BaseCreator: self.create_context = create_context self.project_settings = project_settings - # Creator is running in headless mode (without UI elemets) + # Creator is running in headless mode (without UI elements) # - we may use UI inside processing this attribute should be checked self.headless = headless @@ -223,7 +225,7 @@ class BaseCreator: plugin_name (str): Name of settings. Returns: - Union[dict[str, Any], None]: Settings values or None. + Optional[dict[str, Any]]: Settings values or None. """ settings = project_settings.get(category_name) @@ -297,7 +299,6 @@ class BaseCreator: )) setattr(self, key, value) - @property def identifier(self): """Identifier of creator (must be unique). @@ -389,7 +390,7 @@ class BaseCreator: """Helper method to remove instance from create context. Instances must be removed from DCC workfile metadat aand from create - context in which plugin is existing at the moment of removement to + context in which plugin is existing at the moment of removal to propagate the change without restarting create context. Args: @@ -441,7 +442,7 @@ class BaseCreator: """Store changes of existing instances so they can be recollected. Args: - update_list(List[UpdateData]): Gets list of tuples. Each item + update_list (list[UpdateData]): Gets list of tuples. Each item contain changed instance and it's changes. """ @@ -449,13 +450,13 @@ class BaseCreator: @abstractmethod def remove_instances(self, instances): - """Method called on instance removement. + """Method called on instance removal. Can also remove instance metadata from context but should return 'True' if did so. Args: - instance(List[CreatedInstance]): Instance objects which should be + instances (list[CreatedInstance]): Instance objects which should be removed. """ @@ -480,8 +481,7 @@ class BaseCreator: ): """Dynamic data for product name filling. - These may be get dynamically created based on current context of - workfile. + These may be dynamically created based on current context of workfile. """ return {} @@ -493,7 +493,8 @@ class BaseCreator: task_entity, variant, host_name=None, - instance=None + instance=None, + project_entity=None, ): """Return product name for passed context. @@ -510,8 +511,9 @@ class BaseCreator: instance (Optional[CreatedInstance]): Object of 'CreatedInstance' for which is product name updated. Passed only on product name update. - """ + project_entity (Optional[dict[str, Any]]): Project entity. + """ if host_name is None: host_name = self.create_context.host_name @@ -537,7 +539,8 @@ class BaseCreator: self.product_type, variant, dynamic_data=dynamic_data, - project_settings=self.project_settings + project_settings=self.project_settings, + project_entity=project_entity, ) def get_instance_attr_defs(self): @@ -552,7 +555,7 @@ class BaseCreator: keys/values when plugin attributes change. Returns: - List[AbstractAttrDef]: Attribute definitions that can be tweaked + list[AbstractAttrDef]: Attribute definitions that can be tweaked for created instance. """ @@ -562,8 +565,8 @@ class BaseCreator: def collection_shared_data(self): """Access to shared data that can be used during creator's collection. - Retruns: - Dict[str, Any]: Shared data. + Returns: + dict[str, Any]: Shared data. Raises: UnavailableSharedData: When called out of collection phase. @@ -592,7 +595,7 @@ class BaseCreator: versions. Returns: - Dict[str, int]: Next versions by instance id. + dict[str, int]: Next versions by instance id. """ return get_next_versions_for_instances( @@ -711,7 +714,7 @@ class Creator(BaseCreator): By default, returns `default_variants` value. Returns: - List[str]: Whisper variants for user input. + list[str]: Whisper variants for user input. """ return copy.deepcopy(self.default_variants) @@ -784,7 +787,7 @@ class Creator(BaseCreator): updating keys/values when plugin attributes change. Returns: - List[AbstractAttrDef]: Attribute definitions that can be tweaked + list[AbstractAttrDef]: Attribute definitions that can be tweaked for created instance. """ return self.pre_create_attr_defs @@ -803,7 +806,7 @@ class AutoCreator(BaseCreator): """ def remove_instances(self, instances): - """Skip removement.""" + """Skip removal.""" pass @@ -916,7 +919,7 @@ def cache_and_get_instances(creator, shared_key, list_instances_func): if data were not yet stored under 'shared_key'. Returns: - Dict[str, Dict[str, Any]]: Cached instances by creator identifier from + dict[str, dict[str, Any]]: Cached instances by creator identifier from result of passed function. """ diff --git a/client/ayon_core/pipeline/create/legacy_create.py b/client/ayon_core/pipeline/create/legacy_create.py index ab939343c9..fc24bcf934 100644 --- a/client/ayon_core/pipeline/create/legacy_create.py +++ b/client/ayon_core/pipeline/create/legacy_create.py @@ -112,6 +112,13 @@ class LegacyCreator(object): This method can be modified to prefill some values just keep in mind it is class method. + Args: + project_name (str): Context's project name. + folder_entity (dict[str, Any]): Folder entity. + task_entity (dict[str, Any]): Task entity. + variant (str): What is entered by user in creator tool. + host_name (str): Name of host. + Returns: dict: Fill data for product name template. """ diff --git a/client/ayon_core/pipeline/create/product_name.py b/client/ayon_core/pipeline/create/product_name.py index fecda867e5..8a08bdc36c 100644 --- a/client/ayon_core/pipeline/create/product_name.py +++ b/client/ayon_core/pipeline/create/product_name.py @@ -1,3 +1,5 @@ +import ayon_api + from ayon_core.settings import get_project_settings from ayon_core.lib import filter_profiles, prepare_template_data @@ -37,7 +39,7 @@ def get_product_name_template( task_name (str): Name of task in which context the product is created. task_type (str): Type of task in which context the product is created. default_template (Union[str, None]): Default template which is used if - settings won't find any matching possitibility. Constant + settings won't find any matching possibility. Constant 'DEFAULT_PRODUCT_TEMPLATE' is used if not defined. project_settings (Union[Dict[str, Any], None]): Prepared settings for project. Settings are queried if not passed. @@ -88,6 +90,7 @@ def get_product_name( dynamic_data=None, project_settings=None, product_type_filter=None, + project_entity=None, ): """Calculate product name based on passed context and AYON settings. @@ -120,12 +123,18 @@ def get_product_name( product_type_filter (Optional[str]): Use different product type for product template filtering. Value of `product_type` is used when not passed. + project_entity (Optional[Dict[str, Any]]): Project entity used when + task short name is required by template. + + Returns: + str: Product name. Raises: + TaskNotSetError: If template requires task which is not provided. TemplateFillError: If filled template contains placeholder key which is not collected. - """ + """ if not product_type: return "" @@ -150,6 +159,16 @@ def get_product_name( if "{task}" in template.lower(): task_value = task_name + elif "{task[short]}" in template.lower(): + if project_entity is None: + project_entity = ayon_api.get_project(project_name) + task_types_by_name = { + task["name"]: task for task in + project_entity["taskTypes"] + } + task_short = task_types_by_name.get(task_type, {}).get("shortName") + task_value["short"] = task_short + fill_pairs = { "variant": variant, "family": product_type, diff --git a/client/ayon_core/pipeline/load/utils.py b/client/ayon_core/pipeline/load/utils.py index 7f2bec6d34..9ba407193e 100644 --- a/client/ayon_core/pipeline/load/utils.py +++ b/client/ayon_core/pipeline/load/utils.py @@ -587,6 +587,21 @@ def switch_container(container, representation, loader_plugin=None): return loader.switch(container, context) +def _fix_representation_context_compatibility(repre_context): + """Helper function to fix representation context compatibility. + + Args: + repre_context (dict): Representation context. + + """ + # Auto-fix 'udim' being list of integers + # - This is a legacy issue for old representation entities, + # added 24/07/10 + udim = repre_context.get("udim") + if isinstance(udim, list): + repre_context["udim"] = udim[0] + + def get_representation_path_from_context(context): """Preparation wrapper using only context as a argument""" from ayon_core.pipeline import get_current_project_name @@ -638,7 +653,9 @@ def get_representation_path_with_anatomy(repre_entity, anatomy): try: context = repre_entity["context"] + _fix_representation_context_compatibility(context) context["root"] = anatomy.roots + path = StringTemplate.format_strict_template(template, context) except TemplateUnsolved as exc: @@ -681,6 +698,9 @@ def get_representation_path(representation, root=None): try: context = representation["context"] + + _fix_representation_context_compatibility(context) + context["root"] = root path = StringTemplate.format_strict_template( template, context diff --git a/client/ayon_core/pipeline/project_folders.py b/client/ayon_core/pipeline/project_folders.py index 811a98ce4b..902b969457 100644 --- a/client/ayon_core/pipeline/project_folders.py +++ b/client/ayon_core/pipeline/project_folders.py @@ -2,8 +2,6 @@ import os import re import json -import six - from ayon_core.settings import get_project_settings from ayon_core.lib import Logger @@ -109,6 +107,6 @@ def get_project_basic_paths(project_name): if not folder_structure: return [] - if isinstance(folder_structure, six.string_types): + if isinstance(folder_structure, str): folder_structure = json.loads(folder_structure) return _list_path_items(folder_structure) diff --git a/client/ayon_core/pipeline/publish/abstract_collect_render.py b/client/ayon_core/pipeline/publish/abstract_collect_render.py index 17cab876b6..bd2d76c39c 100644 --- a/client/ayon_core/pipeline/publish/abstract_collect_render.py +++ b/client/ayon_core/pipeline/publish/abstract_collect_render.py @@ -7,8 +7,6 @@ TODO: use @dataclass when times come. from abc import abstractmethod import attr -import six - import pyblish.api from .publish_plugins import AbstractMetaContextPlugin @@ -122,8 +120,9 @@ class RenderInstance(object): raise ValueError("both tiles X a Y sizes are set to 1") -@six.add_metaclass(AbstractMetaContextPlugin) -class AbstractCollectRender(pyblish.api.ContextPlugin): +class AbstractCollectRender( + pyblish.api.ContextPlugin, metaclass=AbstractMetaContextPlugin +): """Gather all publishable render layers from renderSetup.""" order = pyblish.api.CollectorOrder + 0.01 diff --git a/client/ayon_core/pipeline/publish/abstract_expected_files.py b/client/ayon_core/pipeline/publish/abstract_expected_files.py index f9f3c17ef5..fffe723739 100644 --- a/client/ayon_core/pipeline/publish/abstract_expected_files.py +++ b/client/ayon_core/pipeline/publish/abstract_expected_files.py @@ -1,11 +1,9 @@ # -*- coding: utf-8 -*- """Abstract ExpectedFile class definition.""" -from abc import ABCMeta, abstractmethod -import six +from abc import ABC, abstractmethod -@six.add_metaclass(ABCMeta) -class ExpectedFiles: +class ExpectedFiles(ABC): """Class grouping functionality for all supported renderers. Attributes: diff --git a/client/ayon_core/pipeline/schema/__init__.py b/client/ayon_core/pipeline/schema/__init__.py index db98a6d080..d16755696d 100644 --- a/client/ayon_core/pipeline/schema/__init__.py +++ b/client/ayon_core/pipeline/schema/__init__.py @@ -17,7 +17,6 @@ import json import logging import jsonschema -import six log_ = logging.getLogger(__name__) @@ -44,7 +43,7 @@ def validate(data, schema=None): root, schema = data["schema"].rsplit(":", 1) - if isinstance(schema, six.string_types): + if isinstance(schema, str): schema = _cache[schema + ".json"] resolver = jsonschema.RefResolver( diff --git a/client/ayon_core/pipeline/workfile/workfile_template_builder.py b/client/ayon_core/pipeline/workfile/workfile_template_builder.py index bb94d87483..7b15dff049 100644 --- a/client/ayon_core/pipeline/workfile/workfile_template_builder.py +++ b/client/ayon_core/pipeline/workfile/workfile_template_builder.py @@ -3,7 +3,7 @@ Build templates are manually prepared using plugin definitions which create placeholders inside the template which are populated on import. -This approach is very explicit to achive very specific build logic that can be +This approach is very explicit to achieve very specific build logic that can be targeted by task types and names. Placeholders are created using placeholder plugins which should care about @@ -15,9 +15,8 @@ import os import re import collections import copy -from abc import ABCMeta, abstractmethod +from abc import ABC, abstractmethod -import six from ayon_api import ( get_folders, get_folder_by_path, @@ -82,12 +81,11 @@ class TemplateLoadFailed(Exception): pass -@six.add_metaclass(ABCMeta) -class AbstractTemplateBuilder(object): +class AbstractTemplateBuilder(ABC): """Abstraction of Template Builder. Builder cares about context, shared data, cache, discovery of plugins - and trigger logic. Provides public api for host workfile build systen. + and trigger logic. Provides public api for host workfile build system. Rest of logic is based on plugins that care about collection and creation of placeholder items. @@ -806,7 +804,7 @@ class AbstractTemplateBuilder(object): ) def get_template_preset(self): - """Unified way how template preset is received usign settings. + """Unified way how template preset is received using settings. Method is dependent on '_get_build_profiles' which should return filter profiles to resolve path to a template. Default implementation looks @@ -941,8 +939,7 @@ class AbstractTemplateBuilder(object): ) -@six.add_metaclass(ABCMeta) -class PlaceholderPlugin(object): +class PlaceholderPlugin(ABC): """Plugin which care about handling of placeholder items logic. Plugin create and update placeholders in scene and populate them on @@ -1427,7 +1424,7 @@ class PlaceholderLoadMixin(object): placeholder='{"camera":"persp", "lights":True}', tooltip=( "Loader" - "\nDefines a dictionnary of arguments used to load assets." + "\nDefines a dictionary of arguments used to load assets." "\nUseable arguments depend on current placeholder Loader." "\nField should be a valid python dict." " Anything else will be ignored." @@ -1472,7 +1469,7 @@ class PlaceholderLoadMixin(object): ] def parse_loader_args(self, loader_args): - """Helper function to parse string of loader arugments. + """Helper function to parse string of loader arguments. Empty dictionary is returned if conversion fails. @@ -1797,6 +1794,16 @@ class PlaceholderCreateMixin(object): "\ncompiling of product name." ) ), + attribute_definitions.BoolDef( + "active", + label="Active", + default=options.get("active", True), + tooltip=( + "Active" + "\nDefines whether the created instance will default to " + "active or not." + ) + ), attribute_definitions.UISeparatorDef(), attribute_definitions.NumberDef( "order", @@ -1826,6 +1833,7 @@ class PlaceholderCreateMixin(object): legacy_create = self.builder.use_legacy_creators creator_name = placeholder.data["creator"] create_variant = placeholder.data["create_variant"] + active = placeholder.data.get("active") creator_plugin = self.builder.get_creators_by_name()[creator_name] @@ -1872,8 +1880,9 @@ class PlaceholderCreateMixin(object): creator_plugin.identifier, create_variant, folder_entity, - task_name=task_name, - pre_create_data=pre_create_data + task_entity, + pre_create_data=pre_create_data, + active=active ) except: # noqa: E722 diff --git a/client/ayon_core/plugins/load/delete_old_versions.py b/client/ayon_core/plugins/load/delete_old_versions.py index 62302e7123..f8c45baff6 100644 --- a/client/ayon_core/plugins/load/delete_old_versions.py +++ b/client/ayon_core/plugins/load/delete_old_versions.py @@ -1,6 +1,7 @@ import collections import os import uuid +from typing import List, Dict, Any import clique import ayon_api @@ -41,11 +42,13 @@ class DeleteOldVersions(load.ProductLoaderPlugin): ) ] + requires_confirmation = True + def delete_whole_dir_paths(self, dir_paths, delete=True): size = 0 for dir_path in dir_paths: - # Delete all files and fodlers in dir path + # Delete all files and folders in dir path for root, dirs, files in os.walk(dir_path, topdown=False): for name in files: file_path = os.path.join(root, name) @@ -192,6 +195,42 @@ class DeleteOldVersions(load.ProductLoaderPlugin): ) msgBox.exec_() + def _confirm_delete(self, + contexts: List[Dict[str, Any]], + versions_to_keep: int) -> bool: + """Prompt user for a deletion confirmation""" + + contexts_list = "\n".join(sorted( + "- {folder[name]} > {product[name]}".format_map(context) + for context in contexts + )) + num_contexts = len(contexts) + s = "s" if num_contexts > 1 else "" + text = ( + "Are you sure you want to delete versions?\n\n" + f"This will keep only the last {versions_to_keep} " + f"versions for the {num_contexts} selected product{s}." + ) + informative_text="Warning: This will delete files from disk" + detailed_text = ( + f"Keep only {versions_to_keep} versions for:\n{contexts_list}" + ) + + messagebox = QtWidgets.QMessageBox() + messagebox.setIcon(QtWidgets.QMessageBox.Warning) + messagebox.setWindowTitle("Delete Old Versions") + messagebox.setText(text) + messagebox.setInformativeText(informative_text) + messagebox.setDetailedText(detailed_text) + messagebox.setStandardButtons( + QtWidgets.QMessageBox.Yes + | QtWidgets.QMessageBox.Cancel + ) + messagebox.setDefaultButton(QtWidgets.QMessageBox.Cancel) + messagebox.setStyleSheet(style.load_stylesheet()) + messagebox.setAttribute(QtCore.Qt.WA_DeleteOnClose, True) + return messagebox.exec_() == QtWidgets.QMessageBox.Yes + def get_data(self, context, versions_count): product_entity = context["product"] folder_entity = context["folder"] @@ -365,19 +404,29 @@ class DeleteOldVersions(load.ProductLoaderPlugin): return size def load(self, contexts, name=None, namespace=None, options=None): + + # Get user options + versions_to_keep = 2 + remove_publish_folder = False + if options: + versions_to_keep = options.get( + "versions_to_keep", versions_to_keep + ) + remove_publish_folder = options.get( + "remove_publish_folder", remove_publish_folder + ) + + # Because we do not want this run by accident we will add an extra + # user confirmation + if ( + self.requires_confirmation + and not self._confirm_delete(contexts, versions_to_keep) + ): + return + try: size = 0 for count, context in enumerate(contexts): - versions_to_keep = 2 - remove_publish_folder = False - if options: - versions_to_keep = options.get( - "versions_to_keep", versions_to_keep - ) - remove_publish_folder = options.get( - "remove_publish_folder", remove_publish_folder - ) - data = self.get_data(context, versions_to_keep) if not data: continue @@ -408,6 +457,8 @@ class CalculateOldVersions(DeleteOldVersions): ) ] + requires_confirmation = False + def main(self, project_name, data, remove_publish_folder): size = 0 diff --git a/client/ayon_core/plugins/publish/collect_input_representations_to_versions.py b/client/ayon_core/plugins/publish/collect_input_representations_to_versions.py index 770f3470c6..b9fe97b80b 100644 --- a/client/ayon_core/plugins/publish/collect_input_representations_to_versions.py +++ b/client/ayon_core/plugins/publish/collect_input_representations_to_versions.py @@ -1,4 +1,5 @@ import ayon_api +import ayon_api.utils import pyblish.api @@ -23,6 +24,12 @@ class CollectInputRepresentationsToVersions(pyblish.api.ContextPlugin): if inst_repre: representations.update(inst_repre) + # Ignore representation ids that are not valid + representations = { + representation_id for representation_id in representations + if ayon_api.utils.convert_entity_id(representation_id) + } + repre_entities = ayon_api.get_representations( project_name=context.data["projectName"], representation_ids=representations, diff --git a/client/ayon_core/plugins/publish/collect_resources_path.py b/client/ayon_core/plugins/publish/collect_resources_path.py index 63c6bf6345..7a80d0054c 100644 --- a/client/ayon_core/plugins/publish/collect_resources_path.py +++ b/client/ayon_core/plugins/publish/collect_resources_path.py @@ -65,7 +65,8 @@ class CollectResourcesPath(pyblish.api.InstancePlugin): "xgen", "yeticacheUE", "tycache", - "usd" + "usd", + "oxrig" ] def process(self, instance): diff --git a/client/ayon_core/plugins/publish/collect_scene_loaded_versions.py b/client/ayon_core/plugins/publish/collect_scene_loaded_versions.py index 1267c009e7..1abb8e29d2 100644 --- a/client/ayon_core/plugins/publish/collect_scene_loaded_versions.py +++ b/client/ayon_core/plugins/publish/collect_scene_loaded_versions.py @@ -1,7 +1,8 @@ import ayon_api -import pyblish.api +import ayon_api.utils from ayon_core.pipeline import registered_host +import pyblish.api class CollectSceneLoadedVersions(pyblish.api.ContextPlugin): @@ -41,6 +42,12 @@ class CollectSceneLoadedVersions(pyblish.api.ContextPlugin): for container in containers } + # Ignore representation ids that are not valid + repre_ids = { + representation_id for representation_id in repre_ids + if ayon_api.utils.convert_entity_id(representation_id) + } + project_name = context.data["projectName"] repre_entities = ayon_api.get_representations( project_name, @@ -65,7 +72,7 @@ class CollectSceneLoadedVersions(pyblish.api.ContextPlugin): continue # NOTE: - # may have more then one representation that are same version + # may have more than one representation that are same version version = { "container_name": con["name"], "representation_id": repre_entity["id"], diff --git a/client/ayon_core/plugins/publish/extract_burnin.py b/client/ayon_core/plugins/publish/extract_burnin.py index 93774842ca..58a032a030 100644 --- a/client/ayon_core/plugins/publish/extract_burnin.py +++ b/client/ayon_core/plugins/publish/extract_burnin.py @@ -6,7 +6,6 @@ import platform import shutil import clique -import six import pyblish.api from ayon_core import resources, AYON_CORE_ROOT @@ -456,7 +455,7 @@ class ExtractBurnin(publish.Extractor): sys_name = platform.system().lower() font_filepath = font_filepath.get(sys_name) - if font_filepath and isinstance(font_filepath, six.string_types): + if font_filepath and isinstance(font_filepath, str): font_filepath = font_filepath.format(**os.environ) if not os.path.exists(font_filepath): font_filepath = None diff --git a/client/ayon_core/plugins/publish/extract_review.py b/client/ayon_core/plugins/publish/extract_review.py index 1891c25521..c2793f98a2 100644 --- a/client/ayon_core/plugins/publish/extract_review.py +++ b/client/ayon_core/plugins/publish/extract_review.py @@ -4,9 +4,8 @@ import copy import json import shutil import subprocess -from abc import ABCMeta, abstractmethod +from abc import ABC, abstractmethod -import six import clique import speedcopy import pyblish.api @@ -1661,8 +1660,7 @@ class ExtractReview(pyblish.api.InstancePlugin): return vf_back -@six.add_metaclass(ABCMeta) -class _OverscanValue: +class _OverscanValue(ABC): def __repr__(self): return "<{}> {}".format(self.__class__.__name__, str(self)) diff --git a/client/ayon_core/plugins/publish/integrate.py b/client/ayon_core/plugins/publish/integrate.py index 1a4cda4dbb..a2cf910fa6 100644 --- a/client/ayon_core/plugins/publish/integrate.py +++ b/client/ayon_core/plugins/publish/integrate.py @@ -4,7 +4,6 @@ import sys import copy import clique -import six import pyblish.api from ayon_api import ( get_attributes_for_type, @@ -160,15 +159,14 @@ class IntegrateAsset(pyblish.api.InstancePlugin): # Raise DuplicateDestinationError as KnownPublishError # and rollback the transactions file_transactions.rollback() - six.reraise(KnownPublishError, - KnownPublishError(exc), - sys.exc_info()[2]) - except Exception: + raise KnownPublishError(exc).with_traceback(sys.exc_info()[2]) + + except Exception as exc: # clean destination # todo: preferably we'd also rollback *any* changes to the database file_transactions.rollback() self.log.critical("Error when registering", exc_info=True) - six.reraise(*sys.exc_info()) + raise exc # Finalizing can't rollback safely so no use for moving it to # the try, except. @@ -789,11 +787,6 @@ class IntegrateAsset(pyblish.api.InstancePlugin): if value is not None: repre_context[key] = value - # Explicitly store the full list even though template data might - # have a different value because it uses just a single udim tile - if repre.get("udim"): - repre_context["udim"] = repre.get("udim") # store list - # Use previous representation's id if there is a name match existing = existing_repres_by_name.get(repre["name"].lower()) repre_id = None diff --git a/client/ayon_core/style/__init__.py b/client/ayon_core/style/__init__.py index 8d3089ef86..064f527f2b 100644 --- a/client/ayon_core/style/__init__.py +++ b/client/ayon_core/style/__init__.py @@ -2,7 +2,6 @@ import os import copy import json import collections -import six from ayon_core import resources @@ -75,7 +74,7 @@ def _convert_color_values_to_objects(value): output[_key] = _convert_color_values_to_objects(_value) return output - if not isinstance(value, six.string_types): + if not isinstance(value, str): raise TypeError(( "Unexpected type in colors data '{}'. Expected 'str' or 'dict'." ).format(str(type(value)))) diff --git a/client/ayon_core/tools/common_models/hierarchy.py b/client/ayon_core/tools/common_models/hierarchy.py index f92563db20..6bccb0f468 100644 --- a/client/ayon_core/tools/common_models/hierarchy.py +++ b/client/ayon_core/tools/common_models/hierarchy.py @@ -1,18 +1,16 @@ import time import collections import contextlib -from abc import ABCMeta, abstractmethod +from abc import ABC, abstractmethod import ayon_api -import six from ayon_core.lib import NestedCacheItem HIERARCHY_MODEL_SENDER = "hierarchy.model" -@six.add_metaclass(ABCMeta) -class AbstractHierarchyController: +class AbstractHierarchyController(ABC): @abstractmethod def emit_event(self, topic, data, source): pass diff --git a/client/ayon_core/tools/launcher/abstract.py b/client/ayon_core/tools/launcher/abstract.py index 921fe7bc5b..63ba4cd717 100644 --- a/client/ayon_core/tools/launcher/abstract.py +++ b/client/ayon_core/tools/launcher/abstract.py @@ -1,10 +1,7 @@ -from abc import ABCMeta, abstractmethod - -import six +from abc import ABC, abstractmethod -@six.add_metaclass(ABCMeta) -class AbstractLauncherCommon(object): +class AbstractLauncherCommon(ABC): @abstractmethod def register_event_callback(self, topic, callback): """Register event callback. diff --git a/client/ayon_core/tools/loader/abstract.py b/client/ayon_core/tools/loader/abstract.py index 3a1a23edd7..6a68af1eb5 100644 --- a/client/ayon_core/tools/loader/abstract.py +++ b/client/ayon_core/tools/loader/abstract.py @@ -1,5 +1,4 @@ -from abc import ABCMeta, abstractmethod -import six +from abc import ABC, abstractmethod from ayon_core.lib.attribute_definitions import ( AbstractAttrDef, @@ -347,8 +346,7 @@ class ActionItem: return cls(**data) -@six.add_metaclass(ABCMeta) -class _BaseLoaderController(object): +class _BaseLoaderController(ABC): """Base loader controller abstraction. Abstract base class that is required for both frontend and backed. diff --git a/client/ayon_core/tools/loader/ui/_multicombobox.py b/client/ayon_core/tools/loader/ui/_multicombobox.py new file mode 100644 index 0000000000..c026952418 --- /dev/null +++ b/client/ayon_core/tools/loader/ui/_multicombobox.py @@ -0,0 +1,658 @@ +from typing import List, Tuple, Optional, Iterable, Any + +from qtpy import QtWidgets, QtCore, QtGui + +from ayon_core.tools.utils.lib import ( + checkstate_int_to_enum, + checkstate_enum_to_int, +) +from ayon_core.tools.utils.constants import ( + CHECKED_INT, + UNCHECKED_INT, + ITEM_IS_USER_TRISTATE, +) + +VALUE_ITEM_TYPE = 0 +STANDARD_ITEM_TYPE = 1 +SEPARATOR_ITEM_TYPE = 2 + + +class CustomPaintDelegate(QtWidgets.QStyledItemDelegate): + """Delegate showing status name and short name.""" + _checked_value = checkstate_enum_to_int(QtCore.Qt.Checked) + _checked_bg_color = QtGui.QColor("#2C3B4C") + + def __init__( + self, + text_role: int, + short_text_role: int, + text_color_role: int, + icon_role: int, + item_type_role: Optional[int] = None, + parent=None + ): + super().__init__(parent) + self._text_role = text_role + self._text_color_role = text_color_role + self._short_text_role = short_text_role + self._icon_role = icon_role + self._item_type_role = item_type_role + + def paint(self, painter, option, index): + item_type = None + if self._item_type_role is not None: + item_type = index.data(self._item_type_role) + + if item_type is None: + item_type = VALUE_ITEM_TYPE + + if item_type == STANDARD_ITEM_TYPE: + super().paint(painter, option, index) + return + + elif item_type == SEPARATOR_ITEM_TYPE: + self._paint_separator(painter, option, index) + return + + if option.widget: + style = option.widget.style() + else: + style = QtWidgets.QApplication.style() + + self.initStyleOption(option, index) + + mode = QtGui.QIcon.Normal + if not (option.state & QtWidgets.QStyle.State_Enabled): + mode = QtGui.QIcon.Disabled + elif option.state & QtWidgets.QStyle.State_Selected: + mode = QtGui.QIcon.Selected + state = QtGui.QIcon.Off + if option.state & QtWidgets.QStyle.State_Open: + state = QtGui.QIcon.On + icon = self._get_index_icon(index) + option.features |= QtWidgets.QStyleOptionViewItem.HasDecoration + + # Disable visible check indicator + # - checkstate is displayed by background color + option.features &= ( + ~QtWidgets.QStyleOptionViewItem.HasCheckIndicator + ) + + option.icon = icon + act_size = icon.actualSize(option.decorationSize, mode, state) + option.decorationSize = QtCore.QSize( + min(option.decorationSize.width(), act_size.width()), + min(option.decorationSize.height(), act_size.height()) + ) + + text = self._get_index_name(index) + if text: + option.features |= QtWidgets.QStyleOptionViewItem.HasDisplay + option.text = text + + painter.save() + painter.setClipRect(option.rect) + + is_checked = ( + index.data(QtCore.Qt.CheckStateRole) == self._checked_value + ) + if is_checked: + painter.fillRect(option.rect, self._checked_bg_color) + + icon_rect = style.subElementRect( + QtWidgets.QCommonStyle.SE_ItemViewItemDecoration, + option, + option.widget + ) + text_rect = style.subElementRect( + QtWidgets.QCommonStyle.SE_ItemViewItemText, + option, + option.widget + ) + + # Draw background + style.drawPrimitive( + QtWidgets.QCommonStyle.PE_PanelItemViewItem, + option, + painter, + option.widget + ) + + # Draw icon + option.icon.paint( + painter, + icon_rect, + option.decorationAlignment, + mode, + state + ) + fm = QtGui.QFontMetrics(option.font) + if text_rect.width() < fm.width(text): + text = self._get_index_short_name(index) + if not text or text_rect.width() < fm.width(text): + text = "" + + fg_color = self._get_index_text_color(index) + pen = painter.pen() + pen.setColor(fg_color) + painter.setPen(pen) + + painter.drawText( + text_rect, + option.displayAlignment, + text + ) + + if option.state & QtWidgets.QStyle.State_HasFocus: + focus_opt = QtWidgets.QStyleOptionFocusRect() + focus_opt.state = option.state + focus_opt.direction = option.direction + focus_opt.rect = option.rect + focus_opt.fontMetrics = option.fontMetrics + focus_opt.palette = option.palette + + focus_opt.rect = style.subElementRect( + QtWidgets.QCommonStyle.SE_ItemViewItemFocusRect, + option, + option.widget + ) + focus_opt.state |= ( + QtWidgets.QStyle.State_KeyboardFocusChange + | QtWidgets.QStyle.State_Item + ) + focus_opt.backgroundColor = option.palette.color( + ( + QtGui.QPalette.Normal + if option.state & QtWidgets.QStyle.State_Enabled + else QtGui.QPalette.Disabled + ), + ( + QtGui.QPalette.Highlight + if option.state & QtWidgets.QStyle.State_Selected + else QtGui.QPalette.Window + ) + ) + style.drawPrimitive( + QtWidgets.QCommonStyle.PE_FrameFocusRect, + focus_opt, + painter, + option.widget + ) + + painter.restore() + + def _paint_separator(self, painter, option, index): + painter.save() + painter.setClipRect(option.rect) + + style = option.widget.style() + style.drawPrimitive( + QtWidgets.QCommonStyle.PE_PanelItemViewItem, + option, + painter, + option.widget + ) + + pen = painter.pen() + pen.setWidth(2) + painter.setPen(pen) + mid_y = (option.rect.top() + option.rect.bottom()) * 0.5 + painter.drawLine( + QtCore.QPointF(option.rect.left(), mid_y), + QtCore.QPointF(option.rect.right(), mid_y) + ) + + painter.restore() + + def _get_index_name(self, index): + return index.data(self._text_role) + + def _get_index_short_name(self, index): + if self._short_text_role is None: + return None + return index.data(self._short_text_role) + + def _get_index_text_color(self, index): + color = None + if self._text_color_role is not None: + color = index.data(self._text_color_role) + if color is not None: + return QtGui.QColor(color) + return QtGui.QColor(QtCore.Qt.white) + + def _get_index_icon(self, index): + icon = None + if self._icon_role is not None: + icon = index.data(self._icon_role) + if icon is None: + return QtGui.QIcon() + return icon + + +class CustomPaintMultiselectComboBox(QtWidgets.QComboBox): + value_changed = QtCore.Signal() + focused_in = QtCore.Signal() + + ignored_keys = { + QtCore.Qt.Key_Up, + QtCore.Qt.Key_Down, + QtCore.Qt.Key_PageDown, + QtCore.Qt.Key_PageUp, + QtCore.Qt.Key_Home, + QtCore.Qt.Key_End, + } + + def __init__( + self, + text_role, + short_text_role, + text_color_role, + icon_role, + value_role=None, + item_type_role=None, + model=None, + placeholder=None, + parent=None, + ): + super().__init__(parent=parent) + self.setFocusPolicy(QtCore.Qt.StrongFocus) + + if model is not None: + self.setModel(model) + + combo_view = QtWidgets.QListView(self) + + self.setView(combo_view) + + item_delegate = CustomPaintDelegate( + text_role=text_role, + short_text_role=short_text_role, + text_color_role=text_color_role, + icon_role=icon_role, + item_type_role=item_type_role, + parent=combo_view, + ) + combo_view.setItemDelegateForColumn(0, item_delegate) + + if value_role is None: + value_role = text_role + + self._combo_view = combo_view + self._item_delegate = item_delegate + self._value_role = value_role + self._text_role = text_role + self._short_text_role = short_text_role + self._text_color_role = text_color_role + self._icon_role = icon_role + self._item_type_role = item_type_role + + self._popup_is_shown = False + self._block_mouse_release_timer = QtCore.QTimer(self, singleShot=True) + self._initial_mouse_pos = None + self._placeholder_text = placeholder + + self._custom_text = None + self._all_unchecked_as_checked = True + + def all_unchecked_as_checked(self) -> bool: + return self._all_unchecked_as_checked + + def set_all_unchecked_as_checked(self, value: bool): + """Set if all unchecked items should be treated as checked. + + Args: + value (bool): If True, all unchecked items will be treated + as checked. + + """ + self._all_unchecked_as_checked = value + + def get_placeholder_text(self) -> Optional[str]: + return self._placeholder_text + + def set_placeholder_text(self, text: Optional[str]): + """Set the placeholder text. + + Text shown when nothing is selected. + + Args: + text (str | None): The placeholder text. + + """ + if text == self._placeholder_text: + return + self._placeholder_text = text + self.repaint() + + def set_custom_text(self, text: Optional[str]): + """Set the placeholder text. + + Text always shown in combobox field. + + Args: + text (str | None): The text. Use 'None' to reset to default. + + """ + if text == self._custom_text: + return + self._custom_text = text + self.repaint() + + def focusInEvent(self, event): + self.focused_in.emit() + return super().focusInEvent(event) + + def mousePressEvent(self, event): + """Reimplemented.""" + self._popup_is_shown = False + super().mousePressEvent(event) + if self._popup_is_shown: + self._initial_mouse_pos = self.mapToGlobal(event.pos()) + self._block_mouse_release_timer.start( + QtWidgets.QApplication.doubleClickInterval() + ) + + def showPopup(self): + """Reimplemented.""" + super().showPopup() + view = self.view() + view.installEventFilter(self) + view.viewport().installEventFilter(self) + self._popup_is_shown = True + + def hidePopup(self): + """Reimplemented.""" + self.view().removeEventFilter(self) + self.view().viewport().removeEventFilter(self) + self._popup_is_shown = False + self._initial_mouse_pos = None + super().hidePopup() + self.view().clearFocus() + + def _event_popup_shown(self, obj, event): + if not self._popup_is_shown: + return + + current_index = self.view().currentIndex() + model = self.model() + + if event.type() == QtCore.QEvent.MouseMove: + if ( + self.view().isVisible() + and self._initial_mouse_pos is not None + and self._block_mouse_release_timer.isActive() + ): + diff = obj.mapToGlobal(event.pos()) - self._initial_mouse_pos + if diff.manhattanLength() > 9: + self._block_mouse_release_timer.stop() + return + + index_flags = current_index.flags() + state = checkstate_int_to_enum( + current_index.data(QtCore.Qt.CheckStateRole) + ) + + new_state = None + + if event.type() == QtCore.QEvent.MouseButtonRelease: + new_state = self._mouse_released_event_handle( + event, current_index, index_flags, state + ) + + elif event.type() == QtCore.QEvent.KeyPress: + new_state = self._key_press_event_handler( + event, current_index, index_flags, state + ) + + if new_state is not None: + model.setData(current_index, new_state, QtCore.Qt.CheckStateRole) + self.view().update(current_index) + self.repaint() + self.value_changed.emit() + return True + + def eventFilter(self, obj, event): + """Reimplemented.""" + result = self._event_popup_shown(obj, event) + if result is not None: + return result + + return super().eventFilter(obj, event) + + def addItem(self, *args, **kwargs): + idx = self.count() + super().addItem(*args, **kwargs) + self.model().item(idx).setCheckable(True) + + def paintEvent(self, event): + """Reimplemented.""" + painter = QtWidgets.QStylePainter(self) + option = QtWidgets.QStyleOptionComboBox() + self.initStyleOption(option) + painter.drawComplexControl(QtWidgets.QStyle.CC_ComboBox, option) + + idxs = self._get_checked_idx() + # draw the icon and text + draw_text = True + combotext = None + if self._custom_text is not None: + combotext = self._custom_text + elif not idxs: + combotext = self._placeholder_text + else: + draw_text = False + + content_field_rect = self.style().subControlRect( + QtWidgets.QStyle.CC_ComboBox, + option, + QtWidgets.QStyle.SC_ComboBoxEditField + ).adjusted(1, 0, -1, 0) + + if draw_text: + color = option.palette.color(QtGui.QPalette.Text) + color.setAlpha(67) + pen = painter.pen() + pen.setColor(color) + painter.setPen(pen) + painter.drawText( + content_field_rect, + QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter, + combotext + ) + else: + self._paint_items(painter, idxs, content_field_rect) + + painter.end() + + def _paint_items(self, painter, indexes, content_rect): + origin_rect = QtCore.QRect(content_rect) + + metrics = self.fontMetrics() + model = self.model() + available_width = content_rect.width() + total_used_width = 0 + + painter.save() + + spacing = 2 + + for idx in indexes: + index = model.index(idx, 0) + if not index.isValid(): + continue + + icon = index.data(self._icon_role) + # TODO handle this case + if icon is None or icon.isNull(): + continue + + icon_rect = QtCore.QRect(content_rect) + diff = icon_rect.height() - metrics.height() + if diff < 0: + diff = 0 + top_offset = diff // 2 + bottom_offset = diff - top_offset + icon_rect.adjust(0, top_offset, 0, -bottom_offset) + icon_rect.setWidth(metrics.height()) + icon.paint( + painter, + icon_rect, + QtCore.Qt.AlignCenter, + QtGui.QIcon.Normal, + QtGui.QIcon.On + ) + content_rect.setLeft(icon_rect.right() + spacing) + if total_used_width > 0: + total_used_width += spacing + total_used_width += icon_rect.width() + if total_used_width > available_width: + break + + painter.restore() + + if total_used_width > available_width: + ellide_dots = chr(0x2026) + painter.drawText(origin_rect, QtCore.Qt.AlignRight, ellide_dots) + + def setItemCheckState(self, index, state): + self.setItemData(index, state, QtCore.Qt.CheckStateRole) + + def set_value(self, values: Optional[Iterable[Any]], role: Optional[int] = None): + if role is None: + role = self._value_role + + for idx in range(self.count()): + value = self.itemData(idx, role=role) + check_state = CHECKED_INT + if values is None or value not in values: + check_state = UNCHECKED_INT + self.setItemData(idx, check_state, QtCore.Qt.CheckStateRole) + self.repaint() + + def get_value_info( + self, + role: Optional[int] = None, + propagate_all_unchecked_as_checked: bool = None + ) -> List[Tuple[Any, bool]]: + """Get the values and their checked state. + + Args: + role (int | None): The role to get the values from. + If None, the default value role is used. + propagate_all_unchecked_as_checked (bool | None): If True, + all unchecked items will be treated as checked. + If None, the current value of + 'propagate_all_unchecked_as_checked' is used. + + Returns: + List[Tuple[Any, bool]]: The values and their checked state. + + """ + if role is None: + role = self._value_role + + if propagate_all_unchecked_as_checked is None: + propagate_all_unchecked_as_checked = ( + self._all_unchecked_as_checked + ) + + items = [] + all_unchecked = True + for idx in range(self.count()): + item_type = self.itemData(idx, role=self._item_type_role) + if item_type is not None and item_type != VALUE_ITEM_TYPE: + continue + + state = checkstate_int_to_enum( + self.itemData(idx, role=QtCore.Qt.CheckStateRole) + ) + checked = state == QtCore.Qt.Checked + if checked: + all_unchecked = False + items.append( + (self.itemData(idx, role=role), checked) + ) + + if propagate_all_unchecked_as_checked and all_unchecked: + items = [ + (value, True) + for value, checked in items + ] + return items + + def get_value(self, role=None): + if role is None: + role = self._value_role + + return [ + value + for value, checked in self.get_value_info(role) + if checked + ] + + def wheelEvent(self, event): + event.ignore() + + def keyPressEvent(self, event): + if ( + event.key() == QtCore.Qt.Key_Down + and event.modifiers() & QtCore.Qt.AltModifier + ): + return self.showPopup() + + if event.key() in self.ignored_keys: + return event.ignore() + + return super().keyPressEvent(event) + + def _get_checked_idx(self) -> List[int]: + checked_indexes = [] + for idx in range(self.count()): + item_type = self.itemData(idx, role=self._item_type_role) + if item_type is not None and item_type != VALUE_ITEM_TYPE: + continue + + state = checkstate_int_to_enum( + self.itemData(idx, role=QtCore.Qt.CheckStateRole) + ) + if state == QtCore.Qt.Checked: + checked_indexes.append(idx) + return checked_indexes + + def _mouse_released_event_handle( + self, event, current_index, index_flags, state + ): + if ( + self._block_mouse_release_timer.isActive() + or not current_index.isValid() + or not self.view().isVisible() + or not self.view().rect().contains(event.pos()) + or not index_flags & QtCore.Qt.ItemIsSelectable + or not index_flags & QtCore.Qt.ItemIsEnabled + or not index_flags & QtCore.Qt.ItemIsUserCheckable + ): + return None + + if state == QtCore.Qt.Checked: + return UNCHECKED_INT + return CHECKED_INT + + def _key_press_event_handler( + self, event, current_index, index_flags, state + ): + # TODO: handle QtCore.Qt.Key_Enter, Key_Return? + if event.key() != QtCore.Qt.Key_Space: + return None + + if ( + index_flags & QtCore.Qt.ItemIsUserCheckable + and index_flags & ITEM_IS_USER_TRISTATE + ): + return (checkstate_enum_to_int(state) + 1) % 3 + + if index_flags & QtCore.Qt.ItemIsUserCheckable: + # toggle the current items check state + if state != QtCore.Qt.Checked: + return CHECKED_INT + return UNCHECKED_INT + return None diff --git a/client/ayon_core/tools/loader/ui/products_delegates.py b/client/ayon_core/tools/loader/ui/products_delegates.py index cedac6199b..9753da37af 100644 --- a/client/ayon_core/tools/loader/ui/products_delegates.py +++ b/client/ayon_core/tools/loader/ui/products_delegates.py @@ -1,4 +1,7 @@ import numbers +import uuid +from typing import Dict + from qtpy import QtWidgets, QtCore, QtGui from ayon_core.tools.utils.lib import format_version @@ -15,31 +18,21 @@ from .products_model import ( SYNC_REMOTE_SITE_AVAILABILITY, ) +STATUS_NAME_ROLE = QtCore.Qt.UserRole + 1 -class VersionComboBox(QtWidgets.QComboBox): - value_changed = QtCore.Signal(str) - def __init__(self, product_id, parent): - super(VersionComboBox, self).__init__(parent) - self._product_id = product_id +class VersionsModel(QtGui.QStandardItemModel): + def __init__(self): + super().__init__() self._items_by_id = {} - self._current_id = None - - self.currentIndexChanged.connect(self._on_index_change) - - def update_versions(self, version_items, current_version_id): - model = self.model() - root_item = model.invisibleRootItem() - version_items = list(reversed(version_items)) - version_ids = [ + def update_versions(self, version_items): + version_ids = { version_item.version_id for version_item in version_items - ] - if current_version_id not in version_ids and version_ids: - current_version_id = version_ids[0] - self._current_id = current_version_id + } + root_item = self.invisibleRootItem() to_remove = set(self._items_by_id.keys()) - set(version_ids) for item_id in to_remove: item = self._items_by_id.pop(item_id) @@ -54,13 +47,89 @@ class VersionComboBox(QtWidgets.QComboBox): item = QtGui.QStandardItem(label) item.setData(version_id, QtCore.Qt.UserRole) self._items_by_id[version_id] = item + item.setData(version_item.status, STATUS_NAME_ROLE) if item.row() != idx: root_item.insertRow(idx, item) + +class VersionsFilterModel(QtCore.QSortFilterProxyModel): + def __init__(self): + super().__init__() + self._status_filter = None + + def filterAcceptsRow(self, row, parent): + if self._status_filter is None: + return True + + if not self._status_filter: + return False + + index = self.sourceModel().index(row, 0, parent) + status = index.data(STATUS_NAME_ROLE) + return status in self._status_filter + + def set_statuses_filter(self, status_names): + if self._status_filter == status_names: + return + self._status_filter = status_names + self.invalidateFilter() + + +class VersionComboBox(QtWidgets.QComboBox): + value_changed = QtCore.Signal(str, str) + + def __init__(self, product_id, parent): + super().__init__(parent) + + versions_model = VersionsModel() + proxy_model = VersionsFilterModel() + proxy_model.setSourceModel(versions_model) + + self.setModel(proxy_model) + + self._product_id = product_id + self._items_by_id = {} + + self._current_id = None + + self._versions_model = versions_model + self._proxy_model = proxy_model + + self.currentIndexChanged.connect(self._on_index_change) + + def get_product_id(self): + return self._product_id + + def set_statuses_filter(self, status_names): + self._proxy_model.set_statuses_filter(status_names) + if self.count() == 0: + return + if self.currentIndex() != 0: + self.setCurrentIndex(0) + + def all_versions_filtered_out(self): + if self._items_by_id: + return self.count() == 0 + return False + + def update_versions(self, version_items, current_version_id): + self.blockSignals(True) + version_items = list(version_items) + version_ids = [ + version_item.version_id + for version_item in version_items + ] + if current_version_id not in version_ids and version_ids: + current_version_id = version_ids[0] + self._current_id = current_version_id + + self._versions_model.update_versions(version_items) + index = version_ids.index(current_version_id) if self.currentIndex() != index: self.setCurrentIndex(index) + self.blockSignals(False) def _on_index_change(self): idx = self.currentIndex() @@ -68,23 +137,30 @@ class VersionComboBox(QtWidgets.QComboBox): if value == self._current_id: return self._current_id = value - self.value_changed.emit(self._product_id) + self.value_changed.emit(self._product_id, value) class VersionDelegate(QtWidgets.QStyledItemDelegate): """A delegate that display version integer formatted as version string.""" - version_changed = QtCore.Signal() + version_changed = QtCore.Signal(str, str) def __init__(self, *args, **kwargs): - super(VersionDelegate, self).__init__(*args, **kwargs) - self._editor_by_product_id = {} + super().__init__(*args, **kwargs) + + self._editor_by_id: Dict[str, VersionComboBox] = {} + self._statuses_filter = None def displayText(self, value, locale): if not isinstance(value, numbers.Integral): return "N/A" return format_version(value) + def set_statuses_filter(self, status_names): + self._statuses_filter = set(status_names) + for widget in self._editor_by_id.values(): + widget.set_statuses_filter(status_names) + def paint(self, painter, option, index): fg_color = index.data(QtCore.Qt.ForegroundRole) if fg_color: @@ -142,27 +218,27 @@ class VersionDelegate(QtWidgets.QStyledItemDelegate): if not product_id: return + item_id = uuid.uuid4().hex + editor = VersionComboBox(product_id, parent) - self._editor_by_product_id[product_id] = editor + editor.setProperty("itemId", item_id) + editor.value_changed.connect(self._on_editor_change) + editor.destroyed.connect(self._on_destroy) + + self._editor_by_id[item_id] = editor return editor - def _on_editor_change(self, product_id): - editor = self._editor_by_product_id[product_id] - - # Update model data - self.commitData.emit(editor) - # Display model data - self.version_changed.emit() - def setEditorData(self, editor, index): editor.clear() # Current value of the index versions = index.data(VERSION_NAME_EDIT_ROLE) or [] version_id = index.data(VERSION_ID_ROLE) + editor.update_versions(versions, version_id) + editor.set_statuses_filter(self._statuses_filter) def setModelData(self, editor, model, index): """Apply the integer version back in the model""" @@ -170,6 +246,13 @@ class VersionDelegate(QtWidgets.QStyledItemDelegate): version_id = editor.itemData(editor.currentIndex()) model.setData(index, version_id, VERSION_NAME_EDIT_ROLE) + def _on_editor_change(self, product_id, version_id): + self.version_changed.emit(product_id, version_id) + + def _on_destroy(self, obj): + item_id = obj.property("itemId") + self._editor_by_id.pop(item_id, None) + class LoadedInSceneDelegate(QtWidgets.QStyledItemDelegate): """Delegate for Loaded in Scene state columns. diff --git a/client/ayon_core/tools/loader/ui/products_model.py b/client/ayon_core/tools/loader/ui/products_model.py index 6e36317da2..bc24d4d7f7 100644 --- a/client/ayon_core/tools/loader/ui/products_model.py +++ b/client/ayon_core/tools/loader/ui/products_model.py @@ -39,6 +39,8 @@ REPRESENTATIONS_COUNT_ROLE = QtCore.Qt.UserRole + 28 SYNC_ACTIVE_SITE_AVAILABILITY = QtCore.Qt.UserRole + 29 SYNC_REMOTE_SITE_AVAILABILITY = QtCore.Qt.UserRole + 30 +STATUS_NAME_FILTER_ROLE = QtCore.Qt.UserRole + 31 + class ProductsModel(QtGui.QStandardItemModel): refreshed = QtCore.Signal() @@ -105,7 +107,7 @@ class ProductsModel(QtGui.QStandardItemModel): } def __init__(self, controller): - super(ProductsModel, self).__init__() + super().__init__() self.setColumnCount(len(self.column_labels)) for idx, label in enumerate(self.column_labels): self.setHeaderData(idx, QtCore.Qt.Horizontal, label) @@ -130,7 +132,7 @@ class ProductsModel(QtGui.QStandardItemModel): def get_product_item_indexes(self): return [ - item.index() + self.indexFromItem(item) for item in self._items_by_id.values() ] @@ -146,12 +148,26 @@ class ProductsModel(QtGui.QStandardItemModel): return self._product_items_by_id.get(product_id) + def set_product_version(self, product_id, version_id): + if version_id is None: + return + + product_item = self._items_by_id.get(product_id) + if product_item is None: + return + + index = self.indexFromItem(product_item) + self.setData(index, version_id, VERSION_NAME_EDIT_ROLE) + def set_enable_grouping(self, enable_grouping): if enable_grouping is self._grouping_enabled: return self._grouping_enabled = enable_grouping # Ignore change if groups are not available - self.refresh(self._last_project_name, self._last_folder_ids) + self.refresh( + self._last_project_name, + self._last_folder_ids + ) def flags(self, index): # Make the version column editable @@ -163,7 +179,7 @@ class ProductsModel(QtGui.QStandardItemModel): ) if index.column() != 0: index = self.index(index.row(), 0, index.parent()) - return super(ProductsModel, self).flags(index) + return super().flags(index) def data(self, index, role=None): if role is None: @@ -190,7 +206,7 @@ class ProductsModel(QtGui.QStandardItemModel): return self._get_status_icon(status_name) if col == 0: - return super(ProductsModel, self).data(index, role) + return super().data(index, role) if role == QtCore.Qt.DecorationRole: if col == 1: @@ -223,7 +239,7 @@ class ProductsModel(QtGui.QStandardItemModel): index = self.index(index.row(), 0, index.parent()) - return super(ProductsModel, self).data(index, role) + return super().data(index, role) def setData(self, index, value, role=None): if not index.isValid(): @@ -255,7 +271,7 @@ class ProductsModel(QtGui.QStandardItemModel): self._set_version_data_to_product_item(item, final_version_item) self.version_changed.emit() return True - return super(ProductsModel, self).setData(index, value, role) + return super().setData(index, value, role) def _get_next_color(self): return next(self._color_iterator) @@ -349,11 +365,10 @@ class ProductsModel(QtGui.QStandardItemModel): representation count by version id. sync_availability_by_version_id (Optional[str, Tuple[int, int]]): Mapping of sync availability by version id. - """ + """ model_item.setData(version_item.version_id, VERSION_ID_ROLE) model_item.setData(version_item.version, VERSION_NAME_ROLE) - model_item.setData(version_item.version_id, VERSION_ID_ROLE) model_item.setData(version_item.is_hero, VERSION_HERO_ROLE) model_item.setData( version_item.published_time, VERSION_PUBLISH_TIME_ROLE @@ -396,11 +411,15 @@ class ProductsModel(QtGui.QStandardItemModel): remote_site_icon, repre_count_by_version_id, sync_availability_by_version_id, + last_version_by_product_id, ): model_item = self._items_by_id.get(product_item.product_id) - versions = list(product_item.version_items.values()) - versions.sort() - last_version = versions[-1] + last_version = last_version_by_product_id[product_item.product_id] + + statuses = { + version_item.status + for version_item in product_item.version_items.values() + } if model_item is None: product_id = product_item.product_id model_item = QtGui.QStandardItem(product_item.product_name) @@ -418,6 +437,7 @@ class ProductsModel(QtGui.QStandardItemModel): self._product_items_by_id[product_id] = product_item self._items_by_id[product_id] = model_item + model_item.setData("|".join(statuses), STATUS_NAME_FILTER_ROLE) model_item.setData(product_item.folder_label, FOLDER_LABEL_ROLE) in_scene = 1 if product_item.product_in_scene else 0 model_item.setData(in_scene, PRODUCT_IN_SCENE_ROLE) @@ -466,16 +486,19 @@ class ProductsModel(QtGui.QStandardItemModel): product_item.product_id: product_item for product_item in product_items } - last_version_id_by_product_id = {} + last_version_by_product_id = {} for product_item in product_items: versions = list(product_item.version_items.values()) versions.sort() last_version = versions[-1] - last_version_id_by_product_id[product_item.product_id] = ( - last_version.version_id + last_version_by_product_id[product_item.product_id] = ( + last_version ) - version_ids = set(last_version_id_by_product_id.values()) + version_ids = { + version_item.version_id + for version_item in last_version_by_product_id.values() + } repre_count_by_version_id = self._controller.get_versions_representation_count( project_name, version_ids ) @@ -494,10 +517,7 @@ class ProductsModel(QtGui.QStandardItemModel): product_name = product_item.product_name group = product_name_matches_by_group[group_name] - if product_name not in group: - group[product_name] = [product_item] - continue - group[product_name].append(product_item) + group.setdefault(product_name, []).append(product_item) group_names = set(product_name_matches_by_group.keys()) @@ -513,8 +533,16 @@ class ProductsModel(QtGui.QStandardItemModel): merged_product_items = {} top_items = [] group_product_types = set() + group_status_names = set() for product_name, product_items in groups.items(): group_product_types |= {p.product_type for p in product_items} + for product_item in product_items: + group_status_names |= { + version_item.status + for version_item in product_item.version_items.values() + } + group_product_types.add(product_item.product_type) + if len(product_items) == 1: top_items.append(product_items[0]) else: @@ -529,7 +557,13 @@ class ProductsModel(QtGui.QStandardItemModel): if group_name: parent_item = self._get_group_model_item(group_name) parent_item.setData( - "|".join(group_product_types), PRODUCT_TYPE_ROLE) + "|".join(group_product_types), + PRODUCT_TYPE_ROLE + ) + parent_item.setData( + "|".join(group_status_names), + STATUS_NAME_FILTER_ROLE + ) new_items = [] if parent_item is not None and parent_item.row() < 0: @@ -542,6 +576,7 @@ class ProductsModel(QtGui.QStandardItemModel): remote_site_icon, repre_count_by_version_id, sync_availability_by_version_id, + last_version_by_product_id, ) new_items.append(item) @@ -549,13 +584,15 @@ class ProductsModel(QtGui.QStandardItemModel): product_name, product_items = path_info (merged_color_hex, merged_color_qt) = self._get_next_color() merged_color = qtawesome.icon( - "fa.circle", color=merged_color_qt) + "fa.circle", color=merged_color_qt + ) merged_item = self._get_merged_model_item( product_name, len(product_items), merged_color_hex) merged_item.setData(merged_color, QtCore.Qt.DecorationRole) new_items.append(merged_item) merged_product_types = set() + merged_status_names = set() new_merged_items = [] for product_item in product_items: item = self._get_product_model_item( @@ -564,12 +601,25 @@ class ProductsModel(QtGui.QStandardItemModel): remote_site_icon, repre_count_by_version_id, sync_availability_by_version_id, + last_version_by_product_id, ) new_merged_items.append(item) merged_product_types.add(product_item.product_type) + merged_status_names |= { + version_item.status + for version_item in ( + product_item.version_items.values() + ) + } merged_item.setData( - "|".join(merged_product_types), PRODUCT_TYPE_ROLE) + "|".join(merged_product_types), + PRODUCT_TYPE_ROLE + ) + merged_item.setData( + "|".join(merged_status_names), + STATUS_NAME_FILTER_ROLE + ) if new_merged_items: merged_item.appendRows(new_merged_items) diff --git a/client/ayon_core/tools/loader/ui/products_widget.py b/client/ayon_core/tools/loader/ui/products_widget.py index 61ddd690e9..748a1b5fb8 100644 --- a/client/ayon_core/tools/loader/ui/products_widget.py +++ b/client/ayon_core/tools/loader/ui/products_widget.py @@ -22,6 +22,7 @@ from .products_model import ( VERSION_STATUS_COLOR_ROLE, VERSION_STATUS_ICON_ROLE, VERSION_THUMBNAIL_ID_ROLE, + STATUS_NAME_FILTER_ROLE, ) from .products_delegates import ( VersionDelegate, @@ -33,18 +34,31 @@ from .actions_utils import show_actions_menu class ProductsProxyModel(RecursiveSortFilterProxyModel): def __init__(self, parent=None): - super(ProductsProxyModel, self).__init__(parent) + super().__init__(parent) self._product_type_filters = {} + self._statuses_filter = None self._ascending_sort = True + def get_statuses_filter(self): + if self._statuses_filter is None: + return None + return set(self._statuses_filter) + def set_product_type_filters(self, product_type_filters): self._product_type_filters = product_type_filters self.invalidateFilter() + def set_statuses_filter(self, statuses_filter): + if self._statuses_filter == statuses_filter: + return + self._statuses_filter = statuses_filter + self.invalidateFilter() + def filterAcceptsRow(self, source_row, source_parent): source_model = self.sourceModel() index = source_model.index(source_row, 0, source_parent) + product_types_s = source_model.data(index, PRODUCT_TYPE_ROLE) product_types = [] if product_types_s: @@ -53,8 +67,22 @@ class ProductsProxyModel(RecursiveSortFilterProxyModel): for product_type in product_types: if not self._product_type_filters.get(product_type, True): return False - return super(ProductsProxyModel, self).filterAcceptsRow( - source_row, source_parent) + + if not self._accept_row_by_statuses(index): + return False + return super().filterAcceptsRow(source_row, source_parent) + + def _accept_row_by_statuses(self, index): + if self._statuses_filter is None: + return True + if not self._statuses_filter: + return False + + status_s = index.data(STATUS_NAME_FILTER_ROLE) + for status in status_s.split("|"): + if status in self._statuses_filter: + return True + return False def lessThan(self, left, right): l_model = left.model() @@ -74,20 +102,19 @@ class ProductsProxyModel(RecursiveSortFilterProxyModel): if not self._ascending_sort: output = not output return output - return super(ProductsProxyModel, self).lessThan(left, right) + return super().lessThan(left, right) def sort(self, column, order=None): if order is None: order = QtCore.Qt.AscendingOrder self._ascending_sort = order == QtCore.Qt.AscendingOrder - super(ProductsProxyModel, self).sort(column, order) + super().sort(column, order) class ProductsWidget(QtWidgets.QWidget): refreshed = QtCore.Signal() merged_products_selection_changed = QtCore.Signal() selection_changed = QtCore.Signal() - version_changed = QtCore.Signal() default_widths = ( 200, # Product name 90, # Product type @@ -159,11 +186,15 @@ class ProductsWidget(QtWidgets.QWidget): products_proxy_model.rowsInserted.connect(self._on_rows_inserted) products_proxy_model.rowsMoved.connect(self._on_rows_moved) products_model.refreshed.connect(self._on_refresh) + products_model.version_changed.connect(self._on_version_change) products_view.customContextMenuRequested.connect( self._on_context_menu) - products_view.selectionModel().selectionChanged.connect( + products_view_sel_model = products_view.selectionModel() + products_view_sel_model.selectionChanged.connect( self._on_selection_change) - products_model.version_changed.connect(self._on_version_change) + version_delegate.version_changed.connect( + self._on_version_delegate_change + ) controller.register_event_callback( "selection.folders.changed", @@ -211,10 +242,20 @@ class ProductsWidget(QtWidgets.QWidget): Args: name (str): The string filter. - """ + """ self._products_proxy_model.setFilterFixedString(name) + def set_statuses_filter(self, status_names): + """Set filter of version statuses. + + Args: + status_names (list[str]): The list of status names. + + """ + self._version_delegate.set_statuses_filter(status_names) + self._products_proxy_model.set_statuses_filter(status_names) + def set_product_type_filter(self, product_type_filters): """ @@ -403,6 +444,9 @@ class ProductsWidget(QtWidgets.QWidget): def _on_version_change(self): self._on_selection_change() + def _on_version_delegate_change(self, product_id, version_id): + self._products_model.set_product_version(product_id, version_id) + def _on_folders_selection_change(self, event): project_name = event["project_name"] sitesync_enabled = self._controller.is_sitesync_enabled( diff --git a/client/ayon_core/tools/loader/ui/statuses_combo.py b/client/ayon_core/tools/loader/ui/statuses_combo.py new file mode 100644 index 0000000000..9fe7ab62a5 --- /dev/null +++ b/client/ayon_core/tools/loader/ui/statuses_combo.py @@ -0,0 +1,331 @@ +from typing import List, Dict + +from qtpy import QtCore, QtGui + +from ayon_core.tools.utils import get_qt_icon +from ayon_core.tools.common_models import StatusItem + +from ._multicombobox import ( + CustomPaintMultiselectComboBox, + STANDARD_ITEM_TYPE, +) + +STATUS_ITEM_TYPE = 0 +SELECT_ALL_TYPE = 1 +DESELECT_ALL_TYPE = 2 +SWAP_STATE_TYPE = 3 + +STATUSES_FILTER_SENDER = "loader.statuses_filter" +STATUS_NAME_ROLE = QtCore.Qt.UserRole + 1 +STATUS_SHORT_ROLE = QtCore.Qt.UserRole + 2 +STATUS_COLOR_ROLE = QtCore.Qt.UserRole + 3 +STATUS_ICON_ROLE = QtCore.Qt.UserRole + 4 +ITEM_TYPE_ROLE = QtCore.Qt.UserRole + 5 +ITEM_SUBTYPE_ROLE = QtCore.Qt.UserRole + 6 + + +class StatusesQtModel(QtGui.QStandardItemModel): + def __init__(self, controller): + self._controller = controller + self._items_by_name: Dict[str, QtGui.QStandardItem] = {} + self._icons_by_name_n_color: Dict[str, QtGui.QIcon] = {} + self._last_project = None + + self._select_project_item = None + self._empty_statuses_item = None + + self._select_all_item = None + self._deselect_all_item = None + self._swap_states_item = None + + super().__init__() + + self.refresh(None) + + def get_placeholder_text(self): + return self._placeholder + + def refresh(self, project_name): + # New project was selected + # status filter is reset to show all statuses + uncheck_all = False + if project_name != self._last_project: + self._last_project = project_name + uncheck_all = True + + if project_name is None: + self._add_select_project_item() + return + + status_items: List[StatusItem] = ( + self._controller.get_project_status_items( + project_name, sender=STATUSES_FILTER_SENDER + ) + ) + if not status_items: + self._add_empty_statuses_item() + return + + self._remove_empty_items() + + items_to_remove = set(self._items_by_name) + root_item = self.invisibleRootItem() + for row_idx, status_item in enumerate(status_items): + name = status_item.name + if name in self._items_by_name: + is_new = False + item = self._items_by_name[name] + if uncheck_all: + item.setCheckState(QtCore.Qt.Unchecked) + items_to_remove.discard(name) + else: + is_new = True + item = QtGui.QStandardItem() + item.setData(ITEM_SUBTYPE_ROLE, STATUS_ITEM_TYPE) + item.setCheckState(QtCore.Qt.Unchecked) + item.setFlags( + QtCore.Qt.ItemIsEnabled + | QtCore.Qt.ItemIsSelectable + | QtCore.Qt.ItemIsUserCheckable + ) + self._items_by_name[name] = item + + icon = self._get_icon(status_item) + for role, value in ( + (STATUS_NAME_ROLE, status_item.name), + (STATUS_SHORT_ROLE, status_item.short), + (STATUS_COLOR_ROLE, status_item.color), + (STATUS_ICON_ROLE, icon), + ): + if item.data(role) != value: + item.setData(value, role) + + if is_new: + root_item.insertRow(row_idx, item) + + for name in items_to_remove: + item = self._items_by_name.pop(name) + root_item.removeRow(item.row()) + + self._add_selection_items() + + def setData(self, index, value, role): + if role == QtCore.Qt.CheckStateRole and index.isValid(): + item_type = index.data(ITEM_SUBTYPE_ROLE) + if item_type == SELECT_ALL_TYPE: + for item in self._items_by_name.values(): + item.setCheckState(QtCore.Qt.Checked) + return True + if item_type == DESELECT_ALL_TYPE: + for item in self._items_by_name.values(): + item.setCheckState(QtCore.Qt.Unchecked) + return True + if item_type == SWAP_STATE_TYPE: + for item in self._items_by_name.values(): + current_state = item.checkState() + item.setCheckState( + QtCore.Qt.Checked + if current_state == QtCore.Qt.Unchecked + else QtCore.Qt.Unchecked + ) + return True + return super().setData(index, value, role) + + def _get_icon(self, status_item: StatusItem) -> QtGui.QIcon: + name = status_item.name + color = status_item.color + unique_id = "|".join([name or "", color or ""]) + icon = self._icons_by_name_n_color.get(unique_id) + if icon is not None: + return icon + + icon: QtGui.QIcon = get_qt_icon({ + "type": "material-symbols", + "name": status_item.icon, + "color": status_item.color + }) + self._icons_by_name_n_color[unique_id] = icon + return icon + + def _init_default_items(self): + if self._empty_statuses_item is not None: + return + + empty_statuses_item = QtGui.QStandardItem("No statuses...") + select_project_item = QtGui.QStandardItem("Select project...") + + select_all_item = QtGui.QStandardItem("Select all") + deselect_all_item = QtGui.QStandardItem("Deselect all") + swap_states_item = QtGui.QStandardItem("Swap") + + for item in ( + empty_statuses_item, + select_project_item, + select_all_item, + deselect_all_item, + swap_states_item, + ): + item.setData(STANDARD_ITEM_TYPE, ITEM_TYPE_ROLE) + + select_all_item.setIcon(get_qt_icon({ + "type": "material-symbols", + "name": "done_all", + "color": "white" + })) + deselect_all_item.setIcon(get_qt_icon({ + "type": "material-symbols", + "name": "remove_done", + "color": "white" + })) + swap_states_item.setIcon(get_qt_icon({ + "type": "material-symbols", + "name": "swap_horiz", + "color": "white" + })) + + for item in ( + empty_statuses_item, + select_project_item, + ): + item.setFlags(QtCore.Qt.NoItemFlags) + + for item, item_type in ( + (select_all_item, SELECT_ALL_TYPE), + (deselect_all_item, DESELECT_ALL_TYPE), + (swap_states_item, SWAP_STATE_TYPE), + ): + item.setData(item_type, ITEM_SUBTYPE_ROLE) + + for item in ( + select_all_item, + deselect_all_item, + swap_states_item, + ): + item.setFlags( + QtCore.Qt.ItemIsEnabled + | QtCore.Qt.ItemIsSelectable + | QtCore.Qt.ItemIsUserCheckable + ) + + self._empty_statuses_item = empty_statuses_item + self._select_project_item = select_project_item + + self._select_all_item = select_all_item + self._deselect_all_item = deselect_all_item + self._swap_states_item = swap_states_item + + def _get_empty_statuses_item(self): + self._init_default_items() + return self._empty_statuses_item + + def _get_select_project_item(self): + self._init_default_items() + return self._select_project_item + + def _get_empty_items(self): + self._init_default_items() + return [ + self._empty_statuses_item, + self._select_project_item, + ] + + def _get_selection_items(self): + self._init_default_items() + return [ + self._select_all_item, + self._deselect_all_item, + self._swap_states_item, + ] + + def _get_default_items(self): + return self._get_empty_items() + self._get_selection_items() + + def _add_select_project_item(self): + item = self._get_select_project_item() + if item.row() < 0: + self._remove_items() + root_item = self.invisibleRootItem() + root_item.appendRow(item) + + def _add_empty_statuses_item(self): + item = self._get_empty_statuses_item() + if item.row() < 0: + self._remove_items() + root_item = self.invisibleRootItem() + root_item.appendRow(item) + + def _add_selection_items(self): + root_item = self.invisibleRootItem() + items = self._get_selection_items() + for item in self._get_selection_items(): + row = item.row() + if row >= 0: + root_item.takeRow(row) + root_item.appendRows(items) + + def _remove_items(self): + root_item = self.invisibleRootItem() + for item in self._get_default_items(): + if item.row() < 0: + continue + root_item.takeRow(item.row()) + + root_item.removeRows(0, root_item.rowCount()) + self._items_by_name.clear() + + def _remove_empty_items(self): + root_item = self.invisibleRootItem() + for item in self._get_empty_items(): + if item.row() < 0: + continue + root_item.takeRow(item.row()) + + +class StatusesCombobox(CustomPaintMultiselectComboBox): + def __init__(self, controller, parent): + self._controller = controller + model = StatusesQtModel(controller) + super().__init__( + STATUS_NAME_ROLE, + STATUS_SHORT_ROLE, + STATUS_COLOR_ROLE, + STATUS_ICON_ROLE, + item_type_role=ITEM_TYPE_ROLE, + model=model, + parent=parent + ) + self.set_placeholder_text("Version status filter...") + self._model = model + self._last_project_name = None + self._fully_disabled_filter = False + + controller.register_event_callback( + "selection.project.changed", + self._on_project_change + ) + controller.register_event_callback( + "projects.refresh.finished", + self._on_projects_refresh + ) + self.setToolTip("Statuses filter") + self.value_changed.connect( + self._on_status_filter_change + ) + + def _on_status_filter_change(self): + lines = ["Statuses filter"] + for item in self.get_value_info(): + status_name, enabled = item + lines.append(f"{'✔' if enabled else '☐'} {status_name}") + + self.setToolTip("\n".join(lines)) + + def _on_project_change(self, event): + project_name = event["project_name"] + self._last_project_name = project_name + self._model.refresh(project_name) + + def _on_projects_refresh(self): + if self._last_project_name: + self._model.refresh(self._last_project_name) + self._on_status_filter_change() diff --git a/client/ayon_core/tools/loader/ui/window.py b/client/ayon_core/tools/loader/ui/window.py index 8529a53b06..58af6f0b1f 100644 --- a/client/ayon_core/tools/loader/ui/window.py +++ b/client/ayon_core/tools/loader/ui/window.py @@ -19,6 +19,7 @@ from .product_types_widget import ProductTypesView from .product_group_dialog import ProductGroupDialog from .info_widget import InfoWidget from .repres_widget import RepresentationsWidget +from .statuses_combo import StatusesCombobox class LoadErrorMessageBox(ErrorMessageBox): @@ -183,6 +184,9 @@ class LoaderWindow(QtWidgets.QWidget): products_filter_input = PlaceholderLineEdit(products_inputs_widget) products_filter_input.setPlaceholderText("Product name filter...") + + product_status_filter_combo = StatusesCombobox(controller, self) + product_group_checkbox = QtWidgets.QCheckBox( "Enable grouping", products_inputs_widget) product_group_checkbox.setChecked(True) @@ -192,6 +196,7 @@ class LoaderWindow(QtWidgets.QWidget): products_inputs_layout = QtWidgets.QHBoxLayout(products_inputs_widget) products_inputs_layout.setContentsMargins(0, 0, 0, 0) products_inputs_layout.addWidget(products_filter_input, 1) + products_inputs_layout.addWidget(product_status_filter_combo, 1) products_inputs_layout.addWidget(product_group_checkbox, 0) products_wrap_layout = QtWidgets.QVBoxLayout(products_wrap_widget) @@ -245,6 +250,9 @@ class LoaderWindow(QtWidgets.QWidget): products_filter_input.textChanged.connect( self._on_product_filter_change ) + product_status_filter_combo.value_changed.connect( + self._on_status_filter_change + ) product_group_checkbox.stateChanged.connect( self._on_product_group_change ) @@ -299,6 +307,7 @@ class LoaderWindow(QtWidgets.QWidget): self._product_types_widget = product_types_widget self._products_filter_input = products_filter_input + self._product_status_filter_combo = product_status_filter_combo self._product_group_checkbox = product_group_checkbox self._products_widget = products_widget @@ -412,6 +421,10 @@ class LoaderWindow(QtWidgets.QWidget): def _on_product_filter_change(self, text): self._products_widget.set_name_filter(text) + def _on_status_filter_change(self): + status_names = self._product_status_filter_combo.get_value() + self._products_widget.set_statuses_filter(status_names) + def _on_product_type_filter_change(self): self._products_widget.set_product_type_filter( self._product_types_widget.get_filter_info() diff --git a/client/ayon_core/tools/publisher/abstract.py b/client/ayon_core/tools/publisher/abstract.py index a9142396f5..768f4b052f 100644 --- a/client/ayon_core/tools/publisher/abstract.py +++ b/client/ayon_core/tools/publisher/abstract.py @@ -166,6 +166,12 @@ class AbstractPublisherBackend(AbstractPublisherCommon): ) -> Union[TaskItem, None]: pass + @abstractmethod + def get_project_entity( + self, project_name: str + ) -> Union[Dict[str, Any], None]: + pass + @abstractmethod def get_folder_entity( self, project_name: str, folder_id: str diff --git a/client/ayon_core/tools/publisher/control.py b/client/ayon_core/tools/publisher/control.py index f26f8fc524..257b45de08 100644 --- a/client/ayon_core/tools/publisher/control.py +++ b/client/ayon_core/tools/publisher/control.py @@ -193,6 +193,9 @@ class PublisherController( def get_convertor_items(self): return self._create_model.get_convertor_items() + def get_project_entity(self, project_name): + return self._projects_model.get_project_entity(project_name) + def get_folder_type_items(self, project_name, sender=None): return self._projects_model.get_folder_type_items( project_name, sender diff --git a/client/ayon_core/tools/publisher/models/create.py b/client/ayon_core/tools/publisher/models/create.py index 6da3a51a31..ab2bf07614 100644 --- a/client/ayon_core/tools/publisher/models/create.py +++ b/client/ayon_core/tools/publisher/models/create.py @@ -9,6 +9,7 @@ from ayon_core.lib.attribute_definitions import ( ) from ayon_core.lib.profiles_filtering import filter_profiles from ayon_core.lib.attribute_definitions import UIDef +from ayon_core.lib import is_func_signature_supported from ayon_core.pipeline.create import ( BaseCreator, AutoCreator, @@ -26,6 +27,7 @@ from ayon_core.tools.publisher.abstract import ( AbstractPublisherBackend, CardMessageTypes, ) + CREATE_EVENT_SOURCE = "publisher.create.model" @@ -356,13 +358,24 @@ class CreateModel: project_name, task_item.task_id ) - return creator.get_product_name( + project_entity = self._controller.get_project_entity(project_name) + args = ( project_name, folder_entity, task_entity, - variant, - instance=instance + variant ) + kwargs = { + "instance": instance, + "project_entity": project_entity, + } + # Backwards compatibility for 'project_entity' argument + # - 'get_product_name' signature changed 24/07/08 + if not is_func_signature_supported( + creator.get_product_name, *args, **kwargs + ): + kwargs.pop("project_entity") + return creator.get_product_name(*args, **kwargs) def create( self, diff --git a/client/ayon_core/tools/publisher/publish_report_viewer/window.py b/client/ayon_core/tools/publisher/publish_report_viewer/window.py index 3ee986e6f7..aedc3b9e31 100644 --- a/client/ayon_core/tools/publisher/publish_report_viewer/window.py +++ b/client/ayon_core/tools/publisher/publish_report_viewer/window.py @@ -1,6 +1,5 @@ import os import json -import six import uuid import appdirs @@ -387,7 +386,7 @@ class LoadedFilesModel(QtGui.QStandardItemModel): if not filepaths: return - if isinstance(filepaths, six.string_types): + if isinstance(filepaths, str): filepaths = [filepaths] filtered_paths = [] diff --git a/client/ayon_core/tools/stdout_broker/broker.py b/client/ayon_core/tools/stdout_broker/broker.py index 291936008b..c449fa7df9 100644 --- a/client/ayon_core/tools/stdout_broker/broker.py +++ b/client/ayon_core/tools/stdout_broker/broker.py @@ -8,7 +8,7 @@ from datetime import datetime import websocket from ayon_core.lib import Logger -from ayon_core.modules.webserver import HostMsgAction +from ayon_core.tools.tray import HostMsgAction log = Logger.get_logger(__name__) diff --git a/client/ayon_core/tools/tray/__init__.py b/client/ayon_core/tools/tray/__init__.py index 49130e660a..2e179f0620 100644 --- a/client/ayon_core/tools/tray/__init__.py +++ b/client/ayon_core/tools/tray/__init__.py @@ -1,6 +1,21 @@ -from .tray import main +from .structures import HostMsgAction +from .lib import ( + TrayState, + get_tray_state, + is_tray_running, + get_tray_server_url, + make_sure_tray_is_running, + main, +) __all__ = ( + "HostMsgAction", + + "TrayState", + "get_tray_state", + "is_tray_running", + "get_tray_server_url", + "make_sure_tray_is_running", "main", ) diff --git a/client/ayon_core/tools/tray/lib.py b/client/ayon_core/tools/tray/lib.py new file mode 100644 index 0000000000..c26f4835b1 --- /dev/null +++ b/client/ayon_core/tools/tray/lib.py @@ -0,0 +1,445 @@ +import os +import sys +import json +import hashlib +import platform +import subprocess +import csv +import time +import signal +import locale +from typing import Optional, Dict, Tuple, Any + +import ayon_api +import requests + +from ayon_core.lib import Logger, get_ayon_launcher_args, run_detached_process +from ayon_core.lib.local_settings import get_ayon_appdirs + + +class TrayState: + NOT_RUNNING = 0 + STARTING = 1 + RUNNING = 2 + + +class TrayIsRunningError(Exception): + pass + + +def _get_default_server_url() -> str: + """Get default AYON server url.""" + return os.getenv("AYON_SERVER_URL") + + +def _get_default_variant() -> str: + """Get default settings variant.""" + return ayon_api.get_default_settings_variant() + + +def _get_server_and_variant( + server_url: Optional[str] = None, + variant: Optional[str] = None +) -> Tuple[str, str]: + if not server_url: + server_url = _get_default_server_url() + if not variant: + variant = _get_default_variant() + return server_url, variant + + +def _windows_pid_is_running(pid: int) -> bool: + args = ["tasklist.exe", "/fo", "csv", "/fi", f"PID eq {pid}"] + output = subprocess.check_output(args) + encoding = locale.getpreferredencoding() + csv_content = csv.DictReader(output.decode(encoding).splitlines()) + # if "PID" not in csv_content.fieldnames: + # return False + for _ in csv_content: + return True + return False + + +def _is_process_running(pid: int) -> bool: + """Check whether process with pid is running.""" + if platform.system().lower() == "windows": + return _windows_pid_is_running(pid) + + if pid == 0: + return True + + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True + return True + + +def _kill_tray_process(pid: int): + if _is_process_running(pid): + os.kill(pid, signal.SIGTERM) + + +def _create_tray_hash(server_url: str, variant: str) -> str: + """Create tray hash for metadata filename. + + Args: + server_url (str): AYON server url. + variant (str): Settings variant. + + Returns: + str: Hash for metadata filename. + + """ + data = f"{server_url}|{variant}" + return hashlib.sha256(data.encode()).hexdigest() + + +def _wait_for_starting_tray( + server_url: Optional[str] = None, + variant: Optional[str] = None, + timeout: Optional[int] = None +) -> Optional[Dict[str, Any]]: + """Wait for tray to start. + + Args: + server_url (Optional[str]): AYON server url. + variant (Optional[str]): Settings variant. + timeout (Optional[int]): Timeout for tray validation. + + Returns: + Optional[Dict[str, Any]]: Tray file information. + + """ + if timeout is None: + timeout = 10 + started_at = time.time() + while True: + data = get_tray_file_info(server_url, variant) + if data is None: + return None + + if data.get("started") is True: + return data + + pid = data.get("pid") + if pid and not _is_process_running(pid): + remove_tray_server_url() + return None + + if time.time() - started_at > timeout: + return None + time.sleep(0.1) + + +def get_tray_storage_dir() -> str: + """Get tray storage directory. + + Returns: + str: Tray storage directory where metadata files are stored. + + """ + return get_ayon_appdirs("tray") + + +def _get_tray_information(tray_url: str) -> Optional[Dict[str, Any]]: + if not tray_url: + return None + try: + response = requests.get(f"{tray_url}/tray") + response.raise_for_status() + return response.json() + except (requests.HTTPError, requests.ConnectionError): + return None + + +def _get_tray_info_filepath( + server_url: Optional[str] = None, + variant: Optional[str] = None +) -> str: + hash_dir = get_tray_storage_dir() + server_url, variant = _get_server_and_variant(server_url, variant) + filename = _create_tray_hash(server_url, variant) + return os.path.join(hash_dir, filename) + + +def get_tray_file_info( + server_url: Optional[str] = None, + variant: Optional[str] = None +) -> Optional[Dict[str, Any]]: + """Get tray information from file. + + Metadata information about running tray that should contain tray + server url. + + Args: + server_url (Optional[str]): AYON server url. + variant (Optional[str]): Settings variant. + + Returns: + Optional[Dict[str, Any]]: Tray information. + + """ + filepath = _get_tray_info_filepath(server_url, variant) + if not os.path.exists(filepath): + return None + try: + with open(filepath, "r") as stream: + data = json.load(stream) + except Exception: + return None + return data + + +def get_tray_server_url( + validate: Optional[bool] = False, + server_url: Optional[str] = None, + variant: Optional[str] = None, + timeout: Optional[int] = None +) -> Optional[str]: + """Get tray server url. + + Does not validate if tray is running. + + Args: + server_url (Optional[str]): AYON server url. + variant (Optional[str]): Settings variant. + validate (Optional[bool]): Validate if tray is running. + By default, does not validate. + timeout (Optional[int]): Timeout for tray start-up. + + Returns: + Optional[str]: Tray server url. + + """ + data = get_tray_file_info(server_url, variant) + if data is None: + return None + + if data.get("started") is False: + data = _wait_for_starting_tray(server_url, variant, timeout) + if data is None: + return None + + url = data.get("url") + if not url: + return None + + if not validate: + return url + + if _get_tray_information(url): + return url + return None + + +def set_tray_server_url(tray_url: Optional[str], started: bool): + """Add tray server information file. + + Called from tray logic, do not use on your own. + + Args: + tray_url (Optional[str]): Webserver url with port. + started (bool): If tray is started. When set to 'False' it means + that tray is starting up. + + """ + file_info = get_tray_file_info() + if file_info and file_info["pid"] != os.getpid(): + if not file_info["started"] or _get_tray_information(file_info["url"]): + raise TrayIsRunningError("Tray is already running.") + + filepath = _get_tray_info_filepath() + os.makedirs(os.path.dirname(filepath), exist_ok=True) + data = { + "url": tray_url, + "pid": os.getpid(), + "started": started + } + with open(filepath, "w") as stream: + json.dump(data, stream) + + +def remove_tray_server_url(force: Optional[bool] = False): + """Remove tray information file. + + Called from tray logic, do not use on your own. + + Args: + force (Optional[bool]): Force remove tray information file. + + """ + filepath = _get_tray_info_filepath() + if not os.path.exists(filepath): + return + + try: + with open(filepath, "r") as stream: + data = json.load(stream) + except BaseException: + data = {} + + if ( + force + or not data + or data.get("pid") == os.getpid() + or not _is_process_running(data.get("pid")) + ): + os.remove(filepath) + + +def get_tray_information( + server_url: Optional[str] = None, + variant: Optional[str] = None +) -> Optional[Dict[str, Any]]: + """Get information about tray. + + Args: + server_url (Optional[str]): AYON server url. + variant (Optional[str]): Settings variant. + + Returns: + Optional[Dict[str, Any]]: Tray information. + + """ + tray_url = get_tray_server_url(server_url, variant) + return _get_tray_information(tray_url) + + +def get_tray_state( + server_url: Optional[str] = None, + variant: Optional[str] = None +) -> int: + """Get tray state for AYON server and variant. + + Args: + server_url (Optional[str]): AYON server url. + variant (Optional[str]): Settings variant. + + Returns: + int: Tray state. + + """ + file_info = get_tray_file_info(server_url, variant) + if file_info is None: + return TrayState.NOT_RUNNING + + if file_info.get("started") is False: + return TrayState.STARTING + + tray_url = file_info.get("url") + info = _get_tray_information(tray_url) + if not info: + # Remove the information as the tray is not running + remove_tray_server_url(force=True) + return TrayState.NOT_RUNNING + return TrayState.RUNNING + + +def is_tray_running( + server_url: Optional[str] = None, + variant: Optional[str] = None +) -> bool: + """Check if tray is running. + + Args: + server_url (Optional[str]): AYON server url. + variant (Optional[str]): Settings variant. + + Returns: + bool: True if tray is running + + """ + state = get_tray_state(server_url, variant) + return state != TrayState.NOT_RUNNING + + +def make_sure_tray_is_running( + ayon_url: Optional[str] = None, + variant: Optional[str] = None, + env: Optional[Dict[str, str]] = None +): + """Make sure that tray for AYON url and variant is running. + + Args: + ayon_url (Optional[str]): AYON server url. + variant (Optional[str]): Settings variant. + env (Optional[Dict[str, str]]): Environment variables for the process. + + """ + state = get_tray_state(ayon_url, variant) + if state == TrayState.RUNNING: + return + + if state == TrayState.STARTING: + _wait_for_starting_tray(ayon_url, variant) + state = get_tray_state(ayon_url, variant) + if state == TrayState.RUNNING: + return + + args = get_ayon_launcher_args("tray", "--force") + if env is None: + env = os.environ.copy() + + # Make sure 'QT_API' is not set + env.pop("QT_API", None) + + if ayon_url: + env["AYON_SERVER_URL"] = ayon_url + + # TODO maybe handle variant in a better way + if variant: + if variant == "staging": + args.append("--use-staging") + + run_detached_process(args, env=env) + + +def main(force=False): + from ayon_core.tools.tray.ui import main + + Logger.set_process_name("Tray") + + state = get_tray_state() + if force and state in (TrayState.RUNNING, TrayState.STARTING): + file_info = get_tray_file_info() or {} + pid = file_info.get("pid") + if pid is not None: + _kill_tray_process(pid) + remove_tray_server_url(force=True) + state = TrayState.NOT_RUNNING + + if state == TrayState.RUNNING: + print("Tray is already running.") + return + + if state == TrayState.STARTING: + print("Tray is starting. Waiting for it to start.") + _wait_for_starting_tray() + state = get_tray_state() + if state == TrayState.RUNNING: + print("Tray started. Exiting.") + return + + if state == TrayState.STARTING: + print( + "Tray did not start in expected time." + " Killing the process and starting new." + ) + file_info = get_tray_file_info() or {} + pid = file_info.get("pid") + if pid is not None: + _kill_tray_process(pid) + remove_tray_server_url(force=True) + + # Prepare the file with 'pid' information as soon as possible + try: + set_tray_server_url(None, False) + except TrayIsRunningError: + print("Tray is running") + sys.exit(1) + + main() + diff --git a/client/ayon_core/modules/webserver/structures.py b/client/ayon_core/tools/tray/structures.py similarity index 100% rename from client/ayon_core/modules/webserver/structures.py rename to client/ayon_core/tools/tray/structures.py diff --git a/client/ayon_core/tools/tray/ui/__init__.py b/client/ayon_core/tools/tray/ui/__init__.py new file mode 100644 index 0000000000..49130e660a --- /dev/null +++ b/client/ayon_core/tools/tray/ui/__init__.py @@ -0,0 +1,6 @@ +from .tray import main + + +__all__ = ( + "main", +) diff --git a/client/ayon_core/tools/tray/__main__.py b/client/ayon_core/tools/tray/ui/__main__.py similarity index 100% rename from client/ayon_core/tools/tray/__main__.py rename to client/ayon_core/tools/tray/ui/__main__.py diff --git a/client/ayon_core/tools/tray/ui/addons_manager.py b/client/ayon_core/tools/tray/ui/addons_manager.py new file mode 100644 index 0000000000..3fe4bb8dd8 --- /dev/null +++ b/client/ayon_core/tools/tray/ui/addons_manager.py @@ -0,0 +1,247 @@ +import os +import time +from typing import Callable + +from ayon_core.addon import AddonsManager, ITrayAddon, ITrayService +from ayon_core.tools.tray.webserver import ( + find_free_port, + WebServerManager, +) + + +class TrayAddonsManager(AddonsManager): + # TODO do not use env variable + webserver_url_env = "AYON_WEBSERVER_URL" + # Define order of addons in menu + # TODO find better way how to define order + addons_menu_order = ( + "ftrack", + "kitsu", + "launcher_tool", + "clockify", + ) + + def __init__(self, tray_manager): + super().__init__(initialize=False) + + self._tray_manager = tray_manager + + self._webserver_manager = WebServerManager(find_free_port(), None) + + self.doubleclick_callbacks = {} + self.doubleclick_callback = None + + @property + def webserver_url(self): + return self._webserver_manager.url + + def get_doubleclick_callback(self): + callback_name = self.doubleclick_callback + return self.doubleclick_callbacks.get(callback_name) + + def add_doubleclick_callback(self, addon, callback): + """Register double-click callbacks on tray icon. + + Currently, there is no way how to determine which is launched. Name of + callback can be defined with `doubleclick_callback` attribute. + + Missing feature how to define default callback. + + Args: + addon (AYONAddon): Addon object. + callback (FunctionType): Function callback. + """ + + callback_name = "_".join([addon.name, callback.__name__]) + if callback_name not in self.doubleclick_callbacks: + self.doubleclick_callbacks[callback_name] = callback + if self.doubleclick_callback is None: + self.doubleclick_callback = callback_name + return + + self.log.warning(( + "Callback with name \"{}\" is already registered." + ).format(callback_name)) + + def initialize(self, tray_menu): + self.initialize_addons() + self.tray_init() + self.connect_addons() + self.tray_menu(tray_menu) + + def add_route(self, request_method: str, path: str, handler: Callable): + self._webserver_manager.add_route(request_method, path, handler) + + def add_static(self, prefix: str, path: str): + self._webserver_manager.add_static(prefix, path) + + def add_addon_route( + self, + addon_name: str, + path: str, + request_method: str, + handler: Callable + ) -> str: + return self._webserver_manager.add_addon_route( + addon_name, + path, + request_method, + handler + ) + + def add_addon_static( + self, addon_name: str, prefix: str, path: str + ) -> str: + return self._webserver_manager.add_addon_static( + addon_name, + prefix, + path + ) + + def get_enabled_tray_addons(self): + """Enabled tray addons. + + Returns: + list[AYONAddon]: Enabled addons that inherit from tray interface. + """ + + return [ + addon + for addon in self.get_enabled_addons() + if isinstance(addon, ITrayAddon) + ] + + def restart_tray(self): + if self._tray_manager: + self._tray_manager.restart() + + def tray_init(self): + self._init_tray_webserver() + report = {} + time_start = time.time() + prev_start_time = time_start + for addon in self.get_enabled_tray_addons(): + try: + addon._tray_manager = self._tray_manager + addon.tray_init() + addon.tray_initialized = True + except Exception: + self.log.warning( + "Addon \"{}\" crashed on `tray_init`.".format( + addon.name + ), + exc_info=True + ) + + now = time.time() + report[addon.__class__.__name__] = now - prev_start_time + prev_start_time = now + + if self._report is not None: + report[self._report_total_key] = time.time() - time_start + self._report["Tray init"] = report + + def connect_addons(self): + self._webserver_manager.connect_with_addons( + self.get_enabled_addons() + ) + super().connect_addons() + + def tray_menu(self, tray_menu): + ordered_addons = [] + enabled_by_name = { + addon.name: addon + for addon in self.get_enabled_tray_addons() + } + + for name in self.addons_menu_order: + addon_by_name = enabled_by_name.pop(name, None) + if addon_by_name: + ordered_addons.append(addon_by_name) + ordered_addons.extend(enabled_by_name.values()) + + report = {} + time_start = time.time() + prev_start_time = time_start + for addon in ordered_addons: + if not addon.tray_initialized: + continue + + try: + addon.tray_menu(tray_menu) + except Exception: + # Unset initialized mark + addon.tray_initialized = False + self.log.warning( + "Addon \"{}\" crashed on `tray_menu`.".format( + addon.name + ), + exc_info=True + ) + now = time.time() + report[addon.__class__.__name__] = now - prev_start_time + prev_start_time = now + + if self._report is not None: + report[self._report_total_key] = time.time() - time_start + self._report["Tray menu"] = report + + def start_addons(self): + self._webserver_manager.start_server() + + report = {} + time_start = time.time() + prev_start_time = time_start + for addon in self.get_enabled_tray_addons(): + if not addon.tray_initialized: + if isinstance(addon, ITrayService): + addon.set_service_failed_icon() + continue + + try: + addon.tray_start() + except Exception: + self.log.warning( + "Addon \"{}\" crashed on `tray_start`.".format( + addon.name + ), + exc_info=True + ) + now = time.time() + report[addon.__class__.__name__] = now - prev_start_time + prev_start_time = now + + if self._report is not None: + report[self._report_total_key] = time.time() - time_start + self._report["Addons start"] = report + + def on_exit(self): + self._webserver_manager.stop_server() + for addon in self.get_enabled_tray_addons(): + if addon.tray_initialized: + try: + addon.tray_exit() + except Exception: + self.log.warning( + "Addon \"{}\" crashed on `tray_exit`.".format( + addon.name + ), + exc_info=True + ) + + def get_tray_webserver(self): + # TODO rename/remove method + return self._webserver_manager + + def _init_tray_webserver(self): + webserver_url = self.webserver_url + statics_url = f"{webserver_url}/res" + + # TODO stop using these env variables + # - function 'get_tray_server_url' should be used instead + os.environ[self.webserver_url_env] = webserver_url + os.environ["AYON_STATICS_SERVER"] = statics_url + + # Deprecated + os.environ["OPENPYPE_WEBSERVER_URL"] = webserver_url + os.environ["OPENPYPE_STATICS_SERVER"] = statics_url diff --git a/client/ayon_core/tools/tray/dialogs.py b/client/ayon_core/tools/tray/ui/dialogs.py similarity index 98% rename from client/ayon_core/tools/tray/dialogs.py rename to client/ayon_core/tools/tray/ui/dialogs.py index 67348284a1..d37188a845 100644 --- a/client/ayon_core/tools/tray/dialogs.py +++ b/client/ayon_core/tools/tray/ui/dialogs.py @@ -83,7 +83,7 @@ class UpdateDialog(QtWidgets.QDialog): top_layout.addWidget(label_widget, 1) ignore_btn = QtWidgets.QPushButton("Ignore", self) - restart_btn = QtWidgets.QPushButton("Restart && Change", self) + restart_btn = QtWidgets.QPushButton("Restart && Update", self) restart_btn.setObjectName("TrayRestartButton") btns_layout = QtWidgets.QHBoxLayout() diff --git a/client/ayon_core/modules/webserver/host_console_listener.py b/client/ayon_core/tools/tray/ui/host_console_listener.py similarity index 80% rename from client/ayon_core/modules/webserver/host_console_listener.py rename to client/ayon_core/tools/tray/ui/host_console_listener.py index 2efd768e24..62bca2f51b 100644 --- a/client/ayon_core/modules/webserver/host_console_listener.py +++ b/client/ayon_core/tools/tray/ui/host_console_listener.py @@ -9,7 +9,7 @@ from qtpy import QtWidgets from ayon_core.addon import ITrayService from ayon_core.tools.stdout_broker.window import ConsoleDialog -from .structures import HostMsgAction +from ayon_core.tools.tray import HostMsgAction log = logging.getLogger(__name__) @@ -22,18 +22,19 @@ class IconType: class HostListener: - def __init__(self, webserver, module): - self._window_per_id = {} - self.module = module - self.webserver = webserver + def __init__(self, addons_manager, tray_manager): + self._tray_manager = tray_manager self._window_per_id = {} # dialogs per host name self._action_per_id = {} # QAction per host name - webserver.add_route('*', "/ws/host_listener", self.websocket_handler) + addons_manager.add_route( + "*", "/ws/host_listener", self.websocket_handler + ) def _host_is_connecting(self, host_name, label): - """ Initialize dialog, adds to submenu. """ - services_submenu = self.module._services_submenu + """ Initialize dialog, adds to submenu.""" + ITrayService.services_submenu(self._tray_manager) + services_submenu = self._tray_manager.get_services_submenu() action = QtWidgets.QAction(label, services_submenu) action.triggered.connect(lambda: self.show_widget(host_name)) @@ -73,8 +74,9 @@ class HostListener: Dialog get initialized when 'host_name' is connecting. """ - self.module.execute_in_main_thread( - lambda: self._show_widget(host_name)) + self._tray_manager.execute_in_main_thread( + self._show_widget, host_name + ) def _show_widget(self, host_name): widget = self._window_per_id[host_name] @@ -95,21 +97,23 @@ class HostListener: if action == HostMsgAction.CONNECTING: self._action_per_id[host_name] = None # must be sent to main thread, or action wont trigger - self.module.execute_in_main_thread( - lambda: self._host_is_connecting(host_name, text)) + self._tray_manager.execute_in_main_thread( + self._host_is_connecting, host_name, text + ) elif action == HostMsgAction.CLOSE: # clean close self._close(host_name) await ws.close() elif action == HostMsgAction.INITIALIZED: - self.module.execute_in_main_thread( + self._tray_manager.execute_in_main_thread( # must be queued as _host_is_connecting might not # be triggered/finished yet - lambda: self._set_host_icon(host_name, - IconType.RUNNING)) + self._set_host_icon, host_name, IconType.RUNNING + ) elif action == HostMsgAction.ADD: - self.module.execute_in_main_thread( - lambda: self._add_text(host_name, text)) + self._tray_manager.execute_in_main_thread( + self._add_text, host_name, text + ) elif msg.type == aiohttp.WSMsgType.ERROR: print('ws connection closed with exception %s' % ws.exception()) @@ -131,7 +135,7 @@ class HostListener: def _close(self, host_name): """ Clean close - remove from menu, delete widget.""" - services_submenu = self.module._services_submenu + services_submenu = self._tray_manager.get_services_submenu() action = self._action_per_id.pop(host_name) services_submenu.removeAction(action) widget = self._window_per_id.pop(host_name) diff --git a/client/ayon_core/tools/tray/images/gifts.png b/client/ayon_core/tools/tray/ui/images/gifts.png similarity index 100% rename from client/ayon_core/tools/tray/images/gifts.png rename to client/ayon_core/tools/tray/ui/images/gifts.png diff --git a/client/ayon_core/tools/tray/info_widget.py b/client/ayon_core/tools/tray/ui/info_widget.py similarity index 100% rename from client/ayon_core/tools/tray/info_widget.py rename to client/ayon_core/tools/tray/ui/info_widget.py diff --git a/client/ayon_core/tools/tray/tray.py b/client/ayon_core/tools/tray/ui/tray.py similarity index 77% rename from client/ayon_core/tools/tray/tray.py rename to client/ayon_core/tools/tray/ui/tray.py index c0b90dd764..2a2c79129b 100644 --- a/client/ayon_core/tools/tray/tray.py +++ b/client/ayon_core/tools/tray/ui/tray.py @@ -1,10 +1,12 @@ import os import sys +import time import collections import atexit - +import json import platform +from aiohttp.web_response import Response import ayon_api from qtpy import QtCore, QtGui, QtWidgets @@ -21,13 +23,19 @@ from ayon_core.settings import get_studio_settings from ayon_core.addon import ( ITrayAction, ITrayService, - TrayAddonsManager, ) from ayon_core.tools.utils import ( WrappedCallbackItem, get_ayon_qt_app, ) +from ayon_core.tools.tray.lib import ( + set_tray_server_url, + remove_tray_server_url, + TrayIsRunningError, +) +from .addons_manager import TrayAddonsManager +from .host_console_listener import HostListener from .info_widget import InfoWidget from .dialogs import ( UpdateDialog, @@ -54,25 +62,51 @@ class TrayManager: ) if update_check_interval is None: update_check_interval = 5 - self._update_check_interval = update_check_interval * 60 * 1000 - self._addons_manager = TrayAddonsManager() + update_check_interval = update_check_interval * 60 * 1000 + + # create timer loop to check callback functions + main_thread_timer = QtCore.QTimer() + main_thread_timer.setInterval(300) + + update_check_timer = QtCore.QTimer() + if update_check_interval > 0: + update_check_timer.setInterval(update_check_interval) + + main_thread_timer.timeout.connect(self._main_thread_execution) + update_check_timer.timeout.connect(self._on_update_check_timer) + + self._addons_manager = TrayAddonsManager(self) + self._host_listener = HostListener(self._addons_manager, self) self.errors = [] - self._update_check_timer = None self._outdated_dialog = None - self._main_thread_timer = None + self._update_check_timer = update_check_timer + self._update_check_interval = update_check_interval + self._main_thread_timer = main_thread_timer self._main_thread_callbacks = collections.deque() self._execution_in_progress = None + self._services_submenu = None + self._start_time = time.time() + self._closing = False + try: + set_tray_server_url( + self._addons_manager.webserver_url, False + ) + except TrayIsRunningError: + self.log.error("Tray is already running.") + self._closing = True + + def is_closing(self): + return self._closing @property def doubleclick_callback(self): """Double-click callback for Tray icon.""" - callback_name = self._addons_manager.doubleclick_callback - return self._addons_manager.doubleclick_callbacks.get(callback_name) + return self._addons_manager.get_doubleclick_callback() def execute_doubleclick(self): """Execute double click callback in main thread.""" @@ -102,50 +136,64 @@ class TrayManager: def initialize_addons(self): """Add addons to tray.""" + if self._closing: + return - self._addons_manager.initialize(self, self.tray_widget.menu) + tray_menu = self.tray_widget.menu + self._addons_manager.initialize(tray_menu) - admin_submenu = ITrayAction.admin_submenu(self.tray_widget.menu) - self.tray_widget.menu.addMenu(admin_submenu) + self._addons_manager.add_route( + "GET", "/tray", self._get_web_tray_info + ) + + admin_submenu = ITrayAction.admin_submenu(tray_menu) + tray_menu.addMenu(admin_submenu) # Add services if they are - services_submenu = ITrayService.services_submenu( - self.tray_widget.menu - ) - self.tray_widget.menu.addMenu(services_submenu) + services_submenu = ITrayService.services_submenu(tray_menu) + self._services_submenu = services_submenu + tray_menu.addMenu(services_submenu) # Add separator - self.tray_widget.menu.addSeparator() + tray_menu.addSeparator() self._add_version_item() # Add Exit action to menu exit_action = QtWidgets.QAction("Exit", self.tray_widget) exit_action.triggered.connect(self.tray_widget.exit) - self.tray_widget.menu.addAction(exit_action) + tray_menu.addAction(exit_action) # Tell each addon which addons were imported - self._addons_manager.start_addons() + # TODO Capture only webserver issues (the only thing that can crash). + try: + self._addons_manager.start_addons() + except Exception: + self.log.error( + "Failed to start addons.", + exc_info=True + ) + return self.exit() # Print time report self._addons_manager.print_report() - # create timer loop to check callback functions - main_thread_timer = QtCore.QTimer() - main_thread_timer.setInterval(300) - main_thread_timer.timeout.connect(self._main_thread_execution) - main_thread_timer.start() + self._main_thread_timer.start() - self._main_thread_timer = main_thread_timer - - update_check_timer = QtCore.QTimer() if self._update_check_interval > 0: - update_check_timer.timeout.connect(self._on_update_check_timer) - update_check_timer.setInterval(self._update_check_interval) - update_check_timer.start() - self._update_check_timer = update_check_timer + self._update_check_timer.start() self.execute_in_main_thread(self._startup_validations) + try: + set_tray_server_url( + self._addons_manager.webserver_url, True + ) + except TrayIsRunningError: + self.log.warning("Other tray started meanwhile. Exiting.") + self.exit() + + def get_services_submenu(self): + return self._services_submenu def restart(self): """Restart Tray tool. @@ -207,9 +255,13 @@ class TrayManager: def exit(self): self._closing = True - self.tray_widget.exit() + if self._main_thread_timer.isActive(): + self.execute_in_main_thread(self.tray_widget.exit) + else: + self.tray_widget.exit() def on_exit(self): + remove_tray_server_url() self._addons_manager.on_exit() def execute_in_main_thread(self, callback, *args, **kwargs): @@ -222,6 +274,19 @@ class TrayManager: return item + async def _get_web_tray_info(self, request): + return Response(text=json.dumps({ + "bundle": os.getenv("AYON_BUNDLE_NAME"), + "dev_mode": is_dev_mode_enabled(), + "staging_mode": is_staging_enabled(), + "addons": { + addon.name: addon.version + for addon in self._addons_manager.get_enabled_addons() + }, + "installer_version": os.getenv("AYON_VERSION"), + "running_time": time.time() - self._start_time, + })) + def _on_update_check_timer(self): try: bundles = ayon_api.get_bundles() @@ -298,20 +363,24 @@ class TrayManager: ) def _main_thread_execution(self): - if self._execution_in_progress: - return - self._execution_in_progress = True - for _ in range(len(self._main_thread_callbacks)): - if self._main_thread_callbacks: - item = self._main_thread_callbacks.popleft() - try: - item.execute() - except BaseException: - self.log.erorr( - "Main thread execution failed", exc_info=True - ) + try: + if self._execution_in_progress: + return + self._execution_in_progress = True + for _ in range(len(self._main_thread_callbacks)): + if self._main_thread_callbacks: + item = self._main_thread_callbacks.popleft() + try: + item.execute() + except BaseException: + self.log.erorr( + "Main thread execution failed", exc_info=True + ) - self._execution_in_progress = False + self._execution_in_progress = False + + except KeyboardInterrupt: + self.execute_in_main_thread(self.exit) def _startup_validations(self): """Run possible startup validations.""" @@ -319,9 +388,10 @@ class TrayManager: self._update_check_timer.timeout.emit() def _add_version_item(self): + tray_menu = self.tray_widget.menu login_action = QtWidgets.QAction("Login", self.tray_widget) login_action.triggered.connect(self._on_ayon_login) - self.tray_widget.menu.addAction(login_action) + tray_menu.addAction(login_action) version_string = os.getenv("AYON_VERSION", "AYON Info") version_action = QtWidgets.QAction(version_string, self.tray_widget) @@ -333,9 +403,9 @@ class TrayManager: restart_action.triggered.connect(self._on_restart_action) restart_action.setVisible(False) - self.tray_widget.menu.addAction(version_action) - self.tray_widget.menu.addAction(restart_action) - self.tray_widget.menu.addSeparator() + tray_menu.addAction(version_action) + tray_menu.addAction(restart_action) + tray_menu.addSeparator() self._restart_action = restart_action @@ -424,19 +494,23 @@ class SystemTrayIcon(QtWidgets.QSystemTrayIcon): def __init__(self, parent): icon = QtGui.QIcon(resources.get_ayon_icon_filepath()) - super(SystemTrayIcon, self).__init__(icon, parent) + super().__init__(icon, parent) self._exited = False + self._doubleclick = False + self._click_pos = None + self._initializing_addons = False + # Store parent - QtWidgets.QMainWindow() - self.parent = parent + self._parent = parent # Setup menu in Tray self.menu = QtWidgets.QMenu() self.menu.setStyleSheet(style.load_stylesheet()) # Set addons - self.tray_man = TrayManager(self, self.parent) + self._tray_manager = TrayManager(self, parent) # Add menu to Context of SystemTrayIcon self.setContextMenu(self.menu) @@ -456,10 +530,9 @@ class SystemTrayIcon(QtWidgets.QSystemTrayIcon): click_timer.timeout.connect(self._click_timer_timeout) self._click_timer = click_timer - self._doubleclick = False - self._click_pos = None - self._initializing_addons = False + def is_closing(self) -> bool: + return self._tray_manager.is_closing() @property def initializing_addons(self): @@ -468,7 +541,7 @@ class SystemTrayIcon(QtWidgets.QSystemTrayIcon): def initialize_addons(self): self._initializing_addons = True try: - self.tray_man.initialize_addons() + self._tray_manager.initialize_addons() finally: self._initializing_addons = False @@ -478,7 +551,7 @@ class SystemTrayIcon(QtWidgets.QSystemTrayIcon): # Reset bool value self._doubleclick = False if doubleclick: - self.tray_man.execute_doubleclick() + self._tray_manager.execute_doubleclick() else: self._show_context_menu() @@ -492,7 +565,7 @@ class SystemTrayIcon(QtWidgets.QSystemTrayIcon): def on_systray_activated(self, reason): # show contextMenu if left click if reason == QtWidgets.QSystemTrayIcon.Trigger: - if self.tray_man.doubleclick_callback: + if self._tray_manager.doubleclick_callback: self._click_pos = QtGui.QCursor().pos() self._click_timer.start() else: @@ -511,7 +584,7 @@ class SystemTrayIcon(QtWidgets.QSystemTrayIcon): self._exited = True self.hide() - self.tray_man.on_exit() + self._tray_manager.on_exit() QtCore.QCoreApplication.exit() @@ -536,6 +609,11 @@ class TrayStarter(QtCore.QObject): self._start_timer = start_timer def _on_start_timer(self): + if self._tray_widget.is_closing(): + self._start_timer.stop() + self._tray_widget.exit() + return + if self._timer_counter == 0: self._timer_counter += 1 splash = self._get_splash() diff --git a/client/ayon_core/tools/tray/webserver/__init__.py b/client/ayon_core/tools/tray/webserver/__init__.py new file mode 100644 index 0000000000..c40b5b85c3 --- /dev/null +++ b/client/ayon_core/tools/tray/webserver/__init__.py @@ -0,0 +1,9 @@ +from .base_routes import RestApiEndpoint +from .server import find_free_port, WebServerManager + + +__all__ = ( + "RestApiEndpoint", + "find_free_port", + "WebServerManager", +) diff --git a/client/ayon_core/modules/webserver/base_routes.py b/client/ayon_core/tools/tray/webserver/base_routes.py similarity index 94% rename from client/ayon_core/modules/webserver/base_routes.py rename to client/ayon_core/tools/tray/webserver/base_routes.py index f4f1abe16c..82568c201c 100644 --- a/client/ayon_core/modules/webserver/base_routes.py +++ b/client/ayon_core/tools/tray/webserver/base_routes.py @@ -1,7 +1,6 @@ """Helper functions or classes for Webserver module. -These must not be imported in module itself to not break Python 2 -applications. +These must not be imported in module itself to not break in-DCC process. """ import inspect diff --git a/client/ayon_core/modules/webserver/cors_middleware.py b/client/ayon_core/tools/tray/webserver/cors_middleware.py similarity index 100% rename from client/ayon_core/modules/webserver/cors_middleware.py rename to client/ayon_core/tools/tray/webserver/cors_middleware.py diff --git a/client/ayon_core/modules/webserver/server.py b/client/ayon_core/tools/tray/webserver/server.py similarity index 60% rename from client/ayon_core/modules/webserver/server.py rename to client/ayon_core/tools/tray/webserver/server.py index 99d9badb6a..d2a9b0fc6b 100644 --- a/client/ayon_core/modules/webserver/server.py +++ b/client/ayon_core/tools/tray/webserver/server.py @@ -1,24 +1,85 @@ import re import threading import asyncio +import socket +import random +from typing import Callable, Optional from aiohttp import web from ayon_core.lib import Logger +from ayon_core.resources import RESOURCES_DIR + from .cors_middleware import cors_middleware +def find_free_port( + port_from=None, port_to=None, exclude_ports=None, host=None +): + """Find available socket port from entered range. + + It is also possible to only check if entered port is available. + + Args: + port_from (int): Port number which is checked as first. + port_to (int): Last port that is checked in sequence from entered + `port_from`. Only `port_from` is checked if is not entered. + Nothing is processed if is equeal to `port_from`! + exclude_ports (list, tuple, set): List of ports that won't be + checked form entered range. + host (str): Host where will check for free ports. Set to + "localhost" by default. + """ + if port_from is None: + port_from = 8079 + + if port_to is None: + port_to = 65535 + + # Excluded ports (e.g. reserved for other servers/clients) + if exclude_ports is None: + exclude_ports = [] + + # Default host is localhost but it is possible to look for other hosts + if host is None: + host = "localhost" + + found_port = None + while True: + port = random.randint(port_from, port_to) + if port in exclude_ports: + continue + + sock = None + try: + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.bind((host, port)) + found_port = port + + except socket.error: + continue + + finally: + if sock: + sock.close() + + if found_port is not None: + break + + return found_port + + class WebServerManager: """Manger that care about web server thread.""" - def __init__(self, port=None, host=None): + def __init__( + self, port: Optional[int] = None, host: Optional[str] = None + ): self._log = None self.port = port or 8079 self.host = host or "localhost" - self.client = None - self.handlers = {} self.on_stop_callbacks = [] self.app = web.Application( @@ -30,9 +91,10 @@ class WebServerManager: ) # add route with multiple methods for single "external app" - self.webserver_thread = WebServerThread(self) + self.add_static("/res", RESOURCES_DIR) + @property def log(self): if self._log is None: @@ -40,14 +102,46 @@ class WebServerManager: return self._log @property - def url(self): - return "http://{}:{}".format(self.host, self.port) + def url(self) -> str: + return f"http://{self.host}:{self.port}" - def add_route(self, *args, **kwargs): - self.app.router.add_route(*args, **kwargs) + def add_route(self, request_method: str, path: str, handler: Callable): + self.app.router.add_route(request_method, path, handler) - def add_static(self, *args, **kwargs): - self.app.router.add_static(*args, **kwargs) + def add_static(self, prefix: str, path: str): + self.app.router.add_static(prefix, path) + + def add_addon_route( + self, + addon_name: str, + path: str, + request_method: str, + handler: Callable + ) -> str: + path = path.lstrip("/") + full_path = f"/addons/{addon_name}/{path}" + self.app.router.add_route(request_method, full_path, handler) + return full_path + + def add_addon_static( + self, addon_name: str, prefix: str, path: str + ) -> str: + full_path = f"/addons/{addon_name}/{prefix}" + self.app.router.add_static(full_path, path) + return full_path + + def connect_with_addons(self, addons): + for addon in addons: + if not hasattr(addon, "webserver_initialization"): + continue + + try: + addon.webserver_initialization(self) + except Exception: + self.log.warning( + f"Failed to connect addon \"{addon.name}\" to webserver.", + exc_info=True + ) def start_server(self): if self.webserver_thread and not self.webserver_thread.is_alive(): @@ -68,7 +162,7 @@ class WebServerManager: ) @property - def is_running(self): + def is_running(self) -> bool: if not self.webserver_thread: return False return self.webserver_thread.is_running diff --git a/client/ayon_core/tools/utils/lib.py b/client/ayon_core/tools/utils/lib.py index f31bb82e59..8689a97451 100644 --- a/client/ayon_core/tools/utils/lib.py +++ b/client/ayon_core/tools/utils/lib.py @@ -17,7 +17,7 @@ from ayon_core.style import ( from ayon_core.resources import get_image_path from ayon_core.lib import Logger -from .constants import CHECKED_INT, UNCHECKED_INT +from .constants import CHECKED_INT, UNCHECKED_INT, PARTIALLY_CHECKED_INT log = Logger.get_logger(__name__) @@ -37,10 +37,10 @@ def checkstate_enum_to_int(state): if isinstance(state, int): return state if state == QtCore.Qt.Checked: - return 0 + return CHECKED_INT if state == QtCore.Qt.PartiallyChecked: - return 1 - return 2 + return PARTIALLY_CHECKED_INT + return UNCHECKED_INT def center_window(window): @@ -485,7 +485,10 @@ class _IconsCache: parts = [icon_type, icon_def["path"]] elif icon_type in {"awesome-font", "material-symbols"}: - parts = [icon_type, icon_def["name"], icon_def["color"]] + color = icon_def["color"] or "" + if isinstance(color, QtGui.QColor): + color = color.name() + parts = [icon_type, icon_def["name"] or "", color] return "|".join(parts) @classmethod diff --git a/client/ayon_core/tools/utils/widgets.py b/client/ayon_core/tools/utils/widgets.py index 21cab5d682..28331fbc35 100644 --- a/client/ayon_core/tools/utils/widgets.py +++ b/client/ayon_core/tools/utils/widgets.py @@ -770,7 +770,7 @@ class SeparatorWidget(QtWidgets.QFrame): if self._orientation == orientation: return - # Reset min/max sizes in opossite direction + # Reset min/max sizes in opposite direction if self._orientation == QtCore.Qt.Vertical: self.setMinimumHeight(0) self.setMaximumHeight(self._maximum_height) diff --git a/client/ayon_core/tools/workfiles/abstract.py b/client/ayon_core/tools/workfiles/abstract.py index e949915ab2..b78e987032 100644 --- a/client/ayon_core/tools/workfiles/abstract.py +++ b/client/ayon_core/tools/workfiles/abstract.py @@ -1,7 +1,6 @@ import os -from abc import ABCMeta, abstractmethod +from abc import ABC, abstractmethod -import six from ayon_core.style import get_default_entity_icon_color @@ -335,8 +334,7 @@ class WorkareaFilepathResult: self.filepath = filepath -@six.add_metaclass(ABCMeta) -class AbstractWorkfilesCommon(object): +class AbstractWorkfilesCommon(ABC): @abstractmethod def is_host_valid(self): """Host is valid for workfiles tool work. diff --git a/client/ayon_core/version.py b/client/ayon_core/version.py index f0e4b9a10f..a8c42ec80a 100644 --- a/client/ayon_core/version.py +++ b/client/ayon_core/version.py @@ -1,3 +1,3 @@ # -*- coding: utf-8 -*- """Package declaring AYON core addon version.""" -__version__ = "0.4.1-dev.1" +__version__ = "0.4.3-dev.1" diff --git a/package.py b/package.py index e5e567b8e8..4f2d2b16b4 100644 --- a/package.py +++ b/package.py @@ -1,6 +1,6 @@ name = "core" title = "Core" -version = "0.4.1-dev.1" +version = "0.4.3-dev.1" client_dir = "ayon_core" diff --git a/pyproject.toml b/pyproject.toml index 82f0fc364e..f8f840d2c9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,7 +5,7 @@ [tool.poetry] name = "ayon-core" -version = "0.3.1" +version = "0.4.3-dev.1" description = "" authors = ["Ynput Team "] readme = "README.md" @@ -79,11 +79,7 @@ dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$" exclude = [ "client/ayon_core/modules/click_wrap.py", - "client/ayon_core/scripts/slates/__init__.py", - "server_addon/deadline/client/ayon_deadline/repository/custom/plugins/CelAction/*", - "server_addon/deadline/client/ayon_deadline/repository/custom/plugins/HarmonyAYON/*", - "server_addon/hiero/client/ayon_hiero/api/startup/*", - "server_addon/aftereffects/client/ayon_aftereffects/api/extension/js/libs/*" + "client/ayon_core/scripts/slates/__init__.py" ] [tool.ruff.lint.per-file-ignores] diff --git a/server/settings/publish_plugins.py b/server/settings/publish_plugins.py index c1c6bc42a5..0f64d0ff07 100644 --- a/server/settings/publish_plugins.py +++ b/server/settings/publish_plugins.py @@ -983,7 +983,8 @@ DEFAULT_PUBLISH_VALUES = { "nuke", "harmony", "photoshop", - "aftereffects" + "aftereffects", + "fusion" ], "enabled": True, "optional": True, diff --git a/server_addon/README.md b/server_addon/README.md deleted file mode 100644 index c6d467adaa..0000000000 --- a/server_addon/README.md +++ /dev/null @@ -1,34 +0,0 @@ -# Addons for AYON server -Preparation of AYON addons based on OpenPype codebase. The output is a bunch of zip files in `./packages` directory that can be uploaded to AYON server. One of the packages is `openpype` which is OpenPype code converted to AYON addon. The addon is must have requirement to be able to use `ayon-launcher`. The versioning of `openpype` addon is following versioning of OpenPype. The other addons contain only settings models. - -## Intro -OpenPype is transitioning to AYON, a dedicated server with its own database, moving away from MongoDB. During this transition period, OpenPype will remain compatible with both MongoDB and AYON. However, we will gradually update the codebase to align with AYON's data structure and separate individual components into addons. - -Currently, OpenPype has an AYON mode, which means it utilizes the AYON server instead of MongoDB through conversion utilities. Initially, we added the AYON executable alongside the OpenPype executables to enable AYON mode. While this approach worked, updating to new code versions would require a complete reinstallation. To address this, we have decided to create a new repository specifically for the base desktop application logic, which we currently refer to as the AYON Launcher. This Launcher will replace the executables generated by the OpenPype build and convert the OpenPype code into a server addon, resulting in smaller updates. - -Since the implementation of the AYON Launcher is not yet fully completed, we will maintain both methods of starting AYON mode for now. Once the AYON Launcher is finished, we will remove the AYON executables from the OpenPype codebase entirely. - -During this transitional period, the AYON Launcher addon will be a requirement as the entry point for using the AYON Launcher. - -## How to start -There is a `create_ayon_addons.py` python file which contains logic how to create server addon from OpenPype codebase. Just run the code. -```shell -./.poetry/bin/poetry run python ./server_addon/create_ayon_addons.py -``` - -It will create directory `./packages/.zip` files for AYON server. You can then copy upload the zip files to AYON server. Restart server to update addons information, add the addon version to server bundle and set the bundle for production or staging usage. - -Once addon is on server and is enabled, you can just run AYON launcher. Content will be downloaded and used automatically. - -### Additional arguments -Additional arguments are useful for development purposes. - -To skip zip creation to keep only server ready folder structure, pass `--skip-zip` argument. -```shell -./.poetry/bin/poetry run python ./server_addon/create_ayon_addons.py --skip-zip -``` - -To create both zips and keep folder structure, pass `--keep-sources` argument. -```shell -./.poetry/bin/poetry run python ./server_addon/create_ayon_addons.py --keep-sources -``` diff --git a/server_addon/create_ayon_addons.py b/server_addon/create_ayon_addons.py deleted file mode 100644 index 73d0b54770..0000000000 --- a/server_addon/create_ayon_addons.py +++ /dev/null @@ -1,376 +0,0 @@ -import io -import os -import sys -import re -import shutil -import argparse -import zipfile -import types -import importlib.machinery -import platform -import collections -from pathlib import Path -from typing import Optional, Iterable, Pattern, List, Tuple - -# Patterns of directories to be skipped for server part of addon -IGNORE_DIR_PATTERNS: List[Pattern] = [ - re.compile(pattern) - for pattern in { - # Skip directories starting with '.' - r"^\.", - # Skip any pycache folders - "^__pycache__$" - } -] - -# Patterns of files to be skipped for server part of addon -IGNORE_FILE_PATTERNS: List[Pattern] = [ - re.compile(pattern) - for pattern in { - # Skip files starting with '.' - # NOTE this could be an issue in some cases - r"^\.", - # Skip '.pyc' files - r"\.pyc$" - } -] - -IGNORED_HOSTS = [ - "flame", - "harmony", -] - -IGNORED_MODULES = [] - -PACKAGE_PY_TEMPLATE = """name = "{addon_name}" -version = "{addon_version}" -plugin_for = ["ayon_server"] -""" - -CLIENT_VERSION_CONTENT = '''# -*- coding: utf-8 -*- -"""Package declaring AYON addon '{}' version.""" -__version__ = "{}" -''' - - -class ZipFileLongPaths(zipfile.ZipFile): - """Allows longer paths in zip files. - - Regular DOS paths are limited to MAX_PATH (260) characters, including - the string's terminating NUL character. - That limit can be exceeded by using an extended-length path that - starts with the '\\?\' prefix. - """ - _is_windows = platform.system().lower() == "windows" - - def _extract_member(self, member, tpath, pwd): - if self._is_windows: - tpath = os.path.abspath(tpath) - if tpath.startswith("\\\\"): - tpath = "\\\\?\\UNC\\" + tpath[2:] - else: - tpath = "\\\\?\\" + tpath - - return super()._extract_member(member, tpath, pwd) - - -def _value_match_regexes(value: str, regexes: Iterable[Pattern]) -> bool: - return any( - regex.search(value) - for regex in regexes - ) - - -def find_files_in_subdir( - src_path: str, - ignore_file_patterns: Optional[List[Pattern]] = None, - ignore_dir_patterns: Optional[List[Pattern]] = None, - include_empty_dirs: bool = True -): - """Find all files to copy in subdirectories of given path. - - All files that match any of the patterns in 'ignore_file_patterns' will - be skipped and any directories that match any of the patterns in - 'ignore_dir_patterns' will be skipped with all subfiles. - - Args: - src_path (str): Path to directory to search in. - ignore_file_patterns (Optional[List[Pattern]]): List of regexes - to match files to ignore. - ignore_dir_patterns (Optional[List[Pattern]]): List of regexes - to match directories to ignore. - include_empty_dirs (Optional[bool]): Do not skip empty directories. - - Returns: - List[Tuple[str, str]]: List of tuples with path to file and parent - directories relative to 'src_path'. - """ - if not os.path.exists(src_path): - return [] - - if ignore_file_patterns is None: - ignore_file_patterns = IGNORE_FILE_PATTERNS - - if ignore_dir_patterns is None: - ignore_dir_patterns = IGNORE_DIR_PATTERNS - output: List[Tuple[str, str]] = [] - - hierarchy_queue = collections.deque() - hierarchy_queue.append((src_path, [])) - while hierarchy_queue: - item: Tuple[str, List[str]] = hierarchy_queue.popleft() - dirpath, parents = item - subnames = list(os.listdir(dirpath)) - if not subnames and include_empty_dirs: - output.append((dirpath, os.path.sep.join(parents))) - - for name in subnames: - path = os.path.join(dirpath, name) - if os.path.isfile(path): - if not _value_match_regexes(name, ignore_file_patterns): - items = list(parents) - items.append(name) - output.append((path, os.path.sep.join(items))) - continue - - if not _value_match_regexes(name, ignore_dir_patterns): - items = list(parents) - items.append(name) - hierarchy_queue.append((path, items)) - - return output - - -def create_addon_zip( - output_dir: Path, - addon_name: str, - addon_version: str, - files_mapping: List[Tuple[str, str]], - client_zip_content: io.BytesIO -): - zip_filepath = output_dir / f"{addon_name}-{addon_version}.zip" - - with ZipFileLongPaths(zip_filepath, "w", zipfile.ZIP_DEFLATED) as zipf: - for src_path, dst_subpath in files_mapping: - zipf.write(src_path, dst_subpath) - - if client_zip_content is not None: - zipf.writestr("private/client.zip", client_zip_content.getvalue()) - - -def prepare_client_zip( - addon_dir: Path, - addon_name: str, - addon_version: str, - client_dir: str -): - if not client_dir: - return None - client_dir_obj = addon_dir / "client" / client_dir - if not client_dir_obj.exists(): - return None - - # Update version.py with server version if 'version.py' is available - version_path = client_dir_obj / "version.py" - if version_path.exists(): - with open(version_path, "w") as stream: - stream.write( - CLIENT_VERSION_CONTENT.format(addon_name, addon_version) - ) - - zip_content = io.BytesIO() - with ZipFileLongPaths(zip_content, "a", zipfile.ZIP_DEFLATED) as zipf: - # Add client code content to zip - for path, sub_path in find_files_in_subdir( - str(client_dir_obj), include_empty_dirs=False - ): - sub_path = os.path.join(client_dir, sub_path) - zipf.write(path, sub_path) - - zip_content.seek(0) - return zip_content - - -def import_filepath(path: Path, module_name: Optional[str] = None): - if not module_name: - module_name = os.path.splitext(path.name)[0] - - # Convert to string - path = str(path) - module = types.ModuleType(module_name) - module.__file__ = path - - # Use loader so module has full specs - module_loader = importlib.machinery.SourceFileLoader( - module_name, path - ) - module_loader.exec_module(module) - return module - - -def _get_server_mapping( - addon_dir: Path, addon_version: str -) -> List[Tuple[str, str]]: - server_dir = addon_dir / "server" - public_dir = addon_dir / "public" - src_package_py = addon_dir / "package.py" - pyproject_toml = addon_dir / "client" / "pyproject.toml" - - mapping: List[Tuple[str, str]] = [ - (src_path, f"server/{sub_path}") - for src_path, sub_path in find_files_in_subdir(str(server_dir)) - ] - mapping.extend([ - (src_path, f"public/{sub_path}") - for src_path, sub_path in find_files_in_subdir(str(public_dir)) - ]) - mapping.append((src_package_py.as_posix(), "package.py")) - if pyproject_toml.exists(): - mapping.append((pyproject_toml.as_posix(), "private/pyproject.toml")) - - return mapping - - -def create_addon_package( - addon_dir: Path, - output_dir: Path, - create_zip: bool, -): - src_package_py = addon_dir / "package.py" - - package = import_filepath(src_package_py) - addon_name = package.name - addon_version = package.version - - files_mapping = _get_server_mapping(addon_dir, addon_version) - - client_dir = getattr(package, "client_dir", None) - client_zip_content = prepare_client_zip( - addon_dir, addon_name, addon_version, client_dir - ) - - if create_zip: - create_addon_zip( - output_dir, - addon_name, - addon_version, - files_mapping, - client_zip_content - ) - - else: - addon_output_dir = output_dir / addon_dir.name / addon_version - if addon_output_dir.exists(): - shutil.rmtree(str(addon_output_dir)) - - addon_output_dir.mkdir(parents=True, exist_ok=True) - - for src_path, dst_subpath in files_mapping: - dst_path = addon_output_dir / dst_subpath - dst_path.parent.mkdir(parents=True, exist_ok=True) - shutil.copy2(src_path, dst_path) - - if client_zip_content is not None: - private_dir = addon_output_dir / "private" - private_dir.mkdir(parents=True, exist_ok=True) - with open(private_dir / "client.zip", "wb") as stream: - stream.write(client_zip_content.read()) - - -def main( - output_dir=None, - skip_zip=True, - clear_output_dir=False, - addons=None, -): - current_dir = Path(os.path.dirname(os.path.abspath(__file__))) - create_zip = not skip_zip - - if output_dir: - output_dir = Path(output_dir) - else: - output_dir = current_dir / "packages" - - if output_dir.exists() and clear_output_dir: - shutil.rmtree(str(output_dir)) - - print("Package creation started...") - print(f"Output directory: {output_dir}") - - # Make sure output dir is created - output_dir.mkdir(parents=True, exist_ok=True) - ignored_addons = set(IGNORED_HOSTS) | set(IGNORED_MODULES) - for addon_dir in current_dir.iterdir(): - if not addon_dir.is_dir(): - continue - - if addons and addon_dir.name not in addons: - continue - - if addon_dir.name in ignored_addons: - continue - - server_dir = addon_dir / "server" - if not server_dir.exists(): - continue - - create_addon_package(addon_dir, output_dir, create_zip) - - print(f"- package '{addon_dir.name}' created") - print(f"Package creation finished. Output directory: {output_dir}") - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument( - "--skip-zip", - dest="skip_zip", - action="store_true", - help=( - "Skip zipping server package and create only" - " server folder structure." - ) - ) - parser.add_argument( - "--keep-sources", - dest="keep_sources", - action="store_true", - help=( - "Keep folder structure when server package is created." - ) - ) - parser.add_argument( - "-o", "--output", - dest="output_dir", - default=None, - help=( - "Directory path where package will be created" - " (Will be purged if already exists!)" - ) - ) - parser.add_argument( - "-c", "--clear-output-dir", - dest="clear_output_dir", - action="store_true", - help=( - "Clear output directory before package creation." - ) - ) - parser.add_argument( - "-a", - "--addon", - dest="addons", - action="append", - help="Limit addon creation to given addon name", - ) - - args = parser.parse_args(sys.argv[1:]) - if args.keep_sources: - print("Keeping sources is not supported anymore!") - - main( - args.output_dir, - args.skip_zip, - args.clear_output_dir, - args.addons, - ) diff --git a/server_addon/deadline/client/ayon_deadline/__init__.py b/server_addon/deadline/client/ayon_deadline/__init__.py deleted file mode 100644 index 6fec1006e6..0000000000 --- a/server_addon/deadline/client/ayon_deadline/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -from .addon import DeadlineAddon -from .version import __version__ - - -__all__ = ( - "DeadlineAddon", - "__version__" -) diff --git a/server_addon/deadline/client/ayon_deadline/abstract_submit_deadline.py b/server_addon/deadline/client/ayon_deadline/abstract_submit_deadline.py deleted file mode 100644 index ba50aaccf7..0000000000 --- a/server_addon/deadline/client/ayon_deadline/abstract_submit_deadline.py +++ /dev/null @@ -1,617 +0,0 @@ -# -*- coding: utf-8 -*- -"""Abstract package for submitting jobs to Deadline. - -It provides Deadline JobInfo data class. - -""" -import json.decoder -import os -from abc import abstractmethod -import platform -import getpass -from functools import partial -from collections import OrderedDict - -import six -import attr -import requests - -import pyblish.api -from ayon_core.pipeline.publish import ( - AbstractMetaInstancePlugin, - KnownPublishError, - AYONPyblishPluginMixin -) -from ayon_core.pipeline.publish.lib import ( - replace_with_published_scene_path -) - -JSONDecodeError = getattr(json.decoder, "JSONDecodeError", ValueError) - - -def requests_post(*args, **kwargs): - """Wrap request post method. - - Disabling SSL certificate validation if ``verify`` kwarg is set to False. - This is useful when Deadline server is - running with self-signed certificates and its certificate is not - added to trusted certificates on client machines. - - Warning: - Disabling SSL certificate validation is defeating one line - of defense SSL is providing, and it is not recommended. - - """ - auth = kwargs.get("auth") - if auth: - kwargs["auth"] = tuple(auth) # explicit cast to tuple - # add 10sec timeout before bailing out - kwargs['timeout'] = 10 - return requests.post(*args, **kwargs) - - -def requests_get(*args, **kwargs): - """Wrap request get method. - - Disabling SSL certificate validation if ``verify`` kwarg is set to False. - This is useful when Deadline server is - running with self-signed certificates and its certificate is not - added to trusted certificates on client machines. - - Warning: - Disabling SSL certificate validation is defeating one line - of defense SSL is providing, and it is not recommended. - - """ - auth = kwargs.get("auth") - if auth: - kwargs["auth"] = tuple(auth) - # add 10sec timeout before bailing out - kwargs['timeout'] = 10 - return requests.get(*args, **kwargs) - - -class DeadlineKeyValueVar(dict): - """ - - Serializes dictionary key values as "{key}={value}" like Deadline uses - for EnvironmentKeyValue. - - As an example: - EnvironmentKeyValue0="A_KEY=VALUE_A" - EnvironmentKeyValue1="OTHER_KEY=VALUE_B" - - The keys are serialized in alphabetical order (sorted). - - Example: - >>> var = DeadlineKeyValueVar("EnvironmentKeyValue") - >>> var["my_var"] = "hello" - >>> var["my_other_var"] = "hello2" - >>> var.serialize() - - - """ - def __init__(self, key): - super(DeadlineKeyValueVar, self).__init__() - self.__key = key - - def serialize(self): - key = self.__key - - # Allow custom location for index in serialized string - if "{}" not in key: - key = key + "{}" - - return { - key.format(index): "{}={}".format(var_key, var_value) - for index, (var_key, var_value) in enumerate(sorted(self.items())) - } - - -class DeadlineIndexedVar(dict): - """ - - Allows to set and query values by integer indices: - Query: var[1] or var.get(1) - Set: var[1] = "my_value" - Append: var += "value" - - Note: Iterating the instance is not guarantueed to be the order of the - indices. To do so iterate with `sorted()` - - """ - def __init__(self, key): - super(DeadlineIndexedVar, self).__init__() - self.__key = key - - def serialize(self): - key = self.__key - - # Allow custom location for index in serialized string - if "{}" not in key: - key = key + "{}" - - return { - key.format(index): value for index, value in sorted(self.items()) - } - - def next_available_index(self): - # Add as first unused entry - i = 0 - while i in self.keys(): - i += 1 - return i - - def update(self, data): - # Force the integer key check - for key, value in data.items(): - self.__setitem__(key, value) - - def __iadd__(self, other): - index = self.next_available_index() - self[index] = other - return self - - def __setitem__(self, key, value): - if not isinstance(key, int): - raise TypeError("Key must be an integer: {}".format(key)) - - if key < 0: - raise ValueError("Negative index can't be set: {}".format(key)) - dict.__setitem__(self, key, value) - - -@attr.s -class DeadlineJobInfo(object): - """Mapping of all Deadline *JobInfo* attributes. - - This contains all JobInfo attributes plus their default values. - Those attributes set to `None` shouldn't be posted to Deadline as - the only required one is `Plugin`. Their default values used by Deadline - are stated in - comments. - - ..seealso: - https://docs.thinkboxsoftware.com/products/deadline/10.1/1_User%20Manual/manual/manual-submission.html - - """ - - # Required - # ---------------------------------------------- - Plugin = attr.ib() - - # General - Frames = attr.ib(default=None) # default: 0 - Name = attr.ib(default="Untitled") - Comment = attr.ib(default=None) # default: empty - Department = attr.ib(default=None) # default: empty - BatchName = attr.ib(default=None) # default: empty - UserName = attr.ib(default=getpass.getuser()) - MachineName = attr.ib(default=platform.node()) - Pool = attr.ib(default=None) # default: "none" - SecondaryPool = attr.ib(default=None) - Group = attr.ib(default=None) # default: "none" - Priority = attr.ib(default=50) - ChunkSize = attr.ib(default=1) - ConcurrentTasks = attr.ib(default=1) - LimitConcurrentTasksToNumberOfCpus = attr.ib( - default=None) # default: "true" - OnJobComplete = attr.ib(default="Nothing") - SynchronizeAllAuxiliaryFiles = attr.ib(default=None) # default: false - ForceReloadPlugin = attr.ib(default=None) # default: false - Sequential = attr.ib(default=None) # default: false - SuppressEvents = attr.ib(default=None) # default: false - Protected = attr.ib(default=None) # default: false - InitialStatus = attr.ib(default="Active") - NetworkRoot = attr.ib(default=None) - - # Timeouts - # ---------------------------------------------- - MinRenderTimeSeconds = attr.ib(default=None) # Default: 0 - MinRenderTimeMinutes = attr.ib(default=None) # Default: 0 - TaskTimeoutSeconds = attr.ib(default=None) # Default: 0 - TaskTimeoutMinutes = attr.ib(default=None) # Default: 0 - StartJobTimeoutSeconds = attr.ib(default=None) # Default: 0 - StartJobTimeoutMinutes = attr.ib(default=None) # Default: 0 - InitializePluginTimeoutSeconds = attr.ib(default=None) # Default: 0 - # can be one of - OnTaskTimeout = attr.ib(default=None) # Default: Error - EnableTimeoutsForScriptTasks = attr.ib(default=None) # Default: false - EnableFrameTimeouts = attr.ib(default=None) # Default: false - EnableAutoTimeout = attr.ib(default=None) # Default: false - - # Interruptible - # ---------------------------------------------- - Interruptible = attr.ib(default=None) # Default: false - InterruptiblePercentage = attr.ib(default=None) - RemTimeThreshold = attr.ib(default=None) - - # Notifications - # ---------------------------------------------- - # can be comma separated list of users - NotificationTargets = attr.ib(default=None) # Default: blank - ClearNotificationTargets = attr.ib(default=None) # Default: false - # A comma separated list of additional email addresses - NotificationEmails = attr.ib(default=None) # Default: blank - OverrideNotificationMethod = attr.ib(default=None) # Default: false - EmailNotification = attr.ib(default=None) # Default: false - PopupNotification = attr.ib(default=None) # Default: false - # String with `[EOL]` used for end of line - NotificationNote = attr.ib(default=None) # Default: blank - - # Machine Limit - # ---------------------------------------------- - MachineLimit = attr.ib(default=None) # Default: 0 - MachineLimitProgress = attr.ib(default=None) # Default: -1.0 - Whitelist = attr.ib(default=None) # Default: blank - Blacklist = attr.ib(default=None) # Default: blank - - # Limits - # ---------------------------------------------- - # comma separated list of limit groups - LimitGroups = attr.ib(default=None) # Default: blank - - # Dependencies - # ---------------------------------------------- - # comma separated list of job IDs - JobDependencies = attr.ib(default=None) # Default: blank - JobDependencyPercentage = attr.ib(default=None) # Default: -1 - IsFrameDependent = attr.ib(default=None) # Default: false - FrameDependencyOffsetStart = attr.ib(default=None) # Default: 0 - FrameDependencyOffsetEnd = attr.ib(default=None) # Default: 0 - ResumeOnCompleteDependencies = attr.ib(default=None) # Default: true - ResumeOnDeletedDependencies = attr.ib(default=None) # Default: false - ResumeOnFailedDependencies = attr.ib(default=None) # Default: false - # comma separated list of asset paths - RequiredAssets = attr.ib(default=None) # Default: blank - # comma separated list of script paths - ScriptDependencies = attr.ib(default=None) # Default: blank - - # Failure Detection - # ---------------------------------------------- - OverrideJobFailureDetection = attr.ib(default=None) # Default: false - FailureDetectionJobErrors = attr.ib(default=None) # 0..x - OverrideTaskFailureDetection = attr.ib(default=None) # Default: false - FailureDetectionTaskErrors = attr.ib(default=None) # 0..x - IgnoreBadJobDetection = attr.ib(default=None) # Default: false - SendJobErrorWarning = attr.ib(default=None) # Default: false - - # Cleanup - # ---------------------------------------------- - DeleteOnComplete = attr.ib(default=None) # Default: false - ArchiveOnComplete = attr.ib(default=None) # Default: false - OverrideAutoJobCleanup = attr.ib(default=None) # Default: false - OverrideJobCleanup = attr.ib(default=None) - JobCleanupDays = attr.ib(default=None) # Default: false - # - OverrideJobCleanupType = attr.ib(default=None) - - # Scheduling - # ---------------------------------------------- - # - ScheduledType = attr.ib(default=None) # Default: None - #
- ScheduledStartDateTime = attr.ib(default=None) - ScheduledDays = attr.ib(default=None) # Default: 1 - # - JobDelay = attr.ib(default=None) - # Time= - Scheduled = attr.ib(default=None) - - # Scripts - # ---------------------------------------------- - # all accept path to script - PreJobScript = attr.ib(default=None) # Default: blank - PostJobScript = attr.ib(default=None) # Default: blank - PreTaskScript = attr.ib(default=None) # Default: blank - PostTaskScript = attr.ib(default=None) # Default: blank - - # Event Opt-Ins - # ---------------------------------------------- - # comma separated list of plugins - EventOptIns = attr.ib(default=None) # Default: blank - - # Environment - # ---------------------------------------------- - EnvironmentKeyValue = attr.ib(factory=partial(DeadlineKeyValueVar, - "EnvironmentKeyValue")) - - IncludeEnvironment = attr.ib(default=None) # Default: false - UseJobEnvironmentOnly = attr.ib(default=None) # Default: false - CustomPluginDirectory = attr.ib(default=None) # Default: blank - - # Job Extra Info - # ---------------------------------------------- - ExtraInfo = attr.ib(factory=partial(DeadlineIndexedVar, "ExtraInfo")) - ExtraInfoKeyValue = attr.ib(factory=partial(DeadlineKeyValueVar, - "ExtraInfoKeyValue")) - - # Task Extra Info Names - # ---------------------------------------------- - OverrideTaskExtraInfoNames = attr.ib(default=None) # Default: false - TaskExtraInfoName = attr.ib(factory=partial(DeadlineIndexedVar, - "TaskExtraInfoName")) - - # Output - # ---------------------------------------------- - OutputFilename = attr.ib(factory=partial(DeadlineIndexedVar, - "OutputFilename")) - OutputFilenameTile = attr.ib(factory=partial(DeadlineIndexedVar, - "OutputFilename{}Tile")) - OutputDirectory = attr.ib(factory=partial(DeadlineIndexedVar, - "OutputDirectory")) - - # Asset Dependency - # ---------------------------------------------- - AssetDependency = attr.ib(factory=partial(DeadlineIndexedVar, - "AssetDependency")) - - # Tile Job - # ---------------------------------------------- - TileJob = attr.ib(default=None) # Default: false - TileJobFrame = attr.ib(default=None) # Default: 0 - TileJobTilesInX = attr.ib(default=None) # Default: 0 - TileJobTilesInY = attr.ib(default=None) # Default: 0 - TileJobTileCount = attr.ib(default=None) # Default: 0 - - # Maintenance Job - # ---------------------------------------------- - MaintenanceJob = attr.ib(default=None) # Default: false - MaintenanceJobStartFrame = attr.ib(default=None) # Default: 0 - MaintenanceJobEndFrame = attr.ib(default=None) # Default: 0 - - def serialize(self): - """Return all data serialized as dictionary. - - Returns: - OrderedDict: all serialized data. - - """ - def filter_data(a, v): - if isinstance(v, (DeadlineIndexedVar, DeadlineKeyValueVar)): - return False - if v is None: - return False - return True - - serialized = attr.asdict( - self, dict_factory=OrderedDict, filter=filter_data) - - # Custom serialize these attributes - for attribute in [ - self.EnvironmentKeyValue, - self.ExtraInfo, - self.ExtraInfoKeyValue, - self.TaskExtraInfoName, - self.OutputFilename, - self.OutputFilenameTile, - self.OutputDirectory, - self.AssetDependency - ]: - serialized.update(attribute.serialize()) - - return serialized - - def update(self, data): - """Update instance with data dict""" - for key, value in data.items(): - setattr(self, key, value) - - def add_render_job_env_var(self): - """Check if in OP or AYON mode and use appropriate env var.""" - self.EnvironmentKeyValue["AYON_RENDER_JOB"] = "1" - self.EnvironmentKeyValue["AYON_BUNDLE_NAME"] = ( - os.environ["AYON_BUNDLE_NAME"]) - - -@six.add_metaclass(AbstractMetaInstancePlugin) -class AbstractSubmitDeadline(pyblish.api.InstancePlugin, - AYONPyblishPluginMixin): - """Class abstracting access to Deadline.""" - - label = "Submit to Deadline" - order = pyblish.api.IntegratorOrder + 0.1 - - import_reference = False - use_published = True - asset_dependencies = False - default_priority = 50 - - def __init__(self, *args, **kwargs): - super(AbstractSubmitDeadline, self).__init__(*args, **kwargs) - self._instance = None - self._deadline_url = None - self.scene_path = None - self.job_info = None - self.plugin_info = None - self.aux_files = None - - def process(self, instance): - """Plugin entry point.""" - self._instance = instance - context = instance.context - self._deadline_url = instance.data["deadline"]["url"] - - assert self._deadline_url, "Requires Deadline Webservice URL" - - file_path = None - if self.use_published: - if not self.import_reference: - file_path = self.from_published_scene() - else: - self.log.info("use the scene with imported reference for rendering") # noqa - file_path = context.data["currentFile"] - - # fallback if nothing was set - if not file_path: - self.log.warning("Falling back to workfile") - file_path = context.data["currentFile"] - - self.scene_path = file_path - self.log.info("Using {} for render/export.".format(file_path)) - - self.job_info = self.get_job_info() - self.plugin_info = self.get_plugin_info() - self.aux_files = self.get_aux_files() - - job_id = self.process_submission() - self.log.info("Submitted job to Deadline: {}.".format(job_id)) - - # TODO: Find a way that's more generic and not render type specific - if instance.data.get("splitRender"): - self.log.info("Splitting export and render in two jobs") - self.log.info("Export job id: %s", job_id) - render_job_info = self.get_job_info(dependency_job_ids=[job_id]) - render_plugin_info = self.get_plugin_info(job_type="render") - payload = self.assemble_payload( - job_info=render_job_info, - plugin_info=render_plugin_info - ) - auth = instance.data["deadline"]["auth"] - verify = instance.data["deadline"]["verify"] - render_job_id = self.submit(payload, auth, verify) - self.log.info("Render job id: %s", render_job_id) - - def process_submission(self): - """Process data for submission. - - This takes Deadline JobInfo, PluginInfo, AuxFile, creates payload - from them and submit it do Deadline. - - Returns: - str: Deadline job ID - - """ - payload = self.assemble_payload() - auth = self._instance.data["deadline"]["auth"] - verify = self._instance.data["deadline"]["verify"] - return self.submit(payload, auth, verify) - - @abstractmethod - def get_job_info(self): - """Return filled Deadline JobInfo. - - This is host/plugin specific implementation of how to fill data in. - - See: - :class:`DeadlineJobInfo` - - Returns: - :class:`DeadlineJobInfo`: Filled Deadline JobInfo. - - """ - pass - - @abstractmethod - def get_plugin_info(self): - """Return filled Deadline PluginInfo. - - This is host/plugin specific implementation of how to fill data in. - - See: - :class:`DeadlineJobInfo` - - Returns: - dict: Filled Deadline JobInfo. - - """ - pass - - def get_aux_files(self): - """Return list of auxiliary files for Deadline job. - - If needed this should be overridden, otherwise return empty list as - that field even empty must be present on Deadline submission. - - Returns: - list: List of files. - - """ - return [] - - def from_published_scene(self, replace_in_path=True): - """Switch work scene for published scene. - - If rendering/exporting from published scenes is enabled, this will - replace paths from working scene to published scene. - - Args: - replace_in_path (bool): if True, it will try to find - old scene name in path of expected files and replace it - with name of published scene. - - Returns: - str: Published scene path. - None: if no published scene is found. - - Note: - Published scene path is actually determined from project Anatomy - as at the time this plugin is running scene can still no be - published. - - """ - return replace_with_published_scene_path( - self._instance, replace_in_path=replace_in_path) - - def assemble_payload( - self, job_info=None, plugin_info=None, aux_files=None): - """Assemble payload data from its various parts. - - Args: - job_info (DeadlineJobInfo): Deadline JobInfo. You can use - :class:`DeadlineJobInfo` for it. - plugin_info (dict): Deadline PluginInfo. Plugin specific options. - aux_files (list, optional): List of auxiliary file to submit with - the job. - - Returns: - dict: Deadline Payload. - - """ - job = job_info or self.job_info - return { - "JobInfo": job.serialize(), - "PluginInfo": plugin_info or self.plugin_info, - "AuxFiles": aux_files or self.aux_files - } - - def submit(self, payload, auth, verify): - """Submit payload to Deadline API end-point. - - This takes payload in the form of JSON file and POST it to - Deadline jobs end-point. - - Args: - payload (dict): dict to become json in deadline submission. - auth (tuple): (username, password) - verify (bool): verify SSL certificate if present - - Returns: - str: resulting Deadline job id. - - Throws: - KnownPublishError: if submission fails. - - """ - url = "{}/api/jobs".format(self._deadline_url) - response = requests_post( - url, json=payload, auth=auth, verify=verify) - if not response.ok: - self.log.error("Submission failed!") - self.log.error(response.status_code) - self.log.error(response.content) - self.log.debug(payload) - raise KnownPublishError(response.text) - - try: - result = response.json() - except JSONDecodeError: - msg = "Broken response {}. ".format(response) - msg += "Try restarting the Deadline Webservice." - self.log.warning(msg, exc_info=True) - raise KnownPublishError("Broken response from DL") - - # for submit publish job - self._instance.data["deadlineSubmissionJob"] = result - - return result["_id"] diff --git a/server_addon/deadline/client/ayon_deadline/addon.py b/server_addon/deadline/client/ayon_deadline/addon.py deleted file mode 100644 index 87fc2ad665..0000000000 --- a/server_addon/deadline/client/ayon_deadline/addon.py +++ /dev/null @@ -1,81 +0,0 @@ -import os -import sys - -import requests -import six - -from ayon_core.lib import Logger -from ayon_core.addon import AYONAddon, IPluginPaths - -from .version import __version__ - - -class DeadlineWebserviceError(Exception): - """ - Exception to throw when connection to Deadline server fails. - """ - - -class DeadlineAddon(AYONAddon, IPluginPaths): - name = "deadline" - version = __version__ - - def initialize(self, studio_settings): - deadline_settings = studio_settings[self.name] - deadline_servers_info = { - url_item["name"]: url_item - for url_item in deadline_settings["deadline_urls"] - } - - if not deadline_servers_info: - self.enabled = False - self.log.warning(( - "Deadline Webservice URLs are not specified. Disabling addon." - )) - - self.deadline_servers_info = deadline_servers_info - - def get_plugin_paths(self): - """Deadline plugin paths.""" - current_dir = os.path.dirname(os.path.abspath(__file__)) - return { - "publish": [os.path.join(current_dir, "plugins", "publish")] - } - - @staticmethod - def get_deadline_pools(webservice, auth=None, log=None): - """Get pools from Deadline. - Args: - webservice (str): Server url. - auth (Optional[Tuple[str, str]]): Tuple containing username, - password - log (Optional[Logger]): Logger to log errors to, if provided. - Returns: - List[str]: Pools. - Throws: - RuntimeError: If deadline webservice is unreachable. - - """ - from .abstract_submit_deadline import requests_get - - if not log: - log = Logger.get_logger(__name__) - - argument = "{}/api/pools?NamesOnly=true".format(webservice) - try: - kwargs = {} - if auth: - kwargs["auth"] = auth - response = requests_get(argument, **kwargs) - except requests.exceptions.ConnectionError as exc: - msg = 'Cannot connect to DL web service {}'.format(webservice) - log.error(msg) - six.reraise( - DeadlineWebserviceError, - DeadlineWebserviceError('{} - {}'.format(msg, exc)), - sys.exc_info()[2]) - if not response.ok: - log.warning("No pools retrieved") - return [] - - return response.json() diff --git a/server_addon/deadline/client/ayon_deadline/lib.py b/server_addon/deadline/client/ayon_deadline/lib.py deleted file mode 100644 index 7f07c350ec..0000000000 --- a/server_addon/deadline/client/ayon_deadline/lib.py +++ /dev/null @@ -1,10 +0,0 @@ -# describes list of product typed used for plugin filtering for farm publishing -FARM_FAMILIES = [ - "render", "render.farm", "render.frames_farm", - "prerender", "prerender.farm", "prerender.frames_farm", - "renderlayer", "imagesequence", "image", - "vrayscene", "maxrender", - "arnold_rop", "mantra_rop", - "karma_rop", "vray_rop", "redshift_rop", - "renderFarm", "usdrender", "publish.hou" -] diff --git a/server_addon/deadline/client/ayon_deadline/plugins/publish/collect_deadline_server_from_instance.py b/server_addon/deadline/client/ayon_deadline/plugins/publish/collect_deadline_server_from_instance.py deleted file mode 100644 index 2c8cbd1620..0000000000 --- a/server_addon/deadline/client/ayon_deadline/plugins/publish/collect_deadline_server_from_instance.py +++ /dev/null @@ -1,115 +0,0 @@ -# -*- coding: utf-8 -*- -"""Collect Deadline servers from instance. - -This is resolving index of server lists stored in `deadlineServers` instance -attribute or using default server if that attribute doesn't exists. - -""" -import pyblish.api -from ayon_core.pipeline.publish import KnownPublishError - -from ayon_deadline.lib import FARM_FAMILIES - - -class CollectDeadlineServerFromInstance(pyblish.api.InstancePlugin): - """Collect Deadline Webservice URL from instance.""" - - # Run before collect_render. - order = pyblish.api.CollectorOrder + 0.225 - label = "Deadline Webservice from the Instance" - targets = ["local"] - - families = FARM_FAMILIES - - def process(self, instance): - if not instance.data.get("farm"): - self.log.debug("Should not be processed on farm, skipping.") - return - - if not instance.data.get("deadline"): - instance.data["deadline"] = {} - - # todo: separate logic should be removed, all hosts should have same - host_name = instance.context.data["hostName"] - if host_name == "maya": - deadline_url = self._collect_deadline_url(instance) - else: - deadline_url = (instance.data.get("deadlineUrl") or # backwards - instance.data.get("deadline", {}).get("url")) - if deadline_url: - instance.data["deadline"]["url"] = deadline_url.strip().rstrip("/") - else: - instance.data["deadline"]["url"] = instance.context.data["deadline"]["defaultUrl"] # noqa - self.log.debug( - "Using {} for submission".format(instance.data["deadline"]["url"])) - - def _collect_deadline_url(self, render_instance): - # type: (pyblish.api.Instance) -> str - """Get Deadline Webservice URL from render instance. - - This will get all configured Deadline Webservice URLs and create - subset of them based upon project configuration. It will then take - `deadlineServers` from render instance that is now basically `int` - index of that list. - - Args: - render_instance (pyblish.api.Instance): Render instance created - by Creator in Maya. - - Returns: - str: Selected Deadline Webservice URL. - - """ - # Not all hosts can import this module. - from maya import cmds - deadline_settings = ( - render_instance.context.data - ["project_settings"] - ["deadline"] - ) - default_server_url = (render_instance.context.data["deadline"] - ["defaultUrl"]) - # QUESTION How and where is this is set? Should be removed? - instance_server = render_instance.data.get("deadlineServers") - if not instance_server: - self.log.debug("Using default server.") - return default_server_url - - # Get instance server as sting. - if isinstance(instance_server, int): - instance_server = cmds.getAttr( - "{}.deadlineServers".format(render_instance.data["objset"]), - asString=True - ) - - default_servers = { - url_item["name"]: url_item["value"] - for url_item in deadline_settings["deadline_servers_info"] - } - project_servers = ( - render_instance.context.data - ["project_settings"] - ["deadline"] - ["deadline_servers"] - ) - if not project_servers: - self.log.debug("Not project servers found. Using default servers.") - return default_servers[instance_server] - - project_enabled_servers = { - k: default_servers[k] - for k in project_servers - if k in default_servers - } - - if instance_server not in project_enabled_servers: - msg = ( - "\"{}\" server on instance is not enabled in project settings." - " Enabled project servers:\n{}".format( - instance_server, project_enabled_servers - ) - ) - raise KnownPublishError(msg) - - self.log.debug("Using project approved server.") - return project_enabled_servers[instance_server] diff --git a/server_addon/deadline/client/ayon_deadline/plugins/publish/collect_default_deadline_server.py b/server_addon/deadline/client/ayon_deadline/plugins/publish/collect_default_deadline_server.py deleted file mode 100644 index 77d03c713f..0000000000 --- a/server_addon/deadline/client/ayon_deadline/plugins/publish/collect_default_deadline_server.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -"""Collect default Deadline server.""" -import pyblish.api - - -class CollectDefaultDeadlineServer(pyblish.api.ContextPlugin): - """Collect default Deadline Webservice URL. - - DL webservice addresses must be configured first in System Settings for - project settings enum to work. - - Default webservice could be overridden by - `project_settings/deadline/deadline_servers`. Currently only single url - is expected. - - This url could be overridden by some hosts directly on instances with - `CollectDeadlineServerFromInstance`. - """ - - # Run before collect_deadline_server_instance. - order = pyblish.api.CollectorOrder + 0.200 - label = "Default Deadline Webservice" - targets = ["local"] - - def process(self, context): - try: - deadline_addon = context.data["ayonAddonsManager"]["deadline"] - except AttributeError: - self.log.error("Cannot get AYON Deadline addon.") - raise AssertionError("AYON Deadline addon not found.") - - deadline_settings = context.data["project_settings"]["deadline"] - deadline_server_name = deadline_settings["deadline_server"] - - dl_server_info = None - if deadline_server_name: - dl_server_info = deadline_addon.deadline_servers_info.get( - deadline_server_name) - - if dl_server_info: - deadline_url = dl_server_info["value"] - else: - default_dl_server_info = deadline_addon.deadline_servers_info[0] - deadline_url = default_dl_server_info["value"] - - context.data["deadline"] = {} - context.data["deadline"]["defaultUrl"] = ( - deadline_url.strip().rstrip("/")) diff --git a/server_addon/deadline/client/ayon_deadline/plugins/publish/collect_pools.py b/server_addon/deadline/client/ayon_deadline/plugins/publish/collect_pools.py deleted file mode 100644 index b2b6bc60d4..0000000000 --- a/server_addon/deadline/client/ayon_deadline/plugins/publish/collect_pools.py +++ /dev/null @@ -1,91 +0,0 @@ -# -*- coding: utf-8 -*- -import pyblish.api -from ayon_core.lib import TextDef -from ayon_core.pipeline.publish import AYONPyblishPluginMixin - -from ayon_deadline.lib import FARM_FAMILIES - - -class CollectDeadlinePools(pyblish.api.InstancePlugin, - AYONPyblishPluginMixin): - """Collect pools from instance or Publisher attributes, from Setting - otherwise. - - Pools are used to control which DL workers could render the job. - - Pools might be set: - - directly on the instance (set directly in DCC) - - from Publisher attributes - - from defaults from Settings. - - Publisher attributes could be shown even for instances that should be - rendered locally as visibility is driven by product type of the instance - (which will be `render` most likely). - (Might be resolved in the future and class attribute 'families' should - be cleaned up.) - - """ - - order = pyblish.api.CollectorOrder + 0.420 - label = "Collect Deadline Pools" - hosts = [ - "aftereffects", - "fusion", - "harmony", - "maya", - "max", - "houdini", - "nuke", - ] - - families = FARM_FAMILIES - - primary_pool = None - secondary_pool = None - - @classmethod - def apply_settings(cls, project_settings): - # deadline.publish.CollectDeadlinePools - settings = project_settings["deadline"]["publish"]["CollectDeadlinePools"] # noqa - cls.primary_pool = settings.get("primary_pool", None) - cls.secondary_pool = settings.get("secondary_pool", None) - - def process(self, instance): - attr_values = self.get_attr_values_from_data(instance.data) - if not instance.data.get("primaryPool"): - instance.data["primaryPool"] = ( - attr_values.get("primaryPool") or self.primary_pool or "none" - ) - if instance.data["primaryPool"] == "-": - instance.data["primaryPool"] = None - - if not instance.data.get("secondaryPool"): - instance.data["secondaryPool"] = ( - attr_values.get("secondaryPool") or self.secondary_pool or "none" # noqa - ) - - if instance.data["secondaryPool"] == "-": - instance.data["secondaryPool"] = None - - @classmethod - def get_attribute_defs(cls): - # TODO: Preferably this would be an enum for the user - # but the Deadline server URL can be dynamic and - # can be set per render instance. Since get_attribute_defs - # can't be dynamic unfortunately EnumDef isn't possible (yet?) - # pool_names = self.deadline_addon.get_deadline_pools(deadline_url, - # self.log) - # secondary_pool_names = ["-"] + pool_names - - return [ - TextDef("primaryPool", - label="Primary Pool", - default=cls.primary_pool, - tooltip="Deadline primary pool, " - "applicable for farm rendering"), - TextDef("secondaryPool", - label="Secondary Pool", - default=cls.secondary_pool, - tooltip="Deadline secondary pool, " - "applicable for farm rendering") - ] diff --git a/server_addon/deadline/client/ayon_deadline/plugins/publish/collect_user_credentials.py b/server_addon/deadline/client/ayon_deadline/plugins/publish/collect_user_credentials.py deleted file mode 100644 index ab96ba5828..0000000000 --- a/server_addon/deadline/client/ayon_deadline/plugins/publish/collect_user_credentials.py +++ /dev/null @@ -1,83 +0,0 @@ -# -*- coding: utf-8 -*- -"""Collect user credentials - -Requires: - context -> project_settings - instance.data["deadline"]["url"] - -Provides: - instance.data["deadline"] -> require_authentication (bool) - instance.data["deadline"] -> auth (tuple (str, str)) - - (username, password) or None -""" -import pyblish.api - -from ayon_api import get_server_api_connection - -from ayon_deadline.lib import FARM_FAMILIES - - -class CollectDeadlineUserCredentials(pyblish.api.InstancePlugin): - """Collects user name and password for artist if DL requires authentication - """ - order = pyblish.api.CollectorOrder + 0.250 - label = "Collect Deadline User Credentials" - - targets = ["local"] - hosts = ["aftereffects", - "blender", - "fusion", - "harmony", - "nuke", - "maya", - "max", - "houdini"] - - families = FARM_FAMILIES - - def process(self, instance): - if not instance.data.get("farm"): - self.log.debug("Should not be processed on farm, skipping.") - return - - collected_deadline_url = instance.data["deadline"]["url"] - if not collected_deadline_url: - raise ValueError("Instance doesn't have '[deadline][url]'.") - context_data = instance.context.data - deadline_settings = context_data["project_settings"]["deadline"] - - deadline_server_name = None - # deadline url might be set directly from instance, need to find - # metadata for it - for deadline_info in deadline_settings["deadline_urls"]: - dl_settings_url = deadline_info["value"].strip().rstrip("/") - if dl_settings_url == collected_deadline_url: - deadline_server_name = deadline_info["name"] - break - - if not deadline_server_name: - raise ValueError(f"Collected {collected_deadline_url} doesn't " - "match any site configured in Studio Settings") - - instance.data["deadline"]["require_authentication"] = ( - deadline_info["require_authentication"] - ) - instance.data["deadline"]["auth"] = None - - instance.data["deadline"]["verify"] = ( - not deadline_info["not_verify_ssl"]) - - if not deadline_info["require_authentication"]: - return - - addons_manager = instance.context.data["ayonAddonsManager"] - deadline_addon = addons_manager["deadline"] - # TODO import 'get_addon_site_settings' when available - # in public 'ayon_api' - local_settings = get_server_api_connection().get_addon_site_settings( - deadline_addon.name, deadline_addon.version) - local_settings = local_settings["local_settings"] - for server_info in local_settings: - if deadline_server_name == server_info["server_name"]: - instance.data["deadline"]["auth"] = (server_info["username"], - server_info["password"]) diff --git a/server_addon/deadline/client/ayon_deadline/plugins/publish/help/validate_deadline_connection.xml b/server_addon/deadline/client/ayon_deadline/plugins/publish/help/validate_deadline_connection.xml deleted file mode 100644 index eec05df08a..0000000000 --- a/server_addon/deadline/client/ayon_deadline/plugins/publish/help/validate_deadline_connection.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - Deadline Authentication - -## Deadline authentication is required - -This project has set in Settings that Deadline requires authentication. - -### How to repair? - -Please go to Ayon Server > Site Settings and provide your Deadline username and password. -In some cases the password may be empty if Deadline is configured to allow that. Ask your administrator. - - - - \ No newline at end of file diff --git a/server_addon/deadline/client/ayon_deadline/plugins/publish/help/validate_deadline_pools.xml b/server_addon/deadline/client/ayon_deadline/plugins/publish/help/validate_deadline_pools.xml deleted file mode 100644 index 879adcee97..0000000000 --- a/server_addon/deadline/client/ayon_deadline/plugins/publish/help/validate_deadline_pools.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - Deadline Pools - -## Invalid Deadline pools found - -Configured pools don't match available pools in Deadline. - -### How to repair? - -If your instance had deadline pools set on creation, remove or -change them. - -In other cases inform admin to change them in Settings. - -Available deadline pools: - -{pools_str} - - - -### __Detailed Info__ - -This error is shown when a configured pool is not available on Deadline. It -can happen when publishing old workfiles which were created with previous -deadline pools, or someone changed the available pools in Deadline, -but didn't modify AYON Settings to match the changes. - - - \ No newline at end of file diff --git a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_aftereffects_deadline.py b/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_aftereffects_deadline.py deleted file mode 100644 index 45d907cbba..0000000000 --- a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_aftereffects_deadline.py +++ /dev/null @@ -1,143 +0,0 @@ -import os -import attr -import getpass -import pyblish.api -from datetime import datetime - -from ayon_core.lib import ( - env_value_to_bool, - collect_frames, - is_in_tests, -) -from ayon_deadline import abstract_submit_deadline -from ayon_deadline.abstract_submit_deadline import DeadlineJobInfo - - -@attr.s -class DeadlinePluginInfo(): - Comp = attr.ib(default=None) - SceneFile = attr.ib(default=None) - OutputFilePath = attr.ib(default=None) - Output = attr.ib(default=None) - StartupDirectory = attr.ib(default=None) - Arguments = attr.ib(default=None) - ProjectPath = attr.ib(default=None) - AWSAssetFile0 = attr.ib(default=None) - Version = attr.ib(default=None) - MultiProcess = attr.ib(default=None) - - -class AfterEffectsSubmitDeadline( - abstract_submit_deadline.AbstractSubmitDeadline -): - - label = "Submit AE to Deadline" - order = pyblish.api.IntegratorOrder + 0.1 - hosts = ["aftereffects"] - families = ["render.farm"] # cannot be "render' as that is integrated - use_published = True - targets = ["local"] - - priority = 50 - chunk_size = 1000000 - group = None - department = None - multiprocess = True - - def get_job_info(self): - dln_job_info = DeadlineJobInfo(Plugin="AfterEffects") - - context = self._instance.context - - batch_name = os.path.basename(self._instance.data["source"]) - if is_in_tests(): - batch_name += datetime.now().strftime("%d%m%Y%H%M%S") - dln_job_info.Name = self._instance.data["name"] - dln_job_info.BatchName = batch_name - dln_job_info.Plugin = "AfterEffects" - dln_job_info.UserName = context.data.get( - "deadlineUser", getpass.getuser()) - # Deadline requires integers in frame range - frame_range = "{}-{}".format( - int(round(self._instance.data["frameStart"])), - int(round(self._instance.data["frameEnd"]))) - dln_job_info.Frames = frame_range - - dln_job_info.Priority = self.priority - dln_job_info.Pool = self._instance.data.get("primaryPool") - dln_job_info.SecondaryPool = self._instance.data.get("secondaryPool") - dln_job_info.Group = self.group - dln_job_info.Department = self.department - dln_job_info.ChunkSize = self.chunk_size - dln_job_info.OutputFilename += \ - os.path.basename(self._instance.data["expectedFiles"][0]) - dln_job_info.OutputDirectory += \ - os.path.dirname(self._instance.data["expectedFiles"][0]) - dln_job_info.JobDelay = "00:00:00" - - keys = [ - "FTRACK_API_KEY", - "FTRACK_API_USER", - "FTRACK_SERVER", - "AYON_BUNDLE_NAME", - "AYON_DEFAULT_SETTINGS_VARIANT", - "AYON_PROJECT_NAME", - "AYON_FOLDER_PATH", - "AYON_TASK_NAME", - "AYON_WORKDIR", - "AYON_APP_NAME", - "AYON_LOG_NO_COLORS", - "AYON_IN_TESTS" - ] - - environment = { - key: os.environ[key] - for key in keys - if key in os.environ - } - for key in keys: - value = environment.get(key) - if value: - dln_job_info.EnvironmentKeyValue[key] = value - - # to recognize render jobs - dln_job_info.add_render_job_env_var() - - return dln_job_info - - def get_plugin_info(self): - deadline_plugin_info = DeadlinePluginInfo() - - render_path = self._instance.data["expectedFiles"][0] - - file_name, frame = list(collect_frames([render_path]).items())[0] - if frame: - # replace frame ('000001') with Deadline's required '[#######]' - # expects filename in format project_folder_product_version.FRAME.ext - render_dir = os.path.dirname(render_path) - file_name = os.path.basename(render_path) - hashed = '[{}]'.format(len(frame) * "#") - file_name = file_name.replace(frame, hashed) - render_path = os.path.join(render_dir, file_name) - - deadline_plugin_info.Comp = self._instance.data["comp_name"] - deadline_plugin_info.Version = self._instance.data["app_version"] - # must be here because of DL AE plugin - # added override of multiprocess by env var, if shouldn't be used for - # some app variant use MULTIPROCESS:false in Settings, default is True - env_multi = env_value_to_bool("MULTIPROCESS", default=True) - deadline_plugin_info.MultiProcess = env_multi and self.multiprocess - deadline_plugin_info.SceneFile = self.scene_path - deadline_plugin_info.Output = render_path.replace("\\", "/") - - return attr.asdict(deadline_plugin_info) - - def from_published_scene(self): - """ Do not overwrite expected files. - - Use published is set to True, so rendering will be triggered - from published scene (in 'publish' folder). Default implementation - of abstract class renames expected (eg. rendered) files accordingly - which is not needed here. - """ - return super().from_published_scene(False) diff --git a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_blender_deadline.py b/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_blender_deadline.py deleted file mode 100644 index 073de909b4..0000000000 --- a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_blender_deadline.py +++ /dev/null @@ -1,225 +0,0 @@ -# -*- coding: utf-8 -*- -"""Submitting render job to Deadline.""" - -import os -import getpass -import attr -from datetime import datetime - -from ayon_core.lib import ( - BoolDef, - NumberDef, - TextDef, - is_in_tests, -) -from ayon_core.pipeline.publish import AYONPyblishPluginMixin -from ayon_core.pipeline.farm.tools import iter_expected_files - -from ayon_deadline import abstract_submit_deadline -from ayon_deadline.abstract_submit_deadline import DeadlineJobInfo - - -@attr.s -class BlenderPluginInfo(): - SceneFile = attr.ib(default=None) # Input - Version = attr.ib(default=None) # Mandatory for Deadline - SaveFile = attr.ib(default=True) - - -class BlenderSubmitDeadline(abstract_submit_deadline.AbstractSubmitDeadline, - AYONPyblishPluginMixin): - label = "Submit Render to Deadline" - hosts = ["blender"] - families = ["render"] - settings_category = "deadline" - - use_published = True - priority = 50 - chunk_size = 1 - jobInfo = {} - pluginInfo = {} - group = None - job_delay = "00:00:00:00" - - def get_job_info(self): - job_info = DeadlineJobInfo(Plugin="Blender") - - job_info.update(self.jobInfo) - - instance = self._instance - context = instance.context - - # Always use the original work file name for the Job name even when - # rendering is done from the published Work File. The original work - # file name is clearer because it can also have subversion strings, - # etc. which are stripped for the published file. - src_filepath = context.data["currentFile"] - src_filename = os.path.basename(src_filepath) - - if is_in_tests(): - src_filename += datetime.now().strftime("%d%m%Y%H%M%S") - - job_info.Name = f"{src_filename} - {instance.name}" - job_info.BatchName = src_filename - instance.data.get("blenderRenderPlugin", "Blender") - job_info.UserName = context.data.get("deadlineUser", getpass.getuser()) - - # Deadline requires integers in frame range - frames = "{start}-{end}x{step}".format( - start=int(instance.data["frameStartHandle"]), - end=int(instance.data["frameEndHandle"]), - step=int(instance.data["byFrameStep"]), - ) - job_info.Frames = frames - - job_info.Pool = instance.data.get("primaryPool") - job_info.SecondaryPool = instance.data.get("secondaryPool") - job_info.Comment = instance.data.get("comment") - - if self.group != "none" and self.group: - job_info.Group = self.group - - attr_values = self.get_attr_values_from_data(instance.data) - render_globals = instance.data.setdefault("renderGlobals", {}) - machine_list = attr_values.get("machineList", "") - if machine_list: - if attr_values.get("whitelist", True): - machine_list_key = "Whitelist" - else: - machine_list_key = "Blacklist" - render_globals[machine_list_key] = machine_list - - job_info.ChunkSize = attr_values.get("chunkSize", self.chunk_size) - job_info.Priority = attr_values.get("priority", self.priority) - job_info.ScheduledType = "Once" - job_info.JobDelay = attr_values.get("job_delay", self.job_delay) - - # Add options from RenderGlobals - render_globals = instance.data.get("renderGlobals", {}) - job_info.update(render_globals) - - keys = [ - "FTRACK_API_KEY", - "FTRACK_API_USER", - "FTRACK_SERVER", - "OPENPYPE_SG_USER", - "AYON_BUNDLE_NAME", - "AYON_DEFAULT_SETTINGS_VARIANT", - "AYON_PROJECT_NAME", - "AYON_FOLDER_PATH", - "AYON_TASK_NAME", - "AYON_WORKDIR", - "AYON_APP_NAME", - "AYON_IN_TESTS" - ] - - environment = { - key: os.environ[key] - for key in keys - if key in os.environ - } - - for key in keys: - value = environment.get(key) - if not value: - continue - job_info.EnvironmentKeyValue[key] = value - - # to recognize job from PYPE for turning Event On/Off - job_info.add_render_job_env_var() - job_info.EnvironmentKeyValue["AYON_LOG_NO_COLORS"] = "1" - - # Adding file dependencies. - if self.asset_dependencies: - dependencies = instance.context.data["fileDependencies"] - for dependency in dependencies: - job_info.AssetDependency += dependency - - # Add list of expected files to job - # --------------------------------- - exp = instance.data.get("expectedFiles") - for filepath in iter_expected_files(exp): - job_info.OutputDirectory += os.path.dirname(filepath) - job_info.OutputFilename += os.path.basename(filepath) - - return job_info - - def get_plugin_info(self): - # Not all hosts can import this module. - import bpy - - plugin_info = BlenderPluginInfo( - SceneFile=self.scene_path, - Version=bpy.app.version_string, - SaveFile=True, - ) - - plugin_payload = attr.asdict(plugin_info) - - # Patching with pluginInfo from settings - for key, value in self.pluginInfo.items(): - plugin_payload[key] = value - - return plugin_payload - - def process_submission(self, auth=None): - instance = self._instance - - expected_files = instance.data["expectedFiles"] - if not expected_files: - raise RuntimeError("No Render Elements found!") - - first_file = next(iter_expected_files(expected_files)) - output_dir = os.path.dirname(first_file) - instance.data["outputDir"] = output_dir - instance.data["toBeRenderedOn"] = "deadline" - - payload = self.assemble_payload() - auth = self._instance.data["deadline"]["auth"] - verify = self._instance.data["deadline"]["verify"] - return self.submit(payload, auth=auth, verify=verify) - - def from_published_scene(self): - """ - This is needed to set the correct path for the json metadata. Because - the rendering path is set in the blend file during the collection, - and the path is adjusted to use the published scene, this ensures that - the metadata and the rendered files are in the same location. - """ - return super().from_published_scene(False) - - @classmethod - def get_attribute_defs(cls): - defs = super(BlenderSubmitDeadline, cls).get_attribute_defs() - defs.extend([ - BoolDef("use_published", - default=cls.use_published, - label="Use Published Scene"), - - NumberDef("priority", - minimum=1, - maximum=250, - decimals=0, - default=cls.priority, - label="Priority"), - - NumberDef("chunkSize", - minimum=1, - maximum=50, - decimals=0, - default=cls.chunk_size, - label="Frame Per Task"), - - TextDef("group", - default=cls.group, - label="Group Name"), - - TextDef("job_delay", - default=cls.job_delay, - label="Job Delay", - placeholder="dd:hh:mm:ss", - tooltip="Delay the job by the specified amount of time. " - "Timecode: dd:hh:mm:ss."), - ]) - - return defs diff --git a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_celaction_deadline.py b/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_celaction_deadline.py deleted file mode 100644 index e9313e3f2f..0000000000 --- a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_celaction_deadline.py +++ /dev/null @@ -1,271 +0,0 @@ -import os -import re -import json -import getpass -import pyblish.api - -from ayon_deadline.abstract_submit_deadline import requests_post - - -class CelactionSubmitDeadline(pyblish.api.InstancePlugin): - """Submit CelAction2D scene to Deadline - - Renders are submitted to a Deadline Web Service. - - """ - - label = "Submit CelAction to Deadline" - order = pyblish.api.IntegratorOrder + 0.1 - hosts = ["celaction"] - families = ["render.farm"] - settings_category = "deadline" - - deadline_department = "" - deadline_priority = 50 - deadline_pool = "" - deadline_pool_secondary = "" - deadline_group = "" - deadline_chunk_size = 1 - deadline_job_delay = "00:00:08:00" - - def process(self, instance): - - context = instance.context - - deadline_url = instance.data["deadline"]["url"] - assert deadline_url, "Requires Deadline Webservice URL" - - self.deadline_url = "{}/api/jobs".format(deadline_url) - self._comment = instance.data["comment"] - self._deadline_user = context.data.get( - "deadlineUser", getpass.getuser()) - self._frame_start = int(instance.data["frameStart"]) - self._frame_end = int(instance.data["frameEnd"]) - - # get output path - render_path = instance.data['path'] - script_path = context.data["currentFile"] - - response = self.payload_submit(instance, - script_path, - render_path - ) - # Store output dir for unified publisher (filesequence) - instance.data["deadlineSubmissionJob"] = response.json() - - instance.data["outputDir"] = os.path.dirname( - render_path).replace("\\", "/") - - instance.data["publishJobState"] = "Suspended" - - # adding 2d render specific family for version identification in Loader - instance.data["families"] = ["render2d"] - - def payload_submit(self, - instance, - script_path, - render_path - ): - resolution_width = instance.data["resolutionWidth"] - resolution_height = instance.data["resolutionHeight"] - render_dir = os.path.normpath(os.path.dirname(render_path)) - render_path = os.path.normpath(render_path) - script_name = os.path.basename(script_path) - - anatomy = instance.context.data["anatomy"] - publish_template = anatomy.get_template_item( - "publish", "default", "path" - ) - for item in instance.context: - if "workfile" in item.data["productType"]: - msg = "Workfile (scene) must be published along" - assert item.data["publish"] is True, msg - - template_data = item.data.get("anatomyData") - rep = item.data.get("representations")[0].get("name") - template_data["representation"] = rep - template_data["ext"] = rep - template_data["comment"] = None - template_filled = publish_template.format_strict( - template_data - ) - script_path = os.path.normpath(template_filled) - - self.log.info( - "Using published scene for render {}".format(script_path) - ) - - jobname = "%s - %s" % (script_name, instance.name) - - output_filename_0 = self.preview_fname(render_path) - - try: - # Ensure render folder exists - os.makedirs(render_dir) - except OSError: - pass - - # define chunk and priority - chunk_size = instance.context.data.get("chunk") - if not chunk_size: - chunk_size = self.deadline_chunk_size - - # search for %02d pattern in name, and padding number - search_results = re.search(r"(%0)(\d)(d)[._]", render_path).groups() - split_patern = "".join(search_results) - padding_number = int(search_results[1]) - - args = [ - f"{script_path}", - "-a", - "-16", - "-s ", - "-e ", - f"-d {render_dir}", - f"-x {resolution_width}", - f"-y {resolution_height}", - f"-r {render_path.replace(split_patern, '')}", - f"-= AbsoluteFrameNumber=on -= PadDigits={padding_number}", - "-= ClearAttachment=on", - ] - - payload = { - "JobInfo": { - # Job name, as seen in Monitor - "Name": jobname, - - # plugin definition - "Plugin": "CelAction", - - # Top-level group name - "BatchName": script_name, - - # Arbitrary username, for visualisation in Monitor - "UserName": self._deadline_user, - - "Department": self.deadline_department, - "Priority": self.deadline_priority, - - "Group": self.deadline_group, - "Pool": self.deadline_pool, - "SecondaryPool": self.deadline_pool_secondary, - "ChunkSize": chunk_size, - - "Frames": f"{self._frame_start}-{self._frame_end}", - "Comment": self._comment, - - # Optional, enable double-click to preview rendered - # frames from Deadline Monitor - "OutputFilename0": output_filename_0.replace("\\", "/"), - - # # Asset dependency to wait for at least - # the scene file to sync. - # "AssetDependency0": script_path - "ScheduledType": "Once", - "JobDelay": self.deadline_job_delay - }, - "PluginInfo": { - # Input - "SceneFile": script_path, - - # Output directory - "OutputFilePath": render_dir.replace("\\", "/"), - - # Plugin attributes - "StartupDirectory": "", - "Arguments": " ".join(args), - - # Resolve relative references - "ProjectPath": script_path, - "AWSAssetFile0": render_path, - }, - - # Mandatory for Deadline, may be empty - "AuxFiles": [] - } - - plugin = payload["JobInfo"]["Plugin"] - self.log.debug("using render plugin : {}".format(plugin)) - - self.log.debug("Submitting..") - self.log.debug(json.dumps(payload, indent=4, sort_keys=True)) - - # adding expectied files to instance.data - self.expected_files(instance, render_path) - self.log.debug("__ expectedFiles: `{}`".format( - instance.data["expectedFiles"])) - auth = instance.data["deadline"]["auth"] - verify = instance.data["deadline"]["verify"] - response = requests_post(self.deadline_url, json=payload, - auth=auth, - verify=verify) - - if not response.ok: - self.log.error( - "Submission failed! [{}] {}".format( - response.status_code, response.content)) - self.log.debug(payload) - raise SystemExit(response.text) - - return response - - def preflight_check(self, instance): - """Ensure the startFrame, endFrame and byFrameStep are integers""" - - for key in ("frameStart", "frameEnd"): - value = instance.data[key] - - if int(value) == value: - continue - - self.log.warning( - "%f=%d was rounded off to nearest integer" - % (value, int(value)) - ) - - def preview_fname(self, path): - """Return output file path with #### for padding. - - Deadline requires the path to be formatted with # in place of numbers. - For example `/path/to/render.####.png` - - Args: - path (str): path to rendered images - - Returns: - str - - """ - self.log.debug("_ path: `{}`".format(path)) - if "%" in path: - search_results = re.search(r"[._](%0)(\d)(d)[._]", path).groups() - split_patern = "".join(search_results) - split_path = path.split(split_patern) - hashes = "#" * int(search_results[1]) - return "".join([split_path[0], hashes, split_path[-1]]) - - self.log.debug("_ path: `{}`".format(path)) - return path - - def expected_files(self, instance, filepath): - """ Create expected files in instance data - """ - if not instance.data.get("expectedFiles"): - instance.data["expectedFiles"] = [] - - dirpath = os.path.dirname(filepath) - filename = os.path.basename(filepath) - - if "#" in filename: - pparts = filename.split("#") - padding = "%0{}d".format(len(pparts) - 1) - filename = pparts[0] + padding + pparts[-1] - - if "%" not in filename: - instance.data["expectedFiles"].append(filepath) - return - - for i in range(self._frame_start, (self._frame_end + 1)): - instance.data["expectedFiles"].append( - os.path.join(dirpath, (filename % i)).replace("\\", "/") - ) diff --git a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_fusion_deadline.py b/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_fusion_deadline.py deleted file mode 100644 index bf9df40edc..0000000000 --- a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_fusion_deadline.py +++ /dev/null @@ -1,253 +0,0 @@ -import os -import json -import getpass - -import pyblish.api - -from ayon_deadline.abstract_submit_deadline import requests_post -from ayon_core.pipeline.publish import ( - AYONPyblishPluginMixin -) -from ayon_core.lib import NumberDef - - -class FusionSubmitDeadline( - pyblish.api.InstancePlugin, - AYONPyblishPluginMixin -): - """Submit current Comp to Deadline - - Renders are submitted to a Deadline Web Service as - supplied via settings key "DEADLINE_REST_URL". - - """ - - label = "Submit Fusion to Deadline" - order = pyblish.api.IntegratorOrder - hosts = ["fusion"] - families = ["render"] - targets = ["local"] - settings_category = "deadline" - - # presets - plugin = None - - priority = 50 - chunk_size = 1 - concurrent_tasks = 1 - group = "" - - @classmethod - def get_attribute_defs(cls): - return [ - NumberDef( - "priority", - label="Priority", - default=cls.priority, - decimals=0 - ), - NumberDef( - "chunk", - label="Frames Per Task", - default=cls.chunk_size, - decimals=0, - minimum=1, - maximum=1000 - ), - NumberDef( - "concurrency", - label="Concurrency", - default=cls.concurrent_tasks, - decimals=0, - minimum=1, - maximum=10 - ) - ] - - def process(self, instance): - if not instance.data.get("farm"): - self.log.debug("Skipping local instance.") - return - - attribute_values = self.get_attr_values_from_data( - instance.data) - - context = instance.context - - key = "__hasRun{}".format(self.__class__.__name__) - if context.data.get(key, False): - return - else: - context.data[key] = True - - from ayon_fusion.api.lib import get_frame_path - - deadline_url = instance.data["deadline"]["url"] - assert deadline_url, "Requires Deadline Webservice URL" - - # Collect all saver instances in context that are to be rendered - saver_instances = [] - for inst in context: - if inst.data["productType"] != "render": - # Allow only saver family instances - continue - - if not inst.data.get("publish", True): - # Skip inactive instances - continue - - self.log.debug(inst.data["name"]) - saver_instances.append(inst) - - if not saver_instances: - raise RuntimeError("No instances found for Deadline submission") - - comment = instance.data.get("comment", "") - deadline_user = context.data.get("deadlineUser", getpass.getuser()) - - script_path = context.data["currentFile"] - - anatomy = instance.context.data["anatomy"] - publish_template = anatomy.get_template_item( - "publish", "default", "path" - ) - for item in context: - if "workfile" in item.data["families"]: - msg = "Workfile (scene) must be published along" - assert item.data["publish"] is True, msg - - template_data = item.data.get("anatomyData") - rep = item.data.get("representations")[0].get("name") - template_data["representation"] = rep - template_data["ext"] = rep - template_data["comment"] = None - template_filled = publish_template.format_strict( - template_data - ) - script_path = os.path.normpath(template_filled) - - self.log.info( - "Using published scene for render {}".format(script_path) - ) - - filename = os.path.basename(script_path) - - # Documentation for keys available at: - # https://docs.thinkboxsoftware.com - # /products/deadline/8.0/1_User%20Manual/manual - # /manual-submission.html#job-info-file-options - payload = { - "JobInfo": { - # Top-level group name - "BatchName": filename, - - # Asset dependency to wait for at least the scene file to sync. - "AssetDependency0": script_path, - - # Job name, as seen in Monitor - "Name": filename, - - "Priority": attribute_values.get( - "priority", self.priority), - "ChunkSize": attribute_values.get( - "chunk", self.chunk_size), - "ConcurrentTasks": attribute_values.get( - "concurrency", - self.concurrent_tasks - ), - - # User, as seen in Monitor - "UserName": deadline_user, - - "Pool": instance.data.get("primaryPool"), - "SecondaryPool": instance.data.get("secondaryPool"), - "Group": self.group, - - "Plugin": self.plugin, - "Frames": "{start}-{end}".format( - start=int(instance.data["frameStartHandle"]), - end=int(instance.data["frameEndHandle"]) - ), - - "Comment": comment, - }, - "PluginInfo": { - # Input - "FlowFile": script_path, - - # Mandatory for Deadline - "Version": str(instance.data["app_version"]), - - # Render in high quality - "HighQuality": True, - - # Whether saver output should be checked after rendering - # is complete - "CheckOutput": True, - - # Proxy: higher numbers smaller images for faster test renders - # 1 = no proxy quality - "Proxy": 1 - }, - - # Mandatory for Deadline, may be empty - "AuxFiles": [] - } - - # Enable going to rendered frames from Deadline Monitor - for index, instance in enumerate(saver_instances): - head, padding, tail = get_frame_path( - instance.data["expectedFiles"][0] - ) - path = "{}{}{}".format(head, "#" * padding, tail) - folder, filename = os.path.split(path) - payload["JobInfo"]["OutputDirectory%d" % index] = folder - payload["JobInfo"]["OutputFilename%d" % index] = filename - - # Include critical variables with submission - keys = [ - "FTRACK_API_KEY", - "FTRACK_API_USER", - "FTRACK_SERVER", - "AYON_BUNDLE_NAME", - "AYON_DEFAULT_SETTINGS_VARIANT", - "AYON_PROJECT_NAME", - "AYON_FOLDER_PATH", - "AYON_TASK_NAME", - "AYON_WORKDIR", - "AYON_APP_NAME", - "AYON_LOG_NO_COLORS", - "AYON_IN_TESTS", - "AYON_BUNDLE_NAME", - ] - - environment = { - key: os.environ[key] - for key in keys - if key in os.environ - } - - # to recognize render jobs - environment["AYON_RENDER_JOB"] = "1" - - payload["JobInfo"].update({ - "EnvironmentKeyValue%d" % index: "{key}={value}".format( - key=key, - value=environment[key] - ) for index, key in enumerate(environment) - }) - - self.log.debug("Submitting..") - self.log.debug(json.dumps(payload, indent=4, sort_keys=True)) - - # E.g. http://192.168.0.1:8082/api/jobs - url = "{}/api/jobs".format(deadline_url) - auth = instance.data["deadline"]["auth"] - verify = instance.data["deadline"]["verify"] - response = requests_post(url, json=payload, auth=auth, verify=verify) - if not response.ok: - raise Exception(response.text) - - # Store the response for dependent job submission plug-ins - for instance in saver_instances: - instance.data["deadlineSubmissionJob"] = response.json() diff --git a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_harmony_deadline.py b/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_harmony_deadline.py deleted file mode 100644 index bc91483c4f..0000000000 --- a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_harmony_deadline.py +++ /dev/null @@ -1,420 +0,0 @@ -# -*- coding: utf-8 -*- -"""Submitting render job to Deadline.""" -import os -from pathlib import Path -from collections import OrderedDict -from zipfile import ZipFile, is_zipfile -import re -from datetime import datetime - -import attr -import pyblish.api - -from ayon_deadline import abstract_submit_deadline -from ayon_deadline.abstract_submit_deadline import DeadlineJobInfo -from ayon_core.lib import is_in_tests - - -class _ZipFile(ZipFile): - """Extended check for windows invalid characters.""" - - # this is extending default zipfile table for few invalid characters - # that can come from Mac - _windows_illegal_characters = ":<>|\"?*\r\n\x00" - _windows_illegal_name_trans_table = str.maketrans( - _windows_illegal_characters, - "_" * len(_windows_illegal_characters) - ) - - -@attr.s -class PluginInfo(object): - """Plugin info structure for Harmony Deadline plugin.""" - - SceneFile = attr.ib() - # Harmony version - Version = attr.ib() - - Camera = attr.ib(default="") - FieldOfView = attr.ib(default=41.11) - IsDatabase = attr.ib(default=False) - ResolutionX = attr.ib(default=1920) - ResolutionY = attr.ib(default=1080) - - # Resolution name preset, default - UsingResPreset = attr.ib(default=False) - ResolutionName = attr.ib(default="HDTV_1080p24") - - PreRenderInlineScript = attr.ib(default=None) - - # -------------------------------------------------- - _outputNode = attr.ib(factory=list) - - @property - def OutputNode(self): # noqa: N802 - """Return all output nodes formatted for Deadline. - - Returns: - dict: as `{'Output0Node', 'Top/renderFarmDefault'}` - - """ - out = {} - for index, v in enumerate(self._outputNode): - out["Output{}Node".format(index)] = v - return out - - @OutputNode.setter - def OutputNode(self, val): # noqa: N802 - self._outputNode.append(val) - - # -------------------------------------------------- - _outputType = attr.ib(factory=list) - - @property - def OutputType(self): # noqa: N802 - """Return output nodes type formatted for Deadline. - - Returns: - dict: as `{'Output0Type', 'Image'}` - - """ - out = {} - for index, v in enumerate(self._outputType): - out["Output{}Type".format(index)] = v - return out - - @OutputType.setter - def OutputType(self, val): # noqa: N802 - self._outputType.append(val) - - # -------------------------------------------------- - _outputLeadingZero = attr.ib(factory=list) - - @property - def OutputLeadingZero(self): # noqa: N802 - """Return output nodes type formatted for Deadline. - - Returns: - dict: as `{'Output0LeadingZero', '3'}` - - """ - out = {} - for index, v in enumerate(self._outputLeadingZero): - out["Output{}LeadingZero".format(index)] = v - return out - - @OutputLeadingZero.setter - def OutputLeadingZero(self, val): # noqa: N802 - self._outputLeadingZero.append(val) - - # -------------------------------------------------- - _outputFormat = attr.ib(factory=list) - - @property - def OutputFormat(self): # noqa: N802 - """Return output nodes format formatted for Deadline. - - Returns: - dict: as `{'Output0Type', 'PNG4'}` - - """ - out = {} - for index, v in enumerate(self._outputFormat): - out["Output{}Format".format(index)] = v - return out - - @OutputFormat.setter - def OutputFormat(self, val): # noqa: N802 - self._outputFormat.append(val) - - # -------------------------------------------------- - _outputStartFrame = attr.ib(factory=list) - - @property - def OutputStartFrame(self): # noqa: N802 - """Return start frame for output nodes formatted for Deadline. - - Returns: - dict: as `{'Output0StartFrame', '1'}` - - """ - out = {} - for index, v in enumerate(self._outputStartFrame): - out["Output{}StartFrame".format(index)] = v - return out - - @OutputStartFrame.setter - def OutputStartFrame(self, val): # noqa: N802 - self._outputStartFrame.append(val) - - # -------------------------------------------------- - _outputPath = attr.ib(factory=list) - - @property - def OutputPath(self): # noqa: N802 - """Return output paths for nodes formatted for Deadline. - - Returns: - dict: as `{'Output0Path', '/output/path'}` - - """ - out = {} - for index, v in enumerate(self._outputPath): - out["Output{}Path".format(index)] = v - return out - - @OutputPath.setter - def OutputPath(self, val): # noqa: N802 - self._outputPath.append(val) - - def set_output(self, node, image_format, output, - output_type="Image", zeros=3, start_frame=1): - """Helper to set output. - - This should be used instead of setting properties individually - as so index remain consistent. - - Args: - node (str): harmony write node name - image_format (str): format of output (PNG4, TIF, ...) - output (str): output path - output_type (str, optional): "Image" or "Movie" (not supported). - zeros (int, optional): Leading zeros (for 0001 = 3) - start_frame (int, optional): Sequence offset. - - """ - - self.OutputNode = node - self.OutputFormat = image_format - self.OutputPath = output - self.OutputType = output_type - self.OutputLeadingZero = zeros - self.OutputStartFrame = start_frame - - def serialize(self): - """Return all data serialized as dictionary. - - Returns: - OrderedDict: all serialized data. - - """ - def filter_data(a, v): - if a.name.startswith("_"): - return False - if v is None: - return False - return True - - serialized = attr.asdict( - self, dict_factory=OrderedDict, filter=filter_data) - serialized.update(self.OutputNode) - serialized.update(self.OutputFormat) - serialized.update(self.OutputPath) - serialized.update(self.OutputType) - serialized.update(self.OutputLeadingZero) - serialized.update(self.OutputStartFrame) - - return serialized - - -class HarmonySubmitDeadline( - abstract_submit_deadline.AbstractSubmitDeadline -): - """Submit render write of Harmony scene to Deadline. - - Renders are submitted to a Deadline Web Service as - supplied via the environment variable ``DEADLINE_REST_URL``. - - Note: - If Deadline configuration is not detected, this plugin will - be disabled. - - Attributes: - use_published (bool): Use published scene to render instead of the - one in work area. - - """ - - label = "Submit to Deadline" - order = pyblish.api.IntegratorOrder + 0.1 - hosts = ["harmony"] - families = ["render.farm"] - targets = ["local"] - settings_category = "deadline" - - optional = True - use_published = False - priority = 50 - chunk_size = 1000000 - group = "none" - department = "" - - def get_job_info(self): - job_info = DeadlineJobInfo("Harmony") - job_info.Name = self._instance.data["name"] - job_info.Plugin = "HarmonyAYON" - job_info.Frames = "{}-{}".format( - self._instance.data["frameStartHandle"], - self._instance.data["frameEndHandle"] - ) - # for now, get those from presets. Later on it should be - # configurable in Harmony UI directly. - job_info.Priority = self.priority - job_info.Pool = self._instance.data.get("primaryPool") - job_info.SecondaryPool = self._instance.data.get("secondaryPool") - job_info.ChunkSize = self.chunk_size - batch_name = os.path.basename(self._instance.data["source"]) - if is_in_tests(): - batch_name += datetime.now().strftime("%d%m%Y%H%M%S") - job_info.BatchName = batch_name - job_info.Department = self.department - job_info.Group = self.group - - keys = [ - "FTRACK_API_KEY", - "FTRACK_API_USER", - "FTRACK_SERVER", - "AYON_BUNDLE_NAME", - "AYON_DEFAULT_SETTINGS_VARIANT", - "AYON_PROJECT_NAME", - "AYON_FOLDER_PATH", - "AYON_TASK_NAME", - "AYON_WORKDIR", - "AYON_APP_NAME", - "AYON_LOG_NO_COLORS" - "AYON_IN_TESTS" - ] - - environment = { - key: os.environ[key] - for key in keys - if key in os.environ - } - for key in keys: - value = environment.get(key) - if value: - job_info.EnvironmentKeyValue[key] = value - - # to recognize render jobs - job_info.add_render_job_env_var() - - return job_info - - def _unzip_scene_file(self, published_scene: Path) -> Path: - """Unzip scene zip file to its directory. - - Unzip scene file (if it is zip file) to its current directory and - return path to xstage file there. Xstage file is determined by its - name. - - Args: - published_scene (Path): path to zip file. - - Returns: - Path: The path to unzipped xstage. - """ - # if not zip, bail out. - if "zip" not in published_scene.suffix or not is_zipfile( - published_scene.as_posix() - ): - self.log.error("Published scene is not in zip.") - self.log.error(published_scene) - raise AssertionError("invalid scene format") - - xstage_path = ( - published_scene.parent - / published_scene.stem - / f"{published_scene.stem}.xstage" - ) - unzip_dir = (published_scene.parent / published_scene.stem) - with _ZipFile(published_scene, "r") as zip_ref: - # UNC path (//?/) added to minimalize risk with extracting - # to large file paths - zip_ref.extractall("//?/" + str(unzip_dir.as_posix())) - - # find any xstage files in directory, prefer the one with the same name - # as directory (plus extension) - xstage_files = [] - for scene in unzip_dir.iterdir(): - if scene.suffix == ".xstage": - xstage_files.append(scene) - - # there must be at least one (but maybe not more?) xstage file - if not xstage_files: - self.log.error("No xstage files found in zip") - raise AssertionError("Invalid scene archive") - - ideal_scene = False - # find the one with the same name as zip. In case there can be more - # then one xtage file. - for scene in xstage_files: - # if /foo/bar/baz.zip == /foo/bar/baz/baz.xstage - # ^^^ ^^^ - if scene.stem == published_scene.stem: - xstage_path = scene - ideal_scene = True - - # but sometimes xstage file has different name then zip - in that case - # use that one. - if not ideal_scene: - xstage_path = xstage_files[0] - return xstage_path - - def get_plugin_info(self): - # this is path to published scene workfile _ZIP_. Before - # rendering, we need to unzip it. - published_scene = Path( - self.from_published_scene(False)) - self.log.debug(f"Processing {published_scene.as_posix()}") - xstage_path = self._unzip_scene_file(published_scene) - render_path = xstage_path.parent / "renders" - - # for submit_publish job to create .json file in - self._instance.data["outputDir"] = render_path - new_expected_files = [] - render_path_str = str(render_path.as_posix()) - for file in self._instance.data["expectedFiles"]: - _file = str(Path(file).as_posix()) - expected_dir_str = os.path.dirname(_file) - new_expected_files.append( - _file.replace(expected_dir_str, render_path_str) - ) - audio_file = self._instance.data.get("audioFile") - if audio_file: - abs_path = xstage_path.parent / audio_file - self._instance.context.data["audioFile"] = str(abs_path) - - self._instance.data["source"] = str(published_scene.as_posix()) - self._instance.data["expectedFiles"] = new_expected_files - harmony_plugin_info = PluginInfo( - SceneFile=xstage_path.as_posix(), - Version=( - self._instance.context.data["harmonyVersion"].split(".")[0]), - FieldOfView=self._instance.context.data["FOV"], - ResolutionX=self._instance.data["resolutionWidth"], - ResolutionY=self._instance.data["resolutionHeight"] - ) - - pattern = '[0]{' + str(self._instance.data["leadingZeros"]) + \ - '}1\.[a-zA-Z]{3}' - render_prefix = re.sub(pattern, '', - self._instance.data["expectedFiles"][0]) - harmony_plugin_info.set_output( - self._instance.data["setMembers"][0], - self._instance.data["outputFormat"], - render_prefix, - self._instance.data["outputType"], - self._instance.data["leadingZeros"], - self._instance.data["outputStartFrame"] - ) - - all_write_nodes = self._instance.context.data["all_write_nodes"] - disable_nodes = [] - for node in all_write_nodes: - # disable all other write nodes - if node != self._instance.data["setMembers"][0]: - disable_nodes.append("node.setEnable('{}', false)" - .format(node)) - harmony_plugin_info.PreRenderInlineScript = ';'.join(disable_nodes) - - return harmony_plugin_info.serialize() diff --git a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_houdini_cache_deadline.py b/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_houdini_cache_deadline.py deleted file mode 100644 index ac9ad570c3..0000000000 --- a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_houdini_cache_deadline.py +++ /dev/null @@ -1,181 +0,0 @@ -import os -import getpass -from datetime import datetime - -import attr -import pyblish.api -from ayon_core.lib import ( - TextDef, - NumberDef, - is_in_tests, -) -from ayon_core.pipeline import ( - AYONPyblishPluginMixin -) -from ayon_deadline import abstract_submit_deadline -from ayon_deadline.abstract_submit_deadline import DeadlineJobInfo - - -@attr.s -class HoudiniPluginInfo(object): - Build = attr.ib(default=None) - IgnoreInputs = attr.ib(default=True) - ScriptJob = attr.ib(default=True) - SceneFile = attr.ib(default=None) # Input - SaveFile = attr.ib(default=True) - ScriptFilename = attr.ib(default=None) - OutputDriver = attr.ib(default=None) - Version = attr.ib(default=None) # Mandatory for Deadline - ProjectPath = attr.ib(default=None) - - -class HoudiniCacheSubmitDeadline(abstract_submit_deadline.AbstractSubmitDeadline, # noqa - AYONPyblishPluginMixin): - """Submit Houdini scene to perform a local publish in Deadline. - - Publishing in Deadline can be helpful for scenes that publish very slow. - This way it can process in the background on another machine without the - Artist having to wait for the publish to finish on their local machine. - """ - - label = "Submit Scene to Deadline" - order = pyblish.api.IntegratorOrder - hosts = ["houdini"] - families = ["publish.hou"] - targets = ["local"] - settings_category = "deadline" - - priority = 50 - chunk_size = 999999 - group = None - jobInfo = {} - pluginInfo = {} - - - def get_job_info(self): - job_info = DeadlineJobInfo(Plugin="Houdini") - - job_info.update(self.jobInfo) - instance = self._instance - context = instance.context - assert all( - result["success"] for result in context.data["results"] - ), "Errors found, aborting integration.." - - project_name = instance.context.data["projectName"] - filepath = context.data["currentFile"] - scenename = os.path.basename(filepath) - job_name = "{scene} - {instance} [PUBLISH]".format( - scene=scenename, instance=instance.name) - batch_name = "{code} - {scene}".format(code=project_name, - scene=scenename) - if is_in_tests(): - batch_name += datetime.now().strftime("%d%m%Y%H%M%S") - - job_info.Name = job_name - job_info.BatchName = batch_name - job_info.Plugin = instance.data["plugin"] - job_info.UserName = context.data.get("deadlineUser", getpass.getuser()) - rop_node = self.get_rop_node(instance) - if rop_node.type().name() != "alembic": - frames = "{start}-{end}x{step}".format( - start=int(instance.data["frameStart"]), - end=int(instance.data["frameEnd"]), - step=int(instance.data["byFrameStep"]), - ) - - job_info.Frames = frames - - job_info.Pool = instance.data.get("primaryPool") - job_info.SecondaryPool = instance.data.get("secondaryPool") - - attr_values = self.get_attr_values_from_data(instance.data) - - job_info.ChunkSize = instance.data.get("chunk_size", self.chunk_size) - job_info.Comment = context.data.get("comment") - job_info.Priority = attr_values.get("priority", self.priority) - job_info.Group = attr_values.get("group", self.group) - - keys = [ - "FTRACK_API_KEY", - "FTRACK_API_USER", - "FTRACK_SERVER", - "OPENPYPE_SG_USER", - "AYON_PROJECT_NAME", - "AYON_FOLDER_PATH", - "AYON_TASK_NAME", - "AYON_WORKDIR", - "AYON_APP_NAME", - "AYON_LOG_NO_COLORS", - ] - - environment = { - key: os.environ[key] - for key in keys - if key in os.environ - } - - for key in keys: - value = environment.get(key) - if not value: - continue - job_info.EnvironmentKeyValue[key] = value - # to recognize render jobs - job_info.add_render_job_env_var() - - return job_info - - def get_plugin_info(self): - # Not all hosts can import this module. - import hou - - instance = self._instance - version = hou.applicationVersionString() - version = ".".join(version.split(".")[:2]) - rop = self.get_rop_node(instance) - plugin_info = HoudiniPluginInfo( - Build=None, - IgnoreInputs=True, - ScriptJob=True, - SceneFile=self.scene_path, - SaveFile=True, - OutputDriver=rop.path(), - Version=version, - ProjectPath=os.path.dirname(self.scene_path) - ) - - plugin_payload = attr.asdict(plugin_info) - - return plugin_payload - - def process(self, instance): - super(HoudiniCacheSubmitDeadline, self).process(instance) - output_dir = os.path.dirname(instance.data["files"][0]) - instance.data["outputDir"] = output_dir - instance.data["toBeRenderedOn"] = "deadline" - - def get_rop_node(self, instance): - # Not all hosts can import this module. - import hou - - rop = instance.data.get("instance_node") - rop_node = hou.node(rop) - - return rop_node - - @classmethod - def get_attribute_defs(cls): - defs = super(HoudiniCacheSubmitDeadline, cls).get_attribute_defs() - defs.extend([ - NumberDef("priority", - minimum=1, - maximum=250, - decimals=0, - default=cls.priority, - label="Priority"), - TextDef("group", - default=cls.group, - label="Group Name"), - ]) - - return defs diff --git a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_houdini_render_deadline.py b/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_houdini_render_deadline.py deleted file mode 100644 index 7956108e77..0000000000 --- a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_houdini_render_deadline.py +++ /dev/null @@ -1,403 +0,0 @@ -import os -import attr -import getpass -from datetime import datetime - -import pyblish.api - -from ayon_core.pipeline import AYONPyblishPluginMixin -from ayon_core.lib import ( - is_in_tests, - TextDef, - NumberDef -) -from ayon_deadline import abstract_submit_deadline -from ayon_deadline.abstract_submit_deadline import DeadlineJobInfo - - -@attr.s -class DeadlinePluginInfo(): - SceneFile = attr.ib(default=None) - OutputDriver = attr.ib(default=None) - Version = attr.ib(default=None) - IgnoreInputs = attr.ib(default=True) - - -@attr.s -class ArnoldRenderDeadlinePluginInfo(): - InputFile = attr.ib(default=None) - Verbose = attr.ib(default=4) - - -@attr.s -class MantraRenderDeadlinePluginInfo(): - SceneFile = attr.ib(default=None) - Version = attr.ib(default=None) - - -@attr.s -class VrayRenderPluginInfo(): - InputFilename = attr.ib(default=None) - SeparateFilesPerFrame = attr.ib(default=True) - - -@attr.s -class RedshiftRenderPluginInfo(): - SceneFile = attr.ib(default=None) - # Use "1" as the default Redshift version just because it - # default fallback version in Deadline's Redshift plugin - # if no version was specified - Version = attr.ib(default="1") - - -@attr.s -class HuskStandalonePluginInfo(): - """Requires Deadline Husk Standalone Plugin. - See Deadline Plug-in: - https://github.com/BigRoy/HuskStandaloneSubmitter - Also see Husk options here: - https://www.sidefx.com/docs/houdini/ref/utils/husk.html - """ - SceneFile = attr.ib() - # TODO: Below parameters are only supported by custom version of the plugin - Renderer = attr.ib(default=None) - RenderSettings = attr.ib(default="/Render/rendersettings") - Purpose = attr.ib(default="geometry,render") - Complexity = attr.ib(default="veryhigh") - Snapshot = attr.ib(default=-1) - LogLevel = attr.ib(default="2") - PreRender = attr.ib(default="") - PreFrame = attr.ib(default="") - PostFrame = attr.ib(default="") - PostRender = attr.ib(default="") - RestartDelegate = attr.ib(default="") - Version = attr.ib(default="") - - -class HoudiniSubmitDeadline( - abstract_submit_deadline.AbstractSubmitDeadline, - AYONPyblishPluginMixin -): - """Submit Render ROPs to Deadline. - - Renders are submitted to a Deadline Web Service as - supplied via the environment variable AVALON_DEADLINE. - - Target "local": - Even though this does *not* render locally this is seen as - a 'local' submission as it is the regular way of submitting - a Houdini render locally. - - """ - - label = "Submit Render to Deadline" - order = pyblish.api.IntegratorOrder - hosts = ["houdini"] - families = ["redshift_rop", - "arnold_rop", - "mantra_rop", - "karma_rop", - "vray_rop"] - targets = ["local"] - settings_category = "deadline" - use_published = True - - # presets - export_priority = 50 - export_chunk_size = 10 - export_group = "" - priority = 50 - chunk_size = 1 - group = "" - - @classmethod - def get_attribute_defs(cls): - return [ - NumberDef( - "priority", - label="Priority", - default=cls.priority, - decimals=0 - ), - NumberDef( - "chunk", - label="Frames Per Task", - default=cls.chunk_size, - decimals=0, - minimum=1, - maximum=1000 - ), - TextDef( - "group", - default=cls.group, - label="Group Name" - ), - NumberDef( - "export_priority", - label="Export Priority", - default=cls.export_priority, - decimals=0 - ), - NumberDef( - "export_chunk", - label="Export Frames Per Task", - default=cls.export_chunk_size, - decimals=0, - minimum=1, - maximum=1000 - ), - TextDef( - "export_group", - default=cls.export_group, - label="Export Group Name" - ), - ] - - def get_job_info(self, dependency_job_ids=None): - - instance = self._instance - context = instance.context - - attribute_values = self.get_attr_values_from_data(instance.data) - - # Whether Deadline render submission is being split in two - # (extract + render) - split_render_job = instance.data.get("splitRender") - - # If there's some dependency job ids we can assume this is a render job - # and not an export job - is_export_job = True - if dependency_job_ids: - is_export_job = False - - job_type = "[RENDER]" - if split_render_job and not is_export_job: - product_type = instance.data["productType"] - plugin = { - "usdrender": "HuskStandalone", - }.get(product_type) - if not plugin: - # Convert from product type to Deadline plugin name - # i.e., arnold_rop -> Arnold - plugin = product_type.replace("_rop", "").capitalize() - else: - plugin = "Houdini" - if split_render_job: - job_type = "[EXPORT IFD]" - - job_info = DeadlineJobInfo(Plugin=plugin) - - filepath = context.data["currentFile"] - filename = os.path.basename(filepath) - job_info.Name = "{} - {} {}".format(filename, instance.name, job_type) - job_info.BatchName = filename - - job_info.UserName = context.data.get( - "deadlineUser", getpass.getuser()) - - if is_in_tests(): - job_info.BatchName += datetime.now().strftime("%d%m%Y%H%M%S") - - # Deadline requires integers in frame range - start = instance.data["frameStartHandle"] - end = instance.data["frameEndHandle"] - frames = "{start}-{end}x{step}".format( - start=int(start), - end=int(end), - step=int(instance.data["byFrameStep"]), - ) - job_info.Frames = frames - - # Make sure we make job frame dependent so render tasks pick up a soon - # as export tasks are done - if split_render_job and not is_export_job: - job_info.IsFrameDependent = bool(instance.data.get( - "splitRenderFrameDependent", True)) - - job_info.Pool = instance.data.get("primaryPool") - job_info.SecondaryPool = instance.data.get("secondaryPool") - - if split_render_job and is_export_job: - job_info.Priority = attribute_values.get( - "export_priority", self.export_priority - ) - job_info.ChunkSize = attribute_values.get( - "export_chunk", self.export_chunk_size - ) - job_info.Group = self.export_group - else: - job_info.Priority = attribute_values.get( - "priority", self.priority - ) - job_info.ChunkSize = attribute_values.get( - "chunk", self.chunk_size - ) - job_info.Group = self.group - - # Apply render globals, like e.g. data from collect machine list - render_globals = instance.data.get("renderGlobals", {}) - if render_globals: - self.log.debug("Applying 'renderGlobals' to job info: %s", - render_globals) - job_info.update(render_globals) - - job_info.Comment = context.data.get("comment") - - keys = [ - "FTRACK_API_KEY", - "FTRACK_API_USER", - "FTRACK_SERVER", - "OPENPYPE_SG_USER", - "AYON_PROJECT_NAME", - "AYON_FOLDER_PATH", - "AYON_TASK_NAME", - "AYON_WORKDIR", - "AYON_APP_NAME", - "AYON_LOG_NO_COLORS", - ] - - environment = { - key: os.environ[key] - for key in keys - if key in os.environ - } - - for key in keys: - value = environment.get(key) - if value: - job_info.EnvironmentKeyValue[key] = value - - # to recognize render jobs - job_info.add_render_job_env_var() - - for i, filepath in enumerate(instance.data["files"]): - dirname = os.path.dirname(filepath) - fname = os.path.basename(filepath) - job_info.OutputDirectory += dirname.replace("\\", "/") - job_info.OutputFilename += fname - - # Add dependencies if given - if dependency_job_ids: - job_info.JobDependencies = ",".join(dependency_job_ids) - - return job_info - - def get_plugin_info(self, job_type=None): - # Not all hosts can import this module. - import hou - - instance = self._instance - context = instance.context - - hou_major_minor = hou.applicationVersionString().rsplit(".", 1)[0] - - # Output driver to render - if job_type == "render": - product_type = instance.data.get("productType") - if product_type == "arnold_rop": - plugin_info = ArnoldRenderDeadlinePluginInfo( - InputFile=instance.data["ifdFile"] - ) - elif product_type == "mantra_rop": - plugin_info = MantraRenderDeadlinePluginInfo( - SceneFile=instance.data["ifdFile"], - Version=hou_major_minor, - ) - elif product_type == "vray_rop": - plugin_info = VrayRenderPluginInfo( - InputFilename=instance.data["ifdFile"], - ) - elif product_type == "redshift_rop": - plugin_info = RedshiftRenderPluginInfo( - SceneFile=instance.data["ifdFile"] - ) - # Note: To use different versions of Redshift on Deadline - # set the `REDSHIFT_VERSION` env variable in the Tools - # settings in the AYON Application plugin. You will also - # need to set that version in `Redshift.param` file - # of the Redshift Deadline plugin: - # [Redshift_Executable_*] - # where * is the version number. - if os.getenv("REDSHIFT_VERSION"): - plugin_info.Version = os.getenv("REDSHIFT_VERSION") - else: - self.log.warning(( - "REDSHIFT_VERSION env variable is not set" - " - using version configured in Deadline" - )) - - elif product_type == "usdrender": - plugin_info = self._get_husk_standalone_plugin_info( - instance, hou_major_minor) - - else: - self.log.error( - "Product type '%s' not supported yet to split render job", - product_type - ) - return - else: - driver = hou.node(instance.data["instance_node"]) - plugin_info = DeadlinePluginInfo( - SceneFile=context.data["currentFile"], - OutputDriver=driver.path(), - Version=hou_major_minor, - IgnoreInputs=True - ) - - return attr.asdict(plugin_info) - - def process(self, instance): - if not instance.data["farm"]: - self.log.debug("Render on farm is disabled. " - "Skipping deadline submission.") - return - - super(HoudiniSubmitDeadline, self).process(instance) - - # TODO: Avoid the need for this logic here, needed for submit publish - # Store output dir for unified publisher (filesequence) - output_dir = os.path.dirname(instance.data["files"][0]) - instance.data["outputDir"] = output_dir - - def _get_husk_standalone_plugin_info(self, instance, hou_major_minor): - # Not all hosts can import this module. - import hou - - # Supply additional parameters from the USD Render ROP - # to the Husk Standalone Render Plug-in - rop_node = hou.node(instance.data["instance_node"]) - snapshot_interval = -1 - if rop_node.evalParm("dosnapshot"): - snapshot_interval = rop_node.evalParm("snapshotinterval") - - restart_delegate = 0 - if rop_node.evalParm("husk_restartdelegate"): - restart_delegate = rop_node.evalParm("husk_restartdelegateframes") - - rendersettings = ( - rop_node.evalParm("rendersettings") - or "/Render/rendersettings" - ) - return HuskStandalonePluginInfo( - SceneFile=instance.data["ifdFile"], - Renderer=rop_node.evalParm("renderer"), - RenderSettings=rendersettings, - Purpose=rop_node.evalParm("husk_purpose"), - Complexity=rop_node.evalParm("husk_complexity"), - Snapshot=snapshot_interval, - PreRender=rop_node.evalParm("husk_prerender"), - PreFrame=rop_node.evalParm("husk_preframe"), - PostFrame=rop_node.evalParm("husk_postframe"), - PostRender=rop_node.evalParm("husk_postrender"), - RestartDelegate=restart_delegate, - Version=hou_major_minor - ) - - -class HoudiniSubmitDeadlineUsdRender(HoudiniSubmitDeadline): - # Do not use published workfile paths for USD Render ROP because the - # Export Job doesn't seem to occur using the published path either, so - # output paths then do not match the actual rendered paths - use_published = False - families = ["usdrender"] diff --git a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_max_deadline.py b/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_max_deadline.py deleted file mode 100644 index 6a369eb001..0000000000 --- a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_max_deadline.py +++ /dev/null @@ -1,431 +0,0 @@ -import os -import getpass -import copy -import attr - -from ayon_core.lib import ( - TextDef, - BoolDef, - NumberDef, -) -from ayon_core.pipeline import ( - AYONPyblishPluginMixin -) -from ayon_core.pipeline.publish.lib import ( - replace_with_published_scene_path -) -from ayon_core.pipeline.publish import KnownPublishError -from ayon_max.api.lib import ( - get_current_renderer, - get_multipass_setting -) -from ayon_max.api.lib_rendersettings import RenderSettings -from ayon_deadline import abstract_submit_deadline -from ayon_deadline.abstract_submit_deadline import DeadlineJobInfo - - -@attr.s -class MaxPluginInfo(object): - SceneFile = attr.ib(default=None) # Input - Version = attr.ib(default=None) # Mandatory for Deadline - SaveFile = attr.ib(default=True) - IgnoreInputs = attr.ib(default=True) - - -class MaxSubmitDeadline(abstract_submit_deadline.AbstractSubmitDeadline, - AYONPyblishPluginMixin): - - label = "Submit Render to Deadline" - hosts = ["max"] - families = ["maxrender"] - targets = ["local"] - settings_category = "deadline" - - use_published = True - priority = 50 - chunk_size = 1 - jobInfo = {} - pluginInfo = {} - group = None - - @classmethod - def apply_settings(cls, project_settings): - settings = project_settings["deadline"]["publish"]["MaxSubmitDeadline"] # noqa - - # Take some defaults from settings - cls.use_published = settings.get("use_published", - cls.use_published) - cls.priority = settings.get("priority", - cls.priority) - cls.chuck_size = settings.get("chunk_size", cls.chunk_size) - cls.group = settings.get("group", cls.group) - # TODO: multiple camera instance, separate job infos - def get_job_info(self): - job_info = DeadlineJobInfo(Plugin="3dsmax") - - # todo: test whether this works for existing production cases - # where custom jobInfo was stored in the project settings - job_info.update(self.jobInfo) - - instance = self._instance - context = instance.context - # Always use the original work file name for the Job name even when - # rendering is done from the published Work File. The original work - # file name is clearer because it can also have subversion strings, - # etc. which are stripped for the published file. - - src_filepath = context.data["currentFile"] - src_filename = os.path.basename(src_filepath) - job_info.Name = "%s - %s" % (src_filename, instance.name) - job_info.BatchName = src_filename - job_info.Plugin = instance.data["plugin"] - job_info.UserName = context.data.get("deadlineUser", getpass.getuser()) - job_info.EnableAutoTimeout = True - # Deadline requires integers in frame range - frames = "{start}-{end}".format( - start=int(instance.data["frameStart"]), - end=int(instance.data["frameEnd"]) - ) - job_info.Frames = frames - - job_info.Pool = instance.data.get("primaryPool") - job_info.SecondaryPool = instance.data.get("secondaryPool") - - attr_values = self.get_attr_values_from_data(instance.data) - - job_info.ChunkSize = attr_values.get("chunkSize", 1) - job_info.Comment = context.data.get("comment") - job_info.Priority = attr_values.get("priority", self.priority) - job_info.Group = attr_values.get("group", self.group) - - # Add options from RenderGlobals - render_globals = instance.data.get("renderGlobals", {}) - job_info.update(render_globals) - - keys = [ - "FTRACK_API_KEY", - "FTRACK_API_USER", - "FTRACK_SERVER", - "OPENPYPE_SG_USER", - "AYON_BUNDLE_NAME", - "AYON_DEFAULT_SETTINGS_VARIANT", - "AYON_PROJECT_NAME", - "AYON_FOLDER_PATH", - "AYON_TASK_NAME", - "AYON_WORKDIR", - "AYON_APP_NAME", - "AYON_IN_TESTS", - ] - - environment = { - key: os.environ[key] - for key in keys - if key in os.environ - } - - for key in keys: - value = environment.get(key) - if not value: - continue - job_info.EnvironmentKeyValue[key] = value - - # to recognize render jobs - job_info.add_render_job_env_var() - job_info.EnvironmentKeyValue["AYON_LOG_NO_COLORS"] = "1" - - # Add list of expected files to job - # --------------------------------- - if not instance.data.get("multiCamera"): - exp = instance.data.get("expectedFiles") - for filepath in self._iter_expected_files(exp): - job_info.OutputDirectory += os.path.dirname(filepath) - job_info.OutputFilename += os.path.basename(filepath) - - return job_info - - def get_plugin_info(self): - instance = self._instance - - plugin_info = MaxPluginInfo( - SceneFile=self.scene_path, - Version=instance.data["maxversion"], - SaveFile=True, - IgnoreInputs=True - ) - - plugin_payload = attr.asdict(plugin_info) - - # Patching with pluginInfo from settings - for key, value in self.pluginInfo.items(): - plugin_payload[key] = value - - return plugin_payload - - def process_submission(self): - - instance = self._instance - filepath = instance.context.data["currentFile"] - - files = instance.data["expectedFiles"] - if not files: - raise KnownPublishError("No Render Elements found!") - first_file = next(self._iter_expected_files(files)) - output_dir = os.path.dirname(first_file) - instance.data["outputDir"] = output_dir - - filename = os.path.basename(filepath) - - payload_data = { - "filename": filename, - "dirname": output_dir - } - - self.log.debug("Submitting 3dsMax render..") - project_settings = instance.context.data["project_settings"] - auth = self._instance.data["deadline"]["auth"] - verify = self._instance.data["deadline"]["verify"] - if instance.data.get("multiCamera"): - self.log.debug("Submitting jobs for multiple cameras..") - payload = self._use_published_name_for_multiples( - payload_data, project_settings) - job_infos, plugin_infos = payload - for job_info, plugin_info in zip(job_infos, plugin_infos): - self.submit( - self.assemble_payload(job_info, plugin_info), - auth=auth, - verify=verify - ) - else: - payload = self._use_published_name(payload_data, project_settings) - job_info, plugin_info = payload - self.submit( - self.assemble_payload(job_info, plugin_info), - auth=auth, - verify=verify - ) - - def _use_published_name(self, data, project_settings): - # Not all hosts can import these modules. - from ayon_max.api.lib import ( - get_current_renderer, - get_multipass_setting - ) - from ayon_max.api.lib_rendersettings import RenderSettings - - instance = self._instance - job_info = copy.deepcopy(self.job_info) - plugin_info = copy.deepcopy(self.plugin_info) - plugin_data = {} - - multipass = get_multipass_setting(project_settings) - if multipass: - plugin_data["DisableMultipass"] = 0 - else: - plugin_data["DisableMultipass"] = 1 - - files = instance.data.get("expectedFiles") - if not files: - raise KnownPublishError("No render elements found") - first_file = next(self._iter_expected_files(files)) - old_output_dir = os.path.dirname(first_file) - output_beauty = RenderSettings().get_render_output(instance.name, - old_output_dir) - rgb_bname = os.path.basename(output_beauty) - dir = os.path.dirname(first_file) - beauty_name = f"{dir}/{rgb_bname}" - beauty_name = beauty_name.replace("\\", "/") - plugin_data["RenderOutput"] = beauty_name - # as 3dsmax has version with different languages - plugin_data["Language"] = "ENU" - - renderer_class = get_current_renderer() - - renderer = str(renderer_class).split(":")[0] - if renderer in [ - "ART_Renderer", - "Redshift_Renderer", - "V_Ray_6_Hotfix_3", - "V_Ray_GPU_6_Hotfix_3", - "Default_Scanline_Renderer", - "Quicksilver_Hardware_Renderer", - ]: - render_elem_list = RenderSettings().get_render_element() - for i, element in enumerate(render_elem_list): - elem_bname = os.path.basename(element) - new_elem = f"{dir}/{elem_bname}" - new_elem = new_elem.replace("/", "\\") - plugin_data["RenderElementOutputFilename%d" % i] = new_elem # noqa - - if renderer == "Redshift_Renderer": - plugin_data["redshift_SeparateAovFiles"] = instance.data.get( - "separateAovFiles") - if instance.data["cameras"]: - camera = instance.data["cameras"][0] - plugin_info["Camera0"] = camera - plugin_info["Camera"] = camera - plugin_info["Camera1"] = camera - self.log.debug("plugin data:{}".format(plugin_data)) - plugin_info.update(plugin_data) - - return job_info, plugin_info - - def get_job_info_through_camera(self, camera): - """Get the job parameters for deadline submission when - multi-camera is enabled. - Args: - infos(dict): a dictionary with job info. - """ - instance = self._instance - context = instance.context - job_info = copy.deepcopy(self.job_info) - exp = instance.data.get("expectedFiles") - - src_filepath = context.data["currentFile"] - src_filename = os.path.basename(src_filepath) - job_info.Name = "%s - %s - %s" % ( - src_filename, instance.name, camera) - for filepath in self._iter_expected_files(exp): - if camera not in filepath: - continue - job_info.OutputDirectory += os.path.dirname(filepath) - job_info.OutputFilename += os.path.basename(filepath) - - return job_info - # set the output filepath with the relative camera - - def get_plugin_info_through_camera(self, camera): - """Get the plugin parameters for deadline submission when - multi-camera is enabled. - Args: - infos(dict): a dictionary with plugin info. - """ - instance = self._instance - # set the target camera - plugin_info = copy.deepcopy(self.plugin_info) - - plugin_data = {} - # set the output filepath with the relative camera - if instance.data.get("multiCamera"): - scene_filepath = instance.context.data["currentFile"] - scene_filename = os.path.basename(scene_filepath) - scene_directory = os.path.dirname(scene_filepath) - current_filename, ext = os.path.splitext(scene_filename) - camera_scene_name = f"{current_filename}_{camera}{ext}" - camera_scene_filepath = os.path.join( - scene_directory, f"_{current_filename}", camera_scene_name) - plugin_data["SceneFile"] = camera_scene_filepath - - files = instance.data.get("expectedFiles") - if not files: - raise KnownPublishError("No render elements found") - first_file = next(self._iter_expected_files(files)) - old_output_dir = os.path.dirname(first_file) - rgb_output = RenderSettings().get_batch_render_output(camera) # noqa - rgb_bname = os.path.basename(rgb_output) - dir = os.path.dirname(first_file) - beauty_name = f"{dir}/{rgb_bname}" - beauty_name = beauty_name.replace("\\", "/") - plugin_info["RenderOutput"] = beauty_name - renderer_class = get_current_renderer() - - renderer = str(renderer_class).split(":")[0] - if renderer in [ - "ART_Renderer", - "Redshift_Renderer", - "V_Ray_6_Hotfix_3", - "V_Ray_GPU_6_Hotfix_3", - "Default_Scanline_Renderer", - "Quicksilver_Hardware_Renderer", - ]: - render_elem_list = RenderSettings().get_batch_render_elements( - instance.name, old_output_dir, camera - ) - for i, element in enumerate(render_elem_list): - if camera in element: - elem_bname = os.path.basename(element) - new_elem = f"{dir}/{elem_bname}" - new_elem = new_elem.replace("/", "\\") - plugin_info["RenderElementOutputFilename%d" % i] = new_elem # noqa - - if camera: - # set the default camera and target camera - # (weird parameters from max) - plugin_data["Camera"] = camera - plugin_data["Camera1"] = camera - plugin_data["Camera0"] = None - - plugin_info.update(plugin_data) - return plugin_info - - def _use_published_name_for_multiples(self, data, project_settings): - """Process the parameters submission for deadline when - user enables multi-cameras option. - Args: - job_info_list (list): A list of multiple job infos - plugin_info_list (list): A list of multiple plugin infos - """ - job_info_list = [] - plugin_info_list = [] - instance = self._instance - cameras = instance.data.get("cameras", []) - plugin_data = {} - multipass = get_multipass_setting(project_settings) - if multipass: - plugin_data["DisableMultipass"] = 0 - else: - plugin_data["DisableMultipass"] = 1 - for cam in cameras: - job_info = self.get_job_info_through_camera(cam) - plugin_info = self.get_plugin_info_through_camera(cam) - plugin_info.update(plugin_data) - job_info_list.append(job_info) - plugin_info_list.append(plugin_info) - - return job_info_list, plugin_info_list - - def from_published_scene(self, replace_in_path=True): - instance = self._instance - if instance.data["renderer"] == "Redshift_Renderer": - self.log.debug("Using Redshift...published scene wont be used..") - replace_in_path = False - return replace_with_published_scene_path( - instance, replace_in_path) - - @staticmethod - def _iter_expected_files(exp): - if isinstance(exp[0], dict): - for _aov, files in exp[0].items(): - for file in files: - yield file - else: - for file in exp: - yield file - - @classmethod - def get_attribute_defs(cls): - defs = super(MaxSubmitDeadline, cls).get_attribute_defs() - defs.extend([ - BoolDef("use_published", - default=cls.use_published, - label="Use Published Scene"), - - NumberDef("priority", - minimum=1, - maximum=250, - decimals=0, - default=cls.priority, - label="Priority"), - - NumberDef("chunkSize", - minimum=1, - maximum=50, - decimals=0, - default=cls.chunk_size, - label="Frame Per Task"), - - TextDef("group", - default=cls.group, - label="Group Name"), - ]) - - return defs diff --git a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_maya_deadline.py b/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_maya_deadline.py deleted file mode 100644 index d50b0147d9..0000000000 --- a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_maya_deadline.py +++ /dev/null @@ -1,935 +0,0 @@ -# -*- coding: utf-8 -*- -"""Submitting render job to Deadline. - -This module is taking care of submitting job from Maya to Deadline. It -creates job and set correct environments. Its behavior is controlled by -``DEADLINE_REST_URL`` environment variable - pointing to Deadline Web Service -and :data:`MayaSubmitDeadline.use_published` property telling Deadline to -use published scene workfile or not. - -If ``vrscene`` or ``assscene`` are detected in families, it will first -submit job to export these files and then dependent job to render them. - -Attributes: - payload_skeleton (dict): Skeleton payload data sent as job to Deadline. - Default values are for ``MayaBatch`` plugin. - -""" - -from __future__ import print_function -import os -import json -import getpass -import copy -import re -import hashlib -from datetime import datetime -import itertools -from collections import OrderedDict - -import attr - -from ayon_core.pipeline import ( - AYONPyblishPluginMixin -) -from ayon_core.lib import ( - BoolDef, - NumberDef, - TextDef, - EnumDef, - is_in_tests, -) -from ayon_maya.api.lib_rendersettings import RenderSettings -from ayon_maya.api.lib import get_attr_in_layer - -from ayon_core.pipeline.farm.tools import iter_expected_files - -from ayon_deadline import abstract_submit_deadline -from ayon_deadline.abstract_submit_deadline import DeadlineJobInfo - - -def _validate_deadline_bool_value(instance, attribute, value): - if not isinstance(value, (str, bool)): - raise TypeError( - "Attribute {} must be str or bool.".format(attribute)) - if value not in {"1", "0", True, False}: - raise ValueError( - ("Value of {} must be one of " - "'0', '1', True, False").format(attribute) - ) - - -@attr.s -class MayaPluginInfo(object): - SceneFile = attr.ib(default=None) # Input - OutputFilePath = attr.ib(default=None) # Output directory and filename - OutputFilePrefix = attr.ib(default=None) - Version = attr.ib(default=None) # Mandatory for Deadline - UsingRenderLayers = attr.ib(default=True) - RenderLayer = attr.ib(default=None) # Render only this layer - Renderer = attr.ib(default=None) - ProjectPath = attr.ib(default=None) # Resolve relative references - # Include all lights flag - RenderSetupIncludeLights = attr.ib( - default="1", validator=_validate_deadline_bool_value) - StrictErrorChecking = attr.ib(default=True) - - -@attr.s -class PythonPluginInfo(object): - ScriptFile = attr.ib() - Version = attr.ib(default="3.6") - Arguments = attr.ib(default=None) - SingleFrameOnly = attr.ib(default=None) - - -@attr.s -class VRayPluginInfo(object): - InputFilename = attr.ib(default=None) # Input - SeparateFilesPerFrame = attr.ib(default=None) - VRayEngine = attr.ib(default="V-Ray") - Width = attr.ib(default=None) - Height = attr.ib(default=None) # Mandatory for Deadline - OutputFilePath = attr.ib(default=True) - OutputFileName = attr.ib(default=None) # Render only this layer - - -@attr.s -class ArnoldPluginInfo(object): - ArnoldFile = attr.ib(default=None) - - -class MayaSubmitDeadline(abstract_submit_deadline.AbstractSubmitDeadline, - AYONPyblishPluginMixin): - - label = "Submit Render to Deadline" - hosts = ["maya"] - families = ["renderlayer"] - targets = ["local"] - settings_category = "deadline" - - tile_assembler_plugin = "OpenPypeTileAssembler" - priority = 50 - tile_priority = 50 - limit = [] # limit groups - jobInfo = {} - pluginInfo = {} - group = "none" - strict_error_checking = True - - @classmethod - def apply_settings(cls, project_settings): - settings = project_settings["deadline"]["publish"]["MayaSubmitDeadline"] # noqa - - # Take some defaults from settings - cls.asset_dependencies = settings.get("asset_dependencies", - cls.asset_dependencies) - cls.import_reference = settings.get("import_reference", - cls.import_reference) - cls.use_published = settings.get("use_published", cls.use_published) - cls.priority = settings.get("priority", cls.priority) - cls.tile_priority = settings.get("tile_priority", cls.tile_priority) - cls.limit = settings.get("limit", cls.limit) - cls.group = settings.get("group", cls.group) - cls.strict_error_checking = settings.get("strict_error_checking", - cls.strict_error_checking) - job_info = settings.get("jobInfo") - if job_info: - job_info = json.loads(job_info) - plugin_info = settings.get("pluginInfo") - if plugin_info: - plugin_info = json.loads(plugin_info) - - cls.jobInfo = job_info or cls.jobInfo - cls.pluginInfo = plugin_info or cls.pluginInfo - - def get_job_info(self): - job_info = DeadlineJobInfo(Plugin="MayaBatch") - - # todo: test whether this works for existing production cases - # where custom jobInfo was stored in the project settings - job_info.update(self.jobInfo) - - instance = self._instance - context = instance.context - - # Always use the original work file name for the Job name even when - # rendering is done from the published Work File. The original work - # file name is clearer because it can also have subversion strings, - # etc. which are stripped for the published file. - src_filepath = context.data["currentFile"] - src_filename = os.path.basename(src_filepath) - - if is_in_tests(): - src_filename += datetime.now().strftime("%d%m%Y%H%M%S") - - job_info.Name = "%s - %s" % (src_filename, instance.name) - job_info.BatchName = src_filename - job_info.Plugin = instance.data.get("mayaRenderPlugin", "MayaBatch") - job_info.UserName = context.data.get("deadlineUser", getpass.getuser()) - - # Deadline requires integers in frame range - frames = "{start}-{end}x{step}".format( - start=int(instance.data["frameStartHandle"]), - end=int(instance.data["frameEndHandle"]), - step=int(instance.data["byFrameStep"]), - ) - job_info.Frames = frames - - job_info.Pool = instance.data.get("primaryPool") - job_info.SecondaryPool = instance.data.get("secondaryPool") - job_info.Comment = context.data.get("comment") - job_info.Priority = instance.data.get("priority", self.priority) - - if self.group != "none" and self.group: - job_info.Group = self.group - - if self.limit: - job_info.LimitGroups = ",".join(self.limit) - - attr_values = self.get_attr_values_from_data(instance.data) - render_globals = instance.data.setdefault("renderGlobals", dict()) - machine_list = attr_values.get("machineList", "") - if machine_list: - if attr_values.get("whitelist", True): - machine_list_key = "Whitelist" - else: - machine_list_key = "Blacklist" - render_globals[machine_list_key] = machine_list - - job_info.Priority = attr_values.get("priority") - job_info.ChunkSize = attr_values.get("chunkSize") - - # Add options from RenderGlobals - render_globals = instance.data.get("renderGlobals", {}) - job_info.update(render_globals) - - keys = [ - "FTRACK_API_KEY", - "FTRACK_API_USER", - "FTRACK_SERVER", - "OPENPYPE_SG_USER", - "AYON_BUNDLE_NAME", - "AYON_DEFAULT_SETTINGS_VARIANT", - "AYON_PROJECT_NAME", - "AYON_FOLDER_PATH", - "AYON_TASK_NAME", - "AYON_WORKDIR", - "AYON_APP_NAME", - "AYON_IN_TESTS" - ] - - environment = { - key: os.environ[key] - for key in keys - if key in os.environ - } - - for key in keys: - value = environment.get(key) - if not value: - continue - job_info.EnvironmentKeyValue[key] = value - - # to recognize render jobs - job_info.add_render_job_env_var() - job_info.EnvironmentKeyValue["AYON_LOG_NO_COLORS"] = "1" - - # Adding file dependencies. - if not is_in_tests() and self.asset_dependencies: - dependencies = instance.context.data["fileDependencies"] - for dependency in dependencies: - job_info.AssetDependency += dependency - - # Add list of expected files to job - # --------------------------------- - exp = instance.data.get("expectedFiles") - for filepath in iter_expected_files(exp): - job_info.OutputDirectory += os.path.dirname(filepath) - job_info.OutputFilename += os.path.basename(filepath) - - return job_info - - def get_plugin_info(self): - # Not all hosts can import this module. - from maya import cmds - - instance = self._instance - context = instance.context - - # Set it to default Maya behaviour if it cannot be determined - # from instance (but it should be, by the Collector). - - default_rs_include_lights = ( - instance.context.data['project_settings'] - ['maya'] - ['render_settings'] - ['enable_all_lights'] - ) - - rs_include_lights = instance.data.get( - "renderSetupIncludeLights", default_rs_include_lights) - if rs_include_lights not in {"1", "0", True, False}: - rs_include_lights = default_rs_include_lights - - attr_values = self.get_attr_values_from_data(instance.data) - strict_error_checking = attr_values.get("strict_error_checking", - self.strict_error_checking) - plugin_info = MayaPluginInfo( - SceneFile=self.scene_path, - Version=cmds.about(version=True), - RenderLayer=instance.data['setMembers'], - Renderer=instance.data["renderer"], - RenderSetupIncludeLights=rs_include_lights, # noqa - ProjectPath=context.data["workspaceDir"], - UsingRenderLayers=True, - StrictErrorChecking=strict_error_checking - ) - - plugin_payload = attr.asdict(plugin_info) - - # Patching with pluginInfo from settings - for key, value in self.pluginInfo.items(): - plugin_payload[key] = value - - return plugin_payload - - def process_submission(self): - from maya import cmds - instance = self._instance - - filepath = self.scene_path # publish if `use_publish` else workfile - - # TODO: Avoid the need for this logic here, needed for submit publish - # Store output dir for unified publisher (filesequence) - expected_files = instance.data["expectedFiles"] - first_file = next(iter_expected_files(expected_files)) - output_dir = os.path.dirname(first_file) - instance.data["outputDir"] = output_dir - - # Patch workfile (only when use_published is enabled) - if self.use_published: - self._patch_workfile() - - # Gather needed data ------------------------------------------------ - filename = os.path.basename(filepath) - dirname = os.path.join( - cmds.workspace(query=True, rootDirectory=True), - cmds.workspace(fileRuleEntry="images") - ) - - # Fill in common data to payload ------------------------------------ - # TODO: Replace these with collected data from CollectRender - payload_data = { - "filename": filename, - "dirname": dirname, - } - - # Submit preceding export jobs ------------------------------------- - export_job = None - assert not all(x in instance.data["families"] - for x in ['vrayscene', 'assscene']), ( - "Vray Scene and Ass Scene options are mutually exclusive") - - auth = self._instance.data["deadline"]["auth"] - verify = self._instance.data["deadline"]["verify"] - if "vrayscene" in instance.data["families"]: - self.log.debug("Submitting V-Ray scene render..") - vray_export_payload = self._get_vray_export_payload(payload_data) - export_job = self.submit(vray_export_payload, - auth=auth, - verify=verify) - - payload = self._get_vray_render_payload(payload_data) - - else: - self.log.debug("Submitting MayaBatch render..") - payload = self._get_maya_payload(payload_data) - - # Add export job as dependency -------------------------------------- - if export_job: - job_info, _ = payload - job_info.JobDependencies = export_job - - if instance.data.get("tileRendering"): - # Prepare tiles data - self._tile_render(payload) - else: - # Submit main render job - job_info, plugin_info = payload - self.submit(self.assemble_payload(job_info, plugin_info), - auth=auth, - verify=verify) - - def _tile_render(self, payload): - """Submit as tile render per frame with dependent assembly jobs.""" - - # As collected by super process() - instance = self._instance - - payload_job_info, payload_plugin_info = payload - job_info = copy.deepcopy(payload_job_info) - plugin_info = copy.deepcopy(payload_plugin_info) - - # Force plugin reload for vray cause the region does not get flushed - # between tile renders. - if plugin_info["Renderer"] == "vray": - job_info.ForceReloadPlugin = True - - # if we have sequence of files, we need to create tile job for - # every frame - job_info.TileJob = True - job_info.TileJobTilesInX = instance.data.get("tilesX") - job_info.TileJobTilesInY = instance.data.get("tilesY") - - tiles_count = job_info.TileJobTilesInX * job_info.TileJobTilesInY - - plugin_info["ImageHeight"] = instance.data.get("resolutionHeight") - plugin_info["ImageWidth"] = instance.data.get("resolutionWidth") - plugin_info["RegionRendering"] = True - - R_FRAME_NUMBER = re.compile( - r".+\.(?P[0-9]+)\..+") # noqa: N806, E501 - REPL_FRAME_NUMBER = re.compile( - r"(.+\.)([0-9]+)(\..+)") # noqa: N806, E501 - - exp = instance.data["expectedFiles"] - if isinstance(exp[0], dict): - # we have aovs and we need to iterate over them - # get files from `beauty` - files = exp[0].get("beauty") - # assembly files are used for assembly jobs as we need to put - # together all AOVs - assembly_files = list( - itertools.chain.from_iterable( - [f for _, f in exp[0].items()])) - if not files: - # if beauty doesn't exist, use first aov we found - files = exp[0].get(list(exp[0].keys())[0]) - else: - files = exp - assembly_files = files - - auth = instance.data["deadline"]["auth"] - verify = instance.data["deadline"]["verify"] - - # Define frame tile jobs - frame_file_hash = {} - frame_payloads = {} - file_index = 1 - for file in files: - frame = re.search(R_FRAME_NUMBER, file).group("frame") - - new_job_info = copy.deepcopy(job_info) - new_job_info.Name += " (Frame {} - {} tiles)".format(frame, - tiles_count) - new_job_info.TileJobFrame = frame - - new_plugin_info = copy.deepcopy(plugin_info) - - # Add tile data into job info and plugin info - tiles_data = _format_tiles( - file, 0, - instance.data.get("tilesX"), - instance.data.get("tilesY"), - instance.data.get("resolutionWidth"), - instance.data.get("resolutionHeight"), - payload_plugin_info["OutputFilePrefix"] - )[0] - - new_job_info.update(tiles_data["JobInfo"]) - new_plugin_info.update(tiles_data["PluginInfo"]) - - self.log.debug("hashing {} - {}".format(file_index, file)) - job_hash = hashlib.sha256( - ("{}_{}".format(file_index, file)).encode("utf-8")) - - file_hash = job_hash.hexdigest() - frame_file_hash[frame] = file_hash - - new_job_info.ExtraInfo[0] = file_hash - new_job_info.ExtraInfo[1] = file - - frame_payloads[frame] = self.assemble_payload( - job_info=new_job_info, - plugin_info=new_plugin_info - ) - file_index += 1 - - self.log.debug( - "Submitting tile job(s) [{}] ...".format(len(frame_payloads))) - - # Submit frame tile jobs - frame_tile_job_id = {} - for frame, tile_job_payload in frame_payloads.items(): - job_id = self.submit( - tile_job_payload, auth, verify) - frame_tile_job_id[frame] = job_id - - # Define assembly payloads - assembly_job_info = copy.deepcopy(job_info) - assembly_job_info.Plugin = self.tile_assembler_plugin - assembly_job_info.Name += " - Tile Assembly Job" - assembly_job_info.Frames = 1 - assembly_job_info.MachineLimit = 1 - - attr_values = self.get_attr_values_from_data(instance.data) - assembly_job_info.Priority = attr_values.get("tile_priority", - self.tile_priority) - assembly_job_info.TileJob = False - - # TODO: This should be a new publisher attribute definition - pool = instance.context.data["project_settings"]["deadline"] - pool = pool["publish"]["ProcessSubmittedJobOnFarm"]["deadline_pool"] - assembly_job_info.Pool = pool or instance.data.get("primaryPool", "") - - assembly_plugin_info = { - "CleanupTiles": 1, - "ErrorOnMissing": True, - "Renderer": self._instance.data["renderer"] - } - - assembly_payloads = [] - output_dir = self.job_info.OutputDirectory[0] - config_files = [] - for file in assembly_files: - frame = re.search(R_FRAME_NUMBER, file).group("frame") - - frame_assembly_job_info = copy.deepcopy(assembly_job_info) - frame_assembly_job_info.Name += " (Frame {})".format(frame) - frame_assembly_job_info.OutputFilename[0] = re.sub( - REPL_FRAME_NUMBER, - "\\1{}\\3".format("#" * len(frame)), file) - - file_hash = frame_file_hash[frame] - tile_job_id = frame_tile_job_id[frame] - - frame_assembly_job_info.ExtraInfo[0] = file_hash - frame_assembly_job_info.ExtraInfo[1] = file - frame_assembly_job_info.JobDependencies = tile_job_id - frame_assembly_job_info.Frames = frame - - # write assembly job config files - config_file = os.path.join( - output_dir, - "{}_config_{}.txt".format( - os.path.splitext(file)[0], - datetime.now().strftime("%Y_%m_%d_%H_%M_%S") - ) - ) - config_files.append(config_file) - try: - if not os.path.isdir(output_dir): - os.makedirs(output_dir) - except OSError: - # directory is not available - self.log.warning("Path is unreachable: " - "`{}`".format(output_dir)) - - with open(config_file, "w") as cf: - print("TileCount={}".format(tiles_count), file=cf) - print("ImageFileName={}".format(file), file=cf) - print("ImageWidth={}".format( - instance.data.get("resolutionWidth")), file=cf) - print("ImageHeight={}".format( - instance.data.get("resolutionHeight")), file=cf) - - reversed_y = False - if plugin_info["Renderer"] == "arnold": - reversed_y = True - - with open(config_file, "a") as cf: - # Need to reverse the order of the y tiles, because image - # coordinates are calculated from bottom left corner. - tiles = _format_tiles( - file, 0, - instance.data.get("tilesX"), - instance.data.get("tilesY"), - instance.data.get("resolutionWidth"), - instance.data.get("resolutionHeight"), - payload_plugin_info["OutputFilePrefix"], - reversed_y=reversed_y - )[1] - for k, v in sorted(tiles.items()): - print("{}={}".format(k, v), file=cf) - - assembly_payloads.append( - self.assemble_payload( - job_info=frame_assembly_job_info, - plugin_info=assembly_plugin_info.copy(), - # This would fail if the client machine and webserice are - # using different storage paths. - aux_files=[config_file] - ) - ) - - # Submit assembly jobs - assembly_job_ids = [] - num_assemblies = len(assembly_payloads) - for i, payload in enumerate(assembly_payloads): - self.log.debug( - "submitting assembly job {} of {}".format(i + 1, - num_assemblies) - ) - assembly_job_id = self.submit( - payload, - auth=auth, - verify=verify - ) - assembly_job_ids.append(assembly_job_id) - - instance.data["assemblySubmissionJobs"] = assembly_job_ids - - # Remove config files to avoid confusion about where data is coming - # from in Deadline. - for config_file in config_files: - os.remove(config_file) - - def _get_maya_payload(self, data): - - job_info = copy.deepcopy(self.job_info) - - if not is_in_tests() and self.asset_dependencies: - # Asset dependency to wait for at least the scene file to sync. - job_info.AssetDependency += self.scene_path - - # Get layer prefix - renderlayer = self._instance.data["setMembers"] - renderer = self._instance.data["renderer"] - layer_prefix_attr = RenderSettings.get_image_prefix_attr(renderer) - layer_prefix = get_attr_in_layer(layer_prefix_attr, layer=renderlayer) - - plugin_info = copy.deepcopy(self.plugin_info) - plugin_info.update({ - # Output directory and filename - "OutputFilePath": data["dirname"].replace("\\", "/"), - "OutputFilePrefix": layer_prefix, - }) - - # This hack is here because of how Deadline handles Renderman version. - # it considers everything with `renderman` set as version older than - # Renderman 22, and so if we are using renderman > 21 we need to set - # renderer string on the job to `renderman22`. We will have to change - # this when Deadline releases new version handling this. - renderer = self._instance.data["renderer"] - if renderer == "renderman": - try: - from rfm2.config import cfg # noqa - except ImportError: - raise Exception("Cannot determine renderman version") - - rman_version = cfg().build_info.version() # type: str - if int(rman_version.split(".")[0]) > 22: - renderer = "renderman22" - - plugin_info["Renderer"] = renderer - - # this is needed because renderman plugin in Deadline - # handles directory and file prefixes separately - plugin_info["OutputFilePath"] = job_info.OutputDirectory[0] - - return job_info, plugin_info - - def _get_vray_export_payload(self, data): - - job_info = copy.deepcopy(self.job_info) - job_info.Name = self._job_info_label("Export") - - # Get V-Ray settings info to compute output path - vray_scene = self.format_vray_output_filename() - - plugin_info = { - "Renderer": "vray", - "SkipExistingFrames": True, - "UseLegacyRenderLayers": True, - "OutputFilePath": os.path.dirname(vray_scene) - } - - return job_info, attr.asdict(plugin_info) - - def _get_vray_render_payload(self, data): - - # Job Info - job_info = copy.deepcopy(self.job_info) - job_info.Name = self._job_info_label("Render") - job_info.Plugin = "Vray" - job_info.OverrideTaskExtraInfoNames = False - - # Plugin Info - plugin_info = VRayPluginInfo( - InputFilename=self.format_vray_output_filename(), - SeparateFilesPerFrame=False, - VRayEngine="V-Ray", - Width=self._instance.data["resolutionWidth"], - Height=self._instance.data["resolutionHeight"], - OutputFilePath=job_info.OutputDirectory[0], - OutputFileName=job_info.OutputFilename[0] - ) - - return job_info, attr.asdict(plugin_info) - - def _get_arnold_render_payload(self, data): - # Job Info - job_info = copy.deepcopy(self.job_info) - job_info.Name = self._job_info_label("Render") - job_info.Plugin = "Arnold" - job_info.OverrideTaskExtraInfoNames = False - - # Plugin Info - ass_file, _ = os.path.splitext(data["output_filename_0"]) - ass_filepath = ass_file + ".ass" - - plugin_info = ArnoldPluginInfo( - ArnoldFile=ass_filepath - ) - - return job_info, attr.asdict(plugin_info) - - def format_vray_output_filename(self): - """Format the expected output file of the Export job. - - Example: - /_/ - "shot010_v006/shot010_v006_CHARS/CHARS_0001.vrscene" - Returns: - str - - """ - from maya import cmds - # "vrayscene//_/" - vray_settings = cmds.ls(type="VRaySettingsNode") - node = vray_settings[0] - template = cmds.getAttr("{}.vrscene_filename".format(node)) - scene, _ = os.path.splitext(self.scene_path) - - def smart_replace(string, key_values): - new_string = string - for key, value in key_values.items(): - new_string = new_string.replace(key, value) - return new_string - - # Get workfile scene path without extension to format vrscene_filename - scene_filename = os.path.basename(self.scene_path) - scene_filename_no_ext, _ = os.path.splitext(scene_filename) - - layer = self._instance.data['setMembers'] - - # Reformat without tokens - output_path = smart_replace( - template, - {"": scene_filename_no_ext, - "": layer}) - - start_frame = int(self._instance.data["frameStartHandle"]) - workspace = self._instance.context.data["workspace"] - filename_zero = "{}_{:04d}.vrscene".format(output_path, start_frame) - filepath_zero = os.path.join(workspace, filename_zero) - - return filepath_zero.replace("\\", "/") - - def _patch_workfile(self): - """Patch Maya scene. - - This will take list of patches (lines to add) and apply them to - *published* Maya scene file (that is used later for rendering). - - Patches are dict with following structure:: - { - "name": "Name of patch", - "regex": "regex of line before patch", - "line": "line to insert" - } - - """ - project_settings = self._instance.context.data["project_settings"] - patches = ( - project_settings.get( - "deadline", {}).get( - "publish", {}).get( - "MayaSubmitDeadline", {}).get( - "scene_patches", {}) - ) - if not patches: - return - - if not os.path.splitext(self.scene_path)[1].lower() != ".ma": - self.log.debug("Skipping workfile patch since workfile is not " - ".ma file") - return - - compiled_regex = [re.compile(p["regex"]) for p in patches] - with open(self.scene_path, "r+") as pf: - scene_data = pf.readlines() - for ln, line in enumerate(scene_data): - for i, r in enumerate(compiled_regex): - if re.match(r, line): - scene_data.insert(ln + 1, patches[i]["line"]) - pf.seek(0) - pf.writelines(scene_data) - pf.truncate() - self.log.info("Applied {} patch to scene.".format( - patches[i]["name"] - )) - - def _job_info_label(self, label): - return "{label} {job.Name} [{start}-{end}]".format( - label=label, - job=self.job_info, - start=int(self._instance.data["frameStartHandle"]), - end=int(self._instance.data["frameEndHandle"]), - ) - - @classmethod - def get_attribute_defs(cls): - defs = super(MayaSubmitDeadline, cls).get_attribute_defs() - - defs.extend([ - NumberDef("priority", - label="Priority", - default=cls.default_priority, - decimals=0), - NumberDef("chunkSize", - label="Frames Per Task", - default=1, - decimals=0, - minimum=1, - maximum=1000), - TextDef("machineList", - label="Machine List", - default="", - placeholder="machine1,machine2"), - EnumDef("whitelist", - label="Machine List (Allow/Deny)", - items={ - True: "Allow List", - False: "Deny List", - }, - default=False), - NumberDef("tile_priority", - label="Tile Assembler Priority", - decimals=0, - default=cls.tile_priority), - BoolDef("strict_error_checking", - label="Strict Error Checking", - default=cls.strict_error_checking), - - ]) - - return defs - -def _format_tiles( - filename, - index, - tiles_x, - tiles_y, - width, - height, - prefix, - reversed_y=False -): - """Generate tile entries for Deadline tile job. - - Returns two dictionaries - one that can be directly used in Deadline - job, second that can be used for Deadline Assembly job configuration - file. - - This will format tile names: - - Example:: - { - "OutputFilename0Tile0": "_tile_1x1_4x4_Main_beauty.1001.exr", - "OutputFilename0Tile1": "_tile_2x1_4x4_Main_beauty.1001.exr" - } - - And add tile prefixes like: - - Example:: - Image prefix is: - `//_` - - Result for tile 0 for 4x4 will be: - `//_tile_1x1_4x4__` - - Calculating coordinates is tricky as in Job they are defined as top, - left, bottom, right with zero being in top-left corner. But Assembler - configuration file takes tile coordinates as X, Y, Width and Height and - zero is bottom left corner. - - Args: - filename (str): Filename to process as tiles. - index (int): Index of that file if it is sequence. - tiles_x (int): Number of tiles in X. - tiles_y (int): Number of tiles in Y. - width (int): Width resolution of final image. - height (int): Height resolution of final image. - prefix (str): Image prefix. - reversed_y (bool): Reverses the order of the y tiles. - - Returns: - (dict, dict): Tuple of two dictionaries - first can be used to - extend JobInfo, second has tiles x, y, width and height - used for assembler configuration. - - """ - # Math used requires integers for correct output - as such - # we ensure our inputs are correct. - assert isinstance(tiles_x, int), "tiles_x must be an integer" - assert isinstance(tiles_y, int), "tiles_y must be an integer" - assert isinstance(width, int), "width must be an integer" - assert isinstance(height, int), "height must be an integer" - - out = {"JobInfo": {}, "PluginInfo": {}} - cfg = OrderedDict() - w_space = width // tiles_x - h_space = height // tiles_y - - cfg["TilesCropped"] = "False" - - tile = 0 - range_y = range(1, tiles_y + 1) - reversed_y_range = list(reversed(range_y)) - for tile_x in range(1, tiles_x + 1): - for i, tile_y in enumerate(range_y): - tile_y_index = tile_y - if reversed_y: - tile_y_index = reversed_y_range[i] - - tile_prefix = "_tile_{}x{}_{}x{}_".format( - tile_x, tile_y_index, tiles_x, tiles_y - ) - - new_filename = "{}/{}{}".format( - os.path.dirname(filename), - tile_prefix, - os.path.basename(filename) - ) - - top = height - (tile_y * h_space) - bottom = height - ((tile_y - 1) * h_space) - 1 - left = (tile_x - 1) * w_space - right = (tile_x * w_space) - 1 - - # Job info - key = "OutputFilename{}".format(index) - out["JobInfo"][key] = new_filename - - # Plugin Info - key = "RegionPrefix{}".format(str(tile)) - out["PluginInfo"][key] = "/{}".format( - tile_prefix - ).join(prefix.rsplit("/", 1)) - out["PluginInfo"]["RegionTop{}".format(tile)] = top - out["PluginInfo"]["RegionBottom{}".format(tile)] = bottom - out["PluginInfo"]["RegionLeft{}".format(tile)] = left - out["PluginInfo"]["RegionRight{}".format(tile)] = right - - # Tile config - cfg["Tile{}FileName".format(tile)] = new_filename - cfg["Tile{}X".format(tile)] = left - cfg["Tile{}Y".format(tile)] = top - cfg["Tile{}Width".format(tile)] = w_space - cfg["Tile{}Height".format(tile)] = h_space - - tile += 1 - - return out, cfg diff --git a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_nuke_deadline.py b/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_nuke_deadline.py deleted file mode 100644 index 7ead5142cf..0000000000 --- a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_nuke_deadline.py +++ /dev/null @@ -1,558 +0,0 @@ -import os -import re -import json -import getpass -from datetime import datetime - -import pyblish.api - -from ayon_core.pipeline.publish import ( - AYONPyblishPluginMixin -) -from ayon_core.lib import ( - is_in_tests, - BoolDef, - NumberDef -) -from ayon_deadline.abstract_submit_deadline import requests_post - - -class NukeSubmitDeadline(pyblish.api.InstancePlugin, - AYONPyblishPluginMixin): - """Submit write to Deadline - - Renders are submitted to a Deadline Web Service as - supplied via settings key "DEADLINE_REST_URL". - - """ - - label = "Submit Nuke to Deadline" - order = pyblish.api.IntegratorOrder + 0.1 - hosts = ["nuke"] - families = ["render", "prerender"] - optional = True - targets = ["local"] - settings_category = "deadline" - - # presets - priority = 50 - chunk_size = 1 - concurrent_tasks = 1 - group = "" - department = "" - limit_groups = [] - use_gpu = False - env_allowed_keys = [] - env_search_replace_values = [] - workfile_dependency = True - use_published_workfile = True - - @classmethod - def get_attribute_defs(cls): - return [ - NumberDef( - "priority", - label="Priority", - default=cls.priority, - decimals=0 - ), - NumberDef( - "chunk", - label="Frames Per Task", - default=cls.chunk_size, - decimals=0, - minimum=1, - maximum=1000 - ), - NumberDef( - "concurrency", - label="Concurrency", - default=cls.concurrent_tasks, - decimals=0, - minimum=1, - maximum=10 - ), - BoolDef( - "use_gpu", - default=cls.use_gpu, - label="Use GPU" - ), - BoolDef( - "workfile_dependency", - default=cls.workfile_dependency, - label="Workfile Dependency" - ), - BoolDef( - "use_published_workfile", - default=cls.use_published_workfile, - label="Use Published Workfile" - ) - ] - - def process(self, instance): - if not instance.data.get("farm"): - self.log.debug("Skipping local instance.") - return - instance.data["attributeValues"] = self.get_attr_values_from_data( - instance.data) - - families = instance.data["families"] - - node = instance.data["transientData"]["node"] - context = instance.context - - deadline_url = instance.data["deadline"]["url"] - assert deadline_url, "Requires Deadline Webservice URL" - - self.deadline_url = "{}/api/jobs".format(deadline_url) - self._comment = context.data.get("comment", "") - self._ver = re.search(r"\d+\.\d+", context.data.get("hostVersion")) - self._deadline_user = context.data.get( - "deadlineUser", getpass.getuser()) - submit_frame_start = int(instance.data["frameStartHandle"]) - submit_frame_end = int(instance.data["frameEndHandle"]) - - # get output path - render_path = instance.data['path'] - script_path = context.data["currentFile"] - - use_published_workfile = instance.data["attributeValues"].get( - "use_published_workfile", self.use_published_workfile - ) - if use_published_workfile: - script_path = self._get_published_workfile_path(context) - - # only add main rendering job if target is not frames_farm - r_job_response_json = None - if instance.data["render_target"] != "frames_farm": - r_job_response = self.payload_submit( - instance, - script_path, - render_path, - node.name(), - submit_frame_start, - submit_frame_end - ) - r_job_response_json = r_job_response.json() - instance.data["deadlineSubmissionJob"] = r_job_response_json - - # Store output dir for unified publisher (filesequence) - instance.data["outputDir"] = os.path.dirname( - render_path).replace("\\", "/") - instance.data["publishJobState"] = "Suspended" - - if instance.data.get("bakingNukeScripts"): - for baking_script in instance.data["bakingNukeScripts"]: - render_path = baking_script["bakeRenderPath"] - script_path = baking_script["bakeScriptPath"] - exe_node_name = baking_script["bakeWriteNodeName"] - - b_job_response = self.payload_submit( - instance, - script_path, - render_path, - exe_node_name, - submit_frame_start, - submit_frame_end, - r_job_response_json, - baking_submission=True - ) - - # Store output dir for unified publisher (filesequence) - instance.data["deadlineSubmissionJob"] = b_job_response.json() - - instance.data["publishJobState"] = "Suspended" - - # add to list of job Id - if not instance.data.get("bakingSubmissionJobs"): - instance.data["bakingSubmissionJobs"] = [] - - instance.data["bakingSubmissionJobs"].append( - b_job_response.json()["_id"]) - - # redefinition of families - if "render" in instance.data["productType"]: - instance.data["family"] = "write" - instance.data["productType"] = "write" - families.insert(0, "render2d") - elif "prerender" in instance.data["productType"]: - instance.data["family"] = "write" - instance.data["productType"] = "write" - families.insert(0, "prerender") - instance.data["families"] = families - - def _get_published_workfile_path(self, context): - """This method is temporary while the class is not inherited from - AbstractSubmitDeadline""" - anatomy = context.data["anatomy"] - # WARNING Hardcoded template name 'default' > may not be used - publish_template = anatomy.get_template_item( - "publish", "default", "path" - ) - for instance in context: - if ( - instance.data["productType"] != "workfile" - # Disabled instances won't be integrated - or instance.data("publish") is False - ): - continue - template_data = instance.data["anatomyData"] - # Expect workfile instance has only one representation - representation = instance.data["representations"][0] - # Get workfile extension - repre_file = representation["files"] - self.log.info(repre_file) - ext = os.path.splitext(repre_file)[1].lstrip(".") - - # Fill template data - template_data["representation"] = representation["name"] - template_data["ext"] = ext - template_data["comment"] = None - - template_filled = publish_template.format(template_data) - script_path = os.path.normpath(template_filled) - self.log.info( - "Using published scene for render {}".format( - script_path - ) - ) - return script_path - - return None - - def payload_submit( - self, - instance, - script_path, - render_path, - exe_node_name, - start_frame, - end_frame, - response_data=None, - baking_submission=False, - ): - """Submit payload to Deadline - - Args: - instance (pyblish.api.Instance): pyblish instance - script_path (str): path to nuke script - render_path (str): path to rendered images - exe_node_name (str): name of the node to render - start_frame (int): start frame - end_frame (int): end frame - response_data Optional[dict]: response data from - previous submission - baking_submission Optional[bool]: if it's baking submission - - Returns: - requests.Response - """ - render_dir = os.path.normpath(os.path.dirname(render_path)) - - # batch name - src_filepath = instance.context.data["currentFile"] - batch_name = os.path.basename(src_filepath) - job_name = os.path.basename(render_path) - - if is_in_tests(): - batch_name += datetime.now().strftime("%d%m%Y%H%M%S") - - output_filename_0 = self.preview_fname(render_path) - - if not response_data: - response_data = {} - - try: - # Ensure render folder exists - os.makedirs(render_dir) - except OSError: - pass - - # resolve any limit groups - limit_groups = self.get_limit_groups() - self.log.debug("Limit groups: `{}`".format(limit_groups)) - - payload = { - "JobInfo": { - # Top-level group name - "BatchName": batch_name, - - # Job name, as seen in Monitor - "Name": job_name, - - # Arbitrary username, for visualisation in Monitor - "UserName": self._deadline_user, - - "Priority": instance.data["attributeValues"].get( - "priority", self.priority), - "ChunkSize": instance.data["attributeValues"].get( - "chunk", self.chunk_size), - "ConcurrentTasks": instance.data["attributeValues"].get( - "concurrency", - self.concurrent_tasks - ), - - "Department": self.department, - - "Pool": instance.data.get("primaryPool"), - "SecondaryPool": instance.data.get("secondaryPool"), - "Group": self.group, - - "Plugin": "Nuke", - "Frames": "{start}-{end}".format( - start=start_frame, - end=end_frame - ), - "Comment": self._comment, - - # Optional, enable double-click to preview rendered - # frames from Deadline Monitor - "OutputFilename0": output_filename_0.replace("\\", "/"), - - # limiting groups - "LimitGroups": ",".join(limit_groups) - - }, - "PluginInfo": { - # Input - "SceneFile": script_path, - - # Output directory and filename - "OutputFilePath": render_dir.replace("\\", "/"), - # "OutputFilePrefix": render_variables["filename_prefix"], - - # Mandatory for Deadline - "Version": self._ver.group(), - - # Resolve relative references - "ProjectPath": script_path, - "AWSAssetFile0": render_path, - - # using GPU by default - "UseGpu": instance.data["attributeValues"].get( - "use_gpu", self.use_gpu), - - # Only the specific write node is rendered. - "WriteNode": exe_node_name - }, - - # Mandatory for Deadline, may be empty - "AuxFiles": [] - } - - # Add workfile dependency. - workfile_dependency = instance.data["attributeValues"].get( - "workfile_dependency", self.workfile_dependency - ) - if workfile_dependency: - payload["JobInfo"].update({"AssetDependency0": script_path}) - - # TODO: rewrite for baking with sequences - if baking_submission: - payload["JobInfo"].update({ - "JobType": "Normal", - "ChunkSize": 99999999 - }) - - if response_data.get("_id"): - payload["JobInfo"].update({ - "BatchName": response_data["Props"]["Batch"], - "JobDependency0": response_data["_id"], - }) - - # Include critical environment variables with submission - keys = [ - "PYTHONPATH", - "PATH", - "AYON_BUNDLE_NAME", - "AYON_DEFAULT_SETTINGS_VARIANT", - "AYON_PROJECT_NAME", - "AYON_FOLDER_PATH", - "AYON_TASK_NAME", - "AYON_APP_NAME", - "FTRACK_API_KEY", - "FTRACK_API_USER", - "FTRACK_SERVER", - "PYBLISHPLUGINPATH", - "NUKE_PATH", - "TOOL_ENV", - "FOUNDRY_LICENSE", - "OPENPYPE_SG_USER", - ] - - # add allowed keys from preset if any - if self.env_allowed_keys: - keys += self.env_allowed_keys - - environment = { - key: os.environ[key] - for key in keys - if key in os.environ - } - - # to recognize render jobs - environment["AYON_RENDER_JOB"] = "1" - - # finally search replace in values of any key - if self.env_search_replace_values: - for key, value in environment.items(): - for item in self.env_search_replace_values: - environment[key] = value.replace( - item["name"], item["value"] - ) - - payload["JobInfo"].update({ - "EnvironmentKeyValue%d" % index: "{key}={value}".format( - key=key, - value=environment[key] - ) for index, key in enumerate(environment) - }) - - plugin = payload["JobInfo"]["Plugin"] - self.log.debug("using render plugin : {}".format(plugin)) - - self.log.debug("Submitting..") - self.log.debug(json.dumps(payload, indent=4, sort_keys=True)) - - # adding expected files to instance.data - self.expected_files( - instance, - render_path, - start_frame, - end_frame - ) - - self.log.debug("__ expectedFiles: `{}`".format( - instance.data["expectedFiles"])) - auth = instance.data["deadline"]["auth"] - verify = instance.data["deadline"]["verify"] - response = requests_post(self.deadline_url, - json=payload, - timeout=10, - auth=auth, - verify=verify) - - if not response.ok: - raise Exception(response.text) - - return response - - def preflight_check(self, instance): - """Ensure the startFrame, endFrame and byFrameStep are integers""" - - for key in ("frameStart", "frameEnd"): - value = instance.data[key] - - if int(value) == value: - continue - - self.log.warning( - "%f=%d was rounded off to nearest integer" - % (value, int(value)) - ) - - def preview_fname(self, path): - """Return output file path with #### for padding. - - Deadline requires the path to be formatted with # in place of numbers. - For example `/path/to/render.####.png` - - Args: - path (str): path to rendered images - - Returns: - str - - """ - self.log.debug("_ path: `{}`".format(path)) - if "%" in path: - search_results = re.search(r"(%0)(\d)(d.)", path).groups() - self.log.debug("_ search_results: `{}`".format(search_results)) - return int(search_results[1]) - if "#" in path: - self.log.debug("_ path: `{}`".format(path)) - return path - - def expected_files( - self, - instance, - filepath, - start_frame, - end_frame - ): - """ Create expected files in instance data - """ - if not instance.data.get("expectedFiles"): - instance.data["expectedFiles"] = [] - - dirname = os.path.dirname(filepath) - file = os.path.basename(filepath) - - # since some files might be already tagged as publish_on_farm - # we need to avoid adding them to expected files since those would be - # duplicated into metadata.json file - representations = instance.data.get("representations", []) - # check if file is not in representations with publish_on_farm tag - for repre in representations: - # Skip if 'publish_on_farm' not available - if "publish_on_farm" not in repre.get("tags", []): - continue - - # in case where single file (video, image) is already in - # representation file. Will be added to expected files via - # submit_publish_job.py - if file in repre.get("files", []): - self.log.debug( - "Skipping expected file: {}".format(filepath)) - return - - # in case path is hashed sequence expression - # (e.g. /path/to/file.####.png) - if "#" in file: - pparts = file.split("#") - padding = "%0{}d".format(len(pparts) - 1) - file = pparts[0] + padding + pparts[-1] - - # in case input path was single file (video or image) - if "%" not in file: - instance.data["expectedFiles"].append(filepath) - return - - # shift start frame by 1 if slate is present - if instance.data.get("slate"): - start_frame -= 1 - - # add sequence files to expected files - for i in range(start_frame, (end_frame + 1)): - instance.data["expectedFiles"].append( - os.path.join(dirname, (file % i)).replace("\\", "/")) - - def get_limit_groups(self): - """Search for limit group nodes and return group name. - Limit groups will be defined as pairs in Nuke deadline submitter - presents where the key will be name of limit group and value will be - a list of plugin's node class names. Thus, when a plugin uses more - than one node, these will be captured and the triggered process - will add the appropriate limit group to the payload jobinfo attributes. - Returning: - list: captured groups list - """ - # Not all hosts can import this module. - import nuke - - captured_groups = [] - for limit_group in self.limit_groups: - lg_name = limit_group["name"] - - for node_class in limit_group["value"]: - for node in nuke.allNodes(recurseGroups=True): - # ignore all nodes not member of defined class - if node.Class() not in node_class: - continue - # ignore all disabled nodes - if node["disable"].value(): - continue - # add group name if not already added - if lg_name not in captured_groups: - captured_groups.append(lg_name) - return captured_groups diff --git a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_publish_cache_job.py b/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_publish_cache_job.py deleted file mode 100644 index d93592a6a3..0000000000 --- a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_publish_cache_job.py +++ /dev/null @@ -1,463 +0,0 @@ -# -*- coding: utf-8 -*- -"""Submit publishing job to farm.""" -import os -import json -import re -from copy import deepcopy - -import ayon_api -import pyblish.api - -from ayon_core.pipeline import publish -from ayon_core.lib import EnumDef, is_in_tests -from ayon_core.pipeline.version_start import get_versioning_start -from ayon_core.pipeline.farm.pyblish_functions import ( - create_skeleton_instance_cache, - create_instances_for_cache, - attach_instances_to_product, - prepare_cache_representations, - create_metadata_path -) -from ayon_deadline.abstract_submit_deadline import requests_post - - -class ProcessSubmittedCacheJobOnFarm(pyblish.api.InstancePlugin, - publish.AYONPyblishPluginMixin, - publish.ColormanagedPyblishPluginMixin): - """Process Cache Job submitted on farm - This is replicated version of submit publish job - specifically for cache(s). - - These jobs are dependent on a deadline job - submission prior to this plug-in. - - - In case of Deadline, it creates dependent job on farm publishing - rendered image sequence. - - Options in instance.data: - - deadlineSubmissionJob (dict, Required): The returned .json - data from the job submission to deadline. - - - outputDir (str, Required): The output directory where the metadata - file should be generated. It's assumed that this will also be - final folder containing the output files. - - - ext (str, Optional): The extension (including `.`) that is required - in the output filename to be picked up for image sequence - publishing. - - - expectedFiles (list or dict): explained below - - """ - - label = "Submit cache jobs to Deadline" - order = pyblish.api.IntegratorOrder + 0.2 - icon = "tractor" - settings_category = "deadline" - - targets = ["local"] - - hosts = ["houdini"] - - families = ["publish.hou"] - - environ_keys = [ - "FTRACK_API_USER", - "FTRACK_API_KEY", - "FTRACK_SERVER", - "AYON_APP_NAME", - "AYON_USERNAME", - "AYON_SG_USERNAME", - "KITSU_LOGIN", - "KITSU_PWD" - ] - - # custom deadline attributes - deadline_department = "" - deadline_pool = "" - deadline_pool_secondary = "" - deadline_group = "" - deadline_chunk_size = 1 - deadline_priority = None - - # regex for finding frame number in string - R_FRAME_NUMBER = re.compile(r'.+\.(?P[0-9]+)\..+') - - plugin_pype_version = "3.0" - - # script path for publish_filesequence.py - publishing_script = None - - def _submit_deadline_post_job(self, instance, job): - """Submit publish job to Deadline. - - Returns: - (str): deadline_publish_job_id - """ - data = instance.data.copy() - product_name = data["productName"] - job_name = "Publish - {}".format(product_name) - - anatomy = instance.context.data['anatomy'] - - # instance.data.get("productName") != instances[0]["productName"] - # 'Main' vs 'renderMain' - override_version = None - instance_version = instance.data.get("version") # take this if exists - if instance_version != 1: - override_version = instance_version - - output_dir = self._get_publish_folder( - anatomy, - deepcopy(instance.data["anatomyData"]), - instance.data.get("folderEntity"), - instance.data["productName"], - instance.context, - instance.data["productType"], - override_version - ) - - # Transfer the environment from the original job to this dependent - # job so they use the same environment - metadata_path, rootless_metadata_path = \ - create_metadata_path(instance, anatomy) - - environment = { - "AYON_PROJECT_NAME": instance.context.data["projectName"], - "AYON_FOLDER_PATH": instance.context.data["folderPath"], - "AYON_TASK_NAME": instance.context.data["task"], - "AYON_USERNAME": instance.context.data["user"], - "AYON_LOG_NO_COLORS": "1", - "AYON_IN_TESTS": str(int(is_in_tests())), - "AYON_PUBLISH_JOB": "1", - "AYON_RENDER_JOB": "0", - "AYON_REMOTE_PUBLISH": "0", - "AYON_BUNDLE_NAME": os.environ["AYON_BUNDLE_NAME"], - "AYON_DEFAULT_SETTINGS_VARIANT": ( - os.environ["AYON_DEFAULT_SETTINGS_VARIANT"] - ), - } - - # add environments from self.environ_keys - for env_key in self.environ_keys: - if os.getenv(env_key): - environment[env_key] = os.environ[env_key] - - priority = self.deadline_priority or instance.data.get("priority", 50) - - instance_settings = self.get_attr_values_from_data(instance.data) - initial_status = instance_settings.get("publishJobState", "Active") - - args = [ - "--headless", - 'publish', - '"{}"'.format(rootless_metadata_path), - "--targets", "deadline", - "--targets", "farm" - ] - - # Generate the payload for Deadline submission - secondary_pool = ( - self.deadline_pool_secondary or instance.data.get("secondaryPool") - ) - payload = { - "JobInfo": { - "Plugin": "Ayon", - "BatchName": job["Props"]["Batch"], - "Name": job_name, - "UserName": job["Props"]["User"], - "Comment": instance.context.data.get("comment", ""), - - "Department": self.deadline_department, - "ChunkSize": self.deadline_chunk_size, - "Priority": priority, - "InitialStatus": initial_status, - - "Group": self.deadline_group, - "Pool": self.deadline_pool or instance.data.get("primaryPool"), - "SecondaryPool": secondary_pool, - # ensure the outputdirectory with correct slashes - "OutputDirectory0": output_dir.replace("\\", "/") - }, - "PluginInfo": { - "Version": self.plugin_pype_version, - "Arguments": " ".join(args), - "SingleFrameOnly": "True", - }, - # Mandatory for Deadline, may be empty - "AuxFiles": [], - } - - if job.get("_id"): - payload["JobInfo"]["JobDependency0"] = job["_id"] - - for index, (key_, value_) in enumerate(environment.items()): - payload["JobInfo"].update( - { - "EnvironmentKeyValue%d" - % index: "{key}={value}".format( - key=key_, value=value_ - ) - } - ) - # remove secondary pool - payload["JobInfo"].pop("SecondaryPool", None) - - self.log.debug("Submitting Deadline publish job ...") - - url = "{}/api/jobs".format(self.deadline_url) - auth = instance.data["deadline"]["auth"] - verify = instance.data["deadline"]["verify"] - response = requests_post( - url, json=payload, timeout=10, auth=auth, verify=verify) - if not response.ok: - raise Exception(response.text) - - deadline_publish_job_id = response.json()["_id"] - - return deadline_publish_job_id - - def process(self, instance): - # type: (pyblish.api.Instance) -> None - """Process plugin. - - Detect type of render farm submission and create and post dependent - job in case of Deadline. It creates json file with metadata needed for - publishing in directory of render. - - Args: - instance (pyblish.api.Instance): Instance data. - - """ - if not instance.data.get("farm"): - self.log.debug("Skipping local instance.") - return - - anatomy = instance.context.data["anatomy"] - - instance_skeleton_data = create_skeleton_instance_cache(instance) - """ - if content of `expectedFiles` list are dictionaries, we will handle - it as list of AOVs, creating instance for every one of them. - - Example: - -------- - - expectedFiles = [ - { - "beauty": [ - "foo_v01.0001.exr", - "foo_v01.0002.exr" - ], - - "Z": [ - "boo_v01.0001.exr", - "boo_v01.0002.exr" - ] - } - ] - - This will create instances for `beauty` and `Z` product - adding those files to their respective representations. - - If we have only list of files, we collect all file sequences. - More then one doesn't probably make sense, but we'll handle it - like creating one instance with multiple representations. - - Example: - -------- - - expectedFiles = [ - "foo_v01.0001.exr", - "foo_v01.0002.exr", - "xxx_v01.0001.exr", - "xxx_v01.0002.exr" - ] - - This will result in one instance with two representations: - `foo` and `xxx` - """ - - if isinstance(instance.data.get("expectedFiles")[0], dict): - instances = create_instances_for_cache( - instance, instance_skeleton_data) - else: - representations = prepare_cache_representations( - instance_skeleton_data, - instance.data.get("expectedFiles"), - anatomy - ) - - if "representations" not in instance_skeleton_data.keys(): - instance_skeleton_data["representations"] = [] - - # add representation - instance_skeleton_data["representations"] += representations - instances = [instance_skeleton_data] - - # attach instances to product - if instance.data.get("attachTo"): - instances = attach_instances_to_product( - instance.data.get("attachTo"), instances - ) - - r''' SUBMiT PUBLiSH JOB 2 D34DLiN3 - ____ - ' ' .---. .---. .--. .---. .--..--..--..--. .---. - | | --= \ | . \/ _|/ \| . \ || || \ |/ _| - | JOB | --= / | | || __| .. | | | |;_ || \ || __| - | | |____./ \.__|._||_.|___./|_____|||__|\__|\.___| - ._____. - - ''' - - render_job = None - submission_type = "" - if instance.data.get("toBeRenderedOn") == "deadline": - render_job = instance.data.pop("deadlineSubmissionJob", None) - submission_type = "deadline" - - if not render_job: - import getpass - - render_job = {} - self.log.debug("Faking job data ...") - render_job["Props"] = {} - # Render job doesn't exist because we do not have prior submission. - # We still use data from it so lets fake it. - # - # Batch name reflect original scene name - - if instance.data.get("assemblySubmissionJobs"): - render_job["Props"]["Batch"] = instance.data.get( - "jobBatchName") - else: - batch = os.path.splitext(os.path.basename( - instance.context.data.get("currentFile")))[0] - render_job["Props"]["Batch"] = batch - # User is deadline user - render_job["Props"]["User"] = instance.context.data.get( - "deadlineUser", getpass.getuser()) - - deadline_publish_job_id = None - if submission_type == "deadline": - self.deadline_url = instance.data["deadline"]["url"] - assert self.deadline_url, "Requires Deadline Webservice URL" - - deadline_publish_job_id = \ - self._submit_deadline_post_job(instance, render_job) - - # Inject deadline url to instances. - for inst in instances: - if "deadline" not in inst: - inst["deadline"] = {} - inst["deadline"] = instance.data["deadline"] - - # publish job file - publish_job = { - "folderPath": instance_skeleton_data["folderPath"], - "frameStart": instance_skeleton_data["frameStart"], - "frameEnd": instance_skeleton_data["frameEnd"], - "fps": instance_skeleton_data["fps"], - "source": instance_skeleton_data["source"], - "user": instance.context.data["user"], - "version": instance.context.data["version"], # workfile version - "intent": instance.context.data.get("intent"), - "comment": instance.context.data.get("comment"), - "job": render_job or None, - "instances": instances - } - - if deadline_publish_job_id: - publish_job["deadline_publish_job_id"] = deadline_publish_job_id - - metadata_path, rootless_metadata_path = \ - create_metadata_path(instance, anatomy) - - with open(metadata_path, "w") as f: - json.dump(publish_job, f, indent=4, sort_keys=True) - - def _get_publish_folder(self, anatomy, template_data, - folder_entity, product_name, context, - product_type, version=None): - """ - Extracted logic to pre-calculate real publish folder, which is - calculated in IntegrateNew inside of Deadline process. - This should match logic in: - 'collect_anatomy_instance_data' - to - get correct anatomy, family, version for product and - 'collect_resources_path' - get publish_path - - Args: - anatomy (ayon_core.pipeline.anatomy.Anatomy): - template_data (dict): pre-calculated collected data for process - folder_entity (dict[str, Any]): Folder entity. - product_name (str): Product name (actually group name of product). - product_type (str): for current deadline process it's always - 'render' - TODO - for generic use family needs to be dynamically - calculated like IntegrateNew does - version (int): override version from instance if exists - - Returns: - (string): publish folder where rendered and published files will - be stored - based on 'publish' template - """ - - project_name = context.data["projectName"] - host_name = context.data["hostName"] - if not version: - version_entity = None - if folder_entity: - version_entity = ayon_api.get_last_version_by_product_name( - project_name, - product_name, - folder_entity["id"] - ) - - if version_entity: - version = int(version_entity["version"]) + 1 - else: - version = get_versioning_start( - project_name, - host_name, - task_name=template_data["task"]["name"], - task_type=template_data["task"]["type"], - product_type="render", - product_name=product_name, - project_settings=context.data["project_settings"] - ) - - task_info = template_data.get("task") or {} - - template_name = publish.get_publish_template_name( - project_name, - host_name, - product_type, - task_info.get("name"), - task_info.get("type"), - ) - - template_data["subset"] = product_name - template_data["family"] = product_type - template_data["version"] = version - template_data["product"] = { - "name": product_name, - "type": product_type, - } - - render_dir_template = anatomy.get_template_item( - "publish", template_name, "directory" - ) - return render_dir_template.format_strict(template_data) - - @classmethod - def get_attribute_defs(cls): - return [ - EnumDef("publishJobState", - label="Publish Job State", - items=["Active", "Suspended"], - default="Active") - ] diff --git a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_publish_job.py b/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_publish_job.py deleted file mode 100644 index 643dcc1c46..0000000000 --- a/server_addon/deadline/client/ayon_deadline/plugins/publish/submit_publish_job.py +++ /dev/null @@ -1,585 +0,0 @@ -# -*- coding: utf-8 -*- -"""Submit publishing job to farm.""" -import os -import json -import re -from copy import deepcopy - -import clique -import ayon_api -import pyblish.api - -from ayon_core.pipeline import publish -from ayon_core.lib import EnumDef, is_in_tests -from ayon_core.pipeline.version_start import get_versioning_start - -from ayon_core.pipeline.farm.pyblish_functions import ( - create_skeleton_instance, - create_instances_for_aov, - attach_instances_to_product, - prepare_representations, - create_metadata_path -) -from ayon_deadline.abstract_submit_deadline import requests_post - - -def get_resource_files(resources, frame_range=None): - """Get resource files at given path. - - If `frame_range` is specified those outside will be removed. - - Arguments: - resources (list): List of resources - frame_range (list): Frame range to apply override - - Returns: - list of str: list of collected resources - - """ - res_collections, _ = clique.assemble(resources) - assert len(res_collections) == 1, "Multiple collections found" - res_collection = res_collections[0] - - # Remove any frames - if frame_range is not None: - for frame in frame_range: - if frame not in res_collection.indexes: - continue - res_collection.indexes.remove(frame) - - return list(res_collection) - - -class ProcessSubmittedJobOnFarm(pyblish.api.InstancePlugin, - publish.AYONPyblishPluginMixin, - publish.ColormanagedPyblishPluginMixin): - """Process Job submitted on farm. - - These jobs are dependent on a deadline job - submission prior to this plug-in. - - It creates dependent job on farm publishing rendered image sequence. - - Options in instance.data: - - deadlineSubmissionJob (dict, Required): The returned .json - data from the job submission to deadline. - - - outputDir (str, Required): The output directory where the metadata - file should be generated. It's assumed that this will also be - final folder containing the output files. - - - ext (str, Optional): The extension (including `.`) that is required - in the output filename to be picked up for image sequence - publishing. - - - publishJobState (str, Optional): "Active" or "Suspended" - This defaults to "Suspended" - - - expectedFiles (list or dict): explained below - - """ - - label = "Submit Image Publishing job to Deadline" - order = pyblish.api.IntegratorOrder + 0.2 - icon = "tractor" - - targets = ["local"] - - hosts = ["fusion", "max", "maya", "nuke", "houdini", - "celaction", "aftereffects", "harmony", "blender"] - - families = ["render", "render.farm", "render.frames_farm", - "prerender", "prerender.farm", "prerender.frames_farm", - "renderlayer", "imagesequence", "image", - "vrayscene", "maxrender", - "arnold_rop", "mantra_rop", - "karma_rop", "vray_rop", - "redshift_rop", "usdrender"] - settings_category = "deadline" - - aov_filter = [ - { - "name": "maya", - "value": [r".*([Bb]eauty).*"] - }, - { - "name": "blender", - "value": [r".*([Bb]eauty).*"] - }, - { - # for everything from AE - "name": "aftereffects", - "value": [r".*"] - }, - { - "name": "harmony", - "value": [r".*"] - }, - { - "name": "celaction", - "value": [r".*"] - }, - { - "name": "max", - "value": [r".*"] - }, - ] - - environ_keys = [ - "FTRACK_API_USER", - "FTRACK_API_KEY", - "FTRACK_SERVER", - "AYON_APP_NAME", - "AYON_USERNAME", - "AYON_SG_USERNAME", - "KITSU_LOGIN", - "KITSU_PWD" - ] - - # custom deadline attributes - deadline_department = "" - deadline_pool = "" - deadline_pool_secondary = "" - deadline_group = "" - deadline_chunk_size = 1 - deadline_priority = None - - # regex for finding frame number in string - R_FRAME_NUMBER = re.compile(r'.+\.(?P[0-9]+)\..+') - - # mapping of instance properties to be transferred to new instance - # for every specified family - instance_transfer = { - "slate": ["slateFrames", "slate"], - "review": ["lutPath"], - "render2d": ["bakingNukeScripts", "version"], - "renderlayer": ["convertToScanline"] - } - - # list of family names to transfer to new family if present - families_transfer = ["render3d", "render2d", "ftrack", "slate"] - plugin_pype_version = "3.0" - - # script path for publish_filesequence.py - publishing_script = None - - # poor man exclusion - skip_integration_repre_list = [] - - def _submit_deadline_post_job(self, instance, job, instances): - """Submit publish job to Deadline. - - Returns: - (str): deadline_publish_job_id - """ - data = instance.data.copy() - product_name = data["productName"] - job_name = "Publish - {}".format(product_name) - - anatomy = instance.context.data['anatomy'] - - # instance.data.get("productName") != instances[0]["productName"] - # 'Main' vs 'renderMain' - override_version = None - instance_version = instance.data.get("version") # take this if exists - if instance_version != 1: - override_version = instance_version - - output_dir = self._get_publish_folder( - anatomy, - deepcopy(instance.data["anatomyData"]), - instance.data.get("folderEntity"), - instances[0]["productName"], - instance.context, - instances[0]["productType"], - override_version - ) - - # Transfer the environment from the original job to this dependent - # job so they use the same environment - metadata_path, rootless_metadata_path = \ - create_metadata_path(instance, anatomy) - - environment = { - "AYON_PROJECT_NAME": instance.context.data["projectName"], - "AYON_FOLDER_PATH": instance.context.data["folderPath"], - "AYON_TASK_NAME": instance.context.data["task"], - "AYON_USERNAME": instance.context.data["user"], - "AYON_LOG_NO_COLORS": "1", - "AYON_IN_TESTS": str(int(is_in_tests())), - "AYON_PUBLISH_JOB": "1", - "AYON_RENDER_JOB": "0", - "AYON_REMOTE_PUBLISH": "0", - "AYON_BUNDLE_NAME": os.environ["AYON_BUNDLE_NAME"], - "AYON_DEFAULT_SETTINGS_VARIANT": ( - os.environ["AYON_DEFAULT_SETTINGS_VARIANT"] - ), - } - - # add environments from self.environ_keys - for env_key in self.environ_keys: - if os.getenv(env_key): - environment[env_key] = os.environ[env_key] - - priority = self.deadline_priority or instance.data.get("priority", 50) - - instance_settings = self.get_attr_values_from_data(instance.data) - initial_status = instance_settings.get("publishJobState", "Active") - - args = [ - "--headless", - 'publish', - '"{}"'.format(rootless_metadata_path), - "--targets", "deadline", - "--targets", "farm" - ] - - # Generate the payload for Deadline submission - secondary_pool = ( - self.deadline_pool_secondary or instance.data.get("secondaryPool") - ) - payload = { - "JobInfo": { - "Plugin": "Ayon", - "BatchName": job["Props"]["Batch"], - "Name": job_name, - "UserName": job["Props"]["User"], - "Comment": instance.context.data.get("comment", ""), - - "Department": self.deadline_department, - "ChunkSize": self.deadline_chunk_size, - "Priority": priority, - "InitialStatus": initial_status, - - "Group": self.deadline_group, - "Pool": self.deadline_pool or instance.data.get("primaryPool"), - "SecondaryPool": secondary_pool, - # ensure the outputdirectory with correct slashes - "OutputDirectory0": output_dir.replace("\\", "/") - }, - "PluginInfo": { - "Version": self.plugin_pype_version, - "Arguments": " ".join(args), - "SingleFrameOnly": "True", - }, - # Mandatory for Deadline, may be empty - "AuxFiles": [], - } - - # add assembly jobs as dependencies - if instance.data.get("tileRendering"): - self.log.info("Adding tile assembly jobs as dependencies...") - job_index = 0 - for assembly_id in instance.data.get("assemblySubmissionJobs"): - payload["JobInfo"]["JobDependency{}".format( - job_index)] = assembly_id # noqa: E501 - job_index += 1 - elif instance.data.get("bakingSubmissionJobs"): - self.log.info( - "Adding baking submission jobs as dependencies..." - ) - job_index = 0 - for assembly_id in instance.data["bakingSubmissionJobs"]: - payload["JobInfo"]["JobDependency{}".format( - job_index)] = assembly_id # noqa: E501 - job_index += 1 - elif job.get("_id"): - payload["JobInfo"]["JobDependency0"] = job["_id"] - - for index, (key_, value_) in enumerate(environment.items()): - payload["JobInfo"].update( - { - "EnvironmentKeyValue%d" - % index: "{key}={value}".format( - key=key_, value=value_ - ) - } - ) - # remove secondary pool - payload["JobInfo"].pop("SecondaryPool", None) - - self.log.debug("Submitting Deadline publish job ...") - - url = "{}/api/jobs".format(self.deadline_url) - auth = instance.data["deadline"]["auth"] - verify = instance.data["deadline"]["verify"] - response = requests_post( - url, json=payload, timeout=10, auth=auth, verify=verify) - if not response.ok: - raise Exception(response.text) - - deadline_publish_job_id = response.json()["_id"] - - return deadline_publish_job_id - - def process(self, instance): - # type: (pyblish.api.Instance) -> None - """Process plugin. - - Detect type of render farm submission and create and post dependent - job in case of Deadline. It creates json file with metadata needed for - publishing in directory of render. - - Args: - instance (pyblish.api.Instance): Instance data. - - """ - if not instance.data.get("farm"): - self.log.debug("Skipping local instance.") - return - - anatomy = instance.context.data["anatomy"] - - instance_skeleton_data = create_skeleton_instance( - instance, families_transfer=self.families_transfer, - instance_transfer=self.instance_transfer) - """ - if content of `expectedFiles` list are dictionaries, we will handle - it as list of AOVs, creating instance for every one of them. - - Example: - -------- - - expectedFiles = [ - { - "beauty": [ - "foo_v01.0001.exr", - "foo_v01.0002.exr" - ], - - "Z": [ - "boo_v01.0001.exr", - "boo_v01.0002.exr" - ] - } - ] - - This will create instances for `beauty` and `Z` product - adding those files to their respective representations. - - If we have only list of files, we collect all file sequences. - More then one doesn't probably make sense, but we'll handle it - like creating one instance with multiple representations. - - Example: - -------- - - expectedFiles = [ - "foo_v01.0001.exr", - "foo_v01.0002.exr", - "xxx_v01.0001.exr", - "xxx_v01.0002.exr" - ] - - This will result in one instance with two representations: - `foo` and `xxx` - """ - do_not_add_review = False - if instance.data.get("review") is False: - self.log.debug("Instance has review explicitly disabled.") - do_not_add_review = True - - aov_filter = { - item["name"]: item["value"] - for item in self.aov_filter - } - if isinstance(instance.data.get("expectedFiles")[0], dict): - instances = create_instances_for_aov( - instance, instance_skeleton_data, - aov_filter, - self.skip_integration_repre_list, - do_not_add_review - ) - else: - representations = prepare_representations( - instance_skeleton_data, - instance.data.get("expectedFiles"), - anatomy, - aov_filter, - self.skip_integration_repre_list, - do_not_add_review, - instance.context, - self - ) - - if "representations" not in instance_skeleton_data.keys(): - instance_skeleton_data["representations"] = [] - - # add representation - instance_skeleton_data["representations"] += representations - instances = [instance_skeleton_data] - - # attach instances to product - if instance.data.get("attachTo"): - instances = attach_instances_to_product( - instance.data.get("attachTo"), instances - ) - - r''' SUBMiT PUBLiSH JOB 2 D34DLiN3 - ____ - ' ' .---. .---. .--. .---. .--..--..--..--. .---. - | | --= \ | . \/ _|/ \| . \ || || \ |/ _| - | JOB | --= / | | || __| .. | | | |;_ || \ || __| - | | |____./ \.__|._||_.|___./|_____|||__|\__|\.___| - ._____. - - ''' - - render_job = instance.data.pop("deadlineSubmissionJob", None) - if not render_job and instance.data.get("tileRendering") is False: - raise AssertionError(("Cannot continue without valid " - "Deadline submission.")) - if not render_job: - import getpass - - render_job = {} - self.log.debug("Faking job data ...") - render_job["Props"] = {} - # Render job doesn't exist because we do not have prior submission. - # We still use data from it so lets fake it. - # - # Batch name reflect original scene name - - if instance.data.get("assemblySubmissionJobs"): - render_job["Props"]["Batch"] = instance.data.get( - "jobBatchName") - else: - batch = os.path.splitext(os.path.basename( - instance.context.data.get("currentFile")))[0] - render_job["Props"]["Batch"] = batch - # User is deadline user - render_job["Props"]["User"] = instance.context.data.get( - "deadlineUser", getpass.getuser()) - - render_job["Props"]["Env"] = { - "FTRACK_API_USER": os.environ.get("FTRACK_API_USER"), - "FTRACK_API_KEY": os.environ.get("FTRACK_API_KEY"), - "FTRACK_SERVER": os.environ.get("FTRACK_SERVER"), - } - - # get default deadline webservice url from deadline module - self.deadline_url = instance.data["deadline"]["url"] - assert self.deadline_url, "Requires Deadline Webservice URL" - - deadline_publish_job_id = \ - self._submit_deadline_post_job(instance, render_job, instances) - - # Inject deadline url to instances to query DL for job id for overrides - for inst in instances: - inst["deadline"] = instance.data["deadline"] - - # publish job file - publish_job = { - "folderPath": instance_skeleton_data["folderPath"], - "frameStart": instance_skeleton_data["frameStart"], - "frameEnd": instance_skeleton_data["frameEnd"], - "fps": instance_skeleton_data["fps"], - "source": instance_skeleton_data["source"], - "user": instance.context.data["user"], - "version": instance.context.data["version"], # workfile version - "intent": instance.context.data.get("intent"), - "comment": instance.context.data.get("comment"), - "job": render_job or None, - "instances": instances - } - - if deadline_publish_job_id: - publish_job["deadline_publish_job_id"] = deadline_publish_job_id - - # add audio to metadata file if available - audio_file = instance.context.data.get("audioFile") - if audio_file and os.path.isfile(audio_file): - publish_job.update({"audio": audio_file}) - - metadata_path, rootless_metadata_path = \ - create_metadata_path(instance, anatomy) - - with open(metadata_path, "w") as f: - json.dump(publish_job, f, indent=4, sort_keys=True) - - def _get_publish_folder(self, anatomy, template_data, - folder_entity, product_name, context, - product_type, version=None): - """ - Extracted logic to pre-calculate real publish folder, which is - calculated in IntegrateNew inside of Deadline process. - This should match logic in: - 'collect_anatomy_instance_data' - to - get correct anatomy, family, version for product name and - 'collect_resources_path' - get publish_path - - Args: - anatomy (ayon_core.pipeline.anatomy.Anatomy): - template_data (dict): pre-calculated collected data for process - folder_entity (dict[str, Any]): Folder entity. - product_name (string): Product name (actually group name - of product) - product_type (string): for current deadline process it's always - 'render' - TODO - for generic use family needs to be dynamically - calculated like IntegrateNew does - version (int): override version from instance if exists - - Returns: - (string): publish folder where rendered and published files will - be stored - based on 'publish' template - """ - - project_name = context.data["projectName"] - host_name = context.data["hostName"] - if not version: - version_entity = None - if folder_entity: - version_entity = ayon_api.get_last_version_by_product_name( - project_name, - product_name, - folder_entity["id"] - ) - - if version_entity: - version = int(version_entity["version"]) + 1 - else: - version = get_versioning_start( - project_name, - host_name, - task_name=template_data["task"]["name"], - task_type=template_data["task"]["type"], - product_type="render", - product_name=product_name, - project_settings=context.data["project_settings"] - ) - - host_name = context.data["hostName"] - task_info = template_data.get("task") or {} - - template_name = publish.get_publish_template_name( - project_name, - host_name, - product_type, - task_info.get("name"), - task_info.get("type"), - ) - - template_data["version"] = version - template_data["subset"] = product_name - template_data["family"] = product_type - template_data["product"] = { - "name": product_name, - "type": product_type, - } - - render_dir_template = anatomy.get_template_item( - "publish", template_name, "directory" - ) - return render_dir_template.format_strict(template_data) - - @classmethod - def get_attribute_defs(cls): - return [ - EnumDef("publishJobState", - label="Publish Job State", - items=["Active", "Suspended"], - default="Active") - ] diff --git a/server_addon/deadline/client/ayon_deadline/plugins/publish/validate_deadline_connection.py b/server_addon/deadline/client/ayon_deadline/plugins/publish/validate_deadline_connection.py deleted file mode 100644 index fd89e3a2a7..0000000000 --- a/server_addon/deadline/client/ayon_deadline/plugins/publish/validate_deadline_connection.py +++ /dev/null @@ -1,52 +0,0 @@ -import pyblish.api - -from ayon_core.pipeline import PublishXmlValidationError - -from ayon_deadline.abstract_submit_deadline import requests_get - - -class ValidateDeadlineConnection(pyblish.api.InstancePlugin): - """Validate Deadline Web Service is running""" - - label = "Validate Deadline Web Service" - order = pyblish.api.ValidatorOrder - hosts = ["maya", "nuke", "aftereffects", "harmony", "fusion"] - families = ["renderlayer", "render", "render.farm"] - - # cache - responses = {} - - def process(self, instance): - if not instance.data.get("farm"): - self.log.debug("Should not be processed on farm, skipping.") - return - - deadline_url = instance.data["deadline"]["url"] - assert deadline_url, "Requires Deadline Webservice URL" - - kwargs = {} - if instance.data["deadline"]["require_authentication"]: - auth = instance.data["deadline"]["auth"] - kwargs["auth"] = auth - - if not auth[0]: - raise PublishXmlValidationError( - self, - "Deadline requires authentication. " - "At least username is required to be set in " - "Site Settings.") - - if deadline_url not in self.responses: - self.responses[deadline_url] = requests_get(deadline_url, **kwargs) - - response = self.responses[deadline_url] - if response.status_code == 401: - raise PublishXmlValidationError( - self, - "Deadline requires authentication. " - "Provided credentials are not working. " - "Please change them in Site Settings") - assert response.ok, "Response must be ok" - assert response.text.startswith("Deadline Web Service "), ( - "Web service did not respond with 'Deadline Web Service'" - ) diff --git a/server_addon/deadline/client/ayon_deadline/plugins/publish/validate_deadline_pools.py b/server_addon/deadline/client/ayon_deadline/plugins/publish/validate_deadline_pools.py deleted file mode 100644 index c7445465c4..0000000000 --- a/server_addon/deadline/client/ayon_deadline/plugins/publish/validate_deadline_pools.py +++ /dev/null @@ -1,84 +0,0 @@ -import pyblish.api - -from ayon_core.pipeline import ( - PublishXmlValidationError, - OptionalPyblishPluginMixin -) - - -class ValidateDeadlinePools(OptionalPyblishPluginMixin, - pyblish.api.InstancePlugin): - """Validate primaryPool and secondaryPool on instance. - - Values are on instance based on value insertion when Creating instance or - by Settings in CollectDeadlinePools. - """ - - label = "Validate Deadline Pools" - order = pyblish.api.ValidatorOrder - families = ["rendering", - "render.farm", - "render.frames_farm", - "renderFarm", - "renderlayer", - "maxrender", - "publish.hou"] - optional = True - - # cache - pools_per_url = {} - - def process(self, instance): - if not self.is_active(instance.data): - return - - if not instance.data.get("farm"): - self.log.debug("Skipping local instance.") - return - - deadline_url = instance.data["deadline"]["url"] - addons_manager = instance.context.data["ayonAddonsManager"] - deadline_addon = addons_manager["deadline"] - pools = self.get_pools( - deadline_addon, - deadline_url, - instance.data["deadline"].get("auth") - ) - - invalid_pools = {} - primary_pool = instance.data.get("primaryPool") - if primary_pool and primary_pool not in pools: - invalid_pools["primary"] = primary_pool - - secondary_pool = instance.data.get("secondaryPool") - if secondary_pool and secondary_pool not in pools: - invalid_pools["secondary"] = secondary_pool - - if invalid_pools: - message = "\n".join( - "{} pool '{}' not available on Deadline".format(key.title(), - pool) - for key, pool in invalid_pools.items() - ) - raise PublishXmlValidationError( - plugin=self, - message=message, - formatting_data={"pools_str": ", ".join(pools)} - ) - - def get_pools(self, deadline_addon, deadline_url, auth): - if deadline_url not in self.pools_per_url: - self.log.debug( - "Querying available pools for Deadline url: {}".format( - deadline_url) - ) - pools = deadline_addon.get_deadline_pools( - deadline_url, auth=auth, log=self.log - ) - # some DL return "none" as a pool name - if "none" not in pools: - pools.append("none") - self.log.info("Available pools: {}".format(pools)) - self.pools_per_url[deadline_url] = pools - - return self.pools_per_url[deadline_url] diff --git a/server_addon/deadline/client/ayon_deadline/plugins/publish/validate_expected_and_rendered_files.py b/server_addon/deadline/client/ayon_deadline/plugins/publish/validate_expected_and_rendered_files.py deleted file mode 100644 index 3fd13cfa10..0000000000 --- a/server_addon/deadline/client/ayon_deadline/plugins/publish/validate_expected_and_rendered_files.py +++ /dev/null @@ -1,256 +0,0 @@ -import os -import requests - -import pyblish.api - -from ayon_core.lib import collect_frames -from ayon_deadline.abstract_submit_deadline import requests_get - - -class ValidateExpectedFiles(pyblish.api.InstancePlugin): - """Compare rendered and expected files""" - - label = "Validate rendered files from Deadline" - order = pyblish.api.ValidatorOrder - families = ["render"] - targets = ["deadline"] - - # check if actual frame range on render job wasn't different - # case when artists wants to render only subset of frames - allow_user_override = True - - def process(self, instance): - """Process all the nodes in the instance""" - - # get dependency jobs ids for retrieving frame list - dependent_job_ids = self._get_dependent_job_ids(instance) - - if not dependent_job_ids: - self.log.warning("No dependent jobs found for instance: {}" - "".format(instance)) - return - - # get list of frames from dependent jobs - frame_list = self._get_dependent_jobs_frames( - instance, dependent_job_ids) - - for repre in instance.data["representations"]: - expected_files = self._get_expected_files(repre) - - staging_dir = repre["stagingDir"] - existing_files = self._get_existing_files(staging_dir) - - if self.allow_user_override: - # We always check for user override because the user might have - # also overridden the Job frame list to be longer than the - # originally submitted frame range - # todo: We should first check if Job frame range was overridden - # at all so we don't unnecessarily override anything - file_name_template, frame_placeholder = \ - self._get_file_name_template_and_placeholder( - expected_files) - - if not file_name_template: - raise RuntimeError("Unable to retrieve file_name template" - "from files: {}".format(expected_files)) - - job_expected_files = self._get_job_expected_files( - file_name_template, - frame_placeholder, - frame_list) - - job_files_diff = job_expected_files.difference(expected_files) - if job_files_diff: - self.log.debug( - "Detected difference in expected output files from " - "Deadline job. Assuming an updated frame list by the " - "user. Difference: {}".format(sorted(job_files_diff)) - ) - - # Update the representation expected files - self.log.info("Update range from actual job range " - "to frame list: {}".format(frame_list)) - # single item files must be string not list - repre["files"] = (sorted(job_expected_files) - if len(job_expected_files) > 1 else - list(job_expected_files)[0]) - - # Update the expected files - expected_files = job_expected_files - - # We don't use set.difference because we do allow other existing - # files to be in the folder that we might not want to use. - missing = expected_files - existing_files - if missing: - raise RuntimeError( - "Missing expected files: {}\n" - "Expected files: {}\n" - "Existing files: {}".format( - sorted(missing), - sorted(expected_files), - sorted(existing_files) - ) - ) - - def _get_dependent_job_ids(self, instance): - """Returns list of dependent job ids from instance metadata.json - - Args: - instance (pyblish.api.Instance): pyblish instance - - Returns: - (list): list of dependent job ids - - """ - dependent_job_ids = [] - - # job_id collected from metadata.json - original_job_id = instance.data["render_job_id"] - - dependent_job_ids_env = os.environ.get("RENDER_JOB_IDS") - if dependent_job_ids_env: - dependent_job_ids = dependent_job_ids_env.split(',') - elif original_job_id: - dependent_job_ids = [original_job_id] - - return dependent_job_ids - - def _get_dependent_jobs_frames(self, instance, dependent_job_ids): - """Returns list of frame ranges from all render job. - - Render job might be re-submitted so job_id in metadata.json could be - invalid. GlobalJobPreload injects current job id to RENDER_JOB_IDS. - - Args: - instance (pyblish.api.Instance): pyblish instance - dependent_job_ids (list): list of dependent job ids - Returns: - (list) - """ - all_frame_lists = [] - - for job_id in dependent_job_ids: - job_info = self._get_job_info(instance, job_id) - frame_list = job_info["Props"].get("Frames") - if frame_list: - all_frame_lists.extend(frame_list.split(',')) - - return all_frame_lists - - def _get_job_expected_files(self, - file_name_template, - frame_placeholder, - frame_list): - """Calculates list of names of expected rendered files. - - Might be different from expected files from submission if user - explicitly and manually changed the frame list on the Deadline job. - - """ - # no frames in file name at all, eg 'renderCompositingMain.withLut.mov' - if not frame_placeholder: - return {file_name_template} - - real_expected_rendered = set() - src_padding_exp = "%0{}d".format(len(frame_placeholder)) - for frames in frame_list: - if '-' not in frames: # single frame - frames = "{}-{}".format(frames, frames) - - start, end = frames.split('-') - for frame in range(int(start), int(end) + 1): - ren_name = file_name_template.replace( - frame_placeholder, src_padding_exp % frame) - real_expected_rendered.add(ren_name) - - return real_expected_rendered - - def _get_file_name_template_and_placeholder(self, files): - """Returns file name with frame replaced with # and this placeholder""" - sources_and_frames = collect_frames(files) - - file_name_template = frame_placeholder = None - for file_name, frame in sources_and_frames.items(): - - # There might be cases where clique was unable to collect - # collections in `collect_frames` - thus we capture that case - if frame is not None: - frame_placeholder = "#" * len(frame) - - file_name_template = os.path.basename( - file_name.replace(frame, frame_placeholder)) - else: - file_name_template = file_name - break - - return file_name_template, frame_placeholder - - def _get_job_info(self, instance, job_id): - """Calls DL for actual job info for 'job_id' - - Might be different than job info saved in metadata.json if user - manually changes job pre/during rendering. - - Args: - instance (pyblish.api.Instance): pyblish instance - job_id (str): Deadline job id - - Returns: - (dict): Job info from Deadline - - """ - deadline_url = instance.data["deadline"]["url"] - assert deadline_url, "Requires Deadline Webservice URL" - - url = "{}/api/jobs?JobID={}".format(deadline_url, job_id) - try: - kwargs = {} - auth = instance.data["deadline"]["auth"] - if auth: - kwargs["auth"] = auth - response = requests_get(url, **kwargs) - except requests.exceptions.ConnectionError: - self.log.error("Deadline is not accessible at " - "{}".format(deadline_url)) - return {} - - if not response.ok: - self.log.error("Submission failed!") - self.log.error(response.status_code) - self.log.error(response.content) - raise RuntimeError(response.text) - - json_content = response.json() - if json_content: - return json_content.pop() - return {} - - def _get_existing_files(self, staging_dir): - """Returns set of existing file names from 'staging_dir'""" - existing_files = set() - for file_name in os.listdir(staging_dir): - existing_files.add(file_name) - return existing_files - - def _get_expected_files(self, repre): - """Returns set of file names in representation['files'] - - The representations are collected from `CollectRenderedFiles` using - the metadata.json file submitted along with the render job. - - Args: - repre (dict): The representation containing 'files' - - Returns: - set: Set of expected file_names in the staging directory. - - """ - expected_files = set() - - files = repre["files"] - if not isinstance(files, list): - files = [files] - - for file_name in files: - expected_files.add(file_name) - return expected_files diff --git a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/Ayon/Ayon.ico b/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/Ayon/Ayon.ico deleted file mode 100644 index aea977a125..0000000000 Binary files a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/Ayon/Ayon.ico and /dev/null differ diff --git a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/Ayon/Ayon.options b/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/Ayon/Ayon.options deleted file mode 100644 index 1fbe1ef299..0000000000 --- a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/Ayon/Ayon.options +++ /dev/null @@ -1,9 +0,0 @@ -[Arguments] -Type=string -Label=Arguments -Category=Python Options -CategoryOrder=0 -Index=1 -Description=The arguments to pass to the script. If no arguments are required, leave this blank. -Required=false -DisableIfBlank=true diff --git a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/Ayon/Ayon.param b/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/Ayon/Ayon.param deleted file mode 100644 index 8ba044ff81..0000000000 --- a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/Ayon/Ayon.param +++ /dev/null @@ -1,35 +0,0 @@ -[About] -Type=label -Label=About -Category=About Plugin -CategoryOrder=-1 -Index=0 -Default=Ayon Plugin for Deadline -Description=Not configurable - -[AyonExecutable] -Type=multilinemultifilename -Label=Ayon Executable -Category=Ayon Executables -CategoryOrder=1 -Index=0 -Default= -Description=The path to the Ayon executable. Enter alternative paths on separate lines. - -[AyonServerUrl] -Type=string -Label=Ayon Server Url -Category=Ayon Credentials -CategoryOrder=2 -Index=0 -Default= -Description=Url to Ayon server - -[AyonApiKey] -Type=password -Label=Ayon API key -Category=Ayon Credentials -CategoryOrder=2 -Index=0 -Default= -Description=API key for service account on Ayon Server diff --git a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/Ayon/Ayon.py b/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/Ayon/Ayon.py deleted file mode 100644 index bb7f932013..0000000000 --- a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/Ayon/Ayon.py +++ /dev/null @@ -1,159 +0,0 @@ -#!/usr/bin/env python3 - -from System.IO import Path -from System.Text.RegularExpressions import Regex - -from Deadline.Plugins import PluginType, DeadlinePlugin -from Deadline.Scripting import ( - StringUtils, - FileUtils, - RepositoryUtils -) - -import re -import os -import platform - -__version__ = "1.0.0" - -###################################################################### -# This is the function that Deadline calls to get an instance of the -# main DeadlinePlugin class. -###################################################################### -def GetDeadlinePlugin(): - return AyonDeadlinePlugin() - - -def CleanupDeadlinePlugin(deadlinePlugin): - deadlinePlugin.Cleanup() - - -class AyonDeadlinePlugin(DeadlinePlugin): - """ - Standalone plugin for publishing from Ayon - - Calls Ayonexecutable 'ayon_console' from first correctly found - file based on plugin configuration. Uses 'publish' command and passes - path to metadata json file, which contains all needed information - for publish process. - """ - def __init__(self): - super().__init__() - self.InitializeProcessCallback += self.InitializeProcess - self.RenderExecutableCallback += self.RenderExecutable - self.RenderArgumentCallback += self.RenderArgument - - def Cleanup(self): - for stdoutHandler in self.StdoutHandlers: - del stdoutHandler.HandleCallback - - del self.InitializeProcessCallback - del self.RenderExecutableCallback - del self.RenderArgumentCallback - - def InitializeProcess(self): - self.LogInfo( - "Initializing process with AYON plugin {}".format(__version__) - ) - self.PluginType = PluginType.Simple - self.StdoutHandling = True - - self.SingleFramesOnly = self.GetBooleanPluginInfoEntryWithDefault( - "SingleFramesOnly", False) - self.LogInfo("Single Frames Only: %s" % self.SingleFramesOnly) - - self.AddStdoutHandlerCallback( - ".*Progress: (\d+)%.*").HandleCallback += self.HandleProgress - - def RenderExecutable(self): - job = self.GetJob() - - # set required env vars for Ayon - # cannot be in InitializeProcess as it is too soon - config = RepositoryUtils.GetPluginConfig("Ayon") - ayon_server_url = ( - job.GetJobEnvironmentKeyValue("AYON_SERVER_URL") or - config.GetConfigEntryWithDefault("AyonServerUrl", "") - ) - ayon_api_key = ( - job.GetJobEnvironmentKeyValue("AYON_API_KEY") or - config.GetConfigEntryWithDefault("AyonApiKey", "") - ) - ayon_bundle_name = job.GetJobEnvironmentKeyValue("AYON_BUNDLE_NAME") - - environment = { - "AYON_SERVER_URL": ayon_server_url, - "AYON_API_KEY": ayon_api_key, - "AYON_BUNDLE_NAME": ayon_bundle_name, - } - - for env, val in environment.items(): - self.SetEnvironmentVariable(env, val) - - exe_list = self.GetConfigEntry("AyonExecutable") - # clean '\ ' for MacOS pasting - if platform.system().lower() == "darwin": - exe_list = exe_list.replace("\\ ", " ") - - expanded_paths = [] - for path in exe_list.split(";"): - if path.startswith("~"): - path = os.path.expanduser(path) - expanded_paths.append(path) - exe = FileUtils.SearchFileList(";".join(expanded_paths)) - - if exe == "": - self.FailRender( - "Ayon executable was not found in the semicolon separated " - "list: \"{}\". The path to the render executable can be " - "configured from the Plugin Configuration in the Deadline " - "Monitor.".format(exe_list) - ) - return exe - - def RenderArgument(self): - arguments = str(self.GetPluginInfoEntryWithDefault("Arguments", "")) - arguments = RepositoryUtils.CheckPathMapping(arguments) - - arguments = re.sub(r"<(?i)STARTFRAME>", str(self.GetStartFrame()), - arguments) - arguments = re.sub(r"<(?i)ENDFRAME>", str(self.GetEndFrame()), - arguments) - arguments = re.sub(r"<(?i)QUOTE>", "\"", arguments) - - arguments = self.ReplacePaddedFrame(arguments, - "<(?i)STARTFRAME%([0-9]+)>", - self.GetStartFrame()) - arguments = self.ReplacePaddedFrame(arguments, - "<(?i)ENDFRAME%([0-9]+)>", - self.GetEndFrame()) - - count = 0 - for filename in self.GetAuxiliaryFilenames(): - localAuxFile = Path.Combine(self.GetJobsDataDirectory(), filename) - arguments = re.sub(r"<(?i)AUXFILE" + str(count) + r">", - localAuxFile.replace("\\", "/"), arguments) - count += 1 - - return arguments - - def ReplacePaddedFrame(self, arguments, pattern, frame): - frameRegex = Regex(pattern) - while True: - frameMatch = frameRegex.Match(arguments) - if not frameMatch.Success: - break - paddingSize = int(frameMatch.Groups[1].Value) - if paddingSize > 0: - padding = StringUtils.ToZeroPaddedString( - frame, paddingSize, False) - else: - padding = str(frame) - arguments = arguments.replace( - frameMatch.Groups[0].Value, padding) - - return arguments - - def HandleProgress(self): - progress = float(self.GetRegexMatch(1)) - self.SetProgress(progress) diff --git a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/CelAction/CelAction.ico b/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/CelAction/CelAction.ico deleted file mode 100644 index 39d61592fe..0000000000 Binary files a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/CelAction/CelAction.ico and /dev/null differ diff --git a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/CelAction/CelAction.param b/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/CelAction/CelAction.param deleted file mode 100644 index 24c59d2005..0000000000 --- a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/CelAction/CelAction.param +++ /dev/null @@ -1,38 +0,0 @@ -[About] -Type=label -Label=About -Category=About Plugin -CategoryOrder=-1 -Index=0 -Default=Celaction Plugin for Deadline -Description=Not configurable - -[ConcurrentTasks] -Type=label -Label=ConcurrentTasks -Category=About Plugin -CategoryOrder=-1 -Index=0 -Default=True -Description=Not configurable - -[Executable] -Type=filename -Label=Executable -Category=Config -CategoryOrder=0 -CategoryIndex=0 -Description=The command executable to run -Required=false -DisableIfBlank=true - -[RenderNameSeparator] -Type=string -Label=RenderNameSeparator -Category=Config -CategoryOrder=0 -CategoryIndex=1 -Description=The separator to use for naming -Required=false -DisableIfBlank=true -Default=. diff --git a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/CelAction/CelAction.py b/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/CelAction/CelAction.py deleted file mode 100644 index 2d0edd3dca..0000000000 --- a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/CelAction/CelAction.py +++ /dev/null @@ -1,122 +0,0 @@ -from System.Text.RegularExpressions import * - -from Deadline.Plugins import * -from Deadline.Scripting import * - -import _winreg - -###################################################################### -# This is the function that Deadline calls to get an instance of the -# main DeadlinePlugin class. -###################################################################### - - -def GetDeadlinePlugin(): - return CelActionPlugin() - - -def CleanupDeadlinePlugin(deadlinePlugin): - deadlinePlugin.Cleanup() - -###################################################################### -# This is the main DeadlinePlugin class for the CelAction plugin. -###################################################################### - - -class CelActionPlugin(DeadlinePlugin): - - def __init__(self): - self.InitializeProcessCallback += self.InitializeProcess - self.RenderExecutableCallback += self.RenderExecutable - self.RenderArgumentCallback += self.RenderArgument - self.StartupDirectoryCallback += self.StartupDirectory - - def Cleanup(self): - for stdoutHandler in self.StdoutHandlers: - del stdoutHandler.HandleCallback - - del self.InitializeProcessCallback - del self.RenderExecutableCallback - del self.RenderArgumentCallback - del self.StartupDirectoryCallback - - def GetCelActionRegistryKey(self): - # Modify registry for frame separation - path = r'Software\CelAction\CelAction2D\User Settings' - _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, path) - regKey = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, path, 0, - _winreg.KEY_ALL_ACCESS) - return regKey - - def GetSeparatorValue(self, regKey): - useSeparator, _ = _winreg.QueryValueEx( - regKey, 'RenderNameUseSeparator') - separator, _ = _winreg.QueryValueEx(regKey, 'RenderNameSeparator') - - return useSeparator, separator - - def SetSeparatorValue(self, regKey, useSeparator, separator): - _winreg.SetValueEx(regKey, 'RenderNameUseSeparator', - 0, _winreg.REG_DWORD, useSeparator) - _winreg.SetValueEx(regKey, 'RenderNameSeparator', - 0, _winreg.REG_SZ, separator) - - def InitializeProcess(self): - # Set the plugin specific settings. - self.SingleFramesOnly = False - - # Set the process specific settings. - self.StdoutHandling = True - self.PopupHandling = True - - # Ignore 'celaction' Pop-up dialog - self.AddPopupIgnorer(".*Rendering.*") - self.AddPopupIgnorer(".*AutoRender.*") - - # Ignore 'celaction' Pop-up dialog - self.AddPopupIgnorer(".*Wait.*") - - # Ignore 'celaction' Pop-up dialog - self.AddPopupIgnorer(".*Timeline Scrub.*") - - celActionRegKey = self.GetCelActionRegistryKey() - - self.SetSeparatorValue(celActionRegKey, 1, self.GetConfigEntryWithDefault( - "RenderNameSeparator", ".").strip()) - - def RenderExecutable(self): - return RepositoryUtils.CheckPathMapping(self.GetConfigEntry("Executable").strip()) - - def RenderArgument(self): - arguments = RepositoryUtils.CheckPathMapping( - self.GetPluginInfoEntry("Arguments").strip()) - arguments = arguments.replace( - "", str(self.GetStartFrame())) - arguments = arguments.replace("", str(self.GetEndFrame())) - arguments = self.ReplacePaddedFrame( - arguments, "", self.GetStartFrame()) - arguments = self.ReplacePaddedFrame( - arguments, "", self.GetEndFrame()) - arguments = arguments.replace("", "\"") - return arguments - - def StartupDirectory(self): - return self.GetPluginInfoEntryWithDefault("StartupDirectory", "").strip() - - def ReplacePaddedFrame(self, arguments, pattern, frame): - frameRegex = Regex(pattern) - while True: - frameMatch = frameRegex.Match(arguments) - if frameMatch.Success: - paddingSize = int(frameMatch.Groups[1].Value) - if paddingSize > 0: - padding = StringUtils.ToZeroPaddedString( - frame, paddingSize, False) - else: - padding = str(frame) - arguments = arguments.replace( - frameMatch.Groups[0].Value, padding) - else: - break - - return arguments diff --git a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/GlobalJobPreLoad.py b/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/GlobalJobPreLoad.py deleted file mode 100644 index dbd1798608..0000000000 --- a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/GlobalJobPreLoad.py +++ /dev/null @@ -1,662 +0,0 @@ -# /usr/bin/env python3 -# -*- coding: utf-8 -*- -import os -import tempfile -from datetime import datetime -import subprocess -import json -import platform -import uuid -import re -from Deadline.Scripting import ( - RepositoryUtils, - FileUtils, - DirectoryUtils, -) -__version__ = "1.1.1" -VERSION_REGEX = re.compile( - r"(?P0|[1-9]\d*)" - r"\.(?P0|[1-9]\d*)" - r"\.(?P0|[1-9]\d*)" - r"(?:-(?P[a-zA-Z\d\-.]*))?" - r"(?:\+(?P[a-zA-Z\d\-.]*))?" -) - - -class OpenPypeVersion: - """Fake semver version class for OpenPype version purposes. - - The version - """ - def __init__(self, major, minor, patch, prerelease, origin=None): - self.major = major - self.minor = minor - self.patch = patch - self.prerelease = prerelease - - is_valid = True - if major is None or minor is None or patch is None: - is_valid = False - self.is_valid = is_valid - - if origin is None: - base = "{}.{}.{}".format(str(major), str(minor), str(patch)) - if not prerelease: - origin = base - else: - origin = "{}-{}".format(base, str(prerelease)) - - self.origin = origin - - @classmethod - def from_string(cls, version): - """Create an object of version from string. - - Args: - version (str): Version as a string. - - Returns: - Union[OpenPypeVersion, None]: Version object if input is nonempty - string otherwise None. - """ - - if not version: - return None - valid_parts = VERSION_REGEX.findall(version) - if len(valid_parts) != 1: - # Return invalid version with filled 'origin' attribute - return cls(None, None, None, None, origin=str(version)) - - # Unpack found version - major, minor, patch, pre, post = valid_parts[0] - prerelease = pre - # Post release is not important anymore and should be considered as - # part of prerelease - # - comparison is implemented to find suitable build and builds should - # never contain prerelease part so "not proper" parsing is - # acceptable for this use case. - if post: - prerelease = "{}+{}".format(pre, post) - - return cls( - int(major), int(minor), int(patch), prerelease, origin=version - ) - - def has_compatible_release(self, other): - """Version has compatible release as other version. - - Both major and minor versions must be exactly the same. In that case - a build can be considered as release compatible with any version. - - Args: - other (OpenPypeVersion): Other version. - - Returns: - bool: Version is release compatible with other version. - """ - - if self.is_valid and other.is_valid: - return self.major == other.major and self.minor == other.minor - return False - - def __bool__(self): - return self.is_valid - - def __repr__(self): - return "<{} {}>".format(self.__class__.__name__, self.origin) - - def __eq__(self, other): - if not isinstance(other, self.__class__): - return self.origin == other - return self.origin == other.origin - - def __lt__(self, other): - if not isinstance(other, self.__class__): - return None - - if not self.is_valid: - return True - - if not other.is_valid: - return False - - if self.origin == other.origin: - return None - - same_major = self.major == other.major - if not same_major: - return self.major < other.major - - same_minor = self.minor == other.minor - if not same_minor: - return self.minor < other.minor - - same_patch = self.patch == other.patch - if not same_patch: - return self.patch < other.patch - - if not self.prerelease: - return False - - if not other.prerelease: - return True - - pres = [self.prerelease, other.prerelease] - pres.sort() - return pres[0] == self.prerelease - - -def get_openpype_version_from_path(path, build=True): - """Get OpenPype version from provided path. - path (str): Path to scan. - build (bool, optional): Get only builds, not sources - - Returns: - Union[OpenPypeVersion, None]: version of OpenPype if found. - """ - - # fix path for application bundle on macos - if platform.system().lower() == "darwin": - path = os.path.join(path, "MacOS") - - version_file = os.path.join(path, "openpype", "version.py") - if not os.path.isfile(version_file): - return None - - # skip if the version is not build - exe = os.path.join(path, "openpype_console.exe") - if platform.system().lower() in ["linux", "darwin"]: - exe = os.path.join(path, "openpype_console") - - # if only builds are requested - if build and not os.path.isfile(exe): # noqa: E501 - print(" ! path is not a build: {}".format(path)) - return None - - version = {} - with open(version_file, "r") as vf: - exec(vf.read(), version) - - version_str = version.get("__version__") - if version_str: - return OpenPypeVersion.from_string(version_str) - return None - - -def get_openpype_executable(): - """Return OpenPype Executable from Event Plug-in Settings""" - config = RepositoryUtils.GetPluginConfig("OpenPype") - exe_list = config.GetConfigEntryWithDefault("OpenPypeExecutable", "") - dir_list = config.GetConfigEntryWithDefault( - "OpenPypeInstallationDirs", "") - - # clean '\ ' for MacOS pasting - if platform.system().lower() == "darwin": - exe_list = exe_list.replace("\\ ", " ") - dir_list = dir_list.replace("\\ ", " ") - return exe_list, dir_list - - -def get_openpype_versions(dir_list): - print(">>> Getting OpenPype executable ...") - openpype_versions = [] - - # special case of multiple install dirs - for dir_list in dir_list.split(","): - install_dir = DirectoryUtils.SearchDirectoryList(dir_list) - if install_dir: - print("--- Looking for OpenPype at: {}".format(install_dir)) - sub_dirs = [ - f.path for f in os.scandir(install_dir) - if f.is_dir() - ] - for subdir in sub_dirs: - version = get_openpype_version_from_path(subdir) - if not version: - continue - print(" - found: {} - {}".format(version, subdir)) - openpype_versions.append((version, subdir)) - return openpype_versions - - -def get_requested_openpype_executable( - exe, dir_list, requested_version -): - requested_version_obj = OpenPypeVersion.from_string(requested_version) - if not requested_version_obj: - print(( - ">>> Requested version '{}' does not match version regex '{}'" - ).format(requested_version, VERSION_REGEX)) - return None - - print(( - ">>> Scanning for compatible requested version {}" - ).format(requested_version)) - openpype_versions = get_openpype_versions(dir_list) - if not openpype_versions: - return None - - # if looking for requested compatible version, - # add the implicitly specified to the list too. - if exe: - exe_dir = os.path.dirname(exe) - print("Looking for OpenPype at: {}".format(exe_dir)) - version = get_openpype_version_from_path(exe_dir) - if version: - print(" - found: {} - {}".format(version, exe_dir)) - openpype_versions.append((version, exe_dir)) - - matching_item = None - compatible_versions = [] - for version_item in openpype_versions: - version, version_dir = version_item - if requested_version_obj.has_compatible_release(version): - compatible_versions.append(version_item) - if version == requested_version_obj: - # Store version item if version match exactly - # - break if is found matching version - matching_item = version_item - break - - if not compatible_versions: - return None - - compatible_versions.sort(key=lambda item: item[0]) - if matching_item: - version, version_dir = matching_item - print(( - "*** Found exact match build version {} in {}" - ).format(version_dir, version)) - - else: - version, version_dir = compatible_versions[-1] - - print(( - "*** Latest compatible version found is {} in {}" - ).format(version_dir, version)) - - # create list of executables for different platform and let - # Deadline decide. - exe_list = [ - os.path.join(version_dir, "openpype_console.exe"), - os.path.join(version_dir, "openpype_console"), - os.path.join(version_dir, "MacOS", "openpype_console") - ] - return FileUtils.SearchFileList(";".join(exe_list)) - - -def inject_openpype_environment(deadlinePlugin): - """ Pull env vars from OpenPype and push them to rendering process. - - Used for correct paths, configuration from OpenPype etc. - """ - job = deadlinePlugin.GetJob() - - print(">>> Injecting OpenPype environments ...") - try: - exe_list, dir_list = get_openpype_executable() - exe = FileUtils.SearchFileList(exe_list) - - requested_version = job.GetJobEnvironmentKeyValue("OPENPYPE_VERSION") - if requested_version: - exe = get_requested_openpype_executable( - exe, dir_list, requested_version - ) - if exe is None: - raise RuntimeError(( - "Cannot find compatible version available for version {}" - " requested by the job. Please add it through plugin" - " configuration in Deadline or install it to configured" - " directory." - ).format(requested_version)) - - if not exe: - raise RuntimeError(( - "OpenPype executable was not found in the semicolon " - "separated list \"{}\"." - "The path to the render executable can be configured" - " from the Plugin Configuration in the Deadline Monitor." - ).format(";".join(exe_list))) - - print("--- OpenPype executable: {}".format(exe)) - - # tempfile.TemporaryFile cannot be used because of locking - temp_file_name = "{}_{}.json".format( - datetime.utcnow().strftime("%Y%m%d%H%M%S%f"), - str(uuid.uuid1()) - ) - export_url = os.path.join(tempfile.gettempdir(), temp_file_name) - print(">>> Temporary path: {}".format(export_url)) - - args = [ - "--headless", - "extractenvironments", - export_url - ] - - add_kwargs = { - "project": job.GetJobEnvironmentKeyValue("AVALON_PROJECT"), - "asset": job.GetJobEnvironmentKeyValue("AVALON_ASSET"), - "task": job.GetJobEnvironmentKeyValue("AVALON_TASK"), - "app": job.GetJobEnvironmentKeyValue("AVALON_APP_NAME"), - "envgroup": "farm" - } - - # use legacy IS_TEST env var to mark automatic tests for OP - if job.GetJobEnvironmentKeyValue("IS_TEST"): - args.append("--automatic-tests") - - if all(add_kwargs.values()): - for key, value in add_kwargs.items(): - args.extend(["--{}".format(key), value]) - else: - raise RuntimeError(( - "Missing required env vars: AVALON_PROJECT, AVALON_ASSET," - " AVALON_TASK, AVALON_APP_NAME" - )) - - openpype_mongo = job.GetJobEnvironmentKeyValue("OPENPYPE_MONGO") - if openpype_mongo: - # inject env var for OP extractenvironments - # SetEnvironmentVariable is important, not SetProcessEnv... - deadlinePlugin.SetEnvironmentVariable("OPENPYPE_MONGO", - openpype_mongo) - - if not os.environ.get("OPENPYPE_MONGO"): - print(">>> Missing OPENPYPE_MONGO env var, process won't work") - - os.environ["AVALON_TIMEOUT"] = "5000" - - args_str = subprocess.list2cmdline(args) - print(">>> Executing: {} {}".format(exe, args_str)) - process_exitcode = deadlinePlugin.RunProcess( - exe, args_str, os.path.dirname(exe), -1 - ) - - if process_exitcode != 0: - raise RuntimeError( - "Failed to run OpenPype process to extract environments." - ) - - print(">>> Loading file ...") - with open(export_url) as fp: - contents = json.load(fp) - - for key, value in contents.items(): - deadlinePlugin.SetProcessEnvironmentVariable(key, value) - - if "PATH" in contents: - # Set os.environ[PATH] so studio settings' path entries - # can be used to define search path for executables. - print(f">>> Setting 'PATH' Environment to: {contents['PATH']}") - os.environ["PATH"] = contents["PATH"] - - script_url = job.GetJobPluginInfoKeyValue("ScriptFilename") - if script_url: - script_url = script_url.format(**contents).replace("\\", "/") - print(">>> Setting script path {}".format(script_url)) - job.SetJobPluginInfoKeyValue("ScriptFilename", script_url) - - print(">>> Removing temporary file") - os.remove(export_url) - - print(">> Injection end.") - except Exception as e: - if hasattr(e, "output"): - print(">>> Exception {}".format(e.output)) - import traceback - print(traceback.format_exc()) - print("!!! Injection failed.") - RepositoryUtils.FailJob(job) - raise - - -def inject_ayon_environment(deadlinePlugin): - """ Pull env vars from AYON and push them to rendering process. - - Used for correct paths, configuration from AYON etc. - """ - job = deadlinePlugin.GetJob() - - print(">>> Injecting AYON environments ...") - try: - exe_list = get_ayon_executable() - exe = FileUtils.SearchFileList(exe_list) - - if not exe: - raise RuntimeError(( - "Ayon executable was not found in the semicolon " - "separated list \"{}\"." - "The path to the render executable can be configured" - " from the Plugin Configuration in the Deadline Monitor." - ).format(exe_list)) - - print("--- Ayon executable: {}".format(exe)) - - ayon_bundle_name = job.GetJobEnvironmentKeyValue("AYON_BUNDLE_NAME") - if not ayon_bundle_name: - raise RuntimeError( - "Missing env var in job properties AYON_BUNDLE_NAME" - ) - - config = RepositoryUtils.GetPluginConfig("Ayon") - ayon_server_url = ( - job.GetJobEnvironmentKeyValue("AYON_SERVER_URL") or - config.GetConfigEntryWithDefault("AyonServerUrl", "") - ) - ayon_api_key = ( - job.GetJobEnvironmentKeyValue("AYON_API_KEY") or - config.GetConfigEntryWithDefault("AyonApiKey", "") - ) - - if not all([ayon_server_url, ayon_api_key]): - raise RuntimeError(( - "Missing required values for server url and api key. " - "Please fill in Ayon Deadline plugin or provide by " - "AYON_SERVER_URL and AYON_API_KEY" - )) - - # tempfile.TemporaryFile cannot be used because of locking - temp_file_name = "{}_{}.json".format( - datetime.utcnow().strftime("%Y%m%d%H%M%S%f"), - str(uuid.uuid1()) - ) - export_url = os.path.join(tempfile.gettempdir(), temp_file_name) - print(">>> Temporary path: {}".format(export_url)) - - add_kwargs = { - "envgroup": "farm", - } - # Support backwards compatible keys - for key, env_keys in ( - ("project", ["AYON_PROJECT_NAME", "AVALON_PROJECT"]), - ("folder", ["AYON_FOLDER_PATH", "AVALON_ASSET"]), - ("task", ["AYON_TASK_NAME", "AVALON_TASK"]), - ("app", ["AYON_APP_NAME", "AVALON_APP_NAME"]), - ): - value = "" - for env_key in env_keys: - value = job.GetJobEnvironmentKeyValue(env_key) - if value: - break - add_kwargs[key] = value - - if not all(add_kwargs.values()): - raise RuntimeError(( - "Missing required env vars: AYON_PROJECT_NAME," - " AYON_FOLDER_PATH, AYON_TASK_NAME, AYON_APP_NAME" - )) - - # Use applications addon arguments - # TODO validate if applications addon should be used - args = [ - "--headless", - "addon", - "applications", - "extractenvironments", - export_url - ] - # Backwards compatibility for older versions - legacy_args = [ - "--headless", - "extractenvironments", - export_url - ] - - for key, value in add_kwargs.items(): - args.extend(["--{}".format(key), value]) - # Legacy arguments expect '--asset' instead of '--folder' - if key == "folder": - key = "asset" - legacy_args.extend(["--{}".format(key), value]) - - environment = { - "AYON_SERVER_URL": ayon_server_url, - "AYON_API_KEY": ayon_api_key, - "AYON_BUNDLE_NAME": ayon_bundle_name, - } - - automatic_tests = job.GetJobEnvironmentKeyValue("AYON_IN_TESTS") - if automatic_tests: - environment["AYON_IN_TESTS"] = automatic_tests - for env, val in environment.items(): - # Add the env var for the Render Plugin that is about to render - deadlinePlugin.SetEnvironmentVariable(env, val) - # Add the env var for current calls to `DeadlinePlugin.RunProcess` - deadlinePlugin.SetProcessEnvironmentVariable(env, val) - - args_str = subprocess.list2cmdline(args) - print(">>> Executing: {} {}".format(exe, args_str)) - process_exitcode = deadlinePlugin.RunProcess( - exe, args_str, os.path.dirname(exe), -1 - ) - - if process_exitcode != 0: - print( - "Failed to run AYON process to extract environments. Trying" - " to use legacy arguments." - ) - legacy_args_str = subprocess.list2cmdline(legacy_args) - process_exitcode = deadlinePlugin.RunProcess( - exe, legacy_args_str, os.path.dirname(exe), -1 - ) - if process_exitcode != 0: - raise RuntimeError( - "Failed to run AYON process to extract environments." - ) - - print(">>> Loading file ...") - with open(export_url) as fp: - contents = json.load(fp) - - for key, value in contents.items(): - deadlinePlugin.SetProcessEnvironmentVariable(key, value) - - if "PATH" in contents: - # Set os.environ[PATH] so studio settings' path entries - # can be used to define search path for executables. - print(f">>> Setting 'PATH' Environment to: {contents['PATH']}") - os.environ["PATH"] = contents["PATH"] - - script_url = job.GetJobPluginInfoKeyValue("ScriptFilename") - if script_url: - script_url = script_url.format(**contents).replace("\\", "/") - print(">>> Setting script path {}".format(script_url)) - job.SetJobPluginInfoKeyValue("ScriptFilename", script_url) - - print(">>> Removing temporary file") - os.remove(export_url) - - print(">> Injection end.") - except Exception as e: - if hasattr(e, "output"): - print(">>> Exception {}".format(e.output)) - import traceback - print(traceback.format_exc()) - print("!!! Injection failed.") - RepositoryUtils.FailJob(job) - raise - - -def get_ayon_executable(): - """Return AYON Executable from Event Plug-in Settings - - Returns: - list[str]: AYON executable paths. - - Raises: - RuntimeError: When no path configured at all. - - """ - config = RepositoryUtils.GetPluginConfig("Ayon") - exe_list = config.GetConfigEntryWithDefault("AyonExecutable", "") - - if not exe_list: - raise RuntimeError( - "Path to AYON executable not configured." - "Please set it in Ayon Deadline Plugin." - ) - - # clean '\ ' for MacOS pasting - if platform.system().lower() == "darwin": - exe_list = exe_list.replace("\\ ", " ") - - # Expand user paths - expanded_paths = [] - for path in exe_list.split(";"): - if path.startswith("~"): - path = os.path.expanduser(path) - expanded_paths.append(path) - return ";".join(expanded_paths) - - -def inject_render_job_id(deadlinePlugin): - """Inject dependency ids to publish process as env var for validation.""" - print(">>> Injecting render job id ...") - job = deadlinePlugin.GetJob() - - dependency_ids = job.JobDependencyIDs - print(">>> Dependency IDs: {}".format(dependency_ids)) - render_job_ids = ",".join(dependency_ids) - - deadlinePlugin.SetProcessEnvironmentVariable( - "RENDER_JOB_IDS", render_job_ids - ) - print(">>> Injection end.") - - -def __main__(deadlinePlugin): - print("*** GlobalJobPreload {} start ...".format(__version__)) - print(">>> Getting job ...") - job = deadlinePlugin.GetJob() - - openpype_render_job = job.GetJobEnvironmentKeyValue( - "OPENPYPE_RENDER_JOB") - openpype_publish_job = job.GetJobEnvironmentKeyValue( - "OPENPYPE_PUBLISH_JOB") - openpype_remote_job = job.GetJobEnvironmentKeyValue( - "OPENPYPE_REMOTE_PUBLISH") - - if openpype_publish_job == "1" and openpype_render_job == "1": - raise RuntimeError( - "Misconfiguration. Job couldn't be both render and publish." - ) - - if openpype_publish_job == "1": - inject_render_job_id(deadlinePlugin) - if openpype_render_job == "1" or openpype_remote_job == "1": - inject_openpype_environment(deadlinePlugin) - - ayon_render_job = job.GetJobEnvironmentKeyValue("AYON_RENDER_JOB") - ayon_publish_job = job.GetJobEnvironmentKeyValue("AYON_PUBLISH_JOB") - ayon_remote_job = job.GetJobEnvironmentKeyValue("AYON_REMOTE_PUBLISH") - - if ayon_publish_job == "1" and ayon_render_job == "1": - raise RuntimeError( - "Misconfiguration. Job couldn't be both render and publish." - ) - - if ayon_publish_job == "1": - inject_render_job_id(deadlinePlugin) - if ayon_render_job == "1" or ayon_remote_job == "1": - inject_ayon_environment(deadlinePlugin) diff --git a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/HarmonyAYON/HarmonyAYON.ico b/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/HarmonyAYON/HarmonyAYON.ico deleted file mode 100644 index cf6f6bfcfa..0000000000 Binary files a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/HarmonyAYON/HarmonyAYON.ico and /dev/null differ diff --git a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/HarmonyAYON/HarmonyAYON.options b/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/HarmonyAYON/HarmonyAYON.options deleted file mode 100644 index efd44b4f94..0000000000 --- a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/HarmonyAYON/HarmonyAYON.options +++ /dev/null @@ -1,532 +0,0 @@ -[SceneFile] -Type=filename -Label=Scene Filename -Category=Global Settings -CategoryOrder=0 -Index=0 -Description=The scene filename as it exists on the network. -Required=false -DisableIfBlank=true - -[Environment] -Type=filename -Label=Scene Environment -Category=Global Settings -CategoryOrder=0 -Index=1 -Description=The Environment for the scene. -Required=false -DisableIfBlank=true - -[Job] -Type=filename -Label=Scene Job -Category=Global Settings -CategoryOrder=0 -Index=2 -Description=The Job that the scene belongs to. -Required=false -DisableIfBlank=true - -[SceneName] -Type=filename -Label=Scene Name -Category=Global Settings -CategoryOrder=0 -Index=3 -Description=The name of the scene to render -Required=false -DisableIfBlank=true - -[SceneVersion] -Type=filename -Label=Scene Version -Category=Global Settings -CategoryOrder=0 -Index=4 -Description=The version of the scene to render. -Required=false -DisableIfBlank=true - -[Version] -Type=enum -Values=10;11;12 -Label=Harmony Version -Category=Global Settings -CategoryOrder=0 -Index=5 -Description=The version of Harmony to use. -Required=false -DisableIfBlank=true - -[IsDatabase] -Type=Boolean -Label=Is Database Scene -Category=Global Settings -CategoryOrder=0 -Index=6 -Description=Whether or not the scene is in the database or not -Required=false -DisableIfBlank=true - -[Camera] -Type=string -Label=Camera -Category=Render Settings -CategoryOrder=1 -Index=0 -Description=Specifies the camera to use for rendering images. If Blank, the scene will be rendered with the current Camera. -Required=false -DisableIfBlank=true - -[UsingResPreset] -Type=Boolean -Label=Use Resolution Preset -Category=Render Settings -CategoryOrder=1 -Index=1 -Description=Whether or not you are using a resolution preset. -Required=false -DisableIfBlank=true - -[ResolutionName] -Type=enum -Values=HDTV_1080p24;HDTV_1080p25;HDTV_720p24;4K_UHD;8K_UHD;DCI_2K;DCI_4K;film-2K;film-4K;film-1.33_H;film-1.66_H;film-1.66_V;Cineon;NTSC;PAL;2160p;1440p;1080p;720p;480p;360p;240p;low;Web_Video;Game_512;Game_512_Ortho;WebCC_Preview;Custom -Label=Resolution Preset -Category=Render Settings -CategoryOrder=1 -Index=2 -Description=The resolution preset to use. -Required=true -Default=HDTV_1080p24 - -[PresetName] -Type=string -Label=Preset Name -Category=Render Settings -CategoryOrder=1 -Index=3 -Description=Specify the custom resolution name. -Required=true -Default= - -[ResolutionX] -Type=integer -Label=Resolution X -Minimum=0 -Maximum=1000000 -Category=Render Settings -CategoryOrder=1 -Index=4 -Description=Specifies the width of the rendered images. If 0, then the current resolution and Field of view will be used. -Required=true -Default=1920 - -[ResolutionY] -Type=integer -Label=Resolution Y -Minimum=0 -Maximum=1000000 -Category=Render Settings -CategoryOrder=1 -Index=5 -Description=Specifies the height of the rendered images. If 0, then the current resolution and Field of view will be used. -Required=true -Default=1080 - -[FieldOfView] -Type=float -Label=Field Of View -Minimum=0 -Maximum=89 -DecimalPlaces=2 -Category=Render Settings -CategoryOrder=1 -Index=6 -Description=Specifies the field of view of the rendered images. If 0, then the current resolution and Field of view will be used. -Required=true -Default=41.11 - -[Output0Node] -Type=string -Label=Render Node 0 Name -Category=Output Settings -CategoryOrder=2 -Index=0 -Description=The name of the render node. -Required=false -DisableIfBlank=true - -[Output0Type] -Type=enum -Values=Image;Movie -Label=Render Node 0 Type -Category=Output Settings -CategoryOrder=2 -Index=1 -Description=The type of output that the render node is producing. -Required=false -DisableIfBlank=true - -[Output0Path] -Type=string -Label=Render Node 0 Path -Category=Output Settings -CategoryOrder=2 -Index=2 -Description=The output path and file name of the output files. -Required=false -DisableIfBlank=true - -[Output0LeadingZero] -Type=integer -Label=Render Node 0 Leading Zeroes -Category=Output Settings -CategoryOrder=2 -Minimum=0 -Maximum=5 -Index=3 -Description=The number of leading zeroes for a 1 digit frame number. (1 less then the full padded length) -Required=false -DisableIfBlank=true - -[Output0Format] -Type=string -Label=Render Node 0 Format -Category=Output Settings -CategoryOrder=2 -Index=4 -Description=The format for the rendered output images. -Required=false -DisableIfBlank=true - -[Output0StartFrame] -Type=integer -Label=Render Node 0 Start Frame -Category=Output Settings -CategoryOrder=2 -Minimum=1 -Index=5 -Description=The frame that will correspond to frame one when numbering. If this value is not 1 then the monitor's job output features will not work properly. -Required=false -DisableIfBlank=true - -[Output1Node] -Type=string -Label=Render Node 1 Name -Category=Output Settings -CategoryOrder=2 -Index=6 -Description=The name of the render node. -Required=false -DisableIfBlank=true - -[Output1Type] -Type=enum -Values=Image;Movie -Label=Render Node 1 Type -Category=Output Settings -CategoryOrder=2 -Index=7 -Description=The type of output that the render node is producing. -Required=false -DisableIfBlank=true - -[Output1Path] -Type=string -Label=Render Node 1 Path -Category=Output Settings -CategoryOrder=2 -Index=8 -Description=The output path and file name of the output files. -Required=false -DisableIfBlank=true - -[Output1LeadingZero] -Type=integer -Label=Render Node 1 Leading Zeroes -Category=Output Settings -CategoryOrder=2 -Minimum=0 -Maximum=5 -Index=9 -Description=The number of leading zeroes for a 1 digit frame number. (1 less then the full padded length) -Required=false -DisableIfBlank=true - -[Output1Format] -Type=string -Label=Render Node 1 Format -Category=Output Settings -CategoryOrder=2 -Index=10 -Description=The format for the rendered output images. -Required=false -DisableIfBlank=true - -[Output1StartFrame] -Type=integer -Label=Render Node 1 Start Frame -Category=Output Settings -CategoryOrder=2 -Minimum=1 -Index=11 -Description=The frame that will correspond to frame one when numbering. If this value is not 1 then the monitor's job output features will not work properly. -Required=false -DisableIfBlank=true - -[Output2Node] -Type=string -Label=Render Node 2 Name -Category=Output Settings -CategoryOrder=2 -Index=12 -Description=The name of the render node. -Required=false -DisableIfBlank=true - -[Output2Type] -Type=enum -Values=Image;Movie -Label=Render Node 2 Type -Category=Output Settings -CategoryOrder=2 -Index=13 -Description=The type of output that the render node is producing. -Required=false -DisableIfBlank=true - -[Output2Path] -Type=string -Label=Render Node 2 Path -Category=Output Settings -CategoryOrder=2 -Index=14 -Description=The output path and file name of the output files. -Required=false -DisableIfBlank=true - -[Output2LeadingZero] -Type=integer -Label=Render Node 2 Leading Zeroes -Category=Output Settings -CategoryOrder=2 -Minimum=0 -Maximum=5 -Index=15 -Description=The number of leading zeroes for a 1 digit frame number. (1 less then the full padded length) -Required=false -DisableIfBlank=true - -[Output2Format] -Type=string -Label=Render Node 2 Format -Category=Output Settings -CategoryOrder=2 -Index=16 -Description=The format for the rendered output images. -Required=false -DisableIfBlank=true - -[Output2StartFrame] -Type=integer -Label=Render Node 2 Start Frame -Category=Output Settings -CategoryOrder=2 -Minimum=1 -Index=17 -Description=The frame that will correspond to frame one when numbering. If this value is not 1 then the monitor's job output features will not work properly. -Required=false -DisableIfBlank=true - -[Output3Node] -Type=string -Label=Render Node 3 Name -Category=Output Settings -CategoryOrder=2 -Index=18 -Description=The name of the render node. -Required=false -DisableIfBlank=true - -[Output3Type] -Type=enum -Values=Image;Movie -Label=Render Node 3 Type -Category=Output Settings -CategoryOrder=2 -Index=19 -Description=The type of output that the render node is producing. -Required=false -DisableIfBlank=true - -[Output3Path] -Type=string -Label=Render Node 3 Path -Category=Output Settings -CategoryOrder=2 -Index=20 -Description=The output path and file name of the output files. -Required=false -DisableIfBlank=true - -[Output3LeadingZero] -Type=integer -Label=Render Node 3 Leading Zeroes -Category=Output Settings -CategoryOrder=2 -Minimum=0 -Maximum=5 -Index=21 -Description=The number of leading zeroes for a 1 digit frame number. (1 less then the full padded length) -Required=false -DisableIfBlank=true - -[Output3Format] -Type=string -Label=Render Node 3 Format -Category=Output Settings -CategoryOrder=2 -Index=22 -Description=The format for the rendered output images. -Required=false -DisableIfBlank=true - -[Output3StartFrame] -Type=integer -Label=Render Node 3 Start Frame -Category=Output Settings -CategoryOrder=2 -Minimum=1 -Index=23 -Description=The frame that will correspond to frame one when numbering. If this value is not 1 then the monitor's job output features will not work properly. -Required=false -DisableIfBlank=true - -[Output4Node] -Type=string -Label=Render Node 4 Name -Category=Output Settings -CategoryOrder=2 -Index=24 -Description=The name of the render node. -Required=false -DisableIfBlank=true - -[Output4Type] -Type=enum -Values=Image;Movie -Label=Render Node 4 Type -Category=Output Settings -CategoryOrder=2 -Index=25 -Description=The type of output that the render node is producing. -Required=false -DisableIfBlank=true - -[Output4Path] -Type=string -Label=Render Node 4 Path -Category=Output Settings -CategoryOrder=2 -Index=26 -Description=The output path and file name of the output files. -Required=false -DisableIfBlank=true - -[Output4LeadingZero] -Type=integer -Label=Render Node 4 Leading Zeroes -Category=Output Settings -CategoryOrder=2 -Minimum=0 -Maximum=5 -Index=27 -Description=The number of leading zeroes for a 1 digit frame number. (1 less then the full padded length) -Required=false -DisableIfBlank=true - -[Output4Format] -Type=string -Label=Render Node 4 Format -Category=Output Settings -CategoryOrder=2 -Index=28 -Description=The format for the rendered output images. -Required=false -DisableIfBlank=true - -[Output4StartFrame] -Type=integer -Label=Render Node 4 Start Frame -Category=Output Settings -CategoryOrder=2 -Minimum=1 -Index=29 -Description=The frame that will correspond to frame one when numbering. If this value is not 1 then the monitor's job output features will not work properly. -Required=false -DisableIfBlank=true - -[Output5Node] -Type=string -Label=Render Node 5 Name -Category=Output Settings -CategoryOrder=2 -Index=30 -Description=The name of the render node. -Required=false -DisableIfBlank=true - -[Output5Type] -Type=enum -Values=Image;Movie -Label=Render Node 5 Type -Category=Output Settings -CategoryOrder=2 -Index=31 -Description=The type of output that the render node is producing. -Required=false -DisableIfBlank=true - -[Output5Path] -Type=string -Label=Render Node 5 Path -Category=Output Settings -CategoryOrder=2 -Index=32 -Description=The output path and file name of the output files. -Required=false -DisableIfBlank=true - -[Output5LeadingZero] -Type=integer -Label=Render Node 5 Leading Zeroes -Category=Output Settings -CategoryOrder=2 -Minimum=0 -Maximum=5 -Index=33 -Description=The number of leading zeroes for a 1 digit frame number. (1 less then the full padded length) -Required=false -DisableIfBlank=true - -[Output5Format] -Type=string -Label=Render Node 5 Format -Category=Output Settings -CategoryOrder=2 -Index=34 -Description=The format for the rendered output images. -Required=false -DisableIfBlank=true - -[Output5StartFrame] -Type=integer -Label=Render Node 5 Start Frame -Category=Output Settings -CategoryOrder=2 -Minimum=1 -Index=35 -Description=The frame that will correspond to frame one when numbering. If this value is not 1 then the monitor's job output features will not work properly. -Required=false -DisableIfBlank=true \ No newline at end of file diff --git a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/HarmonyAYON/HarmonyAYON.param b/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/HarmonyAYON/HarmonyAYON.param deleted file mode 100644 index 43a54a464e..0000000000 --- a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/HarmonyAYON/HarmonyAYON.param +++ /dev/null @@ -1,98 +0,0 @@ -[About] -Type=label -Label=About -Category=About Plugin -CategoryOrder=-1 -Index=0 -Default=Harmony Render Plugin for Deadline -Description=Not configurable - -[ConcurrentTasks] -Type=label -Label=ConcurrentTasks -Category=About Plugin -CategoryOrder=-1 -Index=0 -Default=True -Description=Not configurable - -[Harmony_RenderExecutable_10] -Type=multilinemultifilename -Category=Render Executables -CategoryOrder=0 -Index=0 -Label=Harmony 10 Render Executable -Description=The path to the Harmony Render executable file used for rendering. Enter alternative paths on separate lines. -Default=C:\Program Files (x86)\Toon Boom Animation\Toon Boom Harmony 10.0\win64\bin\Stage.exe - -[Harmony_RenderExecutable_11] -Type=multilinemultifilename -Category=Render Executables -CategoryOrder=0 -Index=1 -Label=Harmony 11 Render Executable -Description=The path to the Harmony Render executable file used for rendering. Enter alternative paths on separate lines. -Default=C:\Program Files (x86)\Toon Boom Animation\Toon Boom Harmony 11.0\win64\bin\Stage.exe - -[Harmony_RenderExecutable_12] -Type=multilinemultifilename -Category=Render Executables -CategoryOrder=0 -Index=2 -Label=Harmony 12 Render Executable -Description=The path to the Harmony Render executable file used for rendering. Enter alternative paths on separate lines. -Default=C:\Program Files (x86)\Toon Boom Animation\Toon Boom Harmony 12.0 Premium\win64\bin\HarmonyPremium.exe;/Applications/Toon Boom Harmony 12.0 Premium/Harmony Premium.app/Contents/MacOS/Harmony Premium;/usr/local/ToonBoomAnimation/harmonyPremium_12/lnx86_64/bin/HarmonyPremium - -[Harmony_RenderExecutable_14] -Type=multilinemultifilename -Category=Render Executables -CategoryOrder=0 -Index=3 -Label=Harmony 14 Render Executable -Description=The path to the Harmony Render executable file used for rendering. Enter alternative paths on separate lines. -Default=C:\Program Files (x86)\Toon Boom Animation\Toon Boom Harmony 14.0 Premium\win64\bin\HarmonyPremium.exe;/Applications/Toon Boom Harmony 14.0 Premium/Harmony Premium.app/Contents/MacOS/Harmony Premium;/usr/local/ToonBoomAnimation/harmonyPremium_14/lnx86_64/bin/HarmonyPremium - -[Harmony_RenderExecutable_15] -Type=multilinemultifilename -Category=Render Executables -CategoryOrder=0 -Index=4 -Label=Harmony 15 Render Executable -Description=The path to the Harmony Render executable file used for rendering. Enter alternative paths on separate lines. -Default=C:\Program Files (x86)\Toon Boom Animation\Toon Boom Harmony 15.0 Premium\win64\bin\HarmonyPremium.exe;/Applications/Toon Boom Harmony 15.0 Premium/Harmony Premium.app/Contents/MacOS/Harmony Premium;/usr/local/ToonBoomAnimation/harmonyPremium_15.0/lnx86_64/bin/HarmonyPremium - -[Harmony_RenderExecutable_17] -Type=multilinemultifilename -Category=Render Executables -CategoryOrder=0 -Index=4 -Label=Harmony 17 Render Executable -Description=The path to the Harmony Render executable file used for rendering. Enter alternative paths on separate lines. -Default=c:\Program Files (x86)\Toon Boom Animation\Toon Boom Harmony 17 Premium\win64\bin\HarmonyPremium.exe;/Applications/Toon Boom Harmony 17 Premium/Harmony Premium.app/Contents/MacOS/Harmony Premium;/usr/local/ToonBoomAnimation/harmonyPremium_17/lnx86_64/bin/HarmonyPremium - -[Harmony_RenderExecutable_20] -Type=multilinemultifilename -Category=Render Executables -CategoryOrder=0 -Index=4 -Label=Harmony 20 Render Executable -Description=The path to the Harmony Render executable file used for rendering. Enter alternative paths on separate lines. -Default=c:\Program Files (x86)\Toon Boom Animation\Toon Boom Harmony 20 Premium\win64\bin\HarmonyPremium.exe;/Applications/Toon Boom Harmony 20 Premium/Harmony Premium.app/Contents/MacOS/Harmony Premium;/usr/local/ToonBoomAnimation/harmonyPremium_20/lnx86_64/bin/HarmonyPremium - -[Harmony_RenderExecutable_21] -Type=multilinemultifilename -Category=Render Executables -CategoryOrder=0 -Index=4 -Label=Harmony 21 Render Executable -Description=The path to the Harmony Render executable file used for rendering. Enter alternative paths on separate lines. -Default=c:\Program Files (x86)\Toon Boom Animation\Toon Boom Harmony 21 Premium\win64\bin\HarmonyPremium.exe;/Applications/Toon Boom Harmony 21 Premium/Harmony Premium.app/Contents/MacOS/Harmony Premium;/usr/local/ToonBoomAnimation/harmonyPremium_21/lnx86_64/bin/HarmonyPremium - -[Harmony_RenderExecutable_22] -Type=multilinemultifilename -Category=Render Executables -CategoryOrder=0 -Index=4 -Label=Harmony 22 Render Executable -Description=The path to the Harmony Render executable file used for rendering. Enter alternative paths on separate lines. -Default=c:\Program Files (x86)\Toon Boom Animation\Toon Boom Harmony 22 Premium\win64\bin\HarmonyPremium.exe;/Applications/Toon Boom Harmony 22 Premium/Harmony Premium.app/Contents/MacOS/Harmony Premium;/usr/local/ToonBoomAnimation/harmonyPremium_22/lnx86_64/bin/HarmonyPremium diff --git a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/HarmonyAYON/HarmonyAYON.py b/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/HarmonyAYON/HarmonyAYON.py deleted file mode 100644 index d9fd0b49ef..0000000000 --- a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/HarmonyAYON/HarmonyAYON.py +++ /dev/null @@ -1,151 +0,0 @@ -#!/usr/bin/env python3 -from System import * -from System.Diagnostics import * -from System.IO import * -from System.Text import * - -from Deadline.Plugins import * -from Deadline.Scripting import * - -def GetDeadlinePlugin(): - return HarmonyAYONPlugin() - -def CleanupDeadlinePlugin(deadlinePlugin): - deadlinePlugin.Cleanup() - -class HarmonyAYONPlugin(DeadlinePlugin): - - def __init__( self ): - super().__init__() - self.InitializeProcessCallback += self.InitializeProcess - self.RenderExecutableCallback += self.RenderExecutable - self.RenderArgumentCallback += self.RenderArgument - self.CheckExitCodeCallback += self.CheckExitCode - - def Cleanup( self ): - print("Cleanup") - for stdoutHandler in self.StdoutHandlers: - del stdoutHandler.HandleCallback - - del self.InitializeProcessCallback - del self.RenderExecutableCallback - del self.RenderArgumentCallback - - def CheckExitCode( self, exitCode ): - print("check code") - if exitCode != 0: - if exitCode == 100: - self.LogInfo( "Renderer reported an error with error code 100. This will be ignored, since the option to ignore it is specified in the Job Properties." ) - else: - self.FailRender( "Renderer returned non-zero error code %d. Check the renderer's output." % exitCode ) - - def InitializeProcess( self ): - self.PluginType = PluginType.Simple - self.StdoutHandling = True - self.PopupHandling = True - - self.AddStdoutHandlerCallback( "Rendered frame ([0-9]+)" ).HandleCallback += self.HandleStdoutProgress - - def HandleStdoutProgress( self ): - startFrame = self.GetStartFrame() - endFrame = self.GetEndFrame() - if( endFrame - startFrame + 1 != 0 ): - self.SetProgress( 100 * ( int(self.GetRegexMatch(1)) - startFrame + 1 ) / ( endFrame - startFrame + 1 ) ) - - def RenderExecutable( self ): - version = int( self.GetPluginInfoEntry( "Version" ) ) - exe = "" - exeList = self.GetConfigEntry( "Harmony_RenderExecutable_" + str(version) ) - exe = FileUtils.SearchFileList( exeList ) - if( exe == "" ): - self.FailRender( "Harmony render executable was not found in the configured separated list \"" + exeList + "\". The path to the render executable can be configured from the Plugin Configuration in the Deadline Monitor." ) - return exe - - def RenderArgument( self ): - renderArguments = "-batch" - - if self.GetBooleanPluginInfoEntryWithDefault( "UsingResPreset", False ): - resName = self.GetPluginInfoEntryWithDefault( "ResolutionName", "HDTV_1080p24" ) - if resName == "Custom": - renderArguments += " -res " + self.GetPluginInfoEntryWithDefault( "PresetName", "HDTV_1080p24" ) - else: - renderArguments += " -res " + resName - else: - resolutionX = self.GetIntegerPluginInfoEntryWithDefault( "ResolutionX", -1 ) - resolutionY = self.GetIntegerPluginInfoEntryWithDefault( "ResolutionY", -1 ) - fov = self.GetFloatPluginInfoEntryWithDefault( "FieldOfView", -1 ) - - if resolutionX > 0 and resolutionY > 0 and fov > 0: - renderArguments += " -res " + str( resolutionX ) + " " + str( resolutionY ) + " " + str( fov ) - - camera = self.GetPluginInfoEntryWithDefault( "Camera", "" ) - - if not camera == "": - renderArguments += " -camera " + camera - - startFrame = str( self.GetStartFrame() ) - endFrame = str( self.GetEndFrame() ) - - renderArguments += " -frames " + startFrame + " " + endFrame - - if not self.GetBooleanPluginInfoEntryWithDefault( "IsDatabase", False ): - sceneFilename = self.GetPluginInfoEntryWithDefault( "SceneFile", self.GetDataFilename() ) - sceneFilename = RepositoryUtils.CheckPathMapping( sceneFilename ) - renderArguments += " \"" + sceneFilename + "\"" - else: - environment = self.GetPluginInfoEntryWithDefault( "Environment", "" ) - renderArguments += " -env " + environment - job = self.GetPluginInfoEntryWithDefault( "Job", "" ) - renderArguments += " -job " + job - scene = self.GetPluginInfoEntryWithDefault( "SceneName", "" ) - renderArguments += " -scene " + scene - version = self.GetPluginInfoEntryWithDefault( "SceneVersion", "" ) - renderArguments += " -version " + version - - #tempSceneDirectory = self.CreateTempDirectory( "thread" + str(self.GetThreadNumber()) ) - #preRenderScript = - rendernodeNum = 0 - scriptBuilder = StringBuilder() - - while True: - nodeName = self.GetPluginInfoEntryWithDefault( "Output" + str( rendernodeNum ) + "Node", "" ) - if nodeName == "": - break - nodeType = self.GetPluginInfoEntryWithDefault( "Output" + str( rendernodeNum ) + "Type", "Image" ) - if nodeType == "Image": - nodePath = self.GetPluginInfoEntryWithDefault( "Output" + str( rendernodeNum ) + "Path", "" ) - nodeLeadingZero = self.GetPluginInfoEntryWithDefault( "Output" + str( rendernodeNum ) + "LeadingZero", "" ) - nodeFormat = self.GetPluginInfoEntryWithDefault( "Output" + str( rendernodeNum ) + "Format", "" ) - nodeStartFrame = self.GetPluginInfoEntryWithDefault( "Output" + str( rendernodeNum ) + "StartFrame", "" ) - - if not nodePath == "": - scriptBuilder.AppendLine("node.setTextAttr( \"" + nodeName + "\", \"drawingName\", 1, \"" + nodePath + "\" );") - - if not nodeLeadingZero == "": - scriptBuilder.AppendLine("node.setTextAttr( \"" + nodeName + "\", \"leadingZeros\", 1, \"" + nodeLeadingZero + "\" );") - - if not nodeFormat == "": - scriptBuilder.AppendLine("node.setTextAttr( \"" + nodeName + "\", \"drawingType\", 1, \"" + nodeFormat + "\" );") - - if not nodeStartFrame == "": - scriptBuilder.AppendLine("node.setTextAttr( \"" + nodeName + "\", \"start\", 1, \"" + nodeStartFrame + "\" );") - - if nodeType == "Movie": - nodePath = self.GetPluginInfoEntryWithDefault( "Output" + str( rendernodeNum ) + "Path", "" ) - if not nodePath == "": - scriptBuilder.AppendLine("node.setTextAttr( \"" + nodeName + "\", \"moviePath\", 1, \"" + nodePath + "\" );") - - rendernodeNum += 1 - - tempDirectory = self.CreateTempDirectory( "thread" + str(self.GetThreadNumber()) ) - preRenderScriptName = Path.Combine( tempDirectory, "preRenderScript.txt" ) - - File.WriteAllText( preRenderScriptName, scriptBuilder.ToString() ) - - preRenderInlineScript = self.GetPluginInfoEntryWithDefault( "PreRenderInlineScript", "" ) - if preRenderInlineScript: - renderArguments += " -preRenderInlineScript \"" + preRenderInlineScript +"\"" - - renderArguments += " -preRenderScript \"" + preRenderScriptName +"\"" - - return renderArguments diff --git a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/OpenPypeTileAssembler/OpenPypeTileAssembler.ico b/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/OpenPypeTileAssembler/OpenPypeTileAssembler.ico deleted file mode 100644 index de860673c4..0000000000 Binary files a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/OpenPypeTileAssembler/OpenPypeTileAssembler.ico and /dev/null differ diff --git a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/OpenPypeTileAssembler/OpenPypeTileAssembler.options b/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/OpenPypeTileAssembler/OpenPypeTileAssembler.options deleted file mode 100644 index 0b631ba66d..0000000000 --- a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/OpenPypeTileAssembler/OpenPypeTileAssembler.options +++ /dev/null @@ -1,35 +0,0 @@ -[OIIOToolPath] -Type=filename -Label=OIIO Tool location -Category=OIIO -Index=0 -Description=OIIO Tool executable to use. -Required=false -DisableIfBlank=true - -[OutputFile] -Type=filenamesave -Label=Output File -Category=Output -Index=0 -Description=The scene filename as it exists on the network -Required=false -DisableIfBlank=true - -[CleanupTiles] -Type=boolean -Category=Options -Index=0 -Label=Cleanup Tiles -Required=false -DisableIfBlank=true -Description=If enabled, the OpenPype Tile Assembler will cleanup all tiles after assembly. - -[Renderer] -Type=string -Label=Renderer -Category=Quicktime Info -Index=0 -Description=Renderer name -Required=false -DisableIfBlank=true diff --git a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/OpenPypeTileAssembler/OpenPypeTileAssembler.param b/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/OpenPypeTileAssembler/OpenPypeTileAssembler.param deleted file mode 100644 index 66a3342e38..0000000000 --- a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/OpenPypeTileAssembler/OpenPypeTileAssembler.param +++ /dev/null @@ -1,17 +0,0 @@ -[About] -Type=label -Label=About -Category=About Plugin -CategoryOrder=-1 -Index=0 -Default=OpenPype Tile Assembler Plugin for Deadline -Description=Not configurable - -[OIIOTool_RenderExecutable] -Type=multilinemultifilename -Label=OIIO Tool Executable -Category=Render Executables -CategoryOrder=0 -Default=C:\Program Files\OIIO\bin\oiiotool.exe;/usr/bin/oiiotool -Description=The path to the Open Image IO Tool executable file used for rendering. Enter alternative paths on separate lines. -W diff --git a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/OpenPypeTileAssembler/OpenPypeTileAssembler.py b/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/OpenPypeTileAssembler/OpenPypeTileAssembler.py deleted file mode 100644 index f146aef7b4..0000000000 --- a/server_addon/deadline/client/ayon_deadline/repository/custom/plugins/OpenPypeTileAssembler/OpenPypeTileAssembler.py +++ /dev/null @@ -1,457 +0,0 @@ -# -*- coding: utf-8 -*- -"""Tile Assembler Plugin using Open Image IO tool. - -Todo: - Currently we support only EXRs with their data window set. -""" -import os -import re -import subprocess -import xml.etree.ElementTree - -from System.IO import Path - -from Deadline.Plugins import DeadlinePlugin -from Deadline.Scripting import ( - FileUtils, RepositoryUtils, SystemUtils) - - -version_major = 1 -version_minor = 0 -version_patch = 0 -version_string = "{}.{}.{}".format(version_major, version_minor, version_patch) -STRING_TAGS = { - "format" -} -INT_TAGS = { - "x", "y", "z", - "width", "height", "depth", - "full_x", "full_y", "full_z", - "full_width", "full_height", "full_depth", - "tile_width", "tile_height", "tile_depth", - "nchannels", - "alpha_channel", - "z_channel", - "deep", - "subimages", -} - - -XML_CHAR_REF_REGEX_HEX = re.compile(r"&#x?[0-9a-fA-F]+;") - -# Regex to parse array attributes -ARRAY_TYPE_REGEX = re.compile(r"^(int|float|string)\[\d+\]$") - - -def convert_value_by_type_name(value_type, value): - """Convert value to proper type based on type name. - - In some cases value types have custom python class. - """ - - # Simple types - if value_type == "string": - return value - - if value_type == "int": - return int(value) - - if value_type == "float": - return float(value) - - # Vectors will probably have more types - if value_type in ("vec2f", "float2"): - return [float(item) for item in value.split(",")] - - # Matrix should be always have square size of element 3x3, 4x4 - # - are returned as list of lists - if value_type == "matrix": - output = [] - current_index = -1 - parts = value.split(",") - parts_len = len(parts) - if parts_len == 1: - divisor = 1 - elif parts_len == 4: - divisor = 2 - elif parts_len == 9: - divisor = 3 - elif parts_len == 16: - divisor = 4 - else: - print("Unknown matrix resolution {}. Value: \"{}\"".format( - parts_len, value - )) - for part in parts: - output.append(float(part)) - return output - - for idx, item in enumerate(parts): - list_index = idx % divisor - if list_index > current_index: - current_index = list_index - output.append([]) - output[list_index].append(float(item)) - return output - - if value_type == "rational2i": - parts = value.split("/") - top = float(parts[0]) - bottom = 1.0 - if len(parts) != 1: - bottom = float(parts[1]) - return float(top) / float(bottom) - - if value_type == "vector": - parts = [part.strip() for part in value.split(",")] - output = [] - for part in parts: - if part == "-nan": - output.append(None) - continue - try: - part = float(part) - except ValueError: - pass - output.append(part) - return output - - if value_type == "timecode": - return value - - # Array of other types is converted to list - re_result = ARRAY_TYPE_REGEX.findall(value_type) - if re_result: - array_type = re_result[0] - output = [] - for item in value.split(","): - output.append( - convert_value_by_type_name(array_type, item) - ) - return output - - print(( - "Dev note (missing implementation):" - " Unknown attrib type \"{}\". Value: {}" - ).format(value_type, value)) - return value - - -def parse_oiio_xml_output(xml_string): - """Parse xml output from OIIO info command.""" - output = {} - if not xml_string: - return output - - # Fix values with ampresand (lazy fix) - # - oiiotool exports invalid xml which ElementTree can't handle - # e.g. "" - # WARNING: this will affect even valid character entities. If you need - # those values correctly, this must take care of valid character ranges. - # See https://github.com/pypeclub/OpenPype/pull/2729 - matches = XML_CHAR_REF_REGEX_HEX.findall(xml_string) - for match in matches: - new_value = match.replace("&", "&") - xml_string = xml_string.replace(match, new_value) - - tree = xml.etree.ElementTree.fromstring(xml_string) - attribs = {} - output["attribs"] = attribs - for child in tree: - tag_name = child.tag - if tag_name == "attrib": - attrib_def = child.attrib - value = convert_value_by_type_name( - attrib_def["type"], child.text - ) - - attribs[attrib_def["name"]] = value - continue - - # Channels are stored as tex on each child - if tag_name == "channelnames": - value = [] - for channel in child: - value.append(channel.text) - - # Convert known integer type tags to int - elif tag_name in INT_TAGS: - value = int(child.text) - - # Keep value of known string tags - elif tag_name in STRING_TAGS: - value = child.text - - # Keep value as text for unknown tags - # - feel free to add more tags - else: - value = child.text - print(( - "Dev note (missing implementation):" - " Unknown tag \"{}\". Value \"{}\"" - ).format(tag_name, value)) - - output[child.tag] = value - - return output - - -def info_about_input(oiiotool_path, filepath): - args = [ - oiiotool_path, - "--info", - "-v", - "-i:infoformat=xml", - filepath - ] - popen = subprocess.Popen(args, stdout=subprocess.PIPE) - _stdout, _stderr = popen.communicate() - output = "" - if _stdout: - output += _stdout.decode("utf-8", errors="backslashreplace") - - if _stderr: - output += _stderr.decode("utf-8", errors="backslashreplace") - - output = output.replace("\r\n", "\n") - xml_started = False - lines = [] - for line in output.split("\n"): - if not xml_started: - if not line.startswith("<"): - continue - xml_started = True - if xml_started: - lines.append(line) - - if not xml_started: - raise ValueError( - "Failed to read input file \"{}\".\nOutput:\n{}".format( - filepath, output - ) - ) - xml_text = "\n".join(lines) - return parse_oiio_xml_output(xml_text) - - -def GetDeadlinePlugin(): # noqa: N802 - """Helper.""" - return OpenPypeTileAssembler() - - -def CleanupDeadlinePlugin(deadlinePlugin): # noqa: N802, N803 - """Helper.""" - deadlinePlugin.cleanup() - - -class OpenPypeTileAssembler(DeadlinePlugin): - """Deadline plugin for assembling tiles using OIIO.""" - - def __init__(self): - """Init.""" - super().__init__() - self.InitializeProcessCallback += self.initialize_process - self.RenderExecutableCallback += self.render_executable - self.RenderArgumentCallback += self.render_argument - self.PreRenderTasksCallback += self.pre_render_tasks - self.PostRenderTasksCallback += self.post_render_tasks - - def cleanup(self): - """Cleanup function.""" - for stdoutHandler in self.StdoutHandlers: - del stdoutHandler.HandleCallback - - del self.InitializeProcessCallback - del self.RenderExecutableCallback - del self.RenderArgumentCallback - del self.PreRenderTasksCallback - del self.PostRenderTasksCallback - - def initialize_process(self): - """Initialization.""" - self.LogInfo("Plugin version: {}".format(version_string)) - self.SingleFramesOnly = True - self.StdoutHandling = True - self.renderer = self.GetPluginInfoEntryWithDefault( - "Renderer", "undefined") - self.AddStdoutHandlerCallback( - ".*Error.*").HandleCallback += self.handle_stdout_error - - def render_executable(self): - """Get render executable name. - - Get paths from plugin configuration, find executable and return it. - - Returns: - (str): Render executable. - - """ - oiiotool_exe_list = self.GetConfigEntry("OIIOTool_RenderExecutable") - oiiotool_exe = FileUtils.SearchFileList(oiiotool_exe_list) - - if oiiotool_exe == "": - self.FailRender(("No file found in the semicolon separated " - "list \"{}\". The path to the render executable " - "can be configured from the Plugin Configuration " - "in the Deadline Monitor.").format( - oiiotool_exe_list)) - - return oiiotool_exe - - def render_argument(self): - """Generate command line arguments for render executable. - - Returns: - (str): arguments to add to render executable. - - """ - # Read tile config file. This file is in compatible format with - # Draft Tile Assembler - data = {} - with open(self.config_file, "rU") as f: - for text in f: - # Parsing key-value pair and removing white-space - # around the entries - info = [x.strip() for x in text.split("=", 1)] - - if len(info) > 1: - try: - data[str(info[0])] = info[1] - except Exception as e: - # should never be called - self.FailRender( - "Cannot parse config file: {}".format(e)) - - # Get output file. We support only EXRs now. - output_file = data["ImageFileName"] - output_file = RepositoryUtils.CheckPathMapping(output_file) - output_file = self.process_path(output_file) - - tile_info = [] - for tile in range(int(data["TileCount"])): - tile_info.append({ - "filepath": data["Tile{}".format(tile)], - "pos_x": int(data["Tile{}X".format(tile)]), - "pos_y": int(data["Tile{}Y".format(tile)]), - "height": int(data["Tile{}Height".format(tile)]), - "width": int(data["Tile{}Width".format(tile)]) - }) - - arguments = self.tile_oiio_args( - int(data["ImageWidth"]), int(data["ImageHeight"]), - tile_info, output_file) - self.LogInfo( - "Using arguments: {}".format(" ".join(arguments))) - self.tiles = tile_info - return " ".join(arguments) - - def process_path(self, filepath): - """Handle slashes in file paths.""" - if SystemUtils.IsRunningOnWindows(): - filepath = filepath.replace("/", "\\") - if filepath.startswith("\\") and not filepath.startswith("\\\\"): - filepath = "\\" + filepath - else: - filepath = filepath.replace("\\", "/") - return filepath - - def pre_render_tasks(self): - """Load config file and do remapping.""" - self.LogInfo("OpenPype Tile Assembler starting...") - config_file = self.GetPluginInfoEntry("ConfigFile") - - temp_scene_directory = self.CreateTempDirectory( - "thread" + str(self.GetThreadNumber())) - temp_scene_filename = Path.GetFileName(config_file) - self.config_file = Path.Combine( - temp_scene_directory, temp_scene_filename) - - if SystemUtils.IsRunningOnWindows(): - RepositoryUtils.CheckPathMappingInFileAndReplaceSeparator( - config_file, self.config_file, "/", "\\") - else: - RepositoryUtils.CheckPathMappingInFileAndReplaceSeparator( - config_file, self.config_file, "\\", "/") - os.chmod(self.config_file, os.stat(self.config_file).st_mode) - - def post_render_tasks(self): - """Cleanup tiles if required.""" - if self.GetBooleanPluginInfoEntryWithDefault("CleanupTiles", False): - self.LogInfo("Cleaning up Tiles...") - for tile in self.tiles: - try: - self.LogInfo("Deleting: {}".format(tile["filepath"])) - os.remove(tile["filepath"]) - # By this time we would have errored out - # if error on missing was enabled - except KeyError: - pass - except OSError: - self.LogInfo("Failed to delete: {}".format( - tile["filepath"])) - pass - - self.LogInfo("OpenPype Tile Assembler Job finished.") - - def handle_stdout_error(self): - """Handle errors in stdout.""" - self.FailRender(self.GetRegexMatch(0)) - - def tile_oiio_args( - self, output_width, output_height, tile_info, output_path): - """Generate oiio tool arguments for tile assembly. - - Args: - output_width (int): Width of output image. - output_height (int): Height of output image. - tile_info (list): List of tile items, each item must be - dictionary with `filepath`, `pos_x` and `pos_y` keys - representing path to file and x, y coordinates on output - image where top-left point of tile item should start. - output_path (str): Path to file where should be output stored. - - Returns: - (list): oiio tools arguments. - - """ - args = [] - - # Create new image with output resolution, and with same type and - # channels as input - oiiotool_path = self.render_executable() - first_tile_path = tile_info[0]["filepath"] - first_tile_info = info_about_input(oiiotool_path, first_tile_path) - create_arg_template = "--create{} {}x{} {}" - - image_type = "" - image_format = first_tile_info.get("format") - if image_format: - image_type = ":type={}".format(image_format) - - create_arg = create_arg_template.format( - image_type, output_width, - output_height, first_tile_info["nchannels"] - ) - args.append(create_arg) - - for tile in tile_info: - path = tile["filepath"] - pos_x = tile["pos_x"] - tile_height = info_about_input(oiiotool_path, path)["height"] - if self.renderer == "vray": - pos_y = tile["pos_y"] - else: - pos_y = output_height - tile["pos_y"] - tile_height - - # Add input path and make sure inputs origin is 0, 0 - args.append(path) - args.append("--origin +0+0") - # Swap to have input as foreground - args.append("--swap") - # Paste foreground to background - args.append("--paste {x:+d}{y:+d}".format(x=pos_x, y=pos_y)) - - args.append("-o") - args.append(output_path) - - return args diff --git a/server_addon/deadline/client/ayon_deadline/repository/readme.md b/server_addon/deadline/client/ayon_deadline/repository/readme.md deleted file mode 100644 index 31ffffd0b7..0000000000 --- a/server_addon/deadline/client/ayon_deadline/repository/readme.md +++ /dev/null @@ -1,29 +0,0 @@ -## OpenPype Deadline repository overlay - - This directory is an overlay for Deadline repository. - It means that you can copy the whole hierarchy to Deadline repository and it - should work. - - Logic: - ----- - GlobalJobPreLoad - ----- - -The `GlobalJobPreLoad` will retrieve the OpenPype executable path from the -`OpenPype` Deadline Plug-in's settings. Then it will call the executable to -retrieve the environment variables needed for the Deadline Job. -These environment variables are injected into rendering process. - -Deadline triggers the `GlobalJobPreLoad.py` for each Worker as it starts the -Job. - -*Note*: It also contains backward compatible logic to preserve functionality -for old Pype2 and non-OpenPype triggered jobs. - - Plugin - ------ - For each render and publishing job the `OpenPype` Deadline Plug-in is checked - for the configured location of the OpenPype executable (needs to be configured - in `Deadline's Configure Plugins > OpenPype`) through `GlobalJobPreLoad`. - - diff --git a/server_addon/deadline/client/ayon_deadline/version.py b/server_addon/deadline/client/ayon_deadline/version.py deleted file mode 100644 index e131427f12..0000000000 --- a/server_addon/deadline/client/ayon_deadline/version.py +++ /dev/null @@ -1,3 +0,0 @@ -# -*- coding: utf-8 -*- -"""Package declaring AYON addon 'deadline' version.""" -__version__ = "0.2.2" diff --git a/server_addon/deadline/package.py b/server_addon/deadline/package.py deleted file mode 100644 index dcc61e3d46..0000000000 --- a/server_addon/deadline/package.py +++ /dev/null @@ -1,10 +0,0 @@ -name = "deadline" -title = "Deadline" -version = "0.2.2" - -client_dir = "ayon_deadline" - -ayon_required_addons = { - "core": ">0.3.2", -} -ayon_compatible_addons = {} diff --git a/server_addon/deadline/server/__init__.py b/server_addon/deadline/server/__init__.py deleted file mode 100644 index 8d2dc152cd..0000000000 --- a/server_addon/deadline/server/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Type - -from ayon_server.addons import BaseServerAddon - -from .settings import DeadlineSettings, DEFAULT_VALUES, DeadlineSiteSettings - - -class Deadline(BaseServerAddon): - settings_model: Type[DeadlineSettings] = DeadlineSettings - site_settings_model: Type[DeadlineSiteSettings] = DeadlineSiteSettings - - - async def get_default_settings(self): - settings_model_cls = self.get_settings_model() - return settings_model_cls(**DEFAULT_VALUES) diff --git a/server_addon/deadline/server/settings/__init__.py b/server_addon/deadline/server/settings/__init__.py deleted file mode 100644 index d25c0fb330..0000000000 --- a/server_addon/deadline/server/settings/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -from .main import ( - DeadlineSettings, - DEFAULT_VALUES, -) -from .site_settings import DeadlineSiteSettings - - -__all__ = ( - "DeadlineSettings", - "DeadlineSiteSettings", - "DEFAULT_VALUES", -) diff --git a/server_addon/deadline/server/settings/main.py b/server_addon/deadline/server/settings/main.py deleted file mode 100644 index 47ad72a86f..0000000000 --- a/server_addon/deadline/server/settings/main.py +++ /dev/null @@ -1,85 +0,0 @@ -from typing import TYPE_CHECKING -from pydantic import validator - -from ayon_server.settings import ( - BaseSettingsModel, - SettingsField, - ensure_unique_names, -) -if TYPE_CHECKING: - from ayon_server.addons import BaseServerAddon - -from .publish_plugins import ( - PublishPluginsModel, - DEFAULT_DEADLINE_PLUGINS_SETTINGS -) - - -async def defined_deadline_ws_name_enum_resolver( - addon: "BaseServerAddon", - settings_variant: str = "production", - project_name: str | None = None, -) -> list[str]: - """Provides list of names of configured Deadline webservice urls.""" - if addon is None: - return [] - - settings = await addon.get_studio_settings(variant=settings_variant) - - ws_server_name = [] - for deadline_url_item in settings.deadline_urls: - ws_server_name.append(deadline_url_item.name) - - return ws_server_name - -class ServerItemSubmodel(BaseSettingsModel): - """Connection info about configured DL servers.""" - _layout = "compact" - name: str = SettingsField(title="Name") - value: str = SettingsField(title="Url") - require_authentication: bool = SettingsField( - False, title="Require authentication") - not_verify_ssl: bool = SettingsField( - False, title="Don't verify SSL") - - -class DeadlineSettings(BaseSettingsModel): - # configured DL servers - deadline_urls: list[ServerItemSubmodel] = SettingsField( - default_factory=list, - title="System Deadline Webservice Info", - scope=["studio"], - ) - - # name(key) of selected server for project - deadline_server: str = SettingsField( - title="Project Deadline server name", - section="---", - scope=["project"], - enum_resolver=defined_deadline_ws_name_enum_resolver - ) - - publish: PublishPluginsModel = SettingsField( - default_factory=PublishPluginsModel, - title="Publish Plugins", - ) - - @validator("deadline_urls") - def validate_unique_names(cls, value): - ensure_unique_names(value) - return value - - - -DEFAULT_VALUES = { - "deadline_urls": [ - { - "name": "default", - "value": "http://127.0.0.1:8082", - "require_authentication": False, - "not_verify_ssl": False - } - ], - "deadline_server": "default", - "publish": DEFAULT_DEADLINE_PLUGINS_SETTINGS -} diff --git a/server_addon/deadline/server/settings/publish_plugins.py b/server_addon/deadline/server/settings/publish_plugins.py deleted file mode 100644 index 1cf699db23..0000000000 --- a/server_addon/deadline/server/settings/publish_plugins.py +++ /dev/null @@ -1,578 +0,0 @@ -from pydantic import validator - -from ayon_server.settings import ( - BaseSettingsModel, - SettingsField, - ensure_unique_names, -) - - -class CollectDeadlinePoolsModel(BaseSettingsModel): - """Settings Deadline default pools.""" - - primary_pool: str = SettingsField(title="Primary Pool") - - secondary_pool: str = SettingsField(title="Secondary Pool") - - -class ValidateExpectedFilesModel(BaseSettingsModel): - enabled: bool = SettingsField(True, title="Enabled") - active: bool = SettingsField(True, title="Active") - allow_user_override: bool = SettingsField( - True, title="Allow user change frame range" - ) - families: list[str] = SettingsField( - default_factory=list, title="Trigger on families" - ) - targets: list[str] = SettingsField( - default_factory=list, title="Trigger for plugins" - ) - - -def tile_assembler_enum(): - """Return a list of value/label dicts for the enumerator. - - Returning a list of dicts is used to allow for a custom label to be - displayed in the UI. - """ - return [ - { - "value": "DraftTileAssembler", - "label": "Draft Tile Assembler" - }, - { - "value": "OpenPypeTileAssembler", - "label": "Open Image IO" - } - ] - - -class ScenePatchesSubmodel(BaseSettingsModel): - _layout = "expanded" - name: str = SettingsField(title="Patch name") - regex: str = SettingsField(title="Patch regex") - line: str = SettingsField(title="Patch line") - - -class MayaSubmitDeadlineModel(BaseSettingsModel): - """Maya deadline submitter settings.""" - - enabled: bool = SettingsField(title="Enabled") - optional: bool = SettingsField(title="Optional") - active: bool = SettingsField(title="Active") - use_published: bool = SettingsField(title="Use Published scene") - import_reference: bool = SettingsField( - title="Use Scene with Imported Reference" - ) - asset_dependencies: bool = SettingsField(title="Use Asset dependencies") - priority: int = SettingsField(title="Priority") - tile_priority: int = SettingsField(title="Tile Priority") - group: str = SettingsField(title="Group") - limit: list[str] = SettingsField( - default_factory=list, - title="Limit Groups" - ) - tile_assembler_plugin: str = SettingsField( - title="Tile Assembler Plugin", - enum_resolver=tile_assembler_enum, - ) - jobInfo: str = SettingsField( - title="Additional JobInfo data", - widget="textarea", - ) - pluginInfo: str = SettingsField( - title="Additional PluginInfo data", - widget="textarea", - ) - - scene_patches: list[ScenePatchesSubmodel] = SettingsField( - default_factory=list, - title="Scene patches", - ) - strict_error_checking: bool = SettingsField( - title="Disable Strict Error Check profiles" - ) - - @validator("scene_patches") - def validate_unique_names(cls, value): - ensure_unique_names(value) - return value - - -class MaxSubmitDeadlineModel(BaseSettingsModel): - enabled: bool = SettingsField(True) - optional: bool = SettingsField(title="Optional") - active: bool = SettingsField(title="Active") - use_published: bool = SettingsField(title="Use Published scene") - priority: int = SettingsField(title="Priority") - chunk_size: int = SettingsField(title="Frame per Task") - group: str = SettingsField("", title="Group Name") - - -class EnvSearchReplaceSubmodel(BaseSettingsModel): - _layout = "compact" - name: str = SettingsField(title="Name") - value: str = SettingsField(title="Value") - - -class LimitGroupsSubmodel(BaseSettingsModel): - _layout = "expanded" - name: str = SettingsField(title="Name") - value: list[str] = SettingsField( - default_factory=list, - title="Limit Groups" - ) - - -def fusion_deadline_plugin_enum(): - """Return a list of value/label dicts for the enumerator. - - Returning a list of dicts is used to allow for a custom label to be - displayed in the UI. - """ - return [ - { - "value": "Fusion", - "label": "Fusion" - }, - { - "value": "FusionCmd", - "label": "FusionCmd" - } - ] - - -class FusionSubmitDeadlineModel(BaseSettingsModel): - enabled: bool = SettingsField(True, title="Enabled") - optional: bool = SettingsField(False, title="Optional") - active: bool = SettingsField(True, title="Active") - priority: int = SettingsField(50, title="Priority") - chunk_size: int = SettingsField(10, title="Frame per Task") - concurrent_tasks: int = SettingsField( - 1, title="Number of concurrent tasks" - ) - group: str = SettingsField("", title="Group Name") - plugin: str = SettingsField("Fusion", - enum_resolver=fusion_deadline_plugin_enum, - title="Deadline Plugin") - - -class NukeSubmitDeadlineModel(BaseSettingsModel): - """Nuke deadline submitter settings.""" - - enabled: bool = SettingsField(title="Enabled") - optional: bool = SettingsField(title="Optional") - active: bool = SettingsField(title="Active") - priority: int = SettingsField(title="Priority") - chunk_size: int = SettingsField(title="Chunk Size") - concurrent_tasks: int = SettingsField(title="Number of concurrent tasks") - group: str = SettingsField(title="Group") - department: str = SettingsField(title="Department") - use_gpu: bool = SettingsField(title="Use GPU") - workfile_dependency: bool = SettingsField(title="Workfile Dependency") - use_published_workfile: bool = SettingsField( - title="Use Published Workfile" - ) - - env_allowed_keys: list[str] = SettingsField( - default_factory=list, - title="Allowed environment keys" - ) - - env_search_replace_values: list[EnvSearchReplaceSubmodel] = SettingsField( - default_factory=list, - title="Search & replace in environment values", - ) - - limit_groups: list[LimitGroupsSubmodel] = SettingsField( - default_factory=list, - title="Limit Groups", - ) - - @validator( - "limit_groups", - "env_search_replace_values") - def validate_unique_names(cls, value): - ensure_unique_names(value) - return value - - -class HarmonySubmitDeadlineModel(BaseSettingsModel): - """Harmony deadline submitter settings.""" - - enabled: bool = SettingsField(title="Enabled") - optional: bool = SettingsField(title="Optional") - active: bool = SettingsField(title="Active") - use_published: bool = SettingsField(title="Use Published scene") - priority: int = SettingsField(title="Priority") - chunk_size: int = SettingsField(title="Chunk Size") - group: str = SettingsField(title="Group") - department: str = SettingsField(title="Department") - - -class HoudiniSubmitDeadlineModel(BaseSettingsModel): - """Houdini deadline render submitter settings.""" - enabled: bool = SettingsField(title="Enabled") - optional: bool = SettingsField(title="Optional") - active: bool = SettingsField(title="Active") - - priority: int = SettingsField(title="Priority") - chunk_size: int = SettingsField(title="Chunk Size") - group: str = SettingsField(title="Group") - - export_priority: int = SettingsField(title="Export Priority") - export_chunk_size: int = SettingsField(title="Export Chunk Size") - export_group: str = SettingsField(title="Export Group") - - -class HoudiniCacheSubmitDeadlineModel(BaseSettingsModel): - """Houdini deadline cache submitter settings.""" - enabled: bool = SettingsField(title="Enabled") - optional: bool = SettingsField(title="Optional") - active: bool = SettingsField(title="Active") - - priority: int = SettingsField(title="Priority") - chunk_size: int = SettingsField(title="Chunk Size") - group: str = SettingsField(title="Group") - - -class AfterEffectsSubmitDeadlineModel(BaseSettingsModel): - """After Effects deadline submitter settings.""" - - enabled: bool = SettingsField(title="Enabled") - optional: bool = SettingsField(title="Optional") - active: bool = SettingsField(title="Active") - use_published: bool = SettingsField(title="Use Published scene") - priority: int = SettingsField(title="Priority") - chunk_size: int = SettingsField(title="Chunk Size") - group: str = SettingsField(title="Group") - department: str = SettingsField(title="Department") - multiprocess: bool = SettingsField(title="Optional") - - -class CelactionSubmitDeadlineModel(BaseSettingsModel): - enabled: bool = SettingsField(True, title="Enabled") - deadline_department: str = SettingsField("", title="Deadline apartment") - deadline_priority: int = SettingsField(50, title="Deadline priority") - deadline_pool: str = SettingsField("", title="Deadline pool") - deadline_pool_secondary: str = SettingsField( - "", title="Deadline pool (secondary)" - ) - deadline_group: str = SettingsField("", title="Deadline Group") - deadline_chunk_size: int = SettingsField(10, title="Deadline Chunk size") - deadline_job_delay: str = SettingsField( - "", title="Delay job (timecode dd:hh:mm:ss)" - ) - - -class BlenderSubmitDeadlineModel(BaseSettingsModel): - enabled: bool = SettingsField(True) - optional: bool = SettingsField(title="Optional") - active: bool = SettingsField(title="Active") - use_published: bool = SettingsField(title="Use Published scene") - asset_dependencies: bool = SettingsField(title="Use Asset dependencies") - priority: int = SettingsField(title="Priority") - chunk_size: int = SettingsField(title="Frame per Task") - group: str = SettingsField("", title="Group Name") - job_delay: str = SettingsField( - "", title="Delay job (timecode dd:hh:mm:ss)" - ) - - -class AOVFilterSubmodel(BaseSettingsModel): - _layout = "expanded" - name: str = SettingsField(title="Host") - value: list[str] = SettingsField( - default_factory=list, - title="AOV regex" - ) - - -class ProcessCacheJobFarmModel(BaseSettingsModel): - """Process submitted job on farm.""" - - enabled: bool = SettingsField(title="Enabled") - deadline_department: str = SettingsField(title="Department") - deadline_pool: str = SettingsField(title="Pool") - deadline_group: str = SettingsField(title="Group") - deadline_chunk_size: int = SettingsField(title="Chunk Size") - deadline_priority: int = SettingsField(title="Priority") - - -class ProcessSubmittedJobOnFarmModel(BaseSettingsModel): - """Process submitted job on farm.""" - - enabled: bool = SettingsField(title="Enabled") - deadline_department: str = SettingsField(title="Department") - deadline_pool: str = SettingsField(title="Pool") - deadline_group: str = SettingsField(title="Group") - deadline_chunk_size: int = SettingsField(title="Chunk Size") - deadline_priority: int = SettingsField(title="Priority") - publishing_script: str = SettingsField(title="Publishing script path") - skip_integration_repre_list: list[str] = SettingsField( - default_factory=list, - title="Skip integration of representation with ext" - ) - families_transfer: list[str] = SettingsField( - default_factory=list, - title=( - "List of family names to transfer\n" - "to generated instances (AOVs for example)." - ) - ) - aov_filter: list[AOVFilterSubmodel] = SettingsField( - default_factory=list, - title="Reviewable products filter", - ) - - @validator("aov_filter") - def validate_unique_names(cls, value): - ensure_unique_names(value) - return value - - -class PublishPluginsModel(BaseSettingsModel): - CollectDeadlinePools: CollectDeadlinePoolsModel = SettingsField( - default_factory=CollectDeadlinePoolsModel, - title="Default Pools") - ValidateExpectedFiles: ValidateExpectedFilesModel = SettingsField( - default_factory=ValidateExpectedFilesModel, - title="Validate Expected Files" - ) - AfterEffectsSubmitDeadline: AfterEffectsSubmitDeadlineModel = ( - SettingsField( - default_factory=AfterEffectsSubmitDeadlineModel, - title="After Effects to deadline", - section="Hosts" - ) - ) - BlenderSubmitDeadline: BlenderSubmitDeadlineModel = SettingsField( - default_factory=BlenderSubmitDeadlineModel, - title="Blender Submit Deadline") - CelactionSubmitDeadline: CelactionSubmitDeadlineModel = SettingsField( - default_factory=CelactionSubmitDeadlineModel, - title="Celaction Submit Deadline") - FusionSubmitDeadline: FusionSubmitDeadlineModel = SettingsField( - default_factory=FusionSubmitDeadlineModel, - title="Fusion submit to Deadline") - HarmonySubmitDeadline: HarmonySubmitDeadlineModel = SettingsField( - default_factory=HarmonySubmitDeadlineModel, - title="Harmony Submit to deadline") - HoudiniCacheSubmitDeadline: HoudiniCacheSubmitDeadlineModel = SettingsField( - default_factory=HoudiniCacheSubmitDeadlineModel, - title="Houdini Submit cache to deadline") - HoudiniSubmitDeadline: HoudiniSubmitDeadlineModel = SettingsField( - default_factory=HoudiniSubmitDeadlineModel, - title="Houdini Submit render to deadline") - MaxSubmitDeadline: MaxSubmitDeadlineModel = SettingsField( - default_factory=MaxSubmitDeadlineModel, - title="Max Submit to deadline") - MayaSubmitDeadline: MayaSubmitDeadlineModel = SettingsField( - default_factory=MayaSubmitDeadlineModel, - title="Maya Submit to deadline") - NukeSubmitDeadline: NukeSubmitDeadlineModel = SettingsField( - default_factory=NukeSubmitDeadlineModel, - title="Nuke Submit to deadline") - ProcessSubmittedCacheJobOnFarm: ProcessCacheJobFarmModel = SettingsField( - default_factory=ProcessCacheJobFarmModel, - title="Process submitted cache Job on farm", - section="Publish Jobs") - ProcessSubmittedJobOnFarm: ProcessSubmittedJobOnFarmModel = SettingsField( - default_factory=ProcessSubmittedJobOnFarmModel, - title="Process submitted job on farm") - - -DEFAULT_DEADLINE_PLUGINS_SETTINGS = { - "CollectDeadlinePools": { - "primary_pool": "", - "secondary_pool": "" - }, - "ValidateExpectedFiles": { - "enabled": True, - "active": True, - "allow_user_override": True, - "families": [ - "render" - ], - "targets": [ - "deadline" - ] - }, - "AfterEffectsSubmitDeadline": { - "enabled": True, - "optional": False, - "active": True, - "use_published": True, - "priority": 50, - "chunk_size": 10000, - "group": "", - "department": "", - "multiprocess": True - }, - "BlenderSubmitDeadline": { - "enabled": True, - "optional": False, - "active": True, - "use_published": True, - "asset_dependencies": True, - "priority": 50, - "chunk_size": 10, - "group": "none", - "job_delay": "00:00:00:00" - }, - "CelactionSubmitDeadline": { - "enabled": True, - "deadline_department": "", - "deadline_priority": 50, - "deadline_pool": "", - "deadline_pool_secondary": "", - "deadline_group": "", - "deadline_chunk_size": 10, - "deadline_job_delay": "00:00:00:00" - }, - "FusionSubmitDeadline": { - "enabled": True, - "optional": False, - "active": True, - "priority": 50, - "chunk_size": 10, - "concurrent_tasks": 1, - "group": "" - }, - "HarmonySubmitDeadline": { - "enabled": True, - "optional": False, - "active": True, - "use_published": True, - "priority": 50, - "chunk_size": 10000, - "group": "", - "department": "" - }, - "HoudiniCacheSubmitDeadline": { - "enabled": True, - "optional": False, - "active": True, - "priority": 50, - "chunk_size": 999999, - "group": "" - }, - "HoudiniSubmitDeadline": { - "enabled": True, - "optional": False, - "active": True, - "priority": 50, - "chunk_size": 1, - "group": "", - "export_priority": 50, - "export_chunk_size": 10, - "export_group": "" - }, - "MaxSubmitDeadline": { - "enabled": True, - "optional": False, - "active": True, - "use_published": True, - "priority": 50, - "chunk_size": 10, - "group": "none" - }, - "MayaSubmitDeadline": { - "enabled": True, - "optional": False, - "active": True, - "tile_assembler_plugin": "DraftTileAssembler", - "use_published": True, - "import_reference": False, - "asset_dependencies": True, - "strict_error_checking": True, - "priority": 50, - "tile_priority": 50, - "group": "none", - "limit": [], - # this used to be empty dict - "jobInfo": "", - # this used to be empty dict - "pluginInfo": "", - "scene_patches": [] - }, - "NukeSubmitDeadline": { - "enabled": True, - "optional": False, - "active": True, - "priority": 50, - "chunk_size": 10, - "concurrent_tasks": 1, - "group": "", - "department": "", - "use_gpu": True, - "workfile_dependency": True, - "use_published_workfile": True, - "env_allowed_keys": [], - "env_search_replace_values": [], - "limit_groups": [] - }, - "ProcessSubmittedCacheJobOnFarm": { - "enabled": True, - "deadline_department": "", - "deadline_pool": "", - "deadline_group": "", - "deadline_chunk_size": 1, - "deadline_priority": 50 - }, - "ProcessSubmittedJobOnFarm": { - "enabled": True, - "deadline_department": "", - "deadline_pool": "", - "deadline_group": "", - "deadline_chunk_size": 1, - "deadline_priority": 50, - "publishing_script": "", - "skip_integration_repre_list": [], - "families_transfer": ["render3d", "render2d", "ftrack", "slate"], - "aov_filter": [ - { - "name": "maya", - "value": [ - ".*([Bb]eauty).*" - ] - }, - { - "name": "blender", - "value": [ - ".*([Bb]eauty).*" - ] - }, - { - "name": "aftereffects", - "value": [ - ".*" - ] - }, - { - "name": "celaction", - "value": [ - ".*" - ] - }, - { - "name": "harmony", - "value": [ - ".*" - ] - }, - { - "name": "max", - "value": [ - ".*" - ] - }, - { - "name": "fusion", - "value": [ - ".*" - ] - } - ] - } -} diff --git a/server_addon/deadline/server/settings/site_settings.py b/server_addon/deadline/server/settings/site_settings.py deleted file mode 100644 index 92c092324e..0000000000 --- a/server_addon/deadline/server/settings/site_settings.py +++ /dev/null @@ -1,28 +0,0 @@ -from ayon_server.settings import ( - BaseSettingsModel, - SettingsField, -) - -from .main import defined_deadline_ws_name_enum_resolver - - -class CredentialPerServerModel(BaseSettingsModel): - """Provide credentials for configured DL servers""" - _layout = "expanded" - server_name: str = SettingsField( - "", - title="DL server name", - enum_resolver=defined_deadline_ws_name_enum_resolver - ) - username: str = SettingsField("", title="Username") - password: str = SettingsField("", title="Password") - - -class DeadlineSiteSettings(BaseSettingsModel): - local_settings: list[CredentialPerServerModel] = SettingsField( - default_factory=list, - title="Local setting", - description=( - "Please provide credentials for configured Deadline servers" - ), - ) diff --git a/server_addon/max/client/ayon_max/__init__.py b/server_addon/max/client/ayon_max/__init__.py deleted file mode 100644 index 77293f9aa9..0000000000 --- a/server_addon/max/client/ayon_max/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -from .version import __version__ -from .addon import ( - MaxAddon, - MAX_HOST_DIR, -) - - -__all__ = ( - "__version__", - - "MaxAddon", - "MAX_HOST_DIR", -) diff --git a/server_addon/max/client/ayon_max/addon.py b/server_addon/max/client/ayon_max/addon.py deleted file mode 100644 index 9cc0cda1ee..0000000000 --- a/server_addon/max/client/ayon_max/addon.py +++ /dev/null @@ -1,28 +0,0 @@ -# -*- coding: utf-8 -*- -import os -from ayon_core.addon import AYONAddon, IHostAddon - -from .version import __version__ - -MAX_HOST_DIR = os.path.dirname(os.path.abspath(__file__)) - - -class MaxAddon(AYONAddon, IHostAddon): - name = "max" - version = __version__ - host_name = "max" - - def add_implementation_envs(self, env, _app): - # Remove auto screen scale factor for Qt - # - let 3dsmax decide it's value - env.pop("QT_AUTO_SCREEN_SCALE_FACTOR", None) - - def get_workfile_extensions(self): - return [".max"] - - def get_launch_hook_paths(self, app): - if app.host_name != self.host_name: - return [] - return [ - os.path.join(MAX_HOST_DIR, "hooks") - ] diff --git a/server_addon/max/client/ayon_max/api/__init__.py b/server_addon/max/client/ayon_max/api/__init__.py deleted file mode 100644 index 92097cc98b..0000000000 --- a/server_addon/max/client/ayon_max/api/__init__.py +++ /dev/null @@ -1,20 +0,0 @@ -# -*- coding: utf-8 -*- -"""Public API for 3dsmax""" - -from .pipeline import ( - MaxHost, -) - - -from .lib import ( - maintained_selection, - lsattr, - get_all_children -) - -__all__ = [ - "MaxHost", - "maintained_selection", - "lsattr", - "get_all_children" -] diff --git a/server_addon/max/client/ayon_max/api/action.py b/server_addon/max/client/ayon_max/api/action.py deleted file mode 100644 index bed72bc493..0000000000 --- a/server_addon/max/client/ayon_max/api/action.py +++ /dev/null @@ -1,42 +0,0 @@ -from pymxs import runtime as rt - -import pyblish.api - -from ayon_core.pipeline.publish import get_errored_instances_from_context - - -class SelectInvalidAction(pyblish.api.Action): - """Select invalid objects in Blender when a publish plug-in failed.""" - label = "Select Invalid" - on = "failed" - icon = "search" - - def process(self, context, plugin): - errored_instances = get_errored_instances_from_context(context, - plugin=plugin) - - # Get the invalid nodes for the plug-ins - self.log.info("Finding invalid nodes...") - invalid = list() - for instance in errored_instances: - invalid_nodes = plugin.get_invalid(instance) - if invalid_nodes: - if isinstance(invalid_nodes, (list, tuple)): - invalid.extend(invalid_nodes) - else: - self.log.warning( - "Failed plug-in doesn't have any selectable objects." - ) - - if not invalid: - self.log.info("No invalid nodes found.") - return - invalid_names = [obj.name for obj in invalid if not isinstance(obj, tuple)] - if not invalid_names: - invalid_names = [obj.name for obj, _ in invalid] - invalid = [obj for obj, _ in invalid] - self.log.info( - "Selecting invalid objects: %s", ", ".join(invalid_names) - ) - - rt.Select(invalid) diff --git a/server_addon/max/client/ayon_max/api/colorspace.py b/server_addon/max/client/ayon_max/api/colorspace.py deleted file mode 100644 index fafee4ee04..0000000000 --- a/server_addon/max/client/ayon_max/api/colorspace.py +++ /dev/null @@ -1,50 +0,0 @@ -import attr -from pymxs import runtime as rt - - -@attr.s -class LayerMetadata(object): - """Data class for Render Layer metadata.""" - frameStart = attr.ib() - frameEnd = attr.ib() - - -@attr.s -class RenderProduct(object): - """Getting Colorspace as - Specific Render Product Parameter for submitting - publish job. - """ - colorspace = attr.ib() # colorspace - view = attr.ib() - productName = attr.ib(default=None) - - -class ARenderProduct(object): - - def __init__(self): - """Constructor.""" - # Initialize - self.layer_data = self._get_layer_data() - self.layer_data.products = self.get_colorspace_data() - - def _get_layer_data(self): - return LayerMetadata( - frameStart=int(rt.rendStart), - frameEnd=int(rt.rendEnd), - ) - - def get_colorspace_data(self): - """To be implemented by renderer class. - This should return a list of RenderProducts. - Returns: - list: List of RenderProduct - """ - colorspace_data = [ - RenderProduct( - colorspace="sRGB", - view="ACES 1.0", - productName="" - ) - ] - return colorspace_data diff --git a/server_addon/max/client/ayon_max/api/lib.py b/server_addon/max/client/ayon_max/api/lib.py deleted file mode 100644 index 7acc18196f..0000000000 --- a/server_addon/max/client/ayon_max/api/lib.py +++ /dev/null @@ -1,589 +0,0 @@ -# -*- coding: utf-8 -*- -"""Library of functions useful for 3dsmax pipeline.""" -import contextlib -import logging -import json -from typing import Any, Dict, Union - -import six - -from ayon_core.pipeline import ( - get_current_project_name, - colorspace -) -from ayon_core.settings import get_project_settings -from ayon_core.pipeline.context_tools import ( - get_current_task_entity -) -from ayon_core.style import load_stylesheet -from pymxs import runtime as rt - - -JSON_PREFIX = "JSON::" -log = logging.getLogger("ayon_max") - - -def get_main_window(): - """Acquire Max's main window""" - from qtpy import QtWidgets - top_widgets = QtWidgets.QApplication.topLevelWidgets() - name = "QmaxApplicationWindow" - for widget in top_widgets: - if ( - widget.inherits("QMainWindow") - and widget.metaObject().className() == name - ): - return widget - raise RuntimeError('Count not find 3dsMax main window.') - - -def imprint(node_name: str, data: dict) -> bool: - node = rt.GetNodeByName(node_name) - if not node: - return False - - for k, v in data.items(): - if isinstance(v, (dict, list)): - rt.SetUserProp(node, k, f"{JSON_PREFIX}{json.dumps(v)}") - else: - rt.SetUserProp(node, k, v) - - return True - - -def lsattr( - attr: str, - value: Union[str, None] = None, - root: Union[str, None] = None) -> list: - """List nodes having attribute with specified value. - - Args: - attr (str): Attribute name to match. - value (str, Optional): Value to match, of omitted, all nodes - with specified attribute are returned no matter of value. - root (str, Optional): Root node name. If omitted, scene root is used. - - Returns: - list of nodes. - """ - root = rt.RootNode if root is None else rt.GetNodeByName(root) - - def output_node(node, nodes): - nodes.append(node) - for child in node.Children: - output_node(child, nodes) - - nodes = [] - output_node(root, nodes) - return [ - n for n in nodes - if rt.GetUserProp(n, attr) == value - ] if value else [ - n for n in nodes - if rt.GetUserProp(n, attr) - ] - - -def read(container) -> dict: - data = {} - props = rt.GetUserPropBuffer(container) - # this shouldn't happen but let's guard against it anyway - if not props: - return data - - for line in props.split("\r\n"): - try: - key, value = line.split("=") - except ValueError: - # if the line cannot be split we can't really parse it - continue - - value = value.strip() - if isinstance(value.strip(), six.string_types) and \ - value.startswith(JSON_PREFIX): - with contextlib.suppress(json.JSONDecodeError): - value = json.loads(value[len(JSON_PREFIX):]) - - # default value behavior - # convert maxscript boolean values - if value == "true": - value = True - elif value == "false": - value = False - - data[key.strip()] = value - - data["instance_node"] = container.Name - - return data - - -@contextlib.contextmanager -def maintained_selection(): - previous_selection = rt.GetCurrentSelection() - try: - yield - finally: - if previous_selection: - rt.Select(previous_selection) - else: - rt.Select() - - -def get_all_children(parent, node_type=None): - """Handy function to get all the children of a given node - - Args: - parent (3dsmax Node1): Node to get all children of. - node_type (None, runtime.class): give class to check for - e.g. rt.FFDBox/rt.GeometryClass etc. - - Returns: - list: list of all children of the parent node - """ - def list_children(node): - children = [] - for c in node.Children: - children.append(c) - children = children + list_children(c) - return children - child_list = list_children(parent) - - return ([x for x in child_list if rt.SuperClassOf(x) == node_type] - if node_type else child_list) - - -def get_current_renderer(): - """ - Notes: - Get current renderer for Max - - Returns: - "{Current Renderer}:{Current Renderer}" - e.g. "Redshift_Renderer:Redshift_Renderer" - """ - return rt.renderers.production - - -def get_default_render_folder(project_setting=None): - return (project_setting["max"] - ["RenderSettings"] - ["default_render_image_folder"]) - - -def set_render_frame_range(start_frame, end_frame): - """ - Note: - Frame range can be specified in different types. Possible values are: - * `1` - Single frame. - * `2` - Active time segment ( animationRange ). - * `3` - User specified Range. - * `4` - User specified Frame pickup string (for example `1,3,5-12`). - - Todo: - Current type is hard-coded, there should be a custom setting for this. - """ - rt.rendTimeType = 3 - if start_frame is not None and end_frame is not None: - rt.rendStart = int(start_frame) - rt.rendEnd = int(end_frame) - - -def get_multipass_setting(project_setting=None): - return (project_setting["max"] - ["RenderSettings"] - ["multipass"]) - - -def set_scene_resolution(width: int, height: int): - """Set the render resolution - - Args: - width(int): value of the width - height(int): value of the height - - Returns: - None - - """ - # make sure the render dialog is closed - # for the update of resolution - # Changing the Render Setup dialog settings should be done - # with the actual Render Setup dialog in a closed state. - if rt.renderSceneDialog.isOpen(): - rt.renderSceneDialog.close() - - rt.renderWidth = width - rt.renderHeight = height - - -def reset_scene_resolution(): - """Apply the scene resolution from the project definition - - scene resolution can be overwritten by a folder if the folder.attrib - contains any information regarding scene resolution. - """ - task_attributes = get_current_task_entity(fields={"attrib"})["attrib"] - width = int(task_attributes["resolutionWidth"]) - height = int(task_attributes["resolutionHeight"]) - - set_scene_resolution(width, height) - - -def get_frame_range(task_entity=None) -> Union[Dict[str, Any], None]: - """Get the current task frame range and handles - - Args: - task_entity (dict): Task Entity. - - Returns: - dict: with frame start, frame end, handle start, handle end. - """ - # Set frame start/end - if task_entity is None: - task_entity = get_current_task_entity(fields={"attrib"}) - task_attributes = task_entity["attrib"] - frame_start = int(task_attributes["frameStart"]) - frame_end = int(task_attributes["frameEnd"]) - handle_start = int(task_attributes["handleStart"]) - handle_end = int(task_attributes["handleEnd"]) - frame_start_handle = frame_start - handle_start - frame_end_handle = frame_end + handle_end - - return { - "frameStart": frame_start, - "frameEnd": frame_end, - "handleStart": handle_start, - "handleEnd": handle_end, - "frameStartHandle": frame_start_handle, - "frameEndHandle": frame_end_handle, - } - - -def reset_frame_range(fps: bool = True): - """Set frame range to current folder. - This is part of 3dsmax documentation: - - animationRange: A System Global variable which lets you get and - set an Interval value that defines the start and end frames - of the Active Time Segment. - frameRate: A System Global variable which lets you get - and set an Integer value that defines the current - scene frame rate in frames-per-second. - """ - if fps: - rt.frameRate = float(get_fps_for_current_context()) - - frame_range = get_frame_range() - - set_timeline( - frame_range["frameStartHandle"], frame_range["frameEndHandle"]) - set_render_frame_range( - frame_range["frameStartHandle"], frame_range["frameEndHandle"]) - - -def get_fps_for_current_context(): - """Get fps that should be set for current context. - - Todos: - - Skip project value. - - Merge logic with 'get_frame_range' and 'reset_scene_resolution' -> - all the values in the functions can be collected at one place as - they have same requirements. - - Returns: - Union[int, float]: FPS value. - """ - task_entity = get_current_task_entity(fields={"attrib"}) - return task_entity["attrib"]["fps"] - - -def reset_unit_scale(): - """Apply the unit scale setting to 3dsMax - """ - project_name = get_current_project_name() - settings = get_project_settings(project_name).get("max") - scene_scale = settings.get("unit_scale_settings", - {}).get("scene_unit_scale") - if scene_scale: - rt.units.DisplayType = rt.Name("Metric") - rt.units.MetricType = rt.Name(scene_scale) - else: - rt.units.DisplayType = rt.Name("Generic") - - -def convert_unit_scale(): - """Convert system unit scale in 3dsMax - for fbx export - - Returns: - str: unit scale - """ - unit_scale_dict = { - "millimeters": "mm", - "centimeters": "cm", - "meters": "m", - "kilometers": "km" - } - current_unit_scale = rt.Execute("units.MetricType as string") - return unit_scale_dict[current_unit_scale] - - -def set_context_setting(): - """Apply the project settings from the project definition - - Settings can be overwritten by an folder if the folder.attrib contains - any information regarding those settings. - - Examples of settings: - frame range - resolution - - Returns: - None - """ - reset_scene_resolution() - reset_frame_range() - reset_colorspace() - reset_unit_scale() - - -def get_max_version(): - """ - Args: - get max version date for deadline - - Returns: - #(25000, 62, 0, 25, 0, 0, 997, 2023, "") - max_info[7] = max version date - """ - max_info = rt.MaxVersion() - return max_info[7] - - -def is_headless(): - """Check if 3dsMax runs in batch mode. - If it returns True, it runs in 3dsbatch.exe - If it returns False, it runs in 3dsmax.exe - """ - return rt.maxops.isInNonInteractiveMode() - - -def set_timeline(frameStart, frameEnd): - """Set frame range for timeline editor in Max - """ - rt.animationRange = rt.interval(int(frameStart), int(frameEnd)) - return rt.animationRange - - -def reset_colorspace(): - """OCIO Configuration - Supports in 3dsMax 2024+ - - """ - if int(get_max_version()) < 2024: - return - - max_config_data = colorspace.get_current_context_imageio_config_preset() - if max_config_data: - ocio_config_path = max_config_data["path"] - colorspace_mgr = rt.ColorPipelineMgr - colorspace_mgr.Mode = rt.Name("OCIO_Custom") - colorspace_mgr.OCIOConfigPath = ocio_config_path - - -def check_colorspace(): - parent = get_main_window() - if parent is None: - log.info("Skipping outdated pop-up " - "because Max main window can't be found.") - if int(get_max_version()) >= 2024: - color_mgr = rt.ColorPipelineMgr - max_config_data = colorspace.get_current_context_imageio_config_preset() - if max_config_data and color_mgr.Mode != rt.Name("OCIO_Custom"): - if not is_headless(): - from ayon_core.tools.utils import SimplePopup - dialog = SimplePopup(parent=parent) - dialog.setWindowTitle("Warning: Wrong OCIO Mode") - dialog.set_message("This scene has wrong OCIO " - "Mode setting.") - dialog.set_button_text("Fix") - dialog.setStyleSheet(load_stylesheet()) - dialog.on_clicked.connect(reset_colorspace) - dialog.show() - -def unique_namespace(namespace, format="%02d", - prefix="", suffix="", con_suffix="CON"): - """Return unique namespace - - Arguments: - namespace (str): Name of namespace to consider - format (str, optional): Formatting of the given iteration number - suffix (str, optional): Only consider namespaces with this suffix. - con_suffix: max only, for finding the name of the master container - - >>> unique_namespace("bar") - # bar01 - >>> unique_namespace(":hello") - # :hello01 - >>> unique_namespace("bar:", suffix="_NS") - # bar01_NS: - - """ - - def current_namespace(): - current = namespace - # When inside a namespace Max adds no trailing : - if not current.endswith(":"): - current += ":" - return current - - # Always check against the absolute namespace root - # There's no clash with :x if we're defining namespace :a:x - ROOT = ":" if namespace.startswith(":") else current_namespace() - - # Strip trailing `:` tokens since we might want to add a suffix - start = ":" if namespace.startswith(":") else "" - end = ":" if namespace.endswith(":") else "" - namespace = namespace.strip(":") - if ":" in namespace: - # Split off any nesting that we don't uniqify anyway. - parents, namespace = namespace.rsplit(":", 1) - start += parents + ":" - ROOT += start - - iteration = 1 - increment_version = True - while increment_version: - nr_namespace = namespace + format % iteration - unique = prefix + nr_namespace + suffix - container_name = f"{unique}:{namespace}{con_suffix}" - if not rt.getNodeByName(container_name): - name_space = start + unique + end - increment_version = False - return name_space - else: - increment_version = True - iteration += 1 - - -def get_namespace(container_name): - """Get the namespace and name of the sub-container - - Args: - container_name (str): the name of master container - - Raises: - RuntimeError: when there is no master container found - - Returns: - namespace (str): namespace of the sub-container - name (str): name of the sub-container - """ - node = rt.getNodeByName(container_name) - if not node: - raise RuntimeError("Master Container Not Found..") - name = rt.getUserProp(node, "name") - namespace = rt.getUserProp(node, "namespace") - return namespace, name - - -def object_transform_set(container_children): - """A function which allows to store the transform of - previous loaded object(s) - Args: - container_children(list): A list of nodes - - Returns: - transform_set (dict): A dict with all transform data of - the previous loaded object(s) - """ - transform_set = {} - for node in container_children: - name = f"{node}.transform" - transform_set[name] = node.pos - name = f"{node}.scale" - transform_set[name] = node.scale - return transform_set - - -def get_plugins() -> list: - """Get all loaded plugins in 3dsMax - - Returns: - plugin_info_list: a list of loaded plugins - """ - manager = rt.PluginManager - count = manager.pluginDllCount - plugin_info_list = [] - for p in range(1, count + 1): - plugin_info = manager.pluginDllName(p) - plugin_info_list.append(plugin_info) - - return plugin_info_list - - -def update_modifier_node_names(event, node): - """Update the name of the nodes after renaming - - Args: - event (pymxs.MXSWrapperBase): Event Name ( - Mandatory argument for rt.NodeEventCallback) - node (list): Event Number ( - Mandatory argument for rt.NodeEventCallback) - - """ - containers = [ - obj - for obj in rt.Objects - if ( - rt.ClassOf(obj) == rt.Container - and rt.getUserProp(obj, "id") == "pyblish.avalon.instance" - and rt.getUserProp(obj, "productType") not in { - "workfile", "tyflow" - } - ) - ] - if not containers: - return - for container in containers: - ayon_data = container.modifiers[0].openPypeData - updated_node_names = [str(node.node) for node - in ayon_data.all_handles] - rt.setProperty(ayon_data, "sel_list", updated_node_names) - - -@contextlib.contextmanager -def render_resolution(width, height): - """Set render resolution option during context - - Args: - width (int): render width - height (int): render height - """ - current_renderWidth = rt.renderWidth - current_renderHeight = rt.renderHeight - try: - rt.renderWidth = width - rt.renderHeight = height - yield - finally: - rt.renderWidth = current_renderWidth - rt.renderHeight = current_renderHeight - - -@contextlib.contextmanager -def suspended_refresh(): - """Suspended refresh for scene and modify panel redraw. - """ - if is_headless(): - yield - return - rt.disableSceneRedraw() - rt.suspendEditing() - try: - yield - - finally: - rt.enableSceneRedraw() - rt.resumeEditing() diff --git a/server_addon/max/client/ayon_max/api/lib_renderproducts.py b/server_addon/max/client/ayon_max/api/lib_renderproducts.py deleted file mode 100644 index 82a6a0c20c..0000000000 --- a/server_addon/max/client/ayon_max/api/lib_renderproducts.py +++ /dev/null @@ -1,275 +0,0 @@ -# Render Element Example : For scanline render, VRay -# https://help.autodesk.com/view/MAXDEV/2022/ENU/?guid=GUID-E8F75D47-B998-4800-A3A5-610E22913CFC -# arnold -# https://help.autodesk.com/view/ARNOL/ENU/?guid=arnold_for_3ds_max_ax_maxscript_commands_ax_renderview_commands_html -import os - -from pymxs import runtime as rt - -from ayon_max.api.lib import get_current_renderer -from ayon_core.pipeline import get_current_project_name -from ayon_core.settings import get_project_settings - - -class RenderProducts(object): - - def __init__(self, project_settings=None): - self._project_settings = project_settings - if not self._project_settings: - self._project_settings = get_project_settings( - get_current_project_name() - ) - - def get_beauty(self, container): - render_dir = os.path.dirname(rt.rendOutputFilename) - - output_file = os.path.join(render_dir, container) - - setting = self._project_settings - img_fmt = setting["max"]["RenderSettings"]["image_format"] # noqa - - start_frame = int(rt.rendStart) - end_frame = int(rt.rendEnd) + 1 - - return { - "beauty": self.get_expected_beauty( - output_file, start_frame, end_frame, img_fmt - ) - } - - def get_multiple_beauty(self, outputs, cameras): - beauty_output_frames = dict() - for output, camera in zip(outputs, cameras): - filename, ext = os.path.splitext(output) - filename = filename.replace(".", "") - ext = ext.replace(".", "") - start_frame = int(rt.rendStart) - end_frame = int(rt.rendEnd) + 1 - new_beauty = self.get_expected_beauty( - filename, start_frame, end_frame, ext - ) - beauty_output = ({ - f"{camera}_beauty": new_beauty - }) - beauty_output_frames.update(beauty_output) - return beauty_output_frames - - def get_multiple_aovs(self, outputs, cameras): - renderer_class = get_current_renderer() - renderer = str(renderer_class).split(":")[0] - aovs_frames = {} - for output, camera in zip(outputs, cameras): - filename, ext = os.path.splitext(output) - filename = filename.replace(".", "") - ext = ext.replace(".", "") - start_frame = int(rt.rendStart) - end_frame = int(rt.rendEnd) + 1 - - if renderer in [ - "ART_Renderer", - "V_Ray_6_Hotfix_3", - "V_Ray_GPU_6_Hotfix_3", - "Default_Scanline_Renderer", - "Quicksilver_Hardware_Renderer", - ]: - render_name = self.get_render_elements_name() - if render_name: - for name in render_name: - aovs_frames.update({ - f"{camera}_{name}": self.get_expected_aovs( - filename, name, start_frame, - end_frame, ext) - }) - elif renderer == "Redshift_Renderer": - render_name = self.get_render_elements_name() - if render_name: - rs_aov_files = rt.Execute("renderers.current.separateAovFiles") # noqa - # this doesn't work, always returns False - # rs_AovFiles = rt.RedShift_Renderer().separateAovFiles - if ext == "exr" and not rs_aov_files: - for name in render_name: - if name == "RsCryptomatte": - aovs_frames.update({ - f"{camera}_{name}": self.get_expected_aovs( - filename, name, start_frame, - end_frame, ext) - }) - else: - for name in render_name: - aovs_frames.update({ - f"{camera}_{name}": self.get_expected_aovs( - filename, name, start_frame, - end_frame, ext) - }) - elif renderer == "Arnold": - render_name = self.get_arnold_product_name() - if render_name: - for name in render_name: - aovs_frames.update({ - f"{camera}_{name}": self.get_expected_arnold_product( # noqa - filename, name, start_frame, - end_frame, ext) - }) - elif renderer in [ - "V_Ray_6_Hotfix_3", - "V_Ray_GPU_6_Hotfix_3" - ]: - if ext != "exr": - render_name = self.get_render_elements_name() - if render_name: - for name in render_name: - aovs_frames.update({ - f"{camera}_{name}": self.get_expected_aovs( - filename, name, start_frame, - end_frame, ext) - }) - - return aovs_frames - - def get_aovs(self, container): - render_dir = os.path.dirname(rt.rendOutputFilename) - - output_file = os.path.join(render_dir, - container) - - setting = self._project_settings - img_fmt = setting["max"]["RenderSettings"]["image_format"] # noqa - - start_frame = int(rt.rendStart) - end_frame = int(rt.rendEnd) + 1 - renderer_class = get_current_renderer() - renderer = str(renderer_class).split(":")[0] - render_dict = {} - - if renderer in [ - "ART_Renderer", - "V_Ray_6_Hotfix_3", - "V_Ray_GPU_6_Hotfix_3", - "Default_Scanline_Renderer", - "Quicksilver_Hardware_Renderer", - ]: - render_name = self.get_render_elements_name() - if render_name: - for name in render_name: - render_dict.update({ - name: self.get_expected_aovs( - output_file, name, start_frame, - end_frame, img_fmt) - }) - elif renderer == "Redshift_Renderer": - render_name = self.get_render_elements_name() - if render_name: - rs_aov_files = rt.Execute("renderers.current.separateAovFiles") - # this doesn't work, always returns False - # rs_AovFiles = rt.RedShift_Renderer().separateAovFiles - if img_fmt == "exr" and not rs_aov_files: - for name in render_name: - if name == "RsCryptomatte": - render_dict.update({ - name: self.get_expected_aovs( - output_file, name, start_frame, - end_frame, img_fmt) - }) - else: - for name in render_name: - render_dict.update({ - name: self.get_expected_aovs( - output_file, name, start_frame, - end_frame, img_fmt) - }) - - elif renderer == "Arnold": - render_name = self.get_arnold_product_name() - if render_name: - for name in render_name: - render_dict.update({ - name: self.get_expected_arnold_product( - output_file, name, start_frame, - end_frame, img_fmt) - }) - elif renderer in [ - "V_Ray_6_Hotfix_3", - "V_Ray_GPU_6_Hotfix_3" - ]: - if img_fmt != "exr": - render_name = self.get_render_elements_name() - if render_name: - for name in render_name: - render_dict.update({ - name: self.get_expected_aovs( - output_file, name, start_frame, - end_frame, img_fmt) # noqa - }) - - return render_dict - - def get_expected_beauty(self, folder, start_frame, end_frame, fmt): - beauty_frame_range = [] - for f in range(start_frame, end_frame): - frame = "%04d" % f - beauty_output = f"{folder}.{frame}.{fmt}" - beauty_output = beauty_output.replace("\\", "/") - beauty_frame_range.append(beauty_output) - - return beauty_frame_range - - def get_arnold_product_name(self): - """Get all the Arnold AOVs name""" - aov_name = [] - - amw = rt.MaxToAOps.AOVsManagerWindow() - aov_mgr = rt.renderers.current.AOVManager - # Check if there is any aov group set in AOV manager - aov_group_num = len(aov_mgr.drivers) - if aov_group_num < 1: - return - for i in range(aov_group_num): - # get the specific AOV group - aov_name.extend(aov.name for aov in aov_mgr.drivers[i].aov_list) - # close the AOVs manager window - amw.close() - - return aov_name - - def get_expected_arnold_product(self, folder, name, - start_frame, end_frame, fmt): - """Get all the expected Arnold AOVs""" - aov_list = [] - for f in range(start_frame, end_frame): - frame = "%04d" % f - render_element = f"{folder}_{name}.{frame}.{fmt}" - render_element = render_element.replace("\\", "/") - aov_list.append(render_element) - - return aov_list - - def get_render_elements_name(self): - """Get all the render element names for general """ - render_name = [] - render_elem = rt.maxOps.GetCurRenderElementMgr() - render_elem_num = render_elem.NumRenderElements() - if render_elem_num < 1: - return - # get render elements from the renders - for i in range(render_elem_num): - renderlayer_name = render_elem.GetRenderElement(i) - if renderlayer_name.enabled: - target, renderpass = str(renderlayer_name).split(":") - render_name.append(renderpass) - - return render_name - - def get_expected_aovs(self, folder, name, - start_frame, end_frame, fmt): - """Get all the expected render element output files. """ - render_elements = [] - for f in range(start_frame, end_frame): - frame = "%04d" % f - render_element = f"{folder}_{name}.{frame}.{fmt}" - render_element = render_element.replace("\\", "/") - render_elements.append(render_element) - - return render_elements - - def image_format(self): - return self._project_settings["max"]["RenderSettings"]["image_format"] # noqa diff --git a/server_addon/max/client/ayon_max/api/lib_rendersettings.py b/server_addon/max/client/ayon_max/api/lib_rendersettings.py deleted file mode 100644 index 4b65e1397e..0000000000 --- a/server_addon/max/client/ayon_max/api/lib_rendersettings.py +++ /dev/null @@ -1,227 +0,0 @@ -import os -from pymxs import runtime as rt -from ayon_core.lib import Logger -from ayon_core.settings import get_project_settings -from ayon_core.pipeline import get_current_project_name -from ayon_core.pipeline.context_tools import get_current_folder_entity - -from ayon_max.api.lib import ( - set_render_frame_range, - get_current_renderer, - get_default_render_folder -) - - -class RenderSettings(object): - - log = Logger.get_logger("RenderSettings") - - _aov_chars = { - "dot": ".", - "dash": "-", - "underscore": "_" - } - - def __init__(self, project_settings=None): - """ - Set up the naming convention for the render - elements for the deadline submission - """ - - self._project_settings = project_settings - if not self._project_settings: - self._project_settings = get_project_settings( - get_current_project_name() - ) - - def set_render_camera(self, selection): - for sel in selection: - # to avoid Attribute Error from pymxs wrapper - if rt.classOf(sel) in rt.Camera.classes: - rt.viewport.setCamera(sel) - return - raise RuntimeError("Active Camera not found") - - def render_output(self, container): - folder = rt.maxFilePath - # hard-coded, should be customized in the setting - file = rt.maxFileName - folder = folder.replace("\\", "/") - # hard-coded, set the renderoutput path - setting = self._project_settings - render_folder = get_default_render_folder(setting) - filename, ext = os.path.splitext(file) - output_dir = os.path.join(folder, - render_folder, - filename) - if not os.path.exists(output_dir): - os.makedirs(output_dir) - # hard-coded, should be customized in the setting - folder_attributes = get_current_folder_entity()["attrib"] - - # get project resolution - width = folder_attributes.get("resolutionWidth") - height = folder_attributes.get("resolutionHeight") - # Set Frame Range - frame_start = folder_attributes.get("frame_start") - frame_end = folder_attributes.get("frame_end") - set_render_frame_range(frame_start, frame_end) - # get the production render - renderer_class = get_current_renderer() - renderer = str(renderer_class).split(":")[0] - - img_fmt = self._project_settings["max"]["RenderSettings"]["image_format"] # noqa - output = os.path.join(output_dir, container) - try: - aov_separator = self._aov_chars[( - self._project_settings["max"] - ["RenderSettings"] - ["aov_separator"] - )] - except KeyError: - aov_separator = "." - output_filename = f"{output}..{img_fmt}" - output_filename = output_filename.replace("{aov_separator}", - aov_separator) - rt.rendOutputFilename = output_filename - if renderer == "VUE_File_Renderer": - return - # TODO: Finish the arnold render setup - if renderer == "Arnold": - self.arnold_setup() - - if renderer in [ - "ART_Renderer", - "Redshift_Renderer", - "V_Ray_6_Hotfix_3", - "V_Ray_GPU_6_Hotfix_3", - "Default_Scanline_Renderer", - "Quicksilver_Hardware_Renderer", - ]: - self.render_element_layer(output, width, height, img_fmt) - - rt.rendSaveFile = True - - if rt.renderSceneDialog.isOpen(): - rt.renderSceneDialog.close() - - def arnold_setup(self): - # get Arnold RenderView run in the background - # for setting up renderable camera - arv = rt.MAXToAOps.ArnoldRenderView() - render_camera = rt.viewport.GetCamera() - if render_camera: - arv.setOption("Camera", str(render_camera)) - - # TODO: add AOVs and extension - img_fmt = self._project_settings["max"]["RenderSettings"]["image_format"] # noqa - setup_cmd = ( - f""" - amw = MaxtoAOps.AOVsManagerWindow() - amw.close() - aovmgr = renderers.current.AOVManager - aovmgr.drivers = #() - img_fmt = "{img_fmt}" - if img_fmt == "png" then driver = ArnoldPNGDriver() - if img_fmt == "jpg" then driver = ArnoldJPEGDriver() - if img_fmt == "exr" then driver = ArnoldEXRDriver() - if img_fmt == "tif" then driver = ArnoldTIFFDriver() - if img_fmt == "tiff" then driver = ArnoldTIFFDriver() - append aovmgr.drivers driver - aovmgr.drivers[1].aov_list = #() - """) - - rt.execute(setup_cmd) - arv.close() - - def render_element_layer(self, dir, width, height, ext): - """For Renderers with render elements""" - rt.renderWidth = width - rt.renderHeight = height - render_elem = rt.maxOps.GetCurRenderElementMgr() - render_elem_num = render_elem.NumRenderElements() - if render_elem_num < 0: - return - - for i in range(render_elem_num): - renderlayer_name = render_elem.GetRenderElement(i) - target, renderpass = str(renderlayer_name).split(":") - aov_name = f"{dir}_{renderpass}..{ext}" - render_elem.SetRenderElementFileName(i, aov_name) - - def get_render_output(self, container, output_dir): - output = os.path.join(output_dir, container) - img_fmt = self._project_settings["max"]["RenderSettings"]["image_format"] # noqa - output_filename = f"{output}..{img_fmt}" - return output_filename - - def get_render_element(self): - orig_render_elem = [] - render_elem = rt.maxOps.GetCurRenderElementMgr() - render_elem_num = render_elem.NumRenderElements() - if render_elem_num < 0: - return - - for i in range(render_elem_num): - render_element = render_elem.GetRenderElementFilename(i) - orig_render_elem.append(render_element) - - return orig_render_elem - - def get_batch_render_elements(self, container, - output_dir, camera): - render_element_list = list() - output = os.path.join(output_dir, container) - render_elem = rt.maxOps.GetCurRenderElementMgr() - render_elem_num = render_elem.NumRenderElements() - if render_elem_num < 0: - return - img_fmt = self._project_settings["max"]["RenderSettings"]["image_format"] # noqa - - for i in range(render_elem_num): - renderlayer_name = render_elem.GetRenderElement(i) - target, renderpass = str(renderlayer_name).split(":") - aov_name = f"{output}_{camera}_{renderpass}..{img_fmt}" - render_element_list.append(aov_name) - return render_element_list - - def get_batch_render_output(self, camera): - target_layer_no = rt.batchRenderMgr.FindView(camera) - target_layer = rt.batchRenderMgr.GetView(target_layer_no) - return target_layer.outputFilename - - def batch_render_elements(self, camera): - target_layer_no = rt.batchRenderMgr.FindView(camera) - target_layer = rt.batchRenderMgr.GetView(target_layer_no) - outputfilename = target_layer.outputFilename - directory = os.path.dirname(outputfilename) - render_elem = rt.maxOps.GetCurRenderElementMgr() - render_elem_num = render_elem.NumRenderElements() - if render_elem_num < 0: - return - ext = self._project_settings["max"]["RenderSettings"]["image_format"] # noqa - - for i in range(render_elem_num): - renderlayer_name = render_elem.GetRenderElement(i) - target, renderpass = str(renderlayer_name).split(":") - aov_name = f"{directory}_{camera}_{renderpass}..{ext}" - render_elem.SetRenderElementFileName(i, aov_name) - - def batch_render_layer(self, container, - output_dir, cameras): - outputs = list() - output = os.path.join(output_dir, container) - img_fmt = self._project_settings["max"]["RenderSettings"]["image_format"] # noqa - for cam in cameras: - camera = rt.getNodeByName(cam) - layer_no = rt.batchRenderMgr.FindView(cam) - renderlayer = None - if layer_no == 0: - renderlayer = rt.batchRenderMgr.CreateView(camera) - else: - renderlayer = rt.batchRenderMgr.GetView(layer_no) - # use camera name as renderlayer name - renderlayer.name = cam - renderlayer.outputFilename = f"{output}_{cam}..{img_fmt}" - outputs.append(renderlayer.outputFilename) - return outputs diff --git a/server_addon/max/client/ayon_max/api/menu.py b/server_addon/max/client/ayon_max/api/menu.py deleted file mode 100644 index 25dd39fd84..0000000000 --- a/server_addon/max/client/ayon_max/api/menu.py +++ /dev/null @@ -1,167 +0,0 @@ -# -*- coding: utf-8 -*- -"""3dsmax menu definition of AYON.""" -import os -from qtpy import QtWidgets, QtCore -from pymxs import runtime as rt - -from ayon_core.tools.utils import host_tools -from ayon_max.api import lib - - -class AYONMenu(object): - """Object representing AYON menu. - - This is using "hack" to inject itself before "Help" menu of 3dsmax. - For some reason `postLoadingMenus` event doesn't fire, and main menu - if probably re-initialized by menu templates, se we wait for at least - 1 event Qt event loop before trying to insert. - - """ - - def __init__(self): - super().__init__() - self.main_widget = self.get_main_widget() - self.menu = None - - timer = QtCore.QTimer() - # set number of event loops to wait. - timer.setInterval(1) - timer.timeout.connect(self._on_timer) - timer.start() - - self._timer = timer - self._counter = 0 - - def _on_timer(self): - if self._counter < 1: - self._counter += 1 - return - - self._counter = 0 - self._timer.stop() - self._build_ayon_menu() - - @staticmethod - def get_main_widget(): - """Get 3dsmax main window.""" - return QtWidgets.QWidget.find(rt.windows.getMAXHWND()) - - def get_main_menubar(self) -> QtWidgets.QMenuBar: - """Get main Menubar by 3dsmax main window.""" - return list(self.main_widget.findChildren(QtWidgets.QMenuBar))[0] - - def _get_or_create_ayon_menu( - self, name: str = "&AYON", - before: str = "&Help") -> QtWidgets.QAction: - """Create AYON menu. - - Args: - name (str, Optional): AYON menu name. - before (str, Optional): Name of the 3dsmax main menu item to - add AYON menu before. - - Returns: - QtWidgets.QAction: AYON menu action. - - """ - if self.menu is not None: - return self.menu - - menu_bar = self.get_main_menubar() - menu_items = menu_bar.findChildren( - QtWidgets.QMenu, options=QtCore.Qt.FindDirectChildrenOnly) - help_action = None - for item in menu_items: - if name in item.title(): - # we already have AYON menu - return item - - if before in item.title(): - help_action = item.menuAction() - tab_menu_label = os.environ.get("AYON_MENU_LABEL") or "AYON" - op_menu = QtWidgets.QMenu("&{}".format(tab_menu_label)) - menu_bar.insertMenu(help_action, op_menu) - - self.menu = op_menu - return op_menu - - def _build_ayon_menu(self) -> QtWidgets.QAction: - """Build items in AYON menu.""" - ayon_menu = self._get_or_create_ayon_menu() - load_action = QtWidgets.QAction("Load...", ayon_menu) - load_action.triggered.connect(self.load_callback) - ayon_menu.addAction(load_action) - - publish_action = QtWidgets.QAction("Publish...", ayon_menu) - publish_action.triggered.connect(self.publish_callback) - ayon_menu.addAction(publish_action) - - manage_action = QtWidgets.QAction("Manage...", ayon_menu) - manage_action.triggered.connect(self.manage_callback) - ayon_menu.addAction(manage_action) - - library_action = QtWidgets.QAction("Library...", ayon_menu) - library_action.triggered.connect(self.library_callback) - ayon_menu.addAction(library_action) - - ayon_menu.addSeparator() - - workfiles_action = QtWidgets.QAction("Work Files...", ayon_menu) - workfiles_action.triggered.connect(self.workfiles_callback) - ayon_menu.addAction(workfiles_action) - - ayon_menu.addSeparator() - - res_action = QtWidgets.QAction("Set Resolution", ayon_menu) - res_action.triggered.connect(self.resolution_callback) - ayon_menu.addAction(res_action) - - frame_action = QtWidgets.QAction("Set Frame Range", ayon_menu) - frame_action.triggered.connect(self.frame_range_callback) - ayon_menu.addAction(frame_action) - - colorspace_action = QtWidgets.QAction("Set Colorspace", ayon_menu) - colorspace_action.triggered.connect(self.colorspace_callback) - ayon_menu.addAction(colorspace_action) - - unit_scale_action = QtWidgets.QAction("Set Unit Scale", ayon_menu) - unit_scale_action.triggered.connect(self.unit_scale_callback) - ayon_menu.addAction(unit_scale_action) - - return ayon_menu - - def load_callback(self): - """Callback to show Loader tool.""" - host_tools.show_loader(parent=self.main_widget) - - def publish_callback(self): - """Callback to show Publisher tool.""" - host_tools.show_publisher(parent=self.main_widget) - - def manage_callback(self): - """Callback to show Scene Manager/Inventory tool.""" - host_tools.show_scene_inventory(parent=self.main_widget) - - def library_callback(self): - """Callback to show Library Loader tool.""" - host_tools.show_library_loader(parent=self.main_widget) - - def workfiles_callback(self): - """Callback to show Workfiles tool.""" - host_tools.show_workfiles(parent=self.main_widget) - - def resolution_callback(self): - """Callback to reset scene resolution""" - return lib.reset_scene_resolution() - - def frame_range_callback(self): - """Callback to reset frame range""" - return lib.reset_frame_range() - - def colorspace_callback(self): - """Callback to reset colorspace""" - return lib.reset_colorspace() - - def unit_scale_callback(self): - """Callback to reset unit scale""" - return lib.reset_unit_scale() diff --git a/server_addon/max/client/ayon_max/api/pipeline.py b/server_addon/max/client/ayon_max/api/pipeline.py deleted file mode 100644 index a87cd657ce..0000000000 --- a/server_addon/max/client/ayon_max/api/pipeline.py +++ /dev/null @@ -1,297 +0,0 @@ -# -*- coding: utf-8 -*- -"""Pipeline tools for AYON 3ds max integration.""" -import os -import logging -from operator import attrgetter - -import json - -from ayon_core.host import HostBase, IWorkfileHost, ILoadHost, IPublishHost -import pyblish.api -from ayon_core.pipeline import ( - register_creator_plugin_path, - register_loader_plugin_path, - AVALON_CONTAINER_ID, - AYON_CONTAINER_ID, -) -from ayon_max.api.menu import AYONMenu -from ayon_max.api import lib -from ayon_max.api.plugin import MS_CUSTOM_ATTRIB -from ayon_max import MAX_HOST_DIR - -from pymxs import runtime as rt # noqa - -log = logging.getLogger("ayon_max") - -PLUGINS_DIR = os.path.join(MAX_HOST_DIR, "plugins") -PUBLISH_PATH = os.path.join(PLUGINS_DIR, "publish") -LOAD_PATH = os.path.join(PLUGINS_DIR, "load") -CREATE_PATH = os.path.join(PLUGINS_DIR, "create") -INVENTORY_PATH = os.path.join(PLUGINS_DIR, "inventory") - - -class MaxHost(HostBase, IWorkfileHost, ILoadHost, IPublishHost): - - name = "max" - menu = None - - def __init__(self): - super(MaxHost, self).__init__() - self._op_events = {} - self._has_been_setup = False - - def install(self): - pyblish.api.register_host("max") - - pyblish.api.register_plugin_path(PUBLISH_PATH) - register_loader_plugin_path(LOAD_PATH) - register_creator_plugin_path(CREATE_PATH) - - # self._register_callbacks() - self.menu = AYONMenu() - - self._has_been_setup = True - - rt.callbacks.addScript(rt.Name('systemPostNew'), on_new) - - rt.callbacks.addScript(rt.Name('filePostOpen'), - lib.check_colorspace) - - rt.callbacks.addScript(rt.Name('postWorkspaceChange'), - self._deferred_menu_creation) - rt.NodeEventCallback( - nameChanged=lib.update_modifier_node_names) - - def workfile_has_unsaved_changes(self): - return rt.getSaveRequired() - - def get_workfile_extensions(self): - return [".max"] - - def save_workfile(self, dst_path=None): - rt.saveMaxFile(dst_path) - return dst_path - - def open_workfile(self, filepath): - rt.checkForSave() - rt.loadMaxFile(filepath) - return filepath - - def get_current_workfile(self): - return os.path.join(rt.maxFilePath, rt.maxFileName) - - def get_containers(self): - return ls() - - def _register_callbacks(self): - rt.callbacks.removeScripts(id=rt.name("OpenPypeCallbacks")) - - rt.callbacks.addScript( - rt.Name("postLoadingMenus"), - self._deferred_menu_creation, id=rt.Name('OpenPypeCallbacks')) - - def _deferred_menu_creation(self): - self.log.info("Building menu ...") - self.menu = AYONMenu() - - @staticmethod - def create_context_node(): - """Helper for creating context holding node.""" - - root_scene = rt.rootScene - - create_attr_script = (""" -attributes "OpenPypeContext" -( - parameters main rollout:params - ( - context type: #string - ) - - rollout params "OpenPype Parameters" - ( - editText editTextContext "Context" type: #string - ) -) - """) - - attr = rt.execute(create_attr_script) - rt.custAttributes.add(root_scene, attr) - - return root_scene.OpenPypeContext.context - - def update_context_data(self, data, changes): - try: - _ = rt.rootScene.OpenPypeContext.context - except AttributeError: - # context node doesn't exists - self.create_context_node() - - rt.rootScene.OpenPypeContext.context = json.dumps(data) - - def get_context_data(self): - try: - context = rt.rootScene.OpenPypeContext.context - except AttributeError: - # context node doesn't exists - context = self.create_context_node() - if not context: - context = "{}" - return json.loads(context) - - def save_file(self, dst_path=None): - # Force forwards slashes to avoid segfault - dst_path = dst_path.replace("\\", "/") - rt.saveMaxFile(dst_path) - - -def parse_container(container): - """Return the container node's full container data. - - Args: - container (str): A container node name. - - Returns: - dict: The container schema data for this container node. - - """ - data = lib.read(container) - - # Backwards compatibility pre-schemas for containers - data["schema"] = data.get("schema", "openpype:container-3.0") - - # Append transient data - data["objectName"] = container.Name - return data - - -def ls(): - """Get all AYON containers.""" - objs = rt.objects - containers = [ - obj for obj in objs - if rt.getUserProp(obj, "id") in { - AYON_CONTAINER_ID, AVALON_CONTAINER_ID - } - ] - - for container in sorted(containers, key=attrgetter("name")): - yield parse_container(container) - - -def on_new(): - lib.set_context_setting() - if rt.checkForSave(): - rt.resetMaxFile(rt.Name("noPrompt")) - rt.clearUndoBuffer() - rt.redrawViews() - - -def containerise(name: str, nodes: list, context, - namespace=None, loader=None, suffix="_CON"): - data = { - "schema": "openpype:container-2.0", - "id": AVALON_CONTAINER_ID, - "name": name, - "namespace": namespace or "", - "loader": loader, - "representation": context["representation"]["id"], - } - container_name = f"{namespace}:{name}{suffix}" - container = rt.container(name=container_name) - import_custom_attribute_data(container, nodes) - if not lib.imprint(container_name, data): - print(f"imprinting of {container_name} failed.") - return container - - -def load_custom_attribute_data(): - """Re-loading the AYON custom parameter built by the creator - - Returns: - attribute: re-loading the custom OP attributes set in Maxscript - """ - return rt.Execute(MS_CUSTOM_ATTRIB) - - -def import_custom_attribute_data(container: str, selections: list): - """Importing the Openpype/AYON custom parameter built by the creator - - Args: - container (str): target container which adds custom attributes - selections (list): nodes to be added into - group in custom attributes - """ - attrs = load_custom_attribute_data() - modifier = rt.EmptyModifier() - rt.addModifier(container, modifier) - container.modifiers[0].name = "OP Data" - rt.custAttributes.add(container.modifiers[0], attrs) - node_list = [] - sel_list = [] - for i in selections: - node_ref = rt.NodeTransformMonitor(node=i) - node_list.append(node_ref) - sel_list.append(str(i)) - - # Setting the property - rt.setProperty( - container.modifiers[0].openPypeData, - "all_handles", node_list) - rt.setProperty( - container.modifiers[0].openPypeData, - "sel_list", sel_list) - - -def update_custom_attribute_data(container: str, selections: list): - """Updating the AYON custom parameter built by the creator - - Args: - container (str): target container which adds custom attributes - selections (list): nodes to be added into - group in custom attributes - """ - if container.modifiers[0].name == "OP Data": - rt.deleteModifier(container, container.modifiers[0]) - import_custom_attribute_data(container, selections) - - -def get_previous_loaded_object(container: str): - """Get previous loaded_object through the OP data - - Args: - container (str): the container which stores the OP data - - Returns: - node_list(list): list of nodes which are previously loaded - """ - node_list = [] - node_transform_monitor_list = rt.getProperty( - container.modifiers[0].openPypeData, "all_handles") - for node_transform_monitor in node_transform_monitor_list: - node_list.append(node_transform_monitor.node) - return node_list - - -def remove_container_data(container_node: str): - """Function to remove container data after updating, switching or deleting it. - - Args: - container_node (str): container node - """ - if container_node.modifiers[0].name == "OP Data": - all_set_members_names = [ - member.node for member - in container_node.modifiers[0].openPypeData.all_handles] - # clean up the children of alembic dummy objects - for current_set_member in all_set_members_names: - shape_list = [members for members in current_set_member.Children - if rt.ClassOf(members) == rt.AlembicObject - or rt.isValidNode(members)] - if shape_list: # noqa - rt.Delete(shape_list) - rt.Delete(current_set_member) - rt.deleteModifier(container_node, container_node.modifiers[0]) - - rt.Delete(container_node) - rt.redrawViews() diff --git a/server_addon/max/client/ayon_max/api/plugin.py b/server_addon/max/client/ayon_max/api/plugin.py deleted file mode 100644 index e5d12ce87d..0000000000 --- a/server_addon/max/client/ayon_max/api/plugin.py +++ /dev/null @@ -1,298 +0,0 @@ -# -*- coding: utf-8 -*- -"""3dsmax specific AYON/Pyblish plugin definitions.""" -from abc import ABCMeta - -import six -from pymxs import runtime as rt - -from ayon_core.lib import BoolDef -from ayon_core.pipeline import ( - CreatedInstance, - Creator, - CreatorError, - AYON_INSTANCE_ID, - AVALON_INSTANCE_ID, -) - -from .lib import imprint, lsattr, read - -MS_CUSTOM_ATTRIB = """attributes "openPypeData" -( - parameters main rollout:OPparams - ( - all_handles type:#maxObjectTab tabSize:0 tabSizeVariable:on - sel_list type:#stringTab tabSize:0 tabSizeVariable:on - ) - - rollout OPparams "OP Parameters" - ( - listbox list_node "Node References" items:#() - button button_add "Add to Container" - button button_del "Delete from Container" - - fn node_to_name the_node = - ( - handle = the_node.handle - obj_name = the_node.name - handle_name = obj_name + "<" + handle as string + ">" - return handle_name - ) - fn nodes_to_add node = - ( - sceneObjs = #() - if classOf node == Container do return false - n = node as string - for obj in Objects do - ( - tmp_obj = obj as string - append sceneObjs tmp_obj - ) - if sel_list != undefined do - ( - for obj in sel_list do - ( - idx = findItem sceneObjs obj - if idx do - ( - deleteItem sceneObjs idx - ) - ) - ) - idx = findItem sceneObjs n - if idx then return true else false - ) - - fn nodes_to_rmv node = - ( - n = node as string - idx = findItem sel_list n - if idx then return true else false - ) - - on button_add pressed do - ( - current_sel = selectByName title:"Select Objects to add to - the Container" buttontext:"Add" filter:nodes_to_add - if current_sel == undefined then return False - temp_arr = #() - i_node_arr = #() - for c in current_sel do - ( - handle_name = node_to_name c - node_ref = NodeTransformMonitor node:c - idx = finditem list_node.items handle_name - if idx do ( - continue - ) - name = c as string - append temp_arr handle_name - append i_node_arr node_ref - append sel_list name - ) - all_handles = join i_node_arr all_handles - list_node.items = join temp_arr list_node.items - ) - - on button_del pressed do - ( - current_sel = selectByName title:"Select Objects to remove - from the Container" buttontext:"Remove" filter: nodes_to_rmv - if current_sel == undefined or current_sel.count == 0 then - ( - return False - ) - temp_arr = #() - i_node_arr = #() - new_i_node_arr = #() - new_temp_arr = #() - - for c in current_sel do - ( - node_ref = NodeTransformMonitor node:c as string - handle_name = node_to_name c - n = c as string - tmp_all_handles = #() - for i in all_handles do - ( - tmp = i as string - append tmp_all_handles tmp - ) - idx = finditem tmp_all_handles node_ref - if idx do - ( - new_i_node_arr = DeleteItem all_handles idx - - ) - idx = finditem list_node.items handle_name - if idx do - ( - new_temp_arr = DeleteItem list_node.items idx - ) - idx = finditem sel_list n - if idx do - ( - sel_list = DeleteItem sel_list idx - ) - ) - all_handles = join i_node_arr new_i_node_arr - list_node.items = join temp_arr new_temp_arr - ) - - on OPparams open do - ( - if all_handles.count != 0 then - ( - temp_arr = #() - for x in all_handles do - ( - if x.node == undefined do continue - handle_name = node_to_name x.node - append temp_arr handle_name - ) - list_node.items = temp_arr - ) - ) - ) -)""" - - -class MaxCreatorBase(object): - - @staticmethod - def cache_instance_data(shared_data): - if shared_data.get("max_cached_instances") is not None: - return shared_data - - shared_data["max_cached_instances"] = {} - - cached_instances = [] - for id_type in [AYON_INSTANCE_ID, AVALON_INSTANCE_ID]: - cached_instances.extend(lsattr("id", id_type)) - - for i in cached_instances: - creator_id = rt.GetUserProp(i, "creator_identifier") - if creator_id not in shared_data["max_cached_instances"]: - shared_data["max_cached_instances"][creator_id] = [i.name] - else: - shared_data[ - "max_cached_instances"][creator_id].append(i.name) - return shared_data - - @staticmethod - def create_instance_node(node): - """Create instance node. - - If the supplied node is existing node, it will be used to hold the - instance, otherwise new node of type Dummy will be created. - - Args: - node (rt.MXSWrapperBase, str): Node or node name to use. - - Returns: - instance - """ - if isinstance(node, str): - node = rt.Container(name=node) - - attrs = rt.Execute(MS_CUSTOM_ATTRIB) - modifier = rt.EmptyModifier() - rt.addModifier(node, modifier) - node.modifiers[0].name = "OP Data" - rt.custAttributes.add(node.modifiers[0], attrs) - - return node - - -@six.add_metaclass(ABCMeta) -class MaxCreator(Creator, MaxCreatorBase): - selected_nodes = [] - - def create(self, product_name, instance_data, pre_create_data): - if pre_create_data.get("use_selection"): - self.selected_nodes = rt.GetCurrentSelection() - if rt.getNodeByName(product_name): - raise CreatorError(f"'{product_name}' is already created..") - - instance_node = self.create_instance_node(product_name) - instance_data["instance_node"] = instance_node.name - instance = CreatedInstance( - self.product_type, - product_name, - instance_data, - self - ) - if pre_create_data.get("use_selection"): - - node_list = [] - sel_list = [] - for i in self.selected_nodes: - node_ref = rt.NodeTransformMonitor(node=i) - node_list.append(node_ref) - sel_list.append(str(i)) - - # Setting the property - rt.setProperty( - instance_node.modifiers[0].openPypeData, - "all_handles", node_list) - rt.setProperty( - instance_node.modifiers[0].openPypeData, - "sel_list", sel_list) - - self._add_instance_to_context(instance) - imprint(instance_node.name, instance.data_to_store()) - - return instance - - def collect_instances(self): - self.cache_instance_data(self.collection_shared_data) - for instance in self.collection_shared_data["max_cached_instances"].get(self.identifier, []): # noqa - created_instance = CreatedInstance.from_existing( - read(rt.GetNodeByName(instance)), self - ) - self._add_instance_to_context(created_instance) - - def update_instances(self, update_list): - for created_inst, changes in update_list: - instance_node = created_inst.get("instance_node") - new_values = { - key: changes[key].new_value - for key in changes.changed_keys - } - product_name = new_values.get("productName", "") - if product_name and instance_node != product_name: - node = rt.getNodeByName(instance_node) - new_product_name = new_values["productName"] - if rt.getNodeByName(new_product_name): - raise CreatorError( - "The product '{}' already exists.".format( - new_product_name)) - instance_node = new_product_name - created_inst["instance_node"] = instance_node - node.name = instance_node - - imprint( - instance_node, - created_inst.data_to_store(), - ) - - def remove_instances(self, instances): - """Remove specified instance from the scene. - - This is only removing `id` parameter so instance is no longer - instance, because it might contain valuable data for artist. - - """ - for instance in instances: - instance_node = rt.GetNodeByName( - instance.data.get("instance_node")) - if instance_node: - count = rt.custAttributes.count(instance_node.modifiers[0]) - rt.custAttributes.delete(instance_node.modifiers[0], count) - rt.Delete(instance_node) - - self._remove_instance_from_context(instance) - - def get_pre_create_attr_defs(self): - return [ - BoolDef("use_selection", label="Use selection") - ] diff --git a/server_addon/max/client/ayon_max/api/preview_animation.py b/server_addon/max/client/ayon_max/api/preview_animation.py deleted file mode 100644 index acda5360a1..0000000000 --- a/server_addon/max/client/ayon_max/api/preview_animation.py +++ /dev/null @@ -1,344 +0,0 @@ -import logging -import contextlib -from pymxs import runtime as rt -from .lib import get_max_version, render_resolution - -log = logging.getLogger("ayon_max") - - -@contextlib.contextmanager -def play_preview_when_done(has_autoplay): - """Set preview playback option during context - - Args: - has_autoplay (bool): autoplay during creating - preview animation - """ - current_playback = rt.preferences.playPreviewWhenDone - try: - rt.preferences.playPreviewWhenDone = has_autoplay - yield - finally: - rt.preferences.playPreviewWhenDone = current_playback - - -@contextlib.contextmanager -def viewport_layout_and_camera(camera, layout="layout_1"): - """Set viewport layout and camera during context - ***For 3dsMax 2024+ - Args: - camera (str): viewport camera - layout (str): layout to use in viewport, defaults to `layout_1` - Use None to not change viewport layout during context. - """ - needs_maximise = 0 - # Set to first active non extended viewport - rt.viewport.activeViewportEx(1) - original_camera = rt.viewport.getCamera() - original_type = rt.viewport.getType() - review_camera = rt.getNodeByName(camera) - - try: - if rt.viewport.getLayout() != rt.name(layout): - rt.execute("max tool maximize") - needs_maximise = 1 - rt.viewport.setCamera(review_camera) - yield - finally: - if needs_maximise == 1: - rt.execute("max tool maximize") - if original_type == rt.Name("view_camera"): - rt.viewport.setCamera(original_camera) - else: - rt.viewport.setType(original_type) - - -@contextlib.contextmanager -def viewport_preference_setting(general_viewport, - nitrous_manager, - nitrous_viewport, - vp_button_mgr): - """Function to set viewport setting during context - ***For Max Version < 2024 - Args: - camera (str): Viewport camera for review render - general_viewport (dict): General viewport setting - nitrous_manager (dict): Nitrous graphic manager - nitrous_viewport (dict): Nitrous setting for - preview animation - vp_button_mgr (dict): Viewport button manager Setting - preview_preferences (dict): Preview Preferences Setting - """ - orig_vp_grid = rt.viewport.getGridVisibility(1) - orig_vp_bkg = rt.viewport.IsSolidBackgroundColorMode() - - nitrousGraphicMgr = rt.NitrousGraphicsManager - viewport_setting = nitrousGraphicMgr.GetActiveViewportSetting() - vp_button_mgr_original = { - key: getattr(rt.ViewportButtonMgr, key) for key in vp_button_mgr - } - nitrous_manager_original = { - key: getattr(nitrousGraphicMgr, key) for key in nitrous_manager - } - nitrous_viewport_original = { - key: getattr(viewport_setting, key) for key in nitrous_viewport - } - - try: - rt.viewport.setGridVisibility(1, general_viewport["dspGrid"]) - rt.viewport.EnableSolidBackgroundColorMode(general_viewport["dspBkg"]) - for key, value in vp_button_mgr.items(): - setattr(rt.ViewportButtonMgr, key, value) - for key, value in nitrous_manager.items(): - setattr(nitrousGraphicMgr, key, value) - for key, value in nitrous_viewport.items(): - if nitrous_viewport[key] != nitrous_viewport_original[key]: - setattr(viewport_setting, key, value) - yield - - finally: - rt.viewport.setGridVisibility(1, orig_vp_grid) - rt.viewport.EnableSolidBackgroundColorMode(orig_vp_bkg) - for key, value in vp_button_mgr_original.items(): - setattr(rt.ViewportButtonMgr, key, value) - for key, value in nitrous_manager_original.items(): - setattr(nitrousGraphicMgr, key, value) - for key, value in nitrous_viewport_original.items(): - setattr(viewport_setting, key, value) - - -def _render_preview_animation_max_2024( - filepath, start, end, percentSize, ext, viewport_options): - """Render viewport preview with MaxScript using `CreateAnimation`. - ****For 3dsMax 2024+ - Args: - filepath (str): filepath for render output without frame number and - extension, for example: /path/to/file - start (int): startFrame - end (int): endFrame - percentSize (float): render resolution multiplier by 100 - e.g. 100.0 is 1x, 50.0 is 0.5x, 150.0 is 1.5x - viewport_options (dict): viewport setting options, e.g. - {"vpStyle": "defaultshading", "vpPreset": "highquality"} - Returns: - list: Created files - """ - # the percentSize argument must be integer - percent = int(percentSize) - filepath = filepath.replace("\\", "/") - preview_output = f"{filepath}..{ext}" - frame_template = f"{filepath}.{{:04d}}.{ext}" - job_args = [] - for key, value in viewport_options.items(): - if isinstance(value, bool): - if value: - job_args.append(f"{key}:{value}") - elif isinstance(value, str): - if key == "vpStyle": - if value == "Realistic": - value = "defaultshading" - elif value == "Shaded": - log.warning( - "'Shaded' Mode not supported in " - "preview animation in Max 2024.\n" - "Using 'defaultshading' instead.") - value = "defaultshading" - elif value == "ConsistentColors": - value = "flatcolor" - else: - value = value.lower() - elif key == "vpPreset": - if value == "Quality": - value = "highquality" - elif value == "Customize": - value = "userdefined" - else: - value = value.lower() - job_args.append(f"{key}: #{value}") - - job_str = ( - f'CreatePreview filename:"{preview_output}" outputAVI:false ' - f"percentSize:{percent} start:{start} end:{end} " - f"{' '.join(job_args)} " - "autoPlay:false" - ) - rt.completeRedraw() - rt.execute(job_str) - # Return the created files - return [frame_template.format(frame) for frame in range(start, end + 1)] - - -def _render_preview_animation_max_pre_2024( - filepath, startFrame, endFrame, - width, height, percentSize, ext): - """Render viewport animation by creating bitmaps - ***For 3dsMax Version <2024 - Args: - filepath (str): filepath without frame numbers and extension - startFrame (int): start frame - endFrame (int): end frame - width (int): render resolution width - height (int): render resolution height - percentSize (float): render resolution multiplier by 100 - e.g. 100.0 is 1x, 50.0 is 0.5x, 150.0 is 1.5x - ext (str): image extension - Returns: - list: Created filepaths - """ - - # get the screenshot - percent = percentSize / 100.0 - res_width = width * percent - res_height = height * percent - frame_template = "{}.{{:04}}.{}".format(filepath, ext) - frame_template.replace("\\", "/") - files = [] - user_cancelled = False - for frame in range(startFrame, endFrame + 1): - rt.sliderTime = frame - filepath = frame_template.format(frame) - preview_res = rt.bitmap( - res_width, res_height, filename=filepath - ) - dib = rt.gw.getViewportDib() - dib_width = float(dib.width) - dib_height = float(dib.height) - # aspect ratio - viewportRatio = dib_width / dib_height - renderRatio = float(res_width / res_height) - if viewportRatio < renderRatio: - heightCrop = (dib_width / renderRatio) - topEdge = int((dib_height - heightCrop) / 2.0) - tempImage_bmp = rt.bitmap(dib_width, heightCrop) - src_box_value = rt.Box2(0, topEdge, dib_width, heightCrop) - rt.pasteBitmap(dib, tempImage_bmp, src_box_value, rt.Point2(0, 0)) - rt.copy(tempImage_bmp, preview_res) - rt.close(tempImage_bmp) - elif viewportRatio > renderRatio: - widthCrop = dib_height * renderRatio - leftEdge = int((dib_width - widthCrop) / 2.0) - tempImage_bmp = rt.bitmap(widthCrop, dib_height) - src_box_value = rt.Box2(leftEdge, 0, widthCrop, dib_height) - rt.pasteBitmap(dib, tempImage_bmp, src_box_value, rt.Point2(0, 0)) - rt.copy(tempImage_bmp, preview_res) - rt.close(tempImage_bmp) - else: - rt.copy(dib, preview_res) - rt.save(preview_res) - rt.close(preview_res) - rt.close(dib) - files.append(filepath) - if rt.keyboard.escPressed: - user_cancelled = True - break - # clean up the cache - rt.gc(delayed=True) - if user_cancelled: - raise RuntimeError("User cancelled rendering of viewport animation.") - return files - - -def render_preview_animation( - filepath, - ext, - camera, - start_frame=None, - end_frame=None, - percentSize=100.0, - width=1920, - height=1080, - viewport_options=None): - """Render camera review animation - Args: - filepath (str): filepath to render to, without frame number and - extension - ext (str): output file extension - camera (str): viewport camera for preview render - start_frame (int): start frame - end_frame (int): end frame - percentSize (float): render resolution multiplier by 100 - e.g. 100.0 is 1x, 50.0 is 0.5x, 150.0 is 1.5x - width (int): render resolution width - height (int): render resolution height - viewport_options (dict): viewport setting options - Returns: - list: Rendered output files - """ - if start_frame is None: - start_frame = int(rt.animationRange.start) - if end_frame is None: - end_frame = int(rt.animationRange.end) - - if viewport_options is None: - viewport_options = viewport_options_for_preview_animation() - with play_preview_when_done(False): - with viewport_layout_and_camera(camera): - if int(get_max_version()) < 2024: - with viewport_preference_setting( - viewport_options["general_viewport"], - viewport_options["nitrous_manager"], - viewport_options["nitrous_viewport"], - viewport_options["vp_btn_mgr"] - ): - return _render_preview_animation_max_pre_2024( - filepath, - start_frame, - end_frame, - width, - height, - percentSize, - ext - ) - else: - with render_resolution(width, height): - return _render_preview_animation_max_2024( - filepath, - start_frame, - end_frame, - percentSize, - ext, - viewport_options - ) - - -def viewport_options_for_preview_animation(): - """Get default viewport options for `render_preview_animation`. - - Returns: - dict: viewport setting options - """ - # viewport_options should be the dictionary - if int(get_max_version()) < 2024: - return { - "visualStyleMode": "defaultshading", - "viewportPreset": "highquality", - "vpTexture": False, - "dspGeometry": True, - "dspShapes": False, - "dspLights": False, - "dspCameras": False, - "dspHelpers": False, - "dspParticles": True, - "dspBones": False, - "dspBkg": True, - "dspGrid": False, - "dspSafeFrame": False, - "dspFrameNums": False - } - else: - viewport_options = {} - viewport_options["general_viewport"] = { - "dspBkg": True, - "dspGrid": False - } - viewport_options["nitrous_manager"] = { - "AntialiasingQuality": "None" - } - viewport_options["nitrous_viewport"] = { - "VisualStyleMode": "defaultshading", - "ViewportPreset": "highquality", - "UseTextureEnabled": False - } - viewport_options["vp_btn_mgr"] = { - "EnableButtons": False} - return viewport_options diff --git a/server_addon/max/client/ayon_max/hooks/force_startup_script.py b/server_addon/max/client/ayon_max/hooks/force_startup_script.py deleted file mode 100644 index 1699ea300a..0000000000 --- a/server_addon/max/client/ayon_max/hooks/force_startup_script.py +++ /dev/null @@ -1,27 +0,0 @@ -# -*- coding: utf-8 -*- -"""Pre-launch to force 3ds max startup script.""" -import os -from ayon_max import MAX_HOST_DIR -from ayon_applications import PreLaunchHook, LaunchTypes - - -class ForceStartupScript(PreLaunchHook): - """Inject AYON environment to 3ds max. - - Note that this works in combination whit 3dsmax startup script that - is translating it back to PYTHONPATH for cases when 3dsmax drops PYTHONPATH - environment. - - Hook `GlobalHostDataHook` must be executed before this hook. - """ - app_groups = {"3dsmax", "adsk_3dsmax"} - order = 11 - launch_types = {LaunchTypes.local} - - def execute(self): - startup_args = [ - "-U", - "MAXScript", - os.path.join(MAX_HOST_DIR, "startup", "startup.ms"), - ] - self.launch_context.launch_args.append(startup_args) diff --git a/server_addon/max/client/ayon_max/hooks/inject_python.py b/server_addon/max/client/ayon_max/hooks/inject_python.py deleted file mode 100644 index fc9626ab87..0000000000 --- a/server_addon/max/client/ayon_max/hooks/inject_python.py +++ /dev/null @@ -1,20 +0,0 @@ -# -*- coding: utf-8 -*- -"""Pre-launch hook to inject python environment.""" -import os -from ayon_applications import PreLaunchHook, LaunchTypes - - -class InjectPythonPath(PreLaunchHook): - """Inject AYON environment to 3dsmax. - - Note that this works in combination whit 3dsmax startup script that - is translating it back to PYTHONPATH for cases when 3dsmax drops PYTHONPATH - environment. - - Hook `GlobalHostDataHook` must be executed before this hook. - """ - app_groups = {"3dsmax", "adsk_3dsmax"} - launch_types = {LaunchTypes.local} - - def execute(self): - self.launch_context.env["MAX_PYTHONPATH"] = os.environ["PYTHONPATH"] diff --git a/server_addon/max/client/ayon_max/hooks/set_paths.py b/server_addon/max/client/ayon_max/hooks/set_paths.py deleted file mode 100644 index f066de092e..0000000000 --- a/server_addon/max/client/ayon_max/hooks/set_paths.py +++ /dev/null @@ -1,18 +0,0 @@ -from ayon_applications import PreLaunchHook, LaunchTypes - - -class SetPath(PreLaunchHook): - """Set current dir to workdir. - - Hook `GlobalHostDataHook` must be executed before this hook. - """ - app_groups = {"max"} - launch_types = {LaunchTypes.local} - - def execute(self): - workdir = self.launch_context.env.get("AYON_WORKDIR", "") - if not workdir: - self.log.warning("BUG: Workdir is not filled.") - return - - self.launch_context.kwargs["cwd"] = workdir diff --git a/server_addon/max/client/ayon_max/plugins/__init__.py b/server_addon/max/client/ayon_max/plugins/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/server_addon/max/client/ayon_max/plugins/create/create_camera.py b/server_addon/max/client/ayon_max/plugins/create/create_camera.py deleted file mode 100644 index 451e178afc..0000000000 --- a/server_addon/max/client/ayon_max/plugins/create/create_camera.py +++ /dev/null @@ -1,13 +0,0 @@ -# -*- coding: utf-8 -*- -"""Creator plugin for creating camera.""" -from ayon_max.api import plugin - - -class CreateCamera(plugin.MaxCreator): - """Creator plugin for Camera.""" - identifier = "io.openpype.creators.max.camera" - label = "Camera" - product_type = "camera" - icon = "gear" - - settings_category = "max" diff --git a/server_addon/max/client/ayon_max/plugins/create/create_maxScene.py b/server_addon/max/client/ayon_max/plugins/create/create_maxScene.py deleted file mode 100644 index ee58ef663d..0000000000 --- a/server_addon/max/client/ayon_max/plugins/create/create_maxScene.py +++ /dev/null @@ -1,13 +0,0 @@ -# -*- coding: utf-8 -*- -"""Creator plugin for creating raw max scene.""" -from ayon_max.api import plugin - - -class CreateMaxScene(plugin.MaxCreator): - """Creator plugin for 3ds max scenes.""" - identifier = "io.openpype.creators.max.maxScene" - label = "Max Scene" - product_type = "maxScene" - icon = "gear" - - settings_category = "max" diff --git a/server_addon/max/client/ayon_max/plugins/create/create_model.py b/server_addon/max/client/ayon_max/plugins/create/create_model.py deleted file mode 100644 index f48182ecd7..0000000000 --- a/server_addon/max/client/ayon_max/plugins/create/create_model.py +++ /dev/null @@ -1,13 +0,0 @@ -# -*- coding: utf-8 -*- -"""Creator plugin for model.""" -from ayon_max.api import plugin - - -class CreateModel(plugin.MaxCreator): - """Creator plugin for Model.""" - identifier = "io.openpype.creators.max.model" - label = "Model" - product_type = "model" - icon = "gear" - - settings_category = "max" diff --git a/server_addon/max/client/ayon_max/plugins/create/create_pointcache.py b/server_addon/max/client/ayon_max/plugins/create/create_pointcache.py deleted file mode 100644 index 6d7aabe12c..0000000000 --- a/server_addon/max/client/ayon_max/plugins/create/create_pointcache.py +++ /dev/null @@ -1,13 +0,0 @@ -# -*- coding: utf-8 -*- -"""Creator plugin for creating pointcache alembics.""" -from ayon_max.api import plugin - - -class CreatePointCache(plugin.MaxCreator): - """Creator plugin for Point caches.""" - identifier = "io.openpype.creators.max.pointcache" - label = "Point Cache" - product_type = "pointcache" - icon = "gear" - - settings_category = "max" diff --git a/server_addon/max/client/ayon_max/plugins/create/create_pointcloud.py b/server_addon/max/client/ayon_max/plugins/create/create_pointcloud.py deleted file mode 100644 index 52014d77b2..0000000000 --- a/server_addon/max/client/ayon_max/plugins/create/create_pointcloud.py +++ /dev/null @@ -1,13 +0,0 @@ -# -*- coding: utf-8 -*- -"""Creator plugin for creating point cloud.""" -from ayon_max.api import plugin - - -class CreatePointCloud(plugin.MaxCreator): - """Creator plugin for Point Clouds.""" - identifier = "io.openpype.creators.max.pointcloud" - label = "Point Cloud" - product_type = "pointcloud" - icon = "gear" - - settings_category = "max" diff --git a/server_addon/max/client/ayon_max/plugins/create/create_redshift_proxy.py b/server_addon/max/client/ayon_max/plugins/create/create_redshift_proxy.py deleted file mode 100644 index bcc96c7efe..0000000000 --- a/server_addon/max/client/ayon_max/plugins/create/create_redshift_proxy.py +++ /dev/null @@ -1,12 +0,0 @@ -# -*- coding: utf-8 -*- -"""Creator plugin for creating camera.""" -from ayon_max.api import plugin - - -class CreateRedshiftProxy(plugin.MaxCreator): - identifier = "io.openpype.creators.max.redshiftproxy" - label = "Redshift Proxy" - product_type = "redshiftproxy" - icon = "gear" - - settings_category = "max" diff --git a/server_addon/max/client/ayon_max/plugins/create/create_render.py b/server_addon/max/client/ayon_max/plugins/create/create_render.py deleted file mode 100644 index d1e236f3ef..0000000000 --- a/server_addon/max/client/ayon_max/plugins/create/create_render.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -"""Creator plugin for creating camera.""" -import os -from ayon_max.api import plugin -from ayon_core.lib import BoolDef -from ayon_max.api.lib_rendersettings import RenderSettings - - -class CreateRender(plugin.MaxCreator): - """Creator plugin for Renders.""" - identifier = "io.openpype.creators.max.render" - label = "Render" - product_type = "maxrender" - icon = "gear" - - settings_category = "max" - - def create(self, product_name, instance_data, pre_create_data): - from pymxs import runtime as rt - file = rt.maxFileName - filename, _ = os.path.splitext(file) - instance_data["AssetName"] = filename - instance_data["multiCamera"] = pre_create_data.get("multi_cam") - num_of_renderlayer = rt.batchRenderMgr.numViews - if num_of_renderlayer > 0: - rt.batchRenderMgr.DeleteView(num_of_renderlayer) - - instance = super(CreateRender, self).create( - product_name, - instance_data, - pre_create_data) - - container_name = instance.data.get("instance_node") - # set output paths for rendering(mandatory for deadline) - RenderSettings().render_output(container_name) - # TODO: create multiple camera options - if self.selected_nodes: - selected_nodes_name = [] - for sel in self.selected_nodes: - name = sel.name - selected_nodes_name.append(name) - RenderSettings().batch_render_layer( - container_name, filename, - selected_nodes_name) - - def get_pre_create_attr_defs(self): - attrs = super(CreateRender, self).get_pre_create_attr_defs() - return attrs + [ - BoolDef("multi_cam", - label="Multiple Cameras Submission", - default=False), - ] diff --git a/server_addon/max/client/ayon_max/plugins/create/create_review.py b/server_addon/max/client/ayon_max/plugins/create/create_review.py deleted file mode 100644 index a49490519a..0000000000 --- a/server_addon/max/client/ayon_max/plugins/create/create_review.py +++ /dev/null @@ -1,122 +0,0 @@ -# -*- coding: utf-8 -*- -"""Creator plugin for creating review in Max.""" -from ayon_max.api import plugin -from ayon_core.lib import BoolDef, EnumDef, NumberDef - - -class CreateReview(plugin.MaxCreator): - """Review in 3dsMax""" - - identifier = "io.openpype.creators.max.review" - label = "Review" - product_type = "review" - icon = "video-camera" - - settings_category = "max" - - review_width = 1920 - review_height = 1080 - percentSize = 100 - keep_images = False - image_format = "png" - visual_style = "Realistic" - viewport_preset = "Quality" - vp_texture = True - anti_aliasing = "None" - - def apply_settings(self, project_settings): - settings = project_settings["max"]["CreateReview"] # noqa - - # Take some defaults from settings - self.review_width = settings.get("review_width", self.review_width) - self.review_height = settings.get("review_height", self.review_height) - self.percentSize = settings.get("percentSize", self.percentSize) - self.keep_images = settings.get("keep_images", self.keep_images) - self.image_format = settings.get("image_format", self.image_format) - self.visual_style = settings.get("visual_style", self.visual_style) - self.viewport_preset = settings.get( - "viewport_preset", self.viewport_preset) - self.anti_aliasing = settings.get( - "anti_aliasing", self.anti_aliasing) - self.vp_texture = settings.get("vp_texture", self.vp_texture) - - def create(self, product_name, instance_data, pre_create_data): - # Transfer settings from pre create to instance - creator_attributes = instance_data.setdefault( - "creator_attributes", dict()) - for key in ["imageFormat", - "keepImages", - "review_width", - "review_height", - "percentSize", - "visualStyleMode", - "viewportPreset", - "antialiasingQuality", - "vpTexture"]: - if key in pre_create_data: - creator_attributes[key] = pre_create_data[key] - - super(CreateReview, self).create( - product_name, - instance_data, - pre_create_data) - - def get_instance_attr_defs(self): - image_format_enum = ["exr", "jpg", "png", "tga"] - - visual_style_preset_enum = [ - "Realistic", "Shaded", "Facets", - "ConsistentColors", "HiddenLine", - "Wireframe", "BoundingBox", "Ink", - "ColorInk", "Acrylic", "Tech", "Graphite", - "ColorPencil", "Pastel", "Clay", "ModelAssist" - ] - preview_preset_enum = [ - "Quality", "Standard", "Performance", - "DXMode", "Customize"] - anti_aliasing_enum = ["None", "2X", "4X", "8X"] - - return [ - NumberDef("review_width", - label="Review width", - decimals=0, - minimum=0, - default=self.review_width), - NumberDef("review_height", - label="Review height", - decimals=0, - minimum=0, - default=self.review_height), - NumberDef("percentSize", - label="Percent of Output", - default=self.percentSize, - minimum=1, - decimals=0), - BoolDef("keepImages", - label="Keep Image Sequences", - default=self.keep_images), - EnumDef("imageFormat", - image_format_enum, - default=self.image_format, - label="Image Format Options"), - EnumDef("visualStyleMode", - visual_style_preset_enum, - default=self.visual_style, - label="Preference"), - EnumDef("viewportPreset", - preview_preset_enum, - default=self.viewport_preset, - label="Preview Preset"), - EnumDef("antialiasingQuality", - anti_aliasing_enum, - default=self.anti_aliasing, - label="Anti-aliasing Quality"), - BoolDef("vpTexture", - label="Viewport Texture", - default=self.vp_texture) - ] - - def get_pre_create_attr_defs(self): - # Use same attributes as for instance attributes - attrs = super().get_pre_create_attr_defs() - return attrs + self.get_instance_attr_defs() diff --git a/server_addon/max/client/ayon_max/plugins/create/create_tycache.py b/server_addon/max/client/ayon_max/plugins/create/create_tycache.py deleted file mode 100644 index cbdd94e272..0000000000 --- a/server_addon/max/client/ayon_max/plugins/create/create_tycache.py +++ /dev/null @@ -1,13 +0,0 @@ -# -*- coding: utf-8 -*- -"""Creator plugin for creating TyCache.""" -from ayon_max.api import plugin - - -class CreateTyCache(plugin.MaxCreator): - """Creator plugin for TyCache.""" - identifier = "io.openpype.creators.max.tycache" - label = "TyCache" - product_type = "tycache" - icon = "gear" - - settings_category = "max" diff --git a/server_addon/max/client/ayon_max/plugins/create/create_workfile.py b/server_addon/max/client/ayon_max/plugins/create/create_workfile.py deleted file mode 100644 index 35c41f0fcc..0000000000 --- a/server_addon/max/client/ayon_max/plugins/create/create_workfile.py +++ /dev/null @@ -1,119 +0,0 @@ -# -*- coding: utf-8 -*- -"""Creator plugin for creating workfiles.""" -import ayon_api - -from ayon_core.pipeline import CreatedInstance, AutoCreator -from ayon_max.api import plugin -from ayon_max.api.lib import read, imprint -from pymxs import runtime as rt - - -class CreateWorkfile(plugin.MaxCreatorBase, AutoCreator): - """Workfile auto-creator.""" - identifier = "io.ayon.creators.max.workfile" - label = "Workfile" - product_type = "workfile" - icon = "fa5.file" - - default_variant = "Main" - - settings_category = "max" - - def create(self): - variant = self.default_variant - current_instance = next( - ( - instance for instance in self.create_context.instances - if instance.creator_identifier == self.identifier - ), None) - project_name = self.project_name - folder_path = self.create_context.get_current_folder_path() - task_name = self.create_context.get_current_task_name() - host_name = self.create_context.host_name - - if current_instance is None: - folder_entity = ayon_api.get_folder_by_path( - project_name, folder_path - ) - task_entity = ayon_api.get_task_by_name( - project_name, folder_entity["id"], task_name - ) - product_name = self.get_product_name( - project_name, - folder_entity, - task_entity, - variant, - host_name, - ) - data = { - "folderPath": folder_path, - "task": task_name, - "variant": variant - } - - data.update( - self.get_dynamic_data( - project_name, - folder_entity, - task_entity, - variant, - host_name, - current_instance) - ) - self.log.info("Auto-creating workfile instance...") - instance_node = self.create_node(product_name) - data["instance_node"] = instance_node.name - current_instance = CreatedInstance( - self.product_type, product_name, data, self - ) - self._add_instance_to_context(current_instance) - imprint(instance_node.name, current_instance.data) - elif ( - current_instance["folderPath"] != folder_path - or current_instance["task"] != task_name - ): - # Update instance context if is not the same - folder_entity = ayon_api.get_folder_by_path( - project_name, folder_path - ) - task_entity = ayon_api.get_task_by_name( - project_name, folder_entity["id"], task_name - ) - product_name = self.get_product_name( - project_name, - folder_entity, - task_entity, - variant, - host_name, - ) - - current_instance["folderPath"] = folder_entity["path"] - current_instance["task"] = task_name - current_instance["productName"] = product_name - - def collect_instances(self): - self.cache_instance_data(self.collection_shared_data) - cached_instances = self.collection_shared_data["max_cached_instances"] - for instance in cached_instances.get(self.identifier, []): - if not rt.getNodeByName(instance): - continue - created_instance = CreatedInstance.from_existing( - read(rt.GetNodeByName(instance)), self - ) - self._add_instance_to_context(created_instance) - - def update_instances(self, update_list): - for created_inst, _ in update_list: - instance_node = created_inst.get("instance_node") - imprint( - instance_node, - created_inst.data_to_store() - ) - - def create_node(self, product_name): - if rt.getNodeByName(product_name): - node = rt.getNodeByName(product_name) - return node - node = rt.Container(name=product_name) - node.isHidden = True - return node diff --git a/server_addon/max/client/ayon_max/plugins/load/load_camera_fbx.py b/server_addon/max/client/ayon_max/plugins/load/load_camera_fbx.py deleted file mode 100644 index 81ea15d52a..0000000000 --- a/server_addon/max/client/ayon_max/plugins/load/load_camera_fbx.py +++ /dev/null @@ -1,101 +0,0 @@ -import os - -from ayon_max.api import lib -from ayon_max.api.lib import ( - unique_namespace, - get_namespace, - object_transform_set -) -from ayon_max.api.pipeline import ( - containerise, - get_previous_loaded_object, - update_custom_attribute_data, - remove_container_data -) -from ayon_core.pipeline import get_representation_path, load - - -class FbxLoader(load.LoaderPlugin): - """Fbx Loader.""" - - product_types = {"camera"} - representations = {"fbx"} - order = -9 - icon = "code-fork" - color = "white" - - def load(self, context, name=None, namespace=None, data=None): - from pymxs import runtime as rt - filepath = self.filepath_from_context(context) - filepath = os.path.normpath(filepath) - rt.FBXImporterSetParam("Animation", True) - rt.FBXImporterSetParam("Camera", True) - rt.FBXImporterSetParam("AxisConversionMethod", True) - rt.FBXImporterSetParam("Mode", rt.Name("create")) - rt.FBXImporterSetParam("Preserveinstances", True) - rt.ImportFile( - filepath, - rt.name("noPrompt"), - using=rt.FBXIMP) - - namespace = unique_namespace( - name + "_", - suffix="_", - ) - selections = rt.GetCurrentSelection() - - for selection in selections: - selection.name = f"{namespace}:{selection.name}" - - return containerise( - name, selections, context, - namespace, loader=self.__class__.__name__) - - def update(self, container, context): - from pymxs import runtime as rt - - repre_entity = context["representation"] - path = get_representation_path(repre_entity) - node_name = container["instance_node"] - node = rt.getNodeByName(node_name) - namespace, _ = get_namespace(node_name) - - node_list = get_previous_loaded_object(node) - rt.Select(node_list) - prev_fbx_objects = rt.GetCurrentSelection() - transform_data = object_transform_set(prev_fbx_objects) - for prev_fbx_obj in prev_fbx_objects: - if rt.isValidNode(prev_fbx_obj): - rt.Delete(prev_fbx_obj) - - rt.FBXImporterSetParam("Animation", True) - rt.FBXImporterSetParam("Camera", True) - rt.FBXImporterSetParam("Mode", rt.Name("merge")) - rt.FBXImporterSetParam("AxisConversionMethod", True) - rt.FBXImporterSetParam("Preserveinstances", True) - rt.ImportFile( - path, rt.name("noPrompt"), using=rt.FBXIMP) - current_fbx_objects = rt.GetCurrentSelection() - fbx_objects = [] - for fbx_object in current_fbx_objects: - fbx_object.name = f"{namespace}:{fbx_object.name}" - fbx_objects.append(fbx_object) - fbx_transform = f"{fbx_object.name}.transform" - if fbx_transform in transform_data.keys(): - fbx_object.pos = transform_data[fbx_transform] or 0 - fbx_object.scale = transform_data[ - f"{fbx_object.name}.scale"] or 0 - - update_custom_attribute_data(node, fbx_objects) - lib.imprint(container["instance_node"], { - "representation": repre_entity["id"] - }) - - def switch(self, container, context): - self.update(container, context) - - def remove(self, container): - from pymxs import runtime as rt - - node = rt.GetNodeByName(container["instance_node"]) - remove_container_data(node) diff --git a/server_addon/max/client/ayon_max/plugins/load/load_max_scene.py b/server_addon/max/client/ayon_max/plugins/load/load_max_scene.py deleted file mode 100644 index 7fca69b193..0000000000 --- a/server_addon/max/client/ayon_max/plugins/load/load_max_scene.py +++ /dev/null @@ -1,178 +0,0 @@ -import os -from qtpy import QtWidgets, QtCore -from ayon_core.lib.attribute_definitions import EnumDef -from ayon_max.api import lib -from ayon_max.api.lib import ( - unique_namespace, - get_namespace, - object_transform_set, - is_headless -) -from ayon_max.api.pipeline import ( - containerise, get_previous_loaded_object, - update_custom_attribute_data, - remove_container_data -) -from ayon_core.pipeline import get_representation_path, load - - -class MaterialDupOptionsWindow(QtWidgets.QDialog): - """The pop-up dialog allows users to choose material - duplicate options for importing Max objects when updating - or switching assets. - """ - def __init__(self, material_options): - super(MaterialDupOptionsWindow, self).__init__() - self.setWindowFlags(self.windowFlags() | QtCore.Qt.FramelessWindowHint) - - self.material_option = None - self.material_options = material_options - - self.widgets = { - "label": QtWidgets.QLabel( - "Select material duplicate options before loading the max scene."), - "material_options_list": QtWidgets.QListWidget(), - "warning": QtWidgets.QLabel("No material options selected!"), - "buttons": QtWidgets.QWidget(), - "okButton": QtWidgets.QPushButton("Ok"), - "cancelButton": QtWidgets.QPushButton("Cancel") - } - for key, value in material_options.items(): - item = QtWidgets.QListWidgetItem(value) - self.widgets["material_options_list"].addItem(item) - item.setData(QtCore.Qt.UserRole, key) - # Build buttons. - layout = QtWidgets.QHBoxLayout(self.widgets["buttons"]) - layout.addWidget(self.widgets["okButton"]) - layout.addWidget(self.widgets["cancelButton"]) - # Build layout. - layout = QtWidgets.QVBoxLayout(self) - layout.addWidget(self.widgets["label"]) - layout.addWidget(self.widgets["material_options_list"]) - layout.addWidget(self.widgets["buttons"]) - - self.widgets["okButton"].pressed.connect(self.on_ok_pressed) - self.widgets["cancelButton"].pressed.connect(self.on_cancel_pressed) - self.widgets["material_options_list"].itemPressed.connect( - self.on_material_options_pressed) - - def on_material_options_pressed(self, item): - self.material_option = item.data(QtCore.Qt.UserRole) - - def on_ok_pressed(self): - if self.material_option is None: - self.widgets["warning"].setVisible(True) - return - self.close() - - def on_cancel_pressed(self): - self.material_option = "promptMtlDups" - self.close() - -class MaxSceneLoader(load.LoaderPlugin): - """Max Scene Loader.""" - - product_types = { - "camera", - "maxScene", - "model", - } - - representations = {"max"} - order = -8 - icon = "code-fork" - color = "green" - mtl_dup_default = "promptMtlDups" - mtl_dup_enum_dict = { - "promptMtlDups": "Prompt on Duplicate Materials", - "useMergedMtlDups": "Use Incoming Material", - "useSceneMtlDups": "Use Scene Material", - "renameMtlDups": "Merge and Rename Incoming Material" - } - @classmethod - def get_options(cls, contexts): - return [ - EnumDef("mtldup", - items=cls.mtl_dup_enum_dict, - default=cls.mtl_dup_default, - label="Material Duplicate Options") - ] - - def load(self, context, name=None, namespace=None, options=None): - from pymxs import runtime as rt - mat_dup_options = options.get("mtldup", self.mtl_dup_default) - path = self.filepath_from_context(context) - path = os.path.normpath(path) - # import the max scene by using "merge file" - path = path.replace('\\', '/') - rt.MergeMaxFile(path, rt.Name(mat_dup_options), - quiet=True, includeFullGroup=True) - max_objects = rt.getLastMergedNodes() - max_object_names = [obj.name for obj in max_objects] - # implement the OP/AYON custom attributes before load - max_container = [] - namespace = unique_namespace( - name + "_", - suffix="_", - ) - for max_obj, obj_name in zip(max_objects, max_object_names): - max_obj.name = f"{namespace}:{obj_name}" - max_container.append(max_obj) - return containerise( - name, max_container, context, - namespace, loader=self.__class__.__name__) - - def update(self, container, context): - from pymxs import runtime as rt - - repre_entity = context["representation"] - path = get_representation_path(repre_entity) - node_name = container["instance_node"] - node = rt.getNodeByName(node_name) - namespace, _ = get_namespace(node_name) - # delete the old container with attribute - # delete old duplicate - # use the modifier OP data to delete the data - node_list = get_previous_loaded_object(node) - rt.select(node_list) - prev_max_objects = rt.GetCurrentSelection() - transform_data = object_transform_set(prev_max_objects) - - for prev_max_obj in prev_max_objects: - if rt.isValidNode(prev_max_obj): # noqa - rt.Delete(prev_max_obj) - material_option = self.mtl_dup_default - if not is_headless(): - window = MaterialDupOptionsWindow(self.mtl_dup_enum_dict) - window.exec_() - material_option = window.material_option - rt.MergeMaxFile(path, rt.Name(material_option), quiet=True) - - current_max_objects = rt.getLastMergedNodes() - - current_max_object_names = [obj.name for obj - in current_max_objects] - - max_objects = [] - for max_obj, obj_name in zip(current_max_objects, - current_max_object_names): - max_obj.name = f"{namespace}:{obj_name}" - max_objects.append(max_obj) - max_transform = f"{max_obj}.transform" - if max_transform in transform_data.keys(): - max_obj.pos = transform_data[max_transform] or 0 - max_obj.scale = transform_data[ - f"{max_obj}.scale"] or 0 - - update_custom_attribute_data(node, max_objects) - lib.imprint(container["instance_node"], { - "representation": repre_entity["id"] - }) - - def switch(self, container, context): - self.update(container, context) - - def remove(self, container): - from pymxs import runtime as rt - node = rt.GetNodeByName(container["instance_node"]) - remove_container_data(node) diff --git a/server_addon/max/client/ayon_max/plugins/load/load_model.py b/server_addon/max/client/ayon_max/plugins/load/load_model.py deleted file mode 100644 index 2a6bc45c18..0000000000 --- a/server_addon/max/client/ayon_max/plugins/load/load_model.py +++ /dev/null @@ -1,123 +0,0 @@ -import os -from ayon_core.pipeline import load, get_representation_path -from ayon_max.api.pipeline import ( - containerise, - get_previous_loaded_object, - remove_container_data -) -from ayon_max.api import lib -from ayon_max.api.lib import ( - maintained_selection, unique_namespace -) - - -class ModelAbcLoader(load.LoaderPlugin): - """Loading model with the Alembic loader.""" - - product_types = {"model"} - label = "Load Model with Alembic" - representations = {"abc"} - order = -10 - icon = "code-fork" - color = "orange" - - def load(self, context, name=None, namespace=None, data=None): - from pymxs import runtime as rt - - file_path = os.path.normpath(self.filepath_from_context(context)) - - abc_before = { - c - for c in rt.rootNode.Children - if rt.classOf(c) == rt.AlembicContainer - } - - rt.AlembicImport.ImportToRoot = False - rt.AlembicImport.CustomAttributes = True - rt.AlembicImport.UVs = True - rt.AlembicImport.VertexColors = True - rt.importFile(file_path, rt.name("noPrompt"), using=rt.AlembicImport) - - abc_after = { - c - for c in rt.rootNode.Children - if rt.classOf(c) == rt.AlembicContainer - } - - # This should yield new AlembicContainer node - abc_containers = abc_after.difference(abc_before) - - if len(abc_containers) != 1: - self.log.error("Something failed when loading.") - - abc_container = abc_containers.pop() - - namespace = unique_namespace( - name + "_", - suffix="_", - ) - abc_objects = [] - for abc_object in abc_container.Children: - abc_object.name = f"{namespace}:{abc_object.name}" - abc_objects.append(abc_object) - # rename the abc container with namespace - abc_container_name = f"{namespace}:{name}" - abc_container.name = abc_container_name - abc_objects.append(abc_container) - - return containerise( - name, abc_objects, context, - namespace, loader=self.__class__.__name__ - ) - - def update(self, container, context): - from pymxs import runtime as rt - - repre_entity = context["representation"] - path = get_representation_path(repre_entity) - node = rt.GetNodeByName(container["instance_node"]) - node_list = [n for n in get_previous_loaded_object(node) - if rt.ClassOf(n) == rt.AlembicContainer] - with maintained_selection(): - rt.Select(node_list) - - for alembic in rt.Selection: - abc = rt.GetNodeByName(alembic.name) - rt.Select(abc.Children) - for abc_con in abc.Children: - abc_con.source = path - rt.Select(abc_con.Children) - for abc_obj in abc_con.Children: - abc_obj.source = path - lib.imprint( - container["instance_node"], - {"representation": repre_entity["id"]}, - ) - - def switch(self, container, context): - self.update(container, context) - - def remove(self, container): - from pymxs import runtime as rt - node = rt.GetNodeByName(container["instance_node"]) - remove_container_data(node) - - - @staticmethod - def get_container_children(parent, type_name): - from pymxs import runtime as rt - - def list_children(node): - children = [] - for c in node.Children: - children.append(c) - children += list_children(c) - return children - - filtered = [] - for child in list_children(parent): - class_type = str(rt.ClassOf(child.baseObject)) - if class_type == type_name: - filtered.append(child) - - return filtered diff --git a/server_addon/max/client/ayon_max/plugins/load/load_model_fbx.py b/server_addon/max/client/ayon_max/plugins/load/load_model_fbx.py deleted file mode 100644 index 2775e1b453..0000000000 --- a/server_addon/max/client/ayon_max/plugins/load/load_model_fbx.py +++ /dev/null @@ -1,98 +0,0 @@ -import os -from ayon_core.pipeline import load, get_representation_path -from ayon_max.api.pipeline import ( - containerise, get_previous_loaded_object, - update_custom_attribute_data, - remove_container_data -) -from ayon_max.api import lib -from ayon_max.api.lib import ( - unique_namespace, - get_namespace, - object_transform_set -) -from ayon_max.api.lib import maintained_selection - - -class FbxModelLoader(load.LoaderPlugin): - """Fbx Model Loader.""" - - product_types = {"model"} - representations = {"fbx"} - order = -9 - icon = "code-fork" - color = "white" - - def load(self, context, name=None, namespace=None, data=None): - from pymxs import runtime as rt - filepath = self.filepath_from_context(context) - filepath = os.path.normpath(filepath) - rt.FBXImporterSetParam("Animation", False) - rt.FBXImporterSetParam("Cameras", False) - rt.FBXImporterSetParam("Mode", rt.Name("create")) - rt.FBXImporterSetParam("Preserveinstances", True) - rt.importFile( - filepath, rt.name("noPrompt"), using=rt.FBXIMP) - - namespace = unique_namespace( - name + "_", - suffix="_", - ) - selections = rt.GetCurrentSelection() - - for selection in selections: - selection.name = f"{namespace}:{selection.name}" - - return containerise( - name, selections, context, - namespace, loader=self.__class__.__name__) - - def update(self, container, context): - from pymxs import runtime as rt - - repre_entity = context["representation"] - path = get_representation_path(repre_entity) - node_name = container["instance_node"] - node = rt.getNodeByName(node_name) - if not node: - rt.Container(name=node_name) - namespace, _ = get_namespace(node_name) - - node_list = get_previous_loaded_object(node) - rt.Select(node_list) - prev_fbx_objects = rt.GetCurrentSelection() - transform_data = object_transform_set(prev_fbx_objects) - for prev_fbx_obj in prev_fbx_objects: - if rt.isValidNode(prev_fbx_obj): - rt.Delete(prev_fbx_obj) - - rt.FBXImporterSetParam("Animation", False) - rt.FBXImporterSetParam("Cameras", False) - rt.FBXImporterSetParam("Mode", rt.Name("create")) - rt.FBXImporterSetParam("Preserveinstances", True) - rt.importFile(path, rt.name("noPrompt"), using=rt.FBXIMP) - current_fbx_objects = rt.GetCurrentSelection() - fbx_objects = [] - for fbx_object in current_fbx_objects: - fbx_object.name = f"{namespace}:{fbx_object.name}" - fbx_objects.append(fbx_object) - fbx_transform = f"{fbx_object}.transform" - if fbx_transform in transform_data.keys(): - fbx_object.pos = transform_data[fbx_transform] or 0 - fbx_object.scale = transform_data[ - f"{fbx_object}.scale"] or 0 - - with maintained_selection(): - rt.Select(node) - update_custom_attribute_data(node, fbx_objects) - lib.imprint(container["instance_node"], { - "representation": repre_entity["id"] - }) - - def switch(self, container, context): - self.update(container, context) - - def remove(self, container): - from pymxs import runtime as rt - node = rt.GetNodeByName(container["instance_node"]) - remove_container_data(node) diff --git a/server_addon/max/client/ayon_max/plugins/load/load_model_obj.py b/server_addon/max/client/ayon_max/plugins/load/load_model_obj.py deleted file mode 100644 index d38aadb5bc..0000000000 --- a/server_addon/max/client/ayon_max/plugins/load/load_model_obj.py +++ /dev/null @@ -1,89 +0,0 @@ -import os - -from ayon_max.api import lib -from ayon_max.api.lib import ( - unique_namespace, - get_namespace, - maintained_selection, - object_transform_set -) -from ayon_max.api.pipeline import ( - containerise, - get_previous_loaded_object, - update_custom_attribute_data, - remove_container_data -) -from ayon_core.pipeline import get_representation_path, load - - -class ObjLoader(load.LoaderPlugin): - """Obj Loader.""" - - product_types = {"model"} - representations = {"obj"} - order = -9 - icon = "code-fork" - color = "white" - - def load(self, context, name=None, namespace=None, data=None): - from pymxs import runtime as rt - - filepath = os.path.normpath(self.filepath_from_context(context)) - self.log.debug("Executing command to import..") - - rt.Execute(f'importFile @"{filepath}" #noPrompt using:ObjImp') - - namespace = unique_namespace( - name + "_", - suffix="_", - ) - # create "missing" container for obj import - selections = rt.GetCurrentSelection() - # get current selection - for selection in selections: - selection.name = f"{namespace}:{selection.name}" - return containerise( - name, selections, context, - namespace, loader=self.__class__.__name__) - - def update(self, container, context): - from pymxs import runtime as rt - - repre_entity = context["representation"] - path = get_representation_path(repre_entity) - node_name = container["instance_node"] - node = rt.getNodeByName(node_name) - namespace, _ = get_namespace(node_name) - node_list = get_previous_loaded_object(node) - rt.Select(node_list) - previous_objects = rt.GetCurrentSelection() - transform_data = object_transform_set(previous_objects) - for prev_obj in previous_objects: - if rt.isValidNode(prev_obj): - rt.Delete(prev_obj) - - rt.Execute(f'importFile @"{path}" #noPrompt using:ObjImp') - # get current selection - selections = rt.GetCurrentSelection() - for selection in selections: - selection.name = f"{namespace}:{selection.name}" - selection_transform = f"{selection}.transform" - if selection_transform in transform_data.keys(): - selection.pos = transform_data[selection_transform] or 0 - selection.scale = transform_data[ - f"{selection}.scale"] or 0 - update_custom_attribute_data(node, selections) - with maintained_selection(): - rt.Select(node) - - lib.imprint(node_name, { - "representation": repre_entity["id"] - }) - - def switch(self, container, context): - self.update(container, context) - - def remove(self, container): - from pymxs import runtime as rt - node = rt.GetNodeByName(container["instance_node"]) - remove_container_data(node) diff --git a/server_addon/max/client/ayon_max/plugins/load/load_model_usd.py b/server_addon/max/client/ayon_max/plugins/load/load_model_usd.py deleted file mode 100644 index f4dd41d5db..0000000000 --- a/server_addon/max/client/ayon_max/plugins/load/load_model_usd.py +++ /dev/null @@ -1,120 +0,0 @@ -import os - -from pymxs import runtime as rt -from ayon_core.pipeline.load import LoadError -from ayon_max.api import lib -from ayon_max.api.lib import ( - unique_namespace, - get_namespace, - object_transform_set, - get_plugins -) -from ayon_max.api.lib import maintained_selection -from ayon_max.api.pipeline import ( - containerise, - get_previous_loaded_object, - update_custom_attribute_data, - remove_container_data -) -from ayon_core.pipeline import get_representation_path, load - - -class ModelUSDLoader(load.LoaderPlugin): - """Loading model with the USD loader.""" - - product_types = {"model"} - label = "Load Model(USD)" - representations = {"usda"} - order = -10 - icon = "code-fork" - color = "orange" - - def load(self, context, name=None, namespace=None, data=None): - # asset_filepath - plugin_info = get_plugins() - if "usdimport.dli" not in plugin_info: - raise LoadError("No USDImporter loaded/installed in Max..") - filepath = os.path.normpath(self.filepath_from_context(context)) - import_options = rt.USDImporter.CreateOptions() - base_filename = os.path.basename(filepath) - _, ext = os.path.splitext(base_filename) - log_filepath = filepath.replace(ext, "txt") - - rt.LogPath = log_filepath - rt.LogLevel = rt.Name("info") - rt.USDImporter.importFile(filepath, - importOptions=import_options) - namespace = unique_namespace( - name + "_", - suffix="_", - ) - asset = rt.GetNodeByName(name) - usd_objects = [] - - for usd_asset in asset.Children: - usd_asset.name = f"{namespace}:{usd_asset.name}" - usd_objects.append(usd_asset) - - asset_name = f"{namespace}:{name}" - asset.name = asset_name - # need to get the correct container after renamed - asset = rt.GetNodeByName(asset_name) - usd_objects.append(asset) - - return containerise( - name, usd_objects, context, - namespace, loader=self.__class__.__name__) - - def update(self, container, context): - repre_entity = context["representation"] - path = get_representation_path(repre_entity) - node_name = container["instance_node"] - node = rt.GetNodeByName(node_name) - namespace, name = get_namespace(node_name) - node_list = get_previous_loaded_object(node) - rt.Select(node_list) - prev_objects = [sel for sel in rt.GetCurrentSelection() - if sel != rt.Container - and sel.name != node_name] - transform_data = object_transform_set(prev_objects) - for n in prev_objects: - rt.Delete(n) - - import_options = rt.USDImporter.CreateOptions() - base_filename = os.path.basename(path) - _, ext = os.path.splitext(base_filename) - log_filepath = path.replace(ext, "txt") - - rt.LogPath = log_filepath - rt.LogLevel = rt.Name("info") - rt.USDImporter.importFile( - path, importOptions=import_options) - - asset = rt.GetNodeByName(name) - usd_objects = [] - for children in asset.Children: - children.name = f"{namespace}:{children.name}" - usd_objects.append(children) - children_transform = f"{children}.transform" - if children_transform in transform_data.keys(): - children.pos = transform_data[children_transform] or 0 - children.scale = transform_data[ - f"{children}.scale"] or 0 - - asset.name = f"{namespace}:{asset.name}" - usd_objects.append(asset) - update_custom_attribute_data(node, usd_objects) - with maintained_selection(): - rt.Select(node) - - lib.imprint(node_name, { - "representation": repre_entity["id"] - }) - - def switch(self, container, context): - self.update(container, context) - - def remove(self, container): - from pymxs import runtime as rt - node = rt.GetNodeByName(container["instance_node"]) - remove_container_data(node) diff --git a/server_addon/max/client/ayon_max/plugins/load/load_pointcache.py b/server_addon/max/client/ayon_max/plugins/load/load_pointcache.py deleted file mode 100644 index 87ea5c75bc..0000000000 --- a/server_addon/max/client/ayon_max/plugins/load/load_pointcache.py +++ /dev/null @@ -1,132 +0,0 @@ -# -*- coding: utf-8 -*- -"""Simple alembic loader for 3dsmax. - -Because of limited api, alembics can be only loaded, but not easily updated. - -""" -import os -from ayon_core.pipeline import load, get_representation_path -from ayon_max.api import lib, maintained_selection -from ayon_max.api.lib import unique_namespace, reset_frame_range -from ayon_max.api.pipeline import ( - containerise, - get_previous_loaded_object, - remove_container_data -) - - -class AbcLoader(load.LoaderPlugin): - """Alembic loader.""" - - product_types = {"camera", "animation", "pointcache"} - label = "Load Alembic" - representations = {"abc"} - order = -10 - icon = "code-fork" - color = "orange" - - def load(self, context, name=None, namespace=None, data=None): - from pymxs import runtime as rt - - file_path = self.filepath_from_context(context) - file_path = os.path.normpath(file_path) - - abc_before = { - c - for c in rt.rootNode.Children - if rt.classOf(c) == rt.AlembicContainer - } - - rt.AlembicImport.ImportToRoot = False - # TODO: it will be removed after the improvement - # on the post-system setup - reset_frame_range() - rt.importFile(file_path, rt.name("noPrompt"), using=rt.AlembicImport) - - abc_after = { - c - for c in rt.rootNode.Children - if rt.classOf(c) == rt.AlembicContainer - } - - # This should yield new AlembicContainer node - abc_containers = abc_after.difference(abc_before) - - if len(abc_containers) != 1: - self.log.error("Something failed when loading.") - - abc_container = abc_containers.pop() - selections = rt.GetCurrentSelection() - for abc in selections: - for cam_shape in abc.Children: - cam_shape.playbackType = 0 - - namespace = unique_namespace( - name + "_", - suffix="_", - ) - abc_objects = [] - for abc_object in abc_container.Children: - abc_object.name = f"{namespace}:{abc_object.name}" - abc_objects.append(abc_object) - # rename the abc container with namespace - abc_container_name = f"{namespace}:{name}" - abc_container.name = abc_container_name - abc_objects.append(abc_container) - - return containerise( - name, abc_objects, context, - namespace, loader=self.__class__.__name__ - ) - - def update(self, container, context): - from pymxs import runtime as rt - - repre_entity = context["representation"] - path = get_representation_path(repre_entity) - node = rt.GetNodeByName(container["instance_node"]) - abc_container = [n for n in get_previous_loaded_object(node) - if rt.ClassOf(n) == rt.AlembicContainer] - with maintained_selection(): - rt.Select(abc_container) - - for alembic in rt.Selection: - abc = rt.GetNodeByName(alembic.name) - rt.Select(abc.Children) - for abc_con in abc.Children: - abc_con.source = path - rt.Select(abc_con.Children) - for abc_obj in abc_con.Children: - abc_obj.source = path - lib.imprint( - container["instance_node"], - {"representation": repre_entity["id"]}, - ) - - def switch(self, container, context): - self.update(container, context) - - def remove(self, container): - from pymxs import runtime as rt - node = rt.GetNodeByName(container["instance_node"]) - remove_container_data(node) - - - @staticmethod - def get_container_children(parent, type_name): - from pymxs import runtime as rt - - def list_children(node): - children = [] - for c in node.Children: - children.append(c) - children += list_children(c) - return children - - filtered = [] - for child in list_children(parent): - class_type = str(rt.classOf(child.baseObject)) - if class_type == type_name: - filtered.append(child) - - return filtered diff --git a/server_addon/max/client/ayon_max/plugins/load/load_pointcache_ornatrix.py b/server_addon/max/client/ayon_max/plugins/load/load_pointcache_ornatrix.py deleted file mode 100644 index bc997951c1..0000000000 --- a/server_addon/max/client/ayon_max/plugins/load/load_pointcache_ornatrix.py +++ /dev/null @@ -1,111 +0,0 @@ -import os -from ayon_core.pipeline import load, get_representation_path -from ayon_core.pipeline.load import LoadError -from ayon_max.api.pipeline import ( - containerise, - get_previous_loaded_object, - update_custom_attribute_data, - remove_container_data -) - -from ayon_max.api.lib import ( - unique_namespace, - get_namespace, - object_transform_set, - get_plugins -) -from ayon_max.api import lib -from pymxs import runtime as rt - - -class OxAbcLoader(load.LoaderPlugin): - """Ornatrix Alembic loader.""" - - product_types = {"camera", "animation", "pointcache"} - label = "Load Alembic with Ornatrix" - representations = {"abc"} - order = -10 - icon = "code-fork" - color = "orange" - postfix = "param" - - def load(self, context, name=None, namespace=None, data=None): - plugin_list = get_plugins() - if "ephere.plugins.autodesk.max.ornatrix.dlo" not in plugin_list: - raise LoadError("Ornatrix plugin not " - "found/installed in Max yet..") - - file_path = os.path.normpath(self.filepath_from_context(context)) - rt.AlembicImport.ImportToRoot = True - rt.AlembicImport.CustomAttributes = True - rt.importFile( - file_path, rt.name("noPrompt"), - using=rt.Ornatrix_Alembic_Importer) - - scene_object = [] - for obj in rt.rootNode.Children: - obj_type = rt.ClassOf(obj) - if str(obj_type).startswith("Ox_"): - scene_object.append(obj) - - namespace = unique_namespace( - name + "_", - suffix="_", - ) - abc_container = [] - for abc in scene_object: - abc.name = f"{namespace}:{abc.name}" - abc_container.append(abc) - - return containerise( - name, abc_container, context, - namespace, loader=self.__class__.__name__ - ) - - def update(self, container, context): - repre_entity = context["representation"] - path = get_representation_path(repre_entity) - node_name = container["instance_node"] - namespace, name = get_namespace(node_name) - node = rt.getNodeByName(node_name) - node_list = get_previous_loaded_object(node) - rt.Select(node_list) - selections = rt.getCurrentSelection() - transform_data = object_transform_set(selections) - for prev_obj in selections: - if rt.isValidNode(prev_obj): - rt.Delete(prev_obj) - - rt.AlembicImport.ImportToRoot = False - rt.AlembicImport.CustomAttributes = True - rt.importFile( - path, rt.name("noPrompt"), - using=rt.Ornatrix_Alembic_Importer) - - scene_object = [] - for obj in rt.rootNode.Children: - obj_type = rt.ClassOf(obj) - if str(obj_type).startswith("Ox_"): - scene_object.append(obj) - ox_abc_objects = [] - for abc in scene_object: - abc.Parent = container - abc.name = f"{namespace}:{abc.name}" - ox_abc_objects.append(abc) - ox_transform = f"{abc}.transform" - if ox_transform in transform_data.keys(): - abc.pos = transform_data[ox_transform] or 0 - abc.scale = transform_data[f"{abc}.scale"] or 0 - update_custom_attribute_data(node, ox_abc_objects) - lib.imprint( - container["instance_node"], - {"representation": repre_entity["id"]}, - ) - - def switch(self, container, context): - self.update(container, context) - - def remove(self, container): - from pymxs import runtime as rt - node = rt.GetNodeByName(container["instance_node"]) - remove_container_data(node) diff --git a/server_addon/max/client/ayon_max/plugins/load/load_pointcloud.py b/server_addon/max/client/ayon_max/plugins/load/load_pointcloud.py deleted file mode 100644 index 0fb506d5bd..0000000000 --- a/server_addon/max/client/ayon_max/plugins/load/load_pointcloud.py +++ /dev/null @@ -1,69 +0,0 @@ -import os - -from ayon_max.api import lib, maintained_selection -from ayon_max.api.lib import ( - unique_namespace, - -) -from ayon_max.api.pipeline import ( - containerise, - get_previous_loaded_object, - update_custom_attribute_data, - remove_container_data -) -from ayon_core.pipeline import get_representation_path, load - - -class PointCloudLoader(load.LoaderPlugin): - """Point Cloud Loader.""" - - product_types = {"pointcloud"} - representations = {"prt"} - order = -8 - icon = "code-fork" - color = "green" - postfix = "param" - - def load(self, context, name=None, namespace=None, data=None): - """load point cloud by tyCache""" - from pymxs import runtime as rt - filepath = os.path.normpath(self.filepath_from_context(context)) - obj = rt.tyCache() - obj.filename = filepath - - namespace = unique_namespace( - name + "_", - suffix="_", - ) - obj.name = f"{namespace}:{obj.name}" - - return containerise( - name, [obj], context, - namespace, loader=self.__class__.__name__) - - def update(self, container, context): - """update the container""" - from pymxs import runtime as rt - - repre_entity = context["representation"] - path = get_representation_path(repre_entity) - node = rt.GetNodeByName(container["instance_node"]) - node_list = get_previous_loaded_object(node) - update_custom_attribute_data( - node, node_list) - with maintained_selection(): - rt.Select(node_list) - for prt in rt.Selection: - prt.filename = path - lib.imprint(container["instance_node"], { - "representation": repre_entity["id"] - }) - - def switch(self, container, context): - self.update(container, context) - - def remove(self, container): - """remove the container""" - from pymxs import runtime as rt - node = rt.GetNodeByName(container["instance_node"]) - remove_container_data(node) diff --git a/server_addon/max/client/ayon_max/plugins/load/load_redshift_proxy.py b/server_addon/max/client/ayon_max/plugins/load/load_redshift_proxy.py deleted file mode 100644 index 3fd84b7538..0000000000 --- a/server_addon/max/client/ayon_max/plugins/load/load_redshift_proxy.py +++ /dev/null @@ -1,78 +0,0 @@ -import os -import clique - -from ayon_core.pipeline import ( - load, - get_representation_path -) -from ayon_core.pipeline.load import LoadError -from ayon_max.api.pipeline import ( - containerise, - update_custom_attribute_data, - get_previous_loaded_object, - remove_container_data -) -from ayon_max.api import lib -from ayon_max.api.lib import ( - unique_namespace, - get_plugins -) - - -class RedshiftProxyLoader(load.LoaderPlugin): - """Load rs files with Redshift Proxy""" - - label = "Load Redshift Proxy" - product_types = {"redshiftproxy"} - representations = {"rs"} - order = -9 - icon = "code-fork" - color = "white" - - def load(self, context, name=None, namespace=None, data=None): - from pymxs import runtime as rt - plugin_info = get_plugins() - if "redshift4max.dlr" not in plugin_info: - raise LoadError("Redshift not loaded/installed in Max..") - filepath = self.filepath_from_context(context) - rs_proxy = rt.RedshiftProxy() - rs_proxy.file = filepath - files_in_folder = os.listdir(os.path.dirname(filepath)) - collections, remainder = clique.assemble(files_in_folder) - if collections: - rs_proxy.is_sequence = True - - namespace = unique_namespace( - name + "_", - suffix="_", - ) - rs_proxy.name = f"{namespace}:{rs_proxy.name}" - - return containerise( - name, [rs_proxy], context, - namespace, loader=self.__class__.__name__) - - def update(self, container, context): - from pymxs import runtime as rt - - repre_entity = context["representation"] - path = get_representation_path(repre_entity) - node = rt.getNodeByName(container["instance_node"]) - node_list = get_previous_loaded_object(node) - rt.Select(node_list) - update_custom_attribute_data( - node, rt.Selection) - for proxy in rt.Selection: - proxy.file = path - - lib.imprint(container["instance_node"], { - "representation": repre_entity["id"] - }) - - def switch(self, container, context): - self.update(container, context) - - def remove(self, container): - from pymxs import runtime as rt - node = rt.GetNodeByName(container["instance_node"]) - remove_container_data(node) diff --git a/server_addon/max/client/ayon_max/plugins/load/load_tycache.py b/server_addon/max/client/ayon_max/plugins/load/load_tycache.py deleted file mode 100644 index e087d5599a..0000000000 --- a/server_addon/max/client/ayon_max/plugins/load/load_tycache.py +++ /dev/null @@ -1,65 +0,0 @@ -import os -from ayon_max.api import lib, maintained_selection -from ayon_max.api.lib import ( - unique_namespace, - -) -from ayon_max.api.pipeline import ( - containerise, - get_previous_loaded_object, - update_custom_attribute_data, - remove_container_data -) -from ayon_core.pipeline import get_representation_path, load - - -class TyCacheLoader(load.LoaderPlugin): - """TyCache Loader.""" - - product_types = {"tycache"} - representations = {"tyc"} - order = -8 - icon = "code-fork" - color = "green" - - def load(self, context, name=None, namespace=None, data=None): - """Load tyCache""" - from pymxs import runtime as rt - filepath = os.path.normpath(self.filepath_from_context(context)) - obj = rt.tyCache() - obj.filename = filepath - - namespace = unique_namespace( - name + "_", - suffix="_", - ) - obj.name = f"{namespace}:{obj.name}" - - return containerise( - name, [obj], context, - namespace, loader=self.__class__.__name__) - - def update(self, container, context): - """update the container""" - from pymxs import runtime as rt - - repre_entity = context["representation"] - path = get_representation_path(repre_entity) - node = rt.GetNodeByName(container["instance_node"]) - node_list = get_previous_loaded_object(node) - update_custom_attribute_data(node, node_list) - with maintained_selection(): - for tyc in node_list: - tyc.filename = path - lib.imprint(container["instance_node"], { - "representation": repre_entity["id"] - }) - - def switch(self, container, context): - self.update(container, context) - - def remove(self, container): - """remove the container""" - from pymxs import runtime as rt - node = rt.GetNodeByName(container["instance_node"]) - remove_container_data(node) diff --git a/server_addon/max/client/ayon_max/plugins/publish/collect_current_file.py b/server_addon/max/client/ayon_max/plugins/publish/collect_current_file.py deleted file mode 100644 index 6f8b8dda4b..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/collect_current_file.py +++ /dev/null @@ -1,23 +0,0 @@ -import os -import pyblish.api - -from pymxs import runtime as rt - - -class CollectCurrentFile(pyblish.api.ContextPlugin): - """Inject the current working file.""" - - order = pyblish.api.CollectorOrder - 0.5 - label = "Max Current File" - hosts = ['max'] - - def process(self, context): - """Inject the current working file""" - folder = rt.maxFilePath - file = rt.maxFileName - if not folder or not file: - self.log.error("Scene is not saved.") - current_file = os.path.join(folder, file) - - context.data["currentFile"] = current_file - self.log.debug("Scene path: {}".format(current_file)) diff --git a/server_addon/max/client/ayon_max/plugins/publish/collect_frame_range.py b/server_addon/max/client/ayon_max/plugins/publish/collect_frame_range.py deleted file mode 100644 index 6fc8de90d1..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/collect_frame_range.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -import pyblish.api -from pymxs import runtime as rt - - -class CollectFrameRange(pyblish.api.InstancePlugin): - """Collect Frame Range.""" - - order = pyblish.api.CollectorOrder + 0.01 - label = "Collect Frame Range" - hosts = ['max'] - families = ["camera", "maxrender", - "pointcache", "pointcloud", - "review", "redshiftproxy"] - - def process(self, instance): - if instance.data["productType"] == "maxrender": - instance.data["frameStartHandle"] = int(rt.rendStart) - instance.data["frameEndHandle"] = int(rt.rendEnd) - else: - instance.data["frameStartHandle"] = int(rt.animationRange.start) - instance.data["frameEndHandle"] = int(rt.animationRange.end) diff --git a/server_addon/max/client/ayon_max/plugins/publish/collect_members.py b/server_addon/max/client/ayon_max/plugins/publish/collect_members.py deleted file mode 100644 index 010b3cd3e1..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/collect_members.py +++ /dev/null @@ -1,26 +0,0 @@ -# -*- coding: utf-8 -*- -"""Collect instance members.""" -import pyblish.api -from pymxs import runtime as rt - - -class CollectMembers(pyblish.api.InstancePlugin): - """Collect Set Members.""" - - order = pyblish.api.CollectorOrder + 0.01 - label = "Collect Instance Members" - hosts = ['max'] - - def process(self, instance): - if instance.data["productType"] == "workfile": - self.log.debug( - "Skipping Collecting Members for workfile product type." - ) - return - if instance.data.get("instance_node"): - container = rt.GetNodeByName(instance.data["instance_node"]) - instance.data["members"] = [ - member.node for member - in container.modifiers[0].openPypeData.all_handles - ] - self.log.debug("{}".format(instance.data["members"])) diff --git a/server_addon/max/client/ayon_max/plugins/publish/collect_render.py b/server_addon/max/client/ayon_max/plugins/publish/collect_render.py deleted file mode 100644 index a5e8d65df2..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/collect_render.py +++ /dev/null @@ -1,122 +0,0 @@ -# -*- coding: utf-8 -*- -"""Collect Render""" -import os -import pyblish.api - -from pymxs import runtime as rt -from ayon_core.pipeline.publish import KnownPublishError -from ayon_max.api import colorspace -from ayon_max.api.lib import get_max_version, get_current_renderer -from ayon_max.api.lib_rendersettings import RenderSettings -from ayon_max.api.lib_renderproducts import RenderProducts - - -class CollectRender(pyblish.api.InstancePlugin): - """Collect Render for Deadline""" - - order = pyblish.api.CollectorOrder + 0.02 - label = "Collect 3dsmax Render Layers" - hosts = ['max'] - families = ["maxrender"] - - def process(self, instance): - context = instance.context - folder = rt.maxFilePath - file = rt.maxFileName - current_file = os.path.join(folder, file) - filepath = current_file.replace("\\", "/") - context.data['currentFile'] = current_file - - files_by_aov = RenderProducts().get_beauty(instance.name) - aovs = RenderProducts().get_aovs(instance.name) - files_by_aov.update(aovs) - - camera = rt.viewport.GetCamera() - if instance.data.get("members"): - camera_list = [member for member in instance.data["members"] - if rt.ClassOf(member) == rt.Camera.Classes] - if camera_list: - camera = camera_list[-1] - - instance.data["cameras"] = [camera.name] if camera else None # noqa - - if instance.data.get("multiCamera"): - cameras = instance.data.get("members") - if not cameras: - raise KnownPublishError("There should be at least" - " one renderable camera in container") - sel_cam = [ - c.name for c in cameras - if rt.classOf(c) in rt.Camera.classes] - container_name = instance.data.get("instance_node") - render_dir = os.path.dirname(rt.rendOutputFilename) - outputs = RenderSettings().batch_render_layer( - container_name, render_dir, sel_cam - ) - - instance.data["cameras"] = sel_cam - - files_by_aov = RenderProducts().get_multiple_beauty( - outputs, sel_cam) - aovs = RenderProducts().get_multiple_aovs( - outputs, sel_cam) - files_by_aov.update(aovs) - - if "expectedFiles" not in instance.data: - instance.data["expectedFiles"] = list() - instance.data["files"] = list() - instance.data["expectedFiles"].append(files_by_aov) - instance.data["files"].append(files_by_aov) - - img_format = RenderProducts().image_format() - # OCIO config not support in - # most of the 3dsmax renderers - # so this is currently hard coded - # TODO: add options for redshift/vray ocio config - instance.data["colorspaceConfig"] = "" - instance.data["colorspaceDisplay"] = "sRGB" - instance.data["colorspaceView"] = "ACES 1.0 SDR-video" - - if int(get_max_version()) >= 2024: - colorspace_mgr = rt.ColorPipelineMgr # noqa - display = next( - (display for display in colorspace_mgr.GetDisplayList())) - view_transform = next( - (view for view in colorspace_mgr.GetViewList(display))) - instance.data["colorspaceConfig"] = colorspace_mgr.OCIOConfigPath - instance.data["colorspaceDisplay"] = display - instance.data["colorspaceView"] = view_transform - - instance.data["renderProducts"] = colorspace.ARenderProduct() - instance.data["publishJobState"] = "Suspended" - instance.data["attachTo"] = [] - renderer_class = get_current_renderer() - renderer = str(renderer_class).split(":")[0] - product_type = "maxrender" - # also need to get the render dir for conversion - data = { - "folderPath": instance.data["folderPath"], - "productName": str(instance.name), - "publish": True, - "maxversion": str(get_max_version()), - "imageFormat": img_format, - "productType": product_type, - "family": product_type, - "families": [product_type], - "renderer": renderer, - "source": filepath, - "plugin": "3dsmax", - "frameStart": instance.data["frameStartHandle"], - "frameEnd": instance.data["frameEndHandle"], - "farm": True - } - instance.data.update(data) - - # TODO: this should be unified with maya and its "multipart" flag - # on instance. - if renderer == "Redshift_Renderer": - instance.data.update( - {"separateAovFiles": rt.Execute( - "renderers.current.separateAovFiles")}) - - self.log.info("data: {0}".format(data)) diff --git a/server_addon/max/client/ayon_max/plugins/publish/collect_review.py b/server_addon/max/client/ayon_max/plugins/publish/collect_review.py deleted file mode 100644 index 321aa7439c..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/collect_review.py +++ /dev/null @@ -1,153 +0,0 @@ -# dont forget getting the focal length for burnin -"""Collect Review""" -import pyblish.api - -from pymxs import runtime as rt -from ayon_core.lib import BoolDef -from ayon_max.api.lib import get_max_version -from ayon_core.pipeline.publish import ( - AYONPyblishPluginMixin, - KnownPublishError -) - - -class CollectReview(pyblish.api.InstancePlugin, - AYONPyblishPluginMixin): - """Collect Review Data for Preview Animation""" - - order = pyblish.api.CollectorOrder + 0.02 - label = "Collect Review Data" - hosts = ['max'] - families = ["review"] - - def process(self, instance): - nodes = instance.data["members"] - - def is_camera(node): - is_camera_class = rt.classOf(node) in rt.Camera.classes - return is_camera_class and rt.isProperty(node, "fov") - - # Use first camera in instance - cameras = [node for node in nodes if is_camera(node)] - if cameras: - if len(cameras) > 1: - self.log.warning( - "Found more than one camera in instance, using first " - f"one found: {cameras[0]}" - ) - camera = cameras[0] - camera_name = camera.name - focal_length = camera.fov - else: - raise KnownPublishError( - "Unable to find a valid camera in 'Review' container." - " Only native max Camera supported. " - f"Found objects: {nodes}" - ) - creator_attrs = instance.data["creator_attributes"] - attr_values = self.get_attr_values_from_data(instance.data) - - general_preview_data = { - "review_camera": camera_name, - "frameStart": instance.data["frameStartHandle"], - "frameEnd": instance.data["frameEndHandle"], - "percentSize": creator_attrs["percentSize"], - "imageFormat": creator_attrs["imageFormat"], - "keepImages": creator_attrs["keepImages"], - "fps": instance.context.data["fps"], - "review_width": creator_attrs["review_width"], - "review_height": creator_attrs["review_height"], - } - - if int(get_max_version()) >= 2024: - colorspace_mgr = rt.ColorPipelineMgr # noqa - display = next( - (display for display in colorspace_mgr.GetDisplayList())) - view_transform = next( - (view for view in colorspace_mgr.GetViewList(display))) - instance.data["colorspaceConfig"] = colorspace_mgr.OCIOConfigPath - instance.data["colorspaceDisplay"] = display - instance.data["colorspaceView"] = view_transform - - preview_data = { - "vpStyle": creator_attrs["visualStyleMode"], - "vpPreset": creator_attrs["viewportPreset"], - "vpTextures": creator_attrs["vpTexture"], - "dspGeometry": attr_values.get("dspGeometry"), - "dspShapes": attr_values.get("dspShapes"), - "dspLights": attr_values.get("dspLights"), - "dspCameras": attr_values.get("dspCameras"), - "dspHelpers": attr_values.get("dspHelpers"), - "dspParticles": attr_values.get("dspParticles"), - "dspBones": attr_values.get("dspBones"), - "dspBkg": attr_values.get("dspBkg"), - "dspGrid": attr_values.get("dspGrid"), - "dspSafeFrame": attr_values.get("dspSafeFrame"), - "dspFrameNums": attr_values.get("dspFrameNums") - } - else: - general_viewport = { - "dspBkg": attr_values.get("dspBkg"), - "dspGrid": attr_values.get("dspGrid") - } - nitrous_manager = { - "AntialiasingQuality": creator_attrs["antialiasingQuality"], - } - nitrous_viewport = { - "VisualStyleMode": creator_attrs["visualStyleMode"], - "ViewportPreset": creator_attrs["viewportPreset"], - "UseTextureEnabled": creator_attrs["vpTexture"] - } - preview_data = { - "general_viewport": general_viewport, - "nitrous_manager": nitrous_manager, - "nitrous_viewport": nitrous_viewport, - "vp_btn_mgr": {"EnableButtons": False} - } - - # Enable ftrack functionality - instance.data.setdefault("families", []).append('ftrack') - - burnin_members = instance.data.setdefault("burninDataMembers", {}) - burnin_members["focalLength"] = focal_length - - instance.data.update(general_preview_data) - instance.data["viewport_options"] = preview_data - - @classmethod - def get_attribute_defs(cls): - return [ - BoolDef("dspGeometry", - label="Geometry", - default=True), - BoolDef("dspShapes", - label="Shapes", - default=False), - BoolDef("dspLights", - label="Lights", - default=False), - BoolDef("dspCameras", - label="Cameras", - default=False), - BoolDef("dspHelpers", - label="Helpers", - default=False), - BoolDef("dspParticles", - label="Particle Systems", - default=True), - BoolDef("dspBones", - label="Bone Objects", - default=False), - BoolDef("dspBkg", - label="Background", - default=True), - BoolDef("dspGrid", - label="Active Grid", - default=False), - BoolDef("dspSafeFrame", - label="Safe Frames", - default=False), - BoolDef("dspFrameNums", - label="Frame Numbers", - default=False) - ] diff --git a/server_addon/max/client/ayon_max/plugins/publish/collect_tycache_attributes.py b/server_addon/max/client/ayon_max/plugins/publish/collect_tycache_attributes.py deleted file mode 100644 index 4855e952d8..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/collect_tycache_attributes.py +++ /dev/null @@ -1,76 +0,0 @@ -import pyblish.api - -from ayon_core.lib import EnumDef, TextDef -from ayon_core.pipeline.publish import AYONPyblishPluginMixin - - -class CollectTyCacheData(pyblish.api.InstancePlugin, - AYONPyblishPluginMixin): - """Collect Channel Attributes for TyCache Export""" - - order = pyblish.api.CollectorOrder + 0.02 - label = "Collect tyCache attribute Data" - hosts = ['max'] - families = ["tycache"] - - def process(self, instance): - attr_values = self.get_attr_values_from_data(instance.data) - attributes = {} - for attr_key in attr_values.get("tycacheAttributes", []): - attributes[attr_key] = True - - for key in ["tycacheLayer", "tycacheObjectName"]: - attributes[key] = attr_values.get(key, "") - - # Collect the selected channel data before exporting - instance.data["tyc_attrs"] = attributes - self.log.debug( - f"Found tycache attributes: {attributes}" - ) - - @classmethod - def get_attribute_defs(cls): - # TODO: Support the attributes with maxObject array - tyc_attr_enum = ["tycacheChanAge", "tycacheChanGroups", - "tycacheChanPos", "tycacheChanRot", - "tycacheChanScale", "tycacheChanVel", - "tycacheChanSpin", "tycacheChanShape", - "tycacheChanMatID", "tycacheChanMapping", - "tycacheChanMaterials", "tycacheChanCustomFloat" - "tycacheChanCustomVector", "tycacheChanCustomTM", - "tycacheChanPhysX", "tycacheMeshBackup", - "tycacheCreateObject", - "tycacheCreateObjectIfNotCreated", - "tycacheAdditionalCloth", - "tycacheAdditionalSkin", - "tycacheAdditionalSkinID", - "tycacheAdditionalSkinIDValue", - "tycacheAdditionalTerrain", - "tycacheAdditionalVDB", - "tycacheAdditionalSplinePaths", - "tycacheAdditionalGeo", - "tycacheAdditionalGeoActivateModifiers", - "tycacheSplines", - "tycacheSplinesAdditionalSplines" - ] - tyc_default_attrs = ["tycacheChanGroups", "tycacheChanPos", - "tycacheChanRot", "tycacheChanScale", - "tycacheChanVel", "tycacheChanShape", - "tycacheChanMatID", "tycacheChanMapping", - "tycacheChanMaterials", - "tycacheCreateObjectIfNotCreated"] - return [ - EnumDef("tycacheAttributes", - tyc_attr_enum, - default=tyc_default_attrs, - multiselection=True, - label="TyCache Attributes"), - TextDef("tycacheLayer", - label="TyCache Layer", - tooltip="Name of tycache layer", - default="$(tyFlowLayer)"), - TextDef("tycacheObjectName", - label="TyCache Object Name", - tooltip="TyCache Object Name", - default="$(tyFlowName)_tyCache") - ] diff --git a/server_addon/max/client/ayon_max/plugins/publish/collect_workfile.py b/server_addon/max/client/ayon_max/plugins/publish/collect_workfile.py deleted file mode 100644 index 6eec0f7292..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/collect_workfile.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -"""Collect current work file.""" -import os -import pyblish.api - -from pymxs import runtime as rt - - -class CollectWorkfile(pyblish.api.InstancePlugin): - """Inject the current working file into context""" - - order = pyblish.api.CollectorOrder - 0.01 - label = "Collect 3dsmax Workfile" - hosts = ['max'] - families = ["workfile"] - - def process(self, instance): - """Inject the current working file.""" - context = instance.context - folder = rt.maxFilePath - file = rt.maxFileName - if not folder or not file: - self.log.error("Scene is not saved.") - ext = os.path.splitext(file)[-1].lstrip(".") - - data = {} - - data.update({ - "setMembers": context.data["currentFile"], - "frameStart": context.data["frameStart"], - "frameEnd": context.data["frameEnd"], - "handleStart": context.data["handleStart"], - "handleEnd": context.data["handleEnd"] - }) - - data["representations"] = [{ - "name": ext, - "ext": ext, - "files": file, - "stagingDir": folder, - }] - - instance.data.update(data) - self.log.debug("Collected data: {}".format(data)) - self.log.debug("Collected instance: {}".format(file)) - self.log.debug("staging Dir: {}".format(folder)) diff --git a/server_addon/max/client/ayon_max/plugins/publish/extract_alembic.py b/server_addon/max/client/ayon_max/plugins/publish/extract_alembic.py deleted file mode 100644 index b0999e5a78..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/extract_alembic.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Export alembic file. - -Note: - Parameters on AlembicExport (AlembicExport.Parameter): - - ParticleAsMesh (bool): Sets whether particle shapes are exported - as meshes. - AnimTimeRange (enum): How animation is saved: - #CurrentFrame: saves current frame - #TimeSlider: saves the active time segments on time slider (default) - #StartEnd: saves a range specified by the Step - StartFrame (int) - EnFrame (int) - ShapeSuffix (bool): When set to true, appends the string "Shape" to the - name of each exported mesh. This property is set to false by default. - SamplesPerFrame (int): Sets the number of animation samples per frame. - Hidden (bool): When true, export hidden geometry. - UVs (bool): When true, export the mesh UV map channel. - Normals (bool): When true, export the mesh normals. - VertexColors (bool): When true, export the mesh vertex color map 0 and the - current vertex color display data when it differs - ExtraChannels (bool): When true, export the mesh extra map channels - (map channels greater than channel 1) - Velocity (bool): When true, export the meh vertex and particle velocity - data. - MaterialIDs (bool): When true, export the mesh material ID as - Alembic face sets. - Visibility (bool): When true, export the node visibility data. - LayerName (bool): When true, export the node layer name as an Alembic - object property. - MaterialName (bool): When true, export the geometry node material name as - an Alembic object property - ObjectID (bool): When true, export the geometry node g-buffer object ID as - an Alembic object property. - CustomAttributes (bool): When true, export the node and its modifiers - custom attributes into an Alembic object compound property. -""" -import os -import pyblish.api -from ayon_core.pipeline import publish, OptionalPyblishPluginMixin -from pymxs import runtime as rt -from ayon_max.api import maintained_selection -from ayon_max.api.lib import suspended_refresh -from ayon_core.lib import BoolDef - - -class ExtractAlembic(publish.Extractor, - OptionalPyblishPluginMixin): - order = pyblish.api.ExtractorOrder - label = "Extract Pointcache" - hosts = ["max"] - families = ["pointcache"] - optional = True - active = True - - def process(self, instance): - if not self.is_active(instance.data): - return - - parent_dir = self.staging_dir(instance) - file_name = "{name}.abc".format(**instance.data) - path = os.path.join(parent_dir, file_name) - - with suspended_refresh(): - self._set_abc_attributes(instance) - with maintained_selection(): - # select and export - node_list = instance.data["members"] - rt.Select(node_list) - rt.exportFile( - path, - rt.name("noPrompt"), - selectedOnly=True, - using=rt.AlembicExport, - ) - - if "representations" not in instance.data: - instance.data["representations"] = [] - - representation = { - "name": "abc", - "ext": "abc", - "files": file_name, - "stagingDir": parent_dir, - } - instance.data["representations"].append(representation) - - def _set_abc_attributes(self, instance): - start = instance.data["frameStartHandle"] - end = instance.data["frameEndHandle"] - attr_values = self.get_attr_values_from_data(instance.data) - custom_attrs = attr_values.get("custom_attrs", False) - if not custom_attrs: - self.log.debug( - "No Custom Attributes included in this abc export...") - rt.AlembicExport.ArchiveType = rt.Name("ogawa") - rt.AlembicExport.CoordinateSystem = rt.Name("maya") - rt.AlembicExport.StartFrame = start - rt.AlembicExport.EndFrame = end - rt.AlembicExport.CustomAttributes = custom_attrs - - @classmethod - def get_attribute_defs(cls): - defs = super(ExtractAlembic, cls).get_attribute_defs() - defs.extend([ - BoolDef("custom_attrs", - label="Custom Attributes", - default=False), - ]) - return defs - - -class ExtractCameraAlembic(ExtractAlembic): - """Extract Camera with AlembicExport.""" - label = "Extract Alembic Camera" - families = ["camera"] - optional = True - - -class ExtractModelAlembic(ExtractAlembic): - """Extract Geometry in Alembic Format""" - label = "Extract Geometry (Alembic)" - families = ["model"] - optional = True - - def _set_abc_attributes(self, instance): - attr_values = self.get_attr_values_from_data(instance.data) - custom_attrs = attr_values.get("custom_attrs", False) - if not custom_attrs: - self.log.debug( - "No Custom Attributes included in this abc export...") - rt.AlembicExport.ArchiveType = rt.name("ogawa") - rt.AlembicExport.CoordinateSystem = rt.name("maya") - rt.AlembicExport.CustomAttributes = custom_attrs - rt.AlembicExport.UVs = True - rt.AlembicExport.VertexColors = True - rt.AlembicExport.PreserveInstances = True diff --git a/server_addon/max/client/ayon_max/plugins/publish/extract_fbx.py b/server_addon/max/client/ayon_max/plugins/publish/extract_fbx.py deleted file mode 100644 index bdfc1d0d78..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/extract_fbx.py +++ /dev/null @@ -1,83 +0,0 @@ -import os -import pyblish.api -from ayon_core.pipeline import publish, OptionalPyblishPluginMixin -from pymxs import runtime as rt -from ayon_max.api import maintained_selection -from ayon_max.api.lib import convert_unit_scale - - -class ExtractModelFbx(publish.Extractor, OptionalPyblishPluginMixin): - """ - Extract Geometry in FBX Format - """ - - order = pyblish.api.ExtractorOrder - 0.05 - label = "Extract FBX" - hosts = ["max"] - families = ["model"] - optional = True - - def process(self, instance): - if not self.is_active(instance.data): - return - - stagingdir = self.staging_dir(instance) - filename = "{name}.fbx".format(**instance.data) - filepath = os.path.join(stagingdir, filename) - self._set_fbx_attributes() - - with maintained_selection(): - # select and export - node_list = instance.data["members"] - rt.Select(node_list) - rt.exportFile( - filepath, - rt.name("noPrompt"), - selectedOnly=True, - using=rt.FBXEXP, - ) - - if "representations" not in instance.data: - instance.data["representations"] = [] - - representation = { - "name": "fbx", - "ext": "fbx", - "files": filename, - "stagingDir": stagingdir, - } - instance.data["representations"].append(representation) - self.log.info( - "Extracted instance '%s' to: %s" % (instance.name, filepath) - ) - - def _set_fbx_attributes(self): - unit_scale = convert_unit_scale() - rt.FBXExporterSetParam("Animation", False) - rt.FBXExporterSetParam("Cameras", False) - rt.FBXExporterSetParam("Lights", False) - rt.FBXExporterSetParam("PointCache", False) - rt.FBXExporterSetParam("AxisConversionMethod", "Animation") - rt.FBXExporterSetParam("UpAxis", "Y") - rt.FBXExporterSetParam("Preserveinstances", True) - if unit_scale: - rt.FBXExporterSetParam("ConvertUnit", unit_scale) - - -class ExtractCameraFbx(ExtractModelFbx): - """Extract Camera with FbxExporter.""" - - order = pyblish.api.ExtractorOrder - 0.2 - label = "Extract Fbx Camera" - families = ["camera"] - optional = True - - def _set_fbx_attributes(self): - unit_scale = convert_unit_scale() - rt.FBXExporterSetParam("Animation", True) - rt.FBXExporterSetParam("Cameras", True) - rt.FBXExporterSetParam("AxisConversionMethod", "Animation") - rt.FBXExporterSetParam("UpAxis", "Y") - rt.FBXExporterSetParam("Preserveinstances", True) - if unit_scale: - rt.FBXExporterSetParam("ConvertUnit", unit_scale) diff --git a/server_addon/max/client/ayon_max/plugins/publish/extract_max_scene_raw.py b/server_addon/max/client/ayon_max/plugins/publish/extract_max_scene_raw.py deleted file mode 100644 index ecde6d2ce9..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/extract_max_scene_raw.py +++ /dev/null @@ -1,49 +0,0 @@ -import os -import pyblish.api -from ayon_core.pipeline import publish, OptionalPyblishPluginMixin -from pymxs import runtime as rt - - -class ExtractMaxSceneRaw(publish.Extractor, OptionalPyblishPluginMixin): - """ - Extract Raw Max Scene with SaveSelected - """ - - order = pyblish.api.ExtractorOrder - 0.2 - label = "Extract Max Scene (Raw)" - hosts = ["max"] - families = ["camera", "maxScene", "model"] - optional = True - - settings_category = "max" - - def process(self, instance): - if not self.is_active(instance.data): - return - - # publish the raw scene for camera - self.log.debug("Extracting Raw Max Scene ...") - - stagingdir = self.staging_dir(instance) - filename = "{name}.max".format(**instance.data) - - max_path = os.path.join(stagingdir, filename) - - if "representations" not in instance.data: - instance.data["representations"] = [] - - nodes = instance.data["members"] - rt.saveNodes(nodes, max_path, quiet=True) - - self.log.info("Performing Extraction ...") - - representation = { - "name": "max", - "ext": "max", - "files": filename, - "stagingDir": stagingdir, - } - instance.data["representations"].append(representation) - self.log.info( - "Extracted instance '%s' to: %s" % (instance.name, max_path) - ) diff --git a/server_addon/max/client/ayon_max/plugins/publish/extract_model_obj.py b/server_addon/max/client/ayon_max/plugins/publish/extract_model_obj.py deleted file mode 100644 index 6556bd7809..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/extract_model_obj.py +++ /dev/null @@ -1,59 +0,0 @@ -import os -import pyblish.api -from ayon_core.pipeline import publish, OptionalPyblishPluginMixin -from pymxs import runtime as rt -from ayon_max.api import maintained_selection -from ayon_max.api.lib import suspended_refresh -from ayon_core.pipeline.publish import KnownPublishError - - -class ExtractModelObj(publish.Extractor, OptionalPyblishPluginMixin): - """ - Extract Geometry in OBJ Format - """ - - order = pyblish.api.ExtractorOrder - 0.05 - label = "Extract OBJ" - hosts = ["max"] - families = ["model"] - optional = True - - settings_category = "max" - - def process(self, instance): - if not self.is_active(instance.data): - return - - stagingdir = self.staging_dir(instance) - filename = "{name}.obj".format(**instance.data) - filepath = os.path.join(stagingdir, filename) - - with suspended_refresh(): - with maintained_selection(): - # select and export - node_list = instance.data["members"] - rt.Select(node_list) - rt.exportFile( - filepath, - rt.name("noPrompt"), - selectedOnly=True, - using=rt.ObjExp, - ) - if not os.path.exists(filepath): - raise KnownPublishError( - "File {} wasn't produced by 3ds max, please check the logs.") - - if "representations" not in instance.data: - instance.data["representations"] = [] - - representation = { - "name": "obj", - "ext": "obj", - "files": filename, - "stagingDir": stagingdir, - } - - instance.data["representations"].append(representation) - self.log.info( - "Extracted instance '%s' to: %s" % (instance.name, filepath) - ) diff --git a/server_addon/max/client/ayon_max/plugins/publish/extract_model_usd.py b/server_addon/max/client/ayon_max/plugins/publish/extract_model_usd.py deleted file mode 100644 index a48126c6e5..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/extract_model_usd.py +++ /dev/null @@ -1,94 +0,0 @@ -import os - -import pyblish.api -from pymxs import runtime as rt - -from ayon_max.api import maintained_selection -from ayon_core.pipeline import OptionalPyblishPluginMixin, publish - - -class ExtractModelUSD(publish.Extractor, - OptionalPyblishPluginMixin): - """Extract Geometry in USDA Format.""" - - order = pyblish.api.ExtractorOrder - 0.05 - label = "Extract Geometry (USD)" - hosts = ["max"] - families = ["model"] - optional = True - - settings_category = "max" - - def process(self, instance): - if not self.is_active(instance.data): - return - - self.log.info("Extracting Geometry ...") - - stagingdir = self.staging_dir(instance) - asset_filename = "{name}.usda".format(**instance.data) - asset_filepath = os.path.join(stagingdir, - asset_filename) - self.log.info(f"Writing USD '{asset_filepath}' to '{stagingdir}'") - - log_filename = "{name}.txt".format(**instance.data) - log_filepath = os.path.join(stagingdir, - log_filename) - self.log.info(f"Writing log '{log_filepath}' to '{stagingdir}'") - - # get the nodes which need to be exported - export_options = self.get_export_options(log_filepath) - with maintained_selection(): - # select and export - node_list = instance.data["members"] - rt.Select(node_list) - rt.USDExporter.ExportFile(asset_filepath, - exportOptions=export_options, - contentSource=rt.Name("selected"), - nodeList=node_list) - - self.log.info("Performing Extraction ...") - if "representations" not in instance.data: - instance.data["representations"] = [] - - representation = { - 'name': 'usda', - 'ext': 'usda', - 'files': asset_filename, - "stagingDir": stagingdir, - } - instance.data["representations"].append(representation) - - log_representation = { - 'name': 'txt', - 'ext': 'txt', - 'files': log_filename, - "stagingDir": stagingdir, - } - instance.data["representations"].append(log_representation) - - self.log.info( - f"Extracted instance '{instance.name}' to: {asset_filepath}") - - @staticmethod - def get_export_options(log_path): - """Set Export Options for USD Exporter""" - - export_options = rt.USDExporter.createOptions() - - export_options.Meshes = True - export_options.Shapes = False - export_options.Lights = False - export_options.Cameras = False - export_options.Materials = False - export_options.MeshFormat = rt.Name('fromScene') - export_options.FileFormat = rt.Name('ascii') - export_options.UpAxis = rt.Name('y') - export_options.LogLevel = rt.Name('info') - export_options.LogPath = log_path - export_options.PreserveEdgeOrientation = True - export_options.TimeMode = rt.Name('current') - - rt.USDexporter.UIOptions = export_options - - return export_options diff --git a/server_addon/max/client/ayon_max/plugins/publish/extract_pointcloud.py b/server_addon/max/client/ayon_max/plugins/publish/extract_pointcloud.py deleted file mode 100644 index f763325eb9..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/extract_pointcloud.py +++ /dev/null @@ -1,242 +0,0 @@ -import os - -import pyblish.api -from pymxs import runtime as rt - -from ayon_max.api import maintained_selection -from ayon_core.pipeline import publish - - -class ExtractPointCloud(publish.Extractor): - """ - Extract PRT format with tyFlow operators. - - Notes: - Currently only works for the default partition setting - - Args: - self.export_particle(): sets up all job arguments for attributes - to be exported in MAXscript - - self.get_operators(): get the export_particle operator - - self.get_custom_attr(): get all custom channel attributes from Openpype - setting and sets it as job arguments before exporting - - self.get_files(): get the files with tyFlow naming convention - before publishing - - self.partition_output_name(): get the naming with partition settings. - - self.get_partition(): get partition value - - """ - - order = pyblish.api.ExtractorOrder - 0.2 - label = "Extract Point Cloud" - hosts = ["max"] - families = ["pointcloud"] - settings = [] - - def process(self, instance): - self.settings = self.get_setting(instance) - start = instance.data["frameStartHandle"] - end = instance.data["frameEndHandle"] - self.log.info("Extracting PRT...") - - stagingdir = self.staging_dir(instance) - filename = "{name}.prt".format(**instance.data) - path = os.path.join(stagingdir, filename) - - with maintained_selection(): - job_args = self.export_particle(instance.data["members"], - start, - end, - path) - - for job in job_args: - rt.Execute(job) - - self.log.info("Performing Extraction ...") - if "representations" not in instance.data: - instance.data["representations"] = [] - - self.log.info("Writing PRT with TyFlow Plugin...") - filenames = self.get_files( - instance.data["members"], path, start, end) - self.log.debug(f"filenames: {filenames}") - - partition = self.partition_output_name( - instance.data["members"]) - - representation = { - 'name': 'prt', - 'ext': 'prt', - 'files': filenames if len(filenames) > 1 else filenames[0], - "stagingDir": stagingdir, - "outputName": partition # partition value - } - instance.data["representations"].append(representation) - self.log.info(f"Extracted instance '{instance.name}' to: {path}") - - def export_particle(self, - members, - start, - end, - filepath): - """Sets up all job arguments for attributes. - - Those attributes are to be exported in MAX Script. - - Args: - members (list): Member nodes of the instance. - start (int): Start frame. - end (int): End frame. - filepath (str): Path to PRT file. - - Returns: - list of arguments for MAX Script. - - """ - job_args = [] - opt_list = self.get_operators(members) - for operator in opt_list: - start_frame = f"{operator}.frameStart={start}" - job_args.append(start_frame) - end_frame = f"{operator}.frameEnd={end}" - job_args.append(end_frame) - filepath = filepath.replace("\\", "/") - prt_filename = f'{operator}.PRTFilename="{filepath}"' - job_args.append(prt_filename) - # Partition - mode = f"{operator}.PRTPartitionsMode=2" - job_args.append(mode) - - additional_args = self.get_custom_attr(operator) - job_args.extend(iter(additional_args)) - prt_export = f"{operator}.exportPRT()" - job_args.append(prt_export) - - return job_args - - @staticmethod - def get_operators(members): - """Get Export Particles Operator. - - Args: - members (list): Instance members. - - Returns: - list of particle operators - - """ - opt_list = [] - for member in members: - obj = member.baseobject - # TODO: to see if it can be used maxscript instead - anim_names = rt.GetSubAnimNames(obj) - for anim_name in anim_names: - sub_anim = rt.GetSubAnim(obj, anim_name) - boolean = rt.IsProperty(sub_anim, "Export_Particles") - if boolean: - event_name = sub_anim.Name - opt = f"${member.Name}.{event_name}.export_particles" - opt_list.append(opt) - - return opt_list - - @staticmethod - def get_setting(instance): - project_setting = instance.context.data["project_settings"] - return project_setting["max"]["PointCloud"] - - def get_custom_attr(self, operator): - """Get Custom Attributes""" - - custom_attr_list = [] - attr_settings = self.settings["attribute"] - for attr in attr_settings: - key = attr["name"] - value = attr["value"] - custom_attr = "{0}.PRTChannels_{1}=True".format(operator, - value) - self.log.debug( - "{0} will be added as custom attribute".format(key) - ) - custom_attr_list.append(custom_attr) - - return custom_attr_list - - def get_files(self, - container, - path, - start_frame, - end_frame): - """Get file names for tyFlow. - - Set the filenames accordingly to the tyFlow file - naming extension for the publishing purpose - - Actual File Output from tyFlow:: - __partof..prt - - e.g. tyFlow_cloth_CCCS_blobbyFill_001__part1of1_00004.prt - - Args: - container: Instance node. - path (str): Output directory. - start_frame (int): Start frame. - end_frame (int): End frame. - - Returns: - list of filenames - - """ - filenames = [] - filename = os.path.basename(path) - orig_name, ext = os.path.splitext(filename) - partition_count, partition_start = self.get_partition(container) - for frame in range(int(start_frame), int(end_frame) + 1): - actual_name = "{}__part{:03}of{}_{:05}".format(orig_name, - partition_start, - partition_count, - frame) - actual_filename = path.replace(orig_name, actual_name) - filenames.append(os.path.basename(actual_filename)) - - return filenames - - def partition_output_name(self, container): - """Get partition output name. - - Partition output name set for mapping - the published file output. - - Todo: - Customizes the setting for the output. - - Args: - container: Instance node. - - Returns: - str: Partition name. - - """ - partition_count, partition_start = self.get_partition(container) - return f"_part{partition_start:03}of{partition_count}" - - def get_partition(self, container): - """Get Partition value. - - Args: - container: Instance node. - - """ - opt_list = self.get_operators(container) - # TODO: This looks strange? Iterating over - # the opt_list but returning from inside? - for operator in opt_list: - count = rt.Execute(f'{operator}.PRTPartitionsCount') - start = rt.Execute(f'{operator}.PRTPartitionsFrom') - - return count, start diff --git a/server_addon/max/client/ayon_max/plugins/publish/extract_redshift_proxy.py b/server_addon/max/client/ayon_max/plugins/publish/extract_redshift_proxy.py deleted file mode 100644 index dfb3527be1..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/extract_redshift_proxy.py +++ /dev/null @@ -1,61 +0,0 @@ -import os -import pyblish.api -from ayon_core.pipeline import publish -from pymxs import runtime as rt -from ayon_max.api import maintained_selection - - -class ExtractRedshiftProxy(publish.Extractor): - """ - Extract Redshift Proxy with rsProxy - """ - - order = pyblish.api.ExtractorOrder - 0.1 - label = "Extract RedShift Proxy" - hosts = ["max"] - families = ["redshiftproxy"] - - def process(self, instance): - start = instance.data["frameStartHandle"] - end = instance.data["frameEndHandle"] - - self.log.debug("Extracting Redshift Proxy...") - stagingdir = self.staging_dir(instance) - rs_filename = "{name}.rs".format(**instance.data) - rs_filepath = os.path.join(stagingdir, rs_filename) - rs_filepath = rs_filepath.replace("\\", "/") - - rs_filenames = self.get_rsfiles(instance, start, end) - - with maintained_selection(): - # select and export - node_list = instance.data["members"] - rt.Select(node_list) - # Redshift rsProxy command - # rsProxy fp selected compress connectivity startFrame endFrame - # camera warnExisting transformPivotToOrigin - rt.rsProxy(rs_filepath, 1, 0, 0, start, end, 0, 1, 1) - - self.log.info("Performing Extraction ...") - - if "representations" not in instance.data: - instance.data["representations"] = [] - - representation = { - 'name': 'rs', - 'ext': 'rs', - 'files': rs_filenames if len(rs_filenames) > 1 else rs_filenames[0], # noqa - "stagingDir": stagingdir, - } - instance.data["representations"].append(representation) - self.log.info("Extracted instance '%s' to: %s" % (instance.name, - stagingdir)) - - def get_rsfiles(self, instance, startFrame, endFrame): - rs_filenames = [] - rs_name = instance.data["name"] - for frame in range(startFrame, endFrame + 1): - rs_filename = "%s.%04d.rs" % (rs_name, frame) - rs_filenames.append(rs_filename) - - return rs_filenames diff --git a/server_addon/max/client/ayon_max/plugins/publish/extract_review_animation.py b/server_addon/max/client/ayon_max/plugins/publish/extract_review_animation.py deleted file mode 100644 index b6397d404e..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/extract_review_animation.py +++ /dev/null @@ -1,64 +0,0 @@ -import os -import pyblish.api -from ayon_core.pipeline import publish -from ayon_max.api.preview_animation import ( - render_preview_animation -) - - -class ExtractReviewAnimation(publish.Extractor): - """ - Extract Review by Review Animation - """ - - order = pyblish.api.ExtractorOrder + 0.001 - label = "Extract Review Animation" - hosts = ["max"] - families = ["review"] - - def process(self, instance): - staging_dir = self.staging_dir(instance) - ext = instance.data.get("imageFormat") - start = int(instance.data["frameStart"]) - end = int(instance.data["frameEnd"]) - filepath = os.path.join(staging_dir, instance.name) - self.log.debug( - "Writing Review Animation to '{}'".format(filepath)) - - review_camera = instance.data["review_camera"] - viewport_options = instance.data.get("viewport_options", {}) - files = render_preview_animation( - filepath, - ext, - review_camera, - start, - end, - percentSize=instance.data["percentSize"], - width=instance.data["review_width"], - height=instance.data["review_height"], - viewport_options=viewport_options) - - filenames = [os.path.basename(path) for path in files] - - tags = ["review"] - if not instance.data.get("keepImages"): - tags.append("delete") - - self.log.debug("Performing Extraction ...") - - representation = { - "name": instance.data["imageFormat"], - "ext": instance.data["imageFormat"], - "files": filenames, - "stagingDir": staging_dir, - "frameStart": instance.data["frameStartHandle"], - "frameEnd": instance.data["frameEndHandle"], - "tags": tags, - "preview": True, - "camera_name": review_camera - } - self.log.debug(f"{representation}") - - if "representations" not in instance.data: - instance.data["representations"] = [] - instance.data["representations"].append(representation) diff --git a/server_addon/max/client/ayon_max/plugins/publish/extract_thumbnail.py b/server_addon/max/client/ayon_max/plugins/publish/extract_thumbnail.py deleted file mode 100644 index 183e381be2..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/extract_thumbnail.py +++ /dev/null @@ -1,51 +0,0 @@ -import os -import pyblish.api -from ayon_core.pipeline import publish -from ayon_max.api.preview_animation import render_preview_animation - - -class ExtractThumbnail(publish.Extractor): - """Extract Thumbnail for Review - """ - - order = pyblish.api.ExtractorOrder - label = "Extract Thumbnail" - hosts = ["max"] - families = ["review"] - - def process(self, instance): - ext = instance.data.get("imageFormat") - frame = int(instance.data["frameStart"]) - staging_dir = self.staging_dir(instance) - filepath = os.path.join( - staging_dir, f"{instance.name}_thumbnail") - self.log.debug("Writing Thumbnail to '{}'".format(filepath)) - - review_camera = instance.data["review_camera"] - viewport_options = instance.data.get("viewport_options", {}) - files = render_preview_animation( - filepath, - ext, - review_camera, - start_frame=frame, - end_frame=frame, - percentSize=instance.data["percentSize"], - width=instance.data["review_width"], - height=instance.data["review_height"], - viewport_options=viewport_options) - - thumbnail = next(os.path.basename(path) for path in files) - - representation = { - "name": "thumbnail", - "ext": ext, - "files": thumbnail, - "stagingDir": staging_dir, - "thumbnail": True - } - - self.log.debug(f"{representation}") - - if "representations" not in instance.data: - instance.data["representations"] = [] - instance.data["representations"].append(representation) diff --git a/server_addon/max/client/ayon_max/plugins/publish/extract_tycache.py b/server_addon/max/client/ayon_max/plugins/publish/extract_tycache.py deleted file mode 100644 index 576abe32a2..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/extract_tycache.py +++ /dev/null @@ -1,157 +0,0 @@ -import os - -import pyblish.api -from pymxs import runtime as rt - -from ayon_max.api import maintained_selection -from ayon_core.pipeline import publish - - -class ExtractTyCache(publish.Extractor): - """Extract tycache format with tyFlow operators. - Notes: - - TyCache only works for TyFlow Pro Plugin. - - Methods: - self.get_export_particles_job_args(): sets up all job arguments - for attributes to be exported in MAXscript - - self.get_operators(): get the export_particle operator - - self.get_files(): get the files with tyFlow naming convention - before publishing - """ - - order = pyblish.api.ExtractorOrder - 0.2 - label = "Extract TyCache" - hosts = ["max"] - families = ["tycache"] - - def process(self, instance): - # TODO: let user decide the param - start = int(instance.context.data["frameStart"]) - end = int(instance.context.data.get("frameEnd")) - self.log.debug("Extracting Tycache...") - - stagingdir = self.staging_dir(instance) - filename = "{name}.tyc".format(**instance.data) - path = os.path.join(stagingdir, filename) - filenames = self.get_files(instance, start, end) - additional_attributes = instance.data.get("tyc_attrs", {}) - - with maintained_selection(): - job_args = self.get_export_particles_job_args( - instance.data["members"], - start, end, path, - additional_attributes) - for job in job_args: - rt.Execute(job) - representations = instance.data.setdefault("representations", []) - representation = { - 'name': 'tyc', - 'ext': 'tyc', - 'files': filenames if len(filenames) > 1 else filenames[0], - "stagingDir": stagingdir, - } - representations.append(representation) - - # Get the tyMesh filename for extraction - mesh_filename = f"{instance.name}__tyMesh.tyc" - mesh_repres = { - 'name': 'tyMesh', - 'ext': 'tyc', - 'files': mesh_filename, - "stagingDir": stagingdir, - "outputName": '__tyMesh' - } - representations.append(mesh_repres) - self.log.debug(f"Extracted instance '{instance.name}' to: {filenames}") - - def get_files(self, instance, start_frame, end_frame): - """Get file names for tyFlow in tyCache format. - - Set the filenames accordingly to the tyCache file - naming extension(.tyc) for the publishing purpose - - Actual File Output from tyFlow in tyCache format: - __tyPart_.tyc - - e.g. tycacheMain__tyPart_00000.tyc - - Args: - instance (pyblish.api.Instance): instance. - start_frame (int): Start frame. - end_frame (int): End frame. - - Returns: - filenames(list): list of filenames - - """ - filenames = [] - for frame in range(int(start_frame), int(end_frame) + 1): - filename = f"{instance.name}__tyPart_{frame:05}.tyc" - filenames.append(filename) - return filenames - - def get_export_particles_job_args(self, members, start, end, - filepath, additional_attributes): - """Sets up all job arguments for attributes. - - Those attributes are to be exported in MAX Script. - - Args: - members (list): Member nodes of the instance. - start (int): Start frame. - end (int): End frame. - filepath (str): Output path of the TyCache file. - additional_attributes (dict): channel attributes data - which needed to be exported - - Returns: - list of arguments for MAX Script. - - """ - settings = { - "exportMode": 2, - "frameStart": start, - "frameEnd": end, - "tyCacheFilename": filepath.replace("\\", "/") - } - settings.update(additional_attributes) - - job_args = [] - for operator in self.get_operators(members): - for key, value in settings.items(): - if isinstance(value, str): - # embed in quotes - value = f'"{value}"' - - job_args.append(f"{operator}.{key}={value}") - job_args.append(f"{operator}.exportTyCache()") - return job_args - - @staticmethod - def get_operators(members): - """Get Export Particles Operator. - - Args: - members (list): Instance members. - - Returns: - list of particle operators - - """ - opt_list = [] - for member in members: - obj = member.baseobject - # TODO: see if it can use maxscript instead - anim_names = rt.GetSubAnimNames(obj) - for anim_name in anim_names: - sub_anim = rt.GetSubAnim(obj, anim_name) - boolean = rt.IsProperty(sub_anim, "Export_Particles") - if boolean: - event_name = sub_anim.Name - opt = f"${member.Name}.{event_name}.export_particles" - opt_list.append(opt) - - return opt_list diff --git a/server_addon/max/client/ayon_max/plugins/publish/help/validate_model_name.xml b/server_addon/max/client/ayon_max/plugins/publish/help/validate_model_name.xml deleted file mode 100644 index e41146910a..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/help/validate_model_name.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - -Invalid Model Name -## Nodes found with Invalid Model Name - -Nodes were detected in your scene which have invalid model name which does not -match the regex you preset in AYON setting. -### How to repair? -Make sure the model name aligns with validation regex in your AYON setting. - - - -### Invalid nodes - -{nodes} - - -### How could this happen? - -This often happens if you have mesh with the model naming does not match -with regex in the setting. - - - - \ No newline at end of file diff --git a/server_addon/max/client/ayon_max/plugins/publish/increment_workfile_version.py b/server_addon/max/client/ayon_max/plugins/publish/increment_workfile_version.py deleted file mode 100644 index c7c3f49626..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/increment_workfile_version.py +++ /dev/null @@ -1,19 +0,0 @@ -import pyblish.api -from ayon_core.lib import version_up -from pymxs import runtime as rt - - -class IncrementWorkfileVersion(pyblish.api.ContextPlugin): - """Increment current workfile version.""" - - order = pyblish.api.IntegratorOrder + 0.9 - label = "Increment Workfile Version" - hosts = ["max"] - families = ["maxrender", "workfile"] - - def process(self, context): - path = context.data["currentFile"] - filepath = version_up(path) - - rt.saveMaxFile(filepath) - self.log.info("Incrementing file version") diff --git a/server_addon/max/client/ayon_max/plugins/publish/save_scene.py b/server_addon/max/client/ayon_max/plugins/publish/save_scene.py deleted file mode 100644 index fe2c7f50f4..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/save_scene.py +++ /dev/null @@ -1,25 +0,0 @@ -import pyblish.api -from ayon_core.pipeline import registered_host - - -class SaveCurrentScene(pyblish.api.InstancePlugin): - """Save current scene""" - - label = "Save current file" - order = pyblish.api.ExtractorOrder - 0.49 - hosts = ["max"] - families = ["maxrender", "workfile"] - - def process(self, instance): - host = registered_host() - current_file = host.get_current_workfile() - - assert instance.context.data["currentFile"] == current_file - if instance.data["productType"] == "maxrender": - host.save_workfile(current_file) - - elif host.workfile_has_unsaved_changes(): - self.log.info(f"Saving current file: {current_file}") - host.save_workfile(current_file) - else: - self.log.debug("No unsaved changes, skipping file save..") \ No newline at end of file diff --git a/server_addon/max/client/ayon_max/plugins/publish/save_scenes_for_cameras.py b/server_addon/max/client/ayon_max/plugins/publish/save_scenes_for_cameras.py deleted file mode 100644 index a211210550..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/save_scenes_for_cameras.py +++ /dev/null @@ -1,105 +0,0 @@ -import pyblish.api -import os -import sys -import tempfile - -from pymxs import runtime as rt -from ayon_core.lib import run_subprocess -from ayon_max.api.lib_rendersettings import RenderSettings -from ayon_max.api.lib_renderproducts import RenderProducts - - -class SaveScenesForCamera(pyblish.api.InstancePlugin): - """Save scene files for multiple cameras without - editing the original scene before deadline submission - - """ - - label = "Save Scene files for cameras" - order = pyblish.api.ExtractorOrder - 0.48 - hosts = ["max"] - families = ["maxrender"] - - def process(self, instance): - if not instance.data.get("multiCamera"): - self.log.debug( - "Multi Camera disabled. " - "Skipping to save scene files for cameras") - return - current_folder = rt.maxFilePath - current_filename = rt.maxFileName - current_filepath = os.path.join(current_folder, current_filename) - camera_scene_files = [] - scripts = [] - filename, ext = os.path.splitext(current_filename) - fmt = RenderProducts().image_format() - cameras = instance.data.get("cameras") - if not cameras: - return - new_folder = f"{current_folder}_{filename}" - os.makedirs(new_folder, exist_ok=True) - for camera in cameras: - new_output = RenderSettings().get_batch_render_output(camera) # noqa - new_output = new_output.replace("\\", "/") - new_filename = f"{filename}_{camera}{ext}" - new_filepath = os.path.join(new_folder, new_filename) - new_filepath = new_filepath.replace("\\", "/") - camera_scene_files.append(new_filepath) - RenderSettings().batch_render_elements(camera) - rt.rendOutputFilename = new_output - rt.saveMaxFile(current_filepath) - script = (""" -from pymxs import runtime as rt -import os -filename = "{filename}" -new_filepath = "{new_filepath}" -new_output = "{new_output}" -camera = "{camera}" -rt.rendOutputFilename = new_output -directory = os.path.dirname(rt.rendOutputFilename) -directory = os.path.join(directory, filename) -render_elem = rt.maxOps.GetCurRenderElementMgr() -render_elem_num = render_elem.NumRenderElements() -if render_elem_num > 0: - ext = "{ext}" - for i in range(render_elem_num): - renderlayer_name = render_elem.GetRenderElement(i) - target, renderpass = str(renderlayer_name).split(":") - aov_name = f"{{directory}}_{camera}_{{renderpass}}..{ext}" - render_elem.SetRenderElementFileName(i, aov_name) -rt.saveMaxFile(new_filepath) - """).format(filename=instance.name, - new_filepath=new_filepath, - new_output=new_output, - camera=camera, - ext=fmt) - scripts.append(script) - - maxbatch_exe = os.path.join( - os.path.dirname(sys.executable), "3dsmaxbatch") - maxbatch_exe = maxbatch_exe.replace("\\", "/") - if sys.platform == "windows": - maxbatch_exe += ".exe" - maxbatch_exe = os.path.normpath(maxbatch_exe) - with tempfile.TemporaryDirectory() as tmp_dir_name: - tmp_script_path = os.path.join( - tmp_dir_name, "extract_scene_files.py") - self.log.info("Using script file: {}".format(tmp_script_path)) - - with open(tmp_script_path, "wt") as tmp: - for script in scripts: - tmp.write(script + "\n") - - try: - current_filepath = current_filepath.replace("\\", "/") - tmp_script_path = tmp_script_path.replace("\\", "/") - run_subprocess([maxbatch_exe, tmp_script_path, - "-sceneFile", current_filepath]) - except RuntimeError: - self.log.debug("Checking the scene files existing") - - for camera_scene in camera_scene_files: - if not os.path.exists(camera_scene): - self.log.error("Camera scene files not existed yet!") - raise RuntimeError("MaxBatch.exe doesn't run as expected") - self.log.debug(f"Found Camera scene:{camera_scene}") diff --git a/server_addon/max/client/ayon_max/plugins/publish/validate_attributes.py b/server_addon/max/client/ayon_max/plugins/publish/validate_attributes.py deleted file mode 100644 index a489533b2c..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/validate_attributes.py +++ /dev/null @@ -1,143 +0,0 @@ -# -*- coding: utf-8 -*- -"""Validator for Attributes.""" -import json - -from pyblish.api import ContextPlugin, ValidatorOrder -from pymxs import runtime as rt - -from ayon_core.pipeline.publish import ( - OptionalPyblishPluginMixin, - PublishValidationError, - RepairContextAction -) - - -def has_property(object_name, property_name): - """Return whether an object has a property with given name""" - return rt.Execute(f'isProperty {object_name} "{property_name}"') - - -def is_matching_value(object_name, property_name, value): - """Return whether an existing property matches value `value""" - property_value = rt.Execute(f"{object_name}.{property_name}") - - # Wrap property value if value is a string valued attributes - # starting with a `#` - if ( - isinstance(value, str) and - value.startswith("#") and - not value.endswith(")") - ): - # prefix value with `#` - # not applicable for #() array value type - # and only applicable for enum i.e. #bob, #sally - property_value = f"#{property_value}" - - return property_value == value - - -class ValidateAttributes(OptionalPyblishPluginMixin, - ContextPlugin): - """Validates attributes in the project setting are consistent - with the nodes from MaxWrapper Class in 3ds max. - E.g. "renderers.current.separateAovFiles", - "renderers.production.PrimaryGIEngine" - Admin(s) need to put the dict below and enable this validator for a check: - { - "renderers.current":{ - "separateAovFiles" : True - }, - "renderers.production":{ - "PrimaryGIEngine": "#RS_GIENGINE_BRUTE_FORCE" - } - .... - } - - """ - - order = ValidatorOrder - hosts = ["max"] - label = "Attributes" - actions = [RepairContextAction] - optional = True - - settings_category = "max" - - @classmethod - def get_invalid(cls, context): - attributes = json.loads( - context.data - ["project_settings"] - ["max"] - ["publish"] - ["ValidateAttributes"] - ["attributes"] - ) - if not attributes: - return - invalid = [] - for object_name, required_properties in attributes.items(): - if not rt.Execute(f"isValidValue {object_name}"): - # Skip checking if the node does not - # exist in MaxWrapper Class - cls.log.debug(f"Unable to find '{object_name}'." - " Skipping validation of attributes.") - continue - - for property_name, value in required_properties.items(): - if not has_property(object_name, property_name): - cls.log.error( - "Non-existing property: " - f"{object_name}.{property_name}") - invalid.append((object_name, property_name)) - - if not is_matching_value(object_name, property_name, value): - cls.log.error( - f"Invalid value for: {object_name}.{property_name}" - f" should be: {value}") - invalid.append((object_name, property_name)) - - return invalid - - def process(self, context): - if not self.is_active(context.data): - self.log.debug("Skipping Validate Attributes...") - return - invalid_attributes = self.get_invalid(context) - if invalid_attributes: - bullet_point_invalid_statement = "\n".join( - "- {}".format(invalid) for invalid - in invalid_attributes - ) - report = ( - "Required Attribute(s) have invalid value(s).\n\n" - f"{bullet_point_invalid_statement}\n\n" - "You can use repair action to fix them if they are not\n" - "unknown property value(s)." - ) - raise PublishValidationError( - report, title="Invalid Value(s) for Required Attribute(s)") - - @classmethod - def repair(cls, context): - attributes = json.loads( - context.data - ["project_settings"] - ["max"] - ["publish"] - ["ValidateAttributes"] - ["attributes"] - ) - invalid_attributes = cls.get_invalid(context) - for attrs in invalid_attributes: - prop, attr = attrs - value = attributes[prop][attr] - if isinstance(value, str) and not value.startswith("#"): - attribute_fix = '{}.{}="{}"'.format( - prop, attr, value - ) - else: - attribute_fix = "{}.{}={}".format( - prop, attr, value - ) - rt.Execute(attribute_fix) diff --git a/server_addon/max/client/ayon_max/plugins/publish/validate_camera_attributes.py b/server_addon/max/client/ayon_max/plugins/publish/validate_camera_attributes.py deleted file mode 100644 index 63a2ef39a7..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/validate_camera_attributes.py +++ /dev/null @@ -1,90 +0,0 @@ -import pyblish.api -from pymxs import runtime as rt - -from ayon_core.pipeline.publish import ( - RepairAction, - OptionalPyblishPluginMixin, - PublishValidationError -) -from ayon_max.api.action import SelectInvalidAction - - -class ValidateCameraAttributes(OptionalPyblishPluginMixin, - pyblish.api.InstancePlugin): - """Validates Camera has no invalid attribute properties - or values.(For 3dsMax Cameras only) - - """ - - order = pyblish.api.ValidatorOrder - families = ['camera'] - hosts = ['max'] - label = 'Validate Camera Attributes' - actions = [SelectInvalidAction, RepairAction] - optional = True - - settings_category = "max" - - DEFAULTS = ["fov", "nearrange", "farrange", - "nearclip", "farclip"] - CAM_TYPE = ["Freecamera", "Targetcamera", - "Physical"] - - @classmethod - def get_invalid(cls, instance): - invalid = [] - if rt.units.DisplayType != rt.Name("Generic"): - cls.log.warning( - "Generic Type is not used as a scene unit\n\n" - "sure you tweak the settings with your own values\n\n" - "before validation.") - cameras = instance.data["members"] - project_settings = instance.context.data["project_settings"].get("max") - cam_attr_settings = ( - project_settings["publish"]["ValidateCameraAttributes"] - ) - for camera in cameras: - if str(rt.ClassOf(camera)) not in cls.CAM_TYPE: - cls.log.debug( - "Skipping camera created from external plugin..") - continue - for attr in cls.DEFAULTS: - default_value = cam_attr_settings.get(attr) - if default_value == float(0): - cls.log.debug( - f"the value of {attr} in setting set to" - " zero. Skipping the check.") - continue - if round(rt.getProperty(camera, attr), 1) != default_value: - cls.log.error( - f"Invalid attribute value for {camera.name}:{attr} " - f"(should be: {default_value}))") - invalid.append(camera) - - return invalid - - def process(self, instance): - if not self.is_active(instance.data): - self.log.debug("Skipping Validate Camera Attributes.") - return - invalid = self.get_invalid(instance) - - if invalid: - raise PublishValidationError( - "Invalid camera attributes found. See log.") - - @classmethod - def repair(cls, instance): - invalid_cameras = cls.get_invalid(instance) - project_settings = instance.context.data["project_settings"].get("max") - cam_attr_settings = ( - project_settings["publish"]["ValidateCameraAttributes"] - ) - for camera in invalid_cameras: - for attr in cls.DEFAULTS: - expected_value = cam_attr_settings.get(attr) - if expected_value == float(0): - cls.log.debug( - f"the value of {attr} in setting set to zero.") - continue - rt.setProperty(camera, attr, expected_value) diff --git a/server_addon/max/client/ayon_max/plugins/publish/validate_camera_contents.py b/server_addon/max/client/ayon_max/plugins/publish/validate_camera_contents.py deleted file mode 100644 index 334e7dcec9..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/validate_camera_contents.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -import pyblish.api - -from ayon_core.pipeline import PublishValidationError - - -class ValidateCameraContent(pyblish.api.InstancePlugin): - """Validates Camera instance contents. - - A Camera instance may only hold a SINGLE camera's transform - """ - - order = pyblish.api.ValidatorOrder - families = ["camera", "review"] - hosts = ["max"] - label = "Camera Contents" - camera_type = ["$Free_Camera", "$Target_Camera", - "$Physical_Camera", "$Target"] - - def process(self, instance): - invalid = self.get_invalid(instance) - if invalid: - raise PublishValidationError(("Camera instance must only include" - "camera (and camera target). " - f"Invalid content {invalid}")) - - def get_invalid(self, instance): - """ - Get invalid nodes if the instance is not camera - """ - invalid = [] - container = instance.data["instance_node"] - self.log.info(f"Validating camera content for {container}") - - selection_list = instance.data["members"] - for sel in selection_list: - # to avoid Attribute Error from pymxs wrapper - sel_tmp = str(sel) - found = any(sel_tmp.startswith(cam) for cam in self.camera_type) - if not found: - self.log.error("Camera not found") - invalid.append(sel) - return invalid diff --git a/server_addon/max/client/ayon_max/plugins/publish/validate_extended_viewport.py b/server_addon/max/client/ayon_max/plugins/publish/validate_extended_viewport.py deleted file mode 100644 index ed476ec874..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/validate_extended_viewport.py +++ /dev/null @@ -1,29 +0,0 @@ -# -*- coding: utf-8 -*- -import pyblish.api -from ayon_core.pipeline import PublishValidationError -from pymxs import runtime as rt - - -class ValidateExtendedViewport(pyblish.api.ContextPlugin): - """Validate if the first viewport is an extended viewport.""" - - order = pyblish.api.ValidatorOrder - families = ["review"] - hosts = ["max"] - label = "Validate Extended Viewport" - - def process(self, context): - try: - rt.viewport.activeViewportEx(1) - except RuntimeError: - raise PublishValidationError( - "Please make sure one viewport is not an extended viewport", - description = ( - "Please make sure at least one viewport is not an " - "extended viewport but a 3dsmax supported viewport " - "i.e camera/persp/orthographic view.\n\n" - "To rectify it, please go to view in the top menubar, " - "go to Views -> Viewports Configuration -> Layout and " - "right click on one of the panels to change it." - )) - diff --git a/server_addon/max/client/ayon_max/plugins/publish/validate_frame_range.py b/server_addon/max/client/ayon_max/plugins/publish/validate_frame_range.py deleted file mode 100644 index 9a9f22dd3e..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/validate_frame_range.py +++ /dev/null @@ -1,90 +0,0 @@ -import pyblish.api - -from pymxs import runtime as rt -from ayon_core.pipeline import ( - OptionalPyblishPluginMixin -) -from ayon_core.pipeline.publish import ( - RepairAction, - ValidateContentsOrder, - PublishValidationError, - KnownPublishError -) -from ayon_max.api.lib import get_frame_range, set_timeline - - -class ValidateFrameRange(pyblish.api.InstancePlugin, - OptionalPyblishPluginMixin): - """Validates the frame ranges. - - This is an optional validator checking if the frame range on instance - matches the frame range specified for the folder. - - It also validates render frame ranges of render layers. - - Repair action will change everything to match the folder frame range. - - This can be turned off by the artist to allow custom ranges. - """ - - label = "Validate Frame Range" - order = ValidateContentsOrder - families = ["camera", "maxrender", - "pointcache", "pointcloud", - "review", "redshiftproxy"] - hosts = ["max"] - optional = True - actions = [RepairAction] - - settings_category = "max" - - def process(self, instance): - if not self.is_active(instance.data): - self.log.debug("Skipping Validate Frame Range...") - return - - frame_range = get_frame_range( - instance.data["taskEntity"]) - - inst_frame_start = instance.data.get("frameStartHandle") - inst_frame_end = instance.data.get("frameEndHandle") - if inst_frame_start is None or inst_frame_end is None: - raise KnownPublishError( - "Missing frame start and frame end on " - "instance to to validate." - ) - frame_start_handle = frame_range["frameStartHandle"] - frame_end_handle = frame_range["frameEndHandle"] - errors = [] - if frame_start_handle != inst_frame_start: - errors.append( - f"Start frame ({inst_frame_start}) on instance does not match " # noqa - f"with the start frame ({frame_start_handle}) set on the folder attributes. ") # noqa - if frame_end_handle != inst_frame_end: - errors.append( - f"End frame ({inst_frame_end}) on instance does not match " - f"with the end frame ({frame_end_handle}) " - "from the folder attributes. ") - - if errors: - bullet_point_errors = "\n".join( - "- {}".format(error) for error in errors - ) - report = ( - "Frame range settings are incorrect.\n\n" - f"{bullet_point_errors}\n\n" - "You can use repair action to fix it." - ) - raise PublishValidationError(report, title="Frame Range incorrect") - - @classmethod - def repair(cls, instance): - frame_range = get_frame_range() - frame_start_handle = frame_range["frameStartHandle"] - frame_end_handle = frame_range["frameEndHandle"] - - if instance.data["productType"] == "maxrender": - rt.rendStart = frame_start_handle - rt.rendEnd = frame_end_handle - else: - set_timeline(frame_start_handle, frame_end_handle) diff --git a/server_addon/max/client/ayon_max/plugins/publish/validate_instance_has_members.py b/server_addon/max/client/ayon_max/plugins/publish/validate_instance_has_members.py deleted file mode 100644 index 552e9ea0e2..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/validate_instance_has_members.py +++ /dev/null @@ -1,25 +0,0 @@ -# -*- coding: utf-8 -*- -import pyblish.api -from ayon_core.pipeline import PublishValidationError - - -class ValidateInstanceHasMembers(pyblish.api.InstancePlugin): - """Validates Instance has members. - - Check if MaxScene containers includes any contents underneath. - """ - - order = pyblish.api.ValidatorOrder - families = ["camera", - "model", - "maxScene", - "review", - "pointcache", - "pointcloud", - "redshiftproxy"] - hosts = ["max"] - label = "Container Contents" - - def process(self, instance): - if not instance.data["members"]: - raise PublishValidationError("No content found in the container") diff --git a/server_addon/max/client/ayon_max/plugins/publish/validate_instance_in_context.py b/server_addon/max/client/ayon_max/plugins/publish/validate_instance_in_context.py deleted file mode 100644 index d5bdfe4eb0..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/validate_instance_in_context.py +++ /dev/null @@ -1,86 +0,0 @@ -# -*- coding: utf-8 -*- -"""Validate if instance context is the same as current context.""" -import pyblish.api -from ayon_core.pipeline.publish import ( - RepairAction, - ValidateContentsOrder, - PublishValidationError, - OptionalPyblishPluginMixin -) -from ayon_max.api.action import SelectInvalidAction -from pymxs import runtime as rt - - -class ValidateInstanceInContext(pyblish.api.InstancePlugin, - OptionalPyblishPluginMixin): - """Validator to check if instance context match current context. - - When working in per-shot style you always publish data in context of - current context (shot). This validator checks if this is so. It is optional - so it can be disabled when needed. - - Action on this validator will select invalid instances. - """ - order = ValidateContentsOrder - label = "Instance in same Context" - optional = True - hosts = ["max"] - actions = [SelectInvalidAction, RepairAction] - - settings_category = "max" - - def process(self, instance): - if not self.is_active(instance.data): - return - - folderPath = instance.data.get("folderPath") - task = instance.data.get("task") - context = self.get_context(instance) - if (folderPath, task) != context: - context_label = "{} > {}".format(*context) - instance_label = "{} > {}".format(folderPath, task) - message = ( - "Instance '{}' publishes to different context(folder or task) " - "than current context: {}. Current context: {}".format( - instance.name, instance_label, context_label - ) - ) - raise PublishValidationError( - message=message, - description=( - "## Publishing to a different context data(folder or task)\n" - "There are publish instances present which are publishing " - "into a different folder path or task than your current context.\n\n" - "Usually this is not what you want but there can be cases " - "where you might want to publish into another context or " - "shot. If that's the case you can disable the validation " - "on the instance to ignore it." - ) - ) - - @classmethod - def get_invalid(cls, instance): - invalid = [] - folderPath = instance.data.get("folderPath") - task = instance.data.get("task") - context = cls.get_context(instance) - if (folderPath, task) != context: - invalid.append(rt.getNodeByName(instance.name)) - return invalid - - @classmethod - def repair(cls, instance): - context_asset = instance.context.data["folderPath"] - context_task = instance.context.data["task"] - instance_node = rt.getNodeByName(instance.data.get( - "instance_node", "")) - if not instance_node: - return - rt.SetUserProp(instance_node, "folderPath", context_asset) - rt.SetUserProp(instance_node, "task", context_task) - - @staticmethod - def get_context(instance): - """Return asset, task from publishing context data""" - context = instance.context - return context.data["folderPath"], context.data["task"] diff --git a/server_addon/max/client/ayon_max/plugins/publish/validate_loaded_plugin.py b/server_addon/max/client/ayon_max/plugins/publish/validate_loaded_plugin.py deleted file mode 100644 index 1fddc7998d..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/validate_loaded_plugin.py +++ /dev/null @@ -1,143 +0,0 @@ -# -*- coding: utf-8 -*- -"""Validator for Loaded Plugin.""" -import os -import pyblish.api -from pymxs import runtime as rt - -from ayon_core.pipeline.publish import ( - RepairAction, - OptionalPyblishPluginMixin, - PublishValidationError -) -from ayon_max.api.lib import get_plugins - - -class ValidateLoadedPlugin(OptionalPyblishPluginMixin, - pyblish.api.InstancePlugin): - """Validates if the specific plugin is loaded in 3ds max. - Studio Admin(s) can add the plugins they want to check in validation - via studio defined project settings - """ - - order = pyblish.api.ValidatorOrder - hosts = ["max"] - label = "Validate Loaded Plugins" - optional = True - actions = [RepairAction] - - settings_category = "max" - - family_plugins_mapping = [] - - @classmethod - def get_invalid(cls, instance): - """Plugin entry point.""" - family_plugins_mapping = cls.family_plugins_mapping - if not family_plugins_mapping: - return - - # Backward compatibility - settings did have 'product_types' - if "product_types" in family_plugins_mapping: - family_plugins_mapping["families"] = family_plugins_mapping.pop( - "product_types" - ) - - invalid = [] - # Find all plug-in requirements for current instance - instance_families = {instance.data["productType"]} - instance_families.update(instance.data.get("families", [])) - cls.log.debug("Checking plug-in validation " - f"for instance families: {instance_families}") - all_required_plugins = set() - - for mapping in family_plugins_mapping: - # Check for matching families - if not mapping: - return - - match_families = { - fam.strip() for fam in mapping["families"] - } - has_match = "*" in match_families or match_families.intersection( - instance_families) - - if not has_match: - continue - - cls.log.debug( - f"Found plug-in family requirements: {match_families}") - required_plugins = [ - # match lowercase and format with os.environ to allow - # plugin names defined by max version, e.g. {3DSMAX_VERSION} - plugin.format(**os.environ).lower() - for plugin in mapping["plugins"] - # ignore empty fields in settings - if plugin.strip() - ] - - all_required_plugins.update(required_plugins) - - if not all_required_plugins: - # Instance has no plug-in requirements - return - - # get all DLL loaded plugins in Max and their plugin index - available_plugins = { - plugin_name.lower(): index for index, plugin_name in enumerate( - get_plugins()) - } - # validate the required plug-ins - for plugin in sorted(all_required_plugins): - plugin_index = available_plugins.get(plugin) - if plugin_index is None: - debug_msg = ( - f"Plugin {plugin} does not exist" - " in 3dsMax Plugin List." - ) - invalid.append((plugin, debug_msg)) - continue - if not rt.pluginManager.isPluginDllLoaded(plugin_index): - debug_msg = f"Plugin {plugin} not loaded." - invalid.append((plugin, debug_msg)) - return invalid - - def process(self, instance): - if not self.is_active(instance.data): - self.log.debug("Skipping Validate Loaded Plugin...") - return - invalid = self.get_invalid(instance) - if invalid: - bullet_point_invalid_statement = "\n".join( - "- {}".format(message) for _, message in invalid - ) - report = ( - "Required plugins are not loaded.\n\n" - f"{bullet_point_invalid_statement}\n\n" - "You can use repair action to load the plugin." - ) - raise PublishValidationError( - report, title="Missing Required Plugins") - - @classmethod - def repair(cls, instance): - # get all DLL loaded plugins in Max and their plugin index - invalid = cls.get_invalid(instance) - if not invalid: - return - - # get all DLL loaded plugins in Max and their plugin index - available_plugins = { - plugin_name.lower(): index for index, plugin_name in enumerate( - get_plugins()) - } - - for invalid_plugin, _ in invalid: - plugin_index = available_plugins.get(invalid_plugin) - - if plugin_index is None: - cls.log.warning( - f"Can't enable missing plugin: {invalid_plugin}") - continue - - if not rt.pluginManager.isPluginDllLoaded(plugin_index): - rt.pluginManager.loadPluginDll(plugin_index) diff --git a/server_addon/max/client/ayon_max/plugins/publish/validate_mesh_has_uv.py b/server_addon/max/client/ayon_max/plugins/publish/validate_mesh_has_uv.py deleted file mode 100644 index 31143a60c0..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/validate_mesh_has_uv.py +++ /dev/null @@ -1,62 +0,0 @@ - -import pyblish.api -from ayon_max.api.action import SelectInvalidAction -from ayon_core.pipeline.publish import ( - ValidateMeshOrder, - OptionalPyblishPluginMixin, - PublishValidationError -) -from pymxs import runtime as rt - - -class ValidateMeshHasUVs(pyblish.api.InstancePlugin, - OptionalPyblishPluginMixin): - - """Validate the current mesh has UVs. - - This validator only checks if the mesh has UVs but not - whether all the individual faces of the mesh have UVs. - - It validates whether the current mesh has texture vertices. - If the mesh does not have texture vertices, it does not - have UVs in Max. - - """ - - order = ValidateMeshOrder - hosts = ['max'] - families = ['model'] - label = 'Validate Mesh Has UVs' - actions = [SelectInvalidAction] - optional = True - - settings_category = "max" - - @classmethod - def get_invalid(cls, instance): - meshes = [member for member in instance.data["members"] - if rt.isProperty(member, "mesh")] - invalid = [member for member in meshes - if member.mesh.numTVerts == 0] - return invalid - - def process(self, instance): - if not self.is_active(instance.data): - return - invalid = self.get_invalid(instance) - if invalid: - bullet_point_invalid_statement = "\n".join( - "- {}".format(invalid.name) for invalid - in invalid - ) - report = ( - "Model meshes are required to have UVs.\n\n" - "Meshes detected with invalid or missing UVs:\n" - f"{bullet_point_invalid_statement}\n" - ) - raise PublishValidationError( - report, - description=( - "Model meshes are required to have UVs.\n\n" - "Meshes detected with no texture vertice or missing UVs"), - title="Non-mesh objects found or mesh has missing UVs") diff --git a/server_addon/max/client/ayon_max/plugins/publish/validate_model_contents.py b/server_addon/max/client/ayon_max/plugins/publish/validate_model_contents.py deleted file mode 100644 index 9a4d988aa4..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/validate_model_contents.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- -import pyblish.api -from pymxs import runtime as rt - -from ayon_core.pipeline import PublishValidationError - - -class ValidateModelContent(pyblish.api.InstancePlugin): - """Validates Model instance contents. - - A model instance may only hold either geometry-related - object(excluding Shapes) or editable meshes. - """ - - order = pyblish.api.ValidatorOrder - families = ["model"] - hosts = ["max"] - label = "Model Contents" - - def process(self, instance): - invalid = self.get_invalid(instance) - if invalid: - raise PublishValidationError(("Model instance must only include" - "Geometry and Editable Mesh. " - f"Invalid types on: {invalid}")) - - def get_invalid(self, instance): - """ - Get invalid nodes if the instance is not camera - """ - invalid = [] - container = instance.data["instance_node"] - self.log.info(f"Validating model content for {container}") - - selection_list = instance.data["members"] - for sel in selection_list: - if rt.ClassOf(sel) in rt.Camera.classes: - invalid.append(sel) - if rt.ClassOf(sel) in rt.Light.classes: - invalid.append(sel) - if rt.ClassOf(sel) in rt.Shape.classes: - invalid.append(sel) - - return invalid diff --git a/server_addon/max/client/ayon_max/plugins/publish/validate_model_name.py b/server_addon/max/client/ayon_max/plugins/publish/validate_model_name.py deleted file mode 100644 index d691b739b7..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/validate_model_name.py +++ /dev/null @@ -1,123 +0,0 @@ -# -*- coding: utf-8 -*- -"""Validate model nodes names.""" -import re - -import pyblish.api - -from ayon_max.api.action import SelectInvalidAction - -from ayon_core.pipeline.publish import ( - OptionalPyblishPluginMixin, - PublishXmlValidationError, - ValidateContentsOrder -) - -class ValidateModelName(pyblish.api.InstancePlugin, - OptionalPyblishPluginMixin): - """Validate Model Name. - - Validation regex is `(.*)_(?P.*)_(GEO)` by default. - The setting supports the following regex group name: - - project - - asset - - subset - - Examples: - `{SOME_RANDOM_NAME}_{YOUR_SUBSET_NAME}_GEO` should be your - default model name. - The regex of `(?P.*)` can be replaced by `(?P.*)` - and `(?P.*)`. - `(.*)_(?P.*)_(GEO)` check if your model name is - `{SOME_RANDOM_NAME}_{CURRENT_ASSET_NAME}_GEO` - `(.*)_(?P.*)_(GEO)` check if your model name is - `{SOME_RANDOM_NAME}_{CURRENT_PROJECT_NAME}_GEO` - - """ - optional = True - order = ValidateContentsOrder - hosts = ["max"] - families = ["model"] - label = "Validate Model Name" - actions = [SelectInvalidAction] - - settings_category = "max" - - # defined by settings - regex = r"(.*)_(?P.*)_(GEO)" - # cache - regex_compiled = None - - def process(self, instance): - if not self.is_active(instance.data): - return - - invalid = self.get_invalid(instance) - if invalid: - names = "\n".join( - "- {}".format(node.name) for node in invalid - ) - raise PublishXmlValidationError( - plugin=self, - message="Nodes found with invalid model names: {}".format(invalid), - formatting_data={"nodes": names} - ) - - @classmethod - def get_invalid(cls, instance): - if not cls.regex: - cls.log.warning("No regex pattern set. Nothing to validate.") - return - - members = instance.data.get("members") - if not members: - cls.log.error("No members found in the instance.") - return - - cls.regex_compiled = re.compile(cls.regex) - - invalid = [] - for obj in members: - if cls.invalid_name(instance, obj): - invalid.append(obj) - return invalid - - @classmethod - def invalid_name(cls, instance, obj): - """Function to check the object has invalid name - regarding to the validation regex in the AYON setttings - - Args: - instance (pyblish.api.instance): Instance - obj (str): object name - - Returns: - str: invalid object - """ - regex = cls.regex_compiled - name = obj.name - match = regex.match(name) - - if match is None: - cls.log.error("Invalid model name on: %s", name) - cls.log.error("Name doesn't match regex {}".format(regex.pattern)) - return obj - - # Validate regex groups - invalid = False - compare = { - "project": instance.context.data["projectName"], - "asset": instance.data["folderPath"], - "subset": instance.data["productName"] - } - for key, required_value in compare.items(): - if key in regex.groupindex: - if match.group(key) != required_value: - cls.log.error( - "Invalid %s name for the model %s, " - "required name is %s", - key, name, required_value - ) - invalid = True - - if invalid: - return obj diff --git a/server_addon/max/client/ayon_max/plugins/publish/validate_no_animation.py b/server_addon/max/client/ayon_max/plugins/publish/validate_no_animation.py deleted file mode 100644 index 26384954ca..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/validate_no_animation.py +++ /dev/null @@ -1,69 +0,0 @@ -# -*- coding: utf-8 -*- -import pyblish.api -from pymxs import runtime as rt -from ayon_core.pipeline import ( - PublishValidationError, - OptionalPyblishPluginMixin -) -from ayon_max.api.action import SelectInvalidAction - - -def get_invalid_keys(obj): - """function to check on whether there is keyframe in - - Args: - obj (str): object needed to check if there is a keyframe - - Returns: - bool: whether invalid object(s) exist - """ - for transform in ["Position", "Rotation", "Scale"]: - num_of_key = rt.NumKeys(rt.getPropertyController( - obj.controller, transform)) - if num_of_key > 0: - return True - return False - - -class ValidateNoAnimation(pyblish.api.InstancePlugin, - OptionalPyblishPluginMixin): - """Validates No Animation - - Ensure no keyframes on nodes in the Instance - """ - - order = pyblish.api.ValidatorOrder - families = ["model"] - hosts = ["max"] - optional = True - label = "Validate No Animation" - actions = [SelectInvalidAction] - - settings_category = "max" - - def process(self, instance): - if not self.is_active(instance.data): - return - invalid = self.get_invalid(instance) - if invalid: - raise PublishValidationError( - "Keyframes found on:\n\n{0}".format(invalid) - , - title="Keyframes on model" - ) - - @staticmethod - def get_invalid(instance): - """Get invalid object(s) which have keyframe(s) - - - Args: - instance (pyblish.api.instance): Instance - - Returns: - list: list of invalid objects - """ - invalid = [invalid for invalid in instance.data["members"] - if invalid.isAnimated or get_invalid_keys(invalid)] - - return invalid diff --git a/server_addon/max/client/ayon_max/plugins/publish/validate_pointcloud.py b/server_addon/max/client/ayon_max/plugins/publish/validate_pointcloud.py deleted file mode 100644 index 73b18984ed..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/validate_pointcloud.py +++ /dev/null @@ -1,126 +0,0 @@ -import pyblish.api -from ayon_core.pipeline import PublishValidationError -from pymxs import runtime as rt - - -class ValidatePointCloud(pyblish.api.InstancePlugin): - """Validate that work file was saved.""" - - order = pyblish.api.ValidatorOrder - families = ["pointcloud"] - hosts = ["max"] - label = "Validate Point Cloud" - - def process(self, instance): - """ - Notes: - 1. Validate if the export mode of Export Particle is at PRT format - 2. Validate the partition count and range set as default value - Partition Count : 100 - Partition Range : 1 to 1 - 3. Validate if the custom attribute(s) exist as parameter(s) - of export_particle operator - - """ - report = [] - - if self.validate_export_mode(instance): - report.append("The export mode is not at PRT") - - if self.validate_partition_value(instance): - report.append(("tyFlow Partition setting is " - "not at the default value")) - - invalid_attribute = self.validate_custom_attribute(instance) - if invalid_attribute: - report.append(("Custom Attribute not found " - f":{invalid_attribute}")) - - if report: - raise PublishValidationError(f"{report}") - - def validate_custom_attribute(self, instance): - invalid = [] - container = instance.data["instance_node"] - self.log.info( - f"Validating tyFlow custom attributes for {container}") - - selection_list = instance.data["members"] - - project_settings = instance.context.data["project_settings"] - attr_settings = project_settings["max"]["PointCloud"]["attribute"] - for sel in selection_list: - obj = sel.baseobject - anim_names = rt.GetSubAnimNames(obj) - for anim_name in anim_names: - # get all the names of the related tyFlow nodes - sub_anim = rt.GetSubAnim(obj, anim_name) - if rt.IsProperty(sub_anim, "Export_Particles"): - event_name = sub_anim.name - opt = "${0}.{1}.export_particles".format(sel.name, - event_name) - for attr in attr_settings: - key = attr["name"] - value = attr["value"] - custom_attr = "{0}.PRTChannels_{1}".format(opt, - value) - try: - rt.Execute(custom_attr) - except RuntimeError: - invalid.append(key) - - return invalid - - def validate_partition_value(self, instance): - invalid = [] - container = instance.data["instance_node"] - self.log.info( - f"Validating tyFlow partition value for {container}") - - selection_list = instance.data["members"] - for sel in selection_list: - obj = sel.baseobject - anim_names = rt.GetSubAnimNames(obj) - for anim_name in anim_names: - # get all the names of the related tyFlow nodes - sub_anim = rt.GetSubAnim(obj, anim_name) - if rt.IsProperty(sub_anim, "Export_Particles"): - event_name = sub_anim.name - opt = "${0}.{1}.export_particles".format(sel.name, - event_name) - count = rt.Execute(f'{opt}.PRTPartitionsCount') - if count != 100: - invalid.append(count) - start = rt.Execute(f'{opt}.PRTPartitionsFrom') - if start != 1: - invalid.append(start) - end = rt.Execute(f'{opt}.PRTPartitionsTo') - if end != 1: - invalid.append(end) - - return invalid - - def validate_export_mode(self, instance): - invalid = [] - container = instance.data["instance_node"] - self.log.info( - f"Validating tyFlow export mode for {container}") - - con = rt.GetNodeByName(container) - selection_list = list(con.Children) - for sel in selection_list: - obj = sel.baseobject - anim_names = rt.GetSubAnimNames(obj) - for anim_name in anim_names: - # get all the names of the related tyFlow nodes - sub_anim = rt.GetSubAnim(obj, anim_name) - # check if there is export particle operator - boolean = rt.IsProperty(sub_anim, "Export_Particles") - event_name = sub_anim.name - if boolean: - opt = f"${sel.name}.{event_name}.export_particles" - export_mode = rt.Execute(f'{opt}.exportMode') - if export_mode != 1: - invalid.append(export_mode) - - return invalid diff --git a/server_addon/max/client/ayon_max/plugins/publish/validate_renderable_camera.py b/server_addon/max/client/ayon_max/plugins/publish/validate_renderable_camera.py deleted file mode 100644 index dc05771e1b..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/validate_renderable_camera.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -import pyblish.api -from ayon_core.pipeline import ( - PublishValidationError, - OptionalPyblishPluginMixin) -from ayon_core.pipeline.publish import RepairAction -from ayon_max.api.lib import get_current_renderer - -from pymxs import runtime as rt - - -class ValidateRenderableCamera(pyblish.api.InstancePlugin, - OptionalPyblishPluginMixin): - """Validates Renderable Camera - - Check if the renderable camera used for rendering - """ - - order = pyblish.api.ValidatorOrder - families = ["maxrender"] - hosts = ["max"] - label = "Renderable Camera" - optional = True - actions = [RepairAction] - - def process(self, instance): - if not self.is_active(instance.data): - return - if not instance.data["cameras"]: - raise PublishValidationError( - "No renderable Camera found in scene." - ) - - @classmethod - def repair(cls, instance): - - rt.viewport.setType(rt.Name("view_camera")) - camera = rt.viewport.GetCamera() - cls.log.info(f"Camera {camera} set as renderable camera") - renderer_class = get_current_renderer() - renderer = str(renderer_class).split(":")[0] - if renderer == "Arnold": - arv = rt.MAXToAOps.ArnoldRenderView() - arv.setOption("Camera", str(camera)) - arv.close() - instance.data["cameras"] = [camera.name] diff --git a/server_addon/max/client/ayon_max/plugins/publish/validate_renderer_redshift_proxy.py b/server_addon/max/client/ayon_max/plugins/publish/validate_renderer_redshift_proxy.py deleted file mode 100644 index 66c69bc100..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/validate_renderer_redshift_proxy.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -import pyblish.api -from ayon_core.pipeline import PublishValidationError -from pymxs import runtime as rt -from ayon_core.pipeline.publish import RepairAction -from ayon_max.api.lib import get_current_renderer - - -class ValidateRendererRedshiftProxy(pyblish.api.InstancePlugin): - """ - Validates Redshift as the current renderer for creating - Redshift Proxy - """ - - order = pyblish.api.ValidatorOrder - families = ["redshiftproxy"] - hosts = ["max"] - label = "Redshift Renderer" - actions = [RepairAction] - - def process(self, instance): - invalid = self.get_redshift_renderer(instance) - if invalid: - raise PublishValidationError("Please install Redshift for 3dsMax" - " before using the Redshift proxy instance") # noqa - invalid = self.get_current_renderer(instance) - if invalid: - raise PublishValidationError("The Redshift proxy extraction" - "discontinued since the current renderer is not Redshift") # noqa - - def get_redshift_renderer(self, instance): - invalid = list() - max_renderers_list = str(rt.RendererClass.classes) - if "Redshift_Renderer" not in max_renderers_list: - invalid.append(max_renderers_list) - - return invalid - - def get_current_renderer(self, instance): - invalid = list() - renderer_class = get_current_renderer() - current_renderer = str(renderer_class).split(":")[0] - if current_renderer != "Redshift_Renderer": - invalid.append(current_renderer) - - return invalid - - @classmethod - def repair(cls, instance): - for Renderer in rt.RendererClass.classes: - renderer = Renderer() - if "Redshift_Renderer" in str(renderer): - rt.renderers.production = renderer - break diff --git a/server_addon/max/client/ayon_max/plugins/publish/validate_renderpasses.py b/server_addon/max/client/ayon_max/plugins/publish/validate_renderpasses.py deleted file mode 100644 index d0d47c6340..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/validate_renderpasses.py +++ /dev/null @@ -1,187 +0,0 @@ -import os -import pyblish.api -from pymxs import runtime as rt -from ayon_core.pipeline.publish import ( - RepairAction, - ValidateContentsOrder, - PublishValidationError, - OptionalPyblishPluginMixin -) -from ayon_max.api.lib_rendersettings import RenderSettings - - -class ValidateRenderPasses(OptionalPyblishPluginMixin, - pyblish.api.InstancePlugin): - """Validates Render Passes before farm submission - """ - - order = ValidateContentsOrder - families = ["maxrender"] - hosts = ["max"] - label = "Validate Render Passes" - actions = [RepairAction] - - settings_category = "max" - - def process(self, instance): - invalid = self.get_invalid(instance) - if invalid: - bullet_point_invalid_statement = "\n".join( - f"- {err_type}: {filepath}" for err_type, filepath - in invalid - ) - report = ( - "Invalid render passes found.\n\n" - f"{bullet_point_invalid_statement}\n\n" - "You can use repair action to fix the invalid filepath." - ) - raise PublishValidationError( - report, title="Invalid Render Passes") - - @classmethod - def get_invalid(cls, instance): - """Function to get invalid beauty render outputs and - render elements. - - 1. Check Render Output Folder matches the name of - the current Max Scene, e.g. - The name of the current Max scene: - John_Doe.max - The expected render output directory: - {root[work]}/{project[name]}/{hierarchy}/{asset}/ - work/{task[name]}/render/3dsmax/John_Doe/ - - 2. Check image extension(s) of the render output(s) - matches the image format in OP/AYON setting, e.g. - The current image format in settings: png - The expected render outputs: John_Doe.png - - 3. Check filename of render element ends with the name of - render element from the 3dsMax Render Element Manager. - e.g. The name of render element: RsCryptomatte - The expected filename: {InstanceName}_RsCryptomatte.png - - Args: - instance (pyblish.api.Instance): instance - workfile_name (str): filename of the Max scene - - Returns: - list: list of invalid filename which doesn't match - with the project name - """ - invalid = [] - file = rt.maxFileName - workfile_name, ext = os.path.splitext(file) - if workfile_name not in rt.rendOutputFilename: - cls.log.error( - "Render output folder must include" - f" the max scene name {workfile_name} " - ) - invalid_folder_name = os.path.dirname( - rt.rendOutputFilename).replace( - "\\", "/").split("/")[-1] - invalid.append(("Invalid Render Output Folder", - invalid_folder_name)) - beauty_fname = os.path.basename(rt.rendOutputFilename) - beauty_name, ext = os.path.splitext(beauty_fname) - invalid_filenames = cls.get_invalid_filenames( - instance, beauty_name) - invalid.extend(invalid_filenames) - invalid_image_format = cls.get_invalid_image_format( - instance, ext.lstrip(".")) - invalid.extend(invalid_image_format) - renderer = instance.data["renderer"] - if renderer in [ - "ART_Renderer", - "Redshift_Renderer", - "V_Ray_6_Hotfix_3", - "V_Ray_GPU_6_Hotfix_3", - "Default_Scanline_Renderer", - "Quicksilver_Hardware_Renderer", - ]: - render_elem = rt.maxOps.GetCurRenderElementMgr() - render_elem_num = render_elem.NumRenderElements() - for i in range(render_elem_num): - renderlayer_name = render_elem.GetRenderElement(i) - renderpass = str(renderlayer_name).rsplit(":", 1)[-1] - rend_file = render_elem.GetRenderElementFilename(i) - if not rend_file: - continue - - rend_fname, ext = os.path.splitext( - os.path.basename(rend_file)) - invalid_filenames = cls.get_invalid_filenames( - instance, rend_fname, renderpass=renderpass) - invalid.extend(invalid_filenames) - invalid_image_format = cls.get_invalid_image_format( - instance, ext) - invalid.extend(invalid_image_format) - elif renderer == "Arnold": - cls.log.debug( - "Renderpass validation does not support Arnold yet," - " validation skipped...") - else: - cls.log.debug( - "Skipping render element validation " - f"for renderer: {renderer}") - return invalid - - @classmethod - def get_invalid_filenames(cls, instance, file_name, renderpass=None): - """Function to get invalid filenames from render outputs. - - Args: - instance (pyblish.api.Instance): instance - file_name (str): name of the file - renderpass (str, optional): name of the renderpass. - Defaults to None. - - Returns: - list: invalid filenames - """ - invalid = [] - if instance.name not in file_name: - cls.log.error("The renderpass filename should contain the instance name.") - invalid.append(("Invalid instance name", - file_name)) - if renderpass is not None: - if not file_name.rstrip(".").endswith(renderpass): - cls.log.error( - f"Filename for {renderpass} should " - f"end with {renderpass}: {file_name}" - ) - invalid.append((f"Invalid {renderpass}", - os.path.basename(file_name))) - return invalid - - @classmethod - def get_invalid_image_format(cls, instance, ext): - """Function to check if the image format of the render outputs - aligns with that in the setting. - - Args: - instance (pyblish.api.Instance): instance - ext (str): image extension - - Returns: - list: list of files with invalid image format - """ - invalid = [] - settings = instance.context.data["project_settings"].get("max") - image_format = settings["RenderSettings"]["image_format"] - ext = ext.lstrip(".") - if ext != image_format: - msg = ( - f"Invalid image format {ext} for render outputs.\n" - f"Should be: {image_format}") - cls.log.error(msg) - invalid.append((msg, ext)) - return invalid - - @classmethod - def repair(cls, instance): - container = instance.data.get("instance_node") - # TODO: need to rename the function of render_output - RenderSettings().render_output(container) - cls.log.debug("Finished repairing the render output " - "folder and filenames.") diff --git a/server_addon/max/client/ayon_max/plugins/publish/validate_resolution_setting.py b/server_addon/max/client/ayon_max/plugins/publish/validate_resolution_setting.py deleted file mode 100644 index 9f7ec17dd9..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/validate_resolution_setting.py +++ /dev/null @@ -1,92 +0,0 @@ -import pyblish.api -from pymxs import runtime as rt -from ayon_core.pipeline import ( - OptionalPyblishPluginMixin -) -from ayon_core.pipeline.publish import ( - RepairAction, - PublishValidationError -) -from ayon_max.api.lib import ( - reset_scene_resolution, - imprint -) - - -class ValidateResolutionSetting(pyblish.api.InstancePlugin, - OptionalPyblishPluginMixin): - """Validate the resolution setting aligned with DB""" - - order = pyblish.api.ValidatorOrder - 0.01 - families = ["maxrender"] - hosts = ["max"] - label = "Validate Resolution Setting" - optional = True - actions = [RepairAction] - - def process(self, instance): - if not self.is_active(instance.data): - return - width, height = self.get_folder_resolution(instance) - current_width, current_height = ( - self.get_current_resolution(instance) - ) - - if current_width != width and current_height != height: - raise PublishValidationError("Resolution Setting " - "not matching resolution " - "set on asset or shot.") - if current_width != width: - raise PublishValidationError("Width in Resolution Setting " - "not matching resolution set " - "on asset or shot.") - - if current_height != height: - raise PublishValidationError("Height in Resolution Setting " - "not matching resolution set " - "on asset or shot.") - - def get_current_resolution(self, instance): - return rt.renderWidth, rt.renderHeight - - @classmethod - def get_folder_resolution(cls, instance): - task_entity = instance.data.get("taskEntity") - if task_entity: - task_attributes = task_entity["attrib"] - width = task_attributes["resolutionWidth"] - height = task_attributes["resolutionHeight"] - return int(width), int(height) - - # Defaults if not found in folder entity - return 1920, 1080 - - @classmethod - def repair(cls, instance): - reset_scene_resolution() - - -class ValidateReviewResolutionSetting(ValidateResolutionSetting): - families = ["review"] - optional = True - actions = [RepairAction] - - def get_current_resolution(self, instance): - current_width = instance.data["review_width"] - current_height = instance.data["review_height"] - return current_width, current_height - - @classmethod - def repair(cls, instance): - context_width, context_height = ( - cls.get_folder_resolution(instance) - ) - creator_attrs = instance.data["creator_attributes"] - creator_attrs["review_width"] = context_width - creator_attrs["review_height"] = context_height - creator_attrs_data = { - "creator_attributes": creator_attrs - } - # update the width and height of review - # data in creator_attributes - imprint(instance.data["instance_node"], creator_attrs_data) diff --git a/server_addon/max/client/ayon_max/plugins/publish/validate_scene_saved.py b/server_addon/max/client/ayon_max/plugins/publish/validate_scene_saved.py deleted file mode 100644 index 3028a55337..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/validate_scene_saved.py +++ /dev/null @@ -1,18 +0,0 @@ -# -*- coding: utf-8 -*- -import pyblish.api -from ayon_core.pipeline import PublishValidationError -from pymxs import runtime as rt - - -class ValidateSceneSaved(pyblish.api.InstancePlugin): - """Validate that workfile was saved.""" - - order = pyblish.api.ValidatorOrder - families = ["workfile"] - hosts = ["max"] - label = "Validate Workfile is saved" - - def process(self, instance): - if not rt.maxFilePath or not rt.maxFileName: - raise PublishValidationError( - "Workfile is not saved", title=self.label) diff --git a/server_addon/max/client/ayon_max/plugins/publish/validate_tyflow_data.py b/server_addon/max/client/ayon_max/plugins/publish/validate_tyflow_data.py deleted file mode 100644 index 8dd8a1bb68..0000000000 --- a/server_addon/max/client/ayon_max/plugins/publish/validate_tyflow_data.py +++ /dev/null @@ -1,88 +0,0 @@ -import pyblish.api -from ayon_core.pipeline import PublishValidationError -from pymxs import runtime as rt - - -class ValidateTyFlowData(pyblish.api.InstancePlugin): - """Validate TyFlow plugins or relevant operators are set correctly.""" - - order = pyblish.api.ValidatorOrder - families = ["pointcloud", "tycache"] - hosts = ["max"] - label = "TyFlow Data" - - def process(self, instance): - """ - Notes: - 1. Validate the container only include tyFlow objects - 2. Validate if tyFlow operator Export Particle exists - - """ - - invalid_object = self.get_tyflow_object(instance) - if invalid_object: - self.log.error(f"Non tyFlow object found: {invalid_object}") - - invalid_operator = self.get_tyflow_operator(instance) - if invalid_operator: - self.log.error( - "Operator 'Export Particles' not found in tyFlow editor.") - if invalid_object or invalid_operator: - raise PublishValidationError( - "issues occurred", - description="Container should only include tyFlow object " - "and tyflow operator 'Export Particle' should be in " - "the tyFlow editor.") - - def get_tyflow_object(self, instance): - """Get the nodes which are not tyFlow object(s) - and editable mesh(es) - - Args: - instance (pyblish.api.Instance): instance - - Returns: - list: invalid nodes which are not tyFlow - object(s) and editable mesh(es). - """ - container = instance.data["instance_node"] - self.log.debug(f"Validating tyFlow container for {container}") - - allowed_classes = [rt.tyFlow, rt.Editable_Mesh] - return [ - member for member in instance.data["members"] - if rt.ClassOf(member) not in allowed_classes - ] - - def get_tyflow_operator(self, instance): - """Check if the Export Particle Operators in the node - connections. - - Args: - instance (str): instance node - - Returns: - invalid(list): list of invalid nodes which do - not consist of Export Particle Operators as parts - of the node connections - """ - invalid = [] - members = instance.data["members"] - for member in members: - obj = member.baseobject - - # There must be at least one animation with export - # particles enabled - has_export_particles = False - anim_names = rt.GetSubAnimNames(obj) - for anim_name in anim_names: - # get name of the related tyFlow node - sub_anim = rt.GetSubAnim(obj, anim_name) - # check if there is export particle operator - if rt.IsProperty(sub_anim, "Export_Particles"): - has_export_particles = True - break - - if not has_export_particles: - invalid.append(member) - return invalid diff --git a/server_addon/max/client/ayon_max/startup/startup.ms b/server_addon/max/client/ayon_max/startup/startup.ms deleted file mode 100644 index c5b4f0e526..0000000000 --- a/server_addon/max/client/ayon_max/startup/startup.ms +++ /dev/null @@ -1,15 +0,0 @@ --- AYON Init Script -( - local sysPath = dotNetClass "System.IO.Path" - local sysDir = dotNetClass "System.IO.Directory" - local localScript = getThisScriptFilename() - local startup = sysPath.Combine (sysPath.GetDirectoryName localScript) "startup.py" - - local pythonpath = systemTools.getEnvVariable "MAX_PYTHONPATH" - systemTools.setEnvVariable "PYTHONPATH" pythonpath - - /*opens the create menu on startup to ensure users are presented with a useful default view.*/ - max create mode - - python.ExecuteFile startup -) diff --git a/server_addon/max/client/ayon_max/startup/startup.py b/server_addon/max/client/ayon_max/startup/startup.py deleted file mode 100644 index 1462cc93b7..0000000000 --- a/server_addon/max/client/ayon_max/startup/startup.py +++ /dev/null @@ -1,13 +0,0 @@ -# -*- coding: utf-8 -*- -import os -import sys -from ayon_max.api import MaxHost -from ayon_core.pipeline import install_host -# this might happen in some 3dsmax version where PYTHONPATH isn't added -# to sys.path automatically -for path in os.environ["PYTHONPATH"].split(os.pathsep): - if path and path not in sys.path: - sys.path.append(path) - -host = MaxHost() -install_host(host) diff --git a/server_addon/max/client/ayon_max/version.py b/server_addon/max/client/ayon_max/version.py deleted file mode 100644 index acb68bbdfc..0000000000 --- a/server_addon/max/client/ayon_max/version.py +++ /dev/null @@ -1,3 +0,0 @@ -# -*- coding: utf-8 -*- -"""Package declaring AYON addon 'max' version.""" -__version__ = "0.2.1" diff --git a/server_addon/max/package.py b/server_addon/max/package.py deleted file mode 100644 index 09e86f8d50..0000000000 --- a/server_addon/max/package.py +++ /dev/null @@ -1,9 +0,0 @@ -name = "max" -title = "Max" -version = "0.2.1" -client_dir = "ayon_max" - -ayon_required_addons = { - "core": ">0.3.2", -} -ayon_compatible_addons = {} diff --git a/server_addon/max/server/__init__.py b/server_addon/max/server/__init__.py deleted file mode 100644 index d03b29d249..0000000000 --- a/server_addon/max/server/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Type - -from ayon_server.addons import BaseServerAddon - -from .settings import MaxSettings, DEFAULT_VALUES - - -class MaxAddon(BaseServerAddon): - settings_model: Type[MaxSettings] = MaxSettings - - async def get_default_settings(self): - settings_model_cls = self.get_settings_model() - return settings_model_cls(**DEFAULT_VALUES) diff --git a/server_addon/max/server/settings/__init__.py b/server_addon/max/server/settings/__init__.py deleted file mode 100644 index 986b1903a5..0000000000 --- a/server_addon/max/server/settings/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -from .main import ( - MaxSettings, - DEFAULT_VALUES, -) - - -__all__ = ( - "MaxSettings", - "DEFAULT_VALUES", -) diff --git a/server_addon/max/server/settings/create_review_settings.py b/server_addon/max/server/settings/create_review_settings.py deleted file mode 100644 index 807976a391..0000000000 --- a/server_addon/max/server/settings/create_review_settings.py +++ /dev/null @@ -1,91 +0,0 @@ -from ayon_server.settings import BaseSettingsModel, SettingsField - - -def image_format_enum(): - """Return enumerator for image output formats.""" - return [ - {"label": "exr", "value": "exr"}, - {"label": "jpg", "value": "jpg"}, - {"label": "png", "value": "png"}, - {"label": "tga", "value": "tga"} - ] - - -def visual_style_enum(): - """Return enumerator for viewport visual style.""" - return [ - {"label": "Realistic", "value": "Realistic"}, - {"label": "Shaded", "value": "Shaded"}, - {"label": "Facets", "value": "Facets"}, - {"label": "ConsistentColors", - "value": "ConsistentColors"}, - {"label": "Wireframe", "value": "Wireframe"}, - {"label": "BoundingBox", "value": "BoundingBox"}, - {"label": "Ink", "value": "Ink"}, - {"label": "ColorInk", "value": "ColorInk"}, - {"label": "Acrylic", "value": "Acrylic"}, - {"label": "Tech", "value": "Tech"}, - {"label": "Graphite", "value": "Graphite"}, - {"label": "ColorPencil", "value": "ColorPencil"}, - {"label": "Pastel", "value": "Pastel"}, - {"label": "Clay", "value": "Clay"}, - {"label": "ModelAssist", "value": "ModelAssist"} - ] - - -def preview_preset_enum(): - """Return enumerator for viewport visual preset.""" - return [ - {"label": "Quality", "value": "Quality"}, - {"label": "Standard", "value": "Standard"}, - {"label": "Performance", "value": "Performance"}, - {"label": "DXMode", "value": "DXMode"}, - {"label": "Customize", "value": "Customize"}, - ] - - -def anti_aliasing_enum(): - """Return enumerator for viewport anti-aliasing.""" - return [ - {"label": "None", "value": "None"}, - {"label": "2X", "value": "2X"}, - {"label": "4X", "value": "4X"}, - {"label": "8X", "value": "8X"} - ] - - -class CreateReviewModel(BaseSettingsModel): - review_width: int = SettingsField(1920, title="Review Width") - review_height: int = SettingsField(1080, title="Review Height") - percentSize: float = SettingsField(100.0, title="Percent of Output") - keep_images: bool = SettingsField(False, title="Keep Image Sequences") - image_format: str = SettingsField( - enum_resolver=image_format_enum, - title="Image Format Options" - ) - visual_style: str = SettingsField( - enum_resolver=visual_style_enum, - title="Preference" - ) - viewport_preset: str = SettingsField( - enum_resolver=preview_preset_enum, - title="Preview Preset" - ) - anti_aliasing: str = SettingsField( - enum_resolver=anti_aliasing_enum, - title="Anti-aliasing Quality" - ) - vp_texture: bool = SettingsField(True, title="Viewport Texture") - - -DEFAULT_CREATE_REVIEW_SETTINGS = { - "review_width": 1920, - "review_height": 1080, - "percentSize": 100.0, - "keep_images": False, - "image_format": "png", - "visual_style": "Realistic", - "viewport_preset": "Quality", - "anti_aliasing": "None", - "vp_texture": True -} diff --git a/server_addon/max/server/settings/imageio.py b/server_addon/max/server/settings/imageio.py deleted file mode 100644 index 9c6f1b6409..0000000000 --- a/server_addon/max/server/settings/imageio.py +++ /dev/null @@ -1,63 +0,0 @@ -from pydantic import validator -from ayon_server.settings import BaseSettingsModel, SettingsField -from ayon_server.settings.validators import ensure_unique_names - - -class ImageIOConfigModel(BaseSettingsModel): - """[DEPRECATED] Addon OCIO config settings. Please set the OCIO config - path in the Core addon profiles here - (ayon+settings://core/imageio/ocio_config_profiles). - """ - - override_global_config: bool = SettingsField( - False, - title="Override global OCIO config", - description=( - "DEPRECATED functionality. Please set the OCIO config path in the " - "Core addon profiles here (ayon+settings://core/imageio/" - "ocio_config_profiles)." - ), - ) - filepath: list[str] = SettingsField( - default_factory=list, - title="Config path", - description=( - "DEPRECATED functionality. Please set the OCIO config path in the " - "Core addon profiles here (ayon+settings://core/imageio/" - "ocio_config_profiles)." - ), - ) - - -class ImageIOFileRuleModel(BaseSettingsModel): - name: str = SettingsField("", title="Rule name") - pattern: str = SettingsField("", title="Regex pattern") - colorspace: str = SettingsField("", title="Colorspace name") - ext: str = SettingsField("", title="File extension") - - -class ImageIOFileRulesModel(BaseSettingsModel): - activate_host_rules: bool = SettingsField(False) - rules: list[ImageIOFileRuleModel] = SettingsField( - default_factory=list, - title="Rules" - ) - - @validator("rules") - def validate_unique_outputs(cls, value): - ensure_unique_names(value) - return value - - -class ImageIOSettings(BaseSettingsModel): - activate_host_color_management: bool = SettingsField( - True, title="Enable Color Management" - ) - ocio_config: ImageIOConfigModel = SettingsField( - default_factory=ImageIOConfigModel, - title="OCIO config" - ) - file_rules: ImageIOFileRulesModel = SettingsField( - default_factory=ImageIOFileRulesModel, - title="File Rules" - ) diff --git a/server_addon/max/server/settings/main.py b/server_addon/max/server/settings/main.py deleted file mode 100644 index 7b0bfc6421..0000000000 --- a/server_addon/max/server/settings/main.py +++ /dev/null @@ -1,94 +0,0 @@ -from ayon_server.settings import BaseSettingsModel, SettingsField -from .imageio import ImageIOSettings -from .render_settings import ( - RenderSettingsModel, DEFAULT_RENDER_SETTINGS -) -from .create_review_settings import ( - CreateReviewModel, DEFAULT_CREATE_REVIEW_SETTINGS -) -from .publishers import ( - PublishersModel, DEFAULT_PUBLISH_SETTINGS -) - - -def unit_scale_enum(): - """Return enumerator for scene unit scale.""" - return [ - {"label": "mm", "value": "Millimeters"}, - {"label": "cm", "value": "Centimeters"}, - {"label": "m", "value": "Meters"}, - {"label": "km", "value": "Kilometers"} - ] - - -class UnitScaleSettings(BaseSettingsModel): - enabled: bool = SettingsField(True, title="Enabled") - scene_unit_scale: str = SettingsField( - "Centimeters", - title="Scene Unit Scale", - enum_resolver=unit_scale_enum - ) - - -class PRTAttributesModel(BaseSettingsModel): - _layout = "compact" - name: str = SettingsField(title="Name") - value: str = SettingsField(title="Attribute") - - -class PointCloudSettings(BaseSettingsModel): - attribute: list[PRTAttributesModel] = SettingsField( - default_factory=list, title="Channel Attribute") - - -class MaxSettings(BaseSettingsModel): - unit_scale_settings: UnitScaleSettings = SettingsField( - default_factory=UnitScaleSettings, - title="Set Unit Scale" - ) - imageio: ImageIOSettings = SettingsField( - default_factory=ImageIOSettings, - title="Color Management (ImageIO)" - ) - RenderSettings: RenderSettingsModel = SettingsField( - default_factory=RenderSettingsModel, - title="Render Settings" - ) - CreateReview: CreateReviewModel = SettingsField( - default_factory=CreateReviewModel, - title="Create Review" - ) - PointCloud: PointCloudSettings = SettingsField( - default_factory=PointCloudSettings, - title="Point Cloud" - ) - publish: PublishersModel = SettingsField( - default_factory=PublishersModel, - title="Publish Plugins") - - -DEFAULT_VALUES = { - "unit_scale_settings": { - "enabled": True, - "scene_unit_scale": "Centimeters" - }, - "RenderSettings": DEFAULT_RENDER_SETTINGS, - "CreateReview": DEFAULT_CREATE_REVIEW_SETTINGS, - "PointCloud": { - "attribute": [ - {"name": "Age", "value": "age"}, - {"name": "Radius", "value": "radius"}, - {"name": "Position", "value": "position"}, - {"name": "Rotation", "value": "rotation"}, - {"name": "Scale", "value": "scale"}, - {"name": "Velocity", "value": "velocity"}, - {"name": "Color", "value": "color"}, - {"name": "TextureCoordinate", "value": "texcoord"}, - {"name": "MaterialID", "value": "matid"}, - {"name": "custFloats", "value": "custFloats"}, - {"name": "custVecs", "value": "custVecs"}, - ] - }, - "publish": DEFAULT_PUBLISH_SETTINGS - -} diff --git a/server_addon/max/server/settings/publishers.py b/server_addon/max/server/settings/publishers.py deleted file mode 100644 index 5e1b348d92..0000000000 --- a/server_addon/max/server/settings/publishers.py +++ /dev/null @@ -1,222 +0,0 @@ -import json -from pydantic import validator - -from ayon_server.settings import BaseSettingsModel, SettingsField -from ayon_server.exceptions import BadRequestException - - -class ValidateAttributesModel(BaseSettingsModel): - enabled: bool = SettingsField(title="ValidateAttributes") - attributes: str = SettingsField( - "{}", title="Attributes", widget="textarea") - - @validator("attributes") - def validate_json(cls, value): - if not value.strip(): - return "{}" - try: - converted_value = json.loads(value) - success = isinstance(converted_value, dict) - except json.JSONDecodeError: - success = False - - if not success: - raise BadRequestException( - "The attibutes can't be parsed as json object" - ) - return value - - -class ValidateCameraAttributesModel(BaseSettingsModel): - enabled: bool = SettingsField(title="Enabled") - optional: bool = SettingsField(title="Optional") - active: bool = SettingsField(title="Active") - fov: float = SettingsField(0.0, title="Focal Length") - nearrange: float = SettingsField(0.0, title="Near Range") - farrange: float = SettingsField(0.0, title="Far Range") - nearclip: float = SettingsField(0.0, title="Near Clip") - farclip: float = SettingsField(0.0, title="Far Clip") - - -class FamilyMappingItemModel(BaseSettingsModel): - families: list[str] = SettingsField( - default_factory=list, - title="Families" - ) - plugins: list[str] = SettingsField( - default_factory=list, - title="Plugins" - ) - - -class ValidateModelNameModel(BaseSettingsModel): - enabled: bool = SettingsField(title="Enabled") - optional: bool = SettingsField(title="Optional") - active: bool = SettingsField(title="Active") - regex: str = SettingsField( - "(.*)_(?P.*)_(GEO)", - title="Validation regex", - description=( - "Regex for validating model name. You can use named " - " capturing groups:(?P.*) for Asset name" - ) - ) - - -class ValidateLoadedPluginModel(BaseSettingsModel): - enabled: bool = SettingsField(title="Enabled") - optional: bool = SettingsField(title="Optional") - family_plugins_mapping: list[FamilyMappingItemModel] = SettingsField( - default_factory=list, - title="Family Plugins Mapping" - ) - - -class BasicValidateModel(BaseSettingsModel): - enabled: bool = SettingsField(title="Enabled") - optional: bool = SettingsField(title="Optional") - active: bool = SettingsField(title="Active") - - -class PublishersModel(BaseSettingsModel): - ValidateInstanceInContext: BasicValidateModel = SettingsField( - default_factory=BasicValidateModel, - title="Validate Instance In Context", - section="Validators" - ) - ValidateFrameRange: BasicValidateModel = SettingsField( - default_factory=BasicValidateModel, - title="Validate Frame Range" - ) - ValidateAttributes: ValidateAttributesModel = SettingsField( - default_factory=ValidateAttributesModel, - title="Validate Attributes" - ) - ValidateCameraAttributes: ValidateCameraAttributesModel = SettingsField( - default_factory=ValidateCameraAttributesModel, - title="Validate Camera Attributes", - description=( - "If the value of the camera attributes set to 0, " - "the system automatically skips checking it" - ) - ) - ValidateNoAnimation: BasicValidateModel = SettingsField( - default_factory=BasicValidateModel, - title="Validate No Animation" - ) - ValidateLoadedPlugin: ValidateLoadedPluginModel = SettingsField( - default_factory=ValidateLoadedPluginModel, - title="Validate Loaded Plugin" - ) - ValidateMeshHasUVs: BasicValidateModel = SettingsField( - default_factory=BasicValidateModel, - title="Validate Mesh Has UVs" - ) - ValidateModelName: ValidateModelNameModel = SettingsField( - default_factory=ValidateModelNameModel, - title="Validate Model Name" - ) - ValidateRenderPasses: BasicValidateModel = SettingsField( - default_factory=BasicValidateModel, - title="Validate Render Passes" - ) - ExtractModelObj: BasicValidateModel = SettingsField( - default_factory=BasicValidateModel, - title="Extract OBJ", - section="Extractors" - ) - ExtractModelFbx: BasicValidateModel = SettingsField( - default_factory=BasicValidateModel, - title="Extract FBX" - ) - ExtractModelUSD: BasicValidateModel = SettingsField( - default_factory=BasicValidateModel, - title="Extract Geometry (USD)" - ) - ExtractModel: BasicValidateModel = SettingsField( - default_factory=BasicValidateModel, - title="Extract Geometry (Alembic)" - ) - ExtractMaxSceneRaw: BasicValidateModel = SettingsField( - default_factory=BasicValidateModel, - title="Extract Max Scene (Raw)" - ) - - -DEFAULT_PUBLISH_SETTINGS = { - "ValidateInstanceInContext": { - "enabled": True, - "optional": True, - "active": True - }, - "ValidateFrameRange": { - "enabled": True, - "optional": True, - "active": True - }, - "ValidateAttributes": { - "enabled": False, - "attributes": "{}" - }, - "ValidateCameraAttributes": { - "enabled": True, - "optional": True, - "active": False, - "fov": 45.0, - "nearrange": 0.0, - "farrange": 1000.0, - "nearclip": 1.0, - "farclip": 1000.0 - }, - "ValidateModelName": { - "enabled": True, - "optional": True, - "active": False, - "regex": "(.*)_(?P.*)_(GEO)" - }, - "ValidateLoadedPlugin": { - "enabled": False, - "optional": True, - "family_plugins_mapping": [] - }, - "ValidateMeshHasUVs": { - "enabled": True, - "optional": True, - "active": False - }, - "ValidateNoAnimation": { - "enabled": True, - "optional": True, - "active": False, - }, - "ValidateRenderPasses": { - "enabled": True, - "optional": False, - "active": True - }, - "ExtractModelObj": { - "enabled": True, - "optional": True, - "active": False - }, - "ExtractModelFbx": { - "enabled": True, - "optional": True, - "active": False - }, - "ExtractModelUSD": { - "enabled": True, - "optional": True, - "active": False - }, - "ExtractModel": { - "enabled": True, - "optional": True, - "active": True - }, - "ExtractMaxSceneRaw": { - "enabled": True, - "optional": True, - "active": True - } -} diff --git a/server_addon/max/server/settings/render_settings.py b/server_addon/max/server/settings/render_settings.py deleted file mode 100644 index 19d36dd0f8..0000000000 --- a/server_addon/max/server/settings/render_settings.py +++ /dev/null @@ -1,47 +0,0 @@ -from ayon_server.settings import BaseSettingsModel, SettingsField - - -def aov_separators_enum(): - return [ - {"value": "dash", "label": "- (dash)"}, - {"value": "underscore", "label": "_ (underscore)"}, - {"value": "dot", "label": ". (dot)"} - ] - - -def image_format_enum(): - """Return enumerator for image output formats.""" - return [ - {"label": "bmp", "value": "bmp"}, - {"label": "exr", "value": "exr"}, - {"label": "tif", "value": "tif"}, - {"label": "tiff", "value": "tiff"}, - {"label": "jpg", "value": "jpg"}, - {"label": "png", "value": "png"}, - {"label": "tga", "value": "tga"}, - {"label": "dds", "value": "dds"} - ] - - -class RenderSettingsModel(BaseSettingsModel): - default_render_image_folder: str = SettingsField( - title="Default render image folder" - ) - aov_separator: str = SettingsField( - "underscore", - title="AOV Separator character", - enum_resolver=aov_separators_enum - ) - image_format: str = SettingsField( - enum_resolver=image_format_enum, - title="Output Image Format" - ) - multipass: bool = SettingsField(title="multipass") - - -DEFAULT_RENDER_SETTINGS = { - "default_render_image_folder": "renders/3dsmax", - "aov_separator": "underscore", - "image_format": "exr", - "multipass": True -}