#!/bin/bash
#
# Stage everything a `json kind=tilemap` block needs around it.
#
# A tilemap is the least self-contained of the four formats. Loading one really
# opens the tileset image, and an actor object really resolves its `character`
# property against AKGL_REGISTRY_CHARACTER -- which in turn needs the character's
# sprites registered. So this stages three things, and
# tools/docs_checkjson.c's `tilemap` row loads ./sprites and then ./characters
# before the map itself.
#
# **The tileset image is staged as `assets/tileset.png`**, and a chapter's map
# has to name that path. It is a copy of the sprite sheet, and that is fine: the
# loader does not check the image against the tileset's declared geometry, it
# only has to be a readable PNG.
#
#   The obvious alternative was `assets/World_A1.png`, which is what
#   tests/assets/testmap.tmj names. That file carries the default filename of
#   RPG Maker's bundled art and ships here with no license file beside it, which
#   is a finding this project is recording rather than spreading into the manual.
#   A tutorial a reader copies must not inherit an obligation nobody has checked.
#
# **The character is named `testcharacter`**, which is a contract with any
# chapter whose map has an actor object. Change it here and change the chapter.
#
# Embedded tilesets only. `"source"` appears nowhere in src/tilemap.c;
# akgl_tilemap_load_tilesets_each reads `columns`, `firstgid`, `tilecount` and
# `image` straight off each element of the map's own `tilesets` array. An
# external tileset reference -- the form Tiled writes by default -- does not
# load. Every object in an object group also needs a `type` string, plain
# rectangles included.
#
# $1 is the repository root. The caller runs this with the sandbox as the
# working directory.

set -u

ROOT="${1:-}"
if [ -z "${ROOT}" ]; then
    echo "usage: tilemap.sh <repository-root>" >&2
    exit 2
fi

mkdir -p assets sprites characters || exit 1
cp "${ROOT}/tests/assets/spritesheet.png" assets/tileset.png || exit 1
cp "${ROOT}/tests/assets/spritesheet.png" sprites/spritesheet.png || exit 1

cat > sprites/testactor_standing.json <<'JSON'
{
    "spritesheet": {
	"filename": "spritesheet.png",
	"frame_width": 48,
	"frame_height": 48
    },
    "name": "testactor standing",
    "width": 48,
    "height": 48,
    "speed": 200,
    "loop": true,
    "loopReverse": false,
    "frames": [0]
}
JSON

# AKGL_ACTOR_STATE_ALIVE is 1 << 4 and AKGL_ACTOR_STATE_FACE_DOWN is 1 << 0, so
# this mapping is the state 17 a map's actor object usually carries.
cat > characters/testcharacter.json <<'JSON'
{
    "name": "testcharacter",
    "speedtime": 100,
    "speed_x": 0.20,
    "speed_y": 0.20,
    "acceleration_x": 0.20,
    "acceleration_y": 0.20,
    "sprite_mappings": [
	{
	    "state": [
		"AKGL_ACTOR_STATE_ALIVE",
		"AKGL_ACTOR_STATE_FACE_DOWN"
	    ],
	    "sprite": "testactor standing"
	}
    ]
}
JSON
