xiandie/asset/art/ui/note/aseprite_slice_to_atlas.gd

73 lines
1.9 KiB
GDScript3
Raw Normal View History

2025-07-02 11:58:36 +00:00
extends Node2D
@export var export_dir_root := "res://asset/art/ui/note/"
@export var json: JSON # can be a JSONParseResult or a Dictionary
@export var texture: Texture2D
func _ready() -> void:
_run()
var export_dir
func _run() -> void:
if not json or not texture:
printerr("JSON 或 texture 未设置")
return
if not export_dir_root:
push_error("导出目录未设置")
return
export_dir = export_dir_root + ("" if export_dir_root.ends_with("/") else "/")
export_dir = export_dir + json.resource_path.get_file().split(".")[0] + "/"
print("导出目录: ", export_dir)
# 确保导出目录存在
DirAccess.make_dir_recursive_absolute(export_dir)
# 解析 JSON 数据
var data: Dictionary
if json:
data = json.data
# 检查 meta.slices
if not data.has("meta") or not data.meta.has("slices"):
push_error("JSON 中缺少 meta.slices")
return
for slice_dict in data.meta.slices:
var slice_name = slice_dict.get("name", "")
var keys = slice_dict.get("keys", [])
if slice_name == "" or keys.is_empty():
continue
var key = keys[0]
var bounds = key.get("bounds", null)
if typeof(bounds) != TYPE_DICTIONARY:
continue
var rect := Rect2(
bounds.get("x", 0), bounds.get("y", 0), bounds.get("w", 0), bounds.get("h", 0)
)
_create_and_save_atlas(slice_name, rect)
print("已导出 Atlas: ", slice_name, " at ", export_dir)
get_tree().quit.call_deferred()
func _create_and_save_atlas(atlas_name: String, region: Rect2) -> void:
var path = export_dir + atlas_name + ".tres"
var atlas_res: AtlasTexture
if FileAccess.file_exists(path):
atlas_res = load(path)
print_rich("[color=cyan]加载已有的 Atlas: ", path)
if not atlas_res:
atlas_res = AtlasTexture.new()
atlas_res.resource_path = path
print_rich("[color=green]创建新的 Atlas: ", path)
atlas_res.atlas = texture
atlas_res.filter_clip = true
atlas_res.region = region # 修正了原来拼写错误的 regoin
ResourceSaver.save(atlas_res, path)