-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.lua
1942 lines (1722 loc) · 54.2 KB
/
app.lua
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
local ffi = require 'ffi'
local sdl = require 'ffi.req' 'sdl'
local table = require 'ext.table'
local path = require 'ext.path'
local class = require 'ext.class'
local math = require 'ext.math'
local string = require 'ext.string'
local range = require 'ext.range'
local template = require 'template'
local matrix = require 'matrix.ffi'
local Image = require 'image'
local gl = require 'gl'
local GLTex2D = require 'gl.tex2d'
local GLProgram = require 'gl.program'
local GLGeometry = require 'gl.geometry'
local GLSceneObject = require 'gl.sceneobject'
local GLArrayBuffer = require 'gl.arraybuffer'
local GLFBO = require 'gl.fbo'
local glreport = require 'gl.report'
local vec2i = require 'vec-ffi.vec2i'
local vec2f = require 'vec-ffi.vec2f'
local vec3f = require 'vec-ffi.vec3f'
local getTime = require 'ext.timer'.getTime
local ig = require 'imgui'
local Audio = require 'audio'
local AudioSource = require 'audio.source'
local AudioBuffer = require 'audio.buffer'
local Player = require 'sand-attack.player'
local SandModel = require 'sand-attack.sandmodel.sandmodel'
local readDemo = require 'sand-attack.serialize'.readDemo
local writeDemo = require 'sand-attack.serialize'.writeDemo
local sandModelClassNames = require 'sand-attack.sandmodel.all'.classNames
local sandModelClassForName = require 'sand-attack.sandmodel.all'.classForName
ffi.cdef[[
// what type to use for time?
// 60 fps ...
// 2 bytes = 65535 ticks = 1092 seconds @ 60 fps = 18.2 minutes
// 4 bytes = 4294967295 ticks = 71582788.25 seconds = 1193046.4708333 minutes = 19884.107847222 hours = 828.50449363426 days = 27.388578301959 months = 2.268321680039 years
typedef uint32_t gameTick_t;
typedef uint64_t randSeed_t;
]]
-- I'm trying to make reproducible random #s
-- it is reproducible up to the generation of the next pieces
-- but the very next piece after will always be dif
-- this maybe is due to the sand toppling also using rand?
-- but why wouldn't that random() call even be part of the determinism?
-- seems something external must be contributing?
--[[ TODO put this in ext? or its own lib?
local RNG = class()
-- TODO max and the + and % constants are bad, fix them
RNG.max = 2147483647ull
require 'ffi.req' 'c.time'
function RNG:init(seed)
self.seed = ffi.cast('uint64_t', tonumber(seed) or ffi.C.time(nil))
end
function RNG:next(max)
self.seed = self.seed * 1103515245ull + 12345ull
return self.seed % (self.max + 1)
end
function RNG:__call(max)
if max then
return tonumber(self:next() % max) + 1 -- +1 for lua compat
else
return tonumber(self:next()) / tonumber(self.max)
end
end
--]]
-- [[ Lua code says: xoshira256** algorithm
-- but is only a singleton...
local RNG = class()
function RNG:init(seed)
math.randomseed(tonumber(seed))
end
function RNG:__call(...)
return math.random(...)
end
--]]
local mytolua = require 'sand-attack.serialize'.tolua
local myfromlua = require 'sand-attack.serialize'.fromlua
local App = require 'imguiapp':subclass()
App.title = 'Sand Attack'
App.sdlInitFlags = bit.bor(
sdl.SDL_INIT_VIDEO,
sdl.SDL_INIT_JOYSTICK
)
App.useAudio = true -- set to false to disable audio altogether
App.showFPS = false -- show fps in gui / console
App.showDebug = false -- show some more debug stuff
local dontCheckForLinesEver = false -- means don't ever ever check for lines. used for fps testing the sand topple simulation.
App.updateInterval = 1/60
--App.updateInterval = 1/120
--App.updateInterval = 0
App.defaultColors = table{
{1,0,0},
{0,0,1},
{0,1,0},
{1,1,0},
{1,0,1},
{0,1,1},
{1,1,1},
}
-- assumes we have full 8 bits of resolution in th alpha channel (not always the case .... ?)
App.maxColors = 255
App.maxAudioDist = 10
App.chainDuration = 2
App.lineFlashDuration = 1
App.lineNumFlashes = 5
App.cfgfilename = 'config.lua'
App.highScorePath = 'highscores'
function App:initGL(...)
App.super.initGL(self, ...)
-- allow keys to navigate menu
-- TODO how to make it so player keys choose menus, not just space bar/
-- or meh?
local igio = ig.igGetIO()
igio[0].ConfigFlags = bit.bor(
igio[0].ConfigFlags,
ig.ImGuiConfigFlags_NavEnableKeyboard,
ig.ImGuiConfigFlags_NavEnableGamepad
)
igio[0].FontGlobalScale = 2
-- [[ imgui custom font
if not self.skipCustomFont then
xpcall(function()
--local fontfile = 'font/moenstrum.ttf' -- no numbers
--local fontfile = 'font/PixelGamer-Regular.otf' -- no numbers
--local fontfile = 'font/goldingots.ttf'
local fontfile = 'font/Billow twirl Demo.ttf'
self.fontAtlas = ig.ImFontAtlas_ImFontAtlas()
self.font = ig.ImFontAtlas_AddFontFromFileTTF(self.fontAtlas, fontfile, 16, nil, nil)
-- just change the font, and imgui complains that you need to call FontAtlas::Build() ...
assert(ig.ImFontAtlas_Build(self.fontAtlas))
-- just call FontAtlas::Build() and you just get white blobs ...
-- is this proper behavior? or a bug in imgui?
-- you have to download the font texture pixel data, make a GL texture out of it, and re-upload it
local width = ffi.new('int[1]')
local height = ffi.new('int[1]')
local bpp = ffi.new('int[1]')
local outPixels = ffi.new('unsigned char*[1]')
-- GL_LUMINANCE textures are deprecated ... khronos says use GL_RED instead ... meaning you have to write extra shaders for greyscale textures to be used as greyscale in opengl ... ugh
--ig.ImFontAtlas_GetTexDataAsAlpha8(self.fontAtlas, outPixels, width, height, bpp)
ig.ImFontAtlas_GetTexDataAsRGBA32(self.fontAtlas, outPixels, width, height, bpp)
self.fontTex = GLTex2D{
internalFormat = gl.GL_RGBA,
--internalFormat = gl.GL_RED,
format = gl.GL_RGBA,
--format = gl.GL_RED,
width = width[0],
height = height[0],
type = gl.GL_UNSIGNED_BYTE,
data = outPixels[0],
minFilter = gl.GL_NEAREST,
magFilter = gl.GL_NEAREST,
wrap = {
s = gl.GL_CLAMP_TO_EDGE,
t = gl.GL_CLAMP_TO_EDGE,
},
}
require 'ffi.req' 'c.stdlib' -- free()
ffi.C.free(outPixels[0]) -- just betting here I have to free this myself ...
ig.ImFontAtlas_SetTexID(self.fontAtlas, ffi.cast('ImTextureID', self.fontTex.id))
end, function(err)
print(err)
print(debug.traceback())
self.fontAtlas = nil
self.font = nil
self.fontTex = nil
end)
end
--]]
-- load config if it exists
xpcall(function()
local cfgpath = path(self.cfgfilename)
if cfgpath:exists() then
self.cfg = myfromlua(assert(cfgpath:read()))
end
end, function(err)
print('failed to read lua from file '..tostring(self.cfgfilename)..'\n'
..tostring(err)..'\n'
..debug.traceback())
end)
self.cfg = self.cfg or {}
-- load high scores if it exists
self.highscores = {}
-- TODO WARNING
-- for some reason in the Windows version, distributable ONLY (not in runtime setup), errors thrown in the app ctor are being hidden.
-- especially starting right around here ...
path(self.highScorePath):mkdir()
for f in path(self.highScorePath):dir() do
if f.path:match'%.demo$' then
table.insert(
self.highscores,
readDemo(self.highScorePath..'/'..f)
)
end
end
-- board size is 80 x 144 visible
-- piece is 4 blocks arranged
-- blocks are 8 x 8 by default
self.pieceSizeInBlocks = vec2i(4,4) -- fixed
--self.cfg.voxelsPerBlock = self.cfg.voxelsPerBlock or 8 -- original
self.cfg.voxelsPerBlock = self.cfg.voxelsPerBlock or 16 -- double
--self.cfg.voxelsPerBlock = self.cfg.voxelsPerBlock or 32 -- quadruple
self.cfg.effectVolume = self.cfg.effectVolume or 1
self.cfg.backgroundVolume = self.cfg.backgroundVolume or .3
self.cfg.startLevel = self.cfg.startLevel or 1
self.cfg.movedx = self.cfg.movedx or 1 -- TODO configurable
self.cfg.dropSpeed = self.cfg.dropSpeed or 5
self.cfg.sandModel = self.cfg.sandModel or sandModelClassNames[1]
self.cfg.speedupCoeff = self.cfg.speedupCoeff or .007
self.cfg.toppleChance = self.cfg.toppleChance or 1
self.cfg.playerKeys = self.cfg.playerKeys or {}
self.cfg.screenButtonRadius = self.cfg.screenButtonRadius or .05
if self.cfg.continuousDrop == nil then
self.cfg.continuousDrop = true
end
if not self.cfg.colors then
self.cfg.colors = {}
end
self.cfg.numColors = self.cfg.numColors or 4
for i=1,self.cfg.numColors do
self.cfg.colors[i] = self.cfg.colors[i] or self:getDefaultColor(i)
end
self.cfg.boardWidthInBlocks = self.cfg.boardWidthInBlocks or 10 -- original
self.cfg.boardHeightInBlocks = self.cfg.boardHeightInBlocks or 18 -- original
--[[
self.cfg.boardWidthInBlocks = self.cfg.boardWidthInBlocks or 20
self.cfg.boardHeightInBlocks = self.cfg.boardHeightInBlocks or 25
--]]
--[[
self.cfg.boardWidthInBlocks = self.cfg.boardWidthInBlocks or 10
self.cfg.boardHeightInBlocks = self.cfg.boardHeightInBlocks or 45
--]]
--[[
self.cfg.boardWidthInBlocks = self.cfg.boardWidthInBlocks or 64
self.cfg.boardHeightInBlocks = self.cfg.boardHeightInBlocks or 64
--]]
self.cfg.numNextPieces = self.cfg.numNextPieces or 3
-- hmm ... don't save this ... instead generate it new every game ... unless specified ... hmmm ....
-- but do allow editing it in the config screen ... hmm ....
-- and do allow saving it in highscores and in demos ...
self.cfg.randseed = self.cfg.randseed or ffi.new('randSeed_t', -1)
self.cfg.numPlayers = 1
self.fps = 0
self.numSandVoxels = 0
self.loseScreenDuration = 3
local buttonImg = Image(256, 256, 4, 'unsigned char', function(i,j)
-- (i,j) are in [0,255)^2
local x = ((i+.5)/256 - .5) * 2
local y = ((j+.5)/256 - .5) * 2
-- (x,y) are in [-1,1]^2 (plus or minus 1/n ...)
local r2 = x*x + y*y
if r2 < 1 and r2 > .9*.9 then
return 255,255,255,255
else
return 0,0,0,0
end
end)
self.buttonTex = GLTex2D{
image = buttonImg,
wrap = {
s = gl.GL_CLAMP_TO_EDGE,
t = gl.GL_CLAMP_TO_EDGE,
},
minFilter = gl.GL_NEAREST,
magFilter = gl.GL_LINEAR,
}
self.youloseTex = GLTex2D{
image = Image'tex/youlose.png':flip(),
wrap = {
s = gl.GL_CLAMP_TO_EDGE,
t = gl.GL_CLAMP_TO_EDGE,
},
minFilter = gl.GL_NEAREST,
magFilter = gl.GL_NEAREST,
}
self.splashTex = GLTex2D{
image = Image'tex/splash.png':flip(),
wrap = {
s = gl.GL_CLAMP_TO_EDGE,
t = gl.GL_CLAMP_TO_EDGE,
},
minFilter = gl.GL_NEAREST,
magFilter = gl.GL_NEAREST,
}
--[[ assign a view but not a view setup call every frame
local View = require 'glapp.view'
self.view = View()
self.projMat = self.view.projMat
self.mvMat = self.view.mvMat
self.mvProjMat = self.view.projMat
--]]
-- [[
self.projMat = matrix({4,4}, 'float'):zeros():setIdent()
self.mvMat = matrix({4,4}, 'float'):zeros():setIdent()
self.mvProjMat = matrix({4,4}, 'float'):zeros():setIdent()
--]]
local vtxbufCPU = ffi.new('vec2f_t[4]', {
vec2f(0,0),
vec2f(1,0),
vec2f(0,1),
vec2f(1,1),
})
self.quadVertexBuf = GLArrayBuffer{
size = ffi.sizeof(vtxbufCPU),
data = vtxbufCPU,
}:unbind()
self.quadGeom = GLGeometry{
mode = gl.GL_TRIANGLE_STRIP,
count = 4,
}
self.displayShader = GLProgram{
version = 'latest',
precision = 'best',
vertexCode = [[
in vec2 vertex;
out vec2 texcoordv;
uniform mat4 mvProjMat;
void main() {
texcoordv = vertex;
gl_Position = mvProjMat * vec4(vertex, 0., 1.);
}
]],
fragmentCode = [[
in vec2 texcoordv;
out vec4 fragColor;
uniform sampler2D tex;
uniform bool useAlphaTest;
void main() {
fragColor = texture(tex, texcoordv);
if (useAlphaTest && fragColor.a == 0.) discard;
}
]],
uniforms = {
tex = 0,
useAlphaTest = false,
},
}:useNone()
self.splashScreenSceneObj = GLSceneObject{
geometry = self.quadGeom,
program = self.displayShader,
attrs = {
vertex = self.quadVertexBuf,
},
texs = {
self.splashTex,
},
}
-- same as splashScreenSceneObj but without texs
-- I could separate the attr+shader+geom from texs for the sake of minimizing VAO creation...
self.displayQuadSceneObj = GLSceneObject{
geometry = self.quadGeom,
program = self.displayShader,
attrs = {
vertex = self.quadVertexBuf,
},
}
self.populatePieceShader = GLProgram{
version = 'latest',
precision = 'best',
vertexCode = [[
in vec2 vertex;
out vec2 texcoordv;
uniform mat4 mvProjMat;
void main() {
texcoordv = vertex;
gl_Position = mvProjMat * vec4(vertex, 0., 1.);
}
]],
fragmentCode = [[
in vec2 texcoordv;
out vec4 fragColor;
uniform sampler2D tex;
uniform sampler2D randtex;
uniform vec4 color;
uniform vec3 pieceSize; //.z = voxelsPerBlock
void main() {
vec4 dstc = texture(tex, texcoordv) * color;
vec2 ij = texcoordv * pieceSize.xy;
float voxelsPerBlock = pieceSize.z;
vec2 uv = mod(ij, voxelsPerBlock );
float c = max(
abs(uv.x - voxelsPerBlock*.5),
abs(uv.y - voxelsPerBlock*.5)
) / (voxelsPerBlock*.5);
float l = texture(randtex, texcoordv).r * .25 + .75;
l *= .25 + .75 * sqrt(1. - c*c);
fragColor = vec4(dstc.xyz * l, dstc.w);
}
]],
uniforms = {
tex = 0,
randtex = 1,
},
}:useNone()
self.updatePieceOutlineShader = GLProgram{
version = 'latest',
precision = 'best',
vertexCode = [[
in vec2 vertex;
out vec2 texcoordv;
uniform mat4 mvProjMat;
void main() {
texcoordv = vertex;
gl_Position = mvProjMat * vec4(vertex, 0., 1.);
}
]],
fragmentCode = [[
in vec2 texcoordv;
out vec4 fragColor;
uniform sampler2D pieceTex;
uniform ivec2 pieceSize;
uniform ivec3 pieceOutlineSize; //.z = pieceOutlineRadius;
uniform vec3 color;
float lenSq(vec2 v) {
return dot(v,v);
}
void main() {
float maxDistSq = float(pieceOutlineSize.x + pieceOutlineSize.y);
float bestDistSq = maxDistSq;
int pieceOutlineRadius = pieceOutlineSize.z;
ivec2 ij = ivec2(texcoordv * vec2(pieceOutlineSize));
ivec2 ofs;
for (ofs.y = -pieceOutlineRadius; ofs.y <= pieceOutlineRadius; ++ofs.y) {
for (ofs.x = -pieceOutlineRadius; ofs.x <= pieceOutlineRadius; ++ofs.x) {
ivec2 xy = ij - pieceOutlineRadius + ofs;
if (xy.x >= 0 && xy.x < pieceSize.x &&
xy.y >= 0 && xy.y < pieceSize.y
) {
vec4 c = texelFetch(pieceTex, xy, 0);
if (c != vec4(0.)) {
float distSq = max(1., lenSq(vec2(ofs)));
bestDistSq = min(bestDistSq, distSq);
}
}
}
}
if (bestDistSq < maxDistSq) {
float frac = 1. / bestDistSq;
fragColor = vec4(color * frac, 1.);
} else {
fragColor = vec4(0.);
}
}
]],
uniforms = {
pieceTex = 0,
},
}:useNone()
self.sounds = {}
if self.useAudio then
xpcall(function()
self.audio = Audio()
self.audioSources = table()
self.audioSourceIndex = 0
self.audio:setDistanceModel'linear clamped'
for i=1,31 do -- 31 for DirectSound, 32 for iphone, infinite for all else?
local src = AudioSource()
src:setReferenceDistance(1)
src:setMaxDistance(self.maxAudioDist)
src:setRolloffFactor(1)
self.audioSources[i] = src
end
self.bgMusicFiles = table()
for f in path'music':dir() do
if f.path:match'%.ogg$' then
self.bgMusicFiles:insert('music/'..f)
end
end
self.bgMusicFileName = self.bgMusicFiles:pickRandom()
if self.bgMusicFileName then
self.bgMusic = self:loadSound(self.bgMusicFileName)
self.bgAudioSource = AudioSource()
self.bgAudioSource:setBuffer(self.bgMusic)
self.bgAudioSource:setLooping(true)
-- self.usercfg
self.bgAudioSource:setGain(self.cfg.backgroundVolume)
self.bgAudioSource:play()
end
end, function(err)
print('failed to init audio'
..tostring(err)..'\n'
..debug.traceback())
self.audio = nil
self.useAudio = false -- or just test audio's existence?
end)
end
local SplashScreenMenu = require 'sand-attack.menu.splashscreen'
self.menustate = SplashScreenMenu(self)
-- play a demo in the background when the game starts
self:reset{
playingDemoRecord = readDemo'splash.demo',
}
glreport'here'
end
function App:getDefaultColor(i)
if i <= #self.defaultColors then
return {table.unpack(self.defaultColors[i])}
else
return {vec3f():map(function() return math.random() end):normalize():unpack()}
end
end
function App:makeTexFromImage(img)
local tex = GLTex2D{
internalFormat = gl.GL_RGBA,
width = tonumber(img.width),
height = tonumber(img.height),
format = gl.GL_RGBA,
type = gl.GL_UNSIGNED_BYTE,
wrap = {
s = gl.GL_CLAMP_TO_EDGE,
t = gl.GL_CLAMP_TO_EDGE,
},
minFilter = gl.GL_NEAREST,
magFilter = gl.GL_NEAREST,
data = img.buffer, -- stored
}
:unbind()
tex.image = img
return tex
end
-- static method
function App:makeTexWithBlankImage(size)
local img = Image(size.x, size.y, 4, 'unsigned char')
ffi.fill(img.buffer, 4 * size.x * size.y)
return self:makeTexFromImage(img)
end
-- called from App:reset()
function App:makePieceImage(s)
s = string.split(s, '\n')
local img = Image(self.pieceSize.x, self.pieceSize.y, 4, 'unsigned char')
local ptr = ffi.cast('uint32_t*', img.buffer)
ffi.fill(ptr, 4 * img.width * img.height)
local vpb = self.playcfg.voxelsPerBlock
for j=0,self.pieceSizeInBlocks.y-1 do
for i=0,self.pieceSizeInBlocks.x-1 do
if s[j+1]:sub(i+1,i+1) == '#' then
for u=0,vpb-1 do
for v=0,vpb-1 do
ptr[(u + vpb * i) + img.width * (v + vpb * j)] = 0xffffffff
end
end
end
end
end
return self:makeTexFromImage(img)
end
function App:loadSound(filename)
if not filename then error("warning: couldn't find sound file "..searchfilename) end
local sound = self.sounds[filename]
if not sound then
sound = AudioBuffer(filename)
self.sounds[filename] = sound
end
return sound
end
function App:getNextAudioSource()
if #self.audioSources == 0 then return end
local startIndex = self.audioSourceIndex
repeat
self.audioSourceIndex = self.audioSourceIndex % #self.audioSources + 1
local source = self.audioSources[self.audioSourceIndex]
if not source:isPlaying() then
return source
end
until self.audioSourceIndex == startIndex
end
function App:playSound(name, volume, pitch)
if not self.useAudio then return end
local source = self:getNextAudioSource()
if not source then
print('all audio sources used')
return
end
local sound = self:loadSound(name)
source:setBuffer(sound)
source.volume = volume -- save for later
source:setGain((volume or 1) * self.cfg.effectVolume)
source:setPitch(pitch or 1)
source:setPosition(0, 0, 0)
source:setVelocity(0, 0, 0)
source:play()
return source
end
function App:saveConfig()
writeDemo(self.cfgfilename, self.cfg)
end
-- called by App:reset
-- would be called by NewGameMenu:updateGUI once I sort out .cfg vs .playcfg
function App:updateGameScale()
self.gameScaleFloat = self.playcfg.voxelsPerBlock / 8
self.gameScale = math.ceil(self.gameScaleFloat)
self.updatesPerFrame = self.gameScale
end
function App:reset(args)
args = args or {}
self:saveConfig()
self.playingDemo = nil
self.recordingDemo = nil
--[[
demoPlayback blob format:
struct {
gameTick_t gameTick;
uint8_t buttonFlags[ceil(numPlayers * #gameKeyNames / 8)];
} events[];
... packed
--]]
if not args.dontRecordOrPlay then
if args.playingDemoRecord then
xpcall(function()
local data = assert(args.playingDemoRecord.demoPlayback)
local ptr = ffi.cast('char*', data)
-- TODO why reinvent the wheel. just use fread/feof.
-- TODO rename this also to something else, idk what
self.playingDemo = setmetatable({
ptr = ptr,
data = data,
index = 0,
size = #data,
}, {
__index = {
-- without advancing, returns ptr
get = function(self, size)
if self.index + size > self.size then
return nil, "tried to read past end of file"
end
return self.ptr + self.index
end,
-- return cdata value and advance
read = function(self, ctype)
local resultsize = ffi.sizeof(ctype)
local result = self:get(resultsize)
if not result then return result end
self.index = self.index + resultsize
return ffi.cast(ctype..'*', result)[0]
end,
-- return str value and advance
readstr = function(self, len)
len = len or ffi.C.strlen(self.ptr + self.index)
local s, msg = self:get(len)
if not s then return s, msg end
self.index = self.index + len
return ffi.string(s, len)
end,
},
})
self.playingDemo.config = args.playingDemoRecord
-- put currently-playing cfg in playcfg
self.playcfg = self.playingDemo.config
end, function(err)
print('failed to load demo\n'
..tostring(err)..'\n'
..debug.traceback())
self.playingDemo = nil
end)
end
if not self.playingDemo then
--print('recording demo...')
-- ... then record
self.recordingDemo = table()
-- NOTICE THIS IS A SHALLOW COPY
-- that means subtables (player keys, custom colors) won't be copied
-- not sure if i should bother since neither of those things are used by playcfg but ....
self.playcfg = table(self.cfg):setmetatable(nil)
end
end
local playcfg = self.playcfg
-- used only for writing demo file
self.recordingEventSize = ffi.sizeof'gameTick_t' + math.ceil(playcfg.numPlayers * #Player.gameKeyNames / 8)
-- used for reading and writing
self.recordingEvent = ffi.new('uint8_t[?]', self.recordingEventSize)
--[[ print event list
if self.playingDemo then
print('all upcoming events:')
for i=0,#self.playingDemo.data-1,self.recordingEventSize do
local event = self.playingDemo.ptr + i
io.write(('... %08x'):format(ffi.cast('gameTick_t*', event)[0]))
for i=ffi.sizeof'gameTick_t',self.recordingEventSize-1 do
io.write((' %02x'):format(event[i]))
end
end
print()
end
--]]
-- what happens if the replay config is bad?
-- should we lose the old config?
-- or what if it's good?
-- should we allow the demo config to overwrite the previous config?
-- ....
-- thinking more about it, mayb the whoel of :reset() should be wrapped in that xpcall
-- in case the base config.lua file itself was corrupted
self.rng = RNG(playcfg.randseed)
self:updateGameScale()
-- init pieces
self.pieceSize = self.pieceSizeInBlocks * playcfg.voxelsPerBlock
self.pieceFBO = GLFBO{width=self.pieceSize.x, height=self.pieceSize.y}
:unbind()
self.pieceOutlineSize = self.pieceSize + 2 * self.pieceOutlineRadius
self.pieceOutlineFBO = GLFBO{width=self.pieceOutlineSize.x, height=self.pieceOutlineSize.y}
:unbind()
do
local size = self.pieceSize
local img = Image(size.x, size.y, 4, 'unsigned char')
local ptr = ffi.cast('uint32_t*', img.buffer)
for j=0,size.y-1 do
for i=0,size.x-1 do
ptr[0] = bit.bor(
self.rng(0,255),
bit.lshift(self.rng(0,255), 8),
bit.lshift(self.rng(0,255), 16),
bit.lshift(self.rng(0,255), 24)
)
ptr = ptr + 1
end
end
self.pieceRandomColorTex = self:makeTexFromImage(img)
end
self.pieceSourceTexs = table{
[[
#
#
#
#
]],
[[
#
#
##
]],
[[
#
#
##
]],
[[
##
##
]],
[[
#
###
]],
[[
#
##
#
]],
[[
#
##
#
]],
}:mapi(function(s)
return self:makePieceImage(s)
end)
-- init board
self.sandSize = vec2i(
playcfg.boardWidthInBlocks * playcfg.voxelsPerBlock,
playcfg.boardHeightInBlocks * playcfg.voxelsPerBlock)
local w, h = self.sandSize:unpack()
self.loseTime = nil
local sandModelClass = assert(sandModelClassForName[playcfg.sandModel])
self.sandmodel = sandModelClass(self)
-- I only really need to recreate the sand & flash texs if the board size changes ...
self.flashTex = self:makeTexWithBlankImage(self.sandSize)
-- and I only really need to recreate these if the piece size changes ...
self.rotPieceTex = self:makeTexWithBlankImage(self.pieceSize)
self.nextPieces = range(playcfg.numNextPieces):mapi(function(i)
local tex = self:makeTexWithBlankImage(self.pieceSize)
return {tex=tex}
end)
self.sandmodel:reset()
-- TODO don't store the custom colors in the config file unless they've been defined
-- especially now that it's a model file
self.gameColors = table.sub(playcfg.colors, 1, playcfg.numColors):mapi(function(c) return vec3f(c) end) -- colors used now
assert(#self.gameColors == playcfg.numColors) -- menu system should handle this
self.players = range(playcfg.numPlayers):mapi(function(i)
return Player{index=i, app=self}
end)
-- populate the nextpieces via rotation
for i=1,#self.nextPieces do
self:newPiece(self.players[1])
end
-- populate the players pieces
for _,player in ipairs(self.players) do
self:newPiece(player)
end
self.lastUpdateTime = getTime()
self.gameTime = 0
self.gameTick = ffi.new('gameTick_t', 0)
self.fallTick = 0
self.lastLineTime = -math.huge
self.score = 0
self.lines = 0
self.level = playcfg.startLevel
self.scoreChain = 0
self:updateFallSpeed()
-- debugging:
--self.sandmodel:test()
end
-- called in App:reset() and App:updateGame() upon level up
function App:updateFallSpeed()
-- https://harddrop.com/wiki/Tetris_Worlds
local maxSpeedLevel = 13 -- fastest level .. no faster is permitted
local effectiveLevel = math.min(self.level, maxSpeedLevel)
-- TODO make this curve customizable
local secondsPerRow = (.8 - ((effectiveLevel-1.)*self.playcfg.speedupCoeff))^(effectiveLevel-1.)
local secondsPerLine = secondsPerRow / self.playcfg.voxelsPerBlock
-- how many ticks to wait before dropping a piece
self.ticksToFall = secondsPerLine / self.updateInterval
--print('effectiveLevel', effectiveLevel, 'secondsPerRow', secondsPerRow, 'scondsPerLin', secondsPerLine, 'ticksToFall', self.ticksToFall)
end
-- called by App:newPiece()
-- fill in a new piece texture
-- generate it based on the piece template
function App:populatePiece(args)
local srctex = self.pieceSourceTexs:pickRandom()
local colorIndex = self.rng(#self.gameColors) -- 1..n for n colors
local color = self.gameColors[colorIndex]
local alpha = colorIndex/#self.gameColors -- [1/n, 1]
local fbo = self.pieceFBO
local dsttex = args.tex
local shader = self.populatePieceShader
local sceneObj = self.displayQuadSceneObj
gl.glViewport(0, 0, self.pieceSize.x, self.pieceSize.y)
fbo:bind()
:setColorAttachmentTex2D(dsttex.id)
local res, err = fbo.check()
if not res then print(err) end
shader:use()
sceneObj:enableAndSetAttrs()
self.mvProjMat:setOrtho(0, 1, 0, 1, -1, 1)
gl.glUniformMatrix4fv(
shader.uniforms.mvProjMat.loc,
1,
gl.GL_FALSE,
self.mvProjMat.ptr)
gl.glUniform4f(shader.uniforms.color.loc, color.x, color.y, color.z, alpha)
gl.glUniform3f(shader.uniforms.pieceSize.loc,
self.pieceSize.x,
self.pieceSize.y,
self.playcfg.voxelsPerBlock)
srctex:bind(0)
self.pieceRandomColorTex:bind(1)
gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4)
self.pieceRandomColorTex:unbind(1)
srctex:unbind(0)
sceneObj:disableAttrs()
shader:useNone()
gl.glReadPixels(
0, --GLint x,
0, --GLint y,
self.pieceSize.x, --GLsizei width,
self.pieceSize.y, --GLsizei height,
gl.GL_RGBA, --GLenum format,
gl.GL_UNSIGNED_BYTE, --GLenum type,
dsttex.image.buffer) --void *pixels
fbo:unbind()
gl.glViewport(0, 0, self.width, self.height)
end
function App:newPiece(player)
local w, h = self.sandSize:unpack()
local lastPiece = self.nextPieces:last()
-- cycle pieces
do
local tex = player.pieceTex
local np1 = self.nextPieces[1]
player.pieceTex = np1.tex
for i=1,#self.nextPieces-1 do
local np = self.nextPieces[i]
local np2 = self.nextPieces[i+1]
np.tex = np2.tex
end
lastPiece.tex = tex
end
self:populatePiece(lastPiece)
--]]
self:updatePieceTex(player)
player.piecePos = vec2f((w-self.pieceSize.x)*.5, h-1)
player.piecePosLast = vec2f(player.piecePos)
if self.sandmodel:testPieceMerge(player) then
-- but this means you can pause mid-losing ... meh
self.loseTime = self.thisTime
end
end
local function vec3fto4ub(v)