Add-on: Max texture preference; ship.glb exports larger material images scaled
_export_glb points each Image Texture node of the exported objects' materials whose image is longer than the Max texture preference (default 2048) at a scaled copy (longest side at the cap, aspect kept) and restores the originals and removes the copies in its finally block, so the .blend's images are never modified. smoke_package.py reads the GLB's PNG headers: a 4096x1024 map exports at 2048x512 and at 512x128 under a 512 cap, a 256x256 map exports as it is, the .blend images keep their size and no copy is left in bpy.data.images. Builds: yes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
4f9ada5a6f
commit
5545c850a2
2 changed files with 126 additions and 3 deletions
|
|
@ -612,8 +612,14 @@ class AETHERIA_AP_preferences(bpy.types.AddonPreferences):
|
|||
description="The folder whose GameData holds Aetheria.cc and Mods (the install folder); its ModTools holds "
|
||||
"AetherDb. Empty: the nearest folder above the bound .cc whose GameData holds Aetheria.cc")
|
||||
|
||||
max_texture: bpy.props.IntProperty(
|
||||
name="Max texture", default=2048, min=64, soft_max=8192,
|
||||
description="The longest side, in pixels, a material image keeps in ship.glb; larger images are exported "
|
||||
"scaled to it and the .blend's own images are left as they are")
|
||||
|
||||
def draw(self, context):
|
||||
self.layout.prop(self, "game_folder")
|
||||
self.layout.prop(self, "max_texture")
|
||||
|
||||
|
||||
GAME_FOLDER_REFUSAL = ("Set the add-on's Game folder preference to the folder whose GameData holds Aetheria.cc "
|
||||
|
|
@ -684,6 +690,55 @@ def _anchors(collection):
|
|||
return rows
|
||||
|
||||
|
||||
DEFAULT_MAX_TEXTURE = 2048
|
||||
|
||||
|
||||
def _max_texture(context):
|
||||
addon = context.preferences.addons.get(__package__)
|
||||
return addon.preferences.max_texture if addon and addon.preferences else DEFAULT_MAX_TEXTURE
|
||||
|
||||
|
||||
def _image_nodes(tree, seen=None):
|
||||
"""Every Image Texture node of a node tree, node groups included."""
|
||||
seen = set() if seen is None else seen
|
||||
if tree is None or tree.name_full in seen:
|
||||
return
|
||||
seen.add(tree.name_full)
|
||||
for node in tree.nodes:
|
||||
if node.type == "TEX_IMAGE" and node.image is not None:
|
||||
yield node
|
||||
elif node.type == "GROUP":
|
||||
yield from _image_nodes(node.node_tree, seen)
|
||||
|
||||
|
||||
def _swap_in_scaled_images(objects, limit, swaps):
|
||||
"""Points each Image Texture node of the objects' materials that holds an image longer than limit at a scaled copy,
|
||||
and appends each (node, original, copy) to swaps for _restore_images, so a failure part way still restores. The
|
||||
originals are never modified."""
|
||||
copies = {}
|
||||
for obj in objects:
|
||||
for slot in obj.material_slots:
|
||||
for node in _image_nodes(slot.material.node_tree if slot.material else None):
|
||||
original = node.image
|
||||
longest = max(original.size)
|
||||
if longest <= limit:
|
||||
continue
|
||||
if original not in copies:
|
||||
copy = original.copy()
|
||||
copies[original] = copy
|
||||
copy.scale(max(1, round(original.size[0] * limit / longest)),
|
||||
max(1, round(original.size[1] * limit / longest)))
|
||||
node.image = copies[original]
|
||||
swaps.append((node, original, copies[original]))
|
||||
|
||||
|
||||
def _restore_images(swaps):
|
||||
for node, original, _ in swaps:
|
||||
node.image = original
|
||||
for copy in {id(copy): copy for _, _, copy in swaps}.values():
|
||||
bpy.data.images.remove(copy)
|
||||
|
||||
|
||||
def _export_glb(context, collection, filepath):
|
||||
"""Exports the collection's objects with custom properties as node extras: Generated's anchors are exported; Grease
|
||||
Pencil, Source and the Grid are not."""
|
||||
|
|
@ -694,14 +749,17 @@ def _export_glb(context, collection, filepath):
|
|||
previous_layer = view_layer.active_layer_collection
|
||||
previous_selection = [obj for obj in view_layer.objects if obj.select_get()]
|
||||
previous_active = view_layer.objects.active
|
||||
swaps = []
|
||||
try:
|
||||
view_layer.active_layer_collection = layer
|
||||
for obj in previous_selection:
|
||||
obj.select_set(False)
|
||||
derived = _derived_names(collection)
|
||||
for obj in collection.all_objects:
|
||||
if obj.type != "GREASEPENCIL" and obj.name not in derived and obj.name in view_layer.objects:
|
||||
obj.select_set(True)
|
||||
exported = [obj for obj in collection.all_objects
|
||||
if obj.type != "GREASEPENCIL" and obj.name not in derived and obj.name in view_layer.objects]
|
||||
for obj in exported:
|
||||
obj.select_set(True)
|
||||
_swap_in_scaled_images(exported, _max_texture(context), swaps)
|
||||
bpy.ops.export_scene.gltf(
|
||||
filepath=filepath, export_format="GLB", use_active_collection=True, use_selection=True,
|
||||
export_extras=True, export_yup=True, export_apply=True)
|
||||
|
|
@ -709,6 +767,7 @@ def _export_glb(context, collection, filepath):
|
|||
traceback.print_exc()
|
||||
raise RuntimeError("The GLB export failed; its message is in the system console") from None
|
||||
finally:
|
||||
_restore_images(swaps)
|
||||
for obj in view_layer.objects:
|
||||
obj.select_set(obj in previous_selection)
|
||||
view_layer.objects.active = previous_active
|
||||
|
|
|
|||
|
|
@ -22,7 +22,9 @@ the .blend is saved there before the final bind, so the bind crosses drives and
|
|||
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import traceback
|
||||
|
|
@ -61,6 +63,58 @@ def tagged(collection, name, data, role=None, anchor_id=None, location=(0, 0, 0)
|
|||
return obj
|
||||
|
||||
|
||||
def textured(obj, name, width, height):
|
||||
"""Gives the object a material whose base colour is a generated width x height image; returns the image."""
|
||||
image = bpy.data.images.new(name, width, height)
|
||||
image.pixels[0] = 0.5 # a dirty generated image is what the exporter encodes
|
||||
obj.data.uv_layers.new(name="UVMap")
|
||||
material = bpy.data.materials.new(name)
|
||||
material.use_nodes = True
|
||||
tree = material.node_tree
|
||||
texture = tree.nodes.new("ShaderNodeTexImage")
|
||||
texture.image = image
|
||||
tree.links.new(texture.outputs["Color"], tree.nodes["Principled BSDF"].inputs["Base Color"])
|
||||
obj.data.materials.append(material)
|
||||
return image
|
||||
|
||||
|
||||
def glb_image_sizes(glb):
|
||||
"""The (width, height) of each PNG the GLB embeds, read from the PNG headers in its binary chunk."""
|
||||
data = Path(glb).read_bytes()
|
||||
json_length, _ = struct.unpack_from("<II", data, 12)
|
||||
document = json.loads(data[20:20 + json_length])
|
||||
bin_start = 20 + json_length + 8
|
||||
sizes = []
|
||||
for image in document.get("images", []):
|
||||
view = document["bufferViews"][image["bufferView"]]
|
||||
start = bin_start + view.get("byteOffset", 0)
|
||||
png = data[start:start + view["byteLength"]]
|
||||
if image.get("mimeType") != "image/png" or png[:8] != b"\x89PNG\r\n\x1a\n":
|
||||
raise SystemExit("A GLB image is not a PNG")
|
||||
sizes.append(struct.unpack_from(">II", png, 16))
|
||||
return sorted(sizes)
|
||||
|
||||
|
||||
def texture_cap_pass(addon, hull_object, albedo, detail, limit, expected, glb):
|
||||
"""Package at the Max texture preference limit; the GLB holds exactly the expected image sizes, and the .blend's own
|
||||
images are untouched and no scaled copy is left in bpy.data.images."""
|
||||
bpy.context.preferences.addons["aetheria_ships"].preferences.max_texture = limit
|
||||
names = sorted(image.name for image in bpy.data.images)
|
||||
result, report = package(addon)
|
||||
if result != {"FINISHED"}:
|
||||
raise SystemExit(f"Texture cap {limit}: Package was refused")
|
||||
if glb_image_sizes(glb) != sorted(expected):
|
||||
raise SystemExit(f"Texture cap {limit}: the GLB images are {glb_image_sizes(glb)}, not {sorted(expected)}")
|
||||
if tuple(albedo.size) != (4096, 1024) or tuple(detail.size) != (256, 256):
|
||||
raise SystemExit(f"Texture cap {limit}: Package changed a .blend image to {tuple(albedo.size)}, {tuple(detail.size)}")
|
||||
nodes = [node.image for slot in hull_object.material_slots for node in slot.material.node_tree.nodes
|
||||
if node.type == "TEX_IMAGE"]
|
||||
if nodes != [albedo, detail]:
|
||||
raise SystemExit(f"Texture cap {limit}: a material node does not hold its original image")
|
||||
if sorted(image.name for image in bpy.data.images) != names:
|
||||
raise SystemExit(f"Texture cap {limit}: a scaled copy is left in bpy.data.images")
|
||||
|
||||
|
||||
BIND_KEYS = ("aetheria.asset_kind", "aetheria.id", "aetheria.ship_cc")
|
||||
|
||||
|
||||
|
|
@ -196,6 +250,9 @@ def main():
|
|||
ship = bpy.data.collections.new("Smoke Gale")
|
||||
scene.collection.children.link(ship)
|
||||
hull = tagged(ship, "Hull", tetrahedron("Hull"))
|
||||
albedo = textured(hull, "Hull Albedo", 4096, 1024)
|
||||
detail = textured(hull, "Hull Detail", 256, 256)
|
||||
hull.data.polygons[0].material_index = 1 # the exporter writes only materials some face uses
|
||||
tagged(ship, "Map Icon", quad("Map Icon"), "map-icon", "map", (0, 0, -1))
|
||||
tagged(ship, "Hull Collider", tetrahedron("Hull Collider"), "hull-collider", "collider")
|
||||
tagged(ship, "Shield", None, "shield", "shield")
|
||||
|
|
@ -224,6 +281,13 @@ def main():
|
|||
result, report = package(aetheria_ships)
|
||||
if result != {"FINISHED"}:
|
||||
raise SystemExit("Pass 1: the validator refused the primitive ship")
|
||||
# The texture cap: the 4096 x 1024 map exports at 2048 x 512 (the longest side at the cap, the aspect kept), the
|
||||
# 256 x 256 one is under the cap and exports as it is, and the preference decides the cap.
|
||||
glb = Path(path).with_name("ship.glb")
|
||||
texture_cap_pass(aetheria_ships, hull, albedo, detail, 2048, [(2048, 512), (256, 256)], glb)
|
||||
texture_cap_pass(aetheria_ships, hull, albedo, detail, 512, [(512, 128), (256, 256)], glb)
|
||||
bpy.context.preferences.addons["aetheria_ships"].preferences.max_texture = 2048
|
||||
print("TEXTURE_CAP_OK")
|
||||
# A collection with no Ship Root is packaged exactly as before: the frame step makes and moves nothing.
|
||||
if sorted(obj.name for obj in bpy.data.objects) != objects_before or any(
|
||||
child.get("aetheria.frame") for child in ship.children):
|
||||
|
|
|
|||
Loading…
Reference in a new issue