-
Notifications
You must be signed in to change notification settings - Fork 36
/
nico.nim
3338 lines (2797 loc) · 93.3 KB
/
nico.nim
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
import nico/backends/common
import tables
import unicode
import nico/keycodes
export nico.keycodes
import nico/spritedraw
export spritedraw
when not defined(js):
import nico/backends/sdl2 as backend
import os
export StencilMode
export StencilBlend
export EventListener
export Palette
export SynthData
export SynthDataStep
export synthDataToString
export synthDataFromString
export synthIndex
export waitUntilReady
export getRealDt
export profileGetLastStats
export profileGetLastStatsPeak
export profileCollect
export profileBegin
export profileEnd
export ProfilerNode
export profileHistory
export errorPopup
export setClipboardText
# Audio
export joinPath
export loadSfx
export loadMusic
export sfx
export music
export getMusic
export synth
export SfxId
export setAudioCallback
export setAudioBufferSize
export audioInSample
export audioOut
export synthUpdate
export synthShape
export SynthShape
export vibrato
export glide
export wavData
export pitchbend
export pitch
export volume
export musicGetPos
export musicSeek
# shader stuff
export setShaderBool
export setShaderFloat
export setLinearFilter
export clipMinX,clipMinY,clipMaxX,clipMaxY
export currentColor
export cameraX,cameraY
export debug
import nico/controller
export NicoController
export NicoControllerKind
export NicoAxis
export NicoButton
export ColorId
export startTextInput
export stopTextInput
export isTextInput
export btn
export btnp
export btnpr
export btnup
#export axis
#export axisp
export TouchState
export Touch
import nico/ringbuffer
import math
export pow
import algorithm
import json
export math.sin
export math.sqrt
export math.PI
export math.TAU
import random
export shuffle
import times
import strscans
import strutils
## Public API
export Event
export EventKind
export timeStep
export Pint
export toPint
export Pfloat
export toPfloat
export setKeyMap
export basePath
export assetPath
export writePath
export loadConfig
export saveConfig
export updateConfigValue
export getConfigValue
# Fonts
proc getFont*(): FontId
proc setFont*(fontId: FontId)
# Printing text
proc glyph*(c: Rune, x,y: Pint, scale: Pint = 1): Pint {.discardable, inline.}
proc glyph*(c: char, x,y: Pint, scale: Pint = 1): Pint {.discardable, inline.}
proc cursor*(x,y: Pint) # set cursor position
proc print*(text: string, scale: Pint = 1) # print at cursor
proc print*(text: string, x,y: Pint, scale: Pint = 1)
proc printc*(text: string, x,y: Pint, scale: Pint = 1) # centered
proc printr*(text: string, x,y: Pint, scale: Pint = 1) # right aligned
proc textWidth*(text: string, scale: Pint = 1): Pint
proc glyphWidth*(c: Rune, scale: Pint = 1): Pint
proc glyphWidth*(c: char, scale: Pint = 1): Pint
# Colors
proc setColor*(colId: ColorId)
proc getColor*(): ColorId
proc loadPaletteFromGPL*(filename: string): Palette
proc loadPaletteFromHexString*(s: string): Palette
proc loadPaletteFromImage*(filename: string): Palette
proc loadPalettePico8*(): Palette
proc loadPaletteCGA*(mode: range[0..2] = 0, highIntensity: bool = true): Palette
proc loadPaletteGrayscale*(steps: range[1..256] = 256): Palette
proc palSize*(): Pint
proc pal*(a,b: ColorId) # maps one color to another
proc pal*(a: ColorId): ColorId # returns the color mapping for `a`
proc pald*(a,b: ColorId) # maps one color to another on display output
proc pald*(a: ColorId): ColorId # returns the display color mapping for `a`
proc pal*() # resets palette
proc pald*() # resets display palette
proc palt*(a: ColorId, trans: bool) # sets transparency for color
proc palt*() # resets transparency
proc palCol*(c: Pint, r,g,b: uint8) =
## sets the palette color to rgb value
currentPalette.data[c.uint8] = (r,g,b)
proc palCol*(c: ColorId): (uint8,uint8,uint8) =
## gets the palette color as rgb
return currentPalette.data[c.uint8]
proc palIndex*(r,g,b: uint8): int =
## gets the closest color in the palette to given r,g,b
var bestIndex = 0
var smallestDiff = 99999
for i,v in currentPalette.data:
let rdiff = abs(v.r.int - r.int)
let gdiff = abs(v.g.int - g.int)
let bdiff = abs(v.b.int - b.int)
let diff = rdiff + gdiff + bdiff
if diff < smallestDiff:
smallestDiff = diff
bestIndex = i
return bestIndex
# Clipping
proc clip*(x,y,w,h: Pint)
proc clip*()
proc getClip*(): (int,int,int,int)
# Bitops
proc contains[T](flags: T, bit: T): bool =
return (flags.int and 1 shl bit.int) != 0
proc set[T](flags: var T, bit: T) =
flags = (flags.int or 1 shl bit.int).T
proc unset[T](flags: var T, bit: T) =
flags = (flags.int and (not 1 shl bit.int)).T
# Stencil
proc stencilSet*(x,y,v: Pint) =
stencilBuffer.set(x,y,v.uint8)
proc stencilGet*(x,y: Pint): uint8 =
return stencilBuffer.get(x,y)
proc setStencilRef*(v: Pint) =
stencilRef = v.uint8
proc setStencilWrite*(on: bool) =
stencilWrite = on
proc setStencilWriteFail*(on: bool) =
stencilWriteFail = on
proc setStencilOnly*(on: bool) =
stencilOnly = on
proc stencilMode*(mode: StencilMode) =
common.stencilMode = mode
proc stencilClear*() =
for i in 0..<screenWidth*screenHeight:
stencilBuffer.data[i] = 0
proc stencilClear*(v: Pint) =
for i in 0..<screenWidth*screenHeight:
stencilBuffer.data[i] = v.uint8
proc setStencilBlend*(blend: StencilBlend = stencilReplace) =
stencilBlend = blend
proc stencilTest(x,y: int, nv: uint8): bool =
if common.stencilMode == stencilNever:
return false
if common.stencilMode == stencilAlways:
return true
let v = stencilBuffer.get(x,y)
case common.stencilMode:
of stencilNever:
return false
of stencilAlways:
return true
of stencilEqual:
return nv == v
of stencilLess:
return nv < v
of stencilGreater:
return nv > v
of stencilLEqual:
return nv <= v
of stencilGEqual:
return nv >= v
of stencilNot:
return nv != v
# Camera
proc setCamera*(x,y: Pint = 0)
proc getCamera*(): (Pint,Pint)
# Input Gamepad
proc btn*(b: NicoButton): bool
proc btnp*(b: NicoButton): bool
proc btnup*(b: NicoButton): bool
proc btnpr*(b: NicoButton, repeat = 48): bool
proc jaxis*(axis: NicoAxis): Pfloat
proc btn*(b: NicoButton, player: range[0..maxPlayers]): bool
proc btnp*(b: NicoButton, player: range[0..maxPlayers]): bool
proc btnup*(b: NicoButton, player: range[0..maxPlayers]): bool
proc btnpr*(b: NicoButton, player: range[0..maxPlayers], repeat = 48): bool
proc btnRaw*(b: NicoButton, player: range[0..maxPlayers]): int
proc jaxis*(axis: NicoAxis, player: range[0..maxPlayers]): Pfloat
# Input / Mouse
proc mouse*(): (int,int)
proc mouserel*(): (float32,float32)
proc mousebtn*(b: range[0..2]): bool
proc mousebtnup*(b: range[0..2]): bool
proc mousebtnp*(b: range[0..2]): bool
proc mousebtnpr*(b: range[0..2], r: Pint = 48): bool
proc mousewheel*(): int
proc emulateMouse*(on: bool)
# Input / Touch
proc getTouches*(): seq[Touch] =
return touches
proc getTouchCount*(): int =
return touches.len
export hideMouse
export showMouse
## Drawing API
# pixels
proc pset*(x,y: Pint) {.inline.}
proc pget*(x,y: Pint): ColorId
proc pgetRGB*(x,y: Pint): (uint8,uint8,uint8)
proc sset*(x,y: Pint, c: int = -1)
proc sget*(x,y: Pint): ColorId
# rectangles
proc rect*(x1,y1,x2,y2: Pint)
proc rectfill*(x1,y1,x2,y2: Pint)
proc rrect*(x1,y1,x2,y2: Pint, r: Pint = 1)
proc rrectfill*(x1,y1,x2,y2: Pint, r: Pint = 1)
proc rectCorner*(x1,y1,x2,y2: Pint)
proc rrectCorner*(x1,y1,x2,y2: Pint)
proc box*(x,y,w,h: Pint)
proc boxfill*(x,y,w,h: Pint)
# line drawing
proc line*(x0,y0,x1,y1: Pint)
proc hline*(x0,y,x1: Pint)
proc hlineFast*(x0,y,x1: Pint)
proc vline*(x,y0,y1: Pint)
proc tline*(x0,y0,x1,y1: Pint, tx,ty: Pfloat, tdx: Pfloat = 1f, tdy: Pfloat = 0f)
# triangles
proc trifill*(ax,ay,bx,by,cx,cy: Pint)
proc quadfill*(x1,y1,x2,y2,x3,y3,x4,y4: Pint)
# circles
proc circfill*(cx,cy: Pint, r: Pint)
proc circ*(cx,cy: Pint, r: Pint)
proc ellipsefill*(cx,cy: Pint, rx,ry: Pint)
# sprites
proc spr*(spr: Pint, x,y: Pint, w,h: Pint = 1, hflip, vflip: bool = false)
proc sprs*(spr: Pint, x,y: Pint, w,h: Pint = 1, dw,dh: Pint = 1, hflip, vflip: bool = false)
proc sspr*(sx,sy, sw,sh, dx,dy: Pint, dw,dh: Pint = -1, hflip, vflip: bool = false)
proc sprshift*(spr: Pint, x,y: Pint, w,h: Pint = 1, ox,oy: Pint = 0, hflip, vflip: bool = false)
proc sprRot*(spr: Pint, x,y: Pint, radians: float32, w,h: Pint = 1)
proc sprRot90*(spr: Pint, x,y: Pint, rotations: int, w,h: Pint = 1)
proc spr*(drawer: SpriteDraw)
proc spr*(drawer: SpriteDraw, x,y: Pint)
proc sprOverlap*(a, b: SpriteDraw): bool
# misc
proc copy*(sx,sy,dx,dy,w,h: Pint) # copy one area of the screen to another
# math
export sin
export cos
export abs
export `mod`
proc wrap*[T](x,m: T): T
proc clamp*[T](a: T): T =
clamp(a, 0, 1)
proc clamp01*[T](a: T): T =
clamp(a, 0, 1)
proc mid*[T](a,b,c: T): T =
var a = a
var b = b
if a > b:
swap(a,b)
return max(a, min(b, c))
## System functions
proc shutdown*()
proc init*(org: string, app: string)
export getKeyNamesForBtn
export getUnmappedJoysticks
export getFullSpeedGif
export setFullSpeedGif
export getRecordSeconds
export setRecordSeconds
export getKeyMap
export getPerformanceCounter
export getPerformanceFrequency
# Tilemap functions
proc mset*(tx,ty: Pint, t: int)
proc mget*(tx,ty: Pint): int
proc mapDraw*(startTX,startTY, tw,th, dx,dy: Pint, dw,dh: Pint = -1, loop: bool = false, ox,oy: Pint = 0)
proc setMap*(index: int)
proc loadMap*(index: int, filename: string, layer = 0)
proc loadMapObjects*(index: int, filename: string, layer = 0): seq[(float32,float32,string,string)]
proc newMap*(index: int, w,h: Pint, tw,th: Pint = 8)
proc pixelToMap*(px,py: Pint): (Pint,Pint) # returns the tile coordinates at pixel position
proc mapToPixel*(tx,ty: Pint): (Pint,Pint) # returns the pixel position of the tile coordinates
proc saveMap*(index: int, filename: string)
export toPint
export screenWidth
export screenHeight
# Maths functions
proc flr*(x: Pfloat): Pfloat
proc ceil*(x: Pfloat): Pfloat =
-flr(-x)
proc lerp*[T](a,b: T, t: Pfloat): T
proc lerpSnap*[T](a,b: T, t: Pfloat, threshold = 0.1f): T
proc rnd*[T: Natural](x: T): T
proc rnd*[T](a: openarray[T]): T
proc rnd*(x: Pfloat): Pfloat
proc rnd*[T](x: HSlice[T,T]): T
## Internal functions
proc psetRaw*(x,y: Pint, c: ColorId) {.inline.}
proc psetRaw*(x,y: Pint) {.inline.}
proc fps*(fps: int) =
## sets the frame rate in frames per second
frameRate = fps
timeStep = 1.0 / fps.float32
proc fps*(): int =
## returns the current frame rate in frames per second
return frameRate
proc time*(): float =
## returns the current unix epoch time as a float
return epochTime()
proc speed*(speed: int) =
frameMult = speed
proc loadPaletteFromImage*(filename: string): Palette =
## returns a palette from a PNG image
var loaded = false
var palette: Palette
backend.loadSurfaceFromPNGNoConvert(joinPath(assetPath,filename)) do(surface: Surface):
if surface == nil:
loaded = true
raise newException(IOError, "Error loading palette image: " & filename)
var surface = surface
if surface.channels != 4:
surface = surface.convertToRGBA()
var nColors = 0
let stride = surface.w * surface.channels
for y in 0..<surface.h:
for x in 0..<surface.w:
let r = surface.data[(y * stride) + (x * surface.channels) + 0]
let g = surface.data[(y * stride) + (x * surface.channels) + 1]
let b = surface.data[(y * stride) + (x * surface.channels) + 2]
palette.data[nColors] = RGB(r,g,b)
nColors += 1
palette.size = nColors
loaded = true
while not loaded:
# force sync
discard
return palette
proc loadPaletteFromHexString*(s: string): Palette =
var palette: Palette
for i in 0..<s.len/6:
let strI = i*6
let r = strutils.fromHex[uint8](s[strI..<strI+2])
let g = strutils.fromHex[uint8](s[strI+2..<strI+4])
let b = strutils.fromHex[uint8](s[strI+4..<strI+6])
palette.data[i] = RGB(r, g, b)
palette.size += 1
return palette
proc loadPaletteFromGPL*(filename: string): Palette =
## returns a palette from a GPL (GIMP PALETTE) file
var data = backend.readFile(joinPath(assetPath,filename))
var i = 0
for line in data.splitLines():
if line.len == 0:
continue
if i == 0:
if scanf(line, "GIMP Palette"):
i += 1
continue
if line[0] == '#':
continue
if line.len == 0:
continue
var r,g,b: int
if scanf(line, "$s$i$s$i$s$i", r,g,b):
result.data[i-1] = RGB(r,g,b)
result.size += 1
if i > maxPaletteSize:
break
i += 1
else:
debug "not matched: ", line
pal()
pald()
palt()
proc palSize*(): Pint =
## returns the number of entries in the current palette
return currentPalette.size
proc setPalette*(p: Palette) =
## sets the current palette for future drawing operations
currentPalette = p
proc getPalette*(): Palette =
## returns the current palette
return currentPalette
proc loadPaletteCGA*(mode: range[0..2] = 0, highIntensity: bool = true): Palette =
## loads a 4 color CGA palette, mode 0: cyan,magenta,white; mode 1: green,red,yellow; mode 2: cyan,red,white
result.data[0] = RGB(0,0,0)
case mode:
of 0:
if highIntensity:
result.data[1] = RGB(0x55FFFF) # light cyan
result.data[2] = RGB(0xFF55FF) # light magenta
result.data[3] = RGB(0xFFFFFF) # white
else:
result.data[1] = RGB(0x00AAAA) # cyan
result.data[2] = RGB(0xAA00AA) # magenta
result.data[3] = RGB(0xAAAAAA) # grey
of 1:
if highIntensity:
result.data[1] = RGB(0x55FF55) # light green
result.data[2] = RGB(0xFF5555) # light red
result.data[3] = RGB(0xFFFF55) # yellow
else:
result.data[1] = RGB(0x00AA00) # green
result.data[2] = RGB(0xAA0000) # red
result.data[3] = RGB(0xAA5500) # brown
of 2:
if highIntensity:
result.data[1] = RGB(0x55FFFF) # light cyan
result.data[2] = RGB(0xFF5555) # light red
result.data[3] = RGB(0xFFFFFF) # white
else:
result.data[1] = RGB(0x00AAAA) # cyan
result.data[2] = RGB(0xAA0000) # red
result.data[3] = RGB(0xAAAAAA) # grey
result.size = 4
proc loadPalettePico8*(): Palette =
## loads a 16 color palette based on Pico8's built-in palette
result.data[0] = RGB(0,0,0)
result.data[1] = RGB(29,43,83)
result.data[2] = RGB(126,37,83)
result.data[3] = RGB(0,135,81)
result.data[4] = RGB(171,82,54)
result.data[5] = RGB(95,87,79)
result.data[6] = RGB(194,195,199)
result.data[7] = RGB(255,241,232)
result.data[8] = RGB(255,0,77)
result.data[9] = RGB(255,163,0)
result.data[10] = RGB(255,240,36)
result.data[11] = RGB(0,231,86)
result.data[12] = RGB(41,173,255)
result.data[13] = RGB(131,118,156)
result.data[14] = RGB(255,119,168)
result.data[15] = RGB(255,204,170)
result.size = 16
proc loadPalettePico8Extra*(): Palette =
## loads a 32 color palette based on Pico8's built-in palettes
result.data[0] = RGB(0,0,0)
result.data[1] = RGB(29,43,83)
result.data[2] = RGB(126,37,83)
result.data[3] = RGB(0,135,81)
result.data[4] = RGB(171,82,54)
result.data[5] = RGB(95,87,79)
result.data[6] = RGB(194,195,199)
result.data[7] = RGB(255,241,232)
result.data[8] = RGB(255,0,77)
result.data[9] = RGB(255,163,0)
result.data[10] = RGB(255,240,36)
result.data[11] = RGB(0,231,86)
result.data[12] = RGB(41,173,255)
result.data[13] = RGB(131,118,156)
result.data[14] = RGB(255,119,168)
result.data[15] = RGB(255,204,170)
result.data[16] = RGB(37, 25, 21)
result.data[17] = RGB(22, 28, 51)
result.data[18] = RGB(59, 34, 53)
result.data[19] = RGB(48, 82, 88)
result.data[20] = RGB(102, 51, 43)
result.data[21] = RGB(68, 52, 59)
result.data[22] = RGB(155, 137, 123)
result.data[23] = RGB(240, 240, 140)
result.data[24] = RGB(164, 41, 79)
result.data[25] = RGB(225, 117, 54)
result.data[26] = RGB(186, 230, 85)
result.data[27] = RGB(99, 179, 83)
result.data[28] = RGB(55, 88, 175)
result.data[29] = RGB(106, 72, 99)
result.data[30] = RGB(225, 119, 94)
result.data[31] = RGB(232, 162, 133)
result.size = 32
proc loadPaletteGrayscale*(steps: range[1..256] = 256): Palette =
## loads grayscale palette with specified number of steps
for i in 0..<steps:
let v = floor((i / steps) * 256.0).int
result.data[i] = RGB(v,v,v)
result.size = steps
clipMaxX = screenWidth-1
clipMaxY = screenHeight-1
proc clip*() =
## resets the clipping rectangle to the full screen
clipMinX = 0
clipMaxX = screenWidth-1
clipMinY = 0
clipMaxY = screenHeight-1
clippingRect.x = 0
clippingRect.y = 0
clippingRect.w = screenWidth
clippingRect.h = screenHeight
proc clip*(x,y,w,h: Pint) =
## sets the clipping rectangle with top left and width and height
clipMinX = max(x, 0)
clipMaxX = min(x+w-1, screenWidth-1)
clipMinY = max(y, 0)
clipMaxY = min(y+h-1, screenHeight-1)
clippingRect.x = max(x, 0)
clippingRect.y = max(y, 0)
clippingRect.w = min(w, screenWidth - x)
clippingRect.h = min(h, screenHeight - y)
proc getClip*(): (int,int,int,int) =
## returns the clipping rectangle as x,y,w,h
return (clipMinX,clipMinY,clipMaxX-clipMinX,clipMaxY-clipMinY)
var ditherColor: int = -1
proc setDitherColor*(c: Pint = -1) =
## sets the color to draw for the dither pattern, default is do not draw
ditherColor = c
proc ditherPattern*(pattern: uint16 = 0b1111_1111_1111_1111) =
## sets the dithering pattern for future draw calls, default pattern is no dithering
# 0123
# 4567
# 89ab
# cdef
gDitherMode = Dither4x4
gDitherPattern = pattern
proc ditherOffset*(x,y: Pint) =
gDitherOffsetX = x
gDitherOffsetY = y
proc ditherPatternScanlines*() =
## sets the dithering pattern to draw every odd scanline
gDitherMode = Dither4x4
gDitherPattern = 0b1111_0000_1111_0000
proc ditherPatternScanlines2*() =
## sets the dithering pattern to draw every even scanline
gDitherMode = Dither4x4
gDitherPattern = 0b0000_1111_0000_1111
proc ditherPatternCheckerboard*() =
## sets the dithering pattern to draw a checkerboard
gDitherMode = Dither4x4
gDitherPattern = 0b1010_0101_1010_0101
proc ditherPatternCheckerboard2*() =
## sets the dithering pattern to draw a checkerboard
gDitherMode = Dither4x4
gDitherPattern = 0b0101_1010_0101_1010
proc ditherPatternBigCheckerboard*() =
## sets the dithering pattern to draw a 2x2 checkerboard
gDitherMode = Dither4x4
gDitherPattern = 0b1100_1100_0011_0011
proc ditherPatternBigCheckerboard2*() =
## sets the dithering pattern to draw a 2x2 checkerboard
gDitherMode = Dither4x4
gDitherPattern = 0b0011_0011_1100_1100
const bayer4x4int: array[16, int] = [
0, 8, 2, 10,
12, 4, 14, 6,
3, 11, 1, 9,
15, 7, 13, 5
]
var bayer4x4: array[16, float32]
for i in 0..<16:
bayer4x4[i] = bayer4x4int[i].float32 / 16f
proc ditherPatternBayer*(a: float32) =
## sets the dithering pattern based on an amount 0f..1f using a 4x4 bayer matrix
gDitherMode = Dither4x4
gDitherPattern = 0
for i in 0..<16:
let b = a < bayer4x4[i]
if b:
gDitherPattern = gDitherPattern or (1 shl i).uint16
proc ditherNone*() =
gDitherMode = DitherNone
proc ditherADitherAdd*(v: float32, a = 237,b = 119, c = 255) =
gDitherMode = DitherADitherAdd
gDitherADitherInput = v
gDitherADitherA = a
gDitherADitherB = b
gDitherADitherC = c
proc ditherADitherXor*(v: float32, a = 149,b = 1234, c = 511) =
gDitherMode = DitherADitherXor
gDitherADitherInput = v
gDitherADitherA = a
gDitherADitherB = b
gDitherADitherC = c
proc ditherPass(x,y: int): bool {.inline.} =
if gDitherMode == DitherNone:
return true
let x = floorMod(x + gDitherOffsetX, screenWidth)
let y = floorMod(y + gDitherOffsetY, screenHeight)
case gDitherMode:
of DitherNone:
return true
of Dither4x4:
let x4 = (x mod 4).uint16
let y4 = (y mod 4).uint16
let bit = (y4 * 4 + x4).uint16
return (gDitherPattern and (1.uint16 shl bit)) != 0
of DitherADitherAdd:
return (gDitherADitherInput + (((x + y * gDitherADitherA) * gDitherADitherB and gDitherADitherC).float32 / gDitherADitherC.float32)) > 1f
of DitherADitherXor:
return (gDitherADitherInput + (((x xor y * gDitherADitherA) * gDitherADitherB and gDitherADitherC).float32 / gDitherADitherC.float32)) > 1f
proc isKeyboard*(player: range[0..maxPlayers]): bool =
## returns true if player is using a keyboard
if player > controllers.high:
return false
return controllers[player].kind == Keyboard
proc isGamepad*(player: range[0..maxPlayers]): bool =
## returns true if player is using a gamepad
if player > controllers.high:
return false
return controllers[player].kind == Gamepad
proc btn*(b: NicoButton): bool =
## returns true while button is held down on any controller
for c in controllers:
if c.btn(b):
return true
return false
proc btnup*(b: NicoButton): bool =
## returns true if button was just released on any controller
for c in controllers:
if c.btnup(b):
return true
return false
proc btn*(b: NicoButton, player: range[0..maxPlayers]): bool =
## returns true while button is held down on player's controller
if player > controllers.high:
return false
return controllers[player].btn(b)
proc btnup*(b: NicoButton, player: range[0..maxPlayers]): bool =
## returns true if button was just released on player's controller
if player > controllers.high:
return false
return controllers[player].btnup(b)
proc btnRaw*(b: NicoButton, player: range[0..maxPlayers]): int =
## returns the internal button value 0 = not down, -1 = just released, >1 = how long it's been held down
if player > controllers.high:
return 0
return controllers[player].buttons[b]
proc btnp*(b: NicoButton): bool =
## returns true if button was just pressed on any controller
for c in controllers:
if c.btnp(b):
return true
return false
proc btnp*(b: NicoButton, player: range[0..maxPlayers]): bool =
## returns true if button was just pressed on player's controller
if player > controllers.high:
return false
return controllers[player].btnp(b)
proc btnpr*(b: NicoButton, repeat = 48): bool =
## returns true if button was just pressed or held down repeating every repeat frames on player's controller
for c in controllers:
if c.btnpr(b, repeat):
return true
return false
proc btnpr*(b: NicoButton, player: range[0..maxPlayers], repeat = 48): bool =
## returns true if button was just pressed or held down repeating every repeat frames on any controller
if player > controllers.high:
return false
return controllers[player].btnpr(b, repeat)
proc anybtnp*(): bool =
## returns true if any key pressed
for c in controllers:
if c.anybtnp():
return true
proc anybtnp*(player: range[0..maxPlayers]): bool =
## returns true if any key pressed
if player > controllers.high:
return false
return controllers[player].anybtnp()
proc key*(k: Keycode): bool =
## returns true if key is down
keysDown.hasKey(k) and keysDown[k] != 0
proc keyp*(k: Keycode): bool =
## returns true if key was pressed this frame
keysDown.hasKey(k) and keysDown[k] == 1
proc keypr*(k: Keycode, repeat: int = 48): bool =
## returns true if key was pressed this frame or held down repeating every repeat frames
keysDown.hasKey(k) and keysDown[k].int mod repeat == 1
proc anykeyp*(): bool =
## returns true if any key pressed
aKeyWasPressed
proc jaxis*(axis: NicoAxis): Pfloat =
## returns the joystick axis value
for c in controllers:
let v = c.axis(axis)
if abs(v) > c.deadzone:
return v
return 0.0
proc jaxis*(axis: NicoAxis, player: range[0..maxPlayers]): Pfloat =
## returns the joystick axis value
if player > controllers.high:
return 0.0
return controllers[player].axis(axis)
proc axis*(axis: NicoAxis): Pfloat =
## returns the joystick axis value
for c in controllers:
let v = c.axis(axis)
if abs(v) > c.deadzone:
result += v
if axis == pcXAxis:
if c.btn(pcLeft):
result -= 1f
if c.btn(pcRight):
result += 1f
elif axis == pcYAxis:
if c.btn(pcUp):
result -= 1f
if c.btn(pcDown):
result += 1f
result = clamp(result, -1f, 1f)
proc axis*(axis: NicoAxis, player: range[0..maxPlayers]): Pfloat =
## returns the joystick axis value
if player > controllers.high:
return 0.0
## returns the joystick axis value
let c = controllers[player]
let v = c.axis(axis)
if abs(v) > c.deadzone:
result += v
if axis == pcXAxis:
if c.btn(pcLeft):
result -= 1f
if c.btn(pcRight):
result += 1f
elif axis == pcYAxis:
if c.btn(pcUp):
result -= 1f
if c.btn(pcDown):
result += 1f
result = clamp(result, -1f, 1f)
proc pal*(a,b: ColorId) =
## set the drawing palette color mapping for a to b
## future drawing of color a will draw b instead
paletteMapDraw[a] = b
proc pal*(a: ColorId): ColorId =
## returns the drawing palette color mapping for a
return paletteMapDraw[a]
proc pal*() =
## resets the drawing palette to default
for i in 0..<maxPaletteSize:
paletteMapDraw[i] = i
proc pald*(a,b: ColorId) =
## set the display palette color mapping for a to b
paletteMapDisplay[a] = b
proc pald*(a: ColorId): ColorId =
## returns the display palette color mapping for a
return paletteMapDisplay[a]
proc pald*() =
## resets the display palette
for i in 0..<maxPaletteSize:
paletteMapDisplay[i] = i
proc palt*(a: ColorId, trans: bool) =
## sets transparency for color
paletteTransparent[a] = trans
proc palt*() =
## resets palette transparency, all colors will be opaque except for color 0
for i in 0..<maxPaletteSize:
paletteTransparent[i] = if i == 0: true else: false
{.push checks:off, optimization: speed.}
proc cls*(c: ColorId = 0) =
## clears the screen to the given color. Default is 0. If you need clipping, use rectfill() instead.
let colId = paletteMapDraw[c].uint8
for i in 0..<swCanvas.data.len:
swCanvas.data[i] = colId
proc setCamera*(x,y: Pint = 0) =
## sets the current camera position, future drawing operations will draw based on camera position
cameraX = x
cameraY = y
proc getCamera*(): (Pint,Pint) =
## returns the current camera position as a tuple
return (cameraX, cameraY)
proc setColor*(colId: ColorId) =
## sets the current color
currentColor = colId
proc getColor*(): ColorId =
## returns the current color
return currentColor
proc psetRaw*(x,y: Pint, c: ColorId) =
## sets a pixel to the color c
## does not apply camera offset
if x < clipMinX or y < clipMinY or x > clipMaxX or y > clipMaxY:
return
if c >= 0 and stencilTest(x,y,stencilRef):
if not stencilOnly:
if ditherPass(x,y):
swCanvas.set(x,y,paletteMapDraw[c].uint8)
elif ditherColor >= 0:
swCanvas.set(x,y,paletteMapDraw[ditherColor.ColorId].uint8)
if stencilWrite:
case stencilBlend:
of stencilReplace:
stencilBuffer.set(x,y,stencilRef)
of stencilAdd:
stencilBuffer.add(x,y,stencilRef)
of stencilSubtract:
stencilBuffer.subtract(x,y,stencilRef)
of stencilMax:
stencilBuffer.blendMax(x,y,stencilRef)
of stencilMin:
stencilBuffer.blendMin(x,y,stencilRef)
elif c < 0 and stencilTest(x,y,stencilRef):
# special mode to only draw to stencil with negative of color value
# eg. drawing with color -1 will write 1 (blended) to the stencil buffer and not draw to screen
let cref = (-c).uint8
case stencilBlend:
of stencilReplace:
stencilBuffer.set(x,y,cref)
of stencilAdd:
stencilBuffer.add(x,y,cref)