aboutsummaryrefslogtreecommitdiff
path: root/src/cart.c
blob: f639aec0ac22d373b81de39f30dd122d4dbf8934 (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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
#include <SDL3/SDL_filesystem.h>
#include <SDL3/SDL_log.h>

#include "cart.h"
#include "path.h"
#include "png.h"
#include "sysroot.h"

static bool cart_file_path(struct pw_cart_file *file, char const *dir,
                           char const *filename, char const *ext) {
  if (!pw_pathjoin(file->path, PW_CART_PATH_MAX, dir, filename, NULL) ||
      !pw_stripext(file->name, PW_CART_NAME_MAX, filename, ext)) {
    SDL_SetError("invalid cart file name %s", filename);
    return false;
  }

  return true;
}

static int cmp_cart_file(void const *a, void const *b) {
  struct pw_cart_file const *fa = a;
  struct pw_cart_file const *fb = b;
  return SDL_strcmp(fa->name, fb->name);
}

struct pw_carts *pw_carts_list(char const *dir) {
  struct pw_carts *carts = NULL;
  char **cartfiles = NULL;

  SDL_PathInfo pinfo;
  if (!SDL_GetPathInfo(dir, &pinfo) || pinfo.type != SDL_PATHTYPE_DIRECTORY) {
    carts = SDL_malloc(sizeof(struct pw_carts));
    if (!carts) {
      goto error;
    }

    // Set an SDL error while returning an empty carts list. This allows a
    // caller to disambiguate between empty and missing directories.
    SDL_SetError("missing carts directory");
    carts->count = 0;
    return carts;
  }

  int icount;
  cartfiles =
      SDL_GlobDirectory(dir, "*.p8.png", SDL_GLOB_CASEINSENSITIVE, &icount);
  if (!cartfiles || icount < 0) {
    goto error;
  }

  size_t count = (size_t)icount;
  if (count > SIZE_MAX / sizeof(struct pw_cart_file)) {
    goto error;
  }

  carts = SDL_malloc(sizeof(*carts) + count * sizeof(*carts->files));
  if (!carts) {
    goto error;
  }
  carts->count = 0;

  for (size_t i = 0; i < count; i++) {
    struct pw_cart_file *file = &carts->files[i];
    if (!cart_file_path(file, dir, cartfiles[i], ".png")) {
      goto error;
    }
  }

  carts->count = count;
  SDL_qsort(carts->files, carts->count, sizeof(*carts->files), cmp_cart_file);

  SDL_free(cartfiles);
  return carts;

error:
  if (carts) {
    pw_carts_free(carts);
  }
  if (cartfiles) {
    SDL_free(cartfiles);
  }
  return NULL;
}

void pw_carts_free(struct pw_carts *carts) {
  if (!carts) {
    SDL_InvalidParamError("carts");
    return;
  }

  SDL_free(carts);
}

static bool blit_image(union pw_png_pixel const *image, SDL_Texture *texture) {
  SDL_Surface *surface = NULL;
  if (!SDL_LockTextureToSurface(texture, NULL, &surface)) {
    return false;
  }

  // Make sure that the surface dimensions match our expectations, and that
  // the surface pixels buffer properly aligned.
  if (surface->w != PW_CART_PNG_WIDTH || surface->h != PW_CART_PNG_HEIGHT ||
      surface->format != SDL_PIXELFORMAT_RGBA32) {
    SDL_UnlockTexture(texture);
    SDL_SetError("invalid cart PNG surface");
    return false;
  }

  // Copy over the raw image data to the surface, while clearing the
  // steganographic encoding of the cart data.
  for (size_t y = 0; y < PW_CART_PNG_HEIGHT; y++) {
    union pw_png_pixel const *row = image + y * PW_CART_PNG_WIDTH;
    uint8_t *pixels = (uint8_t *)surface->pixels + y * surface->pitch;

    for (size_t x = 0; x < PW_CART_PNG_WIDTH; x++) {
      union pw_png_pixel px = row[x];
      px.raw &= 0xfcfcfcfc;
      px.ch.a |= 0x03;
      SDL_memcpy(pixels + x * sizeof(px), &px, sizeof(px));
    }
  }

  SDL_UnlockTexture(texture);
  return true;
}

struct pw_cart_png *pw_cart_png_init(SDL_Renderer *renderer) {
  struct pw_cart_png *png = SDL_malloc(sizeof(struct pw_cart_png));
  if (!png) {
    return NULL;
  }

  png->texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA32,
                                   SDL_TEXTUREACCESS_STREAMING,
                                   PW_CART_PNG_WIDTH, PW_CART_PNG_HEIGHT);
  if (!png->texture) {
    goto error;
  }
  if (!SDL_SetTextureScaleMode(png->texture, SDL_SCALEMODE_NEAREST)) {
    goto error;
  }

  union pw_png_pixel *image = pw_png_load(
      pw_sysroot_unknown_p8_png.data, pw_sysroot_unknown_p8_png.size,
      PW_CART_PNG_WIDTH, PW_CART_PNG_HEIGHT);
  if (!image) {
    goto error;
  }

  bool ok = blit_image(image, png->texture);
  SDL_free(image);
  if (!ok) {
    goto error;
  }

  SDL_zeroa(png->rom);
  return png;

error:
  pw_cart_png_free(png);
  return NULL;
}

void pw_cart_png_free(struct pw_cart_png *png) {
  if (!png) {
    SDL_InvalidParamError("png");
    return;
  }

  if (png->texture) {
    SDL_DestroyTexture(png->texture);
  }
  SDL_free(png);
}

static bool decode_cart_png(uint8_t const *data, size_t size,
                            SDL_Texture *texture,
                            uint8_t rom[PW_CART_ROM_SIZE]) {
  bool result = false;
  union pw_png_pixel *image = NULL;

  image = pw_png_load(data, size, PW_CART_PNG_WIDTH, PW_CART_PNG_HEIGHT);
  if (!image) {
    goto cleanup;
  }

  if (texture && !blit_image(image, texture)) {
    goto cleanup;
  }

  // Read steganographically encoded cart ROM.
  for (size_t i = 0; i < PW_CART_ROM_SIZE; i++) {
    union pw_png_pixel px = image[i];
    px.raw &= 0x03030303;
    rom[i] = (px.ch.a << 6) | (px.ch.r << 4) | (px.ch.g << 2) | px.ch.b;
  }

  result = true;

cleanup:
  if (image) {
    SDL_free(image);
  }
  return result;
}

static bool load_cart_png(char const *path, SDL_Texture *texture,
                          uint8_t rom[PW_CART_ROM_SIZE]) {

  SDL_IOStream *png = SDL_IOFromFile(path, "rb");
  if (!png) {
    return false;
  }

  bool result = false;
  uint8_t *data = NULL;

  int64_t ssize = SDL_GetIOSize(png);
  if (ssize < 0) {
    goto cleanup;
  }
  if (ssize > 1024 * 1024) {
    SDL_SetError("cart PNG is too large");
    goto cleanup;
  }

  size_t size = (size_t)ssize;
  data = SDL_malloc(size);
  if (!data) {
    goto cleanup;
  }

  size_t n = SDL_ReadIO(png, data, size);
  if (n != size) {
    goto cleanup;
  }

  result = decode_cart_png(data, size, texture, rom);

cleanup:
  if (data) {
    SDL_free(data);
  }
  result &= SDL_CloseIO(png);
  return result;
}

bool pw_cart_png_load(struct pw_cart_file *file, struct pw_cart_png *png) {
  if (!file) {
    SDL_InvalidParamError("file");
    return false;
  }
  if (!png) {
    SDL_InvalidParamError("png");
    return false;
  }

  return load_cart_png(file->path, png->texture, png->rom);
}

static struct pw_fs_node_buffer *embedded_cart(struct pw_fs_entry *e,
                                               char const **filename) {
  static char const cart_dir[] = "user_data/carts/";
  if (e->node.type != PW_FS_NODE_BUFFER ||
      SDL_strstr(e->path, cart_dir) != e->path ||
      !pw_hasext(e->path, ".p8.png")) {
    return NULL;
  }

  if (filename) {
    *filename = e->path + sizeof(cart_dir) - 1;
  }
  return &e->node.w;
}

struct pw_cart *pw_cart_load(struct pw_cart_file *file,
                             struct pw_cart_png *png) {
  if (!file) {
    SDL_InvalidParamError("file");
    return NULL;
  }

  struct pw_fs *storage = NULL;
  struct pw_cart *cart = NULL;

  // We are _guaranteed_ that `len < PW_PATH_MAX` by construction, and that
  // it has a `.p8.png` suffix. This allows us to easily add the `.p8.tar`
  // suffix for the user-data mount.
  char storage_path[PW_CART_PATH_MAX];
  size_t len = SDL_strlcpy(storage_path, file->path, PW_CART_PATH_MAX);
  SDL_memcpy(storage_path + len - 3, "tar", 4);
  storage = pw_fs_init(storage_path);
  if (!storage) {
    goto error;
  }

  // While `LOAD("CART.P8")` works with the filesystem, `RELOAD("CART.P8")`
  // only works for embedded carts. In order to support all cases, we read
  // through our storage and add any valid
  size_t max_count = 1;
  for (size_t i = 0;
       i < storage->root.count && max_count < PW_CART_EMBEDDED_MAX; ++i) {
    struct pw_fs_entry *e = storage->root.entries[i];
    if (!embedded_cart(e, NULL)) {
      continue;
    }
    ++max_count;
  }
  cart = SDL_calloc(1, sizeof(*cart) + max_count * sizeof(*cart->embedded));
  if (!cart) {
    goto error;
  }

  SDL_strlcpy(cart->embedded->name, file->name, PW_CART_NAME_MAX);
  if (png) {
    SDL_memcpy(cart->embedded->rom, png->rom, PW_CART_ROM_SIZE);
  } else if (!load_cart_png(file->path, NULL, cart->embedded->rom)) {
    goto error;
  }

  size_t count = 1;
  for (size_t i = 0; i < storage->root.count; ++i) {
    struct pw_fs_entry *e = storage->root.entries[i];

    char const *fn;
    struct pw_fs_node_buffer *b = embedded_cart(e, &fn);
    if (!b) {
      continue;
    }

    if (count >= max_count) {
      SDL_LogWarn(0, "ignoring cart past embedding limit: %s", fn);
      continue;
    }

    struct pw_cart_data *d = cart->embedded + count;
    if (!pw_stripext(d->name, PW_CART_NAME_MAX, fn, ".png") ||
        !decode_cart_png(b->data, b->size, NULL, d->rom)) {
      SDL_LogWarn(0, "malformed embedded cart %s", e->path);
      continue;
    }

    SDL_LogDebug(0, "embedding cart %s", d->name);
    ++count;
  }

  cart->count = count;
  cart->storage = storage;
  return cart;

error:
  if (storage) {
    pw_fs_free(storage);
  }
  if (cart) {
    SDL_free(cart);
  }
  return NULL;
}

void pw_cart_free(struct pw_cart *cart) {
  if (!cart) {
    SDL_InvalidParamError("cart");
    return;
  }

  pw_fs_free(cart->storage);
  SDL_free(cart);
}