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
use std::fmt;
use cgmath::{EuclideanSpace as _, InnerSpace as _, Point2, Vector2, Vector3};
use cgmath::{Point3, Vector4};
use ordered_float::NotNan;
#[cfg(feature = "rayon")]
use rayon::iter::{IntoParallelIterator as _, ParallelIterator as _};
use crate::block::{Evoxel, Resolution, AIR};
use crate::camera::{Camera, GraphicsOptions, TransparencyOption};
use crate::math::{smoothstep, GridCoordinate};
use crate::math::{Face, FreeCoordinate, GridPoint, Rgb, Rgba};
use crate::raycast::Ray;
use crate::space::{BlockIndex, GridArray, PackedLight, Space, SpaceBlockData};
mod pixel_buf;
pub use pixel_buf::*;
mod surface;
use surface::{DepthIter, DepthStep, Span, Surface, SurfaceIter, TraceStep};
mod text;
pub use text::*;
pub struct SpaceRaytracer<D: RtBlockData> {
blocks: Vec<TracingBlock<D>>,
cubes: GridArray<TracingCubeData>,
graphics_options: GraphicsOptions,
custom_options: D::Options,
sky_color: Rgb,
sky_data: D,
packed_sky_color: PackedLight,
}
impl<D: RtBlockData> SpaceRaytracer<D> {
pub fn new(
space: &Space,
graphics_options: GraphicsOptions,
custom_options: D::Options,
) -> Self {
let options = RtOptionsRef {
graphics_options: &graphics_options,
custom_options: &custom_options,
};
let sky_color = space.physics().sky_color;
SpaceRaytracer {
blocks: space
.block_data()
.iter()
.map(|sbd| TracingBlock::<D>::from_block(options, sbd))
.collect(),
cubes: prepare_cubes(space),
sky_color,
sky_data: D::sky(options),
packed_sky_color: sky_color.into(),
graphics_options,
custom_options,
}
}
pub fn trace_ray<P: PixelBuf<BlockData = D>>(&self, ray: Ray) -> (P, RaytraceInfo) {
let options = RtOptionsRef {
graphics_options: &self.graphics_options,
custom_options: &self.custom_options,
};
let t_to_absolute_distance = ray.direction.magnitude();
let mut s: TracingState<P> = TracingState::default();
let surface_iter = SurfaceIter::new(self, ray);
match self.graphics_options.transparency {
TransparencyOption::Volumetric => {
for step in DepthIter::new(surface_iter) {
if s.count_step_should_stop(options) {
break;
}
match step {
DepthStep::Invisible => {
}
DepthStep::Span(Span {
mut surface,
exit_t_distance,
}) => {
debug_assert!(!surface.diffuse_color.fully_transparent());
let thickness = ((exit_t_distance - surface.t_distance)
* t_to_absolute_distance)
as f32;
let unit_transmittance =
1.0 - surface.diffuse_color.alpha().into_inner();
let depth_transmittance = unit_transmittance.powf(thickness);
surface.diffuse_color = surface
.diffuse_color
.to_rgb()
.with_alpha(NotNan::new(1.0 - depth_transmittance).unwrap());
s.trace_through_surface(surface, self);
}
}
}
}
_ => {
for step in surface_iter {
if s.count_step_should_stop(options) {
break;
}
use TraceStep::*;
match step {
Invisible { .. } | EnterBlock { .. } => {
}
EnterSurface(surface) => {
debug_assert!(!surface.diffuse_color.fully_transparent());
s.trace_through_surface(surface, self);
}
}
}
}
}
s.finish(self.sky_color, &self.sky_data)
}
pub fn trace_scene_to_image<P, E, O>(
&self,
camera: &Camera,
encoder: E,
) -> (Box<[O]>, RaytraceInfo)
where
P: PixelBuf<BlockData = D>,
E: Fn(P) -> O + Send + Sync,
O: Send + Sync,
{
self.trace_scene_to_image_impl(camera, encoder)
}
#[cfg(feature = "rayon")]
fn trace_scene_to_image_impl<P, E, O>(
&self,
camera: &Camera,
encoder: E,
) -> (Box<[O]>, RaytraceInfo)
where
P: PixelBuf<BlockData = D>,
E: Fn(P) -> O + Send + Sync,
O: Send + Sync,
{
let viewport = camera.viewport();
let viewport_size = viewport.framebuffer_size.map(|s| s as usize);
let encoder = &encoder;
let output_iterator = (0..viewport_size.y)
.into_par_iter()
.map(move |ych| {
let y = viewport.normalize_fb_y(ych);
(0..viewport_size.x).into_par_iter().map(move |xch| {
let x = viewport.normalize_fb_x(xch);
let (pixel, info) =
self.trace_ray(camera.project_ndc_into_world(Point2::new(x, y)));
(encoder(pixel), info)
})
})
.flatten();
let (image, info_sum): (Vec<O>, rayon_helper::ParExtSum<RaytraceInfo>) =
output_iterator.unzip();
(image.into_boxed_slice(), info_sum.result())
}
#[cfg(not(feature = "rayon"))]
fn trace_scene_to_image_impl<P, E, O>(
&self,
camera: &Camera,
encoder: E,
) -> (Box<[O]>, RaytraceInfo)
where
P: PixelBuf<BlockData = D>,
E: Fn(P) -> O + Send + Sync,
O: Send + Sync,
{
let viewport = camera.viewport();
let viewport_size = viewport.framebuffer_size.map(|s| s as usize);
let mut image = Vec::with_capacity(viewport.pixel_count().expect("image too large"));
let mut total_info = RaytraceInfo::default();
for ych in 0..viewport_size.y {
let y = viewport.normalize_fb_y(ych);
for xch in 0..viewport_size.x {
let x = viewport.normalize_fb_x(xch);
let (pixel, info) =
self.trace_ray(camera.project_ndc_into_world(Point2::new(x, y)));
total_info += info;
image.push(encoder(pixel));
}
}
(image.into_boxed_slice(), total_info)
}
#[inline]
fn get_packed_light(&self, cube: GridPoint) -> PackedLight {
self.cubes
.get(cube)
.map(|b| b.lighting)
.unwrap_or(self.packed_sky_color)
}
#[inline]
fn get_lighting(&self, cube: GridPoint) -> Rgb {
self.cubes
.get(cube)
.map(|b| b.lighting.value())
.unwrap_or(self.sky_color)
}
fn get_interpolated_light(&self, point: Point3<FreeCoordinate>, face: Face) -> Rgb {
let above_surface_epsilon = 0.5 / 256.0;
let origin = point.to_vec() + face.normal_vector() * above_surface_epsilon;
let reference_frame = face.matrix(0).to_free();
let mut mix_1 = (origin.dot(reference_frame.x.truncate()) - 0.5).rem_euclid(1.0);
let mut mix_2 = (origin.dot(reference_frame.y.truncate()) - 0.5).rem_euclid(1.0);
fn flip_mix(
mix: &mut FreeCoordinate,
dir: Vector4<FreeCoordinate>,
) -> Vector3<FreeCoordinate> {
let dir = dir.truncate();
if *mix > 0.5 {
*mix = 1.0 - *mix;
-dir
} else {
dir
}
}
let dir_1 = flip_mix(&mut mix_1, reference_frame.x);
let dir_2 = flip_mix(&mut mix_2, reference_frame.y);
let mix_1 = smoothstep(mix_1);
let mix_2 = smoothstep(mix_2);
let get_light = |p: Vector3<FreeCoordinate>| {
self.get_packed_light(Point3::from_vec(
(origin + p).map(|s| s.floor() as GridCoordinate),
))
};
let lin_lo = -0.5;
let lin_hi = 0.5;
let near12 = get_light(lin_lo * dir_1 + lin_lo * dir_2);
let near1far2 = get_light(lin_lo * dir_1 + lin_hi * dir_2);
let near2far1 = get_light(lin_hi * dir_1 + lin_lo * dir_2);
let mut far12 = get_light(lin_hi * dir_1 + lin_hi * dir_2);
if !near1far2.valid() && !near2far1.valid() {
far12 = near12;
}
let near12 = near12.value_with_ambient_occlusion();
let near1far2 = near1far2.value_with_ambient_occlusion();
let near2far1 = near2far1.value_with_ambient_occlusion();
let far12 = far12.value_with_ambient_occlusion();
fn mix(x: Vector4<f32>, y: Vector4<f32>, a: FreeCoordinate) -> Vector4<f32> {
let a = a as f32;
x * (1. - a) + y * a
}
let v = mix(
mix(near12, near1far2, mix_2),
mix(near2far1, far12, mix_2),
mix_1,
);
Rgb::try_from(v.truncate() / v.w.max(0.1)).unwrap()
}
}
impl<D: RtBlockData> SpaceRaytracer<D> {
pub fn trace_scene_to_text<P, F, E>(
&self,
camera: &Camera,
line_ending: &str,
write: F,
) -> Result<RaytraceInfo, E>
where
P: PixelBuf<BlockData = D> + Into<String>,
F: FnMut(&str) -> Result<(), E>,
{
self.trace_scene_to_text_impl::<P, F, E>(camera, line_ending, write)
}
#[cfg(feature = "rayon")]
fn trace_scene_to_text_impl<P, F, E>(
&self,
camera: &Camera,
line_ending: &str,
mut write: F,
) -> Result<RaytraceInfo, E>
where
P: PixelBuf<BlockData = D> + Into<String>,
F: FnMut(&str) -> Result<(), E>,
{
let viewport = camera.viewport();
let viewport_size = viewport.framebuffer_size.map(|s| s as usize);
let output_iterator = (0..viewport_size.y)
.into_par_iter()
.map(move |ych| {
let y = viewport.normalize_fb_y(ych);
(0..viewport_size.x)
.into_par_iter()
.map(move |xch| {
let x = viewport.normalize_fb_x(xch);
let (buf, info) =
self.trace_ray::<P>(camera.project_ndc_into_world(Point2::new(x, y)));
(buf.into(), info)
})
.chain(Some((line_ending.to_owned(), RaytraceInfo::default())).into_par_iter())
})
.flatten();
let (text, info_sum): (String, rayon_helper::ParExtSum<RaytraceInfo>) =
output_iterator.unzip();
write(text.as_str())?;
Ok(info_sum.result())
}
#[cfg(not(feature = "rayon"))]
fn trace_scene_to_text_impl<P, F, E>(
&self,
camera: &Camera,
line_ending: &str,
mut write: F,
) -> Result<RaytraceInfo, E>
where
P: PixelBuf<BlockData = D> + Into<String>,
F: FnMut(&str) -> Result<(), E>,
{
let mut total_info = RaytraceInfo::default();
let viewport = camera.viewport();
let viewport_size = viewport.framebuffer_size.map(|s| s as usize);
for ych in 0..viewport_size.y {
let y = viewport.normalize_fb_y(ych);
for xch in 0..viewport_size.x {
let x = viewport.normalize_fb_x(xch);
let (buf, info) =
self.trace_ray::<P>(camera.project_ndc_into_world(Point2::new(x, y)));
total_info += info;
write(buf.into().as_str())?;
}
write(line_ending)?;
}
Ok(total_info)
}
pub fn trace_scene_to_string<P>(&self, camera: &Camera, line_ending: &str) -> String
where
P: PixelBuf<BlockData = D> + Into<String>,
{
let mut out = String::with_capacity(
camera.viewport().framebuffer_size.dot(Vector2::new(1, 1)) as usize,
);
self.trace_scene_to_text::<P, _, _>(camera, line_ending, |s| {
out.push_str(s);
Ok::<(), std::convert::Infallible>(())
})
.unwrap();
out
}
}
impl<D: RtBlockData> fmt::Debug for SpaceRaytracer<D>
where
D: fmt::Debug,
D::Options: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SpaceRaytracer")
.field("blocks.len", &self.blocks.len())
.field("cubes.grid", &self.cubes.grid())
.field("graphics_options", &self.graphics_options)
.field("custom_options", &self.custom_options)
.field("sky_color", &self.sky_color)
.finish_non_exhaustive()
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub struct RaytraceInfo {
cubes_traced: usize,
}
impl std::ops::AddAssign<RaytraceInfo> for RaytraceInfo {
fn add_assign(&mut self, other: Self) {
self.cubes_traced += other.cubes_traced;
}
}
impl std::iter::Sum for RaytraceInfo {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
let mut sum = Self::default();
for part in iter {
sum += part;
}
sum
}
}
#[inline]
fn prepare_cubes(space: &Space) -> GridArray<TracingCubeData> {
space.extract(space.grid(), |index, block_data, lighting| {
TracingCubeData {
block_index: index.unwrap(),
lighting,
always_invisible: block_data.block() == &AIR,
}
})
}
#[derive(Clone, Debug)]
struct TracingCubeData {
block_index: BlockIndex,
lighting: PackedLight,
always_invisible: bool,
}
#[derive(Clone, Debug)]
enum TracingBlock<D> {
Atom(D, Rgba),
Recur(D, Resolution, GridArray<Evoxel>),
}
impl<D: RtBlockData> TracingBlock<D> {
fn from_block(options: RtOptionsRef<'_, D::Options>, block_data: &SpaceBlockData) -> Self {
let evaluated = block_data.evaluated();
let pixel_block_data = D::from_block(options, block_data);
if let Some(ref voxels) = evaluated.voxels {
TracingBlock::Recur(pixel_block_data, evaluated.resolution, voxels.clone())
} else {
TracingBlock::Atom(pixel_block_data, evaluated.color)
}
}
}
#[derive(Clone, Debug, Default)]
struct TracingState<P: PixelBuf> {
cubes_traced: usize,
pixel_buf: P,
}
impl<P: PixelBuf> TracingState<P> {
#[inline]
fn count_step_should_stop(
&mut self,
options: RtOptionsRef<'_, <P::BlockData as RtBlockData>::Options>,
) -> bool {
self.cubes_traced += 1;
if self.cubes_traced > 1000 {
self.pixel_buf = Default::default();
self.pixel_buf
.add(Rgba::new(1.0, 1.0, 1.0, 1.0), &P::BlockData::error(options));
true
} else {
self.pixel_buf.opaque()
}
}
fn finish(mut self, sky_color: Rgb, sky_data: &P::BlockData) -> (P, RaytraceInfo) {
if self.cubes_traced == 0 {
self.pixel_buf.hit_nothing();
}
self.pixel_buf.add(sky_color.with_alpha_one(), sky_data);
if false {
self.pixel_buf = Default::default();
self.pixel_buf.add(
(rgb_const!(0.02, 0.002, 0.0) * self.cubes_traced as f32).with_alpha_one(),
sky_data,
);
}
(
self.pixel_buf,
RaytraceInfo {
cubes_traced: self.cubes_traced,
},
)
}
#[inline]
fn trace_through_surface(
&mut self,
surface: Surface<'_, P::BlockData>,
rt: &SpaceRaytracer<P::BlockData>,
) {
if let Some(color) = surface.to_lit_color(rt) {
self.pixel_buf.add(color, surface.block_data);
}
}
}
pub use updating::*;
mod updating;
#[cfg(feature = "rayon")]
mod rayon_helper {
use rayon::iter::{IntoParallelIterator, ParallelExtend, ParallelIterator as _};
use std::iter::{empty, once, Sum};
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct ParExtSum<T>(Option<T>);
impl<T: Sum> ParExtSum<T> {
pub fn result(self) -> T {
self.0.unwrap_or_else(|| empty().sum())
}
}
impl<T: Sum + Send> ParallelExtend<T> for ParExtSum<T> {
fn par_extend<I>(&mut self, par_iter: I)
where
I: IntoParallelIterator<Item = T>,
{
let new = par_iter.into_par_iter().sum();
self.0 = Some(match self.0.take() {
None => new,
Some(previous) => once(previous).chain(once(new)).sum(),
});
}
}
}