bytepusher.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. /*
  2. * An implementation of the BytePusher VM.
  3. *
  4. * For example programs and more information about BytePusher, see
  5. * https://esolangs.org/wiki/BytePusher
  6. *
  7. * This code is public domain. Feel free to use it for any purpose!
  8. */
  9. #define SDL_MAIN_USE_CALLBACKS
  10. #include <SDL3/SDL.h>
  11. #include <SDL3/SDL_main.h>
  12. #include <stdarg.h>
  13. #define SCREEN_W 256
  14. #define SCREEN_H 256
  15. #define RAM_SIZE 0x1000000
  16. #define FRAMES_PER_SECOND 60
  17. #define SAMPLES_PER_FRAME 256
  18. #define NS_PER_SECOND (Uint64)SDL_NS_PER_SECOND
  19. #define MAX_AUDIO_LATENCY_FRAMES 5
  20. #define IO_KEYBOARD 0
  21. #define IO_PC 2
  22. #define IO_SCREEN_PAGE 5
  23. #define IO_AUDIO_BANK 6
  24. typedef struct {
  25. Uint8 ram[RAM_SIZE + 8];
  26. Uint64 last_tick;
  27. Uint64 tick_acc;
  28. SDL_Window* window;
  29. SDL_Renderer* renderer;
  30. SDL_Palette* palette;
  31. SDL_Texture* texture;
  32. SDL_Texture* rendertarget; /* we need this render target for text to look good */
  33. SDL_AudioStream* audiostream;
  34. char status[SCREEN_W / 8];
  35. int status_ticks;
  36. Uint16 keystate;
  37. bool display_help;
  38. bool positional_input;
  39. } BytePusher;
  40. static const struct {
  41. const char *key;
  42. const char *value;
  43. } extended_metadata[] = {
  44. { SDL_PROP_APP_METADATA_URL_STRING, "https://examples.libsdl.org/SDL3/demo/04-bytepusher/" },
  45. { SDL_PROP_APP_METADATA_CREATOR_STRING, "SDL team" },
  46. { SDL_PROP_APP_METADATA_COPYRIGHT_STRING, "Placed in the public domain" },
  47. { SDL_PROP_APP_METADATA_TYPE_STRING, "game" }
  48. };
  49. static inline Uint16 read_u16(const BytePusher* vm, Uint32 addr) {
  50. const Uint8* ptr = &vm->ram[addr];
  51. return ((Uint16)ptr[0] << 8) | ((Uint16)ptr[1]);
  52. }
  53. static inline Uint32 read_u24(const BytePusher* vm, Uint32 addr) {
  54. const Uint8* ptr = &vm->ram[addr];
  55. return ((Uint32)ptr[0] << 16) | ((Uint32)ptr[1] << 8) | ((Uint32)ptr[2]);
  56. }
  57. static void set_status(BytePusher* vm, const char* fmt, ...) {
  58. va_list args;
  59. va_start(args, fmt);
  60. SDL_vsnprintf(vm->status, sizeof(vm->status), fmt, args);
  61. va_end(args);
  62. vm->status[sizeof(vm->status) - 1] = 0;
  63. vm->status_ticks = FRAMES_PER_SECOND * 3;
  64. }
  65. static bool load(BytePusher* vm, SDL_IOStream* stream, bool closeio) {
  66. size_t bytes_read = 0;
  67. bool ok = true;
  68. SDL_memset(vm->ram, 0, RAM_SIZE);
  69. if (!stream) {
  70. return false;
  71. }
  72. while (bytes_read < RAM_SIZE) {
  73. size_t read = SDL_ReadIO(stream, &vm->ram[bytes_read], RAM_SIZE - bytes_read);
  74. bytes_read += read;
  75. if (read == 0) {
  76. ok = SDL_GetIOStatus(stream) == SDL_IO_STATUS_EOF;
  77. break;
  78. }
  79. }
  80. if (closeio) {
  81. SDL_CloseIO(stream);
  82. }
  83. SDL_ClearAudioStream(vm->audiostream);
  84. vm->display_help = !ok;
  85. return ok;
  86. }
  87. static const char* filename(const char* path) {
  88. size_t i = SDL_strlen(path) + 1;
  89. while (i > 0) {
  90. i -= 1;
  91. if (path[i] == '/' || path[i] == '\\') {
  92. return path + i + 1;
  93. }
  94. }
  95. return path;
  96. }
  97. static bool load_file(BytePusher* vm, const char* path) {
  98. if (load(vm, SDL_IOFromFile(path, "rb"), true)) {
  99. set_status(vm, "loaded %s", filename(path));
  100. return true;
  101. } else {
  102. set_status(vm, "load failed: %s", filename(path));
  103. return false;
  104. }
  105. }
  106. static void print(BytePusher* vm, int x, int y, const char* str) {
  107. SDL_SetRenderDrawColor(vm->renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
  108. SDL_RenderDebugText(vm->renderer, (float)(x + 1), (float)(y + 1), str);
  109. SDL_SetRenderDrawColor(vm->renderer, 0xff, 0xff, 0xff, SDL_ALPHA_OPAQUE);
  110. SDL_RenderDebugText(vm->renderer, (float)x, (float)y, str);
  111. SDL_SetRenderDrawColor(vm->renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
  112. }
  113. SDL_AppResult SDL_AppInit(void** appstate, int argc, char* argv[]) {
  114. BytePusher* vm;
  115. SDL_Rect usable_bounds;
  116. SDL_AudioSpec audiospec = { SDL_AUDIO_S8, 1, SAMPLES_PER_FRAME * FRAMES_PER_SECOND };
  117. SDL_DisplayID primary_display;
  118. int zoom = 2;
  119. int i;
  120. Uint8 r, g, b;
  121. if (!SDL_SetAppMetadata("SDL 3 BytePusher", "1.0", "com.example.SDL3BytePusher")) {
  122. return SDL_APP_FAILURE;
  123. }
  124. for (i = 0; i < (int)SDL_arraysize(extended_metadata); i++) {
  125. if (!SDL_SetAppMetadataProperty(extended_metadata[i].key, extended_metadata[i].value)) {
  126. return SDL_APP_FAILURE;
  127. }
  128. }
  129. if (!SDL_Init(SDL_INIT_AUDIO | SDL_INIT_VIDEO)) {
  130. return SDL_APP_FAILURE;
  131. }
  132. if (!(vm = (BytePusher *)SDL_calloc(1, sizeof(*vm)))) {
  133. return SDL_APP_FAILURE;
  134. }
  135. *(BytePusher**)appstate = vm;
  136. vm->display_help = true;
  137. primary_display = SDL_GetPrimaryDisplay();
  138. if (SDL_GetDisplayUsableBounds(primary_display, &usable_bounds)) {
  139. int zoom_w = (usable_bounds.w - usable_bounds.x) * 2 / 3 / SCREEN_W;
  140. int zoom_h = (usable_bounds.h - usable_bounds.y) * 2 / 3 / SCREEN_H;
  141. zoom = zoom_w < zoom_h ? zoom_w : zoom_h;
  142. if (zoom < 1) {
  143. zoom = 1;
  144. }
  145. }
  146. if (!SDL_CreateWindowAndRenderer("SDL 3 BytePusher",
  147. SCREEN_W * zoom, SCREEN_H * zoom, SDL_WINDOW_RESIZABLE,
  148. &vm->window, &vm->renderer
  149. )) {
  150. return SDL_APP_FAILURE;
  151. }
  152. if (!SDL_SetRenderLogicalPresentation(
  153. vm->renderer, SCREEN_W, SCREEN_H, SDL_LOGICAL_PRESENTATION_INTEGER_SCALE
  154. )) {
  155. return SDL_APP_FAILURE;
  156. }
  157. if (!(vm->palette = SDL_CreatePalette(256))) {
  158. return SDL_APP_FAILURE;
  159. }
  160. i = 0;
  161. for (r = 0; r < 6; ++r) {
  162. for (g = 0; g < 6; ++g) {
  163. for (b = 0; b < 6; ++b, ++i) {
  164. SDL_Color color = { (Uint8)(r * 0x33), (Uint8)(g * 0x33), (Uint8)(b * 0x33), SDL_ALPHA_OPAQUE };
  165. vm->palette->colors[i] = color;
  166. }
  167. }
  168. }
  169. for (; i < 256; ++i) {
  170. SDL_Color color = { 0, 0, 0, SDL_ALPHA_OPAQUE };
  171. vm->palette->colors[i] = color;
  172. }
  173. vm->texture = SDL_CreateTexture(vm->renderer, SDL_PIXELFORMAT_INDEX8, SDL_TEXTUREACCESS_STREAMING, SCREEN_W, SCREEN_H);
  174. vm->rendertarget = SDL_CreateTexture(vm->renderer, SDL_PIXELFORMAT_UNKNOWN, SDL_TEXTUREACCESS_TARGET, SCREEN_W, SCREEN_H);
  175. if (!vm->texture || !vm->rendertarget) {
  176. return SDL_APP_FAILURE;
  177. }
  178. SDL_SetTexturePalette(vm->texture, vm->palette);
  179. SDL_SetTextureScaleMode(vm->texture, SDL_SCALEMODE_NEAREST);
  180. SDL_SetTextureScaleMode(vm->rendertarget, SDL_SCALEMODE_NEAREST);
  181. if (!(vm->audiostream = SDL_OpenAudioDeviceStream(
  182. SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &audiospec, NULL, NULL
  183. ))) {
  184. return SDL_APP_FAILURE;
  185. }
  186. SDL_SetAudioStreamGain(vm->audiostream, 0.1f); /* examples are loud! */
  187. SDL_ResumeAudioStreamDevice(vm->audiostream);
  188. set_status(vm, "renderer: %s", SDL_GetRendererName(vm->renderer));
  189. vm->last_tick = SDL_GetTicksNS();
  190. vm->tick_acc = NS_PER_SECOND;
  191. if (argc > 1) {
  192. load_file(vm, argv[1]);
  193. }
  194. return SDL_APP_CONTINUE;
  195. }
  196. SDL_AppResult SDL_AppIterate(void* appstate) {
  197. BytePusher* vm = (BytePusher*)appstate;
  198. Uint64 tick = SDL_GetTicksNS();
  199. Uint64 delta = tick - vm->last_tick;
  200. bool updated, skip_audio;
  201. vm->last_tick = tick;
  202. vm->tick_acc += delta * FRAMES_PER_SECOND;
  203. updated = vm->tick_acc >= NS_PER_SECOND;
  204. skip_audio = vm->tick_acc >= MAX_AUDIO_LATENCY_FRAMES * NS_PER_SECOND;
  205. if (skip_audio) {
  206. // don't let audio fall too far behind
  207. SDL_ClearAudioStream(vm->audiostream);
  208. }
  209. while (vm->tick_acc >= NS_PER_SECOND) {
  210. Uint32 pc;
  211. int i;
  212. vm->tick_acc -= NS_PER_SECOND;
  213. vm->ram[IO_KEYBOARD] = (Uint8)(vm->keystate >> 8);
  214. vm->ram[IO_KEYBOARD + 1] = (Uint8)(vm->keystate);
  215. pc = read_u24(vm, IO_PC);
  216. for (i = 0; i < SCREEN_W * SCREEN_H; ++i) {
  217. Uint32 src = read_u24(vm, pc);
  218. Uint32 dst = read_u24(vm, pc + 3);
  219. vm->ram[dst] = vm->ram[src];
  220. pc = read_u24(vm, pc + 6);
  221. }
  222. if (!skip_audio || vm->tick_acc < NS_PER_SECOND) {
  223. SDL_PutAudioStreamData(
  224. vm->audiostream,
  225. &vm->ram[(Uint32)read_u16(vm, IO_AUDIO_BANK) << 8],
  226. SAMPLES_PER_FRAME
  227. );
  228. }
  229. }
  230. if (updated) {
  231. const void *pixels = &vm->ram[(Uint32)vm->ram[IO_SCREEN_PAGE] << 16];
  232. SDL_UpdateTexture(vm->texture, NULL, pixels, SCREEN_W);
  233. SDL_SetRenderTarget(vm->renderer, vm->rendertarget);
  234. SDL_RenderTexture(vm->renderer, vm->texture, NULL, NULL);
  235. if (vm->display_help) {
  236. print(vm, 4, 4, "Drop a BytePusher file in this");
  237. print(vm, 8, 12, "window to load and run it!");
  238. print(vm, 4, 28, "Press ENTER to switch between");
  239. print(vm, 8, 36, "positional and symbolic input.");
  240. }
  241. if (vm->status_ticks > 0) {
  242. vm->status_ticks -= 1;
  243. print(vm, 4, SCREEN_H - 12, vm->status);
  244. }
  245. }
  246. SDL_SetRenderTarget(vm->renderer, NULL);
  247. SDL_RenderClear(vm->renderer);
  248. SDL_RenderTexture(vm->renderer, vm->rendertarget, NULL, NULL);
  249. SDL_RenderPresent(vm->renderer);
  250. return SDL_APP_CONTINUE;
  251. }
  252. static Uint16 keycode_mask(SDL_Keycode key) {
  253. int index;
  254. if (key >= SDLK_0 && key <= SDLK_9) {
  255. index = key - SDLK_0;
  256. } else if (key >= SDLK_A && key <= SDLK_F) {
  257. index = key - SDLK_A + 10;
  258. } else {
  259. return 0;
  260. }
  261. return (Uint16)1 << index;
  262. }
  263. static Uint16 scancode_mask(SDL_Scancode scancode) {
  264. int index;
  265. switch (scancode) {
  266. case SDL_SCANCODE_1: index = 0x1; break;
  267. case SDL_SCANCODE_2: index = 0x2; break;
  268. case SDL_SCANCODE_3: index = 0x3; break;
  269. case SDL_SCANCODE_4: index = 0xc; break;
  270. case SDL_SCANCODE_Q: index = 0x4; break;
  271. case SDL_SCANCODE_W: index = 0x5; break;
  272. case SDL_SCANCODE_E: index = 0x6; break;
  273. case SDL_SCANCODE_R: index = 0xd; break;
  274. case SDL_SCANCODE_A: index = 0x7; break;
  275. case SDL_SCANCODE_S: index = 0x8; break;
  276. case SDL_SCANCODE_D: index = 0x9; break;
  277. case SDL_SCANCODE_F: index = 0xe; break;
  278. case SDL_SCANCODE_Z: index = 0xa; break;
  279. case SDL_SCANCODE_X: index = 0x0; break;
  280. case SDL_SCANCODE_C: index = 0xb; break;
  281. case SDL_SCANCODE_V: index = 0xf; break;
  282. default: return 0;
  283. }
  284. return (Uint16)1 << index;
  285. }
  286. SDL_AppResult SDL_AppEvent(void* appstate, SDL_Event* event) {
  287. BytePusher* vm = (BytePusher*)appstate;
  288. switch (event->type) {
  289. case SDL_EVENT_QUIT:
  290. return SDL_APP_SUCCESS;
  291. case SDL_EVENT_DROP_FILE:
  292. load_file(vm, event->drop.data);
  293. break;
  294. case SDL_EVENT_KEY_DOWN:
  295. #ifndef __EMSCRIPTEN__
  296. if (event->key.key == SDLK_ESCAPE) {
  297. return SDL_APP_SUCCESS;
  298. }
  299. #endif
  300. if (event->key.key == SDLK_RETURN) {
  301. vm->positional_input = !vm->positional_input;
  302. vm->keystate = 0;
  303. if (vm->positional_input) {
  304. set_status(vm, "switched to positional input");
  305. } else {
  306. set_status(vm, "switched to symbolic input");
  307. }
  308. }
  309. if (vm->positional_input) {
  310. vm->keystate |= scancode_mask(event->key.scancode);
  311. } else {
  312. vm->keystate |= keycode_mask(event->key.key);
  313. }
  314. break;
  315. case SDL_EVENT_KEY_UP:
  316. if (vm->positional_input) {
  317. vm->keystate &= ~scancode_mask(event->key.scancode);
  318. } else {
  319. vm->keystate &= ~keycode_mask(event->key.key);
  320. }
  321. break;
  322. }
  323. return SDL_APP_CONTINUE;
  324. }
  325. void SDL_AppQuit(void* appstate, SDL_AppResult result) {
  326. if (result == SDL_APP_FAILURE) {
  327. SDL_Log("Error: %s", SDL_GetError());
  328. }
  329. if (appstate) {
  330. BytePusher* vm = (BytePusher*)appstate;
  331. SDL_DestroyAudioStream(vm->audiostream);
  332. SDL_DestroyTexture(vm->rendertarget);
  333. SDL_DestroyTexture(vm->texture);
  334. SDL_DestroyPalette(vm->palette);
  335. SDL_DestroyRenderer(vm->renderer);
  336. SDL_DestroyWindow(vm->window);
  337. SDL_free(vm);
  338. }
  339. }