Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

Night streaming: writes merged where they overlap; the TLAS's changed slots as ranges (#203)

Evan (Yifeng) Wang5291fccf2721
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index d3fe450..b028c3d 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -9,8 +9,9 @@ fn emitter_run(tris: &[crate::EmitterTri], instances: &[scene::Instance], record
first..first + tris[first..].iter().take_while(|e| e.inst == record).count()
}
-/// Writes to one buffer gathered during an edit and sent merged: adjacent ranges as one `write_buffer` (an edit writes
-/// hundreds of small records and meshes, contiguous in the room). Overlapping writes go in the order they came.
+/// Writes to one buffer gathered during an edit and sent merged: adjacent or overlapping ranges as one `write_buffer`
+/// (an edit writes hundreds of small records and meshes, contiguous in the room), overlapping bytes as the last write
+/// to them has them.
#[derive(Default)]
pub(super) struct Gather {
pub(super) parts: Vec<(u64, Vec<u8>)>,
@@ -33,29 +34,32 @@ impl Gather {
}
fn flush_at(self, q: &wgpu::Queue, b: &wgpu::Buffer, base: u64) {
- let mut parts = self.parts;
- let mut sorted = parts.clone();
- sorted.sort_by_key(|p| p.0);
- if sorted.windows(2).any(|w| w[0].0 + w[0].1.len() as u64 > w[1].0) {
- for (at, bytes) in parts.drain(..) {
- q.write_buffer(b, base + at, &bytes);
+ // Runs of the parts that touch or overlap, each one write; within a run the parts are copied in the order they
+ // came, so a later write wins where they overlap. (Overlapping parts, a new emitter's record and its path code
+ // written after, sent each part as a write of its own: 110,000 of them, 400 ms, in a commit of a streamed city.)
+ let parts = self.parts;
+ let mut by_at: Vec<usize> = (0..parts.len()).collect();
+ by_at.sort_by_key(|&i| parts[i].0);
+ let mut runs: Vec<(u64, u64)> = vec![];
+ let mut run_of = vec![0usize; parts.len()];
+ for &i in &by_at {
+ let (at, end) = (parts[i].0, parts[i].0 + parts[i].1.len() as u64);
+ match runs.last_mut() {
+ Some(r) if at <= r.1 => r.1 = r.1.max(end),
+ _ => runs.push((at, end)),
}
- return;
+ run_of[i] = runs.len() - 1;
}
- let mut run: Option<(u64, Vec<u8>)> = None;
- for (at, bytes) in sorted {
- match &mut run {
- Some((start, data)) if *start + data.len() as u64 == at => data.extend_from_slice(&bytes),
- _ => {
- if let Some((start, data)) = run.take() {
- q.write_buffer(b, base + start, &data);
- }
- run = Some((at, bytes));
- }
- }
+ let mut data: Vec<Vec<u8>> = runs.iter().map(|&(a, e)| vec![0u8; (e - a) as usize]).collect();
+ for (i, (at, bytes)) in parts.iter().enumerate() {
+ let k = run_of[i];
+ let o = (at - runs[k].0) as usize;
+ data[k][o..o + bytes.len()].copy_from_slice(bytes);
}
- if let Some((start, data)) = run {
- q.write_buffer(b, base + start, &data);
+ for ((start, _), d) in runs.iter().zip(&data) {
+ if !d.is_empty() {
+ q.write_buffer(b, base + start, d);
+ }
}
}
}
diff --git a/renderer/third_party/wgpu-core/PATCH.md b/renderer/third_party/wgpu-core/PATCH.md
index dbb9a97..00d554f 100644
--- a/renderer/third_party/wgpu-core/PATCH.md
+++ b/renderer/third_party/wgpu-core/PATCH.md
@@ -21,17 +21,19 @@ far up a slot was touched, nothing uses it, and its comment says as much.
## What
-- **wgpu** (`src/api/tlas.rs`, `src/api/device.rs`, `src/backend/wgpu_core.rs`): a `Tlas` keeps the range of slots
- touched since its last build (`dirty_lo..dirty_hi`, atomics: a build reads it through `&Tlas`). Every mutable
- accessor (`index_mut`, `get_mut_single`, `get_mut_slice`, both `IndexMut`s) widens it; a new TLAS starts with all of
- its slots dirty. A build hands wgpu-core that range alone, with where it starts (`first`) and how many slots the
- TLAS has (`total`), and resets it.
+- **wgpu** (`src/api/tlas.rs`, `src/api/device.rs`, `src/backend/wgpu_core.rs`): a `Tlas` keeps the ranges of
+ slots touched since its last build (`dirty`, behind a mutex: a build reads it through `&Tlas`). Every mutable
+ accessor (`index_mut`, `get_mut_single`, `get_mut_slice`, both `IndexMut`s) adds to it; a new TLAS starts with all
+ of its slots dirty. A build hands wgpu-core those slots alone, as sorted ranges (a few slots apart or closer merged),
+ with how many slots the TLAS has (`total`), and empties the list. (One range from the lowest touched slot to the
+ highest, the first version, wrote 340,000 of a streamed city's 575,000 slots at the 90th percentile: its changes fall
+ in free slots all over.)
- **wgpu-core** (`src/ray_tracing.rs`, `src/resource.rs`, `src/device/ray_tracing.rs`, `src/command/ray_tracing.rs`,
- `src/lock/rank.rs`, `src/device/trace/record.rs`): `TlasPackage` / `OwnedTlasPackage` carry `first` and `total`. A
+ `src/lock/rank.rs`, `src/device/trace/record.rs`): `TlasPackage` / `OwnedTlasPackage` carry `ranges` and `total`. A
TLAS keeps its slots between builds (`resource::TlasSlots`: each slot's BLAS, each BLAS once with how many slots name
it). A build:
- - serialises the changed slots alone and copies them to their place in the TLAS's instance buffer (the slots keep
- their positions: upstream packs the present instances together, so one removed moved all after it);
+ - serialises the changed slots alone and copies each run of them to its place in the TLAS's instance buffer (the
+ slots keep their positions: upstream packs the present instances together, so one removed moved all after it);
- writes an empty slot as a copy of the TLAS's first BLAS (`TlasSlots::null`, held for the TLAS's life) with mask 0
and a zero transform: no extent, never hit;
- builds over all `total` slots, from the instance buffer as it now is;
diff --git a/renderer/third_party/wgpu-core/src/command/ray_tracing.rs b/renderer/third_party/wgpu-core/src/command/ray_tracing.rs
index cfad21d..717ae25 100644
--- a/renderer/third_party/wgpu-core/src/command/ray_tracing.rs
+++ b/renderer/third_party/wgpu-core/src/command/ray_tracing.rs
@@ -2,7 +2,7 @@ use alloc::{sync::Arc, vec::Vec};
use core::{
cmp::max,
num::NonZeroU64,
- ops::{Deref, Range},
+ ops::Deref,
};
use wgt::{math::align_to, BufferUsages, BufferUses, Features};
@@ -46,9 +46,8 @@ struct UnsafeTlasStore<'a> {
struct TlasStore<'a> {
internal: UnsafeTlasStore<'a>,
- range: Range<usize>,
- /// ThreeRT patch: where in the instance buffer `range` goes (the first changed slot's).
- dst_offset: u64,
+ /// ThreeRT patch: the staging buffer's runs of changed slots and where each goes in the instance buffer.
+ copies: Vec<hal::BufferCopy>,
}
impl Global {
@@ -184,7 +183,7 @@ impl Global {
tlas: self.resolve_tlas_id(tlas_package.tlas_id)?,
instances,
lowest_unmodified: tlas_package.lowest_unmodified,
- first: tlas_package.first,
+ ranges: tlas_package.ranges,
total: tlas_package.total,
})
})
@@ -231,7 +230,6 @@ pub(crate) fn build_acceleration_structures(
u64::from(state.device.alignments.ray_tracing_scratch_buffer_alignment),
));
- let first_byte_index = instance_buffer_staging_source.len();
// ThreeRT patch (PATCH.md): the slots from `first` that changed; the TLAS keeps the rest from its last builds.
let mut slots = tlas.slots.lock();
@@ -248,11 +246,10 @@ pub(crate) fn build_acceleration_structures(
slots.blas.resize(total, None);
}
let key = |b: &Arc<Blas>| Arc::as_ptr(b) as usize;
- let mut k = package.first as usize;
- for instance in package.instances.iter() {
- if k >= total {
- break;
- }
+ // (the slots of the changed ranges, in order, as `instances` lists them)
+ let slots_of = package.ranges.iter().flat_map(|r| r.start as usize..(r.end as usize).min(total));
+ let mut copies: Vec<hal::BufferCopy> = Vec::new();
+ for (k, instance) in slots_of.zip(package.instances.iter()) {
if let Some(instance) = instance {
if instance.custom_data >= (1u32 << 24u32) {
return Err(BuildAccelerationStructureError::TlasInvalidCustomIndex(
@@ -328,8 +325,19 @@ pub(crate) fn build_acceleration_structures(
}
},
};
+ // (one copy a run of adjacent slots)
+ let (at, len) = (instance_buffer_staging_source.len() as u64, bytes.len() as u64);
+ match copies.last_mut() {
+ Some(c) if c.src_offset + c.size.get() == at && c.dst_offset + c.size.get() == k as u64 * len => {
+ c.size = wgt::BufferSize::new(c.size.get() + len).unwrap();
+ }
+ _ => {
+ if let Some(size) = wgt::BufferSize::new(len) {
+ copies.push(hal::BufferCopy { src_offset: at, dst_offset: k as u64 * len, size });
+ }
+ }
+ }
instance_buffer_staging_source.extend(bytes);
- k += 1;
}
// The TLAS's dependencies: each BLAS once (the null one among them).
let mut dependencies: Vec<Arc<Blas>> = slots.refs.values().map(|(b, _)| b.clone()).collect();
@@ -343,11 +351,6 @@ pub(crate) fn build_acceleration_structures(
}
// (no BLAS at all: an empty TLAS)
let instance_count = if slots.null.is_some() { total as u32 } else { 0 };
- let dst_offset = if k > package.first as usize {
- (instance_buffer_staging_source.len() - first_byte_index) as u64 / (k - package.first as usize) as u64 * package.first as u64
- } else {
- 0
- };
build_command.tlas_s_built.push(TlasBuild {
tlas: tlas.clone(),
@@ -366,8 +369,7 @@ pub(crate) fn build_acceleration_structures(
),
scratch_buffer_offset,
},
- range: first_byte_index..instance_buffer_staging_source.len(),
- dst_offset,
+ copies,
});
}
@@ -471,16 +473,14 @@ pub(crate) fn build_acceleration_structures(
}
let mut instance_buffer_barriers = Vec::new();
- for &TlasStore {
+ for TlasStore {
internal: UnsafeTlasStore { ref tlas, .. },
- ref range,
- dst_offset,
+ copies,
} in &tlas_storage
{
- let size = match wgt::BufferSize::new((range.end - range.start) as u64) {
- None => continue,
- Some(size) => size,
- };
+ if copies.is_empty() {
+ continue;
+ }
instance_buffer_barriers.push(hal::BufferBarrier::<dyn hal::DynBuffer> {
buffer: tlas.instance_buffer.as_ref(),
usage: hal::StateTransition {
@@ -496,15 +496,10 @@ pub(crate) fn build_acceleration_structures(
to: BufferUses::COPY_DST,
},
}]);
- let temp = hal::BufferCopy {
- src_offset: range.start as u64,
- dst_offset,
- size,
- };
raw_encoder.copy_buffer_to_buffer(
staging_buffer.as_ref().unwrap().raw(),
tlas.instance_buffer.as_ref(),
- &[temp],
+ copies,
);
}
}
diff --git a/renderer/third_party/wgpu-core/src/device/trace/record.rs b/renderer/third_party/wgpu-core/src/device/trace/record.rs
index 485e595..82ff759 100644
--- a/renderer/third_party/wgpu-core/src/device/trace/record.rs
+++ b/renderer/third_party/wgpu-core/src/device/trace/record.rs
@@ -419,7 +419,7 @@ impl IntoTrace for crate::ray_tracing::OwnedTlasPackage<ArcReferences> {
.map(|opt| opt.map(|inst| inst.into_trace()))
.collect(),
lowest_unmodified: self.lowest_unmodified,
- first: self.first,
+ ranges: self.ranges,
total: self.total,
}
}
diff --git a/renderer/third_party/wgpu-core/src/ray_tracing.rs b/renderer/third_party/wgpu-core/src/ray_tracing.rs
index 0e2de74..167a8df 100644
--- a/renderer/third_party/wgpu-core/src/ray_tracing.rs
+++ b/renderer/third_party/wgpu-core/src/ray_tracing.rs
@@ -328,11 +328,11 @@ pub struct TlasInstance<'a> {
pub struct TlasPackage<'a> {
pub tlas_id: TlasId,
- /// ThreeRT patch: the instances from `first` that changed since the last build (of `total`); the TLAS keeps the
- /// others (PATCH.md).
+ /// ThreeRT patch: the instances of the slots in `ranges` (in order), those that changed since the last build (of
+ /// `total`); the TLAS keeps the others (PATCH.md).
pub instances: Box<dyn Iterator<Item = Option<TlasInstance<'a>>> + 'a>,
pub lowest_unmodified: u32,
- pub first: u32,
+ pub ranges: Vec<core::ops::Range<u32>>,
pub total: u32,
}
@@ -430,8 +430,8 @@ pub struct OwnedTlasPackage<R: ReferenceType> {
pub tlas: R::Tlas,
pub instances: Vec<Option<OwnedTlasInstance<R>>>,
pub lowest_unmodified: u32,
- /// ThreeRT patch: where `instances` start among the TLAS's `total` (PATCH.md).
- pub first: u32,
+ /// ThreeRT patch: the slots `instances` are, among the TLAS's `total` (PATCH.md).
+ pub ranges: Vec<core::ops::Range<u32>>,
pub total: u32,
}
diff --git a/renderer/third_party/wgpu/src/api/device.rs b/renderer/third_party/wgpu/src/api/device.rs
index 38d41ed..a8374f6 100644
--- a/renderer/third_party/wgpu/src/api/device.rs
+++ b/renderer/third_party/wgpu/src/api/device.rs
@@ -782,8 +782,7 @@ impl Device {
instances: vec![None; desc.max_instances as usize],
lowest_unmodified: 0,
// (the first build writes every instance)
- dirty_lo: core::sync::atomic::AtomicU32::new(0),
- dirty_hi: core::sync::atomic::AtomicU32::new(desc.max_instances),
+ dirty: crate::util::Mutex::new(alloc::vec![(0, desc.max_instances)]),
}
}
}
diff --git a/renderer/third_party/wgpu/src/api/tlas.rs b/renderer/third_party/wgpu/src/api/tlas.rs
index 5d7d549..153fc57 100644
--- a/renderer/third_party/wgpu/src/api/tlas.rs
+++ b/renderer/third_party/wgpu/src/api/tlas.rs
@@ -4,7 +4,7 @@ use alloc::vec::Vec;
#[cfg(wgpu_core)]
use core::ops::Deref;
use core::ops::{Index, IndexMut, Range};
-use core::sync::atomic::{AtomicU32, Ordering};
+use crate::util::Mutex;
use wgt::WasmNotSendSync;
/// Descriptor to create top level acceleration structures.
@@ -25,10 +25,9 @@ pub struct Tlas {
pub(crate) inner: dispatch::DispatchTlas,
pub(crate) instances: Vec<Option<TlasInstance>>,
pub(crate) lowest_unmodified: u32,
- /// ThreeRT patch: the instances changed since the last build, `dirty_lo..dirty_hi` (empty when lo >= hi). A build
- /// hands only those to wgpu-core, which keeps the rest where the last build put them (third_party/wgpu-core/PATCH.md).
- pub(crate) dirty_lo: AtomicU32,
- pub(crate) dirty_hi: AtomicU32,
+ /// ThreeRT patch: the slots changed since the last build, as the ranges touched. A build hands only those to
+ /// wgpu-core, which keeps the rest where the last build put them (third_party/wgpu-core/PATCH.md).
+ pub(crate) dirty: Mutex<Vec<(u32, u32)>>,
}
impl Clone for Tlas {
@@ -37,8 +36,7 @@ impl Clone for Tlas {
inner: self.inner.clone(),
instances: self.instances.clone(),
lowest_unmodified: self.lowest_unmodified,
- dirty_lo: AtomicU32::new(self.dirty_lo.load(Ordering::Relaxed)),
- dirty_hi: AtomicU32::new(self.dirty_hi.load(Ordering::Relaxed)),
+ dirty: Mutex::new(self.dirty.lock().clone()),
}
}
}
@@ -111,16 +109,31 @@ impl Tlas {
/// ThreeRT patch: marks `range` changed (the next build hands it to wgpu-core).
fn touch(&self, range: Range<usize>) {
- self.dirty_lo.fetch_min(range.start as u32, Ordering::Relaxed);
- self.dirty_hi.fetch_max(range.end as u32, Ordering::Relaxed);
+ if range.start < range.end {
+ self.dirty.lock().push((range.start as u32, range.end as u32));
+ }
}
- /// ThreeRT patch: the changed range, taken (a build's).
+ /// ThreeRT patch: the changed slots, taken (a build's): sorted, ranges a few slots apart or closer merged (one copy
+ /// on the GPU each). One range from the lowest touched slot to the highest instead had a streamed city's builds
+ /// write 340,000 of 575,000 slots at the 90th percentile, its changes being scattered over the free slots.
#[cfg(wgpu_core)]
- pub(crate) fn take_dirty(&self) -> Range<u32> {
- let lo = self.dirty_lo.swap(u32::MAX, Ordering::Relaxed);
- let hi = self.dirty_hi.swap(0, Ordering::Relaxed).min(self.instances.len() as u32);
- if lo >= hi { 0..0 } else { lo..hi }
+ pub(crate) fn take_dirty(&self) -> Vec<Range<u32>> {
+ let mut d = core::mem::take(&mut *self.dirty.lock());
+ d.sort_unstable();
+ let n = self.instances.len() as u32;
+ let mut out: Vec<Range<u32>> = Vec::new();
+ for (a, b) in d {
+ let (a, b) = (a.min(n), b.min(n));
+ if a >= b {
+ continue;
+ }
+ match out.last_mut() {
+ Some(r) if a <= r.end + 8 => r.end = r.end.max(b),
+ _ => out.push(a..b),
+ }
+ }
+ out
}
/// Get a mutable slice to a range of instances.
diff --git a/renderer/third_party/wgpu/src/backend/wgpu_core.rs b/renderer/third_party/wgpu/src/backend/wgpu_core.rs
index 2a09d5e..e22c3c8 100644
--- a/renderer/third_party/wgpu/src/backend/wgpu_core.rs
+++ b/renderer/third_party/wgpu/src/backend/wgpu_core.rs
@@ -2872,11 +2872,13 @@ impl dispatch::CommandEncoderInterface for CoreCommandEncoder {
});
let tlas = tlas.into_iter().map(|e| {
- // ThreeRT patch: the instances changed since the last build, from `first` of `total` (wgpu-core keeps the
- // rest where its last build put them).
- let dirty = e.take_dirty();
- let instances = e.instances[dirty.start as usize..dirty.end as usize]
- .iter()
+ // ThreeRT patch: the instances changed since the last build, range after range of `total` (wgpu-core keeps
+ // the rest where its last build put them).
+ let ranges = e.take_dirty();
+ let instances = ranges
+ .clone()
+ .into_iter()
+ .flat_map(move |r| e.instances[r.start as usize..r.end as usize].iter())
.map(|instance: &Option<crate::TlasInstance>| {
instance
.as_ref()
@@ -2891,7 +2893,7 @@ impl dispatch::CommandEncoderInterface for CoreCommandEncoder {
tlas_id: e.inner.as_core().id,
instances: Box::new(instances),
lowest_unmodified: e.lowest_unmodified,
- first: dirty.start,
+ ranges,
total: e.instances.len() as u32,
}
});