-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathdirksimple.c
More file actions
1912 lines (1669 loc) · 64.2 KB
/
dirksimple.c
File metadata and controls
1912 lines (1669 loc) · 64.2 KB
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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* DirkSimple; a dirt-simple player for FMV games.
*
* Please see the file LICENSE.txt in the source's root directory.
*
* This file written by Ryan C. Gordon.
*/
#include "dirksimple_platform.h"
#include "theoraplay.h"
#include "lodepng.h"
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#define DIRKSIMPLE_LUA_NAMESPACE "DirkSimple"
#define DIRKSIMPLE_FAKE_DISC_LAG_TICKS 800
// "included in all copies or substantial portions of the Software"
static const char *GLuaLicense =
"Lua:\n"
"\n"
"Copyright (C) 1994-2008 Lua.org, PUC-Rio.\n"
"\n"
"Permission is hereby granted, free of charge, to any person obtaining a copy\n"
"of this software and associated documentation files (the \"Software\"), to deal\n"
"in the Software without restriction, including without limitation the rights\n"
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n"
"copies of the Software, and to permit persons to whom the Software is\n"
"furnished to do so, subject to the following conditions:\n"
"\n"
"The above copyright notice and this permission notice shall be included in\n"
"all copies or substantial portions of the Software.\n"
"\n"
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n"
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n"
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n"
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n"
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n"
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n"
"THE SOFTWARE.\n"
"\n";
typedef enum RenderPrimitive
{
RENDPRIM_CLEAR,
RENDPRIM_SPRITE,
RENDPRIM_SOUND,
} RenderPrimitive;
typedef struct RenderCommand
{
RenderPrimitive prim;
union
{
struct
{
uint8_t r, g, b;
} clear;
struct
{
char name[32];
int32_t sx, sy, sw, sh, dx, dy, dw, dh;
uint8_t r, g, b;
} sprite;
struct
{
char name[32];
} sound;
} data;
} RenderCommand;
static char *GGameName = NULL;
static char *GGamePath = NULL;
static char *GDataDir = NULL;
static char *GGameDir = NULL;
static THEORAPLAY_Decoder *GDecoder = NULL;
static THEORAPLAY_Io GTheoraplayIo;
static lua_State *GLua = NULL;
static uint64_t GPreviousInputBits = 0;
static int GDiscoveredVideoFormat = 0;
static int GDiscoveredAudioFormat = 0;
static int GAudioChannels = 0;
static int GAudioFreq = 0;
static uint64_t GTicks = 0; // Current ticks into the game, increases each iteration.
static uint64_t GTicksOffset = 0; // offset from monotonic clock where we started.
static uint32_t GFrameMS = 0; // milliseconds each video frame takes.
static int64_t GSeekToTicksOffset = 0;
static uint64_t GClipStartMs = 0; // Milliseconds into video stream that starts this clip.
static uint64_t GClipStartTicks = 0; // GTicks when clip started playing
static int GHalted = 0;
static int GShowingSingleFrame = 0;
static int GFakeDiscLag = 0;
static uint64_t GDiscLagUntilTicks = 0;
static unsigned int GSeekGeneration = 0;
static int GNeedInitialLuaTick = 1;
static const THEORAPLAY_VideoFrame *GPendingVideoFrame = NULL;
static DirkSimple_Sprite *GSprites = NULL;
static DirkSimple_Wave *GWaves = NULL;
static RenderCommand *GRenderCommands = NULL;
static int GNumRenderCommands = 0;
static int GNumAllocatedRenderCommands = 0;
static uint8_t *GBlankVideoFrame = NULL;
static void out_of_memory(void)
{
DirkSimple_panic("Out of memory!");
}
void *DirkSimple_xmalloc(size_t len)
{
void *retval = DirkSimple_malloc(len);
if (!retval) {
out_of_memory();
}
return retval;
}
void *DirkSimple_xcalloc(size_t nmemb, size_t len)
{
void *retval = DirkSimple_calloc(nmemb, len);
if (!retval) {
out_of_memory();
}
return retval;
}
void *DirkSimple_xrealloc(void *ptr, size_t len)
{
void *retval = DirkSimple_realloc(ptr, len);
if (!retval && (len > 0)) {
out_of_memory();
}
return retval;
}
char *DirkSimple_xstrdup(const char *str)
{
char *retval = DirkSimple_strdup(str);
if (!retval) {
out_of_memory();
}
return retval;
}
const char *DirkSimple_gamename(void) { return GGameName; }
const char *DirkSimple_datadir(void) { return GDataDir; }
const char *DirkSimple_gamedir(void) { return GGameDir; }
void DirkSimple_log(const char *fmt, ...)
{
char *str = NULL;
va_list ap;
size_t len;
va_start(ap, fmt);
len = vsnprintf(NULL, 0, fmt, ap);
va_end(ap);
str = DirkSimple_xmalloc(len + 1);
va_start(ap, fmt);
vsnprintf(str, len + 1, fmt, ap);
va_end(ap);
DirkSimple_writelog(str);
DirkSimple_free(str);
}
static long theoraplayiobridge_read(THEORAPLAY_Io *io, void *buf, long buflen)
{
DirkSimple_Io *dio = (DirkSimple_Io *) io->userdata;
return dio->read(dio, buf, buflen);
}
static long theoraplayiobridge_streamlen(THEORAPLAY_Io *io)
{
DirkSimple_Io *dio = (DirkSimple_Io *) io->userdata;
return dio->streamlen(dio);
}
static int theoraplayiobridge_seek(THEORAPLAY_Io *io, long absolute_offset)
{
DirkSimple_Io *dio = (DirkSimple_Io *) io->userdata;
return dio->seek(dio, absolute_offset);
}
static void theoraplayiobridge_close(THEORAPLAY_Io *io)
{
DirkSimple_Io *dio = (DirkSimple_Io *) io->userdata;
dio->close(dio);
}
static uint8_t *invalid_media(const char *fname, const char *err)
{
DirkSimple_log("Failed to load '%s': %s", fname, err);
return NULL;
}
uint8_t *DirkSimple_loadmedia(const char *fname, long *flen)
{
DirkSimple_Io *io = DirkSimple_openfile_read(fname);
if (!io) {
return invalid_media(fname, "Couldn't open file for reading");
}
*flen = io->streamlen(io);
uint8_t *fbuf = (uint8_t *) DirkSimple_malloc(*flen);
if (!fbuf) {
return invalid_media(fname, "Out of memory");
}
const long br = io->read(io, fbuf, *flen);
io->close(io);
if (br != *flen) {
DirkSimple_free(fbuf);
return invalid_media(fname, "couldn't read whole file into memory");
}
return fbuf;
}
static uint32_t readui32le(const uint8_t **pptr)
{
const uint8_t *ptr = *pptr;
uint32_t retval = (uint32_t) ptr[0];
retval |= ((uint32_t) ptr[1]) << 8;
retval |= ((uint32_t) ptr[2]) << 16;
retval |= ((uint32_t) ptr[3]) << 24;
*pptr += sizeof (retval);
return retval;
}
static uint16_t readui16le(const uint8_t **pptr)
{
const uint8_t *ptr = *pptr;
uint16_t retval = (uint16_t) ptr[0];
retval |= ((uint16_t) ptr[1]) << 8;
*pptr += sizeof (retval);
return retval;
}
static uint32_t swap32(uint32_t v) {
return v << 24 | (v << 8 & 0xff0000) | (v >> 8 & 0xff00) | (v >> 24);
}
static uint8_t *loadbmp_from_memory(const char *fname, const uint8_t *buf, int buflen, int *_w, int *_h)
{
const uint8_t *ptr = buf;
*_w = *_h = 0;
if (buflen < 50) {
return invalid_media(fname, "Not a .BMP file");
}
if ((ptr[0] != 'B') || (ptr[1] != 'M')) {
return invalid_media(fname, "Not a .BMP file");
}
ptr += 10;
const uint32_t offset_bits = readui32le(&ptr);
const uint32_t infolen = readui32le(&ptr);
if (offset_bits > buflen) {
return invalid_media(fname, "Incomplete or corrupt .BMP file");
} else if ((infolen + 10) > buflen) {
return invalid_media(fname, "Incomplete or corrupt .BMP file");
} else if (infolen < 40) { // not a standard BITMAPINFOHEADER.
return invalid_media(fname, "Unsupported .BMP format");
} else if (infolen == 64) { // this is some ancient, incompatible OS/2 thing.
return invalid_media(fname, "Unsupported .BMP format");
}
const uint32_t bmpwidth = readui32le(&ptr);
const uint32_t bmpheight = readui32le(&ptr);
ptr += 2; // skip planes
const uint16_t bitcount = readui16le(&ptr);
if ((bmpwidth > 1024) || (bmpheight > 1024)) {
return invalid_media(fname, "Image is too big"); // this is just an arbitrary limit.
} else if ((bmpwidth == 0) || (bmpheight == 0)) {
return invalid_media(fname, "Image is zero pixels in size");
} else if (bitcount != 32) {
return invalid_media(fname, "Only 32bpp .BMP files supported");
} else if ((offset_bits + (bmpwidth * bmpheight * 4)) > buflen) {
return invalid_media(fname, "Incomplete or corrupt .BMP file");
}
const uint32_t compression = readui32le(&ptr);
if ((compression != 0) && (compression != 3)) {
return invalid_media(fname, "Only uncompressed RGB .BMP files supported");
}
// we don't check the color masks; we assume they match what we want,
// and checking them just to verify is a lot of compatibility tapdancing.
uint8_t *pixels = (uint8_t *) DirkSimple_xmalloc(bmpwidth * bmpheight * 4);
// of course the stupid pixels are upside down in a bmp file.
const size_t rowlen = bmpwidth * 4;
const uint8_t *src = (buf + offset_bits) + (rowlen * (bmpheight - 1));
uint8_t *dst = pixels;
for (int y = 0; y < bmpheight; y++) {
memcpy(dst, src, rowlen);
for (int x = 0; x < bmpwidth; x++) {
*(uint32_t*)&dst[4*x] = swap32(*(uint32_t*)&dst[4*x]);
}
dst += rowlen;
src -= rowlen;
}
*_w = (int) bmpwidth;
*_h = (int) bmpheight;
return pixels;
}
uint8_t *DirkSimple_loadbmp(const char *fname, int *_w, int *_h)
{
long flen = 0;
uint8_t *fbuf = DirkSimple_loadmedia(fname, &flen);
uint8_t *pixels = fbuf ? loadbmp_from_memory(fname, fbuf, flen, _w, _h) : NULL;
DirkSimple_free(fbuf);
return (uint8_t *) pixels;
}
uint8_t *DirkSimple_loadpng(const char *fname, int *_w, int *_h)
{
unsigned char *pixels = NULL;
long flen = 0;
uint8_t *fbuf = DirkSimple_loadmedia(fname, &flen);
if (fbuf) {
unsigned uw = 0;
unsigned uh = 0;
if (lodepng_decode32(&pixels, &uw, &uh, (const unsigned char *) fbuf, (size_t) flen) == 0) {
*_w = (int) uw;
*_h = (int) uh;
} else {
lodepng_free(pixels);
pixels = NULL;
*_w = *_h = 0;
}
DirkSimple_free(fbuf);
}
return (uint8_t *) pixels;
}
// !!! FIXME: we should probably cache all sprites and waves we see in the
// !!! FIXME: game's dir during DirkSimple_startup. There are only a handful
// !!! FIXME: of them, we might as well just load them all upfront instead of
// !!! FIXME: risking a stall on the first use.
static DirkSimple_Sprite *get_cached_sprite(const char *name)
{
DirkSimple_Sprite *sprite = NULL;
// lowercase the name, just in case.
char *loweredname = DirkSimple_xstrdup(name);
int i;
for (i = 0; name[i]; i++) {
char ch = name[i];
if ((ch >= 'A') && (ch <= 'Z')) {
loweredname[i] = ch - ('A' - 'a');
}
}
name = loweredname;
for (sprite = GSprites; sprite != NULL; sprite = sprite->next) {
if (strcmp(sprite->name, loweredname) == 0) {
DirkSimple_free(loweredname);
return sprite; // already cached.
}
}
// not cached yet, load it from disk.
int w, h;
uint8_t *rgba;
const size_t slen = strlen(GGameDir) + strlen(name) + 8;
char *fname = (char *) DirkSimple_xmalloc(slen);
snprintf(fname, slen, "%s%s.png", GGameDir, name);
rgba = DirkSimple_loadpng(fname, &w, &h);
if (!rgba) { // maybe it's a bitmap?
snprintf(fname, slen, "%s%s.bmp", GGameDir, name);
rgba = DirkSimple_loadbmp(fname, &w, &h);
}
if (rgba) {
DirkSimple_log("Loaded sprite '%s': %dx%d, RGBA", fname, w, h);
}
DirkSimple_free(fname);
if (!rgba) {
char errmsg[128];
snprintf(errmsg, sizeof (errmsg), "Failed to load needed sprite '%s'. Check your installation?", name);
DirkSimple_panic(errmsg);
}
sprite = (DirkSimple_Sprite *) DirkSimple_xmalloc(sizeof (DirkSimple_Sprite));
sprite->name = loweredname;
sprite->width = w;
sprite->height = h;
sprite->rgba = rgba;
sprite->platform_handle = NULL;
sprite->next = GSprites;
GSprites = sprite;
return sprite;
}
/* this is an extremely simple, low-quality converter, because presumably we're dealing with simple, low-quality audio. */
static float *convertwav(const char *fname, float *pcm, int *_frames, int havechannels, int havefreq, int wantchannels, int wantfreq)
{
const int frames = *_frames;
float *dst;
float *src;
float *retval = NULL;
float *rechanneled = NULL;
DirkSimple_log("Convert audio from '%s': %d frames, %d channels, %dHz -> %d channels, %dHz", fname, frames, havechannels, havefreq, wantchannels, wantfreq);
if (havechannels == wantchannels) {
rechanneled = pcm;
} else {
dst = rechanneled = (float *) DirkSimple_xmalloc(sizeof (float) * frames * wantchannels);
src = pcm;
if ((havechannels == 1) && (wantchannels == 2)) {
for (int i = 0; i < frames; i++, dst += 2) {
dst[0] = dst[1] = src[i];
}
} else if ((havechannels == 2) && (wantchannels == 1)) {
for (int i = 0; i < frames; i++, src += 2) {
*(dst++) = (src[0] + src[1]) * 0.5f;
}
} else {
DirkSimple_free(rechanneled);
return (float *) invalid_media(fname, "Unsupported audio channel count");
}
}
if (havefreq == wantfreq) {
retval = rechanneled;
} else {
const float scale = ((float) havefreq) / ((float) wantfreq);
const int newframes = (int) (((float) frames) * (1.0f / scale));
dst = retval = (float *) DirkSimple_xmalloc(sizeof (float) * newframes * wantchannels);
src = rechanneled;
if (wantchannels == 1) {
float prev = src[0];
for (int i = 0; i < newframes; i++) {
const int newframe = (int) (((float) i) * scale);
const float newval = src[newframe];
*(dst++) = (prev + newval) * 0.5f;
prev = newval;
}
} else if (wantchannels == 2) {
float prevl = src[0];
float prevr = src[1];
for (int i = 0; i < newframes; i++) {
const int newframe = ((int) (((float) i) * scale)) * 2;
const float newl = src[newframe];
const float newr = src[newframe+1];
*(dst++) = (prevl + newl) * 0.5f;
*(dst++) = (prevr + newr) * 0.5f;
prevl = newl;
prevr = newr;
}
} else {
if (rechanneled != pcm) {
DirkSimple_free(rechanneled);
}
DirkSimple_free(retval);
return (float *) invalid_media(fname, "Unsupported audio channel count");
}
if (rechanneled != pcm) {
DirkSimple_free(rechanneled);
}
*_frames = newframes;
}
return retval;
}
static float *loadwav_from_memory(const char *fname, const uint8_t *buf, int buflen, int *_frames, int *_channels, int *_freq)
{
const uint8_t *ptr = buf;
if (buflen < 50) {
return (float *) invalid_media(fname, "Not a .WAV file");
}
if ((ptr[0] != 'R') || (ptr[1] != 'I') || (ptr[2] != 'F') || (ptr[3] != 'F')) {
return (float *) invalid_media(fname, "Not a .WAV file");
}
ptr += 8; // skip RIFF and size of file in bytes
if ((ptr[0] != 'W') || (ptr[1] != 'A') || (ptr[2] != 'V') || (ptr[3] != 'E')) {
return (float *) invalid_media(fname, "Not a .WAV file");
}
ptr += 4;
if ((ptr[0] != 'f') || (ptr[1] != 'm') || (ptr[2] != 't') || (ptr[3] != ' ')) {
return (float *) invalid_media(fname, "Didn't get expected 'fmt ' tag");
}
ptr += 4;
const uint32_t fmtlen = readui32le(&ptr);
const uint16_t fmttype = readui16le(&ptr);
const uint16_t chans = readui16le(&ptr);
const uint32_t samplerate = readui32le(&ptr);
if (fmtlen != 16) { /* Just handling an exact format for simplicity. */
return (float *) invalid_media(fname, "Unexpected .WAV fmt chunk length");
} else if (fmttype != 3) { /* must be float32 encoded for simplicity. */
return (float *) invalid_media(fname, "Only float32 PCM .WAV files supported");
} else if ((chans != 1) && (chans != 2)) {
return (float *) invalid_media(fname, "Only stereo and mono .WAV files supported");
}
ptr += 8; // don't care about the next two fields.
// skip until we find the data chunk and assume everything else is unnecessary. :O
uint32_t datalen;
while ((ptr[0] != 'd') || (ptr[1] != 'a') || (ptr[2] != 't') || (ptr[3] != 'a')) {
//DirkSimple_log("CHUNK %c%c%c%c", (char) ptr[0], (char) ptr[1], (char) ptr[2], (char) ptr[3]);
ptr += 4;
datalen = readui32le(&ptr);
//DirkSimple_log("CHUNKLEN %d", (int) datalen);
if (datalen > (buflen - ((ptr - buf)))) {
return (float *) invalid_media(fname, "Unexpected .WAV data chunk length");
}
ptr += datalen;
}
ptr += 4;
datalen = readui32le(&ptr);
if (datalen > (buflen - ((ptr - buf)))) {
return (float *) invalid_media(fname, "Unexpected .WAV data chunk length");
}
const int frames = (int) ((datalen / sizeof (float)) / chans);
datalen = frames * sizeof (float) * chans; // so this chops off half-frames.
*_frames = frames;
*_channels = (int) chans;
*_freq = (int) samplerate;
float *pcm = (float *) DirkSimple_xmalloc(datalen);
memcpy(pcm, ptr, datalen);
return pcm;
}
float *DirkSimple_loadwav(const char *fname, int *_numframes, const int wantchannels, int wantfreq)
{
long flen = 0;
int havechannels = 0;
int havefreq = 0;
int frames = 0;
uint8_t *fbuf = DirkSimple_loadmedia(fname, &flen);
float *pcm = loadwav_from_memory(fname, fbuf, flen, &frames, &havechannels, &havefreq);
DirkSimple_free(fbuf);
if (pcm) {
float *cvtpcm = convertwav(fname, pcm, &frames, havechannels, havefreq, wantchannels, wantfreq);
if (cvtpcm != pcm) {
DirkSimple_free(pcm);
pcm = cvtpcm;
}
}
*_numframes = frames;
return pcm;
}
static DirkSimple_Wave *get_cached_wave(const char *name)
{
DirkSimple_Wave *wave = NULL;
int frames = 0;
if (!GAudioChannels || !GAudioFreq) {
DirkSimple_log("Attempting to use wave '%s' before laserdisc is ready!", name);
return NULL;
}
// lowercase the name, just in case.
char *loweredname = DirkSimple_xstrdup(name);
int i;
for (i = 0; name[i]; i++) {
char ch = name[i];
if ((ch >= 'A') && (ch <= 'Z')) {
loweredname[i] = ch - ('A' - 'a');
}
}
name = loweredname;
for (wave = GWaves; wave != NULL; wave = wave->next) {
if (strcmp(wave->name, loweredname) == 0) {
DirkSimple_free(loweredname);
return wave; // already cached.
}
}
// not cached yet, load it from disk.
const size_t slen = strlen(GGameDir) + strlen(name) + 8;
char *fname = (char *) DirkSimple_xmalloc(slen);
snprintf(fname, slen, "%s%s.wav", GGameDir, name);
float *pcm = DirkSimple_loadwav(fname, &frames, GAudioChannels, GAudioFreq);
if (pcm) {
DirkSimple_log("Loaded wave '%s': %d channels, %dHz", fname, GAudioChannels, GAudioFreq);
}
DirkSimple_free(fname);
if (!pcm) {
char errmsg[128];
snprintf(errmsg, sizeof (errmsg), "Failed to load needed wave '%s'. Check your installation?", name);
DirkSimple_panic(errmsg);
}
wave = (DirkSimple_Wave *) DirkSimple_xmalloc(sizeof (DirkSimple_Wave));
wave->name = loweredname;
wave->numframes = frames;
wave->pcm = pcm;
wave->duration_ticks = (uint64_t) ((((float) frames) / ((float) GAudioFreq)) * 1000.0f);
wave->ticks_when_available = 0;
wave->platform_handle = NULL;
wave->next = GWaves;
GWaves = wave;
return wave;
}
// Allocator interface for internal Lua use.
static void *DirkSimple_lua_allocator(void *ud, void *ptr, size_t osize, size_t nsize)
{
if (nsize == 0) {
DirkSimple_free(ptr);
return NULL;
}
return DirkSimple_xrealloc(ptr, nsize);
}
// Read data from a DirkSimple_Io when loading Lua code.
static const char *DirkSimple_lua_reader(lua_State *L, void *data, size_t *size)
{
static char buffer[1024];
DirkSimple_Io *in = (DirkSimple_Io *) data;
const long br = in->read(in, buffer, sizeof (buffer));
if (br <= 0) { // eof or error? (lua doesn't care which?!)
*size = 0;
return NULL;
}
*size = (size_t) br;
return buffer;
}
static void collect_lua_garbage(lua_State *L)
{
lua_gc(L, LUA_GCCOLLECT, 0);
}
static inline int snprintfcat(char **ptr, size_t *len, const char *fmt, ...)
{
int bw = 0;
va_list ap;
va_start(ap, fmt);
bw = vsnprintf(*ptr, *len, fmt, ap);
va_end(ap);
*ptr += bw;
*len -= bw;
return bw;
}
static int luahook_DirkSimple_stackwalk(lua_State *L)
{
const char *errstr = lua_tostring(L, 1);
lua_Debug ldbg;
int i;
if (errstr != NULL) {
DirkSimple_log(errstr);
}
DirkSimple_log("Lua stack backtrace:");
// start at 1 to skip this function.
for (i = 1; lua_getstack(L, i, &ldbg); i++) {
char scratchbuf[256];
char *ptr = scratchbuf;
size_t len = sizeof (scratchbuf);
int bw = snprintfcat(&ptr, &len, "#%d", i-1);
const int maxspacing = 4;
int spacing = maxspacing - bw;
while (spacing-- > 0) {
snprintfcat(&ptr, &len, " ");
}
if (!lua_getinfo(L, "nSl", &ldbg)) {
snprintfcat(&ptr, &len, "???");
DirkSimple_log(scratchbuf);
continue;
}
if (ldbg.namewhat[0]) {
snprintfcat(&ptr, &len, "%s ", ldbg.namewhat);
}
if ((ldbg.name) && (ldbg.name[0])) {
snprintfcat(&ptr, &len, "function %s ()", ldbg.name);
} else {
if (strcmp(ldbg.what, "main") == 0) {
snprintfcat(&ptr, &len, "mainline of chunk");
} else if (strcmp(ldbg.what, "tail") == 0) {
snprintfcat(&ptr, &len, "tail call");
} else {
snprintfcat(&ptr, &len, "unidentifiable function");
}
}
DirkSimple_log(scratchbuf);
ptr = scratchbuf;
len = sizeof (scratchbuf);
for (spacing = 0; spacing < maxspacing; spacing++) {
snprintfcat(&ptr, &len, " ");
}
if (strcmp(ldbg.what, "C") == 0) {
snprintfcat(&ptr, &len, "in native code");
} else if (strcmp(ldbg.what, "tail") == 0) {
snprintfcat(&ptr, &len, "in Lua code");
} else if ( (strcmp(ldbg.source, "=?") == 0) && (ldbg.currentline == 0) ) {
snprintfcat(&ptr, &len, "in Lua code (debug info stripped)");
} else {
snprintfcat(&ptr, &len, "in Lua code at %s", ldbg.short_src);
if (ldbg.currentline != -1)
snprintfcat(&ptr, &len, ":%d", ldbg.currentline);
}
DirkSimple_log(scratchbuf);
}
lua_pushstring(L, errstr ? errstr : "");
return 1;
}
// This just lets you punch in one-liners and Lua will run them as individual
// chunks, but you can completely access all Lua state, including calling C
// functions and altering tables. At this time, it's more of a "console"
// than a debugger. You can do "p DirkSimple_lua_debugger()" from gdb to launch this
// from a breakpoint in native code, or call DirkSimple.debugger() to launch
// it from Lua code (with stacktrace intact, too: type 'bt' to see it).
static int luahook_DirkSimple_debugger(lua_State *L)
{
int origtop;
lua_pushcfunction(L, luahook_DirkSimple_stackwalk);
origtop = lua_gettop(L);
printf("Quick and dirty Lua debugger. Type 'exit' to quit.\n");
while (1) {
char buf[256];
int len = 0;
printf("> ");
fflush(stdout);
if (fgets(buf, sizeof (buf), stdin) == NULL) {
printf("\n\n fgets() on stdin failed: ");
break;
}
len = (int) (strlen(buf) - 1);
while ( (len >= 0) && ((buf[len] == '\n') || (buf[len] == '\r')) ) {
buf[len--] = '\0';
}
if (strcmp(buf, "q") == 0) {
break;
} else if (strcmp(buf, "quit") == 0) {
break;
} else if (strcmp(buf, "exit") == 0) {
break;
} else if (strcmp(buf, "bt") == 0) {
strcpy(buf, "DirkSimple.stackwalk()");
}
if ( (luaL_loadstring(L, buf) != 0) ||
(lua_pcall(L, 0, LUA_MULTRET, -2) != 0) ) {
printf("%s\n", lua_tostring(L, -1));
lua_pop(L, 1);
} else {
printf("Returned %d values.\n", lua_gettop(L) - origtop);
while (lua_gettop(L) != origtop) {
// !!! FIXME: dump details of values to stdout here.
lua_pop(L, 1);
}
printf("\n");
}
}
lua_pop(L, 1);
printf("exiting debugger...\n");
return 0;
}
void DirkSimple_debugger(void)
{
luahook_DirkSimple_debugger(GLua);
}
static void DirkSimple_halt_video(void)
{
if (GDecoder) {
DirkSimple_log("HALT VIDEO: GTicks %u", (unsigned int) GTicks);
GClipStartMs = 0;
GClipStartTicks = GTicks;
GHalted = 1;
GShowingSingleFrame = 0;
GSeekGeneration--; // this just makes it throw away _anything_ until the next seek.
DirkSimple_cleardiscaudio();
DirkSimple_discvideo(GBlankVideoFrame);
}
}
static int luahook_DirkSimple_halt_video(lua_State *L)
{
DirkSimple_halt_video();
return 0;
}
static void DirkSimple_show_single_frame(uint32_t startms)
{
if (GDecoder) {
DirkSimple_log("START SINGLE FRAME: GTicks %u, startms %u", (unsigned int) GTicks, (unsigned int) startms);
GSeekGeneration = THEORAPLAY_seek(GDecoder, startms);
DirkSimple_cleardiscaudio();
GClipStartMs = startms;
GClipStartTicks = 0;
GHalted = 0;
GShowingSingleFrame = 1;
if (GFakeDiscLag) {
DirkSimple_discvideo(GBlankVideoFrame);
GDiscLagUntilTicks = GTicks + DIRKSIMPLE_FAKE_DISC_LAG_TICKS;
}
}
}
static int luahook_DirkSimple_show_single_frame(lua_State *L)
{
const uint32_t startms = (uint32_t) lua_tonumber(L, 1);
DirkSimple_show_single_frame(startms);
return 0;
}
static void DirkSimple_start_clip(uint32_t startms)
{
if (GDecoder) {
DirkSimple_log("START CLIP: GTicks %u, startms %u\n", (unsigned int) GTicks, (unsigned int) startms);
GSeekGeneration = THEORAPLAY_seek(GDecoder, startms);
DirkSimple_cleardiscaudio();
GClipStartMs = startms;
GClipStartTicks = 0;
GHalted = 0;
GShowingSingleFrame = 0;
if (GFakeDiscLag) {
DirkSimple_discvideo(GBlankVideoFrame);
GDiscLagUntilTicks = GTicks + DIRKSIMPLE_FAKE_DISC_LAG_TICKS;
}
}
}
static int luahook_DirkSimple_start_clip(lua_State *L)
{
const uint32_t startms = (uint32_t) lua_tonumber(L, 1);
DirkSimple_start_clip(startms);
return 0;
}
static int luahook_DirkSimple_truncate(lua_State *L)
{
lua_pushinteger(L, (lua_Integer) lua_tonumber(L, 1));
return 1;
}
static int luahook_DirkSimple_to_int(lua_State *L)
{
if (lua_isstring(L, 1)) {
lua_pushinteger(L, atoi(lua_tostring(L, 1)));
} else if (lua_isboolean(L, 1)) {
lua_pushinteger(L, lua_toboolean(L, 1) ? 1 : 0);
} else if (lua_isnumber(L, 1)) {
lua_pushinteger(L, (lua_Integer) lua_tonumber(L, 1));
} else {
lua_pushinteger(L, 0);
}
return 1;
}
static int luahook_DirkSimple_to_bool(lua_State *L)
{
if (lua_isstring(L, 1)) {
lua_pushboolean(L, (strcmp(lua_tostring(L, 1), "true") == 0));
} else if (lua_isboolean(L, 1)) {
lua_pushboolean(L, lua_toboolean(L, 1));
} else if (lua_isnumber(L, 1)) {
lua_pushboolean(L, (lua_tonumber(L, 1) != 0));
} else {
lua_pushboolean(L, 0);
}
return 1;
}
static void register_lua_libs(lua_State *L)
{
// We always need the string and base libraries (although base has a
// few we could trim). The rest you can compile in if you want/need them.
int i;
static const luaL_Reg lualibs[] = {
{"_G", luaopen_base},
{LUA_STRLIBNAME, luaopen_string},
{LUA_TABLIBNAME, luaopen_table},
//{LUA_LOADLIBNAME, luaopen_package},
//{LUA_IOLIBNAME, luaopen_io},
//{LUA_OSLIBNAME, luaopen_os},
//{LUA_MATHLIBNAME, luaopen_math},
//{LUA_DBLIBNAME, luaopen_debug},
//{LUA_BITLIBNAME, luaopen_bit32},
//{LUA_COLIBNAME, luaopen_coroutine},
};
for (i = 0; i < (sizeof (lualibs) / sizeof (lualibs[0])); i++) {
luaL_requiref(L, lualibs[i].name, lualibs[i].func, 1);
lua_pop(L, 1); // remove lib
}
}
static int luahook_panic(lua_State *L)
{
const char *errstr;
luahook_DirkSimple_stackwalk(L);
errstr = lua_tostring(L, -1);
if (errstr == NULL) {
errstr = "Something disastrous happened, aborting."; // doesn't actually return.
}
DirkSimple_panic(errstr);
return 1; // doesn't actually return, but stackwalk pushed a return value, so return 1 for hygiene purposes.
}
static int luahook_DirkSimple_log(lua_State *L)
{
const char *str = lua_tostring(L, 1);
DirkSimple_log("%s", str);
return 0;
}
static RenderCommand *new_render_command(const RenderPrimitive prim)
{
if (GNumRenderCommands >= GNumAllocatedRenderCommands) {
if (GNumAllocatedRenderCommands == 0) {
GNumAllocatedRenderCommands = 32;
} else {
GNumAllocatedRenderCommands *= 2;
}
GRenderCommands = DirkSimple_xrealloc(GRenderCommands, sizeof (RenderCommand) * GNumAllocatedRenderCommands);
}
RenderCommand *retval = &GRenderCommands[GNumRenderCommands++];
retval->prim = prim;
return retval;
}
static int luahook_DirkSimple_clear_screen(lua_State *L)
{
RenderCommand *cmd = new_render_command(RENDPRIM_CLEAR);
cmd->data.clear.r = (uint8_t) lua_tonumber(L, 1);
cmd->data.clear.g = (uint8_t) lua_tonumber(L, 2);
cmd->data.clear.b = (uint8_t) lua_tonumber(L, 3);
return 0;
}
static int luahook_DirkSimple_draw_sprite(lua_State *L)
{
RenderCommand *cmd = new_render_command(RENDPRIM_SPRITE);
snprintf(cmd->data.sprite.name, sizeof (cmd->data.sprite.name), "%s", lua_tostring(L, 1));
cmd->data.sprite.sx = (int32_t) lua_tonumber(L, 2);
cmd->data.sprite.sy = (int32_t) lua_tonumber(L, 3);
cmd->data.sprite.sw = (int32_t) lua_tonumber(L, 4);
cmd->data.sprite.sh = (int32_t) lua_tonumber(L, 5);