-
Notifications
You must be signed in to change notification settings - Fork 249
Expand file tree
/
Copy pathLuaShader.lua
More file actions
1328 lines (1121 loc) · 41.3 KB
/
Copy pathLuaShader.lua
File metadata and controls
1328 lines (1121 loc) · 41.3 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
local UNIFORM_TYPE_MIXED = 0 -- includes arrays; float or int
local UNIFORM_TYPE_INT = 1 -- includes arrays
local UNIFORM_TYPE_FLOAT = 2 -- includes arrays
local UNIFORM_TYPE_FLOAT_MATRIX = 3
local glGetUniformLocation = gl.GetUniformLocation
local glUseShader = gl.UseShader
local glActiveShader = gl.ActiveShader
local glUniform = gl.Uniform
local glUniformInt = gl.UniformInt
local glUniformMatrix = gl.UniformMatrix
local glUniformArray = gl.UniformArray
local gldebugannotations = (Spring.GetConfigInt("gldebugannotations") == 1)
local function new(class, shaderParams, shaderName, logEntries)
local logEntriesSanitized
if type(logEntries) == "number" then
logEntriesSanitized = logEntries
else
logEntriesSanitized = 1
end
return setmetatable(
{
shaderName = shaderName or "Unnamed Shader",
shaderParams = shaderParams or {},
logEntries = logEntriesSanitized,
logHash = {},
shaderObj = nil,
active = false,
ignoreActive = false,
ignoreUnkUniform = false,
uniforms = {},
}, class)
end
local function IsGeometryShaderSupported()
return gl.HasExtension("GL_ARB_geometry_shader4") and (gl.SetShaderParameter ~= nil or gl.SetGeometryShaderParameter ~= nil)
end
local function IsTesselationShaderSupported()
return gl.HasExtension("GL_ARB_tessellation_shader") and (gl.SetTesselationShaderParameter ~= nil)
end
local function IsDeferredShadingEnabled()
return (Spring.GetConfigInt("AllowDeferredMapRendering") == 1) and (Spring.GetConfigInt("AllowDeferredModelRendering") == 1) and (Spring.GetConfigInt("AdvMapShading") == 1)
end
local function GetAdvShadingActive()
local _, advMapShading = Spring.HaveAdvShading()
if advMapShading == nil then
advMapShading = true
end --old engine
return advMapShading
end
local function GetEngineUniformBufferDefs()
local eubs = [[
layout(std140, binding = 0) uniform UniformMatrixBuffer {
mat4 screenView;
mat4 screenProj;
mat4 screenViewProj;
mat4 cameraView;
mat4 cameraProj;
mat4 cameraViewProj;
mat4 cameraBillboardView;
mat4 cameraViewInv;
mat4 cameraProjInv;
mat4 cameraViewProjInv;
mat4 shadowView;
mat4 shadowProj;
mat4 shadowViewProj;
mat4 reflectionView;
mat4 reflectionProj;
mat4 reflectionViewProj;
mat4 orthoProj01;
// transforms for [0] := Draw, [1] := DrawInMiniMap, [2] := Lua DrawInMiniMap
mat4 mmDrawView; //world to MM
mat4 mmDrawProj; //world to MM
mat4 mmDrawViewProj; //world to MM
mat4 mmDrawIMMView; //heightmap to MM
mat4 mmDrawIMMProj; //heightmap to MM
mat4 mmDrawIMMViewProj; //heightmap to MM
mat4 mmDrawDimView; //mm dims
mat4 mmDrawDimProj; //mm dims
mat4 mmDrawDimViewProj; //mm dims
};
layout(std140, binding = 1) uniform UniformParamsBuffer {
vec3 rndVec3; //new every draw frame.
uint renderCaps; //various render booleans
vec4 timeInfo; //gameFrame, drawSeconds, interpolated(unsynced)GameSeconds(synced), frameTimeOffset
vec4 viewGeometry; //vsx, vsy, vpx, vpy
vec4 mapSize; //xz, xzPO2
vec4 mapHeight; //height minCur, maxCur, minInit, maxInit
vec4 fogColor; //fog color
vec4 fogParams; //fog {start, end, 0.0, scale}
vec4 sunDir; // (sky != nullptr) ? sky->GetLight()->GetLightDir() : float4(/*map default*/ 0.0f, 0.447214f, 0.894427f, 1.0f);
vec4 sunAmbientModel;
vec4 sunAmbientMap;
vec4 sunDiffuseModel;
vec4 sunDiffuseMap;
vec4 sunSpecularModel; // float4{ sunLighting->modelSpecularColor.xyz, sunLighting->specularExponent };
vec4 sunSpecularMap; // float4{ sunLighting->groundSpecularColor.xyz, sunLighting->specularExponent };
vec4 shadowDensity; // float4{ sunLighting->groundShadowDensity, sunLighting->modelShadowDensity, 0.0, 0.0 };
vec4 windInfo; // windx, windy, windz, windStrength
vec2 mouseScreenPos; //x, y. Screen space.
uint mouseStatus; // bits 0th to 32th: LMB, MMB, RMB, offscreen, mmbScroll, locked
uint mouseUnused;
vec4 mouseWorldPos; //x,y,z; w=0 -- offmap. Ignores water, doesn't ignore units/features under the mouse cursor
vec4 teamColor[255]; //all team colors
};
// glsl rotate convencience funcs: https://github.com/dmnsgn/glsl-rotate
mat3 rotation3dX(float angle) {
float s = sin(angle);
float c = cos(angle);
return mat3(
1.0, 0.0, 0.0,
0.0, c, s,
0.0, -s, c
);
}
mat3 rotation3dY(float a) {
float s = sin(a);
float c = cos(a);
return mat3(
c, 0.0, -s,
0.0, 1.0, 0.0,
s, 0.0, c);
}
mat3 rotation3dZ(float angle) {
float s = sin(angle);
float c = cos(angle);
return mat3(
c, s, 0.0,
-s, c, 0.0,
0.0, 0.0, 1.0
);
}
mat4 scaleMat(vec3 s) {
return mat4(
s.x, 0.0, 0.0, 0.0,
0.0, s.y, 0.0, 0.0,
0.0, 0.0, s.z, 0.0,
0.0, 0.0, 0.0, 1.0
);
}
mat4 translationMat(vec3 t) {
return mat4(
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
t.x, t.y, t.z, 1.0
);
}
mat4 mat4mix(mat4 a, mat4 b, float alpha) {
return (a * (1.0 - alpha) + b * alpha);
}
// Additional helper functions useful in Spring
vec2 heightmapUVatWorldPos(vec2 worldpos){
vec2 inverseMapSize = vec2(1.0) / mapSize.xy;
// Some texel magic to make the heightmap tex perfectly align:
vec2 heightmaptexel = vec2(8.0, 8.0);
worldpos += vec2(-8.0, -8.0) * (worldpos * inverseMapSize) + vec2(4.0, 4.0) ;
vec2 uvhm = clamp(worldpos, heightmaptexel, mapSize.xy - heightmaptexel);
uvhm = uvhm * inverseMapSize;
return uvhm;
}
// This does 'mirror' style tiling of UVs like the way the map edge extension works
vec2 heightmapUVatWorldPosMirrored(vec2 worldpos) {
vec2 inverseMapSize = vec2(1.0) / mapSize.xy;
// Some texel magic to make the heightmap tex perfectly align:
vec2 heightmaptexel = vec2(8.0, 8.0);
worldpos += vec2(-8.0, -8.0) * (worldpos * inverseMapSize) + vec2(4.0, 4.0) ;
vec2 uvhm = worldpos * inverseMapSize;
return abs(fract(uvhm * 0.5 + 0.5) - 0.5) * 2.0;
}
// SphereInViewSignedDistance
// Signed distance from a world-space sphere to the X-Y NDC box.
// Z (near/far) is ignored. Very reliable, reasonably optimized.
// Returns:
// < 0 – sphere at least partially inside the X-Y clip box
// = 0 – sphere exactly touches at least one edge
// > 0 – sphere is more distance from the edge of frustrum by that many NDC units
//
float SphereInViewSignedDistance(vec3 centerWS, float radiusWS)
{
// 1. centre → clip space
vec4 clipC = cameraViewProj * vec4(centerWS, 1.0);
if (clipC.w <= 0.0) // behind the eye? treat as inside
return -1.0;
// 2. NDC centre (one perspective divide, reused later)
vec2 ndc = clipC.xy / clipC.w; // = clipC.xy / clipC.w
// 3. Project world-space +X displacement
// M * (p + (r,0,0,0)) = (M*p) + r*M*Xcol
vec4 deltaClip = radiusWS * cameraViewProj[0]; // first column of matrix
vec4 clipX = clipC + deltaClip;
// 4. Radius in NDC (second perspective divide only once)
float ndcRadius = length((clipX.xy / clipX.w) - ndc);
// 5. Four signed distances, keep the worst (Chebyshev / max)
float dLeft = -(ndc.x + 1.0) - ndcRadius;
float dRight = (ndc.x - 1.0) - ndcRadius;
float dBottom = -(ndc.y + 1.0) - ndcRadius;
float dTop = (ndc.y - 1.0) - ndcRadius;
return max(max(dLeft, dRight), max(dBottom, dTop));
}
// Note that this function does not check the Z or depth of the clip space, but in regular springrts top-down views, this isnt needed either.
// the radius to cameradist ratio is a good proxy for visibility in the XY plane
bool isSphereVisibleXY(vec4 wP, float wR){ //worldPos, worldRadius
vec3 ToCamera = wP.xyz - cameraViewInv[3].xyz; // vector from worldpos to camera
float isqrtDistRatio = wR * inversesqrt(dot(ToCamera, ToCamera)); // calculate the relative screen-space size of it
vec4 cWPpos = cameraViewProj * wP; // transform the worldpos into clip space
vec2 clipVec = cWPpos.ww * (1.0 + isqrtDistRatio); // normalize the clip tolerance
return any(greaterThan(abs(cWPpos.xy), clipVec)); // check if the clip space coords lie outside of the tolerance relaxed [-1.0, 1.0] space
}
/*
vec3 hsv2rgb(vec3 c){
vec4 K=vec4(1.,2./3.,1./3.,3.);
return c.z*mix(K.xxx,saturate(abs(fract(c.x+K.xyz)*6.-K.w)-K.x),c.y);
}
vec3 rgb2hsv(vec3 c){
vec4 K=vec4(0.,-1./3.,2./3.,-1.);
vec4 p=mix(vec4(c.bg ,K.wz),vec4(c.gb,K.xy ),step(c.b,c.g));
vec4 q=mix(vec4(p.xyw,c.r ),vec4(c.r ,p.yzx),step(p.x,c.r));
float d=q.x-min(q.w,q.y);
float e=1e-10;
return vec3(abs(q.z+(q.w-q.y)/(6.*d+e)),d/(q.x+e),q.x);
}
*/
]]
local waterAbsorbColorR, waterAbsorbColorG, waterAbsorbColorB = gl.GetWaterRendering("absorb")
local waterMinColorR, waterMinColorG, waterMinColorB = gl.GetWaterRendering("minColor")
local waterBaseColorR, waterBaseColorG, waterBaseColorB = gl.GetWaterRendering("baseColor")
local waterUniforms =
[[
#define WATERABSORBCOLOR vec3(%f,%f,%f)
#define WATERMINCOLOR vec3(%f,%f,%f)
#define WATERBASECOLOR vec3(%f,%f,%f)
#define SMF_SHALLOW_WATER_DEPTH_INV 0.1
// vertex below shallow water depth --> alpha=1
// vertex above shallow water depth --> alpha=waterShadeAlpha
vec4 waterBlend(float fragmentheight){
if (fragmentheight>=0) return vec4(0.0);
vec4 waterBlendResult = vec4(1.0, 1.0, 1.0, 0.0);
waterBlendResult.rgb = WATERBASECOLOR.rgb;
waterBlendResult.rgb -= WATERABSORBCOLOR * clamp( -fragmentheight, 0, 1023);
waterBlendResult.rgb = max(waterBlendResult.rgb, WATERMINCOLOR);
waterBlendResult.a = clamp(-fragmentheight * SMF_SHALLOW_WATER_DEPTH_INV, 0.0, 1.0);
return waterBlendResult;
}
]]
waterUniforms = string.format(waterUniforms,
waterAbsorbColorR, waterAbsorbColorG, waterAbsorbColorB,
waterMinColorR, waterMinColorG, waterMinColorB,
waterBaseColorR, waterBaseColorG, waterBaseColorB
)
return eubs .. waterUniforms
end
local function GetQuaternionDefs()
-- For replacing //__QUATERNIONDEFS__ with the quaternion definitions
return [[
// Quaternion math functions
struct Transform {
vec4 quat;
vec4 trSc;
};
layout(std140, binding = 0) readonly buffer TransformBuffer {
Transform transforms[];
};
uint GetUnpackedValue(uint packedValue, uint byteNum) {
return (packedValue >> (8u * byteNum)) & 0xFFu;
}
vec4 MultiplyQuat(vec4 a, vec4 b)
{
return vec4(a.w * b.xyz + b.w * a.xyz + cross(a.xyz, b.xyz), a.w * b.w - dot(a.xyz, b.xyz));
}
vec3 RotateByQuaternion(vec4 q, vec3 v) {
return 2.0 * dot(q.xyz, v) * q.xyz + (q.w * q.w - dot(q.xyz, q.xyz)) * v + 2.0 * q.w * cross(q.xyz, v);
}
vec4 RotateByQuaternion(vec4 q, vec4 v) {
return vec4(RotateByQuaternion(q, v.xyz), v.w);
}
vec4 InvertNormalizedQuaternion(vec4 q) {
return vec4(-q.x, -q.y, -q.z, q.w);
}
vec3 ApplyTransform(Transform tra, vec3 v) {
return RotateByQuaternion(tra.quat, v * tra.trSc.w) + tra.trSc.xyz;
}
vec4 ApplyTransform(Transform tra, vec4 v) {
return vec4(RotateByQuaternion(tra.quat, v.xyz * tra.trSc.w) + tra.trSc.xyz * v.w, v.w);
}
Transform ApplyTransform(Transform parentTra, Transform childTra) {
return Transform(
MultiplyQuat(parentTra.quat, childTra.quat),
vec4(
parentTra.trSc.xyz + RotateByQuaternion(parentTra.quat, parentTra.trSc.w * childTra.trSc.xyz),
parentTra.trSc.w * childTra.trSc.w
)
);
}
Transform InvertTransformAffine(Transform tra) {
vec4 invR = InvertNormalizedQuaternion(tra.quat);
float invS = 1.0 / tra.trSc.w;
return Transform(
invR,
vec4(
RotateByQuaternion(invR, -tra.trSc.xyz * invS),
invS
)
);
}
mat4 TransformToMatrix(Transform tra) {
float qxx = tra.quat.x * tra.quat.x;
float qyy = tra.quat.y * tra.quat.y;
float qzz = tra.quat.z * tra.quat.z;
float qxz = tra.quat.x * tra.quat.z;
float qxy = tra.quat.x * tra.quat.y;
float qyz = tra.quat.y * tra.quat.z;
float qrx = tra.quat.w * tra.quat.x;
float qry = tra.quat.w * tra.quat.y;
float qrz = tra.quat.w * tra.quat.z;
mat3 rot = mat3(
vec3(1.0 - 2.0 * (qyy + qzz), 2.0 * (qxy + qrz) , 2.0 * (qxz - qry) ),
vec3(2.0 * (qxy - qrz) , 1.0 - 2.0 * (qxx + qzz), 2.0 * (qyz + qrx) ),
vec3(2.0 * (qxz + qry) , 2.0 * (qyz - qrx) , 1.0 - 2.0 * (qxx + qyy))
);
rot *= tra.trSc.w;
return mat4(
vec4(rot[0] , 0.0),
vec4(rot[1] , 0.0),
vec4(rot[2] , 0.0),
vec4(tra.trSc.xyz, 1.0)
);
}
vec4 SLerp(vec4 qa, vec4 qb, float t) {
// Calculate angle between them.
float cosHalfTheta = dot(qa, qb);
// Every rotation can be represented by two quaternions: (++++) or (----)
// avoid taking the longer way: choose one representation
float s = sign(cosHalfTheta);
qb *= s;
cosHalfTheta *= s;
// now cosHalfTheta is >= 0.0
// if qa and qb (or -qb originally) represent ~ the same rotation
if (cosHalfTheta >= (1.0 - 0.005))
return normalize(mix(qa, qb, t));
// Interpolation of orthogonal rotations (i.e. cosHalfTheta ~ 0)
// does not require special handling, however this usually represents
// "physically impossible" 180 degree turns with infinite speed so perhaps
// it can be handled in the following (cuurently disabled) special way
#if 0
if (cosHalfTheta <= 0.005)
return mix(qa, qb, step(0.5, t));
#endif
float halfTheta = acos(cosHalfTheta);
// both should be divided by sinHalfTheta (calculation skipped),
// but it makes no sense to do it due to follow up normalization
float ratioA = sin((1.0 - t) * halfTheta);
float ratioB = sin(( t) * halfTheta);
return qa * ratioA + qb * ratioB; // already normalized
}
vec4 Lerp(vec4 qa, vec4 qb, float t) {
// Ensure shortest path
if (dot(qa, qb) < 0.0)
qb = -qb;
return normalize(mix(qa, qb, t)); // GLSL's mix() = (1 - t) * qa + t * qb
}
Transform SLerp(Transform t0, Transform t1, float a) {
// generally good idea, otherwise extrapolation artifacts
// will be nasty in some cases (e.g. fast rotation)
a = clamp(a, 0.0, 1.0);
return Transform(
SLerp(t0.quat, t1.quat, a),
mix(t0.trSc, t1.trSc, a)
);
}
Transform Lerp(Transform t0, Transform t1, float a) {
// generally good idea, otherwise extrapolation artifacts
// will be nasty in some cases (e.g. fast rotation)
a = clamp(a, 0.0, 1.0);
return Transform(
Lerp(t0.quat, t1.quat, a),
mix(t0.trSc, t1.trSc, a)
);
}
// This helper function gets the transform that gets you the model-space to world-space transform
Transform GetModelWorldTransform(uint baseIndex)
{
return Lerp(
transforms[baseIndex + 0u],
transforms[baseIndex + 1u],
timeInfo.w
);
}
// This helper function gets the transform that gets you the piece-space to model-space transform
Transform GetPieceModelTransform(uint baseIndex, uint pieceID)
{
return Lerp(
transforms[baseIndex + 2u * (1u + pieceID) + 0u],
transforms[baseIndex + 2u * (1u + pieceID) + 1u],
timeInfo.w
);
}
// This helper function gets the transform that gets you the piece-space to world-space transform
Transform GetPieceWorldTransform(uint baseIndex, uint pieceID)
{
Transform pieceToMModelTX = GetPieceModelTransform(baseIndex, pieceID);
Transform modelToWorldTX = GetModelWorldTransform(baseIndex);
return ApplyTransform(modelToWorldTX, pieceToMModelTX);
}
Transform GetStaticPieceModelTransform(uint baseIndex, uint pieceID)
{
return transforms[baseIndex + 1u * (pieceID) + 0u];
}
]]
end
local function CreateShaderDefinesString(args) -- Args is a table of stuff that are the shader parameters
local defines = {}
for k, v in pairs (args) do
defines[#defines + 1] = string.format("#define %s %s\n", tostring(k), tostring(v))
end
return table.concat(defines)
end
local LuaShader = setmetatable({}, {
__call = function(self, ...) return new(self, ...) end,
})
LuaShader.__index = LuaShader
LuaShader.isGeometryShaderSupported = IsGeometryShaderSupported()
LuaShader.isTesselationShaderSupported = IsTesselationShaderSupported()
LuaShader.isDeferredShadingEnabled = IsDeferredShadingEnabled()
LuaShader.GetAdvShadingActive = GetAdvShadingActive
LuaShader.GetEngineUniformBufferDefs = GetEngineUniformBufferDefs
LuaShader.CreateShaderDefinesString = CreateShaderDefinesString
LuaShader.GetQuaternionDefs = GetQuaternionDefs
local function CheckShaderUpdates(shadersourcecache, delaytime)
-- todo: extract shaderconfig
if shadersourcecache.forceupdate or shadersourcecache.lastshaderupdate == nil or
Spring.DiffTimers(Spring.GetTimer(), shadersourcecache.lastshaderupdate) > (delaytime or 0.5) then
shadersourcecache.lastshaderupdate = Spring.GetTimer()
local vsSrcNew = (shadersourcecache.vssrcpath and VFS.LoadFile(shadersourcecache.vssrcpath)) or shadersourcecache.vsSrc
local fsSrcNew = (shadersourcecache.fssrcpath and VFS.LoadFile(shadersourcecache.fssrcpath)) or shadersourcecache.fsSrc
local gsSrcNew = (shadersourcecache.gssrcpath and VFS.LoadFile(shadersourcecache.gssrcpath)) or shadersourcecache.gsSrc
if vsSrcNew == shadersourcecache.vsSrc and
fsSrcNew == shadersourcecache.fsSrc and
gsSrcNew == shadersourcecache.gsSrc and
not shadersourcecache.forceupdate then
--Spring.Echo("No change in shaders")
return nil
else
local compilestarttime = Spring.GetTimer()
shadersourcecache.vsSrc = vsSrcNew
shadersourcecache.fsSrc = fsSrcNew
shadersourcecache.gsSrc = gsSrcNew
shadersourcecache.forceupdate = nil
shadersourcecache.updateFlag = true
local engineUniformBufferDefs = LuaShader.GetEngineUniformBufferDefs()
local shaderDefines = LuaShader.CreateShaderDefinesString(shadersourcecache.shaderConfig)
local quaternionDefines = LuaShader.GetQuaternionDefs()
local printfpattern = "^[^/]*printf%s*%(%s*([%w_%.]+)%s*%)"
local printf = nil
if not fsSrcNew then
Spring.Echo("Warning: No fragment shader source found for", shadersourcecache.shaderName)
end
local fsSrcNewLines = string.lines(fsSrcNew)
for i, line in ipairs(fsSrcNewLines) do
--Spring.Echo(i,line)
local glslvariable = line:match(printfpattern)
if glslvariable then
--Spring.Echo("printf in fragment shader",i, glslvariable, line)
-- init our printf table
-- Replace uncommented printf's with the function stub to set the SSBO data for that field
-- Figure out wether the glsl variable is a float, vec2-4
local glslvarcount = 1 -- default is 1
local dotposition = string.find(glslvariable, "%.")
local swizzle = 'x'
if dotposition then
swizzle = string.sub(glslvariable, dotposition+1)
glslvarcount = string.len(swizzle)
end
if glslvarcount>4 then
glslvarcount = 4
end
if not printf then printf = {} end
printf["vars"] = printf["vars"] or {}
local vardata = {name = glslvariable, count = glslvarcount, line = i, index = #printf["vars"], swizzle = swizzle, shaderstage = 'f'}
table.insert(printf["vars"], vardata)
local replacementstring = string.format('if (all(lessThan(abs(mouseScreenPos.xy- (gl_FragCoord.xy + vec2(0.5, -1.5))),vec2(0.25) ))) { printfData[%i].%s = %s;} //printfData[INDEX] = vertexPos.xyzw;',
vardata.index, string.sub('xyzw', 1, vardata.count), vardata.name
)
Spring.Echo(string.format("Replacing f:%d %s", i, line))
fsSrcNewLines[i] = replacementstring
end
end
-- If any substitutions were made, reassemble the shader source
if printf then
-- Define the shader storage buffer object, with at most SSBOSize entries
printf.SSBOSize = math.max(#printf['vars'], 16)
--Spring.Echo("SSBOSize", printf.SSBOSize)
printf.SSBO = gl.GetVBO(GL.SHADER_STORAGE_BUFFER)
printf.SSBO:Define(printf.SSBOSize, {{id = 0, name = "printfData", size = 4}})
local initZeros = {}
for i=1, 4 * printf.SSBOSize do initZeros[i] = 0 end
printf.SSBO:Upload(initZeros)--, nil, 0)
printf.SSBODefinition = [[
layout (std430, binding = 7) buffer printfBuffer {
vec4 printfData[];
};
]]
-- Check shader version string and replace if required:
for i, line in ipairs(fsSrcNewLines) do
if string.find(line, "#version", nil, true) then
if line ~= "#version 430 core" then
Spring.Echo("Replacing shader version", line, "with #version 430 core")
fsSrcNewLines[i] = ""
table.insert(fsSrcNewLines,1, "#version 430 core\n")
break
end
end
end
-- Add required extensions
local ssboextensions = {'#extension GL_ARB_shading_language_420pack: require',
'#extension GL_ARB_uniform_buffer_object : require',
'#extension GL_ARB_shader_storage_buffer_object : require'}
for j, ext in ipairs(ssboextensions) do
local found = false
for i, line in ipairs(fsSrcNewLines) do
if string.find(line, ext, nil, true) then
found = true
break
end
end
if not found then
table.insert(fsSrcNewLines, 2, ext) -- insert at position two as first pos is already taken by #version
end
end
-- Reassemble the shader source by joining on newlines:
fsSrcNew = table.concat(fsSrcNewLines, '\n')
--Spring.Echo(fsSrcNew)
end
if vsSrcNew then
vsSrcNew = vsSrcNew:gsub("//__ENGINEUNIFORMBUFFERDEFS__", engineUniformBufferDefs)
vsSrcNew = vsSrcNew:gsub("//__DEFINES__", shaderDefines)
vsSrcNew = vsSrcNew:gsub("//__QUATERNIONDEFS__", quaternionDefines)
shadersourcecache.vsSrcComplete = vsSrcNew
end
if gsSrcNew then
gsSrcNew = gsSrcNew:gsub("//__ENGINEUNIFORMBUFFERDEFS__", engineUniformBufferDefs)
gsSrcNew = gsSrcNew:gsub("//__DEFINES__", shaderDefines)
gsSrcNew = gsSrcNew:gsub("//__QUATERNIONDEFS__", quaternionDefines)
shadersourcecache.gsSrcComplete = gsSrcNew
end
if fsSrcNew then
fsSrcNew = fsSrcNew:gsub("//__ENGINEUNIFORMBUFFERDEFS__", (printf and (engineUniformBufferDefs .. printf.SSBODefinition) or engineUniformBufferDefs))
fsSrcNew = fsSrcNew:gsub("//__DEFINES__", shaderDefines)
fsSrcNew = fsSrcNew:gsub("//__QUATERNIONDEFS__", quaternionDefines)
shadersourcecache.fsSrcComplete = fsSrcNew -- the complete subbed cache should be kept as its needed to decipher lines post compilation errors
end
local reinitshader = LuaShader(
{
vertex = vsSrcNew,
fragment = fsSrcNew,
geometry = gsSrcNew,
uniformInt = shadersourcecache.uniformInt,
uniformFloat = shadersourcecache.uniformFloat,
},
shadersourcecache.shaderName
)
local shaderCompiled = reinitshader:Initialize()
if not shadersourcecache.silent then
Spring.Echo(shadersourcecache.shaderName, " recompiled in ", Spring.DiffTimers(Spring.GetTimer(), compilestarttime, true), "ms at", Spring.GetGameFrame(), "success", shaderCompiled or false)
end
if shaderCompiled then
reinitshader.printf = printf
reinitshader.ignoreUnkUniform = true
return reinitshader
else
return nil
end
end
end
return nil
end
LuaShader.CheckShaderUpdates = CheckShaderUpdates
local function lines(str)
local t = {}
local function helper(line) table.insert(t, line) return "" end
helper((str:gsub("(.-)\r?\n", helper)))
return t
end
function LuaShader:CreateLineTable()
--[[
-- self.shaderParams ==
({[ vertex = "glsl code" ,]
[ tcs = "glsl code" ,]
[ tes = "glsl code" ,]
[ geometry = "glsl code" ,]
[ fragment = "glsl code" ,]
[ uniform = { uniformName = number value, ...} ,] (specify a Lua array as an argument to uniformName to initialize GLSL arrays)
[ uniformInt = { uniformName = number value, ...} ,] (specify a Lua array as an argument to uniformName to initialize GLSL arrays)
[ uniformFloat = { uniformName = number value, ...} ,] (specify a Lua array as an argument to uniformName to initialize GLSL arrays)
[ uniformMatrix = { uniformName = number value, ...} ,]
[ geoInputType = number inType,]
[ geoOutputType = number outType,]
[ geoOutputVerts = number maxVerts,]
[ definitions = "string of shader #defines", ]
})
]]--
local numtoline = {}
--try to translate errors that look like this into lines:
-- 0(31048) : error C1031: swizzle mask element not present in operand "ra"
-- 0(31048) : error C1031: swizzle mask element not present in operand "ra"
--for k, v in pairs(self) do
-- Spring.Echo(k)
--end
for _, shadertype in pairs({'vertex', 'tcs', 'tes', 'geometry', 'fragment', 'compute'}) do
if self.shaderParams[shadertype] ~= nil then
local shaderLines = (self.shaderParams.definitions or "") .. self.shaderParams[shadertype]
local currentlinecount = 0
for i, line in ipairs(lines(shaderLines)) do
numtoline[currentlinecount] = string.format("%s:%i %s", shadertype, currentlinecount, line)
--Spring.Echo(currentlinecount, numtoline[currentlinecount] )
if line:find("#line ", nil, true) then
local defline = tonumber(line:sub(7))
if defline then
currentlinecount = defline
end
else
currentlinecount = currentlinecount + 1
end
end
end
end
return numtoline
end
local function translateLines(alllines, errorcode)
if string.len(errorcode) < 3 then
return ("The shader compilation error code was very short. This likely means a Linker error, check the [in] [out] blocks linking VS/GS/FS shaders to each other to make sure the structs match")
end
local result = ""
for _,line in pairs(lines(errorcode)) do
local pstart = line:find("(", nil, true)
local pend = line:find(")", nil, true)
local found = false
if pstart and pend then
local lineno = line:sub(pstart +1,pend-1)
--Spring.Echo(lineno)
lineno = tonumber(lineno)
--Spring.Echo(lineno, alllines[lineno])
if alllines[lineno] then
result = result .. string.format("%s\n ^^ %s \n", alllines[lineno], line)
found = true
end
end
if found == false then
result = result .. line ..'\n'
end
end
return result
end
-----------------============ Warnings & Error Gandling ============-----------------
function LuaShader:OutputLogEntry(text, isError)
local message
local warnErr = (isError and "error") or "warning"
message = string.format("LuaShader: [%s] shader %s(s):\n%s", self.shaderName, warnErr, text)
Spring.Echo(message)
if isError then
local linetable = self:CreateLineTable()
Spring.Echo(translateLines(linetable, text))
end
if self.logHash[message] == nil then
-- self.logHash[message] = 0
end
if false and self.logHash[message] <= self.logEntries then
local newCnt = self.logHash[message] + 1
self.logHash[message] = newCnt
if (newCnt == self.logEntries) then
message = message .. string.format("\nSupressing further %s of the same kind", warnErr)
end
Spring.Echo(message)
end
end
function LuaShader:ShowWarning(text)
self:OutputLogEntry(text, false)
end
function LuaShader:ShowError(text)
self:OutputLogEntry(text, true)
end
-----------------============ Handle Ghetto Include<> ==============-----------------
local includeRegexps = {
'.-#include <(.-)>.-',
'.-#include \"(.-)\".-',
'.-#pragma(%s+)include <(.-)>.-',
'.-#pragma(%s+)include \"(.-)\".-',
}
function LuaShader:HandleIncludes(shaderCode, shaderName)
local incFiles = {}
local t1 = Spring.GetTimer()
repeat
local incFile
local regEx
for _, rx in ipairs(includeRegexps) do
_, _, incFile = string.find(shaderCode, rx)
if incFile then
regEx = rx
break
end
end
Spring.Echo(shaderName, incFile)
if incFile then
shaderCode = string.gsub(shaderCode, regEx, '', 1)
table.insert(incFiles, incFile)
end
until (incFile == nil)
local t2 = Spring.GetTimer()
Spring.Echo(Spring.DiffTimers(t2, t1, true))
local includeText = ""
for _, incFile in ipairs(incFiles) do
if VFS.FileExists(incFile) then
includeText = includeText .. VFS.LoadFile(incFile) .. "\n"
else
self:ShowError(string.format("Attempt to execute %s with file that does not exist in VFS", incFile))
return false
end
end
if includeText ~= "" then
return includeText .. shaderCode
else
return shaderCode
end
end
-----------------========= End of Handle Ghetto Include<> ==========-----------------
-----------------============ General LuaShader methods ============-----------------
function LuaShader:Compile(suppresswarnings)
if not gl.CreateShader then
self:ShowError("GLSL Shaders are not supported by hardware or drivers")
return false
end
-- LuaShader:HandleIncludes is too slow. Figure out faster way.
--[[
for _, shaderType in ipairs({"vertex", "tcs", "tes", "geometry", "fragment"}) do
if self.shaderParams[shaderType] then
local newShaderCode = LuaShader:HandleIncludes(self.shaderParams[shaderType], self.shaderName)
if newShaderCode then
self.shaderParams[shaderType] = newShaderCode
end
end
end
]]--
local shaderObj, gl_program_id = gl.CreateShader(self.shaderParams)
self.shaderObj = shaderObj
self.gl_program_id = gl_program_id
local shLog = gl.GetShaderLog() or ""
self.shLog = shLog
if not shaderObj then
self:ShowError(shLog)
return false
elseif (shLog ~= "") and suppresswarnings ~= true then
self:ShowWarning(shLog)
end
if gldebugannotations and gl_program_id and self.shaderName then
local GL_PROGRAM = 0x82E2
gl.ObjectLabel(GL_PROGRAM, gl_program_id, self.shaderName)
end
local uniforms = self.uniforms
for idx, info in ipairs(gl.GetActiveUniforms(shaderObj)) do
local uniName = string.gsub(info.name, "%[0%]", "") -- change array[0] to array
uniforms[uniName] = {
location = glGetUniformLocation(shaderObj, uniName),
--type = info.type,
--size = info.size,
values = {},
}
--Spring.Echo(uniName, uniforms[uniName].location, uniforms[uniName].type, uniforms[uniName].size)
--Spring.Echo(uniName, uniforms[uniName].location)
end
-- Note that the function call overhead to the LuaShader:SetUniformFloat is about 500ns
-- With this, a direct gl.Uniform call, this goes down to 100ns
self.uniformLocations = {}
for _, uniformGeneric in ipairs({self.shaderParams.uniformFloat or {}, self.shaderParams.uniformInt or {} }) do
for uniName, defaultvalue in pairs(uniformGeneric) do
local location = glGetUniformLocation(shaderObj, uniName)
if location then
self.uniformLocations[uniName] = location
else
Spring.Echo(string.format("Notice from shader %s: Could not find location of uniform name: %s", "dunno", uniName ))
end
end
end
return true
end
LuaShader.Initialize = LuaShader.Compile
function LuaShader:GetHandle()
if self.shaderObj ~= nil then
return self.shaderObj
else
local funcName = (debug and debug.getinfo and debug.getinfo(1).name) or "UnknownFunction"
self:ShowError(string.format("Attempt to use invalid shader object in [%s](). Did you call :Compile() or :Initialize()?", funcName))
end
end
function LuaShader:Delete()
if self.shaderObj ~= nil then
gl.DeleteShader(self.shaderObj)
else
local funcName = (debug and debug.getinfo and debug.getinfo(1).name) or "UnknownFunction"
self:ShowError(string.format("Attempt to use invalid shader object in [%s](). Did you call :Compile() or :Initialize()", funcName))
end
end
LuaShader.Finalize = LuaShader.Delete
function LuaShader:Activate()
if self.shaderObj ~= nil then
-- bind the printf SSBO if present
if self.printf then
local bindingIndex = self.printf.SSBO:BindBufferRange(7)
if bindingIndex <= 0 then Spring.Echo("Failed to bind printfData SSBO for shader", self.shaderName) end
end
self.active = true
if gldebugannotations and self.gl_program_id then
gl.PushDebugGroup(self.gl_program_id * 1000, self.shaderName)
end
return glUseShader(self.shaderObj)
else
local funcName = (debug and debug.getinfo and debug.getinfo(1).name) or "UnknownFunction"
self:ShowError(string.format("Attempt to use invalid shader object in [%s](). Did you call :Compile() or :Initialize()", funcName))
return false
end
end
function LuaShader:SetActiveStateIgnore(flag)
self.ignoreActive = flag
end
function LuaShader:SetUnknownUniformIgnore(flag)
self.ignoreUnkUniform = flag
end
function LuaShader:ActivateWith(func, ...)
if self.shaderObj ~= nil then
self.active = true
glActiveShader(self.shaderObj, func, ...)
self.active = false
else
local funcName = (debug and debug.getinfo and debug.getinfo(1).name) or "UnknownFunction"
self:ShowError(string.format("Attempt to use invalid shader object in [%s](). Did you call :Compile() or :Initialize()", funcName))
end
end
function LuaShader:Deactivate()
self.active = false
glUseShader(0)
if gldebugannotations then gl.PopDebugGroup() end
--Spring.Echo("LuaShader:Deactivate()")
if self.printf then
--Spring.Echo("self.printf", self.printf)
self.printf.SSBO:UnbindBufferRange(7)
self.printf.bufferData = self.printf.SSBO:Download(-1, 0, nil, true) -- last param is forceGPURead = true
--Spring.Echo(self.printf.bufferData[1],self.printf.bufferData[2],self.printf.bufferData[3],self.printf.bufferData[4])
-- Do NAN checks on bufferData array and replace with -666 if NAN:
for i = 1, #self.printf.bufferData do