From 4cea604b85e084248d1af8842b76c1e3c85ace55 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 13 Oct 2026 01:10:34 +0200 Subject: [PATCH] Bake From Source: the bake never rewrites what Source owns, bakes onto UV0, keeps one pair under its own names, reports Blender errors as fixed text Shared material (shared-material-source-rewritten): a target slot holding a material a Source mesh uses is given a copy before the bake; a replaced image is removed only when unused. UV0 (bake-follows-active-uv-not-uv0): every target's active UV layer is held at 0 for the bake and put back. Relief (normal-tolerance-accepts-near-flat): smoke_bake bounds the normal's median tilt at 3 degrees (copy of Source 0.32, hull 16.59). Pair names (pair-names-suffixed): a name held by an image the bake would not free refuses with fixed text. Fixed text (refusal-passes-plain-runtimeerror-text): any foreign exception inside the bake becomes BakeFailed with the console pointer. All builds; smoke_bake.py passes on Blender 5.2.2. Co-Authored-By: Claude Opus 5.5 --- tools/blender/aetheria_ships/__init__.py | 57 ++++++- tools/blender/tests/smoke_bake.py | 184 ++++++++++++++++++++++- 2 files changed, 232 insertions(+), 9 deletions(-) diff --git a/tools/blender/aetheria_ships/__init__.py b/tools/blender/aetheria_ships/__init__.py index 52c1681eb..086463cd7 100644 --- a/tools/blender/aetheria_ships/__init__.py +++ b/tools/blender/aetheria_ships/__init__.py @@ -126,10 +126,14 @@ def _load_layout(context, collection, path): _EXPECTED = (OSError, ValueError, RuntimeError, ImportError, KeyError) +class BakeFailed(RuntimeError): + """The one error a bake raises past its rollback. Its message is fixed text; whatever Blender raised is on the console.""" + + def _failure_text(exc): """What an operator reports for exc. This module's own ValueError and RuntimeError messages are fixed text that names no input; any other error is reported by its type, and its text goes to the system console.""" - if type(exc) in (ValueError, RuntimeError): + if type(exc) in (ValueError, RuntimeError, BakeFailed): return str(exc) traceback.print_exception(exc) return f"Stopped by {type(exc).__name__}; see the system console" @@ -1159,6 +1163,28 @@ def _target_materials(targets): return list({slot.material.name: slot.material for obj in targets for slot in obj.material_slots}.values()) +def _give_own_materials(sources, targets, undo): + """Gives each target slot that holds a material a Source mesh also uses a copy of its own, so the bake rewires nothing + Source owns; returns how many materials were copied. undo gets the steps that put the slots back.""" + owned = {slot.material.name for obj in sources for slot in obj.material_slots if slot.material} + copies = {} + for obj in targets: + for index, slot in enumerate(obj.material_slots): + original = slot.material + if original is None or original.name not in owned: + continue + if original.name not in copies: + copies[original.name] = original.copy() + undo.append(partial(_remove_material, copies[original.name].name)) + undo.append(partial(_set_slot_material, obj.name, index, original.name)) + slot.material = copies[original.name] + return len(copies) + + +def _set_slot_material(object_name, index, material_name): + bpy.data.objects[object_name].material_slots[index].material = bpy.data.materials[material_name] + + def _hold(owner, name, value, restore): """Sets owner.name to value for the bake; restore gets the step that puts the old value back.""" restore.append(partial(setattr, owner, name, getattr(owner, name))) @@ -1224,6 +1250,18 @@ def _link_into(material, node, input_name, source, undo): undo.append(partial(_restore_link, material.name, node.name, input_name, previous)) +def _refuse_taken_names(ship_id, targets): + """The ship's pair is {ship_id}.albedo and {ship_id}.normal and there is one pair: an image already holding a name must + be one this bake replaces and frees, or the new image would take a numbered name beside it.""" + materials = _target_materials(targets) + for kind, _, _ in BAKE_MAPS: + image = bpy.data.images.get(f"{ship_id}.{kind}") + wired = [node for node in (_wired_image(material, kind) for material in materials) if node is not None and node.image == image] + if image is not None and (image.use_fake_user or image.users != len(wired)): + raise ValueError("The ship's baked image names are held by images this bake does not replace; select every " + "mesh that uses them, or rename the other images") + + def _bake_map(context, sources, targets, settings, extrusion, max_distance, nodes): """Bakes one map from the Source meshes onto every target, the first target clearing the image and the later ones adding to it. nodes maps a material's name to the Image Texture node that holds this map's image. This is the add-on's @@ -1240,7 +1278,7 @@ def _bake_map(context, sources, targets, settings, extrusion, max_distance, node **settings) except RuntimeError: # Blender's text names objects and images traceback.print_exc() - raise RuntimeError("The bake failed; its message is in the system console") from None + raise BakeFailed("The bake failed; its message is in the system console") from None def _bake_from_source(context, collection, replace): @@ -1251,6 +1289,7 @@ def _bake_from_source(context, collection, replace): ship_id, sources, targets = _bake_inputs(context, collection) if not replace and any(_wired_image(material, kind) for material in _target_materials(targets) for kind, _, _ in BAKE_MAPS): raise ValueError("Selected meshes already have baked images; confirm the replace") + _refuse_taken_names(ship_id, targets) addon = context.preferences.addons[__package__].preferences scene, layer = context.scene, context.view_layer previous_selection = [obj for obj in layer.objects if obj.select_get()] @@ -1262,6 +1301,9 @@ def _bake_from_source(context, collection, replace): _hold(scene.render, "engine", "CYCLES", restore) _hold(scene.cycles, "samples", BAKE_SAMPLES, restore) _hold(scene.cycles, "device", "CPU", restore) + copied = _give_own_materials(sources, targets, undo) + for obj in targets: # her unwrap is UV0, whichever layer is active + _hold(obj.data.uv_layers, "active_index", 0, restore) _isolate_sources(sources, restore) images = {} for kind, space, _ in BAKE_MAPS: @@ -1308,9 +1350,12 @@ def _bake_from_source(context, collection, replace): undo.append(partial(_remove_node, material.name, normal.name)) material.node_tree.links.new(node.outputs["Color"], normal.inputs["Color"]) _link_into(material, bsdf, "Normal", normal.outputs["Normal"], undo) - except BaseException: + except BaseException as exc: for step in reversed(undo): step() + if isinstance(exc, Exception) and not isinstance(exc, BakeFailed): # Blender's text names objects and images + traceback.print_exception(exc) + raise BakeFailed("The bake failed; its message is in the system console") from None raise finally: for step in reversed(restore): @@ -1320,6 +1365,7 @@ def _bake_from_source(context, collection, replace): bpy.data.images.remove(image) for kind, image in images.items(): image.name = f"{ship_id}.{kind}" + return copied class AETHERIA_OT_bake_from_source(bpy.types.Operator): @@ -1346,8 +1392,9 @@ class AETHERIA_OT_bake_from_source(bpy.types.Operator): def execute(self, context): try: - _bake_from_source(context, _ship_collection(context), self.replace) - self.report({"INFO"}, "Baked the albedo and normal maps from Source") + copied = _bake_from_source(context, _ship_collection(context), self.replace) + self.report({"INFO"}, "Baked the albedo and normal maps from Source" + ( + f"; {copied} materials shared with Source were copied for the render meshes" if copied else "")) return {"FINISHED"} except _EXPECTED as exc: return _refuse(self, exc) diff --git a/tools/blender/tests/smoke_bake.py b/tools/blender/tests/smoke_bake.py index 98a9113ad..0386211fd 100644 --- a/tools/blender/tests/smoke_bake.py +++ b/tools/blender/tests/smoke_bake.py @@ -16,7 +16,10 @@ settings and selection as they were; a bake that fails on its second call leaves render mesh under a Bevel and Weighted Normal stack, then three render meshes that share one atlas, two without a material. Pass 3 requires every refusal to name no input, change nothing and select the offenders, and a bake over wired images to need replace. Pass 4 requires the images to survive Save As and reopen and ride Package into ship.glb at the Max texture -cap. +cap. Pass 5 runs on the reopened file from a clean set of render meshes: a mesh sharing Source's material bakes on a copy and leaves +Source's material and Tripo image as they were, a replaced image another material uses survives, the bake lands on UV0 whichever +layer is active, the ship keeps one pair under its own names or the bake is refused, and the normal's relief bound rejects a copy +of Source as the target. """ import hashlib @@ -42,6 +45,7 @@ SHIP_ID = "smoke.bake" COLLECTION = "Smoke Bake" SIZE = [256] # the bake size the images are expected at TEXTURE_MEAN = (0.0754, 0.0692, 0.0746) # the fixture's base colour texture, linear, measured in Blender 5.2.2 +RELIEF_MIN = 3.0 # degrees of median tilt: the 10% hull measures 16.6, a 50% hull 5.2, a copy of Source as the target 0.3 NAMES_NOT_ECHOED = [SHIP_ID, COLLECTION, "Hull", "Wing", "Fin", "Tripo Source", str(GAME), GAME.name] @@ -78,9 +82,20 @@ def bake_images(): return bpy.data.images.get(f"{SHIP_ID}.albedo"), bpy.data.images.get(f"{SHIP_ID}.normal") +def relief(albedo, normal): + """The median angle, in degrees, between the normal map's vector and the surface normal over the texels the albedo bake + wrote: a flat or near-flat bake sits near 0 whatever its mean z is.""" + vectors = pixels(normal)[written(albedo)][:, :3] * 2 - 1 + vectors /= numpy.maximum(numpy.linalg.norm(vectors, axis=1, keepdims=True), 1e-6) + return float(numpy.median(numpy.degrees(numpy.arccos(numpy.clip(vectors[:, 2], -1, 1))))) + + def check_maps(label, albedo, normal): """The tolerances measured on Blender 5.2.2: the albedo is the texture's linear mean (Image.pixels is linear) to 0.015 on at least 80% of the - texels, the tangent normal has x and y at 0.5 to 0.02 and z in [0.75, 0.95].""" + texels, the tangent normal has x and y at 0.5 to 0.02, z in [0.75, 0.95] and a median tilt of at least RELIEF_MIN degrees.""" + tilt = relief(albedo, normal) + print(f"{label} normal median tilt {tilt:.2f} degrees") + require(tilt >= RELIEF_MIN, f"{label}: the normal map has no relief (median tilt {tilt:.2f} degrees)") mean = pixels(albedo)[:, :3].mean(axis=0) covered = written(albedo).mean() print(f"{label} albedo mean {tuple(round(float(v), 4) for v in mean)} written {covered:.3f}") @@ -264,8 +279,7 @@ def failing_pass(aetheria_ships, label, targets, materials, sources, replace, si setattr(aetheria_ships, site, real_site) require(patched.calls >= fail_on, f"{label}: the forced failure never landed ({patched.calls} calls)") require(result == {"CANCELLED"}, f"{label}: a failing run was not refused") - if site == "bake": - require("The bake failed" in message and "probe" not in message, f"{label}: Blender's own text reached the report ({message!r})") + require("The bake failed" in message and "probe" not in message, f"{label}: Blender's own text reached the report ({message!r})") after = state() for part, name in enumerate(("wiring", "Source materials", "scene settings and selection", "images", "material slots", "materials")): require(before[part] == after[part], f"{label}: a failed run left the {name} changed") @@ -302,6 +316,7 @@ def main(): try: passes_one_to_three(aetheria_ships, bpy.context.scene) pass_four(aetheria_ships) + pass_five(aetheria_ships) finally: shutil.rmtree(ship_folder, ignore_errors=True) @@ -507,6 +522,167 @@ def pass_four(aetheria_ships): print("PASS 4 save, reopen and package ok") +def pass_five(aetheria_ships): + """On the reopened file, from a clean set of render meshes: a render mesh sharing Source's material is baked on a copy + and Source keeps its material, wiring and Tripo image; a replaced image another material uses survives; the bake lands + on UV0 whichever layer is active; one pair per ship holds under its own names or the bake is refused; the relief bound + rejects a copy of Source as the target.""" + preferences = bpy.context.preferences.addons["aetheria_ships"].preferences + SIZE[0] = preferences.bake_size = 256 + collection, root, source = bpy.data.collections[COLLECTION], bpy.data.objects["Ship Root"], bpy.data.objects["Tripo Source"] + sources = [source] + source_material = source.material_slots[0].material + tripo = next(n for n in source_material.node_tree.nodes if n.type == "BSDF_PRINCIPLED").inputs["Base Color"].links[0].from_node.image + + def owned(): + return (wiring([source_material]), digest(tripo), tripo.name, source_state(sources), source_material.name) + + kept = owned() + + def source_kept(label): + require(bpy.data.materials.get(kept[4]) == source_material and bpy.data.images.get(kept[2]) == tripo, + f"{label}: Source's material or Tripo image is gone") + require(owned() == kept, f"{label}: a bake changed what Source owns") + + def purge(): + for obj in [o for o in bpy.data.objects if o.type == "MESH" and o not in sources and o.name != "Hull Collider"]: + bpy.data.objects.remove(obj, do_unlink=True) + for material in [m for m in bpy.data.materials if m != source_material]: + bpy.data.materials.remove(material) + for image in [i for i in bpy.data.images if i.name.startswith(SHIP_ID) or i.name in ("InUse", "Free")]: + image.use_fake_user = False + bpy.data.images.remove(image) + + def new_render(name, ratio=0.1): + obj = make_render(collection, root, source, name) + if ratio < 1: + obj.modifiers.new("Decimate", "DECIMATE").ratio = ratio + select([obj]) + bpy.ops.object.modifier_apply(modifier="Decimate") + select([obj]) + bpy.ops.object.mode_set(mode="EDIT") + bpy.ops.mesh.select_all(action="SELECT") + bpy.ops.uv.smart_project() + bpy.ops.object.mode_set(mode="OBJECT") + return obj + + def uv_hashes(obj): + rows = [] + for layer in obj.data.uv_layers: + uv = numpy.empty(len(layer.data) * 2, dtype=numpy.float32) + layer.data.foreach_get("uv", uv) + rows.append((layer.name, hashlib.sha256(uv.tobytes()).hexdigest())) + return rows + + pair_names = sorted([f"{SHIP_ID}.albedo", f"{SHIP_ID}.normal"]) + + def one_pair(label): + require(sorted(i.name for i in bpy.data.images if i.name.startswith(SHIP_ID)) == pair_names, + f"{label}: the ship does not hold exactly one pair under its own names") + + def image_state(): + return (len(bpy.data.images), sorted(i.name for i in bpy.data.images)) + + # A render mesh that shares Source's material is baked onto a material of its own. + purge() + wing, fin = new_render("Wing"), new_render("Fin") + for obj in (wing, fin): + obj.data.materials.append(source_material) + select([wing, fin]) + result, message = run(bpy.ops.aetheria.bake_from_source) + require(result == {"CANCELLED"} and "confirm the replace" in message, + f"Shared material: a bake over wired images was not refused: {message}") + failing_pass(aetheria_ships, "Shared material failing wiring", [wing, fin], [source_material], sources, True, "_link_into", 1) + require(wing.data.materials[0] == source_material and fin.data.materials[0] == source_material, + "Shared material: a failed run left a copy on the mesh") + source_kept("Shared material, failed run") + result, message = run(bpy.ops.aetheria.bake_from_source, replace=True) + require(result == {"FINISHED"}, f"Shared material: the bake was refused: {message}") + own = wing.data.materials[0] + require(own != source_material and fin.data.materials[0] == own, "Shared material: the meshes did not take one material of their own") + source_kept("Shared material") + check_images("Shared material", [own.name]) + one_pair("Shared material") + print("PASS 5 shared material ok") + + # A replaced image another material still uses survives. + purge() + target = new_render("Wing") + material = with_material(target, "Own") + shared_image = bpy.data.images.new("InUse", 8, 8) + elsewhere = bpy.data.materials.new("Elsewhere") + elsewhere.use_nodes = True + elsewhere.use_fake_user = True + for owner in (material, elsewhere): + node = owner.node_tree.nodes.new("ShaderNodeTexImage") + node.image = shared_image + if owner is material: + owner.node_tree.links.new(node.outputs["Color"], owner.node_tree.nodes["Principled BSDF"].inputs["Base Color"]) + select([target]) + result, message = run(bpy.ops.aetheria.bake_from_source, replace=True) + require(result == {"FINISHED"}, f"Image in use: the bake was refused: {message}") + require(bpy.data.images.get("InUse") == shared_image and any(n.type == "TEX_IMAGE" and n.image == shared_image for n in elsewhere.node_tree.nodes), + "Image in use: Replace removed an image another material uses") + print("PASS 5 image in use ok") + + # The bake lands on UV0 whichever layer is active. + purge() + target = new_render("Wing") + layers = target.data.uv_layers + layers.new(name="Scratch") + squeezed = numpy.empty(len(layers[0].data) * 2, dtype=numpy.float32) + layers[0].data.foreach_get("uv", squeezed) + layers[1].data.foreach_set("uv", (squeezed * 0.5).tolist()) + layers.active_index = 1 + before = uv_hashes(target) + select([target]) + result, message = run(bpy.ops.aetheria.bake_from_source) + require(result == {"FINISHED"}, f"UV0: the bake was refused: {message}") + covered = float(written(bake_images()[0]).mean()) + print(f"PASS 5 UV0 coverage {covered:.3f} with the second layer active") + require(covered >= 0.9, f"UV0: the bake covers {covered:.3f} of UV0's layout") + require(layers.active_index == 1, "UV0: the active layer was not put back") + require(uv_hashes(target) == before, "UV0: a bake changed the UV layers") + + # One pair per ship under its own names: a name held by a free image or by a pair this bake would leave behind refuses. + purge() + first, second = new_render("Wing"), new_render("Fin") + free = bpy.data.images.new(f"{SHIP_ID}.albedo", 4, 4) + free.use_fake_user = True + select([first]) + refusal("Free image holds the name", "held by images this bake does not replace", image_state) + bpy.data.images.remove(free) + result, message = run(bpy.ops.aetheria.bake_from_source) + require(result == {"FINISHED"}, f"Names: the first bake was refused: {message}") + one_pair("Names, first bake") + select([second]) + refusal("Pair still wired elsewhere", "held by images this bake does not replace", image_state) + select([first, second]) + for _ in range(2): + result, message = run(bpy.ops.aetheria.bake_from_source, replace=True) + require(result == {"FINISHED"}, f"Names: the shared bake was refused: {message}") + one_pair("Names, shared bake") + check_images("Names", [first.data.materials[0].name, second.data.materials[0].name]) + print("PASS 5 pair names ok") + + # The relief bound rejects a copy of Source as the target and accepts a real hull. + purge() + flat = new_render("Fin", ratio=1.0) + select([flat]) + result, message = run(bpy.ops.aetheria.bake_from_source) + require(result == {"FINISHED"}, f"Relief: the copy of Source was refused: {message}") + flat_tilt = relief(*bake_images()) + purge() + real = new_render("Wing") + select([real]) + result, message = run(bpy.ops.aetheria.bake_from_source) + require(result == {"FINISHED"}, f"Relief: the hull was refused: {message}") + real_tilt = relief(*bake_images()) + print(f"PASS 5 relief: median tilt {flat_tilt:.2f} degrees for a copy of Source, {real_tilt:.2f} for the hull, bound {RELIEF_MIN}") + require(flat_tilt < RELIEF_MIN <= real_tilt, "Relief: the bound does not separate a copy of Source from a real hull") + check_maps("Relief hull", *bake_images()) + + try: main() except SystemExit as stop: