use super::pipeline_state::Pipeline;
use crate::lights::shadow::{cascade_frusta, shadow_layer_size, Caster, MAX_SHADOW_RECORDS};
use bytemuck::{Pod, Zeroable};
use std::collections::HashMap;
use std::sync::Arc;
use super::gpu_mesh::{geom_cache_key, GpuMesh};
use super::gpu_texture::{
cube_cache_key, tex_cache_key, GpuCubeTexture, GpuTexture, MipGenerator, TexCacheKey,
};
use super::gpu_timer::GpuTimer;
type TexBgKey = (
[Option<(TexCacheKey, u32)>; 8],
(usize, u32),
usize,
(usize, u32),
);
type VariantBgKey = (
super::material_maps::MapVariant,
Vec<(TexCacheKey, u32, u32, [u32; 6])>,
(usize, u32),
[[u32; 4]; 6],
usize,
);
type DrawItem<M> = (M, Option<(u32, u32)>);
fn variant_bg_key(
slots: &MaterialTextureSlots,
v: super::material_maps::MapVariant,
morph: (usize, u32),
uniforms: [[f32; 4]; 6],
) -> VariantBgKey {
let maps = super::material_maps::role_textures(slots)
.into_iter()
.filter(|(r, _)| v.contains(*r))
.filter_map(|(_, t)| t)
.map(|t| {
let sampler = sampler_index(t) as u32;
let [r0, r1] = t.uv_transform_rows();
let xform = [
r0[0].to_bits(),
r0[1].to_bits(),
r0[2].to_bits(),
r1[0].to_bits(),
r1[1].to_bits(),
r1[2].to_bits(),
];
(
tex_cache_key(t),
t.external_rt_id.unwrap_or(u32::MAX),
sampler,
xform,
)
})
.collect();
let env = slots
.env_map
.as_ref()
.map_or(0, |c| std::sync::Arc::as_ptr(c) as usize);
(v, maps, morph, uniforms.map(|r| r.map(f32::to_bits)), env)
}
fn tex_slot_key(slot: &Option<std::sync::Arc<crate::Texture>>) -> Option<(TexCacheKey, u32)> {
slot.as_ref()
.map(|t| (tex_cache_key(t), t.external_rt_id.unwrap_or(u32::MAX)))
}
fn tex_bg_key(slots: &MaterialTextureSlots) -> TexBgKey {
(
[
tex_slot_key(&slots.map),
tex_slot_key(&slots.normal_map),
tex_slot_key(&slots.roughness_map),
tex_slot_key(&slots.metalness_map),
tex_slot_key(&slots.ao_map),
tex_slot_key(&slots.emissive_map),
tex_slot_key(&slots.matcap_map),
tex_slot_key(&slots.cloud_shadow_map),
],
(0, 0),
slots
.sampler_source()
.map_or(SAMPLER_DEFAULT, |t| sampler_index(t)),
(0, 0),
)
}
const SAMPLER_COUNT: usize = 108;
const SAMPLER_DEFAULT: usize = 0;
fn mip_code(m: Option<crate::textures::TextureFilter>) -> usize {
match m {
Some(crate::textures::TextureFilter::Linear) => 0,
Some(crate::textures::TextureFilter::Nearest) => 1,
None => 2,
}
}
fn sampler_index(t: &Texture) -> usize {
use crate::textures::{TextureFilter, TextureWrap};
let wrap = |w: TextureWrap| match w {
TextureWrap::ClampToEdge => 0,
TextureWrap::Repeat => 1,
TextureWrap::MirroredRepeat => 2,
};
(t.mag_filter == TextureFilter::Nearest) as usize
+ ((t.min_filter == TextureFilter::Nearest) as usize) * 2
+ wrap(t.wrap_s) * 4
+ wrap(t.wrap_t) * 12
+ mip_code(t.mipmap_filter) * 36
}
fn cube_sampler_index(c: &crate::textures::CubeTexture) -> usize {
use crate::textures::TextureFilter;
(c.mag_filter == TextureFilter::Nearest) as usize
+ ((c.min_filter == TextureFilter::Nearest) as usize) * 2
+ mip_code(c.mipmap_filter) * 36
}
fn make_sampler(device: &wgpu::Device, i: usize) -> wgpu::Sampler {
let filter = |nearest: bool| {
if nearest {
wgpu::FilterMode::Nearest
} else {
wgpu::FilterMode::Linear
}
};
let address = |w: usize| match w {
1 => wgpu::AddressMode::Repeat,
2 => wgpu::AddressMode::MirrorRepeat,
_ => wgpu::AddressMode::ClampToEdge,
};
let (mag_nearest, min_nearest) = (i & 1 != 0, i & 2 != 0);
let mip = i / 36;
let all_linear = !mag_nearest && !min_nearest && mip == 0;
device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers map sampler"),
address_mode_u: address((i / 4) % 3),
address_mode_v: address((i / 12) % 3),
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: filter(mag_nearest),
min_filter: filter(min_nearest),
mipmap_filter: if mip == 0 {
wgpu::MipmapFilterMode::Linear
} else {
wgpu::MipmapFilterMode::Nearest
},
lod_max_clamp: if mip == 2 { 0.0 } else { 32.0 },
anisotropy_clamp: if all_linear { 16 } else { 1 },
..Default::default()
})
}
fn take_sized<T>(
current: &mut Option<(u32, u32, T, T)>,
spare: &mut Option<(u32, u32, T, T)>,
w: u32,
h: u32,
) -> bool {
let fits =
|t: &Option<(u32, u32, T, T)>| matches!(t, Some((cw, ch, ..)) if *cw == w && *ch == h);
if fits(current) {
return false;
}
std::mem::swap(current, spare);
!fits(current)
}
fn draw_span(range: Option<(u32, u32)>, count: u32) -> std::ops::Range<u32> {
match range {
Some((start, end)) => start.min(count)..end.min(count),
None => 0..count,
}
}
struct TransmissionCapture {
texture: wgpu::Texture,
view: wgpu::TextureView,
target_view: wgpu::TextureView,
_depth: wgpu::Texture,
depth_view: wgpu::TextureView,
copy: wgpu::Texture,
copy_view: wgpu::TextureView,
size: (u32, u32),
levels: u32,
}
struct UvSetTexture {
version: u32,
_texture: wgpu::Texture,
view: wgpu::TextureView,
}
const UV_SET_NAMES: [&str; 3] = ["uv1", "uv2", "uv3"];
fn uv_sets_entry() -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry {
binding: 8,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
}
}
struct MorphTexture {
version: u32,
_texture: wgpu::Texture,
view: wgpu::TextureView,
instance_layer: Option<(u32, u32)>,
}
use super::shader::{
MAX_DIR_LIGHTS, MAX_HEMI_LIGHTS, MAX_POINT_LIGHTS, MAX_RECT_LIGHTS, MAX_SPOT_LIGHTS,
};
use crate::cameras::Camera;
use crate::core::{BufferGeometry, ObjectKind};
use crate::lights::Light;
use crate::materials::{Material, MaterialKind, MaterialTextureSlots};
use crate::math::{Frustum, Matrix3, Matrix4, Sphere, Vector3};
use crate::scene::Scene;
use crate::textures::{CubeTexture, Texture, TextureFormat};
mod postfx_op;
pub(crate) use postfx_op::stored_clear;
pub use postfx_op::{PostFxBlend, PostFxNoise, PostFxOp, PostFxOutput};
fn rt_sample_format(format: wgpu::TextureFormat) -> wgpu::TextureFormat {
if format == wgpu::TextureFormat::Rgba16Float {
format
} else {
format.add_srgb_suffix()
}
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
struct DirLightGpu {
direction: [f32; 4],
color: [f32; 4],
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
struct PointLightGpu {
position: [f32; 4],
color: [f32; 4],
params: [f32; 4],
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
struct SpotLightGpu {
position: [f32; 4],
direction: [f32; 4],
color: [f32; 4],
params: [f32; 4],
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
struct HemiLightGpu {
sky_color: [f32; 4],
ground_color: [f32; 4],
direction: [f32; 4],
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
struct RectLightGpu {
position: [f32; 4],
color: [f32; 4],
right: [f32; 4],
up: [f32; 4],
}
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct EnvUniforms {
params: [f32; 4],
info: [f32; 4],
rot: [[f32; 4]; 3],
}
impl EnvUniforms {
const NONE: Self = Self {
params: [0.0; 4],
info: [0.0, 1.0, 0.0, 0.0],
rot: [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
],
};
fn of(
cube: &CubeTexture,
gpu: &GpuCubeTexture,
intensity: f32,
rotation: crate::math::Euler,
) -> Self {
let params = match &cube.cube_uv_atlas {
Some(a) => [a.texel_width, a.texel_height, a.lod_max as f32, 1.0],
None => [
0.0,
0.0,
gpu.texture.mip_level_count().saturating_sub(1) as f32,
0.0,
],
};
Self {
params,
info: [1.0, intensity, 0.0, 0.0],
rot: crate::materials::environment_lookup_rows(rotation, cube.cube_uv_atlas.is_none()),
}
}
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct FrameUniforms {
view: [f32; 16],
projection: [f32; 16],
view_proj: [f32; 16],
camera_position: [f32; 4],
ambient: [f32; 4],
light_counts: [u32; 4],
tone_mapping_exposure: [f32; 4],
fog_color: [f32; 4],
fog_params: [f32; 4],
viewport_size: [f32; 4],
env_map_params: [f32; 4],
dir_lights: [DirLightGpu; MAX_DIR_LIGHTS],
point_lights: [PointLightGpu; MAX_POINT_LIGHTS],
spot_lights: [SpotLightGpu; MAX_SPOT_LIGHTS],
hemi_lights: [HemiLightGpu; MAX_HEMI_LIGHTS],
rect_lights: [RectLightGpu; MAX_RECT_LIGHTS],
light_counts2: [u32; 4],
shadow_info: [u32; 4],
shadows: [ShadowRecordGpu; MAX_SHADOW_RECORDS],
}
impl Default for FrameUniforms {
fn default() -> Self {
Self {
view: [0.0; 16],
projection: [0.0; 16],
view_proj: [0.0; 16],
camera_position: [0.0; 4],
ambient: [0.0; 4],
light_counts: [0; 4],
tone_mapping_exposure: [0.0, 1.0, 0.0, 0.0],
fog_color: [1.0, 1.0, 1.0, 1.0],
fog_params: [1.0, 1000.0, 0.0, 0.0],
viewport_size: [1.0, 1.0, 0.0, 0.0],
env_map_params: [0.0; 4],
dir_lights: [DirLightGpu::default(); MAX_DIR_LIGHTS],
point_lights: [PointLightGpu::default(); MAX_POINT_LIGHTS],
spot_lights: [SpotLightGpu::default(); MAX_SPOT_LIGHTS],
hemi_lights: [HemiLightGpu::default(); MAX_HEMI_LIGHTS],
rect_lights: [RectLightGpu::default(); MAX_RECT_LIGHTS],
light_counts2: [0; 4],
shadow_info: [0; 4],
shadows: [ShadowRecordGpu::zeroed(); MAX_SHADOW_RECORDS],
}
}
}
macro_rules! env_bind_group {
($device:expr, $bgl:expr, $label:expr,
$t0:expr, $s1:expr, $t2:expr, $s3:expr, $t4:expr, $s5:expr,
$t6:expr, $s7:expr, $t8:expr, $u13:expr, $ltc14:expr $(,)?) => {{
let entries = [
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView($t0),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler($s1),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::TextureView($t2),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::Sampler($s3),
},
wgpu::BindGroupEntry {
binding: 4,
resource: wgpu::BindingResource::TextureView($t4),
},
wgpu::BindGroupEntry {
binding: 5,
resource: wgpu::BindingResource::Sampler($s5),
},
wgpu::BindGroupEntry {
binding: 6,
resource: wgpu::BindingResource::TextureView($t6),
},
wgpu::BindGroupEntry {
binding: 7,
resource: wgpu::BindingResource::Sampler($s7),
},
wgpu::BindGroupEntry {
binding: 8,
resource: wgpu::BindingResource::TextureView($t8),
},
wgpu::BindGroupEntry {
binding: 13,
resource: $u13.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 14,
resource: wgpu::BindingResource::TextureView($ltc14),
},
];
$device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some($label),
layout: $bgl,
entries: &entries,
})
}};
}
macro_rules! custom_env_bind_group {
($device:expr, $bgl:expr, $label:expr, $t0:expr, $s1:expr, $t8:expr, $u13:expr $(,)?) => {{
let entries = [
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView($t0),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler($s1),
},
wgpu::BindGroupEntry {
binding: 8,
resource: wgpu::BindingResource::TextureView($t8),
},
wgpu::BindGroupEntry {
binding: 13,
resource: $u13.as_entire_binding(),
},
];
$device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some($label),
layout: $bgl,
entries: &entries,
})
}};
}
type MaterialEnvKey = (super::gpu_texture::CubeCacheKey, u32, [u32; 4]);
fn material_env_key(
env: (&std::sync::Arc<CubeTexture>, f32, crate::math::Euler),
) -> MaterialEnvKey {
let (cube, intensity, r) = env;
let order = crate::math::EulerOrder::ALL
.iter()
.position(|o| *o == r.order)
.unwrap_or(0) as u32;
(
cube_cache_key(cube),
intensity.to_bits(),
[r.x.to_bits(), r.y.to_bits(), r.z.to_bits(), order],
)
}
struct TaaBindCache {
resolve: [wgpu::BindGroup; 2],
blit: [wgpu::BindGroup; 2],
}
struct InstanceBuffer {
buffer: wgpu::Buffer,
data: Vec<f32>,
frame: u64,
version: Option<(u64, usize)>,
stamp: u64,
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
struct TaaUniforms {
inv_view_proj: [f32; 16],
prev_view_proj: [f32; 16],
params: [f32; 4],
cam_delta: [f32; 4],
flags: [f32; 4],
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
struct MeshUniforms {
model: [f32; 16],
normal_matrix: [f32; 16],
color: [f32; 4],
emissive: [f32; 4],
specular: [f32; 4],
params: [f32; 4],
params2: [f32; 4],
params3: [f32; 4],
params4: [f32; 4],
params5: [f32; 4],
params6: [f32; 4],
params7: [f32; 4],
params8: [f32; 4],
params9: [f32; 4],
params10: [f32; 4],
params11: [f32; 4],
params12: [f32; 4],
params13: [f32; 4],
params14: [f32; 4],
flags: [u32; 4],
morph: [f32; 4],
morph_weights: [[f32; 4]; crate::core::MAX_MORPH_TARGETS / 4],
clip_plane: [f32; 4],
}
fn clip_plane_of(obj: &crate::core::Object3D) -> [f32; 4] {
obj.clip_plane.map_or([0.0; 4], |p| {
[p.normal.x, p.normal.y, p.normal.z, p.constant]
})
}
const FLAG_MAP: u32 = 1;
const FLAG_NORMAL_MAP: u32 = 2;
const FLAG_ROUGHNESS_MAP: u32 = 4;
const FLAG_METALNESS_MAP: u32 = 8;
const FLAG_AO_MAP: u32 = 16;
const FLAG_EMISSIVE_MAP: u32 = 32;
const FLAG_MATCAP_MAP: u32 = 64;
const FLAG_DASHED: u32 = 128;
const FLAG_SHADOW_MAT: u32 = 256;
const FLAG_RECEIVE_SHADOW: u32 = 512;
const FLAG_CLOUD_SHADOW: u32 = 4096;
const FLAG_ENCODED_OUT: u32 = 8192;
const FLAG_NO_TONE_MAP: u32 = 16384;
const FLAG_OPAQUE_OUT: u32 = 32768;
const FLAG_BLENDED_GLASS: u32 = 65536;
const FLAG_SHADOW_TRANSMITS: u32 = 131072;
fn reverse_depth(m: &crate::math::Matrix4) -> crate::math::Matrix4 {
let mut out = *m;
for c in 0..4 {
out.elements[c * 4 + 2] = m.elements[c * 4 + 3] - m.elements[c * 4 + 2];
}
out
}
fn variant_pipeline(
pipes: &mut super::pipeline_state::StatePipelines,
variants: &HashMap<
super::material_maps::MapVariant,
(wgpu::ShaderModule, wgpu::BindGroupLayout),
>,
device: &wgpu::Device,
main: &wgpu::ShaderModule,
base: &Pipeline,
v: Option<super::material_maps::MapVariant>,
) -> Pipeline {
let Some(v) = v else {
return base.clone();
};
let Some((module, bgl)) = variants.get(&v) else {
log::error!("threers: a draw names material variant {v:?}, which was not built");
return base.clone();
};
pipes
.relayout(device, base, v.key(), 2, bgl, main, module)
.unwrap_or_else(|| {
log::error!("threers: a material-variant draw reached an unrecorded pipeline");
base.clone()
})
}
fn side_cull(faces: bool, side: u32) -> Option<Option<wgpu::Face>> {
faces.then_some(match side {
1 => Some(wgpu::Face::Front),
2 => None,
_ => Some(wgpu::Face::Back),
})
}
fn shadow_cull(side: u32) -> Option<wgpu::Face> {
match side {
1 => Some(wgpu::Face::Back),
2 => None,
_ => Some(wgpu::Face::Front),
}
}
fn shadow_cull_point(side: u32) -> Option<wgpu::Face> {
match shadow_cull(side) {
Some(wgpu::Face::Front) => Some(wgpu::Face::Back),
Some(wgpu::Face::Back) => Some(wgpu::Face::Front),
None => None,
}
}
struct ShadowCutPipelines {
dir: Pipeline,
spot: Pipeline,
dir_skinned: Pipeline,
spot_skinned: Pipeline,
dir_instanced: Pipeline,
spot_instanced: Pipeline,
}
struct CachedGpuMesh {
version: u32,
last_frame: u64,
mesh: GpuMesh,
sphere: Option<Sphere>,
}
fn local_bounding_sphere(geom: &BufferGeometry) -> Option<Sphere> {
if let Some(s) = geom.bounding_sphere {
return Some(s);
}
if geom.gpu_writable {
return None;
}
let mut lo = Vector3::new(f32::INFINITY, f32::INFINITY, f32::INFINITY);
let mut hi = Vector3::new(f32::NEG_INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY);
for p in geom.positions()? {
lo = Vector3::new(lo.x.min(p.x), lo.y.min(p.y), lo.z.min(p.z));
hi = Vector3::new(hi.x.max(p.x), hi.y.max(p.y), hi.z.max(p.z));
}
if !lo.x.is_finite() {
return None;
}
let centre = (lo + hi) * 0.5;
let mut r2 = 0.0f32;
for p in geom.positions()? {
r2 = r2.max((p - centre).length_sq());
}
Some(Sphere::new(centre, r2.sqrt()))
}
#[derive(Clone, Debug)]
pub struct PostFxCamera {
pub near: f32,
pub far: f32,
pub kernel_radius: f32,
pub kernel_size: u32,
pub proj: [f32; 16],
pub inv_proj: [f32; 16],
}
impl Default for PostFxCamera {
fn default() -> Self {
let mut id = [0f32; 16];
id[0] = 1.0;
id[5] = 1.0;
id[10] = 1.0;
id[15] = 1.0;
Self {
near: 0.1,
far: 100.0,
kernel_radius: 8.0,
kernel_size: 32,
proj: id,
inv_proj: id,
}
}
}
pub use crate::math::tone_mapping::ToneMapping;
mod construct;
mod frame;
mod geometry;
mod postfx;
mod targets;
mod textures;
type CustomPipelineKey = (u64, bool, bool, bool, u32);
struct IdentityKeyed<K, V>(HashMap<K, V>);
unsafe impl<K, V: Send> Send for IdentityKeyed<K, V> {}
impl<K, V> Default for IdentityKeyed<K, V> {
fn default() -> Self {
Self(HashMap::new())
}
}
impl<K, V> std::ops::Deref for IdentityKeyed<K, V> {
type Target = HashMap<K, V>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<K, V> std::ops::DerefMut for IdentityKeyed<K, V> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct RendererOptions {
pub lazy: bool,
pub pipeline_cache: Option<wgpu::PipelineCache>,
}
impl RendererOptions {
pub fn lazy(mut self, lazy: bool) -> Self {
self.lazy = lazy;
self
}
#[cfg(not(target_arch = "wasm32"))]
pub fn pipeline_cache(
mut self,
cache: impl crate::renderer::pipeline_cache::IntoPipelineCache,
) -> Self {
self.pipeline_cache = cache.into_pipeline_cache();
self
}
}
pub const DEFAULT_CACHE_RETENTION: u64 = 120;
pub struct Renderer {
device: Arc<wgpu::Device>,
queue: Arc<wgpu::Queue>,
pipeline_tri: Pipeline,
pipeline_tri_alpha: Pipeline,
pipeline_glass_depth: Pipeline,
pipeline_glass_color: Pipeline,
pipeline_glass_depth_f16: Pipeline,
pipeline_glass_color_f16: Pipeline,
pipeline_glass_depth_msaa: Pipeline,
pipeline_glass_color_msaa: Pipeline,
pipeline_glass_tint: Pipeline,
pipeline_glass_tint_f16: Pipeline,
pipeline_glass_tint_msaa: Pipeline,
encoded_glass_msaa: Option<[Pipeline; 3]>,
pipeline_oit: Vec<Pipeline>,
pipeline_oit_resolve: [Pipeline; 2],
pipeline_oit_resolve_f16: [Pipeline; 2],
pipeline_oit_resolve_msaa: [Pipeline; 2],
pipeline_oit_msaa: Vec<Pipeline>,
oit_msaa_targets: Option<(u32, u32, wgpu::TextureView, wgpu::TextureView)>,
oit_msaa_targets_spare: Option<(u32, u32, wgpu::TextureView, wgpu::TextureView)>,
depth_resolve: Option<(wgpu::BindGroupLayout, Pipeline)>,
depth_copy: Option<(wgpu::BindGroupLayout, Pipeline, wgpu::Sampler)>,
oit_resolve_bgl: wgpu::BindGroupLayout,
oit_targets: Option<(
u32,
u32,
wgpu::Texture,
wgpu::TextureView,
wgpu::Texture,
wgpu::TextureView,
wgpu::BindGroup,
)>,
pipeline_tri_nocull: Pipeline,
pipeline_tri_sky: Pipeline,
pipeline_tri_wire: Pipeline,
pipeline_line: Pipeline,
pipeline_point: Pipeline,
pipeline_point_alpha: Pipeline,
pipeline_wide_line: Pipeline,
pipeline_wide_line_alpha: Pipeline,
pipeline_sprite: Pipeline,
pipeline_tri_msaa: Pipeline,
pipeline_skinned_msaa: Pipeline,
pipeline_instanced_msaa: Pipeline,
pipeline_tri_alpha_msaa: Pipeline,
pipeline_tri_nocull_msaa: Pipeline,
pipeline_tri_sky_msaa: Pipeline,
pipeline_tri_wire_msaa: Pipeline,
pipeline_line_msaa: Pipeline,
pipeline_point_msaa: Pipeline,
pipeline_wide_line_msaa: Pipeline,
msaa: u32,
specular_antialiasing: bool,
tone_mapping: ToneMapping,
tone_map_pass: bool,
exposure: f32,
msaa_targets: Option<(u32, u32, wgpu::TextureView, wgpu::TextureView)>,
msaa_targets_spare: Option<(u32, u32, wgpu::TextureView, wgpu::TextureView)>,
overlay_msaa: bool,
pub(super) last_overlay: Option<LastOverlay>,
last_frame_msaa: bool,
fxaa_scratch: Option<(wgpu::Texture, wgpu::TextureView)>,
pipeline_tri_f16: Pipeline,
pipeline_tri_alpha_f16: Pipeline,
pipeline_tri_nocull_f16: Pipeline,
pipeline_tri_sky_f16: Pipeline,
pipeline_tri_wire_f16: Pipeline,
pipeline_line_f16: Pipeline,
pipeline_point_f16: Pipeline,
pipeline_point_alpha_f16: Pipeline,
pipeline_wide_line_f16: Pipeline,
pipeline_wide_line_alpha_f16: Pipeline,
pipeline_sprite_f16: Pipeline,
pipeline_instanced_f16: Pipeline,
pipeline_skinned_f16: Pipeline,
pipeline_shadow: Pipeline,
pipeline_shadow_spot: Pipeline,
pipeline_shadow_point: Pipeline,
pipeline_shadow_skinned: Pipeline,
pipeline_shadow_spot_skinned: Pipeline,
pipeline_shadow_point_skinned: Pipeline,
pipeline_shadow_instanced: Pipeline,
pipeline_shadow_spot_instanced: Pipeline,
shadow_cut: ShadowCutPipelines,
pipeline_shadow_point_instanced: Pipeline,
pipeline_instanced: Pipeline,
pipeline_skinned: Pipeline,
pipeline_instanced_wire: Pipeline,
pipeline_instanced_wire_f16: Pipeline,
pipeline_instanced_alpha: Pipeline,
pipeline_instanced_alpha_f16: Pipeline,
pipeline_skinned_alpha: Pipeline,
pipeline_skinned_alpha_f16: Pipeline,
encoded_blend_pipelines: Option<[Pipeline; 8]>,
pipeline_skinned_wire: Pipeline,
pipeline_skinned_wire_f16: Pipeline,
pipeline_postfx: Pipeline,
pipeline_postfx_add: Pipeline,
pipeline_postfx_outline_add: Pipeline,
pipeline_postfx_multiply: Pipeline,
pipeline_postfx_f16: Pipeline,
pipeline_postfx_add_f16: Pipeline,
postfx_bgl: wgpu::BindGroupLayout,
postfx_sampler: wgpu::Sampler,
postfx_nearest_sampler: wgpu::Sampler,
postfx_noise_sampler: wgpu::Sampler,
postfx_ext: postfx_op::PostFxExt,
ssao_kernel_buffer: wgpu::Buffer,
ssao_noise_tex: wgpu::Texture,
ssao_noise_view: wgpu::TextureView,
glitch_disp_tex: wgpu::Texture,
glitch_disp_view: wgpu::TextureView,
rgba_upload_tex: wgpu::Texture,
rgba_upload_view: wgpu::TextureView,
#[cfg(feature = "captions")]
caption_pass: Option<super::caption_pass::CaptionPass>,
overlay_pass: Option<super::caption_pass::CaptionPass>,
mesh_skinned_bgl: wgpu::BindGroupLayout,
sprite_quad: GpuMesh,
frame_bgl: wgpu::BindGroupLayout,
mesh_bgl: wgpu::BindGroupLayout,
tex_bgl: wgpu::BindGroupLayout,
env_bgl: wgpu::BindGroupLayout,
ltc: (wgpu::Texture, wgpu::TextureView),
env_bgl_glass: wgpu::BindGroupLayout,
custom_tex_bind_group: wgpu::BindGroup,
custom_tex_bgl: wgpu::BindGroupLayout,
mesh_shader: wgpu::ShaderModule,
mesh_pipeline_layout: wgpu::PipelineLayout,
biased_pipelines: HashMap<(u8, u8, u32, i32), Pipeline>,
state_pipelines: super::pipeline_state::StatePipelines,
msaa_color_unorm: Option<wgpu::TextureView>,
encoded_scratch: Option<(u32, u32, wgpu::TextureView)>,
encoded_copy: Option<(wgpu::BindGroupLayout, Pipeline, Pipeline)>,
custom_mesh_bgl: wgpu::BindGroupLayout,
custom_pipeline_layout: Option<wgpu::PipelineLayout>,
custom_ss_pipeline_layout: Option<wgpu::PipelineLayout>,
custom_shadow_frame_bgl: wgpu::BindGroupLayout,
custom_shadow_layout: Option<wgpu::PipelineLayout>,
custom_lit_shadow_layout: Option<wgpu::PipelineLayout>,
custom_shadow_pipelines: HashMap<(u64, bool, u32), Option<wgpu::RenderPipeline>>,
custom_shadow_frames: Option<(wgpu::Buffer, wgpu::BindGroup, usize)>,
custom_shadow_frame_stride: u64,
custom_lit_pipeline_layout: Option<wgpu::PipelineLayout>,
custom_lit_mesh_bgl: Option<wgpu::BindGroupLayout>,
custom_lit: HashMap<u64, bool>,
custom_pipelines: HashMap<CustomPipelineKey, Pipeline>,
custom_encoded_pipelines: HashMap<(u64, bool, bool, u32), Pipeline>,
custom_msaa_pipelines: HashMap<(u64, bool, bool, u32), Pipeline>,
custom_cache: super::custom_cache::CustomCache,
custom_failed: std::collections::HashSet<CustomPipelineKey>,
depth_view: wgpu::TextureView,
depth_texture: wgpu::Texture,
hw_depth_tex: wgpu::Texture,
depth_size: (u32, u32),
geom_cache: IdentityKeyed<*const BufferGeometry, CachedGpuMesh>,
frustum_culling: bool,
cull_stats: (usize, usize),
timer: Option<GpuTimer>,
shadow_timer: Option<GpuTimer>,
shadow_map: super::viewport::ShadowMap,
shadow_sig: Option<ShadowSig>,
shadow_pass_hashes: Vec<Option<u64>>,
shadow_stats: (u64, u64),
shadow_updates: u64,
skin_attr_cache: IdentityKeyed<*const BufferGeometry, wgpu::Buffer>,
morph_cache: IdentityKeyed<*const BufferGeometry, MorphTexture>,
instance_cache: HashMap<(crate::core::ObjectId, u8), InstanceBuffer>,
instance_frame: u64,
instance_stamps: u64,
uv_cache: IdentityKeyed<*const BufferGeometry, UvSetTexture>,
default_uv_sets: (wgpu::Texture, wgpu::TextureView),
default_morph: (wgpu::Texture, wgpu::TextureView),
wire_span_cache: IdentityKeyed<(*const BufferGeometry, u32, u32, u32), (wgpu::Buffer, u32)>,
tex_cache: HashMap<TexCacheKey, GpuTexture>,
tex_last_used: HashMap<TexCacheKey, u64>,
cache_retention: u64,
tex_pinned: std::collections::HashSet<u64>,
stream_uploads: HashMap<u64, u64>,
stream_scratch: Vec<u8>,
yuv: Option<super::yuv::YuvConverter>,
#[cfg(target_arch = "wasm32")]
frame_canvas: Option<(
web_sys::HtmlCanvasElement,
web_sys::CanvasRenderingContext2d,
)>,
mipgen: Option<MipGenerator>,
rt_view_cache: HashMap<u32, wgpu::TextureView>,
rt_linear_view_cache: HashMap<u32, wgpu::TextureView>,
rt_registry: HashMap<u32, Arc<super::RenderTarget>>,
rt_depth_view_cache: HashMap<u32, wgpu::TextureView>,
cube_rt_view_cache: HashMap<u32, wgpu::TextureView>,
env_max_mip: f32,
cube_cache: HashMap<super::gpu_texture::CubeCacheKey, GpuCubeTexture>,
env_bind_group: wgpu::BindGroup,
shadow_env_bind_group: wgpu::BindGroup,
custom_env_bgl: Option<wgpu::BindGroupLayout>,
custom_env_bind_group: Option<wgpu::BindGroup>,
env_uniform: wgpu::Buffer,
material_env_groups: HashMap<MaterialEnvKey, (wgpu::Buffer, wgpu::BindGroup)>,
env_sampler: wgpu::Sampler,
default_env_cube: GpuCubeTexture,
default_cube_uv_view: wgpu::TextureView,
shadow_pass_buffer: Option<(wgpu::Buffer, wgpu::BindGroup)>,
depth_replay: Vec<Pipeline>,
depth_replay_pass: Option<(wgpu::Buffer, wgpu::BindGroup)>,
force_depth_replay: bool,
msaa_depth_out: Option<wgpu::Texture>,
shadow_pass_bgl: wgpu::BindGroupLayout,
shadow_pass_stride: u64,
shadow_type: crate::lights::ShadowType,
env_cached_key: Option<super::gpu_texture::CubeCacheKey>,
env_dirty: bool,
env_cached_rt_id: Option<u32>,
dir_shadows: ShadowArray,
spot_shadows: ShadowArray,
point_shadows: ShadowArray,
cube_pass: bool,
viewport_state: super::viewport::ViewportState,
shadow_sampler: wgpu::Sampler,
spot_shadow_sampler: wgpu::Sampler,
point_shadow_sampler: wgpu::Sampler,
frame_buffer: wgpu::Buffer,
frame_bind_group: wgpu::BindGroup,
frame_bind_group_dummy: wgpu::BindGroup,
frame_buffer_for_bg: wgpu::Buffer,
transmission_sampler: wgpu::Sampler,
transmission: Option<TransmissionCapture>,
capturing_transmission: Option<bool>,
reflective_transparency: bool,
per_mesh: Vec<(u64, wgpu::BindGroup, std::sync::Arc<wgpu::BindGroup>)>,
mesh_arena: Option<wgpu::Buffer>,
mesh_stride: u64,
mesh_bytes: Vec<u8>,
tex_bg_cache: HashMap<TexBgKey, std::sync::Arc<wgpu::BindGroup>>,
main_shader: wgpu::ShaderModule,
map_variants:
HashMap<super::material_maps::MapVariant, (wgpu::ShaderModule, wgpu::BindGroupLayout)>,
pmrem_cache: HashMap<super::gpu_texture::CubeCacheKey, std::sync::Arc<CubeTexture>>,
variant_bg_cache: HashMap<(VariantBgKey, (usize, u32)), std::sync::Arc<wgpu::BindGroup>>,
sampler_linear_repeat: wgpu::Sampler,
samplers: Vec<wgpu::Sampler>,
default_white_srgb: GpuTexture,
default_white_linear: GpuTexture,
default_data_tex_view: wgpu::TextureView,
default_volume_view: wgpu::TextureView,
volume_maps: crate::volume::VolumeMaps,
sampler_volume: wgpu::Sampler,
last_camera_planes: (f32, f32),
last_camera_lens: (f32, f32),
default_normal: GpuTexture, default_transparent: GpuTexture,
ss_color: Option<SsColor>,
ss_glass_sampler: wgpu::Sampler,
ss_depth: Option<(u32, u32, wgpu::Texture, wgpu::TextureView)>,
ss_back_depth: Option<(u32, u32, wgpu::Texture, wgpu::TextureView)>,
ss_layer: Option<(u32, u32, wgpu::Texture, wgpu::TextureView)>,
refraction_layers: usize,
pipeline_ss_back_depth: Pipeline,
pipeline_ss_blit: Pipeline,
pipeline_ss_blit_f16: Pipeline,
pipeline_ss_glass: Pipeline,
pipeline_ss_glass_f16: Pipeline,
pipeline_glass_shadow: Pipeline,
ss_glass_shadow: Option<(wgpu::Texture, wgpu::TextureView)>,
ss_blit_bgl: wgpu::BindGroupLayout,
taa_enabled: bool,
taa_frame: u32,
taa_converge: bool,
taa_blit: bool,
taa_hist_format: Option<wgpu::TextureFormat>,
jitter_override: Option<(f32, f32)>,
taa_bind_cache: Option<TaaBindCache>,
taa_prev_view_proj: [f32; 16],
mb_inv_vp: [f32; 16],
mb_prev_vp: [f32; 16],
mb_last_vp: [f32; 16],
taa_prev_cam: [f32; 3],
taa_history: Option<(
u32,
u32,
wgpu::Texture,
wgpu::TextureView,
wgpu::Texture,
wgpu::TextureView,
)>,
taa_uniform: wgpu::Buffer,
taa_bgl: wgpu::BindGroupLayout,
taa_sampler: wgpu::Sampler,
pipeline_taa: Pipeline,
pipeline_taa_f16: Pipeline,
color_format: wgpu::TextureFormat,
}
struct SsColor {
width: u32,
height: u32,
texture: wgpu::Texture,
all_mips_view: wgpu::TextureView,
mip_render_views: Vec<wgpu::TextureView>,
mip_sample_views: Vec<wgpu::TextureView>,
mip0_unorm: Option<wgpu::TextureView>,
mips: u32,
format: wgpu::TextureFormat,
}
fn default_ssao_kernel() -> Vec<f32> {
let mut out = Vec::with_capacity(32 * 3);
let hash = |i: u32, salt: u32| -> f32 {
let mut h = i
.wrapping_mul(747_796_405)
.wrapping_add(salt.wrapping_mul(2_891_336_453));
h ^= h >> 16;
h = h.wrapping_mul(2_246_822_519);
h ^= h >> 13;
(h >> 8) as f32 / 16_777_216.0
};
for i in 0..32u32 {
let mut v = [
hash(i, 1) * 2.0 - 1.0,
hash(i, 2) * 2.0 - 1.0,
hash(i, 3),
];
let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt().max(1e-4);
let t = i as f32 / 32.0;
let scale = (0.1 + 0.9 * t * t) / len;
v[0] *= scale;
v[1] *= scale;
v[2] *= scale;
out.extend_from_slice(&v);
}
out
}
fn default_ssao_noise() -> Vec<f32> {
(0..16)
.map(|i| {
let mut h = (i as u32).wrapping_mul(2_654_435_761);
h ^= h >> 15;
h = h.wrapping_mul(2_246_822_519);
h ^= h >> 13;
let u = (h >> 8) as f32 / 16_777_216.0;
if u < 0.5 {
-0.35 - u
} else {
0.35 + (u - 0.5)
}
})
.collect()
}
const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct OverlayInfo {
pub samples: u32,
pub depth: bool,
pub reversed: bool,
pub projection_fix: Option<crate::math::Matrix4>,
pub color_format: wgpu::TextureFormat,
}
impl OverlayInfo {
pub const DEPTH_FORMAT: wgpu::TextureFormat = DEPTH_FORMAT;
pub fn projection(&self, projection: &crate::math::Matrix4) -> crate::math::Matrix4 {
let mut p = match &self.projection_fix {
Some(fix) => fix.multiply(projection),
None => *projection,
};
if self.reversed {
for c in 0..4 {
p.elements[c * 4 + 2] = p.elements[c * 4 + 3] - p.elements[c * 4 + 2];
}
}
p
}
pub fn depth_compare(&self) -> wgpu::CompareFunction {
if self.reversed {
wgpu::CompareFunction::GreaterEqual
} else {
wgpu::CompareFunction::LessEqual
}
}
}
#[derive(Debug, Clone)]
pub(super) struct LastOverlay {
pub pane: Option<(super::viewport::PaneKey, super::viewport::PixelRect)>,
pub viewport: super::viewport::PixelRect,
pub scissor: super::viewport::PixelRect,
pub projection_fix: Option<crate::math::Matrix4>,
}
const DEPTH_COPY_SHADER: &str = crate::wgsl!(
r#"
@group(0) @binding(0) var src: texture_2d<f32>;
@group(0) @binding(1) var samp: sampler;
@vertex
fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {
let x = f32((i << 1u) & 2u);
let y = f32(i & 2u);
return vec4<f32>(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0);
}
@fragment
fn fs(@builtin(position) p: vec4<f32>) -> @builtin(frag_depth) f32 {
let uv = p.xy / vec2<f32>(textureDimensions(src));
return textureSampleLevel(src, samp, uv, 0.0).r;
}
"#
);
const MSAA_SAMPLES: u32 = 4;
fn mix_word(h: u64, x: u64) -> u64 {
(h.rotate_left(5) ^ x).wrapping_mul(0x517c_c1b7_2722_0a95)
}
fn hash_words(words: impl Iterator<Item = u64>) -> u64 {
words.fold(0xcbf2_9ce4_8422_2325, mix_word)
}
const SPOT_SHADOW_SIZE: u32 = 4096;
const POINT_SHADOW_SIZE: u32 = 512;
const OIT_REVEAL_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
const GLASS_DEPTH: u8 = 0;
const GLASS_TINT: u8 = 1;
const GLASS_LIGHT: u8 = 2;
const GLASS_SHADOW_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Uint;
type ShadowSig = (usize, usize, usize, u32, u32);
struct ShadowArray {
texture: wgpu::Texture,
view: wgpu::TextureView,
size: u32,
layers: u32,
}
impl ShadowArray {
fn new(device: &wgpu::Device, label: &str, size: u32, layers_needed: u32) -> Self {
let mut layers = layers_needed.max(2);
if layers.is_multiple_of(6) {
layers += 1;
}
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d {
width: size,
height: size,
depth_or_array_layers: layers,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: DEPTH_FORMAT,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
let view = texture.create_view(&wgpu::TextureViewDescriptor {
label: Some(label),
dimension: Some(wgpu::TextureViewDimension::D2Array),
..Default::default()
});
Self {
texture,
view,
size,
layers,
}
}
fn layer_view(&self, layer: u32) -> wgpu::TextureView {
self.texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers shadow layer"),
dimension: Some(wgpu::TextureViewDimension::D2),
base_array_layer: layer,
array_layer_count: Some(1),
..Default::default()
})
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum ShadowKind {
Dir,
Spot,
Point,
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct ShadowRecordGpu {
info: [u32; 4],
params: [f32; 4],
extra: [f32; 4],
pcss: [f32; 4],
vp: [[f32; 16]; 4],
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct ShadowPassGpu {
vp: [f32; 16],
light: [f32; 4],
}
struct ShadowPass {
kind: ShadowKind,
layer: u32,
vp: [f32; 16],
pos: [f32; 4],
}
fn point_face_vp(pos: Vector3, radius: f32, face: usize) -> [f32; 16] {
let face_lookat: [(Vector3, Vector3); 6] = [
(Vector3::new(1.0, 0.0, 0.0), Vector3::new(0.0, -1.0, 0.0)),
(Vector3::new(-1.0, 0.0, 0.0), Vector3::new(0.0, -1.0, 0.0)),
(Vector3::new(0.0, 1.0, 0.0), Vector3::new(0.0, 0.0, 1.0)),
(Vector3::new(0.0, -1.0, 0.0), Vector3::new(0.0, 0.0, -1.0)),
(Vector3::new(0.0, 0.0, 1.0), Vector3::new(0.0, -1.0, 0.0)),
(Vector3::new(0.0, 0.0, -1.0), Vector3::new(0.0, -1.0, 0.0)),
];
let fov = std::f32::consts::FRAC_PI_2;
let proj = Matrix4::perspective(fov, 1.0, 0.1, radius.max(1.0));
let (forward, up) = face_lookat[face];
let view = Matrix4::look_at(pos, pos + forward, up);
let mut vp = proj.multiply(&view).elements;
vp[1] = -vp[1];
vp[5] = -vp[5];
vp[9] = -vp[9];
vp[13] = -vp[13];
vp
}
const INSTANCED_CUSTOM_SALT: u64 = 0x9e37_79b9_7f4a_7c15;
const COVERAGE_CUSTOM_SALT: u64 = 0xc2b2_ae3d_27d4_eb4f;
pub(crate) fn custom_shader_hash(fragment: &str, vertex: Option<&str>) -> u64 {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
fragment.hash(&mut h);
vertex.hash(&mut h);
h.finish()
}
pub(crate) fn custom_shader_module_source(
fragment: &str,
vertex: Option<&str>,
storage_buffers: bool,
coverage: bool,
samples: u32,
) -> String {
let source = super::shader::legacy_shader_source();
let preamble = source.split("@fragment").next().unwrap_or(source);
let user_bindings = "\n\
struct ThreersUserData { data: array<vec4<f32>, 16>, };\n\
@group(1) @binding(1) var<uniform> u_data: ThreersUserData;\n\
@group(1) @binding(5) var u_tex0: texture_2d<f32>;\n\
@group(1) @binding(6) var u_tex1: texture_2d<f32>;\n\
@group(1) @binding(7) var u_tex2: texture_2d<f32>;\n\
@group(1) @binding(8) var u_tex3: texture_2d<f32>;\n\
@group(1) @binding(9) var u_samp: sampler;\n\
@group(1) @binding(10) var u_s0_tex: texture_2d<f32>;\n\
@group(1) @binding(11) var u_s1_tex: texture_2d<f32>;\n\
@group(1) @binding(12) var u_s2_tex: texture_2d<f32>;\n";
let volume_bindings = "@group(1) @binding(13) var u_vol0: texture_3d<f32>;\n\
@group(1) @binding(14) var u_vol1: texture_3d<f32>;\n\
@group(1) @binding(15) var u_vol_samp: sampler;\n";
let storage_bindings = if storage_buffers {
"@group(1) @binding(2) var<storage, read> u_s0: array<f32>;\n\
@group(1) @binding(3) var<storage, read> u_s1: array<f32>;\n\
@group(1) @binding(4) var<storage, read> u_s2: array<f32>;\n"
} else {
""
};
let accessors = if storage_buffers {
"fn s0(i: u32) -> f32 { return u_s0[i]; }\n\
fn s1(i: u32) -> f32 { return u_s1[i]; }\n\
fn s2(i: u32) -> f32 { return u_s2[i]; }\n\
fn s0x4(t: u32) -> vec4<f32> { let i = t * 4u; return vec4<f32>(s0(i), s0(i + 1u), s0(i + 2u), s0(i + 3u)); }\n\
fn s1x4(t: u32) -> vec4<f32> { let i = t * 4u; return vec4<f32>(s1(i), s1(i + 1u), s1(i + 2u), s1(i + 3u)); }\n\
fn s2x4(t: u32) -> vec4<f32> { let i = t * 4u; return vec4<f32>(s2(i), s2(i + 1u), s2(i + 2u), s2(i + 3u)); }\n\
fn s_len(slot: u32) -> u32 {\n\
if (slot == 0u) { return arrayLength(&u_s0); }\n\
if (slot == 1u) { return arrayLength(&u_s1); }\n\
return arrayLength(&u_s2);\n\
}\n"
} else {
"fn s_fetch(t: texture_2d<f32>, i: u32) -> f32 {\n\
let w = u32(textureDimensions(t).x);\n\
let texel = i / 4u;\n\
let p = vec2<i32>(i32(texel % w), i32(texel / w));\n\
let v = textureLoad(t, p, 0);\n\
let c = i % 4u;\n\
if (c == 0u) { return v.x; }\n\
if (c == 1u) { return v.y; }\n\
if (c == 2u) { return v.z; }\n\
return v.w;\n\
}\n\
fn s0(i: u32) -> f32 { return s_fetch(u_s0_tex, i); }\n\
fn s1(i: u32) -> f32 { return s_fetch(u_s1_tex, i); }\n\
fn s2(i: u32) -> f32 { return s_fetch(u_s2_tex, i); }\n\
fn s_texel(t: texture_2d<f32>, i: u32) -> vec4<f32> {\n\
let w = u32(textureDimensions(t).x);\n\
return textureLoad(t, vec2<i32>(i32(i % w), i32(i / w)), 0);\n\
}\n\
fn s0x4(t: u32) -> vec4<f32> { return s_texel(u_s0_tex, t); }\n\
fn s1x4(t: u32) -> vec4<f32> { return s_texel(u_s1_tex, t); }\n\
fn s2x4(t: u32) -> vec4<f32> { return s_texel(u_s2_tex, t); }\n\
fn s_len(slot: u32) -> u32 {\n\
var d = textureDimensions(u_s0_tex);\n\
if (slot == 1u) { d = textureDimensions(u_s1_tex); }\n\
if (slot == 2u) { d = textureDimensions(u_s2_tex); }\n\
return u32(d.x) * u32(d.y) * 4u;\n\
}\n"
};
let mask = samples > 1 && storage_buffers && sample_mask_is_cheap();
let (mask_field, mask_set) = if mask {
("@builtin(sample_mask) mask : u32, ", "o.mask = mask; ")
} else {
("", "")
};
let coverage = format!(
"const THREERS_COVERAGE : bool = {coverage};\n\
const THREERS_SAMPLES : u32 = {samples}u;\n\
const THREERS_SAMPLE_MASK : bool = {mask};\n\
fn coverage_alpha(coverage : f32) -> f32 {{\n\
if (THREERS_COVERAGE) {{ return clamp(coverage, 0.0, 1.0); }}\n\
if (coverage < 0.5) {{ discard; }}\n\
return 1.0;\n\
}}\n\
struct ThreersFragOut {{ @location(0) color : vec4<f32>, {mask_field}}};\n\
fn frag_out(color : vec4<f32>, mask : u32) -> ThreersFragOut {{ var o : ThreersFragOut; o.color = color; {mask_set}return o; }}\n\
fn threers_sample_offset(i : u32) -> vec2<f32> {{\n\
if (THREERS_SAMPLES == 1u) {{ return vec2<f32>(0.0); }}\n\
return select(select(select(vec2<f32>(0.125, 0.375), vec2<f32>(-0.375, 0.125), i == 2u), vec2<f32>(0.375, -0.125), i == 1u), vec2<f32>(-0.125, -0.375), i == 0u);\n\
}}\n"
);
let vertex = vertex.map(|v| format!("\n{v}\n")).unwrap_or_default();
format!("{preamble}{user_bindings}{volume_bindings}{storage_bindings}{accessors}{coverage}{vertex}\n{fragment}\n")
}
#[cfg(any(target_arch = "wasm32", feature = "precompiled-shaders"))]
pub(crate) fn validate_custom_shader(_source: &str, _preamble_lines: usize) -> Result<(), String> {
Ok(())
}
#[cfg(not(any(target_arch = "wasm32", feature = "precompiled-shaders")))]
pub(crate) fn validate_custom_shader(source: &str, preamble_lines: usize) -> Result<(), String> {
if let Ok(path) = std::env::var("THREERS_DUMP_SHADER") {
let _ = std::fs::write(&path, source);
}
let module = match wgpu::naga::front::wgsl::parse_str(source) {
Ok(m) => m,
Err(e) => return Err(annotate(&e.emit_to_string(source), source, preamble_lines)),
};
let mut validator = wgpu::naga::valid::Validator::new(
wgpu::naga::valid::ValidationFlags::all(),
wgpu::naga::valid::Capabilities::all(),
);
match validator.validate(&module) {
Ok(_) => Ok(()),
Err(e) => Err(annotate(&e.emit_to_string(source), source, preamble_lines)),
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct CustomShaderReach {
full_env: bool,
volumes: bool,
}
#[cfg(all(
any(not(target_arch = "wasm32"), feature = "webgl"),
not(feature = "precompiled-shaders")
))]
fn custom_shader_reach(source: &str) -> CustomShaderReach {
use wgpu::naga::valid::{Capabilities, GlobalUse, ValidationFlags, Validator};
let mut reach = CustomShaderReach::default();
let Ok(module) = wgpu::naga::front::wgsl::parse_str(source) else {
return reach;
};
let Ok(info) = Validator::new(ValidationFlags::all(), Capabilities::all()).validate(&module)
else {
return reach;
};
for (handle, var) in module.global_variables.iter() {
let Some(binding) = &var.binding else {
continue;
};
let used = (0..module.entry_points.len())
.any(|i| info.get_entry_point(i)[handle] != GlobalUse::empty());
match (binding.group, binding.binding) {
(3, 2..=7 | 14) => reach.full_env |= used,
(1, 13..=15) => reach.volumes |= used,
_ => {}
}
}
reach
}
#[cfg(not(all(
any(not(target_arch = "wasm32"), feature = "webgl"),
not(feature = "precompiled-shaders")
)))]
fn custom_shader_reach(_source: &str) -> CustomShaderReach {
CustomShaderReach::default()
}
#[cfg(not(target_arch = "wasm32"))]
#[cfg_attr(feature = "precompiled-shaders", allow(dead_code))]
fn annotate(message: &str, source: &str, preamble_lines: usize) -> String {
let total = source.lines().count();
let mut out = String::from(message);
out.push_str(&format!(
"\n\nline numbers above are in the assembled module ({total} lines): the \
built-in preamble is the first {preamble_lines}, so subtract that for a \
position in your own source. Set THREERS_DUMP_SHADER=/tmp/shader.wgsl \
to write the whole module out."
));
out
}
fn light_up(dir: Vector3) -> Vector3 {
let d = dir.normalize();
if d.y.abs() > 0.99 {
Vector3::new(0.0, 0.0, -1.0)
} else {
Vector3::UP
}
}
fn fit_shadow_to_view(
dir: Vector3,
inv_view_proj: &Matrix4,
inv_view: &Matrix4,
reach: f32,
behind: f32,
map_size: u32,
) -> (Vector3, Matrix4, Matrix4) {
let d = dir.normalize();
let e = &inv_view.elements;
let cam = Vector3::new(e[12], e[13], e[14]);
let mut pts = vec![cam];
for (x, y) in [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)] {
let far = Vector3::new(x, y, 1.0).apply_matrix4(inv_view_proj);
let ray = far - cam;
let len = ray.length();
if len > 1e-6 && len.is_finite() {
pts.push(cam + ray * (reach.min(len) / len));
}
}
let rot = Matrix4::look_at(Vector3::ZERO, d, light_up(d));
let (mut lo, mut hi) = (
Vector3::new(f32::MAX, f32::MAX, f32::MAX),
Vector3::new(f32::MIN, f32::MIN, f32::MIN),
);
for p in &pts {
let q = p.apply_matrix4(&rot);
lo = Vector3::new(lo.x.min(q.x), lo.y.min(q.y), lo.z.min(q.z));
hi = Vector3::new(hi.x.max(q.x), hi.y.max(q.y), hi.z.max(q.z));
}
let side = (hi.x - lo.x).max(hi.y - lo.y).max(1e-3);
let side = 2f32.powf((side.log2() * 4.0).ceil() / 4.0).max(side);
let texel = side / map_size.max(1) as f32;
let cx = (((lo.x + hi.x) * 0.5) / texel).round() * texel;
let cy = (((lo.y + hi.y) * 0.5) / texel).round() * texel;
let h = side * 0.5;
let near_z = hi.z + behind;
let depth = (hi.z - lo.z) + behind;
let inv_rot = rot.invert();
let eye = Vector3::new(cx, cy, near_z).apply_matrix4(&inv_rot);
let view = Matrix4::look_at(eye, eye + d, light_up(d));
let proj = Matrix4::orthographic(-h, h, h, -h, 0.0, depth.max(1e-3) * 1.001);
(eye, view, proj)
}
fn custom_vertex_buffers(instanced: bool) -> Vec<Option<wgpu::VertexBufferLayout<'static>>> {
const fn attr(
offset: u64,
shader_location: u32,
format: wgpu::VertexFormat,
) -> wgpu::VertexAttribute {
wgpu::VertexAttribute {
offset,
shader_location,
format,
}
}
use wgpu::VertexFormat::{Float32x2, Float32x3, Float32x4};
const MESH: [wgpu::VertexAttribute; 5] = [
attr(0, 0, Float32x3),
attr(12, 1, Float32x3),
attr(24, 2, Float32x2),
attr(32, 3, Float32x4),
attr(48, 8, Float32x4),
];
const INSTANCE: [wgpu::VertexAttribute; 5] = [
attr(0, 4, Float32x4),
attr(16, 5, Float32x4),
attr(32, 6, Float32x4),
attr(48, 7, Float32x4),
attr(64, 9, Float32x4),
];
const CUSTOM: [wgpu::VertexAttribute; 2] = [attr(0, 10, Float32x4), attr(16, 11, Float32x4)];
let base = wgpu::VertexBufferLayout {
array_stride: GpuMesh::VERTEX_STRIDE as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &MESH,
};
if instanced {
vec![
Some(base),
Some(wgpu::VertexBufferLayout {
array_stride: 80,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &INSTANCE,
}),
Some(wgpu::VertexBufferLayout {
array_stride: 32,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &CUSTOM,
}),
]
} else {
vec![Some(base)]
}
}
fn build_custom_shadow_pipeline(
device: &wgpu::Device,
layout: &wgpu::PipelineLayout,
fragment: &str,
vertex: &str,
instanced: bool,
cull: Option<wgpu::Face>,
) -> Result<wgpu::RenderPipeline, String> {
let source = custom_shader_module_source(
fragment,
Some(vertex),
crate::renderer::caps::supports_storage_buffers(device),
false,
1,
);
validate_custom_shader(&source, custom_preamble_lines())?;
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("threers custom shadow shader"),
source: wgpu::ShaderSource::Wgsl(source.into()),
});
let buffers = custom_vertex_buffers(instanced);
Ok(
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers custom shadow pipeline"),
layout: Some(layout),
vertex: wgpu::VertexState {
module: &module,
entry_point: Some("vs_custom"),
buffers: &buffers,
compilation_options: Default::default(),
},
fragment: None,
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, cull),
depth_stencil: Some(wgpu::DepthStencilState {
format: DEPTH_FORMAT,
depth_write_enabled: Some(true),
depth_compare: Some(wgpu::CompareFunction::LessEqual),
stencil: Default::default(),
bias: wgpu::DepthBiasState {
constant: 2,
slope_scale: 2.0,
clamp: 0.0,
},
}),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
}),
)
}
fn build_custom_pipeline(
device: &wgpu::Device,
layout: &wgpu::PipelineLayout,
fragment: &str,
vertex: Option<&str>,
format: wgpu::TextureFormat,
transparent: bool,
screen_space: bool,
side: u32,
instanced: bool,
samples: u32,
alpha_to_coverage: bool,
pipes: &mut super::pipeline_state::StatePipelines,
) -> Result<Pipeline, String> {
let writes_mask = samples > 1
&& crate::renderer::caps::supports_storage_buffers(device)
&& sample_mask_is_cheap()
&& fragment.contains("ThreersFragOut");
let coverage = alpha_to_coverage && samples > 1 && !writes_mask;
let source = custom_shader_module_source(
fragment,
vertex,
crate::renderer::caps::supports_storage_buffers(device),
coverage,
samples,
);
validate_custom_shader(&source, custom_preamble_lines())?;
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("threers custom shader"),
source: wgpu::ShaderSource::Wgsl(source.into()),
});
let vertex_buffers = custom_vertex_buffers(instanced);
Ok(pipes.create(
device,
&wgpu::RenderPipelineDescriptor {
label: Some("threers custom pipeline"),
layout: Some(layout),
vertex: wgpu::VertexState {
module: &module,
entry_point: Some(if vertex.is_some() {
"vs_custom"
} else if instanced {
"vs_instanced_custom"
} else {
"vs_main"
}),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &module,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(if transparent || screen_space {
wgpu::BlendState::ALPHA_BLENDING
} else if coverage {
wgpu::BlendState {
color: wgpu::BlendComponent::REPLACE,
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Constant,
dst_factor: wgpu::BlendFactor::Zero,
operation: wgpu::BlendOperation::Add,
},
}
} else {
wgpu::BlendState::REPLACE
}),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(
wgpu::PrimitiveTopology::TriangleList,
match side {
1 => Some(wgpu::Face::Front),
2 => None,
_ => Some(wgpu::Face::Back),
},
),
depth_stencil: Some(depth_stencil(
screen_space || !transparent,
wgpu::CompareFunction::LessEqual,
)),
multisample: wgpu::MultisampleState {
count: samples,
alpha_to_coverage_enabled: coverage,
..Default::default()
},
multiview_mask: None,
cache: None,
},
))
}
const fn sample_mask_is_cheap() -> bool {
!cfg!(target_arch = "wasm32")
}
pub(crate) fn custom_preamble_lines() -> usize {
custom_shader_module_source("", None, true, false, 1)
.lines()
.count()
}
impl Renderer {
pub fn camera_planes(&self) -> (f32, f32) {
self.last_camera_planes
}
pub fn camera_lens(&self) -> (f32, f32) {
self.last_camera_lens
}
pub fn device_arc(&self) -> Arc<wgpu::Device> {
self.device.clone()
}
pub fn queue_arc(&self) -> Arc<wgpu::Queue> {
self.queue.clone()
}
pub fn set_reflective_transparency(&mut self, on: bool) {
self.reflective_transparency = on;
}
pub fn reflective_transparency(&self) -> bool {
self.reflective_transparency
}
pub fn set_refraction_layers(&mut self, layers: usize) {
self.refraction_layers = layers.max(1);
}
pub fn refraction_layers(&self) -> usize {
self.refraction_layers
}
pub fn reprojection(&self) -> ([f32; 16], [f32; 16]) {
(self.mb_inv_vp, self.mb_prev_vp)
}
pub fn depth_texture(&self) -> &wgpu::Texture {
&self.depth_texture
}
pub fn draw_over_last(
&self,
target_view: &wgpu::TextureView,
draw: impl FnOnce(&mut wgpu::RenderPass<'_>, &OverlayInfo),
) {
let Some(last) = &self.last_overlay else {
return;
};
let pane = last.pane.as_ref().and_then(|(key, region)| {
self.viewport_state
.pane_target(key)
.map(|t| (t, key, *region))
});
let (color, resolve, depth, samples) = match (&pane, &self.msaa_targets) {
(Some((t, ..)), _) => (
&t.msaa_color,
Some(&t.resolve),
Some(&t.msaa_depth),
self.msaa,
),
(None, Some((_, _, cv, dv))) if self.overlay_msaa => {
(cv, Some(target_view), Some(dv), self.msaa)
}
_ if self.last_frame_msaa => (target_view, None, None, 1),
_ => (target_view, None, Some(&self.depth_view), 1),
};
let info = OverlayInfo {
samples,
depth: depth.is_some(),
reversed: self.reversed_z(),
projection_fix: last.projection_fix,
color_format: self.color_format,
};
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("threers overlay"),
});
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers overlay"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: color,
depth_slice: None,
resolve_target: resolve,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: depth.map(|view| {
wgpu::RenderPassDepthStencilAttachment {
view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
let (v, sc) = (last.viewport, last.scissor);
pass.set_viewport(
v.x as f32,
v.y as f32,
v.width as f32,
v.height as f32,
0.0,
1.0,
);
pass.set_scissor_rect(sc.x, sc.y, sc.width, sc.height);
draw(&mut pass, &info);
}
if let Some((_, key, region)) = pane {
self.viewport_state.composite_pane(
&mut encoder,
target_view,
self.color_format,
key,
region,
);
}
self.queue.submit(Some(encoder.finish()));
}
pub fn overlay_attachments(&self) -> (Option<&wgpu::TextureView>, &wgpu::TextureView, u32) {
match (&self.msaa_targets, self.overlay_msaa) {
(Some((_, _, color, depth)), true) => (Some(color), depth, self.msaa),
_ => (None, &self.depth_view, 1),
}
}
pub fn taa(&self) -> bool {
self.taa_enabled
}
pub fn set_taa(&mut self, enabled: bool) {
if !enabled {
self.taa_frame = 0;
self.taa_history = None;
}
self.taa_enabled = enabled;
}
pub fn set_taa_converge(&mut self, converge: bool) {
self.taa_converge = converge;
}
pub fn taa_converge(&self) -> bool {
self.taa_converge
}
pub fn set_taa_blit(&mut self, on: bool) {
self.taa_blit = on;
}
pub fn set_jitter_override(&mut self, offset: Option<(f32, f32)>) {
self.jitter_override = offset;
}
pub fn reset_taa(&mut self) {
self.taa_frame = 0;
}
pub fn set_frustum_culling(&mut self, on: bool) {
self.frustum_culling = on;
}
pub fn frustum_culling(&self) -> bool {
self.frustum_culling
}
pub fn custom_shader_stats(&self) -> super::CustomShaderStats {
self.custom_cache.stats()
}
pub fn cull_stats(&self) -> (usize, usize) {
self.cull_stats
}
pub fn pending_pipelines(&self) -> usize {
self.state_pipelines.source().uncompiled().len()
}
pub fn warm_up(&self) -> super::PipelineWarmup {
super::PipelineWarmup::new(self.state_pipelines.source().uncompiled())
}
pub fn warm_up_ranked(&self, rank: impl Fn(&str) -> i32) -> super::PipelineWarmup {
let mut pipelines = self.state_pipelines.source().uncompiled();
pipelines.sort_by_key(|p| rank(p.label().unwrap_or("")));
super::PipelineWarmup::new(pipelines)
}
pub fn warm_up_states(
&mut self,
states: &[crate::materials::RenderState],
) -> super::PipelineWarmup {
self.state_pipelines
.variants_of_initial(&self.device, states);
self.warm_up()
}
pub fn pipeline_failures(&self) -> Vec<super::PipelineError> {
self.state_pipelines
.source()
.failed()
.into_iter()
.map(|(label, message)| super::PipelineError { label, message })
.collect()
}
pub fn warm_up_matching(&self, keep: impl Fn(&str) -> bool) -> super::PipelineWarmup {
let pipelines = self.state_pipelines.source().uncompiled();
super::PipelineWarmup::new(
pipelines
.into_iter()
.filter(|p| keep(p.label().unwrap_or("")))
.collect(),
)
}
pub fn pending_pipeline_labels(&self) -> Vec<String> {
let mut labels: Vec<String> = self
.state_pipelines
.source()
.uncompiled()
.iter()
.map(|p| p.label().unwrap_or("").to_owned())
.collect();
labels.sort();
labels.dedup();
labels
}
#[cfg(not(target_arch = "wasm32"))]
pub fn warm_scene(&mut self, scene: &mut Scene, camera: &dyn Camera) {
let (width, height) = self.drawing_buffer_size();
let target = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers warm-up target"),
size: wgpu::Extent3d {
width: width.max(1),
height: height.max(1),
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: self.color_format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let view = target.create_view(&wgpu::TextureViewDescriptor::default());
self.render(scene, camera, &view, false);
let _ = self.device.poll(wgpu::PollType::wait_indefinitely());
}
pub fn pipeline_cache(&self) -> Option<&wgpu::PipelineCache> {
self.state_pipelines.source().cache()
}
pub fn color_format(&self) -> wgpu::TextureFormat {
self.color_format
}
pub fn resize(&mut self, width: u32, height: u32) {
if (width, height) != self.depth_size && width > 0 && height > 0 {
let (tex, view) = create_depth_view(&self.device, width, height);
self.depth_texture = tex;
self.depth_view = view;
self.depth_size = (width, height);
}
}
pub fn set_viewport(&mut self, x: f32, y: f32, width: f32, height: f32) {
self.viewport_state.settings.viewport = Some(super::ViewportRect::new(x, y, width, height));
}
pub fn viewport(&self) -> Option<super::ViewportRect> {
self.viewport_state.settings.viewport
}
pub fn reset_viewport(&mut self) {
self.viewport_state.settings.viewport = None;
}
pub fn set_scissor(&mut self, x: f32, y: f32, width: f32, height: f32) {
self.viewport_state.settings.scissor = Some(super::ViewportRect::new(x, y, width, height));
}
pub fn scissor(&self) -> Option<super::ViewportRect> {
self.viewport_state.settings.scissor
}
pub fn reset_scissor(&mut self) {
self.viewport_state.settings.scissor = None;
}
pub fn set_scissor_test(&mut self, enabled: bool) {
self.viewport_state.settings.scissor_test = enabled;
}
pub fn scissor_test(&self) -> bool {
self.viewport_state.settings.scissor_test
}
pub fn set_pixel_ratio(&mut self, ratio: f32) {
self.viewport_state.settings.set_pixel_ratio(ratio);
}
pub fn pixel_ratio(&self) -> f32 {
self.viewport_state.settings.pixel_ratio()
}
pub fn size(&self) -> (f32, f32) {
let pr = self.viewport_state.settings.pixel_ratio();
(self.depth_size.0 as f32 / pr, self.depth_size.1 as f32 / pr)
}
pub fn drawing_buffer_size(&self) -> (u32, u32) {
self.depth_size
}
pub fn set_auto_clear(&mut self, enabled: bool) {
self.viewport_state.settings.auto_clear = enabled;
}
pub fn auto_clear(&self) -> bool {
self.viewport_state.settings.auto_clear
}
pub fn set_msaa(&mut self, samples: u32) {
let s = if samples > 1 { MSAA_SAMPLES } else { 1 };
self.msaa = s;
}
pub fn msaa(&self) -> u32 {
self.msaa
}
pub fn shadow_stats(&self) -> (u64, u64) {
self.shadow_stats
}
pub fn set_shadow_type(&mut self, kind: crate::lights::ShadowType) {
self.shadow_type = kind;
}
pub fn shadow_type(&self) -> crate::lights::ShadowType {
self.shadow_type
}
#[doc(hidden)]
pub fn force_depth_replay(&mut self, on: bool) {
self.force_depth_replay = on;
}
pub fn last_frame_multisampled(&self) -> bool {
self.last_frame_msaa
}
pub fn set_tone_mapping(&mut self, mode: ToneMapping, exposure: f32) {
self.tone_mapping = mode;
self.exposure = exposure;
}
pub fn tone_mapping(&self) -> (ToneMapping, f32) {
(self.tone_mapping, self.exposure)
}
fn depth_clear(&self) -> f32 {
if self.state_pipelines.reversed() {
0.0
} else {
1.0
}
}
pub fn set_reversed_z(&mut self, on: bool) {
self.state_pipelines.set_reversed(on);
}
pub fn reversed_z(&self) -> bool {
self.state_pipelines.reversed()
}
pub fn set_specular_antialiasing(&mut self, on: bool) {
self.specular_antialiasing = on;
}
pub fn specular_antialiasing(&self) -> bool {
self.specular_antialiasing
}
pub fn gpu_frame_ms(&self) -> f32 {
self.timer.as_ref().map(|t| t.last_ms()).unwrap_or(0.0)
}
pub fn gpu_shadow_ms(&self) -> f32 {
self.shadow_timer
.as_ref()
.map(|t| t.last_ms())
.unwrap_or(0.0)
}
pub fn shadow_map(&self) -> &super::viewport::ShadowMap {
&self.shadow_map
}
pub fn shadow_map_mut(&mut self) -> &mut super::viewport::ShadowMap {
&mut self.shadow_map
}
pub fn shadow_map_updates(&self) -> u64 {
self.shadow_updates
}
}
pub fn stratified_jitter(n: u32) -> Vec<(f32, f32)> {
let n = n.max(1);
let ladder = |base: u32| -> Vec<f32> {
let vals: Vec<f32> = (0..n).map(|k| halton(k + 1, base)).collect();
let mut order: Vec<u32> = (0..n).collect();
order.sort_by(|&a, &b| vals[a as usize].total_cmp(&vals[b as usize]));
let mut out = vec![0.0; n as usize];
for (rung, &k) in order.iter().enumerate() {
out[k as usize] = (rung as f32 + 0.5) / n as f32 - 0.5;
}
out
};
ladder(2).into_iter().zip(ladder(3)).collect()
}
pub fn halton(mut index: u32, base: u32) -> f32 {
let (mut f, mut r) = (1.0f32, 0.0f32);
while index > 0 {
f /= base as f32;
r += f * (index % base) as f32;
index /= base;
}
r
}
fn primitive(topology: wgpu::PrimitiveTopology, cull: Option<wgpu::Face>) -> wgpu::PrimitiveState {
wgpu::PrimitiveState {
topology,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: cull,
polygon_mode: wgpu::PolygonMode::Fill,
unclipped_depth: false,
conservative: false,
}
}
#[allow(clippy::too_many_arguments)]
fn build_biased_pipeline(
device: &wgpu::Device,
module: &wgpu::ShaderModule,
layout: &wgpu::PipelineLayout,
format: wgpu::TextureFormat,
samples: u32,
code: u8,
factor: f32,
units: i32,
pipes: &mut super::pipeline_state::StatePipelines,
) -> Pipeline {
let alpha = code == 1;
let vertex_buffers = [Some(wgpu::VertexBufferLayout {
array_stride: GpuMesh::VERTEX_STRIDE as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: 12,
shader_location: 1,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: 24,
shader_location: 2,
format: wgpu::VertexFormat::Float32x2,
},
wgpu::VertexAttribute {
offset: 32,
shader_location: 3,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: 48,
shader_location: 8,
format: wgpu::VertexFormat::Float32x4,
},
],
})];
let mut ds = depth_stencil(!alpha, wgpu::CompareFunction::LessEqual);
ds.bias = wgpu::DepthBiasState {
constant: units,
slope_scale: factor,
clamp: 0.0,
};
pipes.create(
device,
&wgpu::RenderPipelineDescriptor {
label: Some("threers polygon-offset pipeline"),
layout: Some(layout),
vertex: wgpu::VertexState {
module,
entry_point: Some("vs_main"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(if alpha {
wgpu::BlendState::ALPHA_BLENDING
} else {
wgpu::BlendState::REPLACE
}),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(
wgpu::PrimitiveTopology::TriangleList,
if code == 2 {
None
} else {
Some(wgpu::Face::Back)
},
),
depth_stencil: Some(ds),
multisample: wgpu::MultisampleState {
count: samples,
..Default::default()
},
multiview_mask: None,
cache: None,
},
)
}
fn depth_stencil(write: bool, compare: wgpu::CompareFunction) -> wgpu::DepthStencilState {
wgpu::DepthStencilState {
format: DEPTH_FORMAT,
depth_write_enabled: Some(write),
depth_compare: Some(compare),
stencil: Default::default(),
bias: Default::default(),
}
}
fn create_depth_view(
device: &wgpu::Device,
width: u32,
height: u32,
) -> (wgpu::Texture, wgpu::TextureView) {
let tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers depth"),
size: wgpu::Extent3d {
width: width.max(1),
height: height.max(1),
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: DEPTH_FORMAT,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::COPY_SRC
| wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
(tex, view)
}
fn upload_ltc(device: &wgpu::Device, queue: &wgpu::Queue) -> (wgpu::Texture, wgpu::TextureView) {
#[cfg(not(threers_no_rect_area_light))]
let half: Vec<u16> = {
const LTC_1: &[u8] = include_bytes!("ltc/ltc_float_1.bin");
const LTC_2: &[u8] = include_bytes!("ltc/ltc_float_2.bin");
[LTC_1, LTC_2]
.iter()
.flat_map(|b| b.as_chunks::<4>().0)
.map(|c| {
super::gpu_texture::f32_to_f16_bits(f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
})
.collect()
};
#[cfg(threers_no_rect_area_light)]
let half: Vec<u16> = vec![0; 64 * 64 * 4 * 2];
let size = wgpu::Extent3d {
width: 64,
height: 64,
depth_or_array_layers: 2,
};
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers RectAreaLight LTC tables"),
size,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba16Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
bytemuck::cast_slice(&half),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(64 * 8),
rows_per_image: Some(64),
},
size,
);
let view = texture.create_view(&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::D2Array),
..Default::default()
});
(texture, view)
}
fn frame_bg(
device: &wgpu::Device,
layout: &wgpu::BindGroupLayout,
buffer: &wgpu::Buffer,
capture: &wgpu::TextureView,
sampler: &wgpu::Sampler,
label: &str,
) -> wgpu::BindGroup {
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some(label),
layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(capture),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(sampler),
},
],
})
}
fn transform_direction(m: &Matrix4, v: Vector3) -> Vector3 {
let e = &m.elements;
Vector3::new(
e[0] * v.x + e[4] * v.y + e[8] * v.z,
e[1] * v.x + e[5] * v.y + e[9] * v.z,
e[2] * v.x + e[6] * v.y + e[10] * v.z,
)
}
fn mat3_to_mat4_array(m: &Matrix3) -> [f32; 16] {
let e = &m.elements;
[
e[0], e[1], e[2], 0.0, e[3], e[4], e[5], 0.0, e[6], e[7], e[8], 0.0, 0.0, 0.0, 0.0, 1.0,
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_custom_preamble_carries_the_documented_helpers() {
let module =
custom_shader_module_source("@fragment\nfn fs_main() {}\n", None, true, false, 1);
let preamble = module.split("struct ThreersUserData").next().unwrap();
for name in [
"fn framebuffer_encode",
"fn linear_to_srgb",
"fn aces_tonemap",
"fn sample_env_cube",
"fn pbr_brdf",
"fn apply_fog",
"struct VsOut",
"fn vs_main",
] {
assert!(
preamble.contains(name),
"`{name}` is missing from the custom-shader preamble — something \
declared an entry point above it in SHADER_SOURCE"
);
}
}
#[test]
fn no_fragment_entry_point_precedes_fs_main() {
let source = crate::renderer::shader::legacy_shader_source();
let first = source
.find("@fragment")
.expect("SHADER_SOURCE has a fragment entry point");
let after = &source[first..];
let name = after
.split("fn ")
.nth(1)
.and_then(|s| s.split(|c: char| !c.is_alphanumeric() && c != '_').next())
.unwrap_or("");
assert_eq!(
name, "fs_main",
"the first `@fragment` in SHADER_SOURCE is `{name}`, not `fs_main`; \
move it below `fs_main` or it truncates the shader-material preamble"
);
}
}
#[cfg(target_arch = "wasm32")]
fn frame_canvas(
slot: &mut Option<(
web_sys::HtmlCanvasElement,
web_sys::CanvasRenderingContext2d,
)>,
frame: &web_sys::VideoFrame,
size: (u32, u32),
) -> Option<web_sys::HtmlCanvasElement> {
use wasm_bindgen::JsCast;
if slot.is_none() {
let canvas: web_sys::HtmlCanvasElement = web_sys::window()?
.document()?
.create_element("canvas")
.ok()?
.dyn_into()
.ok()?;
let ctx: web_sys::CanvasRenderingContext2d =
canvas.get_context("2d").ok()??.dyn_into().ok()?;
*slot = Some((canvas, ctx));
}
let (canvas, ctx) = slot.as_ref()?;
if (canvas.width(), canvas.height()) != size {
canvas.set_width(size.0);
canvas.set_height(size.1);
}
let draw = js_sys::Reflect::get(ctx, &"drawImage".into()).ok()?;
let draw: &js_sys::Function = draw.unchecked_ref();
draw.call3(ctx, frame, &0.into(), &0.into()).ok()?;
Some(canvas.clone())
}