@threenative/blender-bridge 0.0.0-stage → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -2
- package/dist/bridge.d.ts +111 -0
- package/dist/bridge.js +321 -0
- package/gpl/LICENSE.GPL +117 -0
- package/gpl/convert.py +192 -0
- package/gpl/fixtures/make_world_fixture.py +184 -0
- package/gpl/recipes/_common.py +180 -0
- package/gpl/recipes/bake_ao.py +111 -0
- package/gpl/recipes/decimate.py +70 -0
- package/gpl/recipes/export_world.py +699 -0
- package/gpl/recipes/retarget.py +131 -0
- package/gpl/recipes/unwrap.py +71 -0
- package/package.json +54 -3
package/gpl/convert.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
# SPDX-License-Identifier: GPL-2.0-or-later
|
|
2
|
+
#
|
|
3
|
+
# Copyright (C) 2026 ThreeNative contributors
|
|
4
|
+
#
|
|
5
|
+
# This program is free software; you can redistribute it and/or modify it under the terms of the
|
|
6
|
+
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
|
|
7
|
+
# License, or (at your option) any later version. See LICENSE.GPL beside this file.
|
|
8
|
+
#
|
|
9
|
+
# This file runs inside Blender against `bpy` and is therefore GPL-covered. The Node code that
|
|
10
|
+
# spawns Blender is MIT and never imports it; the boundary is a process, not a link.
|
|
11
|
+
#
|
|
12
|
+
# Usage: blender --background --factory-startup --python convert.py -- '<json>'
|
|
13
|
+
# {"source": "/abs/in.fbx", "out": "/abs/out.glb", "mode": "convert" | "inspect"}
|
|
14
|
+
#
|
|
15
|
+
# The last line of stdout is `TN_BLENDER_RESULT <json>`. Everything else Blender prints is noise the
|
|
16
|
+
# caller keeps for diagnostics. A run that imports nothing exits non-zero: an empty GLB that
|
|
17
|
+
# reported success is the failure this whole path exists to prevent.
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import sys
|
|
22
|
+
|
|
23
|
+
import bpy
|
|
24
|
+
|
|
25
|
+
RESULT_PREFIX = "TN_BLENDER_RESULT "
|
|
26
|
+
|
|
27
|
+
IMPORTERS = {
|
|
28
|
+
".fbx": lambda p: bpy.ops.import_scene.fbx(filepath=p),
|
|
29
|
+
".obj": lambda p: bpy.ops.wm.obj_import(filepath=p),
|
|
30
|
+
".dae": lambda p: bpy.ops.wm.collada_import(filepath=p),
|
|
31
|
+
".gltf": lambda p: bpy.ops.import_scene.gltf(filepath=p),
|
|
32
|
+
".glb": lambda p: bpy.ops.import_scene.gltf(filepath=p),
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def fail(message):
|
|
37
|
+
sys.stderr.write("TN_BLENDER_ERROR: %s\n" % message)
|
|
38
|
+
sys.stderr.flush()
|
|
39
|
+
# `bpy.ops.wm.quit_blender()` would run Blender's own exit path and report 0.
|
|
40
|
+
os._exit(2)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def arguments():
|
|
44
|
+
if "--" not in sys.argv:
|
|
45
|
+
fail("no '--' separator; pass the JSON request after it")
|
|
46
|
+
tail = sys.argv[sys.argv.index("--") + 1 :]
|
|
47
|
+
if len(tail) != 1:
|
|
48
|
+
fail("expected exactly one JSON argument, got %d" % len(tail))
|
|
49
|
+
try:
|
|
50
|
+
return json.loads(tail[0])
|
|
51
|
+
except ValueError as error:
|
|
52
|
+
fail("request is not JSON: %s" % error)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def clear_scene():
|
|
56
|
+
bpy.ops.wm.read_factory_settings(use_empty=True)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def load(source):
|
|
60
|
+
extension = os.path.splitext(source)[1].lower()
|
|
61
|
+
if extension == ".blend":
|
|
62
|
+
# A .blend is opened, not imported: it *is* a Blender file, and importing would nest it.
|
|
63
|
+
bpy.ops.wm.open_mainfile(filepath=source)
|
|
64
|
+
return
|
|
65
|
+
importer = IMPORTERS.get(extension)
|
|
66
|
+
if importer is None:
|
|
67
|
+
fail("unsupported source extension '%s'" % extension)
|
|
68
|
+
clear_scene()
|
|
69
|
+
importer(source)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def triangles_of(mesh_object):
|
|
73
|
+
# Evaluated, so modifiers the artist left on the stack are counted the way the export will
|
|
74
|
+
# write them. A count taken from the un-evaluated mesh disagrees with the GLB by design.
|
|
75
|
+
depsgraph = bpy.context.evaluated_depsgraph_get()
|
|
76
|
+
evaluated = mesh_object.evaluated_get(depsgraph)
|
|
77
|
+
mesh = evaluated.to_mesh()
|
|
78
|
+
try:
|
|
79
|
+
mesh.calc_loop_triangles()
|
|
80
|
+
return len(mesh.loop_triangles)
|
|
81
|
+
finally:
|
|
82
|
+
evaluated.to_mesh_clear()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def summarize():
|
|
86
|
+
meshes = [item for item in bpy.data.objects if item.type == "MESH"]
|
|
87
|
+
armatures = [item for item in bpy.data.objects if item.type == "ARMATURE"]
|
|
88
|
+
bones = sum(len(item.data.bones) for item in armatures)
|
|
89
|
+
materials = sorted(
|
|
90
|
+
{slot.material.name for item in meshes for slot in item.material_slots if slot.material}
|
|
91
|
+
)
|
|
92
|
+
clips = sorted({action.name for action in bpy.data.actions})
|
|
93
|
+
triangles = sum(triangles_of(item) for item in meshes)
|
|
94
|
+
vertices = sum(len(item.data.vertices) for item in meshes)
|
|
95
|
+
images = sorted({image.name for image in bpy.data.images if image.name != "Render Result"})
|
|
96
|
+
return {
|
|
97
|
+
"bones": bones,
|
|
98
|
+
"clips": clips,
|
|
99
|
+
"images": images,
|
|
100
|
+
"materials": materials,
|
|
101
|
+
"meshes": len(meshes),
|
|
102
|
+
"triangles": triangles,
|
|
103
|
+
"vertices": vertices,
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def push_actions_to_nla():
|
|
108
|
+
"""Give every action a strip so the glTF exporter writes it as its own clip.
|
|
109
|
+
|
|
110
|
+
Blender exports the *active* action plus whatever the NLA holds. An .fbx that arrived with four
|
|
111
|
+
takes lands as four actions and one active one, and without this the GLB ships a single clip
|
|
112
|
+
while every count in the summary still says four.
|
|
113
|
+
"""
|
|
114
|
+
for item in bpy.data.objects:
|
|
115
|
+
if item.animation_data is None:
|
|
116
|
+
continue
|
|
117
|
+
action = item.animation_data.action
|
|
118
|
+
if action is None:
|
|
119
|
+
continue
|
|
120
|
+
existing = {
|
|
121
|
+
strip.action.name
|
|
122
|
+
for track in item.animation_data.nla_tracks
|
|
123
|
+
for strip in track.strips
|
|
124
|
+
if strip.action
|
|
125
|
+
}
|
|
126
|
+
if action.name in existing:
|
|
127
|
+
continue
|
|
128
|
+
track = item.animation_data.nla_tracks.new()
|
|
129
|
+
track.name = action.name
|
|
130
|
+
track.strips.new(action.name, int(action.frame_range[0]), action)
|
|
131
|
+
item.animation_data.action = None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def export(out):
|
|
135
|
+
directory = os.path.dirname(out)
|
|
136
|
+
if directory and not os.path.isdir(directory):
|
|
137
|
+
os.makedirs(directory, exist_ok=True)
|
|
138
|
+
push_actions_to_nla()
|
|
139
|
+
# `export_apply` is not the default, and without it a recipe that works through a
|
|
140
|
+
# modifier reports the number it measured and writes the geometry it started with:
|
|
141
|
+
# `decimate` at ratio 0.25 reported trianglesAfter 154 and shipped a 620-triangle GLB,
|
|
142
|
+
# byte-identical to the unmodified export. Blender's glTF exporter excludes armature
|
|
143
|
+
# modifiers from this, so a rig still exports as a rig rather than being baked flat.
|
|
144
|
+
bpy.ops.export_scene.gltf(
|
|
145
|
+
filepath=out,
|
|
146
|
+
export_apply=True,
|
|
147
|
+
export_format="GLB",
|
|
148
|
+
export_animations=True,
|
|
149
|
+
export_nla_strips=True,
|
|
150
|
+
export_skins=True,
|
|
151
|
+
export_yup=True,
|
|
152
|
+
# Textures ride inside the GLB; a game loading one file must not need a sidecar the
|
|
153
|
+
# conversion silently left in a temp directory.
|
|
154
|
+
export_image_format="AUTO",
|
|
155
|
+
use_selection=False,
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def main():
|
|
160
|
+
request = arguments()
|
|
161
|
+
source = request.get("source")
|
|
162
|
+
mode = request.get("mode", "convert")
|
|
163
|
+
if not isinstance(source, str) or not source:
|
|
164
|
+
fail("request has no 'source' path")
|
|
165
|
+
if not os.path.isfile(source):
|
|
166
|
+
fail("source '%s' does not exist" % source)
|
|
167
|
+
if mode not in ("convert", "inspect"):
|
|
168
|
+
fail("unknown mode '%s'" % mode)
|
|
169
|
+
|
|
170
|
+
load(source)
|
|
171
|
+
summary = summarize()
|
|
172
|
+
if summary["meshes"] == 0:
|
|
173
|
+
fail("'%s' produced no meshes; refusing to report success" % source)
|
|
174
|
+
|
|
175
|
+
if mode == "convert":
|
|
176
|
+
out = request.get("out")
|
|
177
|
+
if not isinstance(out, str) or not out:
|
|
178
|
+
fail("convert requires an 'out' path")
|
|
179
|
+
export(out)
|
|
180
|
+
if not os.path.isfile(out):
|
|
181
|
+
fail("export wrote no file at '%s'" % out)
|
|
182
|
+
summary["out"] = out
|
|
183
|
+
summary["outBytes"] = os.path.getsize(out)
|
|
184
|
+
|
|
185
|
+
summary["source"] = source
|
|
186
|
+
summary["mode"] = mode
|
|
187
|
+
summary["blender"] = bpy.app.version_string
|
|
188
|
+
sys.stdout.write("\n" + RESULT_PREFIX + json.dumps(summary, sort_keys=True) + "\n")
|
|
189
|
+
sys.stdout.flush()
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
main()
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
# SPDX-License-Identifier: GPL-2.0-or-later
|
|
2
|
+
#
|
|
3
|
+
# Copyright (C) 2026 ThreeNative contributors
|
|
4
|
+
#
|
|
5
|
+
# This program is free software; you can redistribute it and/or modify it under the terms of the
|
|
6
|
+
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
|
|
7
|
+
# License, or (at your option) any later version. See ../LICENSE.GPL.
|
|
8
|
+
#
|
|
9
|
+
# Build the tiny, deterministic, CC0-primitives-only world that the export_world spec runs. It
|
|
10
|
+
# exercises every convention the recipe understands: a marked terrain, two tn_asset_id scatter
|
|
11
|
+
# sources and a ground-cover asset with tn_max_distance, a render-density scatter switched by an
|
|
12
|
+
# Is Viewport node, and a tn_world_chunk collection straddling a cell boundary.
|
|
13
|
+
#
|
|
14
|
+
# blender -b --factory-startup --python make_world_fixture.py -- --out /tmp/world.blend
|
|
15
|
+
|
|
16
|
+
import math
|
|
17
|
+
import os
|
|
18
|
+
import sys
|
|
19
|
+
|
|
20
|
+
import bpy
|
|
21
|
+
from mathutils import Matrix
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def fail(message):
|
|
25
|
+
sys.stderr.write("TN_BLENDER_ERROR: %s\n" % message)
|
|
26
|
+
sys.stderr.flush()
|
|
27
|
+
os._exit(2)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def parse_args():
|
|
31
|
+
argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else []
|
|
32
|
+
payload = {}
|
|
33
|
+
index = 0
|
|
34
|
+
while index < len(argv):
|
|
35
|
+
token = argv[index]
|
|
36
|
+
if token.startswith("--"):
|
|
37
|
+
key = token[2:]
|
|
38
|
+
if "=" in key:
|
|
39
|
+
key, value = key.split("=", 1)
|
|
40
|
+
else:
|
|
41
|
+
index += 1
|
|
42
|
+
if index >= len(argv):
|
|
43
|
+
fail("'--%s' needs a value" % key)
|
|
44
|
+
value = argv[index]
|
|
45
|
+
payload[key] = value
|
|
46
|
+
index += 1
|
|
47
|
+
return payload
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def displace(terrain):
|
|
51
|
+
for vertex in terrain.data.vertices:
|
|
52
|
+
x, y = vertex.co.x, vertex.co.y
|
|
53
|
+
vertex.co.z = (
|
|
54
|
+
3.0 * math.sin(x * 0.11) * math.cos(y * 0.13)
|
|
55
|
+
+ 1.5 * math.sin(x * 0.031 + y * 0.047)
|
|
56
|
+
+ 0.5 * math.cos((x + y) * 0.21)
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def scatter_group(asset, render_density, viewport_density, seed):
|
|
61
|
+
group = bpy.data.node_groups.new("TNScatter_%s" % asset.name, "GeometryNodeTree")
|
|
62
|
+
group.interface.new_socket(name="Geometry", in_out="INPUT", socket_type="NodeSocketGeometry")
|
|
63
|
+
group.interface.new_socket(name="Geometry", in_out="OUTPUT", socket_type="NodeSocketGeometry")
|
|
64
|
+
source = group.nodes.new("NodeGroupInput")
|
|
65
|
+
output = group.nodes.new("NodeGroupOutput")
|
|
66
|
+
distribute = group.nodes.new("GeometryNodeDistributePointsOnFaces")
|
|
67
|
+
distribute.distribute_method = "RANDOM"
|
|
68
|
+
distribute.inputs["Seed"].default_value = seed
|
|
69
|
+
instance = group.nodes.new("GeometryNodeInstanceOnPoints")
|
|
70
|
+
info = group.nodes.new("GeometryNodeObjectInfo")
|
|
71
|
+
info.inputs["Object"].default_value = asset
|
|
72
|
+
# Object-level instancing: the depsgraph reports the asset object itself for every point, which
|
|
73
|
+
# is what lets the exporter read tn_asset_id off `instance_object`. Realised geometry instances
|
|
74
|
+
# report the emitter instead, and the asset id is lost.
|
|
75
|
+
info.inputs["As Instance"].default_value = True
|
|
76
|
+
is_viewport = group.nodes.new("GeometryNodeIsViewport")
|
|
77
|
+
switch = group.nodes.new("GeometryNodeSwitch")
|
|
78
|
+
switch.input_type = "FLOAT"
|
|
79
|
+
switch.inputs["False"].default_value = render_density
|
|
80
|
+
switch.inputs["True"].default_value = viewport_density
|
|
81
|
+
group.links.new(source.outputs["Geometry"], distribute.inputs["Mesh"])
|
|
82
|
+
group.links.new(is_viewport.outputs["Is Viewport"], switch.inputs["Switch"])
|
|
83
|
+
group.links.new(switch.outputs["Output"], distribute.inputs["Density"])
|
|
84
|
+
group.links.new(distribute.outputs["Points"], instance.inputs["Points"])
|
|
85
|
+
group.links.new(info.outputs["Geometry"], instance.inputs["Instance"])
|
|
86
|
+
group.links.new(instance.outputs["Instances"], output.inputs["Geometry"])
|
|
87
|
+
return group
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def make_emitter(asset, render_density, viewport_density, seed):
|
|
91
|
+
bpy.ops.mesh.primitive_grid_add(x_subdivisions=8, y_subdivisions=8, size=200, location=(0, 0, 0))
|
|
92
|
+
emitter = bpy.context.object
|
|
93
|
+
emitter.name = "scatter_%s" % asset.name
|
|
94
|
+
modifier = emitter.modifiers.new("TNScatter", "NODES")
|
|
95
|
+
modifier.node_group = scatter_group(asset, render_density, viewport_density, seed)
|
|
96
|
+
return emitter
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def move_to_collection(instance, collection):
|
|
100
|
+
for existing in list(instance.users_collection):
|
|
101
|
+
existing.objects.unlink(instance)
|
|
102
|
+
collection.objects.link(instance)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def main():
|
|
106
|
+
payload = parse_args()
|
|
107
|
+
out = payload.get("out")
|
|
108
|
+
if not isinstance(out, str) or not out:
|
|
109
|
+
fail("make_world_fixture requires an '--out' .blend path")
|
|
110
|
+
out = os.path.abspath(out)
|
|
111
|
+
directory = os.path.dirname(out)
|
|
112
|
+
if directory and not os.path.isdir(directory):
|
|
113
|
+
os.makedirs(directory, exist_ok=True)
|
|
114
|
+
|
|
115
|
+
bpy.ops.wm.read_factory_settings(use_empty=True)
|
|
116
|
+
|
|
117
|
+
bpy.ops.mesh.primitive_grid_add(x_subdivisions=64, y_subdivisions=64, size=256)
|
|
118
|
+
terrain = bpy.context.object
|
|
119
|
+
terrain.name = "terrain"
|
|
120
|
+
displace(terrain)
|
|
121
|
+
terrain["tn_world_terrain"] = 1
|
|
122
|
+
|
|
123
|
+
bpy.ops.mesh.primitive_cone_add(vertices=8, radius1=1.0, radius2=0.0, depth=4.0)
|
|
124
|
+
pine = bpy.context.object
|
|
125
|
+
pine.name = "pine"
|
|
126
|
+
pine["tn_asset_id"] = "pine"
|
|
127
|
+
make_emitter(pine, 0.02, 0.002, 7)
|
|
128
|
+
|
|
129
|
+
bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=1, radius=1.0)
|
|
130
|
+
rock = bpy.context.object
|
|
131
|
+
rock.name = "rock"
|
|
132
|
+
rock["tn_asset_id"] = "rock"
|
|
133
|
+
make_emitter(rock, 0.02, 0.002, 11)
|
|
134
|
+
|
|
135
|
+
bpy.ops.mesh.primitive_circle_add(vertices=8, radius=0.5, fill_type="NGON")
|
|
136
|
+
cover = bpy.context.object
|
|
137
|
+
cover.name = "ground_cover"
|
|
138
|
+
cover["tn_asset_id"] = "ground_cover"
|
|
139
|
+
cover["tn_max_distance"] = 30.0
|
|
140
|
+
make_emitter(cover, 0.05, 0.005, 13)
|
|
141
|
+
|
|
142
|
+
# Real worlds keep scatter sources in an excluded collection so only their instances show.
|
|
143
|
+
sources = bpy.data.collections.new("_src")
|
|
144
|
+
bpy.context.scene.collection.children.link(sources)
|
|
145
|
+
for source in (pine, cover):
|
|
146
|
+
move_to_collection(source, sources)
|
|
147
|
+
bpy.context.view_layer.layer_collection.children["_src"].exclude = True
|
|
148
|
+
|
|
149
|
+
# Other real worlds nest a source in a visible collection under a hidden one, which is a
|
|
150
|
+
# different shape from an excluded collection: the object is in the view layer, so the glTF
|
|
151
|
+
# exporter skips it for not being in any visible collection unless the recipe stages it.
|
|
152
|
+
hidden = bpy.data.collections.new("hidden_sources")
|
|
153
|
+
hidden.hide_viewport = True
|
|
154
|
+
hidden.hide_render = True
|
|
155
|
+
bpy.context.scene.collection.children.link(hidden)
|
|
156
|
+
nested = bpy.data.collections.new("_src nested")
|
|
157
|
+
hidden.children.link(nested)
|
|
158
|
+
move_to_collection(rock, nested)
|
|
159
|
+
|
|
160
|
+
yard = bpy.data.collections.new("yard")
|
|
161
|
+
yard["tn_world_chunk"] = 1
|
|
162
|
+
bpy.context.scene.collection.children.link(yard)
|
|
163
|
+
|
|
164
|
+
bpy.ops.mesh.primitive_cube_add(size=2, location=(-100, 0, 1))
|
|
165
|
+
first = bpy.context.object
|
|
166
|
+
first.name = "yard_crate_a"
|
|
167
|
+
move_to_collection(first, yard)
|
|
168
|
+
|
|
169
|
+
bpy.ops.mesh.primitive_cube_add(size=2, location=(-30, 20, 1))
|
|
170
|
+
second = bpy.context.object
|
|
171
|
+
second.name = "yard_crate_b"
|
|
172
|
+
move_to_collection(second, yard)
|
|
173
|
+
|
|
174
|
+
# A unit-scale sanity anchor: this object crosses no convention and must not disturb a count.
|
|
175
|
+
bpy.ops.mesh.primitive_cube_add(size=2, location=(0, 0, 3))
|
|
176
|
+
anchor = bpy.context.object
|
|
177
|
+
anchor.name = "anchor"
|
|
178
|
+
anchor.matrix_world = Matrix.Identity(4)
|
|
179
|
+
|
|
180
|
+
bpy.ops.wm.save_as_mainfile(filepath=out)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
if __name__ == "__main__":
|
|
184
|
+
main()
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
# SPDX-License-Identifier: GPL-2.0-or-later
|
|
2
|
+
#
|
|
3
|
+
# Copyright (C) 2026 ThreeNative contributors
|
|
4
|
+
#
|
|
5
|
+
# This program is free software; you can redistribute it and/or modify it under the terms of the
|
|
6
|
+
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
|
|
7
|
+
# License, or (at your option) any later version. See ../LICENSE.GPL.
|
|
8
|
+
#
|
|
9
|
+
# What every recipe repeats: read the JSON request after `--`, load the source, export the GLB,
|
|
10
|
+
# print one machine-readable result line. A recipe file is then only the operation itself, which is
|
|
11
|
+
# the part an agent reads and adapts.
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import sys
|
|
16
|
+
|
|
17
|
+
import bpy
|
|
18
|
+
|
|
19
|
+
RESULT_PREFIX = "TN_BLENDER_RESULT "
|
|
20
|
+
|
|
21
|
+
IMPORTERS = {
|
|
22
|
+
".fbx": lambda p: bpy.ops.import_scene.fbx(filepath=p),
|
|
23
|
+
".obj": lambda p: bpy.ops.wm.obj_import(filepath=p),
|
|
24
|
+
".dae": lambda p: bpy.ops.wm.collada_import(filepath=p),
|
|
25
|
+
".gltf": lambda p: bpy.ops.import_scene.gltf(filepath=p),
|
|
26
|
+
".glb": lambda p: bpy.ops.import_scene.gltf(filepath=p),
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def fail(message):
|
|
31
|
+
sys.stderr.write("TN_BLENDER_ERROR: %s\n" % message)
|
|
32
|
+
sys.stderr.flush()
|
|
33
|
+
os._exit(2)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def request():
|
|
37
|
+
if "--" not in sys.argv:
|
|
38
|
+
fail("no '--' separator; pass the JSON request after it")
|
|
39
|
+
tail = sys.argv[sys.argv.index("--") + 1 :]
|
|
40
|
+
if len(tail) != 1:
|
|
41
|
+
fail("expected exactly one JSON argument, got %d" % len(tail))
|
|
42
|
+
try:
|
|
43
|
+
return json.loads(tail[0])
|
|
44
|
+
except ValueError as error:
|
|
45
|
+
fail("request is not JSON: %s" % error)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def load(source):
|
|
49
|
+
if not os.path.isfile(source):
|
|
50
|
+
fail("source '%s' does not exist" % source)
|
|
51
|
+
extension = os.path.splitext(source)[1].lower()
|
|
52
|
+
if extension == ".blend":
|
|
53
|
+
bpy.ops.wm.open_mainfile(filepath=source)
|
|
54
|
+
return
|
|
55
|
+
importer = IMPORTERS.get(extension)
|
|
56
|
+
if importer is None:
|
|
57
|
+
fail("unsupported source extension '%s'" % extension)
|
|
58
|
+
bpy.ops.wm.read_factory_settings(use_empty=True)
|
|
59
|
+
importer(source)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def meshes():
|
|
63
|
+
return [item for item in bpy.data.objects if item.type == "MESH"]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def triangles():
|
|
67
|
+
depsgraph = bpy.context.evaluated_depsgraph_get()
|
|
68
|
+
total = 0
|
|
69
|
+
for item in meshes():
|
|
70
|
+
evaluated = item.evaluated_get(depsgraph)
|
|
71
|
+
mesh = evaluated.to_mesh()
|
|
72
|
+
try:
|
|
73
|
+
mesh.calc_loop_triangles()
|
|
74
|
+
total += len(mesh.loop_triangles)
|
|
75
|
+
finally:
|
|
76
|
+
evaluated.to_mesh_clear()
|
|
77
|
+
return total
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def uv_layers():
|
|
81
|
+
return sum(len(item.data.uv_layers) for item in meshes())
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def collapse_decimate(item, ratio):
|
|
85
|
+
"""Add the collapse-decimate modifier `decimate` uses, so other recipes reuse that recipe's
|
|
86
|
+
operation instead of copying it. It measures nothing and writes nothing; the caller decides
|
|
87
|
+
what to export."""
|
|
88
|
+
modifier = item.modifiers.new(name="TNDecimate", type="DECIMATE")
|
|
89
|
+
modifier.decimate_type = "COLLAPSE"
|
|
90
|
+
modifier.ratio = float(ratio)
|
|
91
|
+
modifier.use_collapse_triangulate = True
|
|
92
|
+
return modifier
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def export(out):
|
|
96
|
+
directory = os.path.dirname(out)
|
|
97
|
+
if directory and not os.path.isdir(directory):
|
|
98
|
+
os.makedirs(directory, exist_ok=True)
|
|
99
|
+
for item in bpy.data.objects:
|
|
100
|
+
if item.animation_data is None or item.animation_data.action is None:
|
|
101
|
+
continue
|
|
102
|
+
action = item.animation_data.action
|
|
103
|
+
existing = {
|
|
104
|
+
strip.action.name
|
|
105
|
+
for track in item.animation_data.nla_tracks
|
|
106
|
+
for strip in track.strips
|
|
107
|
+
if strip.action
|
|
108
|
+
}
|
|
109
|
+
if action.name in existing:
|
|
110
|
+
continue
|
|
111
|
+
track = item.animation_data.nla_tracks.new()
|
|
112
|
+
track.name = action.name
|
|
113
|
+
track.strips.new(action.name, int(action.frame_range[0]), action)
|
|
114
|
+
item.animation_data.action = None
|
|
115
|
+
# `export_apply` is not the default, and without it a recipe that works through a
|
|
116
|
+
# modifier reports the number it measured and writes the geometry it started with:
|
|
117
|
+
# `decimate` at ratio 0.25 reported trianglesAfter 154 and shipped a 620-triangle GLB,
|
|
118
|
+
# byte-identical to the unmodified export. Blender's glTF exporter excludes armature
|
|
119
|
+
# modifiers from this, so a rig still exports as a rig rather than being baked flat.
|
|
120
|
+
bpy.ops.export_scene.gltf(
|
|
121
|
+
filepath=out,
|
|
122
|
+
export_apply=True,
|
|
123
|
+
export_format="GLB",
|
|
124
|
+
export_animations=True,
|
|
125
|
+
export_nla_strips=True,
|
|
126
|
+
export_skins=True,
|
|
127
|
+
export_yup=True,
|
|
128
|
+
use_selection=False,
|
|
129
|
+
)
|
|
130
|
+
if not os.path.isfile(out):
|
|
131
|
+
fail("export wrote no file at '%s'" % out)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def emit(summary):
|
|
135
|
+
summary["blender"] = bpy.app.version_string
|
|
136
|
+
sys.stdout.write("\n" + RESULT_PREFIX + json.dumps(summary, sort_keys=True) + "\n")
|
|
137
|
+
sys.stdout.flush()
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def action_fcurves(action):
|
|
141
|
+
"""Every F-curve in an action, across both of Blender's action shapes.
|
|
142
|
+
|
|
143
|
+
Blender 4.4 replaced `action.fcurves` with slotted actions — layers, strips and channelbags —
|
|
144
|
+
and 5.2 removed the old attribute outright, so a recipe written against `action.fcurves` dies
|
|
145
|
+
with `AttributeError: 'Action' object has no attribute 'fcurves'` on a current Blender while
|
|
146
|
+
still working on the 4.2 floor. Both shapes are read here so a recipe never has to know.
|
|
147
|
+
"""
|
|
148
|
+
curves = getattr(action, "fcurves", None)
|
|
149
|
+
if curves is not None:
|
|
150
|
+
return list(curves)
|
|
151
|
+
collected = []
|
|
152
|
+
for layer in action.layers:
|
|
153
|
+
for strip in layer.strips:
|
|
154
|
+
for bag in strip.channelbags:
|
|
155
|
+
collected.extend(bag.fcurves)
|
|
156
|
+
return collected
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def new_action(name, owner):
|
|
160
|
+
"""A new action and the F-curve collection to write into, for either action shape.
|
|
161
|
+
|
|
162
|
+
Returns `(action, fcurves, slot)`. `slot` is None on Blender before 4.4; `assign_action`
|
|
163
|
+
handles both.
|
|
164
|
+
"""
|
|
165
|
+
action = bpy.data.actions.new(name)
|
|
166
|
+
action.use_fake_user = True
|
|
167
|
+
if hasattr(action, "fcurves"):
|
|
168
|
+
return action, action.fcurves, None
|
|
169
|
+
slot = action.slots.new(id_type="OBJECT", name=owner.name)
|
|
170
|
+
layer = action.layers.new("Layer")
|
|
171
|
+
strip = layer.strips.new(type="KEYFRAME")
|
|
172
|
+
bag = strip.channelbag(slot, ensure=True)
|
|
173
|
+
return action, bag.fcurves, slot
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def assign_action(owner, action, slot):
|
|
177
|
+
owner.animation_data_create()
|
|
178
|
+
owner.animation_data.action = action
|
|
179
|
+
if slot is not None:
|
|
180
|
+
owner.animation_data.action_slot = slot
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# SPDX-License-Identifier: GPL-2.0-or-later
|
|
2
|
+
#
|
|
3
|
+
# Copyright (C) 2026 ThreeNative contributors
|
|
4
|
+
#
|
|
5
|
+
# This program is free software; you can redistribute it and/or modify it under the terms of the
|
|
6
|
+
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
|
|
7
|
+
# License, or (at your option) any later version. See ../LICENSE.GPL.
|
|
8
|
+
#
|
|
9
|
+
# Bake ambient occlusion into a texture. AO is *computed from geometry* — how much of the sky each
|
|
10
|
+
# point can see — so this measures the model rather than choosing an appearance. What the game then
|
|
11
|
+
# does with the map (multiply it, tint it, ignore it) is the game's decision, in src/render/.
|
|
12
|
+
#
|
|
13
|
+
# blender --background --factory-startup --python bake_ao.py -- \
|
|
14
|
+
# '{"source":"/abs/in.glb","out":"/abs/ao.png","size":256,"samples":16}'
|
|
15
|
+
#
|
|
16
|
+
# Adapt it: bake to a UV set the game controls, or raise `samples` for a hero asset. The recipe
|
|
17
|
+
# unwraps meshes that have no UVs, because a bake with no parameterisation writes nothing.
|
|
18
|
+
|
|
19
|
+
import math
|
|
20
|
+
import os
|
|
21
|
+
import sys
|
|
22
|
+
|
|
23
|
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
24
|
+
|
|
25
|
+
import bpy # noqa: E402
|
|
26
|
+
|
|
27
|
+
from _common import emit, fail, load, meshes, request # noqa: E402
|
|
28
|
+
|
|
29
|
+
payload = request()
|
|
30
|
+
source = payload.get("source")
|
|
31
|
+
out = payload.get("out")
|
|
32
|
+
size = int(payload.get("size", 256))
|
|
33
|
+
samples = int(payload.get("samples", 16))
|
|
34
|
+
|
|
35
|
+
if not isinstance(source, str) or not source:
|
|
36
|
+
fail("bake_ao requires a 'source' path")
|
|
37
|
+
if not isinstance(out, str) or not out:
|
|
38
|
+
fail("bake_ao requires an 'out' path for the baked PNG")
|
|
39
|
+
if size < 16 or size > 4096:
|
|
40
|
+
fail("'size' must be between 16 and 4096, got %d" % size)
|
|
41
|
+
|
|
42
|
+
load(source)
|
|
43
|
+
targets = meshes()
|
|
44
|
+
if not targets:
|
|
45
|
+
fail("'%s' has no meshes to bake" % source)
|
|
46
|
+
|
|
47
|
+
image = bpy.data.images.new("TN_AO", width=size, height=size)
|
|
48
|
+
|
|
49
|
+
for item in targets:
|
|
50
|
+
if len(item.data.uv_layers) == 0:
|
|
51
|
+
bpy.context.view_layer.objects.active = item
|
|
52
|
+
for other in bpy.context.selected_objects:
|
|
53
|
+
other.select_set(False)
|
|
54
|
+
item.select_set(True)
|
|
55
|
+
bpy.ops.object.mode_set(mode="EDIT")
|
|
56
|
+
bpy.ops.mesh.select_all(action="SELECT")
|
|
57
|
+
bpy.ops.uv.smart_project(angle_limit=math.radians(66.0), island_margin=0.02)
|
|
58
|
+
bpy.ops.object.mode_set(mode="OBJECT")
|
|
59
|
+
if not item.data.materials:
|
|
60
|
+
item.data.materials.append(bpy.data.materials.new("TN_BakeTarget"))
|
|
61
|
+
for material in item.data.materials:
|
|
62
|
+
if material is None:
|
|
63
|
+
continue
|
|
64
|
+
material.use_nodes = True
|
|
65
|
+
node = material.node_tree.nodes.new("ShaderNodeTexImage")
|
|
66
|
+
node.image = image
|
|
67
|
+
node.select = True
|
|
68
|
+
material.node_tree.nodes.active = node
|
|
69
|
+
|
|
70
|
+
bpy.context.scene.render.engine = "CYCLES"
|
|
71
|
+
bpy.context.scene.cycles.samples = samples
|
|
72
|
+
bpy.context.scene.render.bake.use_selected_to_active = False
|
|
73
|
+
|
|
74
|
+
for other in bpy.context.selected_objects:
|
|
75
|
+
other.select_set(False)
|
|
76
|
+
for item in targets:
|
|
77
|
+
item.select_set(True)
|
|
78
|
+
bpy.context.view_layer.objects.active = targets[0]
|
|
79
|
+
bpy.ops.object.bake(type="AO")
|
|
80
|
+
|
|
81
|
+
directory = os.path.dirname(out)
|
|
82
|
+
if directory and not os.path.isdir(directory):
|
|
83
|
+
os.makedirs(directory, exist_ok=True)
|
|
84
|
+
image.filepath_raw = out
|
|
85
|
+
image.file_format = "PNG"
|
|
86
|
+
image.save()
|
|
87
|
+
if not os.path.isfile(out):
|
|
88
|
+
fail("bake wrote no file at '%s'" % out)
|
|
89
|
+
|
|
90
|
+
pixels = list(image.pixels)
|
|
91
|
+
luminance = [
|
|
92
|
+
0.2126 * pixels[index] + 0.7152 * pixels[index + 1] + 0.0722 * pixels[index + 2]
|
|
93
|
+
for index in range(0, len(pixels), 4)
|
|
94
|
+
]
|
|
95
|
+
mean = sum(luminance) / len(luminance) if luminance else 0.0
|
|
96
|
+
lowest = min(luminance) if luminance else 0.0
|
|
97
|
+
highest = max(luminance) if luminance else 0.0
|
|
98
|
+
|
|
99
|
+
emit(
|
|
100
|
+
{
|
|
101
|
+
"meanLuminance": mean,
|
|
102
|
+
"maxLuminance": highest,
|
|
103
|
+
"minLuminance": lowest,
|
|
104
|
+
"out": out,
|
|
105
|
+
"outBytes": os.path.getsize(out),
|
|
106
|
+
"recipe": "bake_ao",
|
|
107
|
+
"samples": samples,
|
|
108
|
+
"size": size,
|
|
109
|
+
"source": source,
|
|
110
|
+
}
|
|
111
|
+
)
|