summaryrefslogtreecommitdiff
path: root/src/main/c
diff options
context:
space:
mode:
Diffstat (limited to 'src/main/c')
-rw-r--r--src/main/c/simple_audio.c40
-rw-r--r--src/main/c/simple_audio.h16
-rw-r--r--src/main/c/simple_graphics.c102
-rw-r--r--src/main/c/simple_graphics.h20
-rw-r--r--src/main/c/simple_miniaudio.c123
-rw-r--r--src/main/c/simple_minifb.c117
-rw-r--r--src/main/c/simple_time.c61
7 files changed, 479 insertions, 0 deletions
diff --git a/src/main/c/simple_audio.c b/src/main/c/simple_audio.c
new file mode 100644
index 00000000..b8ed62de
--- /dev/null
+++ b/src/main/c/simple_audio.c
@@ -0,0 +1,40 @@
+#include "simple_audio.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <dlfcn.h>
+
+static const struct simple_audio_api *api;
+static void *library;
+
+int32_t simple_audio_open(void) {
+ const char *path = getenv("SIMPLE_MINIAUDIO");
+ if (path && strcmp(path,"off")==0) return -1;
+ if (!api) {
+ if (!path || !*path) return -1; // Optional: games may run silently.
+ library = dlopen(path,RTLD_NOW | RTLD_LOCAL);
+ if (!library) {
+ fprintf(stderr,"Simple audio: cannot load backend '%s': %s\n",path,dlerror());
+ return -1;
+ }
+ const struct simple_audio_api *(*get_api)(void) =
+ (const struct simple_audio_api *(*)(void))dlsym(library,"simple_miniaudio_api");
+ const struct simple_audio_api *candidate = get_api ? get_api() : NULL;
+ if (!candidate || candidate->version!=SIMPLE_AUDIO_VERSION || !candidate->open ||
+ !candidate->load || !candidate->play || !candidate->stop ||
+ !candidate->playing || !candidate->close) {
+ fprintf(stderr,"Simple audio: incompatible backend; rebuild with make audio.\n");
+ dlclose(library);
+ library=NULL;
+ return -1;
+ }
+ api=candidate;
+ atexit(api->close);
+ }
+ return api->open();
+}
+int32_t simple_audio_load(const int16_t *samples, uint32_t count) { return api ? api->load(samples,count) : -1; }
+int32_t simple_audio_play(int32_t sound) { return api ? api->play(sound) : -1; }
+int32_t simple_audio_stop(void) { return api ? api->stop() : 0; }
+int32_t simple_audio_playing(void) { return api ? api->playing() : 0; }
+int32_t simple_audio_close(void) { if (api) api->close(); return 0; }
diff --git a/src/main/c/simple_audio.h b/src/main/c/simple_audio.h
new file mode 100644
index 00000000..77cce530
--- /dev/null
+++ b/src/main/c/simple_audio.h
@@ -0,0 +1,16 @@
+#ifndef SIMPLE_AUDIO_H
+#define SIMPLE_AUDIO_H
+#include <stdint.h>
+
+// Main-thread API. Samples are copied; no Simple heap pointer is retained.
+struct simple_audio_api {
+ int32_t version;
+ int32_t (*open)(void);
+ int32_t (*load)(const int16_t *, uint32_t);
+ int32_t (*play)(int32_t);
+ int32_t (*stop)(void);
+ int32_t (*playing)(void);
+ void (*close)(void);
+};
+#define SIMPLE_AUDIO_VERSION 1
+#endif
diff --git a/src/main/c/simple_graphics.c b/src/main/c/simple_graphics.c
new file mode 100644
index 00000000..40d66ba9
--- /dev/null
+++ b/src/main/c/simple_graphics.c
@@ -0,0 +1,102 @@
+#define _POSIX_C_SOURCE 200809L
+#include "simple_graphics.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <dlfcn.h>
+#include <unistd.h>
+
+#ifdef __CYGWIN__
+#define BACKEND_NAME "simple_minifb.dll"
+#define BACKEND_ABI "x86_64_v2_win64"
+#else
+#define BACKEND_NAME "libsimple_minifb.so"
+#define BACKEND_ABI "x86_64_v2_SystemV"
+#endif
+
+// Executable-relative paths work even when launched outside the checkout.
+// Working-directory paths also cover test executables and chapter/root shells.
+static void *find_backend(void) {
+ char executable[4096], path[8192];
+ ssize_t n=readlink("/proc/self/exe",executable,sizeof(executable)-1);
+ if (n>0 && n<(ssize_t)sizeof(executable)-1) {
+ executable[n]=0;
+ char *slash=strrchr(executable,'/');
+ if (slash) {
+ *slash=0;
+ const char *relative[]={"/" BACKEND_NAME,
+ "/../../release/" BACKEND_ABI "/" BACKEND_NAME,
+ "/../release/" BACKEND_ABI "/" BACKEND_NAME};
+ for (unsigned i=0;i<sizeof(relative)/sizeof(*relative);++i) {
+ snprintf(path,sizeof(path),"%s%s",executable,relative[i]);
+ void *handle=dlopen(path,RTLD_NOW | RTLD_LOCAL);
+ if (handle) return handle;
+ }
+ }
+ }
+ const char *relative[]={"./" BACKEND_NAME,
+ "./build/release/" BACKEND_ABI "/" BACKEND_NAME,
+ "./chapter31/build/release/" BACKEND_ABI "/" BACKEND_NAME};
+ for (unsigned i=0;i<sizeof(relative)/sizeof(*relative);++i) {
+ void *handle=dlopen(relative[i],RTLD_NOW | RTLD_LOCAL);
+ if (handle) return handle;
+ }
+ return NULL;
+}
+
+// No MiniFB headers or link dependency in the default runtime. Cygwin's
+// dlopen also loads native Windows DLLs; both use the x64 Windows C ABI.
+static const struct simple_graphics_api *api;
+static void *library;
+
+static int load_graphics(void) {
+ // Explicitly disabling graphics also makes headless tests deterministic.
+ const char *path = getenv("SIMPLE_MINIFB");
+ if (path && strcmp(path, "off") == 0) {
+ fprintf(stderr, "Simple graphics: disabled (SIMPLE_MINIFB=off).\n");
+ return -1;
+ }
+ if (api) return 0;
+ int explicit_path=path && *path;
+ library = explicit_path ? dlopen(path, RTLD_NOW | RTLD_LOCAL) : find_backend();
+ if (!library) {
+ if (explicit_path)
+ fprintf(stderr, "Simple graphics: cannot load MiniFB backend '%s': %s\n", path, dlerror());
+ else
+ fprintf(stderr, "Simple graphics: MiniFB backend not found beside the executable or in build/release/"
+ BACKEND_ABI ". Run make graphics, or set SIMPLE_MINIFB to its full path.\n");
+ return -1;
+ }
+ if (!explicit_path) path="automatically discovered backend";
+ const struct simple_graphics_api *(*get_api)(void) =
+ (const struct simple_graphics_api *(*)(void))dlsym(library, "simple_minifb_api");
+ const struct simple_graphics_api *candidate = get_api ? get_api() : NULL;
+ if (!candidate || candidate->version != SIMPLE_GRAPHICS_VERSION ||
+ !candidate->open || !candidate->present || !candidate->poll ||
+ !candidate->mouse_x || !candidate->mouse_y || !candidate->button ||
+ !candidate->key || !candidate->close || !candidate->wait) {
+ fprintf(stderr, "Simple graphics: incompatible MiniFB backend '%s'. Rebuild with make graphics.\n", path);
+ dlclose(library);
+ library = NULL;
+ return -1;
+ }
+ api = candidate;
+ // Keep the library loaded until process exit; its window callbacks may
+ // still be registered. Closing a window releases its native resources.
+ atexit(api->close);
+ return 0;
+}
+
+int32_t simple_gfx_open(const char *title, uint32_t width, uint32_t height) {
+ return load_graphics() ? -1 : api->open(title, width, height);
+}
+int32_t simple_gfx_present(const uint32_t *pixels, uint32_t count) {
+ return api ? api->present(pixels, count) : -1;
+}
+int32_t simple_gfx_poll(int32_t wait) { return api ? api->poll(wait) : -1; }
+int32_t simple_gfx_mouse_x(void) { return api ? api->mouse_x() : 0; }
+int32_t simple_gfx_mouse_y(void) { return api ? api->mouse_y() : 0; }
+int32_t simple_gfx_button(int32_t button) { return api ? api->button(button) : 0; }
+int32_t simple_gfx_key(int32_t key) { return api ? api->key(key) : 0; }
+int32_t simple_gfx_close(void) { if (api) api->close(); return 0; }
+int32_t simple_gfx_wait(int64_t timeout) { return api ? api->wait(timeout) : -1; }
diff --git a/src/main/c/simple_graphics.h b/src/main/c/simple_graphics.h
new file mode 100644
index 00000000..370256be
--- /dev/null
+++ b/src/main/c/simple_graphics.h
@@ -0,0 +1,20 @@
+#ifndef SIMPLE_GRAPHICS_H
+#define SIMPLE_GRAPHICS_H
+#include <stdint.h>
+
+// Private, versioned boundary between the tiny runtime loader and MiniFB.
+// All calls run on the main thread. Pixel memory is borrowed for present only.
+struct simple_graphics_api {
+ int32_t version;
+ int32_t (*open)(const char *, uint32_t, uint32_t);
+ int32_t (*present)(const uint32_t *, uint32_t);
+ int32_t (*poll)(int32_t);
+ int32_t (*mouse_x)(void);
+ int32_t (*mouse_y)(void);
+ int32_t (*button)(int32_t);
+ int32_t (*key)(int32_t);
+ void (*close)(void);
+ int32_t (*wait)(int64_t);
+};
+#define SIMPLE_GRAPHICS_VERSION 2
+#endif
diff --git a/src/main/c/simple_miniaudio.c b/src/main/c/simple_miniaudio.c
new file mode 100644
index 00000000..03dbadd7
--- /dev/null
+++ b/src/main/c/simple_miniaudio.c
@@ -0,0 +1,123 @@
+#include "simple_audio.h"
+#define MA_NO_DECODING
+#define MA_NO_ENCODING
+#define MA_NO_RESOURCE_MANAGER
+#define MA_NO_NODE_GRAPH
+#define MA_NO_ENGINE
+#define MINIAUDIO_IMPLEMENTATION
+#include <miniaudio.h>
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+
+#define RATE 48000
+#define SLOTS 32
+static ma_device device;
+static ma_mutex mutex;
+static int opened, active;
+static uint32_t cursor;
+static struct { int16_t *pcm; uint32_t count; } sounds[SLOTS];
+
+// Only native-owned immutable PCM is read on the audio thread. The lock covers
+// a bounded copy, never allocation, synthesis, device calls, or Simple code.
+static void output(ma_device *unused, void *out, const void *in, ma_uint32 frames) {
+ (void)unused; (void)in;
+ memset(out,0,frames*sizeof(int16_t));
+ ma_mutex_lock(&mutex);
+ if (active) {
+ uint32_t count=sounds[active].count-cursor;
+ if (count>frames) count=frames;
+ memcpy(out,sounds[active].pcm+cursor,count*sizeof(int16_t));
+ cursor+=count;
+ if (cursor==sounds[active].count) active=0;
+ }
+ ma_mutex_unlock(&mutex);
+}
+static int32_t load(const int16_t *pcm, uint32_t count) {
+ if (!opened || !pcm || !count || count>RATE*10) return -1;
+ int slot;
+ for (slot=4; slot<SLOTS && sounds[slot].pcm; ++slot) {}
+ if (slot==SLOTS) return -1;
+ int16_t *copy=malloc(count*sizeof(*copy));
+ if (!copy) return -1;
+ memcpy(copy,pcm,count*sizeof(*copy));
+ ma_mutex_lock(&mutex);
+ sounds[slot].pcm=copy; sounds[slot].count=count;
+ ma_mutex_unlock(&mutex);
+ return slot;
+}
+static int32_t play(int32_t sound) {
+ if (!opened || sound<=0 || sound>=SLOTS || !sounds[sound].pcm) return -1;
+ ma_mutex_lock(&mutex);
+ active=sound; cursor=0;
+ ma_mutex_unlock(&mutex);
+ return 0;
+}
+static int32_t stop(void) {
+ if (opened) { ma_mutex_lock(&mutex); active=0; ma_mutex_unlock(&mutex); }
+ return 0;
+}
+static int32_t playing(void) {
+ if (!opened) return 0;
+ ma_mutex_lock(&mutex);
+ int result=active!=0;
+ ma_mutex_unlock(&mutex);
+ return result;
+}
+static void close_audio(void) {
+ if (!opened) return;
+ ma_device_uninit(&device); // Joins callback before freeing buffers/mutex.
+ ma_mutex_uninit(&mutex);
+ for (int i=1;i<SLOTS;++i) {
+ free(sounds[i].pcm); sounds[i].pcm=NULL; sounds[i].count=0;
+ }
+ opened=0; active=0; cursor=0;
+}
+static int tone(int slot, int descending) {
+ uint32_t note=slot==1 ? RATE*7/100 : RATE*16/100;
+ int notes=slot==1 ? 1 : 3;
+ sounds[slot].count=note*notes;
+ sounds[slot].pcm=calloc(note*notes,sizeof(int16_t));
+ if (!sounds[slot].pcm) return -1;
+ const double pitches[3]={523.251,659.255,783.991};
+ for (int n=0;n<notes;++n) {
+ double hz=slot==1 ? 440.0 : pitches[descending ? 2-n : n];
+ for (uint32_t i=0;i<note;++i) {
+ double t=(double)i/note;
+ double envelope=sin(3.141592653589793*t);
+ sounds[slot].pcm[n*note+i]=(int16_t)(3200*envelope*envelope*sin(6.283185307179586*hz*i/RATE));
+ }
+ }
+ return 0;
+}
+static int32_t open_audio(void) {
+ if (opened) return 0;
+ if (ma_mutex_init(&mutex)!=MA_SUCCESS) return -1;
+ ma_device_config config=ma_device_config_init(ma_device_type_playback);
+ config.playback.format=ma_format_s16;
+ config.playback.channels=1;
+ config.sampleRate=RATE;
+ config.dataCallback=output;
+#ifdef SIMPLE_AUDIO_TEST_NULL
+ ma_backend backend=ma_backend_null;
+ ma_result result=ma_device_init_ex(&backend,1,NULL,&config,&device);
+#else
+ ma_result result=ma_device_init(NULL,&config,&device);
+#endif
+ if (result!=MA_SUCCESS) {
+ ma_mutex_uninit(&mutex);
+ fprintf(stderr,"Simple audio: no playback device (%d); continuing silently.\n",result);
+ return -1;
+ }
+ opened=1;
+ if (tone(1,0) || tone(2,0) || tone(3,1) || ma_device_start(&device)!=MA_SUCCESS) {
+ close_audio(); return -1;
+ }
+ return 0;
+}
+static const struct simple_audio_api api={SIMPLE_AUDIO_VERSION,open_audio,load,play,stop,playing,close_audio};
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+const struct simple_audio_api *simple_miniaudio_api(void) { return &api; }
diff --git a/src/main/c/simple_minifb.c b/src/main/c/simple_minifb.c
new file mode 100644
index 00000000..2117f0d2
--- /dev/null
+++ b/src/main/c/simple_minifb.c
@@ -0,0 +1,117 @@
+#include "simple_graphics.h"
+#include <MiniFB.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+#ifdef _WIN32
+#include <windows.h>
+#else
+#include <errno.h>
+#include <time.h>
+#include <poll.h>
+#include "WindowData.h"
+#include "x11/WindowData_X11.h"
+#endif
+
+// One fixed-size window for now. No Simple pointer survives a native call:
+// MiniFB retains its last draw buffer for OS repaint events, so copy it here.
+static struct mfb_window *window;
+static uint32_t *frame;
+static uint32_t width, height;
+
+// The C-only build never installs the upstream C++ callback wrappers.
+void release_cpp_stub(struct mfb_window *unused) { (void)unused; }
+
+static void close_window(void) {
+ if (window) {
+ mfb_close(window); // Requests close.
+ mfb_update_events(window); // Actually destroys the window.
+ window = NULL;
+ }
+ free(frame);
+ frame = NULL;
+}
+
+static int32_t open_window(const char *title, uint32_t w, uint32_t h) {
+ if (window || !w || !h || w > UINT32_MAX / 4 ||
+ (uint64_t)w * h > UINT32_MAX || (uint64_t)w * h > SIZE_MAX / 4) {
+ fprintf(stderr, "Simple graphics: invalid dimensions or a window is already open.\n");
+ return -1;
+ }
+ frame = calloc((size_t)w * h, sizeof(*frame));
+ if (!frame) {
+ fprintf(stderr, "Simple graphics: cannot allocate the display buffer.\n");
+ return -1;
+ }
+ window = mfb_open(title, w, h);
+ if (!window) {
+ fprintf(stderr, "Simple graphics: MiniFB could not open a window (is a graphical display available?).\n");
+ close_window();
+ return -1;
+ }
+ width = w;
+ height = h;
+ return 0;
+}
+
+static int32_t status(mfb_update_state state) {
+ if (state == MFB_STATE_OK) return 0;
+ if (state == MFB_STATE_EXIT) {
+ window = NULL; // MiniFB has already destroyed it.
+ close_window();
+ return 1;
+ }
+ fprintf(stderr, "Simple graphics: MiniFB update failed (%d).\n", state);
+ close_window();
+ return -1;
+}
+
+static int32_t present(const uint32_t *pixels, uint32_t count) {
+ if (!window) return 1;
+ if (!pixels || count != (uint64_t)width * height) {
+ fprintf(stderr, "Simple graphics: pixel array length must equal width * height.\n");
+ return -1;
+ }
+ memcpy(frame, pixels, (size_t)count * sizeof(*frame));
+ return status(mfb_update_ex(window, frame, width, height));
+}
+
+static int32_t wait_events(int64_t timeout) {
+ if (!window) return 1;
+ if (timeout < -1) return -1;
+ // May return early; the game recomputes its deadlines after every wakeup.
+ int ms=timeout>INT_MAX ? INT_MAX : (int)timeout;
+#ifdef _WIN32
+ if (MsgWaitForMultipleObjectsEx(0,NULL,ms<0 ? INFINITE : (DWORD)ms,
+ QS_ALLINPUT,MWMO_INPUTAVAILABLE)==WAIT_FAILED) return -1;
+#else
+ // The pinned MiniFB X11 backend owns this connection. Check already queued
+ // Xlib events before waiting on its socket; no new event thread is needed.
+ SWindowData *data=(SWindowData *)window;
+ SWindowData_X11 *native=(SWindowData_X11 *)data->specific;
+ if (!XPending(native->display)) {
+ struct pollfd fd={ConnectionNumber(native->display),POLLIN,0};
+ if (poll(&fd,1,ms)<0 && errno!=EINTR) return -1;
+ }
+#endif
+ return status(mfb_update_events(window));
+}
+static int32_t poll_events(int32_t wait) { return wait_events(wait ? 17 : 0); }
+static int32_t mouse_x(void) { return window ? mfb_get_mouse_x(window) : 0; }
+static int32_t mouse_y(void) { return window ? mfb_get_mouse_y(window) : 0; }
+static int32_t button(int32_t b) {
+ return window && b >= 0 && b < 8 ? mfb_get_mouse_button_buffer(window)[b] != 0 : 0;
+}
+static int32_t key(int32_t k) {
+ return window && k >= 0 && k <= MFB_KB_KEY_LAST ? mfb_get_key_buffer(window)[k] != 0 : 0;
+}
+
+static const struct simple_graphics_api api = {
+ SIMPLE_GRAPHICS_VERSION, open_window, present, poll_events,
+ mouse_x, mouse_y, button, key, close_window, wait_events
+};
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+const struct simple_graphics_api *simple_minifb_api(void) { return &api; }
diff --git a/src/main/c/simple_time.c b/src/main/c/simple_time.c
new file mode 100644
index 00000000..2e579922
--- /dev/null
+++ b/src/main/c/simple_time.c
@@ -0,0 +1,61 @@
+#define _POSIX_C_SOURCE 200809L
+#include <time.h>
+#include <stdint.h>
+#include <errno.h>
+
+// Fixed-width bridge; no native struct layout or retained Simple pointers.
+static int64_t clock_value(clockid_t clock, int64_t scale) {
+ struct timespec t;
+ if (clock_gettime(clock,&t)) return -1;
+ if (t.tv_sec>INT64_MAX/scale || t.tv_sec<INT64_MIN/scale) {
+ errno=EOVERFLOW; return -1;
+ }
+ int64_t base=(int64_t)t.tv_sec*scale;
+ int64_t fraction=t.tv_nsec/(1000000000/scale);
+ if (base>INT64_MAX-fraction) { errno=EOVERFLOW; return -1; }
+ return base+fraction;
+}
+int64_t simple_time_now(void) { return clock_value(CLOCK_REALTIME,1000); }
+int64_t simple_time_mono(void) { return clock_value(CLOCK_MONOTONIC,1000); }
+int64_t simple_time_nano(void) { return clock_value(CLOCK_MONOTONIC,1000000000); }
+int32_t simple_time_sleep(int64_t ms, int32_t absolute) {
+ if (ms<0) { errno=EINVAL; return -1; }
+ struct timespec t={ms/1000,(ms%1000)*1000000};
+ int result;
+ if (!absolute) {
+ // Retry the remaining duration after signals; no busy waiting.
+ do { result=nanosleep(&t,&t); } while (result && errno==EINTR);
+ return result;
+ }
+ do { result=clock_nanosleep(CLOCK_MONOTONIC,TIMER_ABSTIME,&t,NULL); } while (result==EINTR);
+ if (result) { errno=result; return -1; }
+ return 0;
+}
+static int leap(int y) { return y%4==0 && (y%100!=0 || y%400==0); }
+static int local_fields(int64_t ms, struct tm *local, struct tm *utc) {
+ tzset();
+ int64_t sec=ms/1000;
+ if (ms%1000<0) --sec;
+ time_t t=(time_t)sec;
+ if ((int64_t)t!=sec || !localtime_r(&t,local) || !gmtime_r(&t,utc)) return -1;
+ if (local->tm_year < -1899 || local->tm_year > 8099) { errno=EOVERFLOW; return -1; }
+ return 0;
+}
+int32_t simple_time_local(int64_t ms, int64_t *out) {
+ struct tm t,u;
+ if (local_fields(ms,&t,&u)) return -1;
+ int days=t.tm_yday-u.tm_yday;
+ if (t.tm_year>u.tm_year) days+=365+leap(u.tm_year+1900);
+ if (t.tm_year<u.tm_year) days-=365+leap(t.tm_year+1900);
+ int offset=days*86400+(t.tm_hour-u.tm_hour)*3600+(t.tm_min-u.tm_min)*60+t.tm_sec-u.tm_sec;
+ out[0]=t.tm_year+1900; out[1]=t.tm_mon+1; out[2]=t.tm_mday;
+ out[3]=t.tm_hour; out[4]=t.tm_min; out[5]=t.tm_sec;
+ out[6]=(ms%1000+1000)%1000; out[7]=t.tm_wday;
+ out[8]=offset; out[9]=t.tm_isdst>0;
+ return 0;
+}
+int32_t simple_time_zone(int64_t ms, char *out, uint32_t capacity) {
+ struct tm t,u;
+ if (!capacity || local_fields(ms,&t,&u)) return -1;
+ return (int32_t)strftime(out,capacity,"%Z",&t);
+}