Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support to export texture sets as single output per texture map #25

Open
wants to merge 16 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@ def create(self, product_name, instance_data, pre_create_data):
"exportPadding",
"exportDilationDistance",
"useCustomExportPreset",
"exportChannel"
"exportChannel",
"exportTextureSets",
"flattenTextureSets"
]:
if key in pre_create_data:
creator_attributes[key] = pre_create_data[key]
Expand Down Expand Up @@ -152,6 +154,11 @@ def get_instance_attr_defs(self):
label="Review",
tooltip="Mark as reviewable",
default=True),
BoolDef("flattenTextureSets",
label="Flatten Texture Sets As One Texture Output",
tooltip="Export multiple texture set(s) "
"as one Texture Output",
default=False),
EnumDef("exportTextureSets",
items=export_texture_set_enum,
multiselection=True,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,22 @@ def create_image_instance(self, instance, template, outputs,

context = instance.context
first_filepath = outputs[0]["filepath"]
is_single_output = instance.data["creator_attributes"].get(
"flattenTextureSets", False)
fnames = [os.path.basename(output["filepath"]) for output in outputs]
ext = os.path.splitext(first_filepath)[1]
assert ext.lstrip("."), f"No extension: {ext}"
if is_single_output:
# Function to remove textureSet from filepath
def remove_texture_set_token(filepath, texture_set):
return filepath.replace(texture_set, "")

fnames = [
remove_texture_set_token(
output["output"], output["textureSet"]
)
for output in outputs
]

always_include_texture_set_name = False # todo: make this configurable
all_texture_sets = substance_painter.textureset.all_texture_sets()
Expand All @@ -76,12 +89,13 @@ def create_image_instance(self, instance, template, outputs,
# Define the suffix we want to give this particular texture
# set and set up a remapped product naming for it.
suffix = ""
if always_include_texture_set_name or len(all_texture_sets) > 1:
# More than one texture set, include texture set name
suffix += f".{texture_set_name}"
if texture_set.is_layered_material() and stack_name:
# More than one stack, include stack name
suffix += f".{stack_name}"
if not is_single_output:
if always_include_texture_set_name or len(all_texture_sets) > 1:
# More than one texture set, include texture set name
suffix += f".{texture_set_name}"
if texture_set.is_layered_material() and stack_name:
# More than one stack, include stack name
suffix += f".{stack_name}"

# Always include the map identifier
map_identifier = strip_template(template)
Expand Down Expand Up @@ -146,6 +160,10 @@ def create_image_instance(self, instance, template, outputs,
image_instance.data["families"] = [product_type, "textures"]
if instance.data["creator_attributes"].get("review"):
image_instance.data["families"].append("review")
if is_single_output:
image_instance.data["image_outputs"] = [
os.path.basename(output["filepath"]) for output in outputs
]

image_instance.data["representations"] = [representation]

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import clique
import os

from ayon_core.pipeline import publish
from ayon_core.lib import (
get_oiio_tool_args,
run_subprocess,
)


def get_texture_outputs(staging_dir, image_outputs, has_udim=False):
"""Getting the expected texture output(s) with/without udim sequence
before merging them with oiio tools.

Args:
staging_dir (str): staging dir
image_outputs (list): source image outputs
has_udim (bool, optional): Is with UDIM. Defaults to False.

Returns:
list: Texture outputs which are used for merging.
"""
if has_udim:
collections, remainder = clique.assemble(image_outputs, minimum_items=1)
return [
os.path.join(
staging_dir,
collection.format(pattern="{head}{padding}{tail}")
)
for collection in collections
]
else:
return [
os.path.join(staging_dir, output) for output in image_outputs
]


def convert_texture_maps_as_single_output(staging_dir, source_image_outputs,
dest_image_outputs, has_udim=False,
log=None):
oiio_tool_args = get_oiio_tool_args("oiiotool")

source_maps = get_texture_outputs(
staging_dir, source_image_outputs, has_udim=has_udim)
dest_map = next(get_texture_outputs(
staging_dir, dest_image_outputs, has_udim=has_udim
), None)

log.info(f"{source_maps} composited as {dest_map}")
oiio_cmd = oiio_tool_args + source_maps + [
"--paste:mergeroi=1",
"+0+0",
"-o",
dest_map
]

env = os.environ.copy()

try:
run_subprocess(oiio_cmd, env=env)
except Exception as exc:
raise RuntimeError("Flattening texture stack to single output image failed") from exc


class ExtractTexturesAsSingleOutput(publish.Extractor):
"""Extract Texture As Single Output

Combine the multliple texture sets into one single texture output.

"""

label = "Extract Texture Sets as Single Texture Output"
hosts = ["substancepainter"]
families = ["image"]
settings_category = "substancepainter"

# Run directly after textures export
order = publish.Extractor.order - 0.099

def process(self, instance):
if not instance.data.get("creator_attributes", {}).get(
"flattenTextureSets", False):
self.log.debug(
"Skipping to export texture sets as single texture output.."
)
return

representations: "list[dict]" = instance.data["representations"]
repre = representations[0]

staging_dir = instance.data["stagingDir"]
source_image_outputs = instance.data["image_outputs"]
has_udim = False
dest_image_outputs = []
dest_files = repre["files"]
is_sequence = isinstance(dest_files, (list, tuple))
if not is_sequence:
dest_image_outputs = [dest_image_outputs]
else:
dest_image_outputs = dest_files
if "udim" in repre:
has_udim = True

convert_texture_maps_as_single_output(
staging_dir, source_image_outputs,
dest_image_outputs, has_udim=has_udim,
log=self.log
)