-
Notifications
You must be signed in to change notification settings - Fork 18
/
camera.go
2570 lines (1891 loc) · 85.4 KB
/
camera.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 tetra3d
import (
"errors"
"fmt"
"image"
"math"
"sort"
"time"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/ebitenutil"
"github.com/hajimehoshi/ebiten/v2/text"
"golang.org/x/image/font/basicfont"
)
// DebugInfo is a struct that holds debugging information for a Camera's render pass. These values are reset when Camera.Clear() is called.
type DebugInfo struct {
FrameTime time.Duration // Amount of CPU frame time spent transforming vertices and calling Image.DrawTriangles. Doesn't include time ebitengine spends flushing the command queue.
AnimationTime time.Duration // Amount of CPU frame time spent animating vertices.
LightTime time.Duration // Amount of CPU frame time spent lighting vertices.
currentAnimationTime time.Duration
currentLightTime time.Duration
currentFrameTime time.Duration
tickTime time.Time
DrawnParts int // Number of draw calls, excluding those invisible or culled based on distance
TotalParts int // Total number of draw calls
BatchedParts int // Total batched number of draw calls
DrawnTris int // Number of drawn triangles, excluding those hidden from backface culling
TotalTris int // Total number of triangles
LightCount int // Total number of lights
ActiveLightCount int // Total active number of lights
}
type AccumulationColorMode int
const (
AccumulationColorModeNone AccumulationColorMode = iota // No accumulation buffer rendering
AccumulationColorModeBelow // Accumulation buffer is on and applies over time, renders ColorTexture after the accumulation result (which is, then, below)
AccumulationColorModeAbove // Accumulation buffer is on and applies over time, renders ColorTexture before the accumulation result (which is on top)
AccumulationColorModeSingleLastFrame // Accumulation buffer is on and renders just the previous frame's ColorTexture result
)
// Camera represents a camera (where you look from) in Tetra3D.
type Camera struct {
*Node
RenderDepth bool // If the Camera should attempt to render a depth texture; if this is true, then DepthTexture() will hold the depth texture render results. Defaults to true.
RenderNormals bool // If the Camera should attempt to render a normal texture; if this is true, then NormalTexture() will hold the normal texture render results. Defaults to false.
SectorRendering bool // If the Camera should render using sectors or not; if no sectors are present, then it won't attempt to render with them. Defaults to false.
SectorRenderDepth int // How far out the Camera renders other sectors. Defaults to 1 (so the current sector and its immediate neighbors).
PerspectiveCorrectedTextureMapping bool // If the Camera should render textures with perspective corrected texture mapping. Defaults to false.
currentSector *Sector
// How many lights (sorted by distance) should be used to render each object, maximum. If it's greater than 0,
// then only that many lights will be considered. If less than or equal to 0 (the default), then all available lights will be used.
MaxLightCount int
resultColorTexture *ebiten.Image // ColorTexture holds the color results of rendering any models.
resultDepthTexture *ebiten.Image // DepthTexture holds the depth results of rendering any models, if Camera.RenderDepth is on.
resultNormalTexture *ebiten.Image // NormalTexture holds a texture indicating the normal render
depthIntermediate *ebiten.Image
resultAccumulatedColorTexture *ebiten.Image // ResultAccumulatedColorTexture holds the previous frame's render result of rendering any models.
accumulatedBackBuffer *ebiten.Image
// The mode to use when rendering previous frames to the accumulation buffer.
// When set to anything but AccumulationColorModeNone, clearing the Camera will copy the previous frame's color texture render result to the accumulation buffer.
// The AccumulationColorMode influences in what order the color texture and previous frame's acccumulation color mode result is drawn to the buffer.
// Defaults to AccumulateColorModeNone.
AccumulationColorMode AccumulationColorMode
// Draw image options to use when rendering frames to the accumulation buffer; use this to fade out or color previous frames.
// This should probably be set once, or once per frame before rendering; otherwise, the effects compound and it's impossible to see the result.
AccumulationDrawOptions *ebiten.DrawImageOptions
near, far float64 // The near and far clipping plane. Near defaults to 0.1, Far to 100 (unless these settings are loaded from a camera in a GLTF file).
perspective bool // If the Camera has a perspective projection. If not, it would be orthographic
fieldOfView float64 // Vertical field of view in degrees for a perspective projection camera
orthoScale float64 // Scale of the view for an orthographic projection camera in units horizontally
// When set to a value > 0, it will snap all rendered models' vertices to a grid of the provided size (so VertexSnapping of 0.1 will snap all rendered positions to 0.1 intervals).
// Note that snapping vertices is not free and does take some time to execute (so if you're up against a performance limit, turning off vertex snapping might make a bit of a difference).
// Defaults to 0 (off).
VertexSnapping float64
DebugInfo DebugInfo
depthShader *ebiten.Shader
clipAlphaShader *ebiten.Shader
colorShader *ebiten.Shader
sprite3DShader *ebiten.Shader
// Visibility check variables
cameraForward Vector
cameraRight Vector
cameraUp Vector
sphereFactorX float64
sphereFactorY float64
sphereFactorTang float64
sphereFactorCalculated bool
updateProjectionMatrix bool
cachedProjectionMatrix Matrix4
debugTextTexture *ebiten.Image
// DepthMargin is a margin in percentage on both the near and far plane to leave some
// distance remaining in the depth buffer for triangle comparison.
// This ensures that objects that are, for example, close to or far from the camera
// don't begin Z-fighting unnecessarily. It defaults to 4% (on both ends).
DepthMargin float64
}
// NewCamera creates a new Camera with the specified width and height.
func NewCamera(w, h int) *Camera {
cam := &Camera{
Node: NewNode("Camera"),
RenderDepth: true,
near: 0.1,
far: 100,
DepthMargin: 0.04,
orthoScale: 20,
SectorRendering: false,
SectorRenderDepth: 1,
}
depthShaderText := []byte(
`package main
//kage:unit pixels
func encodeDepth(depth float) vec4 {
r := floor(depth * 255) / 255
g := floor(fract(depth * 255) * 255) / 255
b := fract(depth * 255*255)
return vec4(r, g, b, 1);
}
func decodeDepth(rgba vec4) float {
return rgba.r + (rgba.g / 255) + (rgba.b / 65025)
}
func dstPosToSrcPos(dstPos vec2) vec2 {
return dstPos.xy - imageDstOrigin() + imageSrc0Origin()
}
func Fragment(dstPos vec4, srcPos vec2, color vec4) vec4 {
existingDepth := imageSrc0UnsafeAt(dstPosToSrcPos(dstPos.xy))
if existingDepth.a == 0 || decodeDepth(existingDepth) > color.r {
return encodeDepth(color.r)
}
discard()
}
`,
)
var err error
cam.depthShader, err = ebiten.NewShader(depthShaderText)
if err != nil {
panic(err)
}
clipAlphaShaderText := []byte(
`//kage:unit pixels
package main
var PerspectiveCorrection int
func encodeDepth(depth float) vec4 {
r := floor(depth * 255) / 255
g := floor(fract(depth * 255) * 255) / 255
b := fract(depth * 255*255)
return vec4(r, g, b, 1);
}
func decodeDepth(rgba vec4) float {
return rgba.r + (rgba.g / 255) + (rgba.b / 65025)
}
func dstPosToSrcPos(dstPos vec2) vec2 {
return dstPos.xy - imageDstOrigin() + imageSrc0Origin()
}
func Fragment(dstPos vec4, srcPos vec2, vc, custom vec4) vec4 {
color := vc
srcSize := imageSrc1Size()
// There's atlassing going on behind the scenes here, so:
// Subtract the source position by the src texture's origin on the atlas.
// This gives us the actual pixel coordinates.
tx := srcPos
// Divide by the source image size to get the UV coordinates.
tx /= srcSize
if PerspectiveCorrection > 0 {
tx *= 1.0 / custom.x
}
// Apply fract() to loop the UV coords around [0-1].
tx = fract(tx)
// Multiply by the size to get the pixel coordinates again.
tx *= srcSize
tex := imageSrc1UnsafeAt(tx)
if (tex.a == 0) {
discard()
}
depthValue := imageSrc0UnsafeAt(dstPosToSrcPos(dstPos.xy))
if depthValue.a == 0 || decodeDepth(depthValue) > color.r {
return vec4(encodeDepth(color.r).rgb, tex.a)
}
discard()
}
`,
)
cam.clipAlphaShader, err = ebiten.NewShader(clipAlphaShaderText)
if err != nil {
panic(err)
}
cam.colorShader, err = ExtendBase3DShader("")
if err != nil {
panic(err)
}
sprite3DShaderText := []byte(
`package main
//kage:unit pixels
var SpriteDepth float
func decodeDepth(rgba vec4) float {
return rgba.r + (rgba.g / 255) + (rgba.b / 65025)
}
func dstPosToSrcPos(dstPos vec2) vec2 {
return dstPos.xy - imageDstOrigin() + imageSrc0Origin()
}
func Fragment(dstPos vec4, srcPos vec2, color vec4) vec4 {
resultDepth := imageSrc1UnsafeAt(dstPosToSrcPos(dstPos.xy))
if resultDepth.a == 0 || decodeDepth(resultDepth) > SpriteDepth {
return imageSrc0UnsafeAt(srcPos)
}
discard()
}
`,
)
cam.sprite3DShader, err = ebiten.NewShader(sprite3DShaderText)
if err != nil {
panic(err)
}
if w != 0 && h != 0 {
cam.Resize(w, h)
}
cam.SetPerspective(true)
cam.SetFieldOfView(60)
return cam
}
// Clone clones the Camera and returns it.
func (camera *Camera) Clone() INode {
w, h := camera.resultColorTexture.Size()
clone := NewCamera(w, h)
clone.RenderDepth = camera.RenderDepth
clone.near = camera.near
clone.far = camera.far
clone.perspective = camera.perspective
clone.fieldOfView = camera.fieldOfView
clone.orthoScale = camera.orthoScale
clone.SectorRendering = camera.SectorRendering
clone.SectorRenderDepth = camera.SectorRenderDepth
clone.PerspectiveCorrectedTextureMapping = camera.PerspectiveCorrectedTextureMapping
clone.AccumulationColorMode = camera.AccumulationColorMode
if camera.AccumulationDrawOptions != nil {
newOptions := *camera.AccumulationDrawOptions
clone.AccumulationDrawOptions = &newOptions
}
clone.Node = camera.Node.Clone().(*Node)
for _, child := range camera.children {
child.setParent(camera)
}
clone.MaxLightCount = camera.MaxLightCount
return clone
}
// Resize resizes the backing texture for the Camera to the specified width and height. If the camera already has a backing texture and the
// width and height are already set to the specified arguments, then the function does nothing.
func (camera *Camera) Resize(w, h int) {
if camera.resultColorTexture != nil {
origW, origH := camera.Size()
if w == origW && h == origH {
return
}
camera.resultColorTexture.Dispose()
camera.resultAccumulatedColorTexture.Dispose()
camera.resultNormalTexture.Dispose()
camera.accumulatedBackBuffer.Dispose()
camera.resultDepthTexture.Dispose()
camera.depthIntermediate.Dispose()
}
bounds := image.Rect(0, 0, w, h)
opt := &ebiten.NewImageOptions{
Unmanaged: true,
}
camera.resultAccumulatedColorTexture = ebiten.NewImageWithOptions(bounds, opt)
camera.accumulatedBackBuffer = ebiten.NewImageWithOptions(bounds, opt)
camera.resultColorTexture = ebiten.NewImageWithOptions(bounds, opt)
camera.resultDepthTexture = ebiten.NewImageWithOptions(bounds, opt)
camera.resultNormalTexture = ebiten.NewImageWithOptions(bounds, opt)
camera.depthIntermediate = ebiten.NewImageWithOptions(bounds, opt)
camera.sphereFactorCalculated = false
camera.updateProjectionMatrix = true
}
// Size returns the width and height of the camera's backing color texture. All of the Camera's textures are the same size, so these
// same size values can also be used for the depth texture, the accumulation buffer, etc.
func (camera *Camera) Size() (w, h int) {
size := camera.resultColorTexture.Bounds().Size()
return size.X, size.Y
}
// ViewMatrix returns the Camera's view matrix.
func (camera *Camera) ViewMatrix() Matrix4 {
camPos := camera.WorldPosition().Invert()
transform := NewMatrix4Translate(camPos.X, camPos.Y, camPos.Z)
// We invert the rotation because the Camera is looking down -Z
transform = transform.Mult(camera.WorldRotation().Transposed())
return transform
}
// Projection returns the Camera's projection matrix.
func (camera *Camera) Projection() Matrix4 {
if !camera.updateProjectionMatrix {
return camera.cachedProjectionMatrix
}
camera.updateProjectionMatrix = false
if !camera.sphereFactorCalculated {
angle := camera.fieldOfView * 3.1415 / 360
camera.sphereFactorTang = math.Tan(angle)
camera.sphereFactorY = 1.0 / math.Cos(angle)
camera.sphereFactorX = 1.0 / math.Cos(math.Atan(camera.sphereFactorTang*camera.AspectRatio()))
camera.sphereFactorCalculated = true
}
if camera.perspective {
camera.cachedProjectionMatrix = NewProjectionPerspective(camera.fieldOfView, camera.near, camera.far, float64(camera.resultColorTexture.Bounds().Dx()), float64(camera.resultColorTexture.Bounds().Dy()))
} else {
w, h := camera.resultColorTexture.Size()
asr := float64(h) / float64(w)
camera.cachedProjectionMatrix = NewProjectionOrthographic(camera.near, camera.far, 1*camera.orthoScale, -1*camera.orthoScale, asr*camera.orthoScale, -asr*camera.orthoScale)
}
return camera.cachedProjectionMatrix
// return NewProjectionOrthographic(camera.Near, camera.far, float64(camera.ColorTexture.Bounds().Dx())*camera.orthoScale, float64(camera.ColorTexture.Bounds().Dy())*camera.orthoScale)
}
// SetPerspective sets the Camera's projection to be a perspective (true) or orthographic (false) projection.
func (camera *Camera) SetPerspective(perspective bool) {
if camera.perspective == perspective {
return
}
camera.perspective = perspective
camera.sphereFactorCalculated = false
camera.updateProjectionMatrix = true
}
// Perspective returns whether the Camera is perspective or not (orthographic).
func (camera *Camera) Perspective() bool {
return camera.perspective
}
// SetFieldOfView sets the vertical field of the view of the camera in degrees.
func (camera *Camera) SetFieldOfView(fovY float64) {
if camera.fieldOfView == fovY {
return
}
camera.fieldOfView = fovY
camera.sphereFactorCalculated = false
camera.updateProjectionMatrix = true
}
// FieldOfView returns the vertical field of view in degrees.
func (camera *Camera) FieldOfView() float64 {
return camera.fieldOfView
}
// SetOrthoScale sets the scale of an orthographic camera in world units across (horizontally).
func (camera *Camera) SetOrthoScale(scale float64) {
if camera.orthoScale == scale {
return
}
camera.orthoScale = scale
camera.sphereFactorCalculated = false
camera.updateProjectionMatrix = true
}
// OrthoScale returns the scale of an orthographic camera in world units across (horizontally).
func (camera *Camera) OrthoScale() float64 {
return camera.orthoScale
}
// Near returns the near plane of a camera.
func (camera *Camera) Near() float64 {
return camera.near
}
// SetNear sets the near plane of a camera.
func (camera *Camera) SetNear(near float64) {
if camera.near == near {
return
}
camera.near = near
camera.sphereFactorCalculated = false
camera.updateProjectionMatrix = true
}
// Far returns the far plane of a camera.
func (camera *Camera) Far() float64 {
return camera.far
}
// SetFar sets the far plane of the camera.
func (camera *Camera) SetFar(far float64) {
if camera.far == far {
return
}
camera.far = far
camera.sphereFactorCalculated = false
camera.updateProjectionMatrix = true
}
// We do this for each vertex for each triangle for each model, so we want to avoid allocating vectors if possible. clipToScreen
// does this by taking outVec, a vertex (Vector) that it stores the values in and returns, which avoids reallocation.
func (camera *Camera) clipToScreen(vert Vector, vertID int, model *Model, width, height, halfWidth, halfHeight float64, limitW bool) Vector {
v3 := vert.W
if limitW {
if !camera.perspective {
v3 = 1.0
}
// If the trangle is beyond the screen, we'll just pretend it's not and limit it to the closest possible value > 0
// TODO: Replace this with triangle clipping or fix whatever graphical glitch seems to arise periodically
if v3 < 0 {
v3 = 0.000001
}
} else {
if v3 < 0 {
v3 *= -1
}
}
// Again, this function should only be called with pre-transformed 4D vertex arguments.
// It's 1 frame faster on the stress test not to have to calculate the half screen width and height here.
vert.X = (vert.X/v3)*width + halfWidth
vert.Y = (vert.Y/-v3)*height + halfHeight
vert.Z = vert.Z / v3
vert.W = 1
return vert
}
// ClipToScreen projects the pre-transformed vertex in View space and remaps it to screen coordinates.
func (camera *Camera) ClipToScreen(vert Vector) Vector {
width, height := camera.Size()
return camera.clipToScreen(vert, 0, nil, float64(width), float64(height), float64(width)/2, float64(height)/2, false)
}
// WorldToScreenPixels transforms a 3D position in the world to a position onscreen, with X and Y representing the pixels.
// The Z coordinate indicates depth away from the camera in 3D world units.
func (camera *Camera) WorldToScreenPixels(vert Vector) Vector {
v := NewMatrix4Translate(vert.X, vert.Y, vert.Z).Mult(camera.ViewMatrix().Mult(camera.Projection()))
width, height := camera.Size()
return camera.clipToScreen(v.MultVecW(NewVectorZero()), 0, nil, float64(width), float64(height), float64(width)/2, float64(height)/2, false)
}
// WorldToScreen transforms a 3D position in the world to a 2D vector, with X and Y ranging from -1 to 1.
// The Z coordinate indicates depth away from the camera in 3D world units.
func (camera *Camera) WorldToScreen(vert Vector) Vector {
v := camera.WorldToScreenPixels(vert)
w, h := camera.Size()
v.X /= float64(w) / 2
v.X -= 1
v.Y /= float64(h) / 2
v.Y -= 1
return v
}
// ScreenToWorldPixels converts an x and y pixel position on screen to a 3D point in front of the camera.
// The depth argument changes how deep the returned Vector is in 3D world units.
func (camera *Camera) ScreenToWorldPixels(x, y int, depth float64) Vector {
w := camera.ColorTexture().Bounds().Dx()
h := camera.ColorTexture().Bounds().Dy()
x = clamp(x, 0, w)
y = clamp(y, 0, h)
// For whatever reason, the depth isn't being properly transformed, so I do it manually sorta below
vec := Vector{float64(x)/float64(w) - 0.5, -(float64(y)/float64(h) - 0.5), -1, 1}
return camera.screenToWorldTransform(vec, depth)
}
// ScreenToWorld converts an x and y position on screen to a 3D point in front of the camera.
// x and y are values ranging between -0.5 and 0.5 for both the horizontal and vertical axes.
// The depth argument changes how deep the returned Vector is in 3D world units.
func (camera *Camera) ScreenToWorld(x, y, depth float64) Vector {
// x = clamp(x, -0.5, 0.5)
// y = clamp(y, -0.5, 0.5)
vec := Vector{x, y, -1, 1}
return camera.screenToWorldTransform(vec, depth)
}
func (camera *Camera) screenToWorldTransform(vec Vector, depth float64) Vector {
projection := camera.ViewMatrix().Mult(camera.Projection()).Inverted()
vecOut := projection.MultVecW(vec)
vecOut.X /= vecOut.W
vecOut.Y /= vecOut.W
vecOut.Z /= vecOut.W
// TODO: This part shouldn't be necessary if the inverted projection matrix properly transformed the depth part
// back into the Vector, but for whatever reason, it's not working, so here I basically hack in a manual solution
diff := vecOut.Sub(camera.WorldPosition()).Unit()
vecOut = camera.WorldPosition().Add(diff.Scale(depth))
return vecOut
}
// WorldUnitToViewRangePercentage converts a unit of world space into a percentage of the view range.
// Basically, let's say a camera's far range is 100 and its near range is 0.
// If you called camera.WorldUnitToViewRangePercentage(50), it would return 0.5.
// This function is primarily useful for custom depth functions operating on Materials.
func (camera *Camera) WorldUnitToViewRangePercentage(unit float64) float64 {
return unit / (camera.far - camera.near)
}
// int glhUnProjectf(float winx, float winy, float winz, float *modelview, float *projection, int *viewport, float *objectCoordinate)
// {
// // Transformation matrices
// float m[16], A[16];
// float in[4], out[4];
// // Calculation for inverting a matrix, compute projection x modelview
// // and store in A[16]
// MultiplyMatrices4by4OpenGL_FLOAT(A, projection, modelview);
// // Now compute the inverse of matrix A
// if(glhInvertMatrixf2(A, m)==0)
// return 0;
// // Transformation of normalized coordinates between -1 and 1
// in[0]=(winx-(float)viewport[0])/(float)viewport[2]*2.0-1.0;
// in[1]=(winy-(float)viewport[1])/(float)viewport[3]*2.0-1.0;
// in[2]=2.0*winz-1.0;
// in[3]=1.0;
// // Objects coordinates
// MultiplyMatrixByVector4by4OpenGL_FLOAT(out, m, in);
// if(out[3]==0.0)
// return 0;
// out[3]=1.0/out[3];
// objectCoordinate[0]=out[0]*out[3];
// objectCoordinate[1]=out[1]*out[3];
// objectCoordinate[2]=out[2]*out[3];
// return 1;
// }
// WorldToClip transforms a 3D position in the world to clip coordinates (before screen normalization).
func (camera *Camera) WorldToClip(vert Vector) Vector {
v := NewMatrix4Translate(vert.X, vert.Y, vert.Z).Mult(camera.ViewMatrix().Mult(camera.Projection()))
return v.MultVecW(NewVectorZero())
}
// PointInFrustum returns true if the point is visible through the camera frustum.
func (camera *Camera) PointInFrustum(point Vector) bool {
diff := point.Sub(camera.WorldPosition())
pcZ := diff.Dot(camera.cameraForward)
aspectRatio := camera.AspectRatio()
if pcZ > camera.far || pcZ < camera.near {
return false
}
if camera.perspective {
h := pcZ * camera.sphereFactorTang
pcY := diff.Dot(camera.cameraUp)
if -h > pcY || pcY > h {
return false
}
w := h * aspectRatio
pcX := diff.Dot(camera.cameraRight)
if -w > pcX || pcX > w {
return false
}
} else {
width := camera.orthoScale / 2
height := width / camera.AspectRatio()
pcY := diff.Dot(camera.cameraUp)
if -height > pcY || pcY > height {
return false
}
pcX := diff.Dot(camera.cameraRight)
if -width > pcX || pcX > width {
return false
}
}
return true
}
// SphereInFrustum returns true if the sphere would be visible through the camera frustum.
func (camera *Camera) SphereInFrustum(sphere *BoundingSphere) bool {
radius := sphere.WorldRadius()
diff := sphere.WorldPosition().Sub(camera.WorldPosition())
pcZ := diff.Dot(camera.cameraForward)
if pcZ > camera.far+radius || pcZ < camera.near-radius {
return false
}
if camera.perspective {
d := camera.sphereFactorY * radius
pcZ *= camera.sphereFactorTang
pcY := diff.Dot(camera.cameraUp)
if pcY > pcZ+d || pcY < -pcZ-d {
return false
}
pcZ *= camera.AspectRatio()
d = camera.sphereFactorX * radius
pcX := diff.Dot(camera.cameraRight)
if pcX > pcZ+d || pcX < -pcZ-d {
return false
}
} else {
width := camera.orthoScale
height := width / camera.AspectRatio()
pcY := diff.Dot(camera.cameraUp)
if -height/2-radius > pcY || pcY > height/2+radius {
return false
}
pcX := diff.Dot(camera.cameraRight)
if -width/2-radius > pcX || pcX > width/2+radius {
return false
}
}
return true
}
// ModelInFrustum returns if a model is onscreen when viewed through a Camera.
func (camera *Camera) ModelInFrustum(model *Model) bool {
model.Transform() // Make sure to update the transform of the Model as necessary.
return camera.SphereInFrustum(model.frustumCullingSphere)
}
// AspectRatio returns the camera's aspect ratio (width / height).
func (camera *Camera) AspectRatio() float64 {
w, h := camera.Size()
return float64(w) / float64(h)
}
// Clear should be called at the beginning of a single rendered frame and clears the Camera's backing textures
// before rendering.
// It also resets the debug values.
// This function will use the world's clear color, assuming the Camera is in a Scene that has a World.
// If the Scene has no World, or the Camera is not in the Scene, then it will clear using transparent black.
func (camera *Camera) Clear() {
if scene := camera.Scene(); scene != nil {
if world := scene.World; world != nil {
camera.ClearWithColor(world.ClearColor)
return
}
}
camera.ClearWithColor(NewColor(0, 0, 0, 0))
}
// ClearWithColor should be called at the beginning of a single rendered frame and clears the Camera's backing textures
// to the desired color before rendering.
// It also resets the debug values.
func (camera *Camera) ClearWithColor(clear Color) {
rgba := clear.ToNRGBA64()
if camera.AccumulationColorMode != AccumulationColorModeNone {
camera.accumulatedBackBuffer.Clear()
camera.accumulatedBackBuffer.DrawImage(camera.resultAccumulatedColorTexture, nil)
camera.resultAccumulatedColorTexture.Clear()
switch camera.AccumulationColorMode {
case AccumulationColorModeBelow:
camera.resultAccumulatedColorTexture.DrawImage(camera.accumulatedBackBuffer, camera.AccumulationDrawOptions)
camera.resultAccumulatedColorTexture.DrawImage(camera.resultColorTexture, nil)
case AccumulationColorModeAbove:
camera.resultAccumulatedColorTexture.DrawImage(camera.resultColorTexture, nil)
camera.resultAccumulatedColorTexture.DrawImage(camera.accumulatedBackBuffer, camera.AccumulationDrawOptions)
case AccumulationColorModeSingleLastFrame:
camera.resultAccumulatedColorTexture.DrawImage(camera.resultColorTexture, camera.AccumulationDrawOptions)
}
}
camera.resultColorTexture.Fill(rgba)
if camera.RenderDepth {
camera.resultDepthTexture.Clear()
}
if camera.RenderNormals {
camera.resultNormalTexture.Clear()
}
if time.Since(camera.DebugInfo.tickTime).Milliseconds() >= 100 {
camera.DebugInfo.FrameTime = camera.DebugInfo.currentFrameTime
camera.DebugInfo.AnimationTime = camera.DebugInfo.currentAnimationTime
camera.DebugInfo.LightTime = camera.DebugInfo.currentLightTime
camera.DebugInfo.tickTime = time.Now()
}
camera.DebugInfo.currentFrameTime = 0
camera.DebugInfo.currentAnimationTime = 0
camera.DebugInfo.currentLightTime = 0
camera.DebugInfo.DrawnParts = 0
camera.DebugInfo.BatchedParts = 0
camera.DebugInfo.TotalParts = 0
camera.DebugInfo.TotalTris = 0
camera.DebugInfo.DrawnTris = 0
camera.DebugInfo.LightCount = 0
camera.DebugInfo.ActiveLightCount = 0
cameraRot := camera.WorldRotation()
camera.cameraForward = cameraRot.Forward().Invert()
camera.cameraRight = cameraRot.Right()
camera.cameraUp = cameraRot.Up()
}
// RenderScene renders the provided Scene.
// Note that if Camera.RenderDepth is false, scenes rendered one after another in multiple RenderScene() calls will be rendered on top of
// each other in the Camera's texture buffers. Note that each MeshPart of a Model has a maximum renderable triangle count of 21845.
func (camera *Camera) RenderScene(scene *Scene) {
camera.RenderNodes(scene, scene.Root)
}
// RenderNodes renders all nodes starting with the provided rootNode using the Scene's properties (fog, for example). Note that if Camera.RenderDepth
// is false, scenes rendered one after another in multiple RenderScene() calls will be rendered on top of each other in the Camera's texture buffers.
// Note that each MeshPart of a Model has a maximum renderable triangle count of 21845.
func (camera *Camera) RenderNodes(scene *Scene, rootNode INode) {
meshes := []*Model{}
lights := []ILight{}
if model, isModel := rootNode.(*Model); isModel {
meshes = append(meshes, model)
}
if camera.SectorRendering {
// Gather sectors
sectors := rootNode.SearchTree().bySectors()
sectorModels := sectors.Models()
var insideSector *Sector
sectors.ForEach(func(node INode) bool {
sectorModel := node.(*Model)
sector := node.(*Model).sector
sector.rendering = false
// Set them all to be invisible by default
if sectorModel.DynamicBatchOwner == nil {
sector.rendering = false
} else {
// Making a sector dynamically batched is just way too much to deal with, I'm sorry
panic("Can't make a sector " + sectorModel.Path() + " dynamically batched as well")
}
if sector.AABB.PointInside(camera.WorldPosition()) {
if insideSector == nil || sector.AABB.Dimensions.MaxSpan() < insideSector.AABB.Dimensions.MaxSpan() {
insideSector = sector
}
}
return true
})
camera.currentSector = insideSector
if insideSector != nil {
insideSector.rendering = true
// Make neighbors visible
for r := range insideSector.NeighborsWithinRange(camera.SectorRenderDepth) {
r.rendering = true
}
rootNode.SearchTree().ByType(NodeTypeModel).ForEach(func(node INode) bool {
model := node.(*Model)
if model.sector != nil && model.sector.rendering {
if model.sector.rendering {
meshes = append(meshes, model)
}
} else if model.DynamicBatchOwner == nil {
// If something is dynamically batching, then we don't want to deal with sectors, because the batched objects belong to sectors.
if model.DynamicBatcher() {
meshes = append(meshes, model)
} else if model.SectorType() == SectorTypeStandalone || (model.SectorType() == SectorTypeObject && model.isInVisibleSector(sectorModels)) {
meshes = append(meshes, model)
} else if s := model.sectorHierarchy(); s != nil && s.rendering {
meshes = append(meshes, model)
}
}
return true
})
rootNode.SearchTree().ByType(NodeTypeLight).ForEach(func(node INode) bool {
light := node.(ILight)
if light.SectorType() == SectorTypeStandalone || (light.SectorType() == SectorTypeObject && light.isInVisibleSector(sectorModels)) {
lights = append(lights, light)
} else if s := light.sectorHierarchy(); s != nil && s.rendering {
lights = append(lights, light)
}
return true
})
}
// for _, s := range sectorModels {
// if s.sector.sectorVisible {
// }
// }
// // Make sectors and objects under their tree visible
// for _, s := range sectorModels {
// if s.sector.sectorVisible {
// search := s.SearchTree().INodes()
// meshes = append(meshes, s)
// for _, n := range search {
// if model, ok := n.(*Model); ok {
// meshes = append(meshes, model)
// }
// if light, ok := n.(ILight); ok && light.IsOn() {
// lights = append(lights, light)
// }
// }
// }
// }
// // Now search for non-Sectors
// nonSectorSearch := rootNode.SearchTree().ByFunc(func(node INode) bool {
// model, ok := node.(*Model)
// return !ok || model.sector == nil
// })
// nonSectorSearch.StopOnFiltered = true
// for _, i := range nonSectorSearch.INodes() {
// if model, ok := i.(*Model); ok {
// meshes = append(meshes, model)
// }
// if light, ok := i.(ILight); ok && light.IsOn() {
// lights = append(lights, light)
// }
// }
} else {
models := rootNode.SearchTree().Models()
lights = rootNode.SearchTree().ILights()
for _, model := range models {
if model.DynamicBatchOwner == nil {
meshes = append(meshes, model)
}
}
}
camera.Render(scene, lights, meshes...)
}
// CurrentSector returns the current sector the Camera is in, if sector-based rendering is enabled.
func (camera *Camera) CurrentSector() *Sector { return camera.currentSector }
type renderPair struct {
Model *Model
MeshPart *MeshPart
}
// Bayer Matrix for transparency dithering
var bayerMatrix = []float32{
1.0 / 17.0, 9.0 / 17.0, 3.0 / 17.0, 11.0 / 17.0,
13.0 / 17.0, 5.0 / 17.0, 15.0 / 17.0, 7.0 / 17.0,
4.0 / 17.0, 12.0 / 17.0, 2.0 / 17.0, 10.0 / 17.0,
16.0 / 17.0, 8.0 / 17.0, 14.0 / 17.0, 6.0 / 17.0,
}
// Render renders all of the models passed using the provided Scene's properties (fog, for example). Note that if Camera.RenderDepth
// is false, scenes rendered one after another in multiple Render() calls will be rendered on top of each other in the Camera's texture buffers.
// Note that each MeshPart of a Model has a maximum renderable triangle count of 21845.
func (camera *Camera) Render(scene *Scene, lights []ILight, models ...*Model) {
scene.HandleAutobatch()