aboutsummaryrefslogtreecommitdiff
path: root/io.go
blob: 1b2fd5d21408436fba2290a5491fa3979c9eda90 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package main

import (
	"bytes"
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"gopkg.in/yaml.v3"
)

// Save format is YAML header with metadata, then the text grid below.
// Format:
// ---
// <yaml metadata>
// ...
// <grid lines>

type SaveData struct {
	Name       string      `yaml:"name"`
	Width      int         `yaml:"width"`
	Height     int         `yaml:"height"`
	Palette    []Terrain   `yaml:"palette"`
	GridBody   string      `yaml:"grid_body,omitempty"`
	GridColors []string    `yaml:"grid_colors,omitempty"`
	TextLabels []TextLabel `yaml:"text_labels,omitempty"`
	Submaps    []SubmapRef `yaml:"submaps,omitempty"`
}

type SubmapRef struct {
	X    int       `yaml:"x"`
	Y    int       `yaml:"y"`
	Data SaveData  `yaml:"data"`
}

// SerializeMap serializes the map to the save format.
func SerializeMap(m *Map, path string) error {
	data := buildSaveData(m)

	yamlBytes, err := yaml.Marshal(data)
	if err != nil {
		return err
	}

	var buf bytes.Buffer
	buf.WriteString("---\n")
	buf.Write(yamlBytes)
	buf.WriteString("...\n")

	for _, row := range m.Grid {
		for _, cell := range row {
			if cell.Terrain < 0 || cell.Terrain >= len(m.Palette) {
				buf.WriteByte(' ')
			} else {
				buf.WriteString(m.Palette[cell.Terrain].ASCII)
			}
		}
		buf.WriteByte('\n')
	}

	dir := filepath.Dir(path)
	if err := os.MkdirAll(dir, 0755); err != nil {
		return err
	}
	return os.WriteFile(path, buf.Bytes(), 0644)
}

func buildSaveData(m *Map) SaveData {
	sd := SaveData{
		Name:    m.Name,
		Width:   m.Width,
		Height:  m.Height,
		Palette: m.Palette,
	}
	// Build grid body (only stored in YAML for submaps)
	var gb strings.Builder
	for _, row := range m.Grid {
		for _, cell := range row {
			if cell.Terrain < 0 || cell.Terrain >= len(m.Palette) {
				gb.WriteByte(' ')
			} else {
				gb.WriteString(m.Palette[cell.Terrain].ASCII)
			}
		}
		gb.WriteByte('\n')
	}
	if m.Parent != nil {
		sd.GridBody = gb.String()
	}

	for y := range m.Grid {
		for x := range m.Grid[y] {
			c := m.Grid[y][x]
			if c.Color != "" {
				sd.GridColors = append(sd.GridColors, fmt.Sprintf("%d,%d,%s", x, y, c.Color))
			}
		}
	}
	for _, tl := range m.TextLabels {
		sd.TextLabels = append(sd.TextLabels, tl)
	}
	for pt, sub := range m.Submaps {
		sd.Submaps = append(sd.Submaps, SubmapRef{
			X: pt.X, Y: pt.Y,
			Data: buildSaveData(sub),
		})
	}
	return sd
}

// DeserializeMap reads a saved map file.
func DeserializeMap(path string) (*Map, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}
	content := string(data)

	if !strings.HasPrefix(content, "---\n") {
		return nil, fmt.Errorf("invalid save file: missing YAML header")
	}

	endIdx := strings.Index(content, "\n...\n")
	if endIdx < 0 {
		return nil, fmt.Errorf("invalid save file: missing ... terminator")
	}

	yamlPart := content[4:endIdx]
	gridPart := content[endIdx+5:]

	var sd SaveData
	if err := yaml.Unmarshal([]byte(yamlPart), &sd); err != nil {
		return nil, fmt.Errorf("invalid YAML header: %w", err)
	}

	m := NewMap(sd.Name, sd.Width, sd.Height, sd.Palette)
	m.Filename = path

	// Restore colors
	for _, entry := range sd.GridColors {
		var x, y int
		var c string
		if n, _ := fmt.Sscanf(entry, "%d,%d,%s", &x, &y, &c); n == 3 {
			if y >= 0 && y < m.Height && x >= 0 && x < m.Width {
				m.Grid[y][x].Color = c
			}
		}
	}

	lines := strings.Split(strings.TrimRight(gridPart, "\n"), "\n")
	for y, line := range lines {
		if y >= m.Height {
			break
		}
		for x, ch := range line {
			if x >= m.Width {
				break
			}
			for i, t := range m.Palette {
				if string(ch) == t.ASCII {
					m.Grid[y][x].Terrain = i
					break
				}
			}
		}
	}

	for _, tl := range sd.TextLabels {
		PlaceTextLabel(m, tl.Start, tl.Text, tl.Color)
	}

	for _, sr := range sd.Submaps {
		sub := restoreMap(&sr.Data, m)
		m.Submaps[Point{sr.X, sr.Y}] = sub
	}

	return m, nil
}

func restoreMap(sd *SaveData, parent *Map) *Map {
	m := NewMap(sd.Name, sd.Width, sd.Height, sd.Palette)
	m.Parent = parent
	// Restore colors
	for _, entry := range sd.GridColors {
		var x, y int
		var c string
		if n, _ := fmt.Sscanf(entry, "%d,%d,%s", &x, &y, &c); n == 3 {
			if y >= 0 && y < m.Height && x >= 0 && x < m.Width {
				m.Grid[y][x].Color = c
			}
		}
	}
	// Restore grid from GridBody
	if sd.GridBody != "" {
		lines := strings.Split(strings.TrimRight(sd.GridBody, "\n"), "\n")
		for y, line := range lines {
			if y >= m.Height {
				break
			}
			for x, ch := range line {
				if x >= m.Width {
					break
				}
				for i, t := range m.Palette {
					if string(ch) == t.ASCII {
						m.Grid[y][x].Terrain = i
						break
					}
				}
			}
		}
	}
	for _, tl := range sd.TextLabels {
		PlaceTextLabel(m, tl.Start, tl.Text, tl.Color)
	}
	for _, sr := range sd.Submaps {
		sub := restoreMap(&sr.Data, m)
		m.Submaps[Point{sr.X, sr.Y}] = sub
	}
	return m
}