gamemaker_jmap_import/main.odin
2026-11-11 21:18:43 +01:00

653 lines
21 KiB
Odin

#+feature dynamic-literals
package main
import "base:runtime"
import "core:os"
import "core:math"
import "core:math/rand"
import "core:fmt"
import "core:encoding/json"
import "core:strings"
import "core:strconv"
import "core:mem"
/* ###
SWITCHES
*/
SwitchDefinition :: struct {
name: string,
fullname: string,
shortname: string,
usage: string,
description: string,
no_argument: bool,
callback: proc(value: string, args: ^byte) -> (ok: bool),
}
SwitchSplitError :: enum {
None,
Empty,
MissingDash,
MissingStartQuote,
MissingEndQuote,
}
switch_split :: proc(str: string) -> (name, value: string, err: SwitchSplitError) {
name = ""
value = ""
err = .None
if len(str) == 0 {
err = .Empty
return
}
if str[0] != '-' {
err = .MissingDash
return
}
colon_index := strings.index_rune(str, ':')
if colon_index == -1 {
name = str[1:]
return
}
name = str[1:colon_index]
value = str[colon_index + 1:]
if value[0] != '"' && value[len(value) - 1] == '"' {
err = .MissingStartQuote
return
} else if value[0] == '"' && value[len(value) - 1] != '"' {
err = .MissingEndQuote
return
}
if value[0] == '"' && value[len(value) - 1] == '"' {
value = value[1:len(value) - 2]
}
return
}
process_switches :: proc(switch_definitions: []SwitchDefinition, args: []string, args_out: ^byte, temp_allocator := context.temp_allocator) -> (_ok: bool) {
_ok = true
error_state: bool
switch_map := make(map[string]SwitchDefinition, temp_allocator)
for switch_definition in switch_definitions {
shortname := switch_definition.shortname
shortname_length := len(shortname)
if shortname_length > 0 {
if shortname in switch_map {
_ok = false
existing_switch_definition := switch_map[shortname]
fmt.eprintln("Argument error: Switch for ", switch_definition.name, " (", shortname, ") already existed for '", existing_switch_definition.name, sep = "")
} else {
switch_map[shortname] = switch_definition
}
}
fullname := switch_definition.fullname
fullname_length := len(fullname)
if fullname_length > 0 {
if fullname in switch_map {
_ok = false
existing_switch_definition := switch_map[fullname]
fmt.eprintln("Argument error: Switch for ", switch_definition.name, " (", fullname, ") already existed for '", existing_switch_definition.name, sep = "")
} else {
switch_map[fullname] = switch_definition
}
}
if shortname_length == 0 && fullname_length == 0 {
_ok = false
fmt.eprintln("Switch definition error: ", switch_definition.name, " had no shortname or fullname", sep = "")
}
}
for arg in args[1:] {
name, value, err := switch_split(arg)
if err != .None {
_ok = false
fmt.eprintln("Argument error: ", err, " (", arg, ")", sep = "")
continue
}
if name not_in switch_map {
_ok = false
fmt.eprintln("Argument error: Non-existent switch", name, sep = "")
continue
}
switch_map[name].callback(value, args_out)
}
return _ok
}
/* ###
GAMEMAKER RESOURCE HANDLING
*/
GAMEMAKER_RESOURCE_JSON5_MARSHAL_OPTIONS :: json.Marshal_Options {
spec = .JSON5,
pretty = true,
sort_maps_by_key = true,
indentation = 0,
spaces = 4,
use_spaces = true,
}
ResourceError :: union {
os.Error,
json.Error,
json.Marshal_Error,
}
ResourceType :: enum {
Extension,
Font,
Note,
Object,
Particle,
Path,
Room,
Script,
Sequence,
Shader,
Sound,
Sprite,
Tileset,
}
@rodata resource_type_folder_names := [ResourceType]string {
.Extension = "extensions",
.Font = "fonts",
.Note = "notes",
.Object = "objects",
.Particle = "particles",
.Path = "paths",
.Room = "rooms",
.Script = "scripts",
.Sequence = "sequences",
.Shader = "shaders",
.Sound = "sound",
.Sprite = "sprites",
.Tileset = "tilesets",
}
RoomLayerType :: enum {
Background,
Instance,
Tile,
Path,
Asset,
Effects,
UI,
_Invalid,
}
@rodata room_layer_type_identifier := [RoomLayerType]string {
.Background = "GMRBackgroundLayer",
.Instance = "GMRInstanceLayer",
.Tile = "GMRTileLayer",
.Path = "GMRPathLayer",
.Asset = "GMRAssetLayer",
.Effects = "GMREffectsLayer",
.UI = "GMRUiLayer",
._Invalid = "",
}
resource_read :: proc(path: string) -> (object: json.Object, err: ResourceError) {
data := os.read_entire_file(path, context.allocator) or_return
resource := json.parse(data, .JSON5, true) or_return
object = resource.(json.Object)
return
}
resource_write :: proc(path: string, data: json.Value) -> ResourceError {
str := json.marshal(data, GAMEMAKER_RESOURCE_JSON5_MARSHAL_OPTIONS) or_return
os.write_entire_file(path, str) or_return
return nil
}
resource_get_version :: proc(resource: json.Object) -> string {
return resource["resourceVersion"].(json.String)
}
resource_project_find_asset :: proc(project: json.Object, name: string, type: ResourceType) -> json.Value {
resources := project["resources"].(json.Array)
for resource in resources {
id := resource.(json.Object)["id"].(json.Object)
if id["name"].(json.String) != name {
continue
}
if strings.split(id["path"].(json.String), "/")[0] != resource_type_folder_names[type] {
continue
}
return resource
}
return nil
}
resource_room_layer_get_type :: proc(layer: json.Object) -> RoomLayerType {
type_name := layer["resourceType"].(json.String)
for type in RoomLayerType {
if type_name == room_layer_type_identifier[type] {
return type
}
}
return ._Invalid
}
resource_room_get_by_name :: proc(layers: ^json.Array, name: string) -> (_layer: ^json.Object, _ok: bool) {
for &layer in layers {
layer := &layer.(json.Object)
layer_name := layer["name"].(json.String)
if name == layer_name {
return layer, true
}
}
return nil, false
}
resource_path_is_type :: proc(path: string, type: ResourceType) -> bool {
path := strings.split(path, "/")
return path[0] == resource_type_folder_names[type]
}
resource_room_layer_create_instance :: proc(version, resource_version, object_name: string, x, y: f64, path: string, allocator := context.allocator) -> json.Object {
instance_id_number := rand.uint32() % (0xffffffff - 0x10000000) + 0x10000000
instance_id_hex_buffer: [8]byte
instance_id_hex := strconv.write_uint(instance_id_hex_buffer[:], u64(instance_id_number), 16)
instance_id := strings.concatenate({"inst_", instance_id_hex}, allocator)
instance := make(json.Object, allocator)
instance["$GMRInstance"] = version
instance["%Name"] = instance_id
instance["colour"] = 4294967295
instance["frozen"] = false
instance["hasCreationCode"] = false
instance["ignore"] = false
instance["imageIndex"] = 0
instance["imageSpeed"] = 1.0
instance["inheritCode"] = false
instance["inheritedItemId"] = nil
instance["inheritItemSettings"] = false
instance["isDnd"] = false
instance["name"] = instance_id
object_id := make(json.Object, allocator)
object_id["name"] = object_name
object_id["path"] = path
instance["objectId"] = object_id
instance["properties"] = json.Array({})
instance["resourceType"] = "GMRinstance"
instance["resourceVersion"] = resource_version
instance["rotation"] = 0.0
instance["scaleX"] = 1.0
instance["scaleY"] = 1.0
instance["x"] = x
instance["y"] = y
return instance
}
/* ###
PROGRAM
*/
HELP_MESSAGE :: """
--- GAMEMAKER JMAP IMPORTER ---
Usage: <program> <yyp_resource_path> <room_resource_path> <jmap_path> <jmap_config_path> [other flags...]
"""
ProgramArguments :: struct {
x, y: int,
clear_area: bool,
}
switch_definitions := []SwitchDefinition {
{
name = "x",
fullname = "x",
shortname = "x",
description = "set x at which to place the jmap contents at (default: 0)",
no_argument = false,
usage = "-x <value>",
callback = proc(value: string, args: ^byte) -> (ok: bool) {
args := cast(^ProgramArguments)args
x, x_ok := strconv.parse_int(value, 10)
if !x_ok {
fmt.eprintln("Invalid argument passed to switch 'x'")
return false
}
return true
}
},
{
name = "y",
fullname = "y",
shortname = "y",
description = "set y at which to place the jmap contents at (default: 0)",
no_argument = false,
usage = "-y <value>",
callback = proc(value: string, args: ^byte) -> (ok: bool) {
args := cast(^ProgramArguments)args
y, y_ok := strconv.parse_int(value, 10)
if !y_ok {
fmt.eprintln("Invalid argument passed to switch 'y'")
return false
}
return true
}
},
{
name = "clear_area",
fullname = "clear_area",
shortname = "clear_area",
description = "clear area where jmap contents are placed",
no_argument = true,
usage = "-clear_area",
callback = proc(value: string, args: ^byte) -> (ok: bool) {
args := cast(^ProgramArguments)args
args.clear_area = true
return true
}
},
}
main :: proc() {
args := os.args
switch len(args) {
case 0, 1, 2, 3, 4:
fmt.println("ERROR: Too few arguments")
fmt.println(HELP_MESSAGE)
case:
yyp_resource_path := os.args[1]
room_resource_path := os.args[2]
jmap_path := os.args[3]
jmap_config_path := os.args[4]
error := program(yyp_resource_path, room_resource_path, jmap_path, jmap_config_path)
if error != nil {
error := error.(ProgramError)
fmt.println("ERROR (", error.type, "):", error.message, sep = "")
fmt.println(error.location)
}
}
}
ProgramErrorError :: enum {
JmapBadObjectList,
BadJmapConfig,
RoomLayerNotFound,
RoomLayerNotInstance,
}
ProgramErrorType :: union {
ProgramErrorError,
JmapObjectListError,
os.Error,
json.Error,
json.Marshal_Error,
}
ProgramError :: struct {
type: ProgramErrorType,
message: string,
location: runtime.Source_Code_Location,
}
program_error_create :: proc(error: ProgramErrorType, message: string, loc := #caller_location) -> ProgramError {
return {type = error, message = message, location = loc}
}
program :: proc(yyp_project_path, room_resource_path, jmap_path, jmap_config_path: string) -> Maybe(ProgramError) {
yyp_project_string, yyp_project_read_error := os.read_entire_file_from_path(yyp_project_path, context.allocator)
if yyp_project_read_error != nil {
return program_error_create(yyp_project_read_error, fmt.tprint("Couldn't open Gamemaker project at '", yyp_project_path, "'", sep = ""))
}
yyp_project_json, yyp_project_parse_error := json.parse_bytes(yyp_project_string, allocator = context.allocator)
if yyp_project_parse_error != nil {
return program_error_create(yyp_project_parse_error, "Couldn't parse Gamemaker project json")
}
room_resource_string, room_resource_read_error := os.read_entire_file_from_path(room_resource_path, context.allocator)
if room_resource_read_error != nil {
return program_error_create(room_resource_read_error, fmt.tprint("Couldn't open GameMaker room resource at '", room_resource_path, "'", sep = ""))
}
room_resource_json, room_resource_parse_error := json.parse_bytes(room_resource_string, allocator = context.allocator)
if room_resource_parse_error != nil {
return program_error_create(room_resource_parse_error ,"Failed to parse yyp project json")
}
jmap_json, jmap_read_error := os.read_entire_file_from_path(jmap_path, context.allocator)
if jmap_read_error != nil {
return program_error_create(jmap_read_error, fmt.tprint("Couldn't open jmap path at '", jmap_path, "'", sep = ""))
}
jmap_instance_list, jmap_instance_list_error := jmap_instance_list_from_text(string(jmap_json), context.allocator, context.temp_allocator)
switch jmap_instance_list_error {
case .None:
case .NoStartMarker:
return program_error_create(jmap_instance_list_error, "Couldn't find start marker in jmap")
case .NoEndMarker:
return program_error_create(jmap_instance_list_error, "Couldn't find end marker in jmap")
case .BadListLength:
return program_error_create(jmap_instance_list_error, "Object list was not of a correct length")
case .BadObject:
return program_error_create(jmap_instance_list_error, "Bad object in jmap object list")
}
jmap_config_text, jmap_config_read_error := os.read_entire_file_from_path(jmap_config_path, allocator = context.allocator)
if jmap_config_read_error != nil {
return program_error_create(jmap_read_error, fmt.tprint("Couldn't open jmap config path at '", jmap_config_path, "'", sep = ""))
}
jmap_config_json, jmap_config_parse_error := json.parse_bytes(jmap_config_text, allocator = context.allocator)
if jmap_config_parse_error != nil {
return program_error_create(jmap_config_parse_error, "Failed to parse jmap config");
}
jmap_config, jmap_config_ok := jmap_config_get_from_json(jmap_config_json)
if !jmap_config_ok {
return program_error_create(ProgramErrorError.BadJmapConfig, "Malformed jmap config")
}
jmap_name_to_gamemaker_instance_map := make(map[string]^GameMakerInstanceDefinition)
for key, &binding in jmap_instance_to_gamemaker_binding_map {
jmap_name_to_gamemaker_instance_map[binding.jmap_object_name] = &binding
}
jmap_config_root := jmap_config_json.(json.Object)
jmap_config_mappings, jmap_config_mappings_ok := jmap_config_root["mappings"]
if jmap_config_mappings_ok {
jmap_config_mappings := jmap_config_mappings.(json.Object)
for key, value in jmap_config_mappings {
binding, binding_ok := jmap_name_to_gamemaker_instance_map[key]
if !binding_ok {
fmt.eprintln("WARNING: Binding for jmap object '", key, "' does not exist", sep = "")
continue
}
binding.changed = true
jmap_name_to_gamemaker_instance_map[key].object_name = value.(json.Object)["object_name"].(json.String)
}
}
for key, &binding in jmap_instance_to_gamemaker_binding_map {
resource := resource_project_find_asset(yyp_project_json.(json.Object), binding.object_name, .Object)
if resource == nil {
if binding.changed {
fmt.eprintln("WARNING: Resource for jmap object '", binding.jmap_object_name, "' couldn't be found in project file (looked for '", binding.object_name, "')", sep = "")
}
continue
}
binding.path = resource.(json.Object)["id"].(json.Object)["path"].(json.String)
}
room_resource := &room_resource_json.(json.Object)
room_layers := &(&room_resource["layers"]).(json.Array)
room_layer, room_layer_found := resource_room_get_by_name(room_layers, jmap_config.layer)
if !room_layer_found {
return program_error_create(ProgramErrorError.RoomLayerNotFound, fmt.aprint("Couldn't find room layer '", jmap_config.layer, "'", sep = ""))
}
if room_layer_type := resource_room_layer_get_type(room_layer^); room_layer_type != .Instance {
return program_error_create(ProgramErrorError.RoomLayerNotInstance, fmt.aprint("Found room layer '", jmap_config.layer, "' was not an instance layer", sep = ""))
}
room_layer_instances := &((&room_layer["instances"]).(json.Array))
for jmap_instance in jmap_instance_list {
binding := &jmap_instance_to_gamemaker_binding_map[jmap_instance.object_index]
if len(binding.path) == 0 {
if !binding.warned {
fmt.eprintln("Jmap used '", binding.jmap_object_name, "' but no binding was set, or object wasn't found in project '", binding.object_name, sep = "")
binding.warned = true
}
continue
}
instance := resource_room_layer_create_instance("v4", "2.0", binding.object_name, 32, 32, binding.path, context.allocator)
append(room_layer_instances, instance)
}
room_resource_after, room_resource_after_marshal_error := json.marshal(room_resource_json, GAMEMAKER_RESOURCE_JSON5_MARSHAL_OPTIONS)
if room_resource_after_marshal_error != nil {
return program_error_create(room_resource_after_marshal_error, "Failed to convert marshal room data to resource")
}
room_resource_after_write_error := os.write_entire_file_from_bytes(room_resource_path, room_resource_after)
if room_resource_after_write_error != nil {
return program_error_create(room_resource_after_write_error, "Failed to write modified room data to resource")
}
return nil
}
JmapImportConfig :: struct {
layer: string,
}
JmapObjectListError :: enum {
None,
NoStartMarker,
NoEndMarker,
BadListLength,
BadObject,
}
JmapObjectInstance :: struct {
x, y, object_index: int,
}
jmap_instance_list_from_text :: proc(text: string, allocator: mem.Allocator, temp_allocator: mem.Allocator) -> (_object_list: []JmapObjectInstance, _error: JmapObjectListError) {
object_start_marker := "objects: (x, y, type)\n"
object_start_marker_index := strings.index(text, object_start_marker)
if object_start_marker_index == -1 {
return {}, .NoStartMarker
}
object_start_index := object_start_marker_index + len(object_start_marker)
object_end_marker := "version:"
object_end_index := strings.index(text, object_end_marker)
if object_end_index == -1 {
return {}, .NoEndMarker
}
object_list_string := text[object_start_index:object_end_index]
object_list_split := strings.split(object_list_string, sep = " ", allocator = temp_allocator)
if len(object_list_split) % 3 != 0 {
return {}, .BadListLength
}
object_list := make([]JmapObjectInstance, len(object_list_split) / 3, allocator)
for i := 0; i < len(object_list); i += 1 {
x, x_ok := strconv.parse_int(strings.trim_space(object_list_split[i * 3 + 0]), 10)
if !x_ok {
fmt.println("ERROR: Couldn't parse x of object '", object_list_split[i * 3 + 0], "'", sep = "")
return {}, .BadObject
}
y, y_ok := strconv.parse_int(strings.trim_space(object_list_split[i * 3 + 1]), 10)
if !y_ok {
fmt.println("ERROR: Couldn't parse y of object '", object_list_split[i * 3 + 1], "'", sep = "")
return {}, .BadObject
}
object_index, object_index_ok := strconv.parse_int(strings.trim_space(object_list_split[i * 3 + 2]), 10)
if !object_index_ok {
fmt.println("ERROR: Couldn't parse object_index of object '", object_list_split[i * 3 + 2], "'", sep = "")
return {}, .BadObject
}
object_list[i] = {x, y, object_index}
}
return object_list, .None
}
jmap_config_get_from_json :: proc(root: json.Value) -> (_config: JmapImportConfig, _ok: bool) {
_ok = true
root := root.(json.Object)
if layer, layer_ok := root["layer"]; !layer_ok {
fmt.println("ERROR: Couldn't find 'layer' property in jmap config")
_ok = false
} else {
_config.layer = layer.(json.String)
}
return _config, _ok
}
jmap_object_map_reverse: map[string]int
GameMakerInstanceDefinition :: struct {
object_name: string,
jmap_object_name: string,
changed: bool,
warned: bool,
path: string,
}
jmap_instance_to_gamemaker_binding_map := map[int]GameMakerInstanceDefinition {
1 = {object_name = "objBlock", jmap_object_name = "block"},
2 = {object_name = "objMiniBlock", jmap_object_name = "mini_block"},
3 = {object_name = "objSpikeUp", jmap_object_name = "spike_up"},
4 = {object_name = "objSpikeRight", jmap_object_name = "spike_right"},
5 = {object_name = "objSpikeLeft", jmap_object_name = "spike_left"},
6 = {object_name = "objSpikeDown", jmap_object_name = "spike_down"},
7 = {object_name = "objMiniSpikeUp", jmap_object_name = "mini_spike_up"},
8 = {object_name = "objMiniSpikeRight", jmap_object_name = "mini_spike_right"},
9 = {object_name = "objMiniSpikeLeft", jmap_object_name = "mini_spike_left"},
10 = {object_name = "objMiniSpikeDown", jmap_object_name = "mini_spike_down"},
11 = {object_name = "objCherry", jmap_object_name = "fruit"},
12 = {object_name = "objSave", jmap_object_name = "save"},
13 = {object_name = "objPlatform", jmap_object_name = "platform"},
14 = {object_name = "objWater1", jmap_object_name = "water_1"},
15 = {object_name = "objWater3", jmap_object_name = "water_3"},
16 = {object_name = "objVineR", jmap_object_name = "vine_r"},
17 = {object_name = "objVineL", jmap_object_name = "vine_l"},
18 = {object_name = "objKillerBlock", jmap_object_name = "killer_block"},
20 = {object_name = "objPlayerStart", jmap_object_name = "player_start"},
21 = {object_name = "objWarp", jmap_object_name = "warp"},
22 = {object_name = "objJumpRefresher", jmap_object_name = "jump_refresher"},
23 = {object_name = "objWater2", jmap_object_name = "water_2"},
24 = {object_name = "objGravityFlipperUp", jmap_object_name = "gravity_flipper_up"},
25 = {object_name = "objGravityFlipperDown", jmap_object_name = "gravity_flipper_down"},
26 = {object_name = "objSaveFlipped", jmap_object_name = "save_flipped"},
27 = {object_name = "objBulletBlocker", jmap_object_name = "bullet_blocker"},
28 = {object_name = "objSidewaysPlatform", jmap_object_name = "sideways_platform"},
30 = {object_name = "objMiniWater1", jmap_object_name = "mini_water_1"},
31 = {object_name = "objMiniWater3", jmap_object_name = "mini_water_3"},
32 = {object_name = "objMiniWater2", jmap_object_name = "mini_water_2"},
33 = {object_name = "objMiniCatharsisWater", jmap_object_name = "mini_catharsis_water"},
34 = {object_name = "objWaterNekoron", jmap_object_name = "water_nekoron"},
35 = {object_name = "objMiniWaterNekoron", jmap_object_name = "mini_water_nekoron"},
36 = {object_name = "objLineSpikeUp", jmap_object_name = "spike_up"},
37 = {object_name = "objLineSpikeRight", jmap_object_name = "spike_right"},
38 = {object_name = "objLineSpikeLeft", jmap_object_name = "spike_left"},
39 = {object_name = "objLineSpikeDown", jmap_object_name = "spike_down"},
40 = {object_name = "objMiniLineSpikeUp", jmap_object_name = "spike_up"},
41 = {object_name = "objMiniLineSpikeRight", jmap_object_name = "spike_right"},
42 = {object_name = "objMiniLineSpikeLeft", jmap_object_name = "spike_left"},
43 = {object_name = "objMiniLineSpikeDown", jmap_object_name = "spike_down"},
44 = {object_name = "objLineBlockHorizontal", jmap_object_name = "line_block_horizontal"},
45 = {object_name = "objLineBlockVertical", jmap_object_name = "line_block_vertical"},
46 = {object_name = "objMiniLineBlockHorizontal", jmap_object_name = "mini_line_block_horizontal"},
47 = {object_name = "objMiniLineBlockVertical", jmap_object_name = "mini_line_block_vertical"},
}