@threenative/core 0.3.0 → 0.3.2

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.
Files changed (39) hide show
  1. package/README.md +10 -0
  2. package/capabilities.json +1881 -131
  3. package/dist/assets-kyoF7JlJ.d.ts +103 -0
  4. package/dist/{audio-Dp2mXpD3.d.ts → audio-BFiGneTL.d.ts} +62 -0
  5. package/dist/canvas-layer-BLVijiUJ.d.ts +62 -0
  6. package/dist/{game-CYIaKhgl.d.ts → game-XGrTzapq.d.ts} +350 -164
  7. package/dist/gpu-readback-D2iRvoe9.d.ts +112 -0
  8. package/dist/hot.d.ts +5 -3
  9. package/dist/hot.js +5 -1
  10. package/dist/index.d.ts +813 -143
  11. package/dist/index.js +4548 -941
  12. package/dist/net.d.ts +65 -0
  13. package/dist/net.js +643 -0
  14. package/dist/playtest.d.ts +29 -5
  15. package/dist/playtest.js +181 -35
  16. package/dist/react.d.ts +4 -2
  17. package/dist/{canvas-layer-CtrZHgIh.d.ts → renderer-C6hqZpoG.d.ts} +237 -75
  18. package/dist/world.d.ts +203 -4
  19. package/dist/world.js +2536 -25
  20. package/gpl/LICENSE.GPL +117 -0
  21. package/gpl/convert.py +192 -0
  22. package/gpl/recipes/_common.py +169 -0
  23. package/gpl/recipes/bake_ao.py +111 -0
  24. package/gpl/recipes/decimate.py +64 -0
  25. package/gpl/recipes/retarget.py +131 -0
  26. package/gpl/recipes/unwrap.py +71 -0
  27. package/mcp/blender-server.mjs +632 -0
  28. package/mcp/blender.mjs +27 -0
  29. package/mcp/engine-server.mjs +271 -23
  30. package/mcp/engine.mjs +15 -7
  31. package/mcp/install.d.mts +37 -0
  32. package/mcp/install.mjs +94 -26
  33. package/mcp/servers.d.mts +34 -0
  34. package/mcp/servers.mjs +110 -9
  35. package/package.json +36 -8
  36. package/patches/three@0.185.1.patch +249 -14
  37. package/scripts/ensure-mcp.mjs +20 -13
  38. package/scripts/bundle-engine-mcp.mjs +0 -15
  39. package/scripts/generate-version.mjs +0 -13
@@ -0,0 +1,117 @@
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 2, June 1991
3
+
4
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
5
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
6
+
7
+ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
8
+
9
+ Preamble
10
+
11
+ The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
12
+
13
+ When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
14
+
15
+ To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
16
+
17
+ For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
18
+
19
+ We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
20
+
21
+ Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
22
+
23
+ Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
24
+
25
+ The precise terms and conditions for copying, distribution and modification follow.
26
+
27
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
28
+
29
+ 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
30
+
31
+ Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
32
+
33
+ 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
34
+
35
+ You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
36
+
37
+ 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
38
+
39
+ a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
40
+
41
+ b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
42
+
43
+ c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
44
+
45
+ These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
46
+
47
+ Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
48
+
49
+ In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
50
+
51
+ 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
52
+
53
+ a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
54
+
55
+ b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
56
+
57
+ c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
58
+
59
+ The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
60
+
61
+ If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
62
+
63
+ 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
64
+
65
+ 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
66
+
67
+ 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
68
+
69
+ 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
70
+
71
+ If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
72
+
73
+ It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
74
+
75
+ This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
76
+
77
+ 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
78
+
79
+ 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
80
+
81
+ Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
82
+
83
+ 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
84
+
85
+ NO WARRANTY
86
+
87
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
88
+
89
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
90
+
91
+ END OF TERMS AND CONDITIONS
92
+
93
+ How to Apply These Terms to Your New Programs
94
+
95
+ If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
96
+
97
+ To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
98
+
99
+ one line to give the program's name and an idea of what it does. Copyright (C) yyyy name of author
100
+
101
+ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
102
+
103
+ This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
104
+
105
+ You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail.
106
+
107
+ If the program is interactive, make it output a short notice like this when it starts in an interactive mode:
108
+
109
+ Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
110
+
111
+ The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.
112
+
113
+ You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:
114
+
115
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker.
116
+
117
+ signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice
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,169 @@
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 export(out):
85
+ directory = os.path.dirname(out)
86
+ if directory and not os.path.isdir(directory):
87
+ os.makedirs(directory, exist_ok=True)
88
+ for item in bpy.data.objects:
89
+ if item.animation_data is None or item.animation_data.action is None:
90
+ continue
91
+ action = item.animation_data.action
92
+ existing = {
93
+ strip.action.name
94
+ for track in item.animation_data.nla_tracks
95
+ for strip in track.strips
96
+ if strip.action
97
+ }
98
+ if action.name in existing:
99
+ continue
100
+ track = item.animation_data.nla_tracks.new()
101
+ track.name = action.name
102
+ track.strips.new(action.name, int(action.frame_range[0]), action)
103
+ item.animation_data.action = None
104
+ # `export_apply` is not the default, and without it a recipe that works through a
105
+ # modifier reports the number it measured and writes the geometry it started with:
106
+ # `decimate` at ratio 0.25 reported trianglesAfter 154 and shipped a 620-triangle GLB,
107
+ # byte-identical to the unmodified export. Blender's glTF exporter excludes armature
108
+ # modifiers from this, so a rig still exports as a rig rather than being baked flat.
109
+ bpy.ops.export_scene.gltf(
110
+ filepath=out,
111
+ export_apply=True,
112
+ export_format="GLB",
113
+ export_animations=True,
114
+ export_nla_strips=True,
115
+ export_skins=True,
116
+ export_yup=True,
117
+ use_selection=False,
118
+ )
119
+ if not os.path.isfile(out):
120
+ fail("export wrote no file at '%s'" % out)
121
+
122
+
123
+ def emit(summary):
124
+ summary["blender"] = bpy.app.version_string
125
+ sys.stdout.write("\n" + RESULT_PREFIX + json.dumps(summary, sort_keys=True) + "\n")
126
+ sys.stdout.flush()
127
+
128
+
129
+ def action_fcurves(action):
130
+ """Every F-curve in an action, across both of Blender's action shapes.
131
+
132
+ Blender 4.4 replaced `action.fcurves` with slotted actions — layers, strips and channelbags —
133
+ and 5.2 removed the old attribute outright, so a recipe written against `action.fcurves` dies
134
+ with `AttributeError: 'Action' object has no attribute 'fcurves'` on a current Blender while
135
+ still working on the 4.2 floor. Both shapes are read here so a recipe never has to know.
136
+ """
137
+ curves = getattr(action, "fcurves", None)
138
+ if curves is not None:
139
+ return list(curves)
140
+ collected = []
141
+ for layer in action.layers:
142
+ for strip in layer.strips:
143
+ for bag in strip.channelbags:
144
+ collected.extend(bag.fcurves)
145
+ return collected
146
+
147
+
148
+ def new_action(name, owner):
149
+ """A new action and the F-curve collection to write into, for either action shape.
150
+
151
+ Returns `(action, fcurves, slot)`. `slot` is None on Blender before 4.4; `assign_action`
152
+ handles both.
153
+ """
154
+ action = bpy.data.actions.new(name)
155
+ action.use_fake_user = True
156
+ if hasattr(action, "fcurves"):
157
+ return action, action.fcurves, None
158
+ slot = action.slots.new(id_type="OBJECT", name=owner.name)
159
+ layer = action.layers.new("Layer")
160
+ strip = layer.strips.new(type="KEYFRAME")
161
+ bag = strip.channelbag(slot, ensure=True)
162
+ return action, bag.fcurves, slot
163
+
164
+
165
+ def assign_action(owner, action, slot):
166
+ owner.animation_data_create()
167
+ owner.animation_data.action = action
168
+ if slot is not None:
169
+ 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
+ )
@@ -0,0 +1,64 @@
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
+ # Reduce a model's triangle count to a requested fraction, preserving its materials, UVs and rig.
10
+ # It changes how much geometry there is, never what the geometry looks like: no material, colour,
11
+ # light or curve is authored here.
12
+ #
13
+ # blender --background --factory-startup --python decimate.py -- \
14
+ # '{"source":"/abs/in.glb","out":"/abs/out.glb","ratio":0.5}'
15
+ #
16
+ # Adapt it: `ratio` is per-object here; a real budget is usually per-object, weighted by how close
17
+ # the object gets to the camera. Read `blender_recipes` for this text and edit it into your game.
18
+
19
+ import os
20
+ import sys
21
+
22
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
23
+
24
+ import bpy # noqa: E402
25
+
26
+ from _common import export, fail, load, meshes, request, triangles, emit # noqa: E402
27
+
28
+ payload = request()
29
+ source = payload.get("source")
30
+ out = payload.get("out")
31
+ ratio = payload.get("ratio", 0.5)
32
+
33
+ if not isinstance(source, str) or not source:
34
+ fail("decimate requires a 'source' path")
35
+ if not isinstance(out, str) or not out:
36
+ fail("decimate requires an 'out' path")
37
+ if not isinstance(ratio, (int, float)) or not 0 < float(ratio) <= 1:
38
+ fail("'ratio' must be greater than 0 and at most 1, got %r" % (ratio,))
39
+
40
+ load(source)
41
+ before = triangles()
42
+ if before == 0:
43
+ fail("'%s' has no triangles to decimate" % source)
44
+
45
+ for item in meshes():
46
+ modifier = item.modifiers.new(name="TNDecimate", type="DECIMATE")
47
+ modifier.decimate_type = "COLLAPSE"
48
+ modifier.ratio = float(ratio)
49
+ modifier.use_collapse_triangulate = True
50
+
51
+ after = triangles()
52
+ export(out)
53
+ emit(
54
+ {
55
+ "achievedRatio": (after / before) if before else 0.0,
56
+ "out": out,
57
+ "outBytes": os.path.getsize(out),
58
+ "recipe": "decimate",
59
+ "requestedRatio": float(ratio),
60
+ "source": source,
61
+ "trianglesAfter": after,
62
+ "trianglesBefore": before,
63
+ }
64
+ )