-
Notifications
You must be signed in to change notification settings - Fork 0
/
raytracer.nim
1780 lines (1599 loc) · 77.9 KB
/
raytracer.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import strformat, os, terminal, macros, math, random, times
import basetypes, hittables, camera
import arraymancer, unchained
import sdl2 except Color, Point
type
RenderContext = ref object
rnd: Rand
camera: Camera
world: HittablesList[RGBSpectrum]
worldXray: HittablesList[XraySpectrum] ## Copy of the world without any light sources.
sources: HittablesList[XraySpectrum] ## List of all light sources
targets: HittablesList[XraySpectrum] ## List of all targets for diffuse lights
buf: ptr UncheckedArray[uint32]
counts: ptr UncheckedArray[int]
window: SurfacePtr
numRays: int
width: int
height: int
maxDepth: int
numPer: int = -1 # only used for multithreaded case
numThreads: int = -1 # only used for multithreaded case
TracingType = enum
ttCamera, ttLights
SourceKind = enum
skSun, skXrayFinger, skParallelXrayFinger
Config = object
gridLines: bool
usePerfectMirror: bool
sourceKind: SourceKind
solarModelFile: string
chameleonFile: string # for chameleon images, hand this argument
energyMin: float
energyMax: float
rayAt = 1.0
setupRotation = 90.0.° # Angle the entire setup is rotated. This is the rotation to bring the downward pointing
# setup to the realistic sideways setup.
telescopeRotation = 14.17.° # *Additional* rotation of the telescope on top of `setupRotation`.
# Separate to include real rotation aside from pointing the entire setup.
windowRotation = 30.0.°
windowZOffset = 3.0
ignoreWindow = false
ignoreMagnet = true ## Whether to include the magnet
ignoreMirrorThickness = false
ignoreSpacer = false
mirrorThickness = Inf # adjust mirror thickenss. 0.2 by default
sensorKind = sCount
brokenMirrors = false # disables telescope mirror reflection for debugging
midTelescopeSensor = false
endTelescopeSensor = false # An ~ImageSensor~ directly at the end of the telescope. Useful to view
# the illumination of the telescope
# X-ray source fields
sourceDistance = 14.2.m # distance of the source ``from the telescope entrance``
sourceRadius = 3.0.mm
sourceOnOpticalAxis = false
# targets
visibleTarget: bool
targetRadius: MilliMeter = 0.mm
# misc
batchMode: bool = false
totalRays: int = 1_000_000 # number of rays for batch mode
shmOutfile: string = "/dev/shm/image_sensor.dat" ## The output file where to store the temp image senso data
bufOutdir: string = "out" ## directory where buffer binaries are stored
var Tracing = ttCamera
proc initConfig(visibleTarget, gridLines, usePerfectMirror: bool, sourceKind: SourceKind,
solarModelFile: string,
chameleonFile: string,
energyMin, energyMax: float,
rayAt: float, setupRotation, telescopeRotation, windowRotation: Degree, windowZOffset: float,
ignoreWindow: bool,
sensorKind: SensorKind,
brokenMirrors: bool,
midTelescopeSensor, endTelescopeSensor: bool,
ignoreMirrorThickness: bool,
mirrorThickness: float,
ignoreSpacer: bool,
ignoreMagnet: bool,
sourceDistance: Meter, sourceRadius: MilliMeter,
sourceOnOpticalAxis: bool,
targetRadius: MilliMeter,
batchMode: bool, totalRays: int,
shmOutfile: string,
bufOutdir: string
): Config =
result = Config(visibleTarget: visibleTarget,
gridLines: gridLines,
usePerfectMirror: usePerfectMirror,
sourceKind: sourceKind,
solarModelFile: solarModelFile,
chameleonFile: chameleonFile,
energyMin: energyMin,
energyMax: energyMax,
rayAt: rayAt,
setupRotation: setupRotation,
telescopeRotation: telescopeRotation,
windowRotation: windowRotation,
windowZOffset: windowZOffset,
ignoreWindow: ignoreWindow,
sensorKind: sensorKind,
brokenMirrors: brokenMirrors,
midTelescopeSensor: midTelescopeSensor,
endTelescopeSensor: endTelescopeSensor,
ignoreMirrorThickness: ignoreMirrorThickness,
mirrorThickness: mirrorThickness,
ignoreSpacer: ignoreSpacer,
ignoreMagnet: ignoreMagnet,
sourceDistance: sourceDistance,
sourceRadius: sourceRadius,
sourceOnOpticalAxis: sourceOnOpticalAxis,
targetRadius: targetRadius,
batchMode: batchMode, totalRays: totalRays,
shmOutfile: shmOutfile,
bufOutdir: bufOutdir)
proc initRenderContext(rnd: var Rand,
buf: ptr UncheckedArray[uint32], counts: ptr UncheckedArray[int],
window: SurfacePtr, numRays, width, height: int,
camera: Camera, world: GenericHittablesList, maxDepth: int,
numPer, numThreads: int): RenderContext =
var worldRGB = world.cloneAsRGB()
var worldXray = world.cloneAsXray()
let sources = worldXray.getSources(delete = true)
let targets = worldXray.getLightTargets(delete = true)
# filter invisible targets
worldRGB.removeInvisibleTargets()
result = RenderContext(rnd: rnd,
buf: buf, counts: counts,
window: window,
numRays: numRays, width: width, height: height,
camera: camera,
world: worldRGB,
worldXray: worldXray,
sources: sources,
targets: targets,
maxDepth: maxDepth,
numPer: numPer, numThreads: numThreads)
proc initRenderContext(rnd: var Rand,
buf: var Tensor[uint32], counts: var Tensor[int],
window: SurfacePtr, numRays, width, height: int,
camera: Camera, world: GenericHittablesList, maxDepth: int,
numPer: int = -1, numThreads: int = -1): RenderContext =
let bufP = cast[ptr UncheckedArray[uint32]](buf.unsafe_raw_offset())
var countsP = cast[ptr UncheckedArray[int]](counts.unsafe_raw_offset())
result = initRenderContext(rnd, bufP, countsP, window, numRays, width, height, camera, world, maxDepth, numPer, numThreads)
proc initRenderContexts(numThreads: int,
buf: var Tensor[uint32], counts: var Tensor[int],
window: SurfacePtr, numRays, width, height: int,
camera: Camera, world: GenericHittablesList, maxDepth: int): seq[RenderContext] =
result = newSeq[RenderContext](numThreads)
let numPer = (width * height) div numThreads
for i in 0 ..< numThreads:
let bufP = cast[ptr UncheckedArray[uint32]](buf.unsafe_raw_offset()[i * numPer].addr)
let countsP = cast[ptr UncheckedArray[int]](counts.unsafe_raw_offset()[i * numPer].addr)
## XXX: clone world?
var rnd = initRand(i * 0xfafe)
result[i] = initRenderContext(rnd, bufP, countsP, window, numRays, width, height, camera.clone(), world.clone(), maxDepth, numPer, numThreads)
when compileOption("threads"):
import malebolgia
let THREADS = ThreadPoolSize
else:
let THREADS = 1
proc rayColor*[S: SomeSpectrum](c: Camera, rnd: var Rand, r: Ray, world: HittablesList[S], depth: int): S {.gcsafe.} =
var rec: HitRecord[S]
if depth <= 0:
return toSpectrum(color(0, 0, 0), S)
if world.hit(r, 0.001, Inf, rec):
var scattered: Ray
var attenuation: S
var emitted = rec.mat.emit(rec.u, rec.v, rec.p)
if not rec.mat.scatter(rnd, r, rec, attenuation, scattered):
result = emitted
else:
result = attenuation * c.rayColor(rnd, scattered, world, depth - 1) + emitted
else:
result = toSpectrum(c.background, S)
when false: ## Old code with background gradient
let unitDirection = unitVector(r.dir)
let t = 0.5 * (unitDirection.y + 1.0)
result = (1.0 - t) * color(1.0, 1.0, 1.0) + t * color(0.5, 0.7, 1.0)
proc rayColorRecurse*[S: SomeSpectrum](
c: Camera, rnd: var Rand, r: Ray, world: HittablesList[S], depth: int,
accumulatedSpectrum: var S
): S {.gcsafe.} =
var rec: HitRecord[S]
if depth <= 0:
return toSpectrum(color(0, 0, 0), S)
if world.hit(r, 0.001, Inf, rec):
#if r.typ == rtLight:
# echo "Hit ", depth
var scattered: Ray
var attenuation = accumulatedSpectrum ## NOTE: `attenuation` starts with the current accumulated spectrum.
## That way `scatter` can both look at the current value while still
## using it as a buffer!
#if r.typ == rtLight and rec.mat.kind == mkImageSensor:
# echo "Current attenuation: ", attenuation
var emitted = rec.mat.emit(rec.u, rec.v, rec.p)
if not rec.mat.scatter(rnd, r, rec, attenuation, scattered):
result = emitted
else:
# Accumulate the spectrum down the call chain, that way `scatter` sees the up to date attenuation
accumulatedSpectrum = accumulatedSpectrum * attenuation + emitted
result = attenuation * c.rayColorRecurse(rnd, scattered, world, depth - 1, accumulatedSpectrum) + emitted
else:
result = toSpectrum(c.background, S)
proc rayColorRecurse*[S: SomeSpectrum](
c: Camera, rnd: var Rand, r: Ray, world: HittablesList[S], depth: int,
accumulatedSpectrum: S = toSpectrum(1, S)
): S {.gcsafe.} =
## Overload for no `accumulatedSpectrum` or non `var` argument.
var spectrum = accumulatedSpectrum # variable only needed due to recursive calls to update
result = rayColorRecurse(c, rnd, r, world, depth, spectrum)
proc rayColorAndPos*[S: SomeSpectrum](c: Camera, rnd: var Rand, r: Ray,
initialColor: S, world: HittablesList[S],
depth: int): (S, float, float) {.gcsafe.} =
var rec: HitRecord[S]
echo "Start==============================\n\n"
proc recurse[S: SomeSpectrum](rec: var HitRecord[S], c: Camera, rnd: var Rand,
r: Ray, world: HittablesList[S], depth: int,
initialColor: S): S =
echo "Depth = ", depth
if depth <= 0:
return toSpectrum(0, S)
#var color: Color = initialColor
result = initialColor
if world.hit(r, 0.001, Inf, rec):
#echo "Hit: ", rec.p, " mat: ", rec.mat, " at depth = ", depth, " rec: ", rec
var scattered: Ray
var attenuation: S
var emitted = rec.mat.emit(rec.u, rec.v, rec.p)
if rec.mat.kind == mkImageSensor:
result = toSpectrum(1, S) ## Here we return 1 so that the function call above terminates correctly
discard
elif not rec.mat.scatter(rnd, r, rec, attenuation, scattered):
result = emitted
else:
let angle = arccos(scattered.dir.dot(rec.normal)).radToDeg
echo "Scattering angle : ", angle
result = attenuation * recurse(rec, c, rnd, scattered, world, depth - 1, initialColor) + emitted
#let res =
#if rec.mat.kind == mkImageSensor:
#
#else:
# result = attenuation * res + emitted
else:
result = toSpectrum(c.background, S)
let color = recurse(rec, c, rnd, r, world, depth, initialColor)
echo "------------------------------Finish\n\n"
if rec.mat.kind == mkImageSensor: # and color != initialColor:
## In this case return color and position
echo "Initial color? ", color, " rec.mat: ", rec.mat, " at ", (rec.u, rec.v)
result = (color, rec.u, rec.v)
else: # else just return nothing
result = (toSpectrum(0, S), 0, 0)
when false: ## Old code with background gradient
let unitDirection = unitVector(r.dir)
let t = 0.5 * (unitDirection.y + 1.0)
result = (1.0 - t) * color(1.0, 1.0, 1.0) + t * color(0.5, 0.7, 1.0)
proc writeColor*(f: File, color: Color, samplesPerPixel: int) =
let scale = 1.0 / samplesPerPixel.float
let
r = sqrt(color.r * scale)
g = sqrt(color.g * scale)
b = sqrt(color.b * scale)
f.write(&"{(256 * r.clamp(0, 0.999)).int} {(256 * g.clamp(0, 0.999)).int} {(256 * b.clamp(0, 0.999)).int}\n")
proc writeColor*(f: File, color: Color) =
f.write(&"{color.r} {color.g} {color.b}\n")
proc toColor(u: uint32 | int32): Color =
result[0] = ((u and 0xFF0000) shr 16).float / 256.0
result[1] = ((u and 0x00FF00) shr 8).float / 256.0
result[2] = (u and 0x0000FF).float / 256.0
proc toUInt32(c: ColorU8): uint32
proc toColorU8(c: Color, samplesPerPixel: int = 1): ColorU8 {.inline.} =
let scale = 1.0 / samplesPerPixel.float
let
r = 256 * clamp(c.r * scale, 0, 0.999)
g = 256 * clamp(c.g * scale, 0, 0.999)
b = 256 * clamp(c.b * scale, 0, 0.999)
result = (r: r.uint8, g: g.uint8, b: b.uint8)
#echo c.repr, " and result ", result, " and asuint32 ", result.toUint32, " and back ", result.toUint32.toColor.repr
proc gammaCorrect*(c: Color): Color =
result[0] = sqrt(c.r)
result[1] = sqrt(c.g)
result[2] = sqrt(c.b)
proc toUInt32(c: ColorU8): uint32 =
result = (#255 shl 24 or
c.r.int shl 16 or
c.g.int shl 8 or
c.b.int).uint32
proc render*(img: Image, f: string,
rnd: var Rand,
world: var HittablesList,
camera: Camera,
samplesPerPixel, maxDepth: int) =
## Write a ppm file to `f`
var f = open(f, fmWrite)
f.write(&"P3\n{img.width} {img.height}\n255\n")
for j in countdown(img.height - 1, 0):
stderr.write(&"\rScanlines remaining: {j}")
for i in 0 ..< img.width:
var pixelColor = color(0, 0, 0)
for s in 0 ..< samplesPerPixel:
let r = camera.getRay(rnd, i, j)
pixelColor += camera.rayColor(rnd, r, world, maxDepth)
f.writeColor(pixelColor, samplesPerPixel)
f.close()
proc renderMC*(img: Image, f: string,
rnd: var Rand,
world: var HittablesList,
camera: Camera,
samplesPerPixel, maxDepth: int) =
## Write a ppm file to `f`
var f = open(f, fmWrite)
f.write(&"P3\n{img.width} {img.height}\n255\n")
var numRays = samplesPerPixel * img.width * img.height
var buf = newTensor[Color](@[img.height, img.width])
var counts = newTensor[int](@[img.height, img.width])
var idx = 0
while idx < numRays:
let x = rnd.rand(img.width)
let y = rnd.rand(img.height)
let r = camera.getRay(rnd, x, y)
let color = camera.rayColor(rnd, r, world, maxDepth)
buf[y, x] = buf[y, x] + color
counts[y, x] = counts[y, x] + 1
inc idx
if idx mod (img.width * img.height) == 0:
let remain = numRays - idx
stderr.write(&"\rRays remaining: {remain}")
for j in countdown(img.height - 1, 0):
stderr.write(&"\rScanlines remaining: {j}")
for i in 0 ..< img.width:
f.writeColor(buf[j, i], counts[j, i])
f.close()
proc sampleRay[S: SomeSpectrum](rnd: var Rand, sources, targets: HittablesList[S]): (Ray, S) {.gcsafe.} =
## Sample a ray from one of the sources
# 1. pick a sources
let num = sources.len
let idx = if num == 1: 0 else: rnd.rand(num - 1) ## XXX: For now uniform sampling between sources!
let source = sources[idx]
# 2. sample from source
let p = samplePoint(source, rnd)
# 3. get the color of the source
let pOrigin = source.transform(p) # convert point back to object space to get point from center of source
let spectrum = source.getMaterial.emitAxion(pOrigin, source.getRadius())
# 4. depending on the source material choose direction
case source.getMaterial.kind
of mkLaser: # lasers just sample along the normal of the material
let dir = vec3(0.0, 0.0, -1.0) ## XXX: make this the normal surface!
result = (initRay(p, dir, rtLight), spectrum)
of mkDiffuseLight, mkSolarAxionEmission, mkSolarChameleonEmission: # diffuse light need a target
let numT = targets.len
if numT == 0:
raise newException(ValueError, "There must be at least one target for diffuse lights.")
let idxT = if numT == 1: 0 else: rnd.rand(numT - 1)
let target = targets[idxT]
let targetP = target.samplePoint(rnd)
let dir = normalize(targetP - p)
# For diffuse lights we propagate the ray *towards the target*
# and place it 1 before it. This is to avoid issues with ray intersections
# if the source is _very far_ away from the target.
#echo "Initial origin: ", p
var ray = initRay(p, dir, rtLight)
ray.orig = ray.at((targetP - p).length() - 1.0)
result = (ray, spectrum)
when false:# true:
block SanityCheck: # Check the produced ray actually hits the target
var rec: HitRecord
if not targets.hit(result[0], 0.001, Inf, rec):
doAssert false, "Sampled ray does not hit our target! " & $result
else: doAssert false, "Not a possible branch, these materials are not sources."
#echo "Sampled ray has angle to z axis: ", arccos(vec3(0.0,0.0,1.0).dot(result[0].dir)).radToDeg, " ray: ", result[0]
proc renderSdlFrame(ctx: RenderContext) =
var idx = 0
let
width = ctx.width
height = ctx.height
maxDepth = ctx.maxDepth
camera = ctx.camera
while idx < ctx.numRays:
var
yIdx: int
xIdx: int
color: Color
case Tracing
of ttCamera:
let x = ctx.rnd.rand(width - 1)
let y = ctx.rnd.rand(height - 1)
#if x.int >= window.w: continue
#if y.int >= window.h: continue
let r = camera.getRay(ctx.rnd, x, y)
color = toColor(camera.rayColorRecurse(ctx.rnd, r, ctx.world, maxDepth))
yIdx = y #height - y - 1
xIdx = x
of ttLights:
# 1. get a ray from a source
let (r, initialColor) = ctx.rnd.sampleRay(ctx.sources, ctx.targets)
# 2. trace it. Check if ray ended up on `ImageSensor`
let (c, u, v) = camera.rayColorAndPos(ctx.rnd, r, initialColor, ctx.worldXray, maxDepth)
if c.isBlack: continue
#echo r
#echo "empty?? ", c, " at ", (u, v)
# 3. if so, get the relative position on sensor, map to x/y
color = toColor c
xIdx = clamp((u * (width.float - 1.0)).round.int, 0, width)
yIdx = clamp((v * (height.float - 1.0)).round.int, 0, height)
when true:
# 1. get a ray from a source
for _ in 0 ..< 1:
let (r, initialColor) = ctx.rnd.sampleRay(ctx.sources, ctx.targets)
# 2. trace it
let c = camera.rayColorRecurse(ctx.rnd, r, ctx.worldXray, maxDepth, initialColor)
# this color itself is irrelevant, but might illuminate the image sensor!
let bufIdx = yIdx * height + xIdx
ctx.counts[bufIdx] = ctx.counts[bufIdx] + 1
let curColor = ctx.buf[bufIdx].toColor
let delta = (color.gammaCorrect - curColor) / ctx.counts[bufIdx].float
let newColor = curColor + delta
let cu8 = toColorU8(newColor)
let sdlColor = sdl2.mapRGB(ctx.window.format, cu8.r.byte, cu8.g.byte, cu8.b.byte)
ctx.buf[bufIdx] = sdlColor
inc idx
proc renderFrame(j: int, ctx: ptr RenderContext) {.gcsafe.} =
let ctx = ctx[]
let
width = ctx.width
height = ctx.height
maxDepth = ctx.maxDepth
camera = ctx.camera
numPer = ctx.numPer
let frm = numPer * j
## XXX: I removed the `-1` in the `else` branch, check!
## -> Seems to have fixed the 'empty pixels'
let to = if j == ctx.numThreads: width * height - 1 else: numPer * (j + 1) # - 1
var j = 0
while j < ctx.numRays:
let idx = ctx.rnd.rand(frm.float .. to.float)
let x = idx mod width.float
let y = idx.float / width.float
#if x.int >= window.w: continue
#if y.int >= window.h: continue
let r = camera.getRay(ctx.rnd, x.int, y.int)
let color = toColor camera.rayColor(ctx.rnd, r, ctx.world, maxDepth)
block LightSources:
# 1. get a ray from a source
if ctx.sources.len > 0:
for _ in 0 ..< 1:
let (r, spectrum) = ctx.rnd.sampleRay(ctx.sources, ctx.targets)
# 2. trace it
let c = camera.rayColorRecurse(ctx.rnd, r, ctx.worldXray, maxDepth, spectrum)
# this color itself is irrelevant, but might illuminate the image sensor!
ctx.counts[idx.int - frm] = ctx.counts[idx.int - frm] + 1
let curColor = ctx.buf[idx.int - frm].toColor
let delta = (color.gammaCorrect - curColor) / ctx.counts[idx.int - frm].float
let newColor = curColor + delta
let cu8 = toColorU8(newColor)
if false:# delta.r > 0.0 or delta.g > 0.0 or delta.b > 0.0 or curColor.r > 0 or curColor.g > 0 or curColor.b > 0:
echo "curColor = ", curColor
echo "color = ", color, " gamma corrected: ", color.gammaCorrect
echo "Delta = ", delta
echo "New = ", curColor + delta
echo "Cu8 = ", cu8
echo "\n"
let sdlColor = sdl2.mapRGB(ctx.window.format, cu8.r.byte, cu8.g.byte, cu8.b.byte)
ctx.buf[idx.int - frm] = sdlColor
inc j
proc renderBatchFrame(ctx: ptr RenderContext) {.gcsafe.} =
## Render only X-ray raytracer in batch mode
let ctx = ctx[]
let
maxDepth = ctx.maxDepth
camera = ctx.camera
doAssert ctx.sources.len > 0
for j in 0 ..< ctx.numRays:
let (r, spectrum) = ctx.rnd.sampleRay(ctx.sources, ctx.targets)
# 2. trace it
let c = camera.rayColorRecurse(ctx.rnd, r, ctx.worldXray, maxDepth, spectrum)
proc copyBuf(bufT: Tensor[uint32], window: SurfacePtr) =
var surf = fromBuffer[uint32](window.pixels, @[window.h.int, window.w.int])
if surf.shape == bufT.shape:
surf.copyFrom(bufT)
else:
echo "Buffer and window size don't match, slow copy!"
## have to copy manually, because surf smaller than bufT
for y in 0 ..< surf.shape[0]:
for x in 0 ..< surf.shape[1]:
surf[y, x] = bufT[y, x]
proc updateCamera(ctxs: var seq[RenderContext], camera: Camera) =
for ctx in mitems(ctxs):
ctx.camera = clone(camera)
proc writeData[T](p: ptr UncheckedArray[T], len, width, height: int, outpath, prefix: string): string =
## XXX: TODO use `nio`?
result = &"{outpath}/{prefix}_type_{$T}_len_{len}_width_{width}_height_{height}.dat"
echo "[INFO] Writing file: ", result
writeFile(result, toOpenArray(cast[ptr UncheckedArray[byte]](p), 0, len * sizeof(T)))
from std / times import now, `$`
import ggplotnim except Point, Color, colortypes, color
proc saveBuffers(bufT: Tensor[uint32], counts: Tensor[int], width, height: int,
world: GenericHittablesList,
bufOutdir: string,
shmOutfile: string = "/dev/shm/image_sensor.dat",
isBatch: bool = false) =
echo "[INFO] Writing buffers to binary files."
createDir(bufOutdir)
let tStr = $now()
if not isBatch:
let bufP = cast[ptr UncheckedArray[uint32]](bufT.unsafe_raw_offset())
discard bufP.writeData(bufT.size.int, width, height,
bufOutdir, &"buffer_{tStr}")
let countsP = cast[ptr UncheckedArray[int]](counts.unsafe_raw_offset())
discard countsP.writeData(counts.size.int, width, height,
bufOutdir, &"counts_{tStr}")
# now get all image sensors and write their data
let sensors = world.getImageSensors()
var idx = 0
for s in sensors:
let sm = s.getMaterial.mImageSensor.sensor
var prefix = &"image_sensor_{idx}_{tStr}_"
case s.kind
of htBox:
let physSize = s.hBox.boxMax - s.hBox.boxMin
prefix.add &"_dx_{physSize.x:.1f}_dy_{physSize.y:.1f}_dz_{physSize.z:.1f}"
else: discard
let fname = sm.buf.writeData(sm.len, sm.width, sm.height,
bufOutdir, prefix)
# copy last buffer to `/dev/shm/image_sensor.dat` for batch processing
copyFile(fname, shmOutfile)
inc idx
proc renderSdl*(img: Image, world: GenericHittablesList,
rnd: var Rand, # the *main thread* RNG
camera: Camera,
samplesPerPixel, maxDepth: int,
speed = 1.0, speedMul = 1.1,
numRays = 100,
batchMode = false, totalRays = 1_000_000,
bufOutdir = "out"
) =
discard sdl2.init(INIT_EVERYTHING)
var screen = sdl2.createWindow("Ray tracing".cstring,
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
img.width.cint, img.height.cint,
SDL_WINDOW_OPENGL);
var renderer = sdl2.createRenderer(screen, -1, 1)
if screen.isNil:
quit($sdl2.getError())
var current = 0
var mouseModeIsRelative = false
var mouseEnabled = false
var movementIsFree = true
var quit = false
var event = sdl2.defaultEvent
var window = sdl2.getsurface(screen)
# store original position from and to we look to reset using `backspace`
let origLookFrom = camera.lookFrom
let origLookAt = camera.lookAt
template resetBufs(bufT, counts: untyped): untyped {.dirty.} =
bufT.setZero()
counts.setZero()
var bufT = newTensor[uint32](@[img.height, img.width])
var counts = newTensor[int](@[img.height, img.width])
let width = img.width
let height = img.height
var speed = speed
## XXX: IMPLEMENT change of vertical field of view using mouse wheel! sort of a zoom
var lastLookFrom: Point
when compileOption("threads"):
var ctxSeq = initRenderContexts(THREADS,
bufT, counts, window, numRays, width, height, camera, world, maxDepth)
else:
let ctx = initRenderContext(rnd, bufT, counts, window, numRays, width, height, camera, world, maxDepth)
while not quit:
while pollEvent(event):
case event.kind
of QuitEvent:
quit = true
of KeyDown:
const dist = 1.0
case event.key.keysym.scancode
of SDL_SCANCODE_LEFT, SDL_SCANCODE_RIGHT, SDL_SCANCODE_A, SDL_SCANCODE_D:
let cL = (camera.lookFrom - camera.lookAt).Vec3d
let zAx = vec3(0.0, 1.0, 0.0)
let newFrom = point(speed * cL.cross(zAx).normalize())
var nCL: Point
var nCA: Point
if event.key.keysym.scancode in {SDL_SCANCODE_LEFT, SDL_SCANCODE_A}:
nCL = camera.lookFrom +. newFrom
nCA = camera.lookAt +. newFrom
else:
nCL = camera.lookFrom -. newFrom
nCA = camera.lookAt -. newFrom
camera.updateLookFromAt(nCL, nCA)
resetBufs(bufT, counts)
of SDL_SCANCODE_PAGEUP:
speed *= speedMul
echo "[INFO] New speed = ", speed
of SDL_SCANCODE_PAGEDOWN:
speed /= speedMul
echo "[INFO] New speed = ", speed
of SDL_SCANCODE_UP, SDL_SCANCODE_DOWN, SDL_SCANCODE_W, SDL_SCANCODE_S:
var cL = camera.lookFrom - camera.lookAt
if not movementIsFree:
cL[1] = 0.0
cL = speed * cL.normalize()
var nCL: Point
var nCA: Point
if event.key.keysym.scancode in {SDL_SCANCODE_UP, SDL_SCANCODE_W}:
nCL = camera.lookFrom -. point(cL)
nCA = camera.lookAt -. point(cL)
else:
nCL = camera.lookFrom +. point(cL)
nCA = camera.lookAt +. point(cL)
camera.updateLookFromAt(nCL, nCA)
resetBufs(bufT, counts)
of SDL_SCANCODE_LCTRL, SDL_SCANCODE_SPACE:
let cL = (camera.lookFrom - camera.lookAt).Vec3d
let zAx = vec3(1.0, 0.0, 0.0)
let newFrom = if cL.dot(zAx) > 0:
speed * point(cL.cross(zAx).normalize())
else:
speed * point(-cL.cross(zAx).normalize())
var nCL: Point
var nCA: Point
if event.key.keysym.scancode == SDL_SCANCODE_LCTRL:
nCL = camera.lookFrom -. newFrom
nCA = camera.lookAt -. newFrom
else:
nCL = camera.lookFrom +. newFrom
nCA = camera.lookAt +. newFrom
camera.updateLookFromAt(nCL, nCA)
resetBufs(bufT, counts)
of SDL_SCANCODE_TAB:
let nYaw = camera.yaw + PI
let nPitch = -camera.pitch
camera.updateYawPitchRoll(camera.lookFrom, nYaw, nPitch, 0.0)
resetBufs(bufT, counts)
of SDL_SCANCODE_BACKSPACE:
echo "Resetting view!"
camera.updateLookFromAt(origLookFrom, origLookAt)
resetBufs(bufT, counts)
of SDL_SCANCODE_N:
## activate free movement (n for noclip ;))
movementIsFree = not movementIsFree
of SDL_SCANCODE_T:
Tracing = if Tracing == ttLights: ttCamera else: ttLights
resetBufs(bufT, counts)
echo "[INFO]: Set tracing type to: ", Tracing
of SDL_SCANCODE_ESCAPE:
## 'Uncapture' the mouse
if mouseModeIsRelative:
discard setRelativeMouseMode(False32)
mouseModeIsRelative = false
mouseEnabled = false
echo "[INFO] Mouse disabled."
of SDL_SCANCODE_F5:
## Save the current data on the image sensor as well as the current camera buffer and counts buffer
saveBuffers(bufT, counts, width, height, world, bufOutdir = bufOutdir)
else: discard
of MousebuttonDown:
## activate relative mouse motion
if not mouseModeIsRelative:
discard setRelativeMouseMode(True32)
mouseModeIsRelative = true
mouseEnabled = true
echo "[INFO] Mouse enabled."
#if mouseEnabled: echo "[INFO] Mouse enabled."
#else: echo "[INFO] Mouse disabled."
of WindowEvent:
freeSurface(window)
window = sdl2.getsurface(screen)
of MouseMotion:
## for now just take a small fraction of movement as basis
if mouseEnabled:
let yaw = -event.motion.xrel.float / 1000.0
var pitch = -event.motion.yrel.float / 1000.0
var newLook: Vec3d
if not movementIsFree:
## TODO: fix me
newLook = (camera.lookAt - camera.lookFrom).Vec3d.rotateAround(camera.lookAt, yaw, 0, pitch)
camera.updateLookFrom(Point(newLook))
else:
let nYaw = camera.yaw + yaw
echo "Old yaw ", camera.yaw, " add yaw = ", yaw, " new yaw ", nYaw
let nPitch = camera.pitch + pitch
camera.updateYawPitchRoll(camera.lookFrom, nYaw, nPitch, 0.0)
echo "Now looking at: ", camera.lookAt, " from : ", camera.lookFrom, ", yaw = ", nYaw, ", pitch = ", nPitch
resetBufs(bufT, counts)
else: echo event.kind
discard lockSurface(window)
## rendering of this frame
when not compileOption("threads"):
renderSdlFrame(ctx)
copyBuf(bufT, window)
else:
## TODO: replace this by a long running background service to which we submit
## jobs and the await them? So we don't have the overhead!
if camera.lookFrom != lastLookFrom:
echo "[INFO] Current position (lookFrom) = ", camera.lookFrom, " at (lookAt) ", camera.lookAt
lastLookFrom = camera.lookFrom
ctxSeq.updateCamera(camera)
var m = createMaster()
m.awaitAll:
for j in 0 ..< THREADS:
m.spawn renderFrame(j, ctxSeq[j].addr)
copyBuf(bufT, window)
unlockSurface(window)
#sdl2.clear(arg.renderer)
sdl2.present(renderer)
if batchMode:
if numRays * current * ThreadPoolSize > totalRays:
# save all buffers
saveBuffers(bufT, counts, width, height, world, bufOutdir = bufOutdir)
# and stop
break
inc current
sdl2.quit()
proc renderBatch*(img: Image, world: GenericHittablesList,
rnd: var Rand, # the *main thread* RNG
camera: Camera,
maxDepth: int,
shmOutfile: string,
bufOutdir: string,
totalRays = 1_000_000
) =
# store original position from and to we look to reset using `backspace`
let width = img.width
let height = img.height
var bufT = zeros[uint32](@[img.height, img.width]) # dummy, we don't save them
var counts = zeros[int](@[img.height, img.width])
let raysPerThread = totalRays div THREADS
when compileOption("threads"): # pass SurfacePtr as `nil`. We don't need it here
var ctxSeq = initRenderContexts(THREADS,
bufT, counts, nil, raysPerThread, width, height, camera, world, maxDepth)
else:
let ctx = initRenderContext(rnd, bufT, counts, nil, raysPerThread, width, height, camera, world, maxDepth)
var m = createMaster()
m.awaitAll:
for j in 0 ..< THREADS:
m.spawn renderBatchFrame(ctxSeq[j].addr)
# save all buffers
saveBuffers(bufT, counts, width, height, world, shmOutfile = shmOutfile, bufOutdir = bufOutdir, isBatch = true)
# and stop
proc sceneRedBlue(): GenericHittablesList =
result = initGenericHittables()
let R = cos(Pi/4.0)
#world.add Sphere(center: point(0, 0, -1), radius: 0.5)
#world.add Sphere(center: point(0, -100.5, -1), radius: 100)
let matLeft = initMaterial(initLambertian(color(0,0,1)))
let matRight = initMaterial(initLambertian(color(1,0,0)))
result.add translate(vec3(-R, 0.0, -1.0), toHittable(Sphere(radius: R), matLeft))
result.add translate(vec3(R, 0, -1), toHittable(Sphere(radius: R), matRight))
proc mixOfSpheres(): GenericHittablesList =
result = initGenericHittables()
let matGround = initMaterial(initLambertian(color(0.8, 0.8, 0.0)))
let matCenter = initMaterial(initLambertian(color(0.1, 0.2, 0.5)))
# let matLeft = initMaterial(initMetal(color(0.8, 0.8, 0.8), 0.3))
let matLeft = initMaterial(initDielectric(1.5))
let matRight = initMaterial(initMetal(color(0.8, 0.6, 0.2), 1.0))
result.add translate(vec3(0.0, -100.5, -1), toHittable(Sphere(radius: 100), matGround))
result.add translate(vec3(0.0, 0.0, -1), toHittable(Sphere(radius: 0.5), matCenter))
result.add translate(vec3(-1.0, 0.0, -1), toHittable(Sphere(radius: 0.5), matLeft))
result.add translate(vec3(-1.0, 0.0, -1), toHittable(Sphere(radius: -0.4), matLeft))
result.add translate(vec3(1.0, 0.0, -1), toHittable(Sphere(radius: 0.5), matRight))
proc randomSpheres(rnd: var Rand, numBalls: int): HittablesList[RGBSpectrum] =
result = initHittables[RGBSpectrum]()
for a in -numBalls ..< numBalls:
for b in -numBalls ..< numBalls:
let chooseMat = rnd.rand(1.0)
var center = point(a.float + 0.9 * rnd.rand(1.0), 0.2, b.float + 0.9 * rnd.rand(1.0))
if (center - point(4, 0.2, 0)).length() > 0.9:
var sphereMaterial: Material[RGBSpectrum]
if chooseMat < 0.8:
# diffuse
let albedo = rnd.randomVec().Color * rnd.randomVec().Color
sphereMaterial = initMaterial(initLambertian(albedo))
result.add translate(center, toHittable(Sphere(radius: 0.2), sphereMaterial))
elif chooseMat < 0.95:
# metal
let albedo = rnd.randomVec(0.5, 1.0).Color
let fuzz = rnd.rand(0.0 .. 0.5)
sphereMaterial = initMaterial(initMetal(albedo, fuzz))
result.add translate(center, toHittable(Sphere(radius: 0.2), sphereMaterial))
else:
# glass
sphereMaterial = initMaterial(initDielectric(1.5))
result.add translate(center, toHittable(Sphere(radius: 0.2), sphereMaterial))
proc randomScene(rnd: var Rand, useBvh = true, numBalls = 11): GenericHittablesList =
## XXX: the BVH is also broken here :) Guess we just broke it completely, haha.
result = initGenericHittables()
let groundMaterial = initMaterial(initLambertian(color(0.5, 0.5, 0.5)))
result.add translate(vec3(0.0, -1000.0, 0.0), toHittable(Sphere(radius: 1000), groundMaterial))
let smallSpheres = rnd.randomSpheres(numBalls)
if useBvh:
result.add toHittable(rnd.initBvhNode(smallSpheres))
else:
result.add smallSpheres
let mat1 = initMaterial(initDielectric(1.5))
result.add translate(vec3(0.0, 1.0, 0.0), toHittable(Sphere(radius: 1.0), mat1))
let mat2 = initMaterial(initLambertian(color(0.4, 0.2, 0.1)))
result.add translate(vec3(-4.0, 1.0, 0.0), toHittable(Sphere(radius: 1.0), mat2))
let mat3 = initMaterial(initMetal(color(0.7, 0.6, 0.5), 0.0))
result.add translate(vec3(4.0, 1.0, 0.0), toHittable(Sphere(radius: 1.0), mat3))
proc sceneCast(): GenericHittablesList =
result = initGenericHittables()
let groundMaterial = initMaterial(initLambertian(color(0.2, 0.7, 0.2)))
let EarthR = 6_371_000.0
result.add translate(vec3(0.0, -EarthR - 5, 0.0), toHittable(Sphere(radius: EarthR), groundMaterial))
#let concrete = initMaterial(initLambertian(color(0.5, 0.5, 0.5)))
#let airportWall = initXyRect(-10, 0, 0, 10, 10, mat = concrete)
#result.add airportWall
let strMetal = initMaterial(initMetal(color(0.6, 0.6, 0.6), 0.2))
let telBox = rotateX(toHittable(initBox(point(-2, 1.5, 4), point(0, 1.75, 5.5)),
strMetal), 30.0.°)
result.add telBox
let concreteMaterial = initMaterial(initLambertian(color(0.6, 0.6, 0.6)))
let controlRoom = toHittable(initBox(point(1, 0.0, 0.0), point(4, 2.2, 2.2)), concreteMaterial)
result.add controlRoom
let floorMaterial = initMaterial(initLambertian(color(0.7, 0.7, 0.7)))
let upperFloor = toHittable(initBox(point(-4, 0.0, -100), point(20, 2.0, 0)), floorMaterial)
result.add upperFloor
let glass = initMaterial(initDielectric(1.5))
let railing = toHittable(initBox(point(-4, 2.0, -0.1), point(10, 2.6, 0)), floorMaterial)
result.add railing
let SunR = 695_700_000.0
let AU = 1.496e11
let pos = point(AU / 10.0, AU / 10.0, AU).normalize * AU
echo pos.repr
let sunMat = initMaterial(initLambertian(color(1.0, 1.0, 0.0)))
result.add translate(pos, toHittable(Sphere(radius: SunR), sunMat))
#result.add toHittable(Disk(distance: 3.3, radius: 10.0), concreteMaterial)
proc sceneDisk(): GenericHittablesList =
result = initGenericHittables()
let groundMaterial = initMaterial(initLambertian(color(0.2, 0.7, 0.2)))
result.add toHittable(Disk(distance: 1.5, radius: 1.5), groundMaterial)
proc sceneTest(rnd: var Rand): GenericHittablesList =
result = initGenericHittables()
let groundMaterial = initMaterial(initLambertian(color(0.2, 0.7, 0.2)))
let EarthR = 6_371_000.0
result.add translate(point(0, -EarthR - 5, 0), toHittable(Sphere(radius: EarthR), groundMaterial))
let smallSpheres = rnd.randomSpheres(3)
result.add toHittable(rnd.initBvhNode(smallSpheres))
let matBox = initMaterial(initLambertian(color(1,0,0)))
when false:
let center = -vec3(1.0, 1.75, 5.5) / 2.0
let telBox1 = rotateX(
translate(
initBox(point(0, 0, 0), point(1, 1.75, 5.5), matBox),
center),
0.0.°)
let telBox2 = rotateX(
translate(
initBox(point(0, 0, 0), point(1, 1.75, 5.5), matBox),
center),
-50.0.°)
result.add telBox1
result.add telBox2
elif false:
let center = vec3(-0.5, -0.5, -0.5)#vec3(0.0, 0.0, 0.0) #vec3(0.5, 0.5, 0.5)
let telBox1 = rotateZ(
translate(
initBox(point(0, 0, 0), point(1, 1, 1), matBox),
center),
0.0.°)
let telBox2 = rotateZ(
translate(
initBox(point(0, 0, 0), point(1, 1, 1), matBox),
center),
-50.0.°)
result.add telBox1
result.add telBox2
let cylMetal = initMaterial(initMetal(color(0.6, 0.6, 0.6), 0.2))
#let cyl = Cylinder(radius: 3.0, zMin: 0.0, zMax: 5.0, phiMax: 180.0.degToRad), cylMetal)
let cyl = toHittable(Cone(radius: 3.0, zMax: 4.0, height: 5.0, phiMax: 360.0.degToRad), cylMetal)
#let cyl = toHittable(Sphere(radius: 3.0), cylMetal)
let center = vec3(0'f64, 0'f64, 0'f64)#vec3(0.5, 0.5, 0.5)
let h = rotateX(#cyl,
translate(
cyl,
center),
90.0.°)
result.add h
#
#let conMetal = initMaterial(initMetal(color(0.9, 0.9, 0.9), 0.2))
#let con = translate(vec3(3.0, 3.0, 0.0),
# Cone(radius: 2.0, height: 5.0, zMax: 3.0, phiMax: 180.0.degToRad), conMetal))
#result.add con
#let ball0 = translate(vec3(1.0, -2.0, -4.0), toHittable(Sphere(radius: 1.5), strMetal))