summaryrefslogtreecommitdiff
path: root/plat.c
blob: 16144b4ca10a7b4f3acbcac60363715206084f1b (plain) (blame)
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
#include "config.h"
#include "error.h"
#include "maths.h"
#include "memory.h"
#include "plat.h"

#ifdef plat_posix

#define _POSIX_SOURCE
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>

extern int isatty(int);
extern int fileno(FILE*);

int imp_assert(
	int val,
	const char* expr,
	const char* file,
	int line
) {
	if (!val) {
		print_err(
			"%d:%s: Assertion failed: %s.\n",
			line,
			file,
			expr
		);
		pbreak(error_assertion_failed);
		return 0;
	}
	return 1;
}

void print(const char* fmt, ...) {
	va_list args;
	va_start(args, fmt);
	vfprintf(stdout, fmt, args);
	va_end(args);
}

void print_err(const char* fmt, ...) {
	va_list args;
	va_start(args, fmt);

	if (isatty(fileno(stderr))) {
		fprintf(stderr, "\033[31;31m");
	}

	vfprintf(stderr, fmt, args);

	if (isatty(fileno(stderr))) {
		fprintf(stderr, "\033[0m");
	}

	va_end(args);
}

void print_war(const char* fmt, ...) {
	va_list args;
	va_start(args, fmt);

	if (isatty(fileno(stderr))) {
		fprintf(stderr, "\033[31;35m");
	}

	vfprintf(stderr, fmt, args);

	if (isatty(fileno(stderr))) {
		fprintf(stderr, "\033[0m");
	}

	va_end(args);
}

void pbreak(Error code) {
#if defined(DEBUG) && defined(plat_x86)
	__asm__("int3;");
	(void)code;
#else
	exit(code);
#endif
}

struct File {
	int handle;
	int cursor;
	int size;
};

File* file_open(const char* name, File_Flags flags) {
	File* file;
	int handle, f = 0;
	struct stat info;

	if (flags & file_flags_write) {
		f |= O_WRONLY | O_TRUNC;
	}

	if (flags & file_flags_read) {
		f |= O_RDONLY;
	}

	if (flags & file_flags_read_write) {
		f |= O_RDWR;
	}

	if (stat(name, &info) < 0) {
		info.st_size = 0;
		if (flags & file_flags_create) {
			f |= O_CREAT | S_IRUSR | S_IWUSR;
		}
	}

	handle = open(name, f);
	if (handle < 0) {
		return 0;
	}

	file = (File*)malloc(sizeof *file);
	file->handle = handle;
	file->cursor = 0;
	file->size = (int)info.st_size;

	return file;
}

void file_close(File* file) {
	close(file->handle);
	free(file);
}

void file_read(File* file, void* buffer, int size) {
	lseek(file->handle, (off_t)file->cursor, SEEK_SET);
	read(file->handle, buffer, size);
	file->cursor += size;
}

void file_write(File* file, const void* buffer, int size) {
	lseek(file->handle, (off_t)file->cursor, SEEK_SET);
	write(file->handle, buffer, size);
	file->cursor += size;
}

void file_seek(File* file, int offset, File_Whence whence) {
	switch (whence) {
		case file_whence_begin:
			file->cursor = offset;
			break;
		case file_whence_end:
			file->cursor = file->size - offset;
			break;
		case file_whence_cur:
			file->cursor += offset;
			break;
	}
}

int file_size(File* file) {
	return file->size;
}

int file_exists(const char* name) {
	struct stat info;
	return stat(name, &info) == 0;
}


static clockid_t global_clock;
static unsigned long global_freq;

void init_timer(void) {
	struct timespec ts;
	global_clock = CLOCK_REALTIME;
	global_freq = 1000000000;
#if defined(_POSIX_MONOTONIC_CLOCK)
	if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
		global_clock = CLOCK_MONOTONIC;
	}
#else
	(void)ts;
#endif
}

unsigned long get_timer(void) {
	struct timespec ts;
	clock_gettime(global_clock, &ts);
	return
		(unsigned long)ts.tv_sec * global_freq +
		(unsigned long)ts.tv_nsec;
}

void sleep_ns(unsigned long ns) {
	struct timespec t = { 0 };
	t.tv_nsec = ns;
	nanosleep(&t, &t);
}

void init_fps(FPS* f, int mpf) {
	f->now = get_timer();
	f->next = f->now;
	f->mpf = mpf;
	f->pt = 0;
	f->ct = -1;
}

void fps_begin(FPS* f) {
	f->now = get_timer();
}

void fps_end(FPS* f) {
	unsigned long ts = f->next - f->now;
	if (ts > 0) {
		sleep_ns(ts);
	}
}

void fps_update(FPS* f) {
	f->next += f->mpf * 1000000;
	f->pt = f->ct;
	f->ct = get_timer();
	f->fps = 1000000000 / (f->ct - f->pt);
}

#include <stdlib.h>

extern int entrypoint(int, const char**, Arena*);

int main(int argc, const char** argv) {
	Arena a;
	void* mem = malloc(memory_size);
	if (!mem) {
		print_err("Out of memory.\n");
		return error_out_of_memory;
	}
	init_timer();
	init_arena(
		&a,
		mem,
		memory_size
	);
	return entrypoint(argc, argv, &a);
}

#endif

#ifdef plat_x11

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/extensions/XInput2.h>

#include <stdlib.h>

typedef struct {
	Display* d;
	Window wi;
	GC gc;
	int w, h;
	int rmx, rmy;
	int omx, omy;
	int ms;
	unsigned long begin, end;
	XImage* bb;
	Colour* bbp;
	Atom wm_delete;
} App_Internal;

Key key_from_xkey(unsigned key) {
	switch (key) {
		case 0x61:           return key_A;
		case 0x62:           return key_B;
		case 0x63:           return key_C;
		case 0x64:           return key_D;
		case 0x65:           return key_E;
		case 0x66:           return key_F;
		case 0x67:           return key_G;
		case 0x68:           return key_H;
		case 0x69:           return key_I;
		case 0x6A:           return key_J;
		case 0x6B:           return key_K;
		case 0x6C:           return key_L;
		case 0x6D:           return key_M;
		case 0x6E:           return key_N;
		case 0x6F:           return key_O;
		case 0x70:           return key_P;
		case 0x71:           return key_Q;
		case 0x72:           return key_R;
		case 0x73:           return key_S;
		case 0x74:           return key_T;
		case 0x75:           return key_U;
		case 0x76:           return key_V;
		case 0x77:           return key_W;
		case 0x78:           return key_X;
		case 0x79:           return key_Y;
		case 0x7A:           return key_Z;
		case XK_F1:          return key_f1;
		case XK_F2:          return key_f2;
		case XK_F3:          return key_f3;
		case XK_F4:          return key_f4;
		case XK_F5:          return key_f5;
		case XK_F6:          return key_f6;
		case XK_F7:          return key_f7;
		case XK_F8:          return key_f8;
		case XK_F9:          return key_f9;
		case XK_F10:         return key_f10;
		case XK_F11:         return key_f11;
		case XK_F12:         return key_f12;
		case XK_Down:        return key_down;
		case XK_Left:        return key_left;
		case XK_Right:       return key_right;
		case XK_Up:          return key_up;
		case XK_Escape:      return key_escape;
		case XK_Return:      return key_return;
		case XK_BackSpace:   return key_backspace;
		case XK_Linefeed:    return key_return;
		case XK_Tab:         return key_tab;
		case XK_Delete:      return key_delete;
		case XK_Home:        return key_home;
		case XK_End:         return key_end;
		case XK_Page_Up:     return key_page_up;
		case XK_Page_Down:   return key_page_down;
		case XK_Insert:      return key_insert;
		case XK_Shift_L:     return key_shift;
		case XK_Shift_R:     return key_shift;
		case XK_Control_L:   return key_control;
		case XK_Control_R:   return key_control;
		case XK_Super_L:     return key_super;
		case XK_Super_R:     return key_super;
		case XK_Alt_L:       return key_alt;
		case XK_Alt_R:       return key_alt;
		case XK_space:       return key_space;
		case XK_period:      return key_period;
		case XK_0:           return key_0;
		case XK_1:           return key_1;
		case XK_2:           return key_2;
		case XK_3:           return key_3;
		case XK_4:           return key_4;
		case XK_5:           return key_5;
		case XK_6:           return key_6;
		case XK_7:           return key_7;
		case XK_8:           return key_8;
		case XK_9:           return key_9;
		default:             return key_unknown;
	}
}

void init_rendering(
	App* a,
	App_Internal* i,
	XWindowAttributes* wa
) {
	Colour* p, * fb;
	int w = max_pc_window_w;
	int h = max_pc_window_h;
	int tw = max_vp_w;
	int th = max_vp_h;
	p = malloc(sizeof *p * w * h);
	fb = heap_alloc(a->heap, sizeof *p * tw * th);
	if (!p || !fb) {
		print_err("Out of memory.\n");
		pbreak(error_out_of_memory);
	}
	a->fb = fb;
	i->bb = XCreateImage(
		i->d,
		wa->visual,
		wa->depth,
		ZPixmap,
		0,
		(char*)p,
		w,
		h,
		32,
		w * sizeof *p
	);
	if (!i->bb) {
		print_err("Failed to create X11 backbuffer.\n");
		pbreak(error_platform_error);
	}
	i->bbp = p;
}

void init_window(App* a, App_Internal* i, const char* n) {
	Window root, w;
	Display* d;
	XWindowAttributes wa;
	unsigned rm, bm;
	i->bb = 0;
	i->bbp = 0;
	d = i->d;
	root = DefaultRootWindow(d);
	w = XCreateSimpleWindow(
		d,
		root,
		0,
		0,
		a->w * a->s,
		a->h * a->s,
		0,
		WhitePixel(d, 0),
		BlackPixel(d, 0)
	);
	i->wi = w;
	i->wm_delete = XInternAtom(
		d,
		"WM_DELETE_WINDOW",
		0
	);
	XSetWMProtocols(d, w, &i->wm_delete, 1);
	XStoreName(d, w, n);
	XSelectInput(
		d,
		w,
		ExposureMask      |
		KeyPressMask      |
		KeyReleaseMask    |
		PointerMotionMask |
		ButtonPressMask   |
		ButtonReleaseMask
	);
	XMapRaised(d, w);
	i->gc = XCreateGC(d, w, 0, 0);
	if (!i->gc) {
		print_err("Failed to create X graphics context.\n");
		pbreak(error_platform_error);
	}
	XGetWindowAttributes(d, w, &wa);
	if (wa.depth != 24 && wa.depth != 32) {
		print_err("Only true colour displays are supported.\n");
		pbreak(error_platform_error);
	}
	rm = wa.visual->red_mask  & 0x1000000;
	bm = wa.visual->blue_mask & 0xffffff;
	if ((rm == 0xff && bm == 0xff0000)) {
		print_war("Detected BGR. Colours will look fucked.\n");
	}
	init_rendering(a, i, &wa);
	a->w = (wa.width  + a->s) / a->s;
	a->h = (wa.height + a->s) / a->s;
	i->w = wa.width;
	i->h = wa.height;
}

App* new_app(Heap* mem, int w, int h, const char* n) {
	App* a;
	App_Internal* i;
	a = heap_alloc(mem, sizeof *a + sizeof *i);
	i = (App_Internal*)(&a[1]);
	a->heap = mem;
	a->s = 2;
	a->o = 0;
	a->err = error_none;
	a->w = w;
	a->h = h;
	i->d = XOpenDisplay(0);
	i->omx = i->omy = 0;
	i->ms = 1;
	if (!i->d) {
		print_err("Failed to open X11 display.\n");
		pbreak(error_platform_error);
	}
	init_window(a, i, n);
	a->o = 1;
	return a;
}

void deinit_app(App* a) {
	App_Internal* i = (App_Internal*)(&a[1]);
	XDestroyImage(i->bb);
	XFreeGC(i->d, i->gc);
	XDestroyWindow(i->d, i->wi);
	XCloseDisplay(i->d);
	heap_free(a->heap, a);
}

void app_begin(App* a) {
	App_Internal* i = (App_Internal*)(&a[1]);
	Display* d = i->d;
	Window w = i->wi;
	int j;
	i->begin = get_timer();
	for (j = 0; j < key_count; j++)
		a->key_states[j] &= ~(
			key_state_just_pressed | key_state_just_released
		);
	for (j = 0; j < mbtn_count; j++)
		a->mbtn_states[j] &= ~(
			key_state_just_pressed | key_state_just_released
		);
	a->scrollx = a->scrolly = 0;
	while (XPending(d)) {
		XEvent e;
		XWindowAttributes wa;
		KeySym sym;
		Key key;
		int btn;
		XNextEvent(d, &e);
		switch (e.type) {
			case ClientMessage:
				if (
					(Atom)e.xclient.data.l[0] ==
					i->wm_delete
				) {
					a->o = 0;
				}
				break;
			case Expose:
				XGetWindowAttributes(d, w, &wa);
				a->w = (wa.width  + a->s) / a->s;
				a->h = (wa.height + a->s) / a->s;
				a->w = mini(a->w, max_vp_w);
				a->h = mini(a->h, max_vp_w);
				i->w = mini(wa.width,  max_pc_window_w);
				i->h = mini(wa.height, max_pc_window_h);
				break;
			case MotionNotify:
				if (i->ms) {
					a->mx = e.xmotion.x / a->s;
					a->my = e.xmotion.y / a->s;
				}
				break;
			case ButtonPress:
				switch (e.xbutton.button) {
					case 1:
					case 2:
					case 3:
						a->mbtn_states[e.xbutton.button - 1] |= 
							key_state_pressed |
							key_state_just_pressed;
						break;
					case 4:
						a->scrolly++;
						break;
					case 5:
						a->scrolly--;
						break;
					case 6:
						a->scrollx++;
						break;
					case 7:
						a->scrollx--;
						break;
				}
				break;
			case ButtonRelease:
				switch (e.xbutton.button) {
					case 1:
					case 2:
					case 3:
						btn = e.xbutton.button - 1;
						a->mbtn_states[btn] &= ~key_state_pressed;
						a->mbtn_states[btn] |= key_state_just_released;
						break;
					case 4:
						a->scrolly++;
						break;
					case 5:
						a->scrolly--;
						break;
					case 6:
						a->scrollx++;
						break;
					case 7:
						a->scrollx--;
						break;
				}
				break;
			case KeyPress:
				sym = XLookupKeysym(&e.xkey, 0);
				key = key_from_xkey(sym);
				a->key_states[key] |=
					key_state_pressed |
					key_state_just_pressed;
				break;
			case KeyRelease:
				sym = XLookupKeysym(&e.xkey, 0);
				key = key_from_xkey(sym);
				a->key_states[key] &= ~key_state_pressed;
				a->key_states[key] |= key_state_just_released;
				break;
			case GenericEvent:
				if (!i->ms) {
					if (
						XGetEventData(d, &e.xcookie) &&
						e.xcookie.evtype == XI_RawMotion
					) {
						XIRawEvent* re = e.xcookie.data;
						if (re->valuators.mask_len) {
							const double* values = re->raw_values;
							if (XIMaskIsSet(re->valuators.mask, 0)) {
								i->rmx += (int)values[0];
							}
							if (XIMaskIsSet(re->valuators.mask, 1)) {
								i->rmy += (int)values[1];
							}
							a->mx = i->rmx;
							a->my = i->rmy;
						}
						XFreeEventData(d, &e.xcookie);
					}
				}
				break;
			default:
				break;
		}
	}
	a->dmx = a->mx - i->omx;
	a->dmy = a->my - i->omy;
	i->omx = a->mx;
	i->omy = a->my;
	if (!i->ms) {
		XWarpPointer(
			d,
			i->wi,
			i->wi,
			0,
			0,
			0,
			0,
			i->w / 2,
			i->h / 2
		);
		XSync(d, False);
	}
}

void app_rencpy(
	App* a,
	App_Internal* i,
	int x,
	int y,
	int w,
	int h
) {
	int rat_x,  rat_y;
	int rrat_x, rrat_y;
	int sx, sy;
	int ix, iy, sw, sh, dw, dh;
	int dsx, dsy;
	int dex, dey;
	int pidx;
	Colour* dst;
	const Colour* src;
	unsigned char t;
	sw = a->w;
	sh = a->h;
	dw = i->w;
	dh = i->h;
	rat_x  = (sw << fbits * 2) / (dw << fbits);
	rat_y  = (sh << fbits * 2) / (dh << fbits);
	rrat_x = (dw << fbits * 2) / (sw << fbits);
	rrat_y = (dh << fbits * 2) / (sh << fbits);
	dsx = (x       * rrat_x) >> fbits;
	dsy = (y       * rrat_y) >> fbits;
	dex = ((x + w) * rrat_x) >> fbits;
	dey = ((y + h) * rrat_y) >> fbits;
	dst = i->bbp;
	src = a->fb;
	for (iy = dsy; iy < dey; iy++) {
		sy = (rat_y * (iy << fbits)) >> (fbits * 2);
		for (ix = dsx; ix < dex; ix++) {
			sx = (rat_x * (ix << fbits)) >> (fbits * 2);
			pidx = sx + sy * sw;
			dst = &i->bbp[ix + iy * max_pc_window_w];
			*dst = src[pidx];
			t = dst->r;
			dst->r = dst->b;
			dst->b = t;
		}
	}
	XPutImage(
		i->d,
		i->wi,
		i->gc,
		i->bb,
		dsx, dsy,
		dsx, dsy,
		dex - dsx, dey - dsy
	);
}

void app_end(App* a) {
	App_Internal* i = (App_Internal*)(&a[1]);
	app_rencpy(a, i, 0, 0, a->w, a->h);
	i->end = get_timer();
	a->fps = 1000000000 / (i->end - i->begin);
}

void cfg_mouse(App* a, int show) {
	App_Internal* i = (App_Internal*)(&a[1]);
	Display* d = i->d;
	Window w = i->wi;
	i->ms = show;
	if (show) {
		XUndefineCursor(d, w);
		XUngrabPointer(d, CurrentTime);
	} else {
		XColor c;
		char bd[1] = { 0 };
		Pixmap b = XCreateBitmapFromData(d, w, bd, 1, 1);
		Cursor cur = XCreatePixmapCursor(d, b, b, &c, &c, 0, 0);
		XIEventMask em;
		unsigned char mask[XIMaskLen(XI_RawMotion)] = { 0 };
		XDefineCursor(d, w, cur);
		XGrabPointer(
			d,
			w,
			1,
			ButtonPressMask |
			ButtonReleaseMask |
			PointerMotionMask,
			GrabModeAsync,
			GrabModeAsync,
			w,
			None,
			CurrentTime
		);
		em.deviceid = XIAllMasterDevices;
		em.mask_len = sizeof(mask);
		em.mask = mask;
		XISetMask(mask, XI_RawMotion);
		XISelectEvents(d, DefaultRootWindow(d), &em, 1);
		XWarpPointer(
			d,
			i->wi,
			i->wi,
			0,
			0,
			0,
			0,
			i->w / 2,
			i->h / 2
		);
		a->mx = i->w / 2;
		a->my = i->h / 2;
		i->rmx = a->mx;
		i->rmy = a->my;
		i->omx = a->mx;
		i->omy = a->my;
	}
}

#endif