-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.go
executable file
·1473 lines (1165 loc) · 42 KB
/
main.go
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
package main
import (
"fmt"
"os"
"runtime"
"runtime/pprof"
"strconv"
imgui "github.com/AllenDang/cimgui-go"
"github.com/bloeys/gglm/gglm"
"github.com/bloeys/nmage/assert"
"github.com/bloeys/nmage/assets"
"github.com/bloeys/nmage/buffers"
"github.com/bloeys/nmage/camera"
"github.com/bloeys/nmage/engine"
"github.com/bloeys/nmage/input"
"github.com/bloeys/nmage/logging"
"github.com/bloeys/nmage/materials"
"github.com/bloeys/nmage/meshes"
"github.com/bloeys/nmage/renderer/rend3dgl"
"github.com/bloeys/nmage/timing"
nmageimgui "github.com/bloeys/nmage/ui/imgui"
"github.com/go-gl/gl/v4.1-core/gl"
"github.com/veandco/go-sdl2/sdl"
)
/*
@TODO:
- Rendering:
- Blinn-Phong lighting model ✅
- Directional lights ✅
- Point lights ✅
- Spotlights ✅
- Directional light shadows ✅
- Point light shadows ✅
- Spotlight shadows ✅
- Create VAO struct independent from VBO to support multi-VBO use cases (e.g. instancing) ✅
- Normals maps ✅
- HDR ✅
- Fix bad point light acne ✅
- UBO support ✅
- Skeletal animations
- (?) Cascaded shadow mapping
- In some cases we DO want input even when captured by UI. We need two systems within input package, one filtered and one not✅
- (?) Support OpenGL 4.1 and 4.6, and default to 4.6
- Proper model loading (i.e. load model by reading all its meshes, textures, and so on together)
- Renderer batching
- Scene graph
- (?) Separate engine loop from rendering loop
- Frustum culling
- Proper Asset loading system
- Material system editor with fields automatically extracted from the shader
*/
type DirLight struct {
Dir gglm.Vec3
DiffuseColor gglm.Vec3
SpecularColor gglm.Vec3
}
var (
renderDirLightShadows = true
renderPointLightShadows = true
renderSpotLightShadows = true
dirLightSize float32 = 30
dirLightNear float32 = 0.1
dirLightFar float32 = 30
dirLightPos = gglm.NewVec3(0, 10, 0)
pointLightRadiusToFarPlaneRatio float32 = 1.25
)
func (d *DirLight) GetProjViewMat() gglm.Mat4 {
// Some arbitrary position for the directional light
pos := dirLightPos
size := dirLightSize
nearClip := dirLightNear
farClip := dirLightFar
up := gglm.NewVec3(0, 1, 0)
projMat := gglm.Ortho(-size, size, -size, size, nearClip, farClip).Mat4
viewMat := gglm.LookAtRH(&pos, pos.Clone().Add(&d.Dir), &up).Mat4
return *projMat.Mul(&viewMat)
}
// Based on: https://lisyarus.github.io/blog/posts/point-light-attenuation.html
type PointLight struct {
Pos gglm.Vec3
DiffuseColor gglm.Vec3
SpecularColor gglm.Vec3
Radius float32
Falloff float32
// MaxBias is the max shadow bias applied for this light.
// A usual value is 0.05
MaxBias float32
// NearPlane is the distance where if the pixel
// is closer to the light than this distance, no shadow will be casted.
//
// This helps not produce shadows from within objects.
// Same idea a camera near plane.
NearPlane float32
// Far plane is the max distance at which shadows from this
// light will show.
//
// This should be a bit bigger than the radius, as an object
// at the edge of the radius should still cast a shadow, and
// so this shadow will be further than the radius.
//
// Something like 'FarPlane=Radius*1.25' might work.
FarPlane float32
}
const (
MaxPointLights = 8
// If this changes update the array depth map shader
MaxSpotLights = 4
)
var (
pointLightNear float32 = 1
)
func (p *PointLight) GetProjViewMats(shadowMapWidth, shadowMapHeight float32) [6]gglm.Mat4 {
aspect := float32(shadowMapWidth) / float32(shadowMapHeight)
projMat := gglm.Perspective(90*gglm.Deg2Rad, aspect, pointLightNear, p.FarPlane)
targetPos0 := gglm.NewVec3(1+p.Pos.X(), p.Pos.Y(), p.Pos.Z())
targetPos1 := gglm.NewVec3(-1+p.Pos.X(), p.Pos.Y(), p.Pos.Z())
targetPos2 := gglm.NewVec3(p.Pos.X(), 1+p.Pos.Y(), p.Pos.Z())
targetPos3 := gglm.NewVec3(p.Pos.X(), -1+p.Pos.Y(), p.Pos.Z())
targetPos4 := gglm.NewVec3(p.Pos.X(), p.Pos.Y(), 1+p.Pos.Z())
targetPos5 := gglm.NewVec3(p.Pos.X(), p.Pos.Y(), -1+p.Pos.Z())
worldUp0 := gglm.NewVec3(0, -1, 0)
worldUp1 := gglm.NewVec3(0, -1, 0)
worldUp2 := gglm.NewVec3(0, 0, 1)
worldUp3 := gglm.NewVec3(0, 0, -1)
worldUp4 := gglm.NewVec3(0, -1, 0)
worldUp5 := gglm.NewVec3(0, -1, 0)
lookAt0 := gglm.LookAtRH(&p.Pos, &targetPos0, &worldUp0)
lookAt1 := gglm.LookAtRH(&p.Pos, &targetPos1, &worldUp1)
lookAt2 := gglm.LookAtRH(&p.Pos, &targetPos2, &worldUp2)
lookAt3 := gglm.LookAtRH(&p.Pos, &targetPos3, &worldUp3)
lookAt4 := gglm.LookAtRH(&p.Pos, &targetPos4, &worldUp4)
lookAt5 := gglm.LookAtRH(&p.Pos, &targetPos5, &worldUp5)
projViewMats := [6]gglm.Mat4{
*projMat.Clone().Mul(&lookAt0.Mat4),
*projMat.Clone().Mul(&lookAt1.Mat4),
*projMat.Clone().Mul(&lookAt2.Mat4),
*projMat.Clone().Mul(&lookAt3.Mat4),
*projMat.Clone().Mul(&lookAt4.Mat4),
*projMat.Clone().Mul(&lookAt5.Mat4),
}
return projViewMats
}
type SpotLight struct {
Pos gglm.Vec3
Dir gglm.Vec3
DiffuseColor gglm.Vec3
SpecularColor gglm.Vec3
InnerCutoffRad float32
OuterCutoffRad float32
// Near plane like 0.x (or anything too small) causes shadows to not work properly.
// Needs adjusting as the distance of light to object increases
NearPlane float32
FarPlane float32
}
func (s *SpotLight) GetProjViewMat() gglm.Mat4 {
projMat := gglm.Perspective(s.OuterCutoffRad*2, 1, s.NearPlane, s.FarPlane)
// Adjust up vector if lightDir is parallel or nearly parallel to upVector
// as lookat view matrix breaks if up and look at are parallel
up := gglm.NewVec3(0, 1, 0)
if gglm.Abs32(gglm.DotVec3(&s.Dir, &up)) > 0.99 {
up.SetXY(1, 0)
}
viewMat := gglm.LookAtRH(&s.Pos, s.Pos.Clone().Add(&s.Dir), &up).Mat4
return *projMat.Mul(&viewMat)
}
func (s *SpotLight) InnerCutoffCos() float32 {
return gglm.Cos32(s.InnerCutoffRad)
}
func (s *SpotLight) OuterCutoffCos() float32 {
return gglm.Cos32(s.OuterCutoffRad)
}
type GlobalMatricesUboData struct {
CamPos gglm.Vec3
ProjViewMat gglm.Mat4
}
type DirLightUboData struct {
Dir gglm.Vec3
DiffuseColor gglm.Vec3
SpecularColor gglm.Vec3
}
type PointLightUboData struct {
Pos gglm.Vec3
DiffuseColor gglm.Vec3
SpecularColor gglm.Vec3
Radius float32
Falloff float32
MaxBias float32
NearPlane float32
FarPlane float32
}
type SpotLightUboData struct {
Pos gglm.Vec3
Dir gglm.Vec3
DiffuseColor gglm.Vec3
SpecularColor gglm.Vec3
InnerCutoff float32
OuterCutoff float32
}
type LightsUboData struct {
DirLight DirLightUboData
PointLights [POINT_LIGHT_COUNT]PointLightUboData
SpotLights [SPOT_LIGHT_COUNT]SpotLightUboData
AmbientColor gglm.Vec3
}
const (
// These must match the shader values
POINT_LIGHT_COUNT = 8
SPOT_LIGHT_COUNT = 4
UNSCALED_WINDOW_WIDTH = 1280
UNSCALED_WINDOW_HEIGHT = 720
PROFILE_CPU = false
PROFILE_MEM = false
FRAME_TIME_MS_SAMPLES = 10000
)
var (
globalMatricesUboData GlobalMatricesUboData
globalMatricesUbo buffers.UniformBuffer
lightsUboData LightsUboData
lightsUbo buffers.UniformBuffer
frameTimesMsIndex int = 0
frameTimesMs []float32 = make([]float32, 0, FRAME_TIME_MS_SAMPLES)
camMoveSpeed float32 = 15
camRotSpeed float32 = 0.5
window engine.Window
pitch float32 = 0
yaw float32 = -1.5
cam camera.Camera
renderToBackBuffer = true
// Demo fbo
renderToDemoFbo = false
demoFboScale = gglm.NewVec2(0.25, 0.25)
demoFboOffset = gglm.NewVec2(0.75, -0.75)
demoFbo buffers.Framebuffer
// Dir light fbo
showDirLightDepthMapFbo = false
dirLightDepthMapFboScale = gglm.NewVec2(0.25, 0.25)
dirLightDepthMapFboOffset = gglm.NewVec2(0.75, -0.2)
dirLightDepthMapFbo buffers.Framebuffer
// Point light fbo
pointLightDepthMapFbo buffers.Framebuffer
// Spot light fbo
spotLightDepthMapFbo buffers.Framebuffer
// Hdr Fbo
hdrRendering = true
hdrExposure float32 = 1
tonemappedScreenQuadMat materials.Material
hdrFbo buffers.Framebuffer
screenQuadVao buffers.VertexArray
screenQuadMat materials.Material
unlitMat materials.Material
whiteMat materials.Material
containerMat materials.Material
groundMat materials.Material
palleteMat materials.Material
skyboxMat materials.Material
depthMapMat materials.Material
arrayDepthMapMat materials.Material
omnidirDepthMapMat materials.Material
debugDepthMat materials.Material
cubeMesh meshes.Mesh
sphereMesh meshes.Mesh
chairMesh meshes.Mesh
skyboxMesh meshes.Mesh
cubeModelMat = gglm.NewTrMatId()
renderSkybox = true
renderDepthBuffer = false
skyboxCmap assets.Cubemap
dpiScaling float32
// Light settings
dirLightDir = gglm.NewVec3(0, -0.5, -0.8)
// Lights
dirLight = DirLight{
Dir: *dirLightDir.Normalize(),
DiffuseColor: gglm.NewVec3(63.0/255, 63.0/255, 63.0/255),
SpecularColor: gglm.NewVec3(1, 1, 1),
}
pointLights = [POINT_LIGHT_COUNT]PointLight{
{
Pos: gglm.NewVec3(0, 4, -3),
DiffuseColor: gglm.NewVec3(1, 0, 0),
SpecularColor: gglm.NewVec3(1, 1, 1),
Radius: 10,
Falloff: 1.0,
MaxBias: 0.05,
NearPlane: 0.2,
FarPlane: 20 * pointLightRadiusToFarPlaneRatio,
},
{
Pos: gglm.NewVec3(5, 0, 0),
DiffuseColor: gglm.NewVec3(1, 1, 1),
SpecularColor: gglm.NewVec3(1, 1, 1),
Radius: 10,
Falloff: 1.0,
MaxBias: 0.05,
NearPlane: 0.2,
FarPlane: 20 * pointLightRadiusToFarPlaneRatio,
},
{
Pos: gglm.NewVec3(-3, 4, 3),
DiffuseColor: gglm.NewVec3(1, 1, 1),
SpecularColor: gglm.NewVec3(1, 1, 1),
Radius: 10,
Falloff: 1.0,
MaxBias: 0.05,
NearPlane: 0.2,
FarPlane: 20 * pointLightRadiusToFarPlaneRatio,
},
}
spotLightDir0 = gglm.NewVec3(1.5, -0.9, 0)
spotLights = [SPOT_LIGHT_COUNT]SpotLight{
{
Pos: gglm.NewVec3(-4, 7, 5),
Dir: *spotLightDir0.Normalize(),
DiffuseColor: gglm.NewVec3(1, 0, 1),
SpecularColor: gglm.NewVec3(1, 1, 1),
// These must be cosine values
InnerCutoffRad: 15 * gglm.Deg2Rad,
OuterCutoffRad: 20 * gglm.Deg2Rad,
NearPlane: 2,
FarPlane: 50,
},
}
)
type Game struct {
WinWidth int32
WinHeight int32
Win *engine.Window
Rend *rend3dgl.Rend3DGL
ImGUIInfo nmageimgui.ImguiInfo
}
func main() {
//Init engine
err := engine.Init()
if err != nil {
logging.ErrLog.Fatalln("Failed to init nMage. Err:", err)
}
//Create window
dpiScaling = getDpiScaling(UNSCALED_WINDOW_WIDTH, UNSCALED_WINDOW_HEIGHT)
window, err = engine.CreateOpenGLWindowCentered("nMage", int32(UNSCALED_WINDOW_WIDTH*dpiScaling), int32(UNSCALED_WINDOW_HEIGHT*dpiScaling), engine.WindowFlags_RESIZABLE)
if err != nil {
logging.ErrLog.Fatalln("Failed to create window. Err: ", err)
}
defer window.Destroy()
engine.SetMSAA(true)
engine.SetVSync(false)
engine.SetSrgbFramebuffer(true)
game := &Game{
Win: &window,
WinWidth: int32(UNSCALED_WINDOW_WIDTH * dpiScaling),
WinHeight: int32(UNSCALED_WINDOW_HEIGHT * dpiScaling),
Rend: rend3dgl.NewRend3DGL(),
ImGUIInfo: nmageimgui.NewImGui("./res/shaders/imgui.glsl"),
}
window.EventCallbacks = append(window.EventCallbacks, game.handleWindowEvents)
if PROFILE_CPU {
pf, err := os.Create("cpu.pprof")
if err == nil {
defer pf.Close()
pprof.StartCPUProfile(pf)
} else {
logging.ErrLog.Printf("Creating cpu.pprof file failed. CPU profiling will not run. Err=%v\n", err)
}
}
window.SDLWin.SetTitle("nMage")
engine.Run(game, &window, game.Rend, game.ImGUIInfo)
if PROFILE_CPU {
pprof.StopCPUProfile()
}
if PROFILE_MEM {
heapProfile, err := os.Create("heap.pprof")
if err == nil {
err = pprof.WriteHeapProfile(heapProfile)
if err != nil {
logging.ErrLog.Printf("Writing heap profile to heap.pprof failed. Err=%v\n", err)
}
heapProfile.Close()
} else {
logging.ErrLog.Printf("Creating heap.pprof file failed. Err=%v\n", err)
}
}
}
func (g *Game) handleWindowEvents(e sdl.Event) {
switch e := e.(type) {
case *sdl.WindowEvent:
if e.Event == sdl.WINDOWEVENT_SIZE_CHANGED {
g.WinWidth = e.Data1
g.WinHeight = e.Data2
cam.AspectRatio = float32(g.WinWidth) / float32(g.WinHeight)
cam.Update()
updateAllProjViewMats(cam.ProjMat, cam.ViewMat)
}
}
}
func getDpiScaling(unscaledWindowWidth, unscaledWindowHeight int32) float32 {
// Great read on DPI here: https://nlguillemot.wordpress.com/2016/12/11/high-dpi-rendering/
// The no-scaling DPI on different platforms (e.g. when scale=100% on windows)
var defaultDpi float32 = 96
if runtime.GOOS == "windows" {
defaultDpi = 96
} else if runtime.GOOS == "darwin" {
defaultDpi = 72
}
// Current DPI of the monitor
_, dpiHorizontal, _, err := sdl.GetDisplayDPI(0)
if err != nil {
dpiHorizontal = defaultDpi
logging.ErrLog.Printf("Failed to get DPI with error '%s'. Using default DPI of '%f'\n", err.Error(), defaultDpi)
}
// Scaling factor (e.g. will be 1.25 for 125% scaling on windows)
dpiScaling := dpiHorizontal / defaultDpi
logging.InfoLog.Printf(
"Default DPI=%f\nHorizontal DPI=%f\nDPI scaling=%f\nUnscaled window size (width, height)=(%d, %d)\nScaled window size (width, height)=(%d, %d)\n\n",
defaultDpi,
dpiHorizontal,
dpiScaling,
unscaledWindowWidth, unscaledWindowHeight,
int32(float32(unscaledWindowWidth)*dpiScaling), int32(float32(unscaledWindowHeight)*dpiScaling),
)
return dpiScaling
}
func (g *Game) Init() {
var err error
// Camera
winWidth, winHeight := g.Win.SDLWin.GetSize()
camPos := gglm.NewVec3(0, 10, 20)
camForward := gglm.NewVec3(0, 0, -1)
camWorldUp := gglm.NewVec3(0, 1, 0)
cam = camera.NewPerspective(
&camPos,
&camForward,
&camWorldUp,
0.1, 200,
45*gglm.Deg2Rad,
float32(winWidth)/float32(winHeight),
)
//Load meshes
cubeMesh, err = meshes.NewMesh("Cube", "./res/models/cube.fbx", 0)
if err != nil {
logging.ErrLog.Fatalln("Failed to load mesh. Err: ", err)
}
sphereMesh, err = meshes.NewMesh("Sphere", "./res/models/sphere.fbx", 0)
if err != nil {
logging.ErrLog.Fatalln("Failed to load mesh. Err: ", err)
}
chairMesh, err = meshes.NewMesh("Chair", "./res/models/chair.fbx", 0)
if err != nil {
logging.ErrLog.Fatalln("Failed to load mesh. Err: ", err)
}
skyboxMesh, err = meshes.NewMesh("Skybox", "./res/models/skybox-cube.obj", 0)
if err != nil {
logging.ErrLog.Fatalln("Failed to load mesh. Err: ", err)
}
//Load textures
containerDiffuseTex, err := assets.LoadTexturePNG("./res/textures/container-diffuse.png", &assets.TextureLoadOptions{})
if err != nil {
logging.ErrLog.Fatalln("Failed to load texture. Err: ", err)
}
containerSpecularTex, err := assets.LoadTexturePNG("./res/textures/container-specular.png", &assets.TextureLoadOptions{})
if err != nil {
logging.ErrLog.Fatalln("Failed to load texture. Err: ", err)
}
palleteTex, err := assets.LoadTexturePNG("./res/textures/pallete-endesga-64-1x.png", &assets.TextureLoadOptions{})
if err != nil {
logging.ErrLog.Fatalln("Failed to load texture. Err: ", err)
}
brickwallDiffuseTex, err := assets.LoadTexturePNG("./res/textures/brickwall.png", &assets.TextureLoadOptions{})
if err != nil {
logging.ErrLog.Fatalln("Failed to load texture. Err: ", err)
}
brickwallNormalTex, err := assets.LoadTexturePNG("./res/textures/brickwall-normal.png", &assets.TextureLoadOptions{NoSrgba: true})
if err != nil {
logging.ErrLog.Fatalln("Failed to load texture. Err: ", err)
}
skyboxCmap, err = assets.LoadCubemapTextures(
"./res/textures/sb-right.jpg", "./res/textures/sb-left.jpg",
"./res/textures/sb-top.jpg", "./res/textures/sb-bottom.jpg",
"./res/textures/sb-front.jpg", "./res/textures/sb-back.jpg",
&assets.TextureLoadOptions{},
)
if err != nil {
logging.ErrLog.Fatalln("Failed to load cubemap. Err: ", err)
}
//
// Create materials and assign any unused texture slots to black
//
screenQuadMat = materials.NewMaterial("Screen Quad Mat", "./res/shaders/screen-quad.glsl")
screenQuadMat.SetUnifVec2("scale", &demoFboScale)
screenQuadMat.SetUnifVec2("offset", &demoFboOffset)
screenQuadMat.SetUnifInt32("material.diffuse", int32(materials.TextureSlot_Diffuse))
tonemappedScreenQuadMat = materials.NewMaterial("Tonemapped Screen Quad Mat", "./res/shaders/tonemapped-screen-quad.glsl")
tonemappedScreenQuadMat.SetUnifInt32("material.diffuse", int32(materials.TextureSlot_Diffuse))
unlitMat = materials.NewMaterial("Unlit mat", "./res/shaders/simple-unlit.glsl")
unlitMat.Settings.Set(materials.MaterialSettings_HasModelMtx)
unlitMat.SetUnifInt32("material.diffuse", int32(materials.TextureSlot_Diffuse))
whiteMat = materials.NewMaterial("White mat", "./res/shaders/simple.glsl")
whiteMat.Settings.Set(materials.MaterialSettings_HasModelMtx)
whiteMat.Shininess = 64
whiteMat.SetUnifInt32("material.diffuse", int32(materials.TextureSlot_Diffuse))
whiteMat.SetUnifInt32("material.specular", int32(materials.TextureSlot_Specular))
whiteMat.SetUnifInt32("material.normal", int32(materials.TextureSlot_Normal))
whiteMat.SetUnifInt32("material.emission", int32(materials.TextureSlot_Emission))
whiteMat.SetUnifFloat32("material.shininess", whiteMat.Shininess)
whiteMat.SetUnifInt32("dirLightShadowMap", int32(materials.TextureSlot_ShadowMap1))
whiteMat.SetUnifInt32("pointLightCubeShadowMaps", int32(materials.TextureSlot_Cubemap_Array))
whiteMat.SetUnifInt32("spotLightShadowMaps", int32(materials.TextureSlot_ShadowMap_Array1))
containerMat = materials.NewMaterial("Container mat", "./res/shaders/simple.glsl")
containerMat.Settings.Set(materials.MaterialSettings_HasModelMtx)
containerMat.Shininess = 64
containerMat.DiffuseTex = containerDiffuseTex.TexID
containerMat.SpecularTex = containerSpecularTex.TexID
containerMat.SetUnifInt32("material.diffuse", int32(materials.TextureSlot_Diffuse))
containerMat.SetUnifInt32("material.specular", int32(materials.TextureSlot_Specular))
containerMat.SetUnifInt32("material.normal", int32(materials.TextureSlot_Normal))
containerMat.SetUnifInt32("material.emission", int32(materials.TextureSlot_Emission))
containerMat.SetUnifFloat32("material.shininess", containerMat.Shininess)
containerMat.SetUnifInt32("dirLightShadowMap", int32(materials.TextureSlot_ShadowMap1))
containerMat.SetUnifInt32("pointLightCubeShadowMaps", int32(materials.TextureSlot_Cubemap_Array))
containerMat.SetUnifInt32("spotLightShadowMaps", int32(materials.TextureSlot_ShadowMap_Array1))
groundMat = materials.NewMaterial("Ground mat", "./res/shaders/simple.glsl")
groundMat.Settings.Set(materials.MaterialSettings_HasModelMtx)
groundMat.Shininess = 64
groundMat.DiffuseTex = brickwallDiffuseTex.TexID
groundMat.NormalTex = brickwallNormalTex.TexID
groundMat.SetUnifInt32("material.diffuse", int32(materials.TextureSlot_Diffuse))
groundMat.SetUnifInt32("material.specular", int32(materials.TextureSlot_Specular))
groundMat.SetUnifInt32("material.normal", int32(materials.TextureSlot_Normal))
groundMat.SetUnifInt32("material.emission", int32(materials.TextureSlot_Emission))
groundMat.SetUnifFloat32("material.shininess", groundMat.Shininess)
groundMat.SetUnifInt32("dirLightShadowMap", int32(materials.TextureSlot_ShadowMap1))
groundMat.SetUnifInt32("pointLightCubeShadowMaps", int32(materials.TextureSlot_Cubemap_Array))
groundMat.SetUnifInt32("spotLightShadowMaps", int32(materials.TextureSlot_ShadowMap_Array1))
palleteMat = materials.NewMaterial("Pallete mat", "./res/shaders/simple.glsl")
palleteMat.Settings.Set(materials.MaterialSettings_HasModelMtx)
palleteMat.Shininess = 64
palleteMat.DiffuseTex = palleteTex.TexID
palleteMat.SetUnifInt32("material.diffuse", int32(materials.TextureSlot_Diffuse))
palleteMat.SetUnifInt32("material.specular", int32(materials.TextureSlot_Specular))
palleteMat.SetUnifInt32("material.normal", int32(materials.TextureSlot_Normal))
palleteMat.SetUnifInt32("material.emission", int32(materials.TextureSlot_Emission))
palleteMat.SetUnifFloat32("material.shininess", palleteMat.Shininess)
palleteMat.SetUnifInt32("dirLightShadowMap", int32(materials.TextureSlot_ShadowMap1))
palleteMat.SetUnifInt32("pointLightCubeShadowMaps", int32(materials.TextureSlot_Cubemap_Array))
palleteMat.SetUnifInt32("spotLightShadowMaps", int32(materials.TextureSlot_ShadowMap_Array1))
debugDepthMat = materials.NewMaterial("Debug depth mat", "./res/shaders/debug-depth.glsl")
debugDepthMat.Settings.Set(materials.MaterialSettings_HasModelMtx)
depthMapMat = materials.NewMaterial("Depth Map mat", "./res/shaders/depth-map.glsl")
depthMapMat.Settings.Set(materials.MaterialSettings_HasModelMtx)
arrayDepthMapMat = materials.NewMaterial("Array Depth Map mat", "./res/shaders/array-depth-map.glsl")
arrayDepthMapMat.Settings.Set(materials.MaterialSettings_HasModelMtx)
omnidirDepthMapMat = materials.NewMaterial("Omnidirectional Depth Map mat", "./res/shaders/omnidirectional-depth-map.glsl")
omnidirDepthMapMat.Settings.Set(materials.MaterialSettings_HasModelMtx)
skyboxMat = materials.NewMaterial("Skybox mat", "./res/shaders/skybox.glsl")
skyboxMat.CubemapTex = skyboxCmap.TexID
skyboxMat.SetUnifInt32("skybox", int32(materials.TextureSlot_Cubemap))
// Cube model mat
translationMat := gglm.NewTranslationMat(0, 0, 0)
scaleMat := gglm.NewScaleMat(1, 1, 1)
rotMatRot := gglm.NewQuatEuler(-90*gglm.Deg2Rad, -90*gglm.Deg2Rad, 0)
rotMat := gglm.NewRotMatQuat(&rotMatRot)
cubeModelMat.Mul(translationMat.Mul(rotMat.Mul(&scaleMat)))
// Screen quad vao setup.
// We don't actually care about the values here because the quad is hardcoded in the shader,
// but we just want to have a vao with 6 vertices and uv0 so opengl can be called properly
screenQuadVbo := buffers.NewVertexBuffer(buffers.Element{ElementType: buffers.DataTypeVec3}, buffers.Element{ElementType: buffers.DataTypeVec2})
screenQuadVbo.SetData(make([]float32, 6), buffers.BufUsage_Static_Draw)
screenQuadVao = buffers.NewVertexArray()
screenQuadVao.AddVertexBuffer(screenQuadVbo)
// Fbos and lights
g.initFbos()
// Ubos
g.initUbos()
// Initial camera update
cam.Update()
updateAllProjViewMats(cam.ProjMat, cam.ViewMat)
lightsUboData.AmbientColor = gglm.NewVec3(20.0/255, 20.0/255, 20.0/255)
g.applyLightUpdates()
}
func (g *Game) initUbos() {
globalMatricesUbo = buffers.NewUniformBuffer(
[]buffers.UniformBufferFieldInput{
{Id: 0, Type: buffers.DataTypeVec3},
{Id: 1, Type: buffers.DataTypeMat4},
},
buffers.BufUsage_Dynamic_Draw,
)
globalMatricesUbo.SetBindPoint(0)
groundMat.SetUniformBlockBindingPoint("GlobalMatrices", 0)
whiteMat.SetUniformBlockBindingPoint("GlobalMatrices", 0)
containerMat.SetUniformBlockBindingPoint("GlobalMatrices", 0)
palleteMat.SetUniformBlockBindingPoint("GlobalMatrices", 0)
lightsUbo = buffers.NewUniformBuffer(
[]buffers.UniformBufferFieldInput{
// Dir light
{Id: 0, Type: buffers.DataTypeStruct,
Subfields: []buffers.UniformBufferFieldInput{
{Id: 1, Type: buffers.DataTypeVec3}, // 12 00
{Id: 2, Type: buffers.DataTypeVec3}, // 12 16
{Id: 3, Type: buffers.DataTypeVec3}, // 12 32
},
},
// Point lights
{Id: 5, Type: buffers.DataTypeStruct,
Count: POINT_LIGHT_COUNT,
Subfields: []buffers.UniformBufferFieldInput{
{Id: 6, Type: buffers.DataTypeVec3}, // 12 48
{Id: 7, Type: buffers.DataTypeVec3}, // 12 64
{Id: 8, Type: buffers.DataTypeVec3}, // 12 80
{Id: 9, Type: buffers.DataTypeFloat32}, // 04 92
{Id: 10, Type: buffers.DataTypeFloat32}, // 04 96
{Id: 11, Type: buffers.DataTypeFloat32}, // 04 100
{Id: 12, Type: buffers.DataTypeFloat32}, // 04 104
{Id: 13, Type: buffers.DataTypeFloat32}, // 04 108
},
},
// Spot lights
{Id: 14, Type: buffers.DataTypeStruct,
Count: SPOT_LIGHT_COUNT,
Subfields: []buffers.UniformBufferFieldInput{
{Id: 15, Type: buffers.DataTypeVec3}, // 12 112
{Id: 16, Type: buffers.DataTypeVec3}, // 12 128
{Id: 17, Type: buffers.DataTypeVec3}, // 12 144
{Id: 18, Type: buffers.DataTypeVec3}, // 12 160
{Id: 19, Type: buffers.DataTypeFloat32}, // 04 172
{Id: 20, Type: buffers.DataTypeFloat32}, // 04 176
},
},
// Ambient
{Id: 21, Type: buffers.DataTypeVec3}, // 12 192
},
buffers.BufUsage_Dynamic_Draw,
)
// fmt.Printf("\n==Lights UBO (id=%d)==\nSize=%d\nFields: %+v\n\n", lightsUbo.Id, lightsUbo.Size, lightsUbo.Fields)
lightsUbo.SetBindPoint(1)
groundMat.SetUniformBlockBindingPoint("Lights", 1)
whiteMat.SetUniformBlockBindingPoint("Lights", 1)
containerMat.SetUniformBlockBindingPoint("Lights", 1)
palleteMat.SetUniformBlockBindingPoint("Lights", 1)
}
func (g *Game) initFbos() {
// @TODO: Resize window sized fbos on window resize
// Demo fbo
demoFbo = buffers.NewFramebuffer(uint32(g.WinWidth), uint32(g.WinHeight))
demoFbo.NewColorAttachment(
buffers.FramebufferAttachmentType_Texture,
buffers.FramebufferAttachmentDataFormat_SRGBA,
)
demoFbo.NewDepthStencilAttachment(
buffers.FramebufferAttachmentType_Renderbuffer,
buffers.FramebufferAttachmentDataFormat_Depth24Stencil8,
)
assert.T(demoFbo.IsComplete(), "Demo fbo is not complete after init")
// Depth map fbo
dirLightDepthMapFbo = buffers.NewFramebuffer(4096, 4096)
dirLightDepthMapFbo.SetNoColorBuffer()
dirLightDepthMapFbo.NewDepthAttachment(
buffers.FramebufferAttachmentType_Texture,
buffers.FramebufferAttachmentDataFormat_DepthF32,
)
assert.T(dirLightDepthMapFbo.IsComplete(), "Depth map fbo is not complete after init")
// Point light depth map fbo
pointLightDepthMapFbo = buffers.NewFramebuffer(1024, 1024)
pointLightDepthMapFbo.SetNoColorBuffer()
pointLightDepthMapFbo.NewDepthCubemapArrayAttachment(
buffers.FramebufferAttachmentDataFormat_DepthF32,
MaxPointLights,
)
assert.T(pointLightDepthMapFbo.IsComplete(), "Point light depth map fbo is not complete after init")
// Spot light depth map fbo
spotLightDepthMapFbo = buffers.NewFramebuffer(1024, 1024)
spotLightDepthMapFbo.SetNoColorBuffer()
spotLightDepthMapFbo.NewDepthTextureArrayAttachment(
buffers.FramebufferAttachmentDataFormat_DepthF32,
MaxSpotLights,
)
assert.T(spotLightDepthMapFbo.IsComplete(), "Spot light depth map fbo is not complete after init")
// Hdr fbo
hdrFbo = buffers.NewFramebuffer(uint32(g.WinWidth), uint32(g.WinHeight))
hdrFbo.NewColorAttachment(
buffers.FramebufferAttachmentType_Texture,
buffers.FramebufferAttachmentDataFormat_RGBAF16,
)
hdrFbo.NewDepthStencilAttachment(
buffers.FramebufferAttachmentType_Renderbuffer,
buffers.FramebufferAttachmentDataFormat_Depth24Stencil8,
)
assert.T(hdrFbo.IsComplete(), "Hdr fbo is not complete after init")
}
// applyLightUpdates updates materials and light ubo using
// data from the game's light structs
func (g *Game) applyLightUpdates() {
// Directional light
lightsUboData.DirLight = DirLightUboData(dirLight)
whiteMat.ShadowMapTex1 = dirLightDepthMapFbo.Attachments[0].Id
containerMat.ShadowMapTex1 = dirLightDepthMapFbo.Attachments[0].Id
groundMat.ShadowMapTex1 = dirLightDepthMapFbo.Attachments[0].Id
palleteMat.ShadowMapTex1 = dirLightDepthMapFbo.Attachments[0].Id
// Point lights
for i := 0; i < len(pointLights); i++ {
p := &pointLights[i]
lightsUboData.PointLights[i] = PointLightUboData(*p)
}
whiteMat.CubemapArrayTex = pointLightDepthMapFbo.Attachments[0].Id
containerMat.CubemapArrayTex = pointLightDepthMapFbo.Attachments[0].Id
groundMat.CubemapArrayTex = pointLightDepthMapFbo.Attachments[0].Id
palleteMat.CubemapArrayTex = pointLightDepthMapFbo.Attachments[0].Id
// Spotlights
for i := 0; i < len(spotLights); i++ {
l := &spotLights[i]
innerCutoffCos := l.InnerCutoffCos()
outerCutoffCos := l.OuterCutoffCos()
lightsUboData.SpotLights[i] = SpotLightUboData{
Pos: l.Pos,
Dir: l.Dir,
DiffuseColor: l.DiffuseColor,
SpecularColor: l.SpecularColor,
InnerCutoff: innerCutoffCos,
OuterCutoff: outerCutoffCos,
}
}
whiteMat.ShadowMapTexArray1 = spotLightDepthMapFbo.Attachments[0].Id
containerMat.ShadowMapTexArray1 = spotLightDepthMapFbo.Attachments[0].Id
groundMat.ShadowMapTexArray1 = spotLightDepthMapFbo.Attachments[0].Id
palleteMat.ShadowMapTexArray1 = spotLightDepthMapFbo.Attachments[0].Id
// Apply changes
lightsUbo.Bind()
lightsUbo.SetStruct(lightsUboData)
}
func (g *Game) Update() {
if input.IsQuitClicked() || input.KeyClicked(sdl.K_ESCAPE) {
engine.Quit()
}
g.updateCameraLookAround()
g.updateCameraPos()
globalMatricesUboData.CamPos = cam.Pos
updateAllProjViewMats(cam.ProjMat, cam.ViewMat)
g.showDebugWindow()
}
func (g *Game) showDebugWindow() {
imgui.ShowDemoWindow()
imgui.Begin("Debug controls")
imgui.PushStyleColorVec4(imgui.ColText, imgui.NewColor(1, 1, 0, 1).FieldValue)
imgui.LabelText("FPS", fmt.Sprint(timing.GetAvgFPS()))
imgui.PopStyleColor()
if len(frameTimesMs) < FRAME_TIME_MS_SAMPLES {
frameTimesMs = append(frameTimesMs, timing.DT()*1000)
} else {
frameTimesMs[frameTimesMsIndex] = timing.DT() * 1000
frameTimesMsIndex++
if frameTimesMsIndex >= len(frameTimesMs) {
frameTimesMsIndex = 0
}
}
imgui.PlotLinesFloatPtrV("Frame Times", frameTimesMs, int32(len(frameTimesMs)), 0, "", 0, 16, imgui.Vec2{Y: 50}, 4)
imgui.Spacing()
// Camera
imgui.Text("Camera")
if imgui.DragFloat3("Cam Pos", &cam.Pos.Data) {
cam.Update()
updateAllProjViewMats(cam.ProjMat, cam.ViewMat)
}
if imgui.DragFloat3("Cam Forward", &cam.Forward.Data) {
cam.Update()
updateAllProjViewMats(cam.ProjMat, cam.ViewMat)
}
imgui.Spacing()
imgui.Text("HDR")
imgui.Checkbox("Enable HDR", &hdrRendering)
if imgui.DragFloatV("Exposure", &hdrExposure, 0.1, -10, 100, "%.3f", imgui.SliderFlagsNone) {
tonemappedScreenQuadMat.SetUnifFloat32("exposure", hdrExposure)
}
imgui.Spacing()
//
// Lights
//
updateLights := false
// Ambient light
imgui.Text("Ambient Light")
if imgui.ColorEdit3("Ambient Color", &lightsUboData.AmbientColor.Data) {
updateLights = true
}
imgui.Spacing()
// Directional light
imgui.Text("Directional Light")
imgui.Checkbox("Render Directional Light Shadows", &renderDirLightShadows)
if imgui.DragFloat3("Direction", &dirLight.Dir.Data) {
updateLights = true
}
if imgui.ColorEdit3("Diffuse Color", &dirLight.DiffuseColor.Data) {
updateLights = true
}
if imgui.ColorEdit3("Specular Color", &dirLight.SpecularColor.Data) {
updateLights = true
}
if imgui.DragFloat3("dPos", &dirLightPos.Data) {
updateLights = true
}
if imgui.DragFloat("dSize", &dirLightSize) {
updateLights = true
}
if imgui.DragFloat("dNear", &dirLightNear) {
updateLights = true
}
if imgui.DragFloat("dFar", &dirLightFar) {
updateLights = true
}
imgui.Spacing()
// Specular
imgui.Text("Specular Settings")
if imgui.DragFloat("Specular Shininess", &whiteMat.Shininess) {