Files
horizon-airdef/crates/horizon-client/src/gfx.rs
T
Ludovic Marie 5dac64f770 Merge pull request #561 from ludovic111/perf/section-culling-columns
Renderer: cull sections by chunk column from a dense list (section walk 5x faster, exact)
2026-10-16 23:04:53 +02:00

3528 lines
140 KiB
Rust

//! GPU renderer for streamed terrain sections, sky, block outline and HUD.
//! Section origins are supplied relative to the camera each frame so large
//! world coordinates keep full precision.
use crate::{
Result,
environment::Sky,
hud::{HudBatch, HudRenderer},
mesher::{SectionMesh, TerrainVertex, Vertex},
sprites::SpriteAnimation,
};
use glam::{DVec3, Mat4, Vec3, Vec4};
use std::{collections::HashMap, path::PathBuf, sync::Arc, time::Instant};
use wgpu::util::DeviceExt;
use winit::window::Window;
// RenderPipelines.CRUMBLING: dst * src + src * dst, alpha replaced.
const CRUMBLING_BLEND: wgpu::BlendState = wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Dst,
dst_factor: wgpu::BlendFactor::Src,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent::REPLACE,
};
/// `TerrainVertex` for `vs_terrain`: position, UV, layer, light, colour.
const TERRAIN_ATTRIBUTES: [wgpu::VertexAttribute; 5] =
wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint16,4=>Uint8x2,3=>Unorm8x4];
/// entity.wgsl after the OverlayTexture constants it reads.
fn entity_shader() -> String {
crate::overlay::wgsl_constants() + include_str!("entity.wgsl")
}
mod entity_batch;
use entity_batch::EntityBatch;
/// Window.getAppropriateLineWidth, in framebuffer pixels.
pub fn outline_width(width: u32) -> f32 {
2.5f32.max(width as f32 / 1920.0 * 2.5)
}
/// ScreenSize, stroke width and ProjectionType.PERSPECTIVE layering.
pub fn outline_params(width: u32, height: u32) -> [f32; 4] {
[
width as f32,
height.max(1) as f32,
outline_width(width),
1.0 - 1.0 / 4096.0,
]
}
/// Camera-relative segment endpoints; no shape expansion in vanilla 26.3.
pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6]> {
edges
.iter()
.map(|e| std::array::from_fn(|i| (e[i] - camera.to_array()[i % 3]) as f32))
.collect()
}
mod arena;
mod java_stages;
mod occlusion;
mod pack_stages;
pub mod panorama;
mod resident;
mod timing;
pub(crate) mod upload;
mod world_post;
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Globals {
view_proj: [[f32; 4]; 4],
fog_color: [f32; 4],
fog: [f32; 4],
sky_color: [f32; 4],
misc: [f32; 4],
inverse_view: [[f32; 4]; 4],
sunrise: [f32; 4],
sun: [f32; 4],
/// x: sky fog end, y: cloud fog end, z: dark disc (camera below the horizon), w: unused.
fog_ends: [f32; 4],
/// Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png.
end_portal_sprites: [[f32; 4]; 2],
/// x: vanilla's `GameTime` uniform; y: nether cardinal lighting, zw unused.
time: [f32; 4],
/// Atlas rect of the current destroy stage (entity.wgsl).
crumbling_sprite: [f32; 4],
/// Framebuffer size, selection stroke width, perspective layering scale.
outline_params: [f32; 4],
}
pub type SectionKey = (i32, i32, i32);
struct SectionGpu {
/// Arena page and first vertex in it: solid quads, then translucent ones.
page: u32,
start: u64,
solid: u32,
translucent: u32,
/// The solid quads by facing: back-facing groups are skipped.
faces: crate::mesher::FaceGroups,
}
/// Line segments the hit outline can hold.
const MAX_OUTLINE_EDGES: u64 = 256;
pub struct Frame<'a> {
pub camera: DVec3,
pub yaw: f32,
pub pitch: f32,
pub fov_degrees: f32,
/// The `GameRenderer.bobHurt`/`bobView` pose multiplied into the
/// projection (`crate::camera::bob_matrix`).
pub bob: Mat4,
pub sky: Sky,
/// Render distance in blocks (fog end).
pub distance: f32,
/// `Camera.depthFar`: the far plane (`crate::camera::depth_far`).
pub depth_far: f32,
pub underwater: bool,
/// Skip sections the camera cannot see through open faces (vanilla's
/// occlusion graph; off in spectator-like views inside blocks).
pub cave_culling: bool,
/// Title screen: only the dedicated panorama cube map and the HUD.
pub title: bool,
/// Dimensions without a skybox (the Nether) clear to the fog colour.
pub skybox: bool,
/// The End: clear to black and draw `celestial` (the End sky box) behind the world.
pub end_sky: bool,
/// Environmental fog start/end (Nether 10..96), if any.
pub environment_fog: Option<(f32, f32)>,
pub water_fog: [f32; 3],
/// `FogRenderer.setupFog` result; replaces the underwater/environment fields when set.
pub fog: Option<crate::fog::FogData>,
/// Camera eye below the horizon height and not under water (`shouldRenderDarkDisc`).
pub dark_disc: bool,
/// The hit block outline as line segments (from, to) in world space.
pub outline: Vec<[f64; 6]>,
/// `lines` with a colour and pixel width (`gizmos::camera_relative`):
/// the fishing line and debug gizmos, depth tested, then gizmos drawn
/// over everything.
pub debug_lines: &'a [[f32; 8]],
pub debug_lines_on_top: &'a [[f32; 8]],
/// `DebugCrosshairRenderer`'s axes, camera relative like `debug_lines`:
/// drawn after the hand at its projection, without the bob or fog.
pub debug_crosshair: &'a [[f32; 8]],
pub hud: &'a HudBatch,
/// CardinalLighting.Type.NETHER, otherwise DEFAULT.
pub nether_lighting: bool,
/// Camera-relative entity geometry textured from the shared atlas.
pub entities: &'a [Vertex],
/// Cloud mesh inputs; geometry and GPU storage are retained by the renderer.
pub clouds: Option<crate::clouds::Input<'a>>,
/// Additive translucent geometry after the entities (lightning, dragon rays).
pub additive: &'a [Vertex],
/// Name tags over everything, without depth (`TEXT_SEE_THROUGH`).
pub see_through: &'a [Vertex],
/// Camera-relative sun, moon and stars (drawn behind everything, additive).
pub celestial: &'a [Vertex],
/// First-person hand and held item, drawn after clearing depth.
pub hand: &'a [Vertex],
/// `CameraRenderState.hudFov`: the hand's own field of view
/// (`GameRenderer.render3dHud`).
pub hand_fov_degrees: f32,
/// Full-screen camera effects drawn over the world and hand, under the HUD.
pub screen: &'a [crate::screen_effects::ScreenQuad],
/// The world border wall, when near enough to be drawn.
pub border: Option<BorderDraw>,
pub game_time: f32,
/// `GlobalSettingsUniform` GameTime: (game time % 24000 + partial tick) / 24000.
pub shader_game_time: f32,
/// Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png
/// (`rendertype_end_portal`'s Sampler0 and Sampler1).
pub end_portal_sprites: [[f32; 4]; 2],
/// Current destroy-stage sprite: projected UVs repeat inside this atlas rect.
pub crumbling_sprite: [f32; 4],
pub ticks: u64,
/// The darkness effect on the lightmap: the brightness it takes off the
/// gamma option and the pulsing scale subtracted from the light.
pub darkness: (f32, f32),
/// Night vision (or conduit water vision) intensity on the lightmap.
pub night_vision: f32,
/// Torch flicker added to the block light factor of 1.4.
pub block_flicker: f32,
/// Blur and grade the frame under a Horizon-style menu (`post`).
pub post: Option<crate::post::PostGrade>,
/// `Screen.extractBlurredBackground`: blur the frame by this radius
/// (`menuBackgroundBlurriness`) before the screen is drawn over it.
pub menu_blur: Option<f32>,
/// What a shader pack's `Frame` uniform reads beyond the rest of the frame.
pub shader: ShaderInputs,
}
/// A shader pack's view of the game this frame (docs/shader-packs.md, `Frame`).
#[derive(Clone, Copy, Debug, Default)]
pub struct ShaderInputs {
/// `Level.getRainLevel` and `getThunderLevel` at the partial tick.
pub rain: f32,
pub thunder: f32,
/// The camera's fog type: 0 air, 1 water, 2 lava, 3 powder snow.
pub submerged: u8,
/// 0 overworld, -1 the Nether, 1 the End.
pub dimension: i8,
pub has_sky_light: bool,
/// `DimensionType.moonPhase`, 0..=7.
pub moon_phase: u8,
/// The time of day as a fraction (0 sunrise, 0.25 noon) and the partial tick.
pub day_fraction: f32,
pub partial_tick: f32,
}
/// One frame of the world border wall (`WorldBorderRenderer.render`).
#[derive(Clone, Debug)]
pub struct BorderDraw {
/// The cached wall buffer; uploaded only when `rebuilt`.
pub vertices: [crate::border_render::BorderVertex; 16],
pub rebuilt: bool,
pub transforms: crate::border_render::BorderTransforms,
/// Walls to draw (indices of four-vertex quads), nearest first.
pub sides: Vec<usize>,
}
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct BorderUniform {
color: [f32; 4],
offset: [f32; 4],
}
pub struct Renderer {
instance: wgpu::Instance,
/// The window's swapchain; `None` when rendering offscreen (`--offscreen`).
surface: Option<wgpu::Surface<'static>>,
/// The offscreen colour target, sized like `config`.
offscreen: Option<wgpu::Texture>,
/// Offscreen submissions still on the GPU: at most two frames run ahead.
in_flight: std::collections::VecDeque<wgpu::SubmissionIndex>,
gpu_timer: Option<timing::GpuTimer>,
/// GPU frame times (ms) read back since the caller last drained them.
pub gpu_times: Vec<f32>,
/// The last lightmap written, RGBA rows of sky level by block level
/// (F3+4 shows it).
pub lightmap_pixels: [u8; 16 * 16 * 4],
/// Time the last `render` spent blocked on the GPU or the display
/// (acquiring, presenting, offscreen pacing), excluded from CPU time.
pub last_wait: std::time::Duration,
/// CPU time of the last `render`, waits excluded.
pub last_encode: std::time::Duration,
window: Arc<Window>,
pub device: wgpu::Device,
pub queue: wgpu::Queue,
pub config: wgpu::SurfaceConfiguration,
solid: wgpu::RenderPipeline,
translucent: wgpu::RenderPipeline,
sky: wgpu::RenderPipeline,
dark_disc: wgpu::RenderPipeline,
lines: wgpu::RenderPipeline,
/// Gizmo lines (`RenderTypes.linesTranslucentNoDepthWrite`) and the
/// always-on-top ones.
debug_lines: wgpu::RenderPipeline,
debug_lines_on_top: wgpu::RenderPipeline,
debug_line_buffer: wgpu::Buffer,
debug_line_capacity: u64,
/// The terrain resources with the debug crosshair's projection
/// (`crosshair_globals`).
crosshair_group: wgpu::BindGroup,
crosshair_globals: wgpu::Buffer,
entity_pipeline: wgpu::RenderPipeline,
crumbling_pipeline: wgpu::RenderPipeline,
cloud_pipeline: wgpu::RenderPipeline,
cloud_mesh: crate::clouds::Mesh,
cloud_buffer: wgpu::Buffer,
cloud_capacity: u64,
cloud_uniform: wgpu::Buffer,
cloud_group: wgpu::BindGroup,
additive_pipeline: wgpu::RenderPipeline,
see_through_pipeline: wgpu::RenderPipeline,
celestial_pipeline: wgpu::RenderPipeline,
celestial_buffer: wgpu::Buffer,
panorama: panorama::Panorama,
/// `RenderPipelines.WORLD_BORDER` and its buffers.
border_pipeline: wgpu::RenderPipeline,
border_group: wgpu::BindGroup,
border_uniform: wgpu::Buffer,
border_vertices: wgpu::Buffer,
/// Screen effects: alpha-blended and vignette (`dst * (1 - src)`) pipelines.
screen_pipelines: [wgpu::RenderPipeline; 2],
screen_buffer: wgpu::Buffer,
screen_capacity: u64,
entity_group: wgpu::BindGroup,
/// The entity resources with the hand's projection (`hand_globals`).
hand_group: wgpu::BindGroup,
hand_globals: wgpu::Buffer,
entity_buffer: wgpu::Buffer,
entity_capacity: u64,
entity_batch: EntityBatch,
group: wgpu::BindGroup,
globals: wgpu::Buffer,
lightmap: wgpu::Texture,
sprite_texture: wgpu::Texture,
mip_levels: u32,
/// The mipmap levels sampled (the Mipmap Levels option), at most `mip_levels - 1`.
mipmaps: u32,
terrain_layout: wgpu::BindGroupLayout,
sprite_sampler: wgpu::Sampler,
lightmap_view: wgpu::TextureView,
lightmap_sampler: wgpu::Sampler,
animations: AnimatedSprites,
uploads: upload::Uploads,
/// Whether `lightmap` holds `lightmap_pixels` yet.
lightmap_uploaded: bool,
sprite_minimum_size: u32,
indices: wgpu::Buffer,
index_quads: u32,
instances: wgpu::Buffer,
instance_capacity: u64,
outline: wgpu::Buffer,
depth: wgpu::TextureView,
sections: resident::Resident<SectionGpu>,
arena: arena::Arena,
/// `DrawIndexedIndirectArgs` for this frame's solid then translucent draws.
indirect: wgpu::Buffer,
indirect_capacity: u64,
/// Indirect draws may set `first_instance` (the section origin).
pub multi_draw: bool,
/// Per-frame scratch, kept to avoid allocating every frame.
visible: Vec<resident::Visible>,
origins: Vec<[f32; 4]>,
/// `DrawIndexedIndirectArgs` words: index count, instance count, first
/// index, base vertex, first instance.
draws: Vec<[u32; 5]>,
/// The arena page of each of `draws`.
draw_pages: Vec<u32>,
/// Block-entity blocks per meshed section (world position, state id).
block_entities: HashMap<SectionKey, Vec<([i32; 3], u32)>>,
/// VisGraph face connectivity per meshed section (cave culling).
occlusion: occlusion::Occlusion,
/// Resolution scale and FXAA (Horizon settings).
world_post: world_post::Post,
/// The selected shader pack's stages (Horizon setting; none by default).
pack: Option<Pack>,
pub hud: HudRenderer,
/// The menus' backdrop blur, made on first use.
post: Option<crate::post::Post>,
/// Vanilla's menu background blur, made on first use.
menu_blur: Option<crate::menu_blur::MenuBlur>,
pub info: wgpu::AdapterInfo,
pub suspended: bool,
pub drawn_sections: usize,
pub uploaded_bytes: u64,
started: Instant,
/// Write the next presented frame to this PNG path (control socket).
pub screenshot: Option<PathBuf>,
/// Outcome of the last screenshot: frame size, or the error.
pub screenshot_result: Option<std::result::Result<[u32; 2], String>>,
/// Brightness option (lightmap gamma), 0..1.
pub gamma: f32,
/// Advance animated block textures (Horizon setting; vanilla always does).
pub animated_textures: bool,
present_modes: Vec<wgpu::PresentMode>,
}
/// Every layer's mip levels, layer major (`first` is the first layer's
/// index into `settings`), made by `MipmapGenerator`.
fn mip_chain(
pixels: &[u8],
size: u32,
settings: &[crate::mipmap::Settings],
first: u32,
layers: u32,
) -> (Vec<u8>, u32) {
let levels = size.trailing_zeros() + 1;
let layer_bytes = (size * size * 4) as usize;
// Exactly the chain's size: cached animation frames count their capacity.
let chain_bytes: usize = (0..levels).map(|l| layer_bytes >> (2 * l)).sum();
let mut out = Vec::with_capacity(chain_bytes * layers as usize);
for layer in 0..layers as usize {
let base = crate::mipmap::Image {
width: size,
height: size,
pixels: pixels[layer * layer_bytes..(layer + 1) * layer_bytes]
.as_chunks::<4>()
.0
.to_vec(),
};
let s = settings
.get(first as usize + layer)
.copied()
.unwrap_or_default();
let has_transparent = s.has_transparent || base.pixels.iter().any(|p| p[3] == 0);
for image in crate::mipmap::generate(
base,
levels - 1,
crate::mipmap::Settings {
has_transparent,
..s
},
) {
out.extend(image.pixels.iter().flatten());
}
}
debug_assert_eq!(out.len(), chain_bytes * layers as usize);
(out, levels)
}
/// The wgpu instance options, without wgpu's validation of indirect draws
/// in release builds. That validation (meant for untrusted WebGPU content)
/// copies every indirect draw through a compute pass before the render pass
/// and costs about a tenth of `render`'s CPU time on Metal. The only indirect
/// draws are the section draws `render` writes from resident sections, in
/// bounds by construction: index counts within `indices`, vertices within
/// the section's arena range, first instances below the origins written that
/// frame. Debug builds keep validating them; `WGPU_VALIDATION_INDIRECT_CALL=1`
/// turns it back on.
fn instance_descriptor() -> wgpu::InstanceDescriptor {
let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle();
if !cfg!(debug_assertions) {
descriptor
.flags
.remove(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL);
}
descriptor.with_env()
}
/// What to tell a player whose system offers no usable graphics adapter.
/// Vulkan is loaded at run time (the game links no graphics library), so a
/// missing driver shows here rather than as a missing-DLL dialog.
#[cfg(target_os = "windows")]
const NO_GPU_DRIVER: &str = "No Vulkan graphics driver found: Horizon needs a GPU driver with Vulkan \
(vulkan-1.dll comes with it). Install the latest driver for your NVIDIA, AMD or Intel GPU \
and start the game again";
#[cfg(target_os = "macos")]
const NO_GPU_DRIVER: &str = "No Metal graphics device found";
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
const NO_GPU_DRIVER: &str = "No Vulkan graphics driver found: Horizon needs the Vulkan loader \
(libvulkan.so.1) and a Vulkan driver for your GPU (Mesa's, or NVIDIA's)";
impl Renderer {
/// Sections with GPU buffers, for soak tests watching residency.
pub fn resident_sections(&self) -> usize {
self.sections.len()
}
/// Bytes of the section vertex arena's buffers, and of the vertices
/// resident sections hold in them.
pub fn section_vertex_bytes(&self) -> [u64; 2] {
let stride = std::mem::size_of::<TerrainVertex>() as u64;
let vertices: u64 = self
.sections
.values()
.map(|s| u64::from(s.solid + s.translucent) * 4)
.sum();
[self.arena.bytes(), vertices * stride]
}
}
impl Renderer {
pub async fn new(
window: Arc<Window>,
offscreen: bool,
sprite_pixels: &[u8],
sprite_size: u32,
sprite_minimum_size: u32,
layers: u32,
sprite_mips: &[crate::mipmap::Settings],
animations: &[SpriteAnimation],
hud_atlas: (&[u8], u32, u32),
forcefield: (&[u8], u32),
panorama_faces: &panorama::Faces,
) -> Result<Self> {
let instance = wgpu::Instance::new(instance_descriptor());
// Offscreen rendering needs no surface, so it can use a GPU the
// window's display cannot present from (a headless compositor).
let surface = if offscreen {
None
} else {
Some(instance.create_surface(window.clone())?)
};
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: surface.as_ref(),
force_fallback_adapter: false,
..Default::default()
})
.await
.map_err(|e| format!("{NO_GPU_DRIVER} ({e})"))?;
let info = adapter.get_info();
log::info!(
"Horizon renderer: {} ({:?}, {:?})",
info.name,
info.backend,
info.device_type
);
crate::telemetry::set_gpu(
&info.name,
format!("{} {}", info.driver, info.driver_info)
.trim()
.to_owned(),
format!("{:?}", info.backend),
);
crate::crash::set_detail(
"Graphics Adapter",
format!(
"{} ({:?}, {:?}), driver {} {}",
info.name, info.backend, info.device_type, info.driver, info.driver_info
),
);
let limits = adapter.limits();
if limits.max_texture_array_layers < layers {
return Err(format!(
"GPU supports {} texture layers; {layers} required",
limits.max_texture_array_layers
)
.into());
}
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor {
label: Some("Horizon device"),
required_features: timing::GpuTimer::features(&adapter)
| (adapter.features() & wgpu::Features::INDIRECT_FIRST_INSTANCE),
required_limits: limits.clone(),
..Default::default()
})
.await?;
let size = window.inner_size();
let (config, present_modes) = if let Some(surface) = &surface {
let mut config = surface
.get_default_config(&adapter, size.width.max(1), size.height.max(1))
.ok_or("surface has no supported configuration")?;
let caps = surface.get_capabilities(&adapter);
// Vanilla blends and tints in gamma space: use a non-sRGB target.
config.format = caps
.formats
.iter()
.copied()
.find(|f| !f.is_srgb())
.unwrap_or(config.format);
config.view_formats = vec![config.format.remove_srgb_suffix()];
// Screenshots copy the presented frame back from the swapchain.
if caps.usages.contains(wgpu::TextureUsages::COPY_SRC) {
config.usage |= wgpu::TextureUsages::COPY_SRC;
}
config.present_mode = if caps.present_modes.contains(&wgpu::PresentMode::Mailbox) {
wgpu::PresentMode::Mailbox
} else {
wgpu::PresentMode::Fifo
};
surface.configure(&device, &config);
(config, caps.present_modes.clone())
} else {
let format = wgpu::TextureFormat::Bgra8Unorm;
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
format,
width: size.width.max(1),
height: size.height.max(1),
present_mode: wgpu::PresentMode::Immediate,
desired_maximum_frame_latency: 2,
alpha_mode: wgpu::CompositeAlphaMode::Opaque,
view_formats: vec![format],
color_space: wgpu::SurfaceColorSpace::default(),
};
(config, Vec::new())
};
let offscreen = surface
.is_none()
.then(|| Self::offscreen_target(&device, &config));
let gpu_timer = timing::GpuTimer::new(&device, &queue);
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Horizon terrain"),
source: wgpu::ShaderSource::Wgsl(include_str!("terrain.wgsl").into()),
});
let entry = |binding, visibility, ty| wgpu::BindGroupLayoutEntry {
binding,
visibility,
ty,
count: None,
};
let vf = wgpu::ShaderStages::VERTEX_FRAGMENT;
let bindings = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Horizon terrain bindings"),
entries: &[
entry(
0,
vf,
wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
),
entry(
1,
vf,
wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2Array,
multisampled: false,
},
),
entry(
1 + 1,
vf,
wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
),
entry(
3,
vf,
wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
),
entry(
4,
vf,
wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
),
],
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Horizon terrain layout"),
bind_group_layouts: &[Some(&bindings)],
..Default::default()
});
let instance_attributes = wgpu::vertex_attr_array![5=>Float32x4];
let terrain_buffers = [
Some(wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<TerrainVertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &TERRAIN_ATTRIBUTES,
}),
Some(wgpu::VertexBufferLayout {
array_stride: 16,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &instance_attributes,
}),
];
let line_attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x3];
let line_buffers = [Some(wgpu::VertexBufferLayout {
array_stride: 24,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &line_attributes,
})];
let alpha_blend = wgpu::BlendState::ALPHA_BLENDING;
let debug_line_attributes =
wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x3,2=>Unorm8x4,3=>Float32];
let debug_line_buffers = [Some(wgpu::VertexBufferLayout {
array_stride: 32,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &debug_line_attributes,
})];
let pipeline = |label: &str,
vertex: &str,
fragment: &str,
buffers: &[Option<wgpu::VertexBufferLayout<'_>>],
topology: wgpu::PrimitiveTopology,
cull: Option<wgpu::Face>,
depth_write: bool,
depth_test: bool,
blend: Option<wgpu::BlendState>| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some(vertex),
compilation_options: Default::default(),
buffers,
},
primitive: wgpu::PrimitiveState {
topology,
cull_mode: cull,
..Default::default()
},
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(depth_write),
depth_compare: Some(if depth_test {
wgpu::CompareFunction::GreaterEqual
} else {
wgpu::CompareFunction::Always
}),
stencil: Default::default(),
bias: Default::default(),
}),
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some(fragment),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: config.format.remove_srgb_suffix(),
blend,
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
})
};
let tri = wgpu::PrimitiveTopology::TriangleList;
let solid = pipeline(
"Terrain solid",
"vs_terrain",
"fs_solid",
&terrain_buffers,
tri,
Some(wgpu::Face::Back),
true,
true,
None,
);
let translucent = pipeline(
"Terrain translucent",
"vs_terrain",
"fs_translucent",
&terrain_buffers,
tri,
Some(wgpu::Face::Back),
false,
true,
Some(alpha_blend),
);
let sky = pipeline(
"Sky",
"vs_sky",
"fs_sky",
&[],
tri,
None,
false,
false,
None,
);
let dark_disc = pipeline(
"Dark disc",
"vs_sky",
"fs_dark_disc",
&[],
tri,
None,
false,
false,
Some(alpha_blend),
);
let lines = pipeline(
"Block outline",
"vs_line",
"fs_line",
&line_buffers,
wgpu::PrimitiveTopology::TriangleStrip,
None,
false,
true,
Some(alpha_blend),
);
let debug_lines = pipeline(
"Debug lines",
"vs_debug_line",
"fs_debug_line",
&debug_line_buffers,
wgpu::PrimitiveTopology::TriangleStrip,
None,
false,
true,
Some(alpha_blend),
);
let debug_lines_on_top = pipeline(
"Debug lines on top",
"vs_debug_line",
"fs_debug_line",
&debug_line_buffers,
wgpu::PrimitiveTopology::TriangleStrip,
None,
false,
false,
Some(alpha_blend),
);
let globals = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Horizon globals"),
size: std::mem::size_of::<Globals>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let hand_globals = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("First-person hand globals"),
size: std::mem::size_of::<Globals>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let crosshair_globals = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Debug crosshair globals"),
size: std::mem::size_of::<Globals>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let (mips, mip_levels) = mip_chain(sprite_pixels, sprite_size, sprite_mips, 0, layers);
let sprite_texture = device.create_texture_with_data(
&queue,
&wgpu::TextureDescriptor {
label: Some("Block sprites"),
size: wgpu::Extent3d {
width: sprite_size,
height: sprite_size,
depth_or_array_layers: layers,
},
mip_level_count: mip_levels,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
},
wgpu::util::TextureDataOrder::LayerMajor,
&mips,
);
let sprite_view = sprite_texture.create_view(&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::D2Array),
..Default::default()
});
let sprite_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("Block sprites"),
address_mode_u: wgpu::AddressMode::Repeat,
address_mode_v: wgpu::AddressMode::Repeat,
mag_filter: wgpu::FilterMode::Nearest,
min_filter: wgpu::FilterMode::Nearest,
mipmap_filter: wgpu::MipmapFilterMode::Nearest,
..Default::default()
});
let lightmap = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Lightmap"),
size: wgpu::Extent3d {
width: 16,
height: 16,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let lightmap_view = lightmap.create_view(&Default::default());
let lightmap_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("Lightmap"),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Horizon terrain resources"),
layout: &bindings,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: globals.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&sprite_view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&sprite_sampler),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::TextureView(&lightmap_view),
},
wgpu::BindGroupEntry {
binding: 4,
resource: wgpu::BindingResource::Sampler(&lightmap_sampler),
},
],
});
let crosshair_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Debug crosshair resources"),
layout: &bindings,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: crosshair_globals.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&sprite_view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&sprite_sampler),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::TextureView(&lightmap_view),
},
wgpu::BindGroupEntry {
binding: 4,
resource: wgpu::BindingResource::Sampler(&lightmap_sampler),
},
],
});
let index_quads = 1 << 16;
let indices = Self::quad_indices(&device, index_quads);
let instance_capacity = 4096;
let instances = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Section origins"),
size: instance_capacity * 16,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let outline = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Outline"),
size: 24 * MAX_OUTLINE_EDGES,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let debug_line_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Debug lines"),
size: 32 * 4096,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let depth = Self::depth(&device, &config);
let (atlas_pixels, atlas_width, atlas_height) = hud_atlas;
let atlas = device.create_texture_with_data(
&queue,
&wgpu::TextureDescriptor {
label: Some("Shared atlas"),
size: wgpu::Extent3d {
width: atlas_width,
height: atlas_height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
},
wgpu::util::TextureDataOrder::LayerMajor,
atlas_pixels,
);
let atlas_view = atlas.create_view(&Default::default());
let mut hud = HudRenderer::new(&device, config.format.remove_srgb_suffix(), &atlas_view)?;
hud.atlas_texture = Some(atlas.clone());
let entity_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Horizon entities"),
source: wgpu::ShaderSource::Wgsl(entity_shader().into()),
});
let entity_bindings = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Entity bindings"),
entries: &[
entry(
0,
vf,
wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
),
entry(
1,
vf,
wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
),
entry(
2,
vf,
wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
),
entry(
3,
vf,
wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
),
entry(
4,
vf,
wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
),
],
});
let atlas_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("Atlas"),
..Default::default()
});
let entity_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Entity resources"),
layout: &entity_bindings,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: globals.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&atlas_view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&atlas_sampler),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::TextureView(&lightmap_view),
},
wgpu::BindGroupEntry {
binding: 4,
resource: wgpu::BindingResource::Sampler(&lightmap_sampler),
},
],
});
let hand_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("First-person hand resources"),
layout: &entity_bindings,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: hand_globals.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&atlas_view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&atlas_sampler),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::TextureView(&lightmap_view),
},
wgpu::BindGroupEntry {
binding: 4,
resource: wgpu::BindingResource::Sampler(&lightmap_sampler),
},
],
});
let entity_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Entity layout"),
bind_group_layouts: &[Some(&entity_bindings)],
..Default::default()
});
let cloud_bindings = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Cloud bindings"),
entries: &[entry(
0,
wgpu::ShaderStages::VERTEX,
wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
)],
});
let cloud_uniform = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Cloud transforms and colors"),
size: std::mem::size_of::<crate::clouds::Uniform>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let cloud_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Cloud resources"),
layout: &cloud_bindings,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: cloud_uniform.as_entire_binding(),
}],
});
let cloud_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Cloud layout"),
bind_group_layouts: &[Some(&entity_bindings), Some(&cloud_bindings)],
..Default::default()
});
let cloud_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Cloud vertices"),
size: 4 * std::mem::size_of::<Vertex>() as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let entity_attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Unorm8x4,4=>Uint8x4,5=>Snorm8x4];
let entity_vertex = [Some(wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<Vertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &entity_attributes,
})];
let entity_pipeline = |label, cull_mode, depth_write, compare, bias, blend, clouds| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(if clouds {
&cloud_layout
} else {
&entity_layout
}),
vertex: wgpu::VertexState {
module: &entity_shader,
entry_point: Some(if clouds { "vs_cloud" } else { "vs_entity" }),
compilation_options: Default::default(),
buffers: &entity_vertex,
},
primitive: wgpu::PrimitiveState {
cull_mode,
..Default::default()
},
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(depth_write),
depth_compare: Some(compare),
stencil: Default::default(),
bias,
}),
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &entity_shader,
entry_point: Some("fs_entity"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: config.format.remove_srgb_suffix(),
blend: Some(blend),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
})
};
let crumbling_pipeline = entity_pipeline(
"Breaking cracks",
Some(wgpu::Face::Back),
false,
wgpu::CompareFunction::GreaterEqual,
wgpu::DepthBiasState {
constant: 10,
slope_scale: 1.0,
clamp: 0.0,
},
CRUMBLING_BLEND,
false,
);
let cloud_pipeline = entity_pipeline(
"Clouds",
Some(wgpu::Face::Back),
true,
wgpu::CompareFunction::GreaterEqual,
Default::default(),
alpha_blend,
true,
);
// RenderPipelines.TEXT_SEE_THROUGH: translucent, no depth test or writes.
let see_through_pipeline = entity_pipeline(
"See-through text",
None,
false,
wgpu::CompareFunction::Always,
Default::default(),
alpha_blend,
false,
);
let entity_pipeline = entity_pipeline(
"Entities",
None,
true,
wgpu::CompareFunction::GreaterEqual,
Default::default(),
alpha_blend,
false,
);
// BlendFunction.LIGHTNING: src alpha, one; no depth writes.
let additive_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Additive entities"),
layout: Some(&entity_layout),
vertex: wgpu::VertexState {
module: &entity_shader,
entry_point: Some("vs_entity"),
compilation_options: Default::default(),
buffers: &entity_vertex,
},
primitive: wgpu::PrimitiveState {
cull_mode: None,
..Default::default()
},
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(false),
depth_compare: Some(wgpu::CompareFunction::GreaterEqual),
stencil: Default::default(),
bias: Default::default(),
}),
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &entity_shader,
entry_point: Some("fs_celestial"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: config.format.remove_srgb_suffix(),
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::SrcAlpha,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::SrcAlpha,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
}),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
let celestial_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Celestial bodies"),
layout: Some(&entity_layout),
vertex: wgpu::VertexState {
module: &entity_shader,
entry_point: Some("vs_entity"),
compilation_options: Default::default(),
buffers: &entity_vertex,
},
primitive: wgpu::PrimitiveState {
cull_mode: None,
..Default::default()
},
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(false),
depth_compare: Some(wgpu::CompareFunction::Always),
stencil: Default::default(),
bias: Default::default(),
}),
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &entity_shader,
entry_point: Some("fs_celestial"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: config.format.remove_srgb_suffix(),
// RenderPipelines.CELESTIAL: additive (src alpha, one).
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::SrcAlpha,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent::OVER,
}),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
// WorldBorderRenderer: misc/forcefield.png as a MipmappedTexture
// (repeat, linear minification with mipmaps, nearest magnification).
let (forcefield_pixels, forcefield_size) = forcefield;
let (forcefield_mips, forcefield_levels) =
mip_chain(forcefield_pixels, forcefield_size, &[], 0, 1);
let forcefield_texture = device.create_texture_with_data(
&queue,
&wgpu::TextureDescriptor {
label: Some("Forcefield"),
size: wgpu::Extent3d {
width: forcefield_size,
height: forcefield_size,
depth_or_array_layers: 1,
},
mip_level_count: forcefield_levels,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
},
wgpu::util::TextureDataOrder::LayerMajor,
&forcefield_mips,
);
let forcefield_view = forcefield_texture.create_view(&Default::default());
let forcefield_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("Forcefield"),
address_mode_u: wgpu::AddressMode::Repeat,
address_mode_v: wgpu::AddressMode::Repeat,
min_filter: wgpu::FilterMode::Linear,
mag_filter: wgpu::FilterMode::Nearest,
mipmap_filter: wgpu::MipmapFilterMode::Linear,
..Default::default()
});
let border_uniform = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("World border"),
size: std::mem::size_of::<BorderUniform>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let border_vertices = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("World border vertices"),
size: 16 * std::mem::size_of::<crate::border_render::BorderVertex>() as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let border_bindings = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("World border bindings"),
entries: &[
entry(
0,
vf,
wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
),
entry(
1,
vf,
wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
),
entry(
2,
vf,
wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
),
entry(
3,
vf,
wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
),
],
});
let border_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("World border resources"),
layout: &border_bindings,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: globals.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&forcefield_view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&forcefield_sampler),
},
wgpu::BindGroupEntry {
binding: 3,
resource: border_uniform.as_entire_binding(),
},
],
});
let border_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("World border layout"),
bind_group_layouts: &[Some(&border_bindings)],
..Default::default()
});
let border_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Horizon world border"),
source: wgpu::ShaderSource::Wgsl(include_str!("border.wgsl").into()),
});
let border_attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2];
// RenderPipelines.WORLD_BORDER: BlendFunction.OVERLAY, no culling,
// depth writes with a polygon offset of 3 towards the camera.
let border_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("World border"),
layout: Some(&border_layout),
vertex: wgpu::VertexState {
module: &border_shader,
entry_point: Some("vs_border"),
compilation_options: Default::default(),
buffers: &[Some(wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<crate::border_render::BorderVertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &border_attributes,
})],
},
primitive: wgpu::PrimitiveState {
cull_mode: None,
..Default::default()
},
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(true),
depth_compare: Some(wgpu::CompareFunction::GreaterEqual),
stencil: Default::default(),
bias: wgpu::DepthBiasState {
constant: 3,
slope_scale: 3.0,
clamp: 0.0,
},
}),
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &border_shader,
entry_point: Some("fs_border"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: config.format.remove_srgb_suffix(),
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::SrcAlpha,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::Zero,
operation: wgpu::BlendOperation::Add,
},
}),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
let screen_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Horizon screen effects"),
source: wgpu::ShaderSource::Wgsl(include_str!("screen.wgsl").into()),
});
let screen_attributes =
wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Float32x4,3=>Float32x4];
let screen_vertex = [Some(wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<crate::screen_effects::ScreenVertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &screen_attributes,
})];
let vignette_blend = wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Zero,
dst_factor: wgpu::BlendFactor::OneMinusSrc,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Zero,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
};
let screen_pipelines =
[("fs_screen", alpha_blend), ("fs_vignette", vignette_blend)].map(|(entry, blend)| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Screen effects"),
layout: Some(&entity_layout),
vertex: wgpu::VertexState {
module: &screen_shader,
entry_point: Some("vs_screen"),
compilation_options: Default::default(),
buffers: &screen_vertex,
},
primitive: wgpu::PrimitiveState {
cull_mode: None,
..Default::default()
},
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &screen_shader,
entry_point: Some(entry),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: config.format.remove_srgb_suffix(),
blend: Some(blend),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
})
});
let screen_capacity = 64;
let screen_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Screen effect vertices"),
size: screen_capacity
* std::mem::size_of::<crate::screen_effects::ScreenVertex>() as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let celestial_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Celestial vertices"),
size: 2048 * 4 * std::mem::size_of::<Vertex>() as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let entity_capacity = 1 << 14;
let entity_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Entity vertices"),
size: entity_capacity * std::mem::size_of::<Vertex>() as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let arena = arena::Arena::new(
&device,
std::mem::size_of::<TerrainVertex>() as u64,
1 << 20,
);
let indirect = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Section draws"),
size: 1024 * 20,
usage: wgpu::BufferUsages::INDIRECT | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let multi_draw = device
.features()
.contains(wgpu::Features::INDIRECT_FIRST_INSTANCE);
let world_post = world_post::Post::new(&device, config.format.remove_srgb_suffix());
let uploads = upload::Uploads::new(&device);
let panorama = panorama::Panorama::new(
&device,
&queue,
config.format.remove_srgb_suffix(),
panorama_faces,
);
Ok(Self {
instance,
surface,
offscreen,
in_flight: std::collections::VecDeque::new(),
gpu_timer,
gpu_times: Vec::new(),
lightmap_pixels: [0; 16 * 16 * 4],
last_wait: std::time::Duration::ZERO,
last_encode: std::time::Duration::ZERO,
window,
device,
queue,
config,
solid,
translucent,
sky,
dark_disc,
lines,
debug_lines,
debug_lines_on_top,
debug_line_buffer,
debug_line_capacity: 4096,
crosshair_group,
crosshair_globals,
entity_pipeline,
crumbling_pipeline,
cloud_pipeline,
cloud_mesh: Default::default(),
cloud_buffer,
cloud_capacity: 4,
cloud_uniform,
cloud_group,
additive_pipeline,
see_through_pipeline,
celestial_pipeline,
celestial_buffer,
panorama,
border_pipeline,
border_group,
border_uniform,
border_vertices,
screen_pipelines,
screen_buffer,
screen_capacity,
entity_group,
hand_group,
hand_globals,
entity_buffer,
entity_capacity,
entity_batch: EntityBatch::default(),
group,
globals,
lightmap,
sprite_texture,
mip_levels,
mipmaps: mip_levels - 1,
terrain_layout: bindings,
sprite_sampler,
lightmap_view,
lightmap_sampler,
animations: AnimatedSprites::new(animations, sprite_size, sprite_mips),
uploads,
lightmap_uploaded: false,
sprite_minimum_size,
indices,
index_quads,
instances,
instance_capacity,
outline,
depth,
sections: resident::Resident::default(),
arena,
indirect,
indirect_capacity: 1024,
multi_draw,
visible: Vec::new(),
origins: Vec::new(),
draws: Vec::new(),
draw_pages: Vec::new(),
block_entities: HashMap::new(),
occlusion: occlusion::Occlusion::new(crate::chunk::HEIGHT / 16),
world_post,
pack: None,
hud,
post: None,
menu_blur: None,
info,
suspended: size.width == 0 || size.height == 0,
drawn_sections: 0,
uploaded_bytes: 0,
started: Instant::now(),
screenshot: None,
screenshot_result: None,
gamma: 0.5,
animated_textures: true,
present_modes,
})
}
fn quad_indices(device: &wgpu::Device, quads: u32) -> wgpu::Buffer {
let indices: Vec<u32> = (0..quads)
.flat_map(|q| {
let b = q * 4;
[b, b + 1, b + 2, b, b + 2, b + 3]
})
.collect();
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Quad indices"),
contents: bytemuck::cast_slice(&indices),
usage: wgpu::BufferUsages::INDEX,
})
}
fn offscreen_target(
device: &wgpu::Device,
config: &wgpu::SurfaceConfiguration,
) -> wgpu::Texture {
device.create_texture(&wgpu::TextureDescriptor {
label: Some("Offscreen frame"),
size: wgpu::Extent3d {
width: config.width,
height: config.height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: config.format,
usage: config.usage,
view_formats: &config.view_formats,
})
}
/// Rendering to a texture instead of the window (`--offscreen`).
pub fn is_offscreen(&self) -> bool {
self.surface.is_none()
}
fn depth(device: &wgpu::Device, config: &wgpu::SurfaceConfiguration) -> wgpu::TextureView {
device
.create_texture(&wgpu::TextureDescriptor {
label: Some("Horizon depth"),
size: wgpu::Extent3d {
width: config.width,
height: config.height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Depth32Float,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
})
.create_view(&Default::default())
}
/// VSync on: tear-free presentation (Mailbox, else Fifo); off: Immediate when available.
/// VSync, unless Horizon's present-mode setting names a supported mode.
pub fn set_present_mode(&mut self, vsync: bool, mode: crate::graphics::PresentMode) {
use crate::graphics::PresentMode as P;
let wanted = match mode {
P::Auto => None,
P::Fifo => Some(wgpu::PresentMode::Fifo),
P::Mailbox => Some(wgpu::PresentMode::Mailbox),
P::Immediate => Some(wgpu::PresentMode::Immediate),
};
match wanted.filter(|m| self.present_modes.contains(m)) {
Some(m) => {
if self.config.present_mode != m
&& let Some(surface) = &self.surface
{
self.config.present_mode = m;
surface.configure(&self.device, &self.config);
}
}
None => self.set_vsync(vsync),
}
}
pub fn set_vsync(&mut self, vsync: bool) {
use crate::window::{PresentMode, vsync_present_mode};
let supported: Vec<PresentMode> = self
.present_modes
.iter()
.filter_map(|m| match m {
wgpu::PresentMode::Fifo => Some(PresentMode::Fifo),
wgpu::PresentMode::Mailbox => Some(PresentMode::Mailbox),
wgpu::PresentMode::Immediate => Some(PresentMode::Immediate),
_ => None,
})
.collect();
// GpuSurface.PresentMode.getSupportedVsyncMode.
let mode = match vsync_present_mode(&supported, vsync) {
Some(PresentMode::Mailbox) => wgpu::PresentMode::Mailbox,
Some(PresentMode::Immediate) => wgpu::PresentMode::Immediate,
_ => wgpu::PresentMode::Fifo,
};
if self.config.present_mode != mode
&& let Some(surface) = &self.surface
{
self.config.present_mode = mode;
surface.configure(&self.device, &self.config);
}
}
pub fn resize(&mut self, width: u32, height: u32) {
self.suspended = width == 0 || height == 0;
if self.suspended {
return;
}
self.config.width = width;
self.config.height = height;
if let Some(surface) = &self.surface {
surface.configure(&self.device, &self.config);
} else {
self.offscreen = Some(Self::offscreen_target(&self.device, &self.config));
}
self.depth = Self::depth(&self.device, &self.config);
}
pub fn section_count(&self) -> usize {
self.sections.len()
}
pub fn has_section(&self, key: SectionKey) -> bool {
self.sections.contains(key)
}
pub fn upload(&mut self, key: SectionKey, mesh: &SectionMesh) {
self.occlusion.set(key, mesh.visibility);
if mesh.block_entities.is_empty() {
self.block_entities.remove(&key);
} else {
self.block_entities.insert(key, mesh.block_entities.clone());
}
let solid = (mesh.solid.len() / 4) as u32;
let translucent = (mesh.translucent.len() / 4) as u32;
self.release_section(key);
if solid + translucent == 0 {
return;
}
let max = solid.max(translucent);
if max > self.index_quads {
self.index_quads = max.next_power_of_two();
self.indices = Self::quad_indices(&self.device, self.index_quads);
}
let vertices = (mesh.solid.len() + mesh.translucent.len()) as u64;
let (page, start) = self.arena.alloc(&self.device, &self.queue, vertices);
let stride = std::mem::size_of::<TerrainVertex>() as u64;
for (offset, part) in [(0, &mesh.solid), (mesh.solid.len(), &mesh.translucent)] {
if !part.is_empty() {
let bytes: &[u8] = bytemuck::cast_slice(part);
self.uploaded_bytes += bytes.len() as u64;
self.queue.write_buffer(
self.arena.buffer(page),
(start + offset as u64) * stride,
bytes,
);
}
}
self.sections.insert(
key,
SectionGpu {
page,
start,
solid,
translucent,
faces: mesh.faces,
},
);
}
/// Draws `count` section draws from `first` with the arena and section
/// origins bound: one indirect multi-draw, or a loop without it.
/// Consecutive draws in one arena page share a vertex buffer binding,
/// keeping the list's order (translucent sections go back to front).
fn draw_sections(&self, pass: &mut wgpu::RenderPass<'_>, first: u32, count: u32) {
let (mut i, end) = (first as usize, (first + count) as usize);
while i < end {
let page = self.draw_pages[i];
let run = self.draw_pages[i..end]
.iter()
.take_while(|&&p| p == page)
.count();
pass.set_vertex_buffer(0, self.arena.buffer(page).slice(..));
if self.multi_draw {
pass.multi_draw_indexed_indirect(&self.indirect, i as u64 * 20, run as u32);
} else {
for d in &self.draws[i..i + run] {
pass.draw_indexed(0..d[0], d[3] as i32, d[4]..d[4] + 1);
}
}
i += run;
}
}
fn release_section(&mut self, key: SectionKey) {
if let Some(s) = self.sections.remove(key) {
self.arena
.release(s.page, s.start, u64::from(s.solid + s.translucent) * 4);
}
}
/// Block-entity blocks of every meshed section (see `SectionMesh::block_entities`).
pub fn block_entities(&self) -> impl Iterator<Item = &([i32; 3], u32)> {
self.block_entities.values().flatten()
}
pub fn clear_sections(&mut self) {
self.block_entities.clear();
self.sections.clear();
self.arena.clear();
self.occlusion.clear();
}
pub fn remove(&mut self, key: SectionKey) {
self.block_entities.remove(&key);
self.occlusion.remove(key);
self.release_section(key);
}
/// Run `pack`'s stages over the world from now on (`None`: no pack, the
/// vanilla frame). On error the previous pack stays.
pub fn set_shader_pack(&mut self, pack: Option<&crate::shader_pack::ShaderPack>) -> Result<()> {
let format = self.config.format.remove_srgb_suffix();
self.pack = match pack {
Some(pack) => Some(match &pack.java {
Some(java) => Pack::Java(java_stages::JavaStages::new(
&self.device,
&self.queue,
format,
&pack.id,
java,
)?),
None => Pack::Horizon(pack_stages::PackStages::new(&self.device, format, pack)?),
}),
None => None,
};
Ok(())
}
/// The folder name of the pack `set_shader_pack` gave.
pub fn shader_pack_id(&self) -> Option<&str> {
self.pack.as_ref().map(|p| match p {
Pack::Horizon(p) => p.id.as_str(),
Pack::Java(p) => p.id.as_str(),
})
}
/// Horizon's resolution scale (world pixels per window pixel) and FXAA.
pub fn set_world_post(&mut self, scale: f32, antialias: bool) {
self.world_post.scale = scale.clamp(0.25, 2.0);
self.world_post.antialias = antialias;
}
/// The Mipmap Levels option: block textures sample at most `levels`
/// reduced copies (0: none).
pub fn set_mipmap_levels(&mut self, levels: u32) {
let levels = sprite_mipmap_limit(
levels,
self.sprite_texture.width(),
self.sprite_minimum_size,
self.mip_levels,
);
if levels == self.mipmaps {
return;
}
self.mipmaps = levels;
let sprite_view = self
.sprite_texture
.create_view(&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::D2Array),
mip_level_count: Some(levels + 1),
..Default::default()
});
self.group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Horizon terrain resources"),
layout: &self.terrain_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: self.globals.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&sprite_view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&self.sprite_sampler),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::TextureView(&self.lightmap_view),
},
wgpu::BindGroupEntry {
binding: 4,
resource: wgpu::BindingResource::Sampler(&self.lightmap_sampler),
},
],
});
}
pub fn view_projection(&self, frame: &Frame) -> Mat4 {
self.projection(
frame.fov_degrees,
frame.yaw,
frame.pitch,
frame.bob,
frame.depth_far,
)
}
/// The view frustum `render` will cull with, for culling geometry built
/// before the frame (entities, block entities) the same way.
pub fn camera_frustum(
&self,
fov_degrees: f32,
yaw: f32,
pitch: f32,
bob: Mat4,
depth_far: f32,
) -> Frustum {
Frustum {
planes: frustum(self.projection(fov_degrees, yaw, pitch, bob, depth_far)),
}
}
fn projection(&self, fov_degrees: f32, yaw: f32, pitch: f32, bob: Mat4, far: f32) -> Mat4 {
let aspect = self.config.width as f32 / self.config.height.max(1) as f32;
world_projection(fov_degrees, aspect, far) * bob * crate::camera::view_matrix(yaw, pitch)
}
fn update_lightmap(
&mut self,
encoder: &mut wgpu::CommandEncoder,
sky: &Sky,
darkness: f32,
gamma: f32,
night_vision: f32,
flicker: f32,
) {
// lightmap.fsh: per (block, sky) level.
let brightness = |level: f32| level / (4.0 - 3.0 * level);
let mut pixels = [0u8; 16 * 16 * 4];
for s in 0..16 {
for b in 0..16 {
let block_level = b as f32 / 15.0;
let sky_level = s as f32 / 15.0;
let block_brightness = brightness(block_level) * (1.4 + flicker);
let sky_brightness = brightness(sky_level) * sky.sky_light_factor;
// NightVisionColor defaults to 0x999999.
let mut color =
Vec3::from(sky.ambient_light_color).max(Vec3::splat(0.6 * night_vision));
color += Vec3::from(sky.sky_light_color) * sky_brightness;
let parabolic = (2.0 * block_level - 1.0).powi(2);
let block_color = Vec3::from(sky.block_light_tint).lerp(Vec3::ONE, 0.9 * parabolic);
color += block_color * block_brightness;
color -= Vec3::splat(darkness);
color = color.clamp(Vec3::ZERO, Vec3::ONE);
let max = color.max_element().max(1e-6);
let inverted = 1.0 - max;
let scaled = 1.0 - inverted.powi(4);
let not_gamma = color * (scaled / max);
color = color.lerp(not_gamma, gamma);
let i = (s * 16 + b) * 4;
pixels[i] = (color.x * 255.0) as u8;
pixels[i + 1] = (color.y * 255.0) as u8;
pixels[i + 2] = (color.z * 255.0) as u8;
pixels[i + 3] = 255;
}
}
// The lightmap changes with the time of day, flicker and effects,
// not every frame: upload only what differs from the texture.
if pixels == self.lightmap_pixels && self.lightmap_uploaded {
return;
}
self.uploads.texture(
encoder,
wgpu::TexelCopyTextureInfo {
texture: &self.lightmap,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
16,
16,
&pixels,
);
self.lightmap_pixels = pixels;
self.lightmap_uploaded = true;
}
fn animate(&mut self, encoder: &mut wgpu::CommandEncoder, tick: u64) {
animate_sprites(
&mut self.animations,
tick,
self.mip_levels,
|layer, level, size, pixels| {
self.uploads.texture(
encoder,
wgpu::TexelCopyTextureInfo {
texture: &self.sprite_texture,
mip_level: level,
origin: wgpu::Origin3d {
x: 0,
y: 0,
z: layer,
},
aspect: wgpu::TextureAspect::All,
},
size,
size,
pixels,
);
},
);
}
pub fn render(&mut self, frame: &Frame) -> Result<bool> {
if self.suspended {
return Ok(false);
}
let started = Instant::now();
let acquire = Instant::now();
let acquired = self.surface.as_ref().map(|s| s.get_current_texture());
self.last_wait = acquire.elapsed();
let (surface_frame, reconfigure) = match acquired {
None => (None, false),
Some(wgpu::CurrentSurfaceTexture::Success(f)) => (Some(f), false),
Some(wgpu::CurrentSurfaceTexture::Suboptimal(f)) => (Some(f), true),
Some(wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded) => {
return Ok(false);
}
Some(wgpu::CurrentSurfaceTexture::Outdated) => {
if let Some(surface) = &self.surface {
surface.configure(&self.device, &self.config);
}
return Ok(false);
}
Some(wgpu::CurrentSurfaceTexture::Lost) => {
let surface = self.instance.create_surface(self.window.clone())?;
surface.configure(&self.device, &self.config);
self.surface = Some(surface);
return Ok(false);
}
Some(wgpu::CurrentSurfaceTexture::Validation) => {
return Err("surface acquisition failed validation".into());
}
};
let target_texture = match &surface_frame {
Some(f) => f.texture.clone(),
None => self.offscreen.clone().ok_or("no offscreen target")?,
};
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Horizon frame"),
});
if self.animated_textures {
self.animate(&mut encoder, frame.ticks);
self.hud.animate_fire(&self.queue, frame.ticks);
}
self.update_lightmap(
&mut encoder,
&frame.sky,
frame.darkness.1,
(self.gamma - frame.darkness.0).max(0.0),
frame.night_vision,
frame.block_flicker,
);
let view_proj = self.view_projection(frame);
if frame.title {
self.panorama.prepare(
&self.queue,
self.config.width,
self.config.height,
frame.yaw,
frame.pitch,
);
}
let aspect = self.config.width as f32 / self.config.height.max(1) as f32;
let view = crate::camera::view_matrix(frame.yaw, frame.pitch);
let sun_angle = frame.sky.sun_angle.to_radians();
// Celestial bodies rotate around the X axis; angle 0 = noon.
let sun = Vec3::new(0.0, sun_angle.cos(), -sun_angle.sin());
let (fog_color, fog) = if let Some(f) = frame.fog {
(
f.color,
[
f.environmental_start,
f.environmental_end,
f.render_distance_start,
f.render_distance_end,
],
)
} else if frame.underwater {
(
[
frame.water_fog[0],
frame.water_fog[1],
frame.water_fog[2],
1.0,
],
[-8.0, 96.0, -8.0, 96.0],
)
} else {
let d = frame.distance;
(
[
frame.sky.fog_color[0],
frame.sky.fog_color[1],
frame.sky.fog_color[2],
1.0,
],
// FogRenderer: render-distance fog starts at max(d - 16, 0)... d.
{
let (start, end) = frame.environment_fog.unwrap_or((f32::MAX, f32::MAX));
[start, end, (d - d.min(64.0) * 0.25).max(0.0), d]
},
)
};
let globals = Globals {
view_proj: view_proj.to_cols_array_2d(),
fog_color,
fog,
sky_color: [
frame.sky.sky_color[0],
frame.sky.sky_color[1],
frame.sky.sky_color[2],
1.0,
],
misc: [
1.0 - frame.sky.sky_light_factor,
frame.game_time,
aspect,
(frame.fov_degrees.to_radians() / 2.0).tan(),
],
inverse_view: view.inverse().to_cols_array_2d(),
sunrise: frame.sky.sunrise_color,
sun: [sun.x, sun.y, sun.z, frame.sky.star_brightness],
fog_ends: [
frame.fog.map_or(frame.distance.min(512.0), |f| f.sky_end),
frame.fog.map_or(2048.0, |f| f.cloud_end),
if frame.dark_disc { 1.0 } else { 0.0 },
0.0,
],
end_portal_sprites: frame.end_portal_sprites,
crumbling_sprite: frame.crumbling_sprite,
time: [
frame.shader_game_time,
f32::from(frame.nether_lighting),
0.0,
0.0,
],
outline_params: outline_params(self.config.width, self.config.height),
};
self.uploads
.buffer(&mut encoder, &self.globals, 0, bytemuck::bytes_of(&globals));
let pack_uniform = shader_pack_uniform(
frame,
view,
world_projection(frame.fov_degrees, aspect, frame.depth_far) * frame.bob,
sun,
fog_color,
globals.fog,
globals.fog_ends,
);
// GameRenderer.render3dHud: the hand's projection at hudFov, with the
// bob in its pose rather than the projection (same product).
let hand_projection = Mat4::from_cols_array(&crate::camera::hand_projection(
frame.hand_fov_degrees,
self.config.width as f32,
self.config.height.max(1) as f32,
frame.depth_far,
));
let hand_globals = Globals {
view_proj: (hand_projection * frame.bob * view).to_cols_array_2d(),
..globals
};
self.uploads.buffer(
&mut encoder,
&self.hand_globals,
0,
bytemuck::bytes_of(&hand_globals),
);
// GameRenderer.render3dHud: DebugCrosshairRenderer draws with the
// hand's projection but no bob, and FogMode.NONE (no fog colour).
let crosshair_globals = Globals {
view_proj: (hand_projection * view).to_cols_array_2d(),
fog_color: [0.0; 4],
..globals
};
self.uploads.buffer(
&mut encoder,
&self.crosshair_globals,
0,
bytemuck::bytes_of(&crosshair_globals),
);
// Frustum culling and camera-relative origins.
let view = Frustum {
planes: frustum(view_proj),
};
let camera = frame.camera;
let camera_section = (
(camera.x.floor() as i32) >> 4,
(camera.y.floor() as i32 - crate::chunk::MIN_Y) >> 4,
(camera.z.floor() as i32) >> 4,
);
let culling = !frame.title && frame.cave_culling;
if culling {
let radius = (frame.distance / 16.0) as i32 + 2;
self.occlusion.update(camera_section, radius);
}
let reachable = &self.occlusion;
let mut visible = std::mem::take(&mut self.visible);
visible.clear();
self.sections.visible(
camera,
frame.distance,
&view,
|k| !culling || reachable.contains(k),
&mut visible,
);
self.drawn_sections = visible.len();
if visible.len() as u64 > self.instance_capacity {
self.instance_capacity = (visible.len() as u64).next_power_of_two();
self.instances = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Section origins"),
size: self.instance_capacity * 16,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
}
self.origins.clear();
self.origins.extend(
visible
.iter()
.map(|v| [v.origin[0], v.origin[1], v.origin[2], 0.0]),
);
if !self.origins.is_empty() {
self.uploads.buffer(
&mut encoder,
&self.instances,
0,
bytemuck::cast_slice(&self.origins),
);
}
if frame.title {
visible.clear();
}
// Solid sections front to back, then translucent ones back to front,
// as one list of indirect draws over the section arena.
self.draws.clear();
self.draw_pages.clear();
// The eye, camera-relative: view bobbing moves it off the camera.
let eye = (frame.bob * crate::camera::view_matrix(frame.yaw, frame.pitch))
.inverse()
.transform_point3(Vec3::ZERO);
for (i, v) in visible.iter().enumerate() {
let s = self.sections.get(v.slot);
// Only the solid groups that can face the eye.
s.faces.ranges(eye - Vec3::from(v.origin), |first, quads| {
let first = s.start + u64::from(first) * 4;
self.draws.push([quads * 6, 1, 0, first as u32, i as u32]);
self.draw_pages.push(s.page);
});
}
let solid_draws = self.draws.len() as u32;
for (i, v) in visible.iter().enumerate().rev() {
let s = self.sections.get(v.slot);
if s.translucent > 0 {
let first = s.start + u64::from(s.solid) * 4;
self.draws
.push([s.translucent * 6, 1, 0, first as u32, i as u32]);
self.draw_pages.push(s.page);
}
}
let translucent_draws = self.draws.len() as u32 - solid_draws;
if self.multi_draw && !self.draws.is_empty() {
if self.draws.len() as u64 > self.indirect_capacity {
self.indirect_capacity = (self.draws.len() as u64).next_power_of_two();
self.indirect = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Section draws"),
size: self.indirect_capacity * 20,
usage: wgpu::BufferUsages::INDIRECT | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
}
self.uploads.buffer(
&mut encoder,
&self.indirect,
0,
bytemuck::cast_slice(&self.draws),
);
}
let debug_depth = frame.debug_lines.len() as u32;
let debug_top = frame.debug_lines_on_top.len() as u32;
let crosshair = frame.debug_crosshair.len() as u32;
if debug_depth + debug_top + crosshair > 0 {
let needed = u64::from(debug_depth + debug_top + crosshair);
if needed > self.debug_line_capacity {
self.debug_line_capacity = needed.next_power_of_two();
self.debug_line_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Debug lines"),
size: 32 * self.debug_line_capacity,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
}
let all: Vec<[f32; 8]> = frame
.debug_lines
.iter()
.chain(frame.debug_lines_on_top)
.chain(frame.debug_crosshair)
.copied()
.collect();
self.uploads.buffer(
&mut encoder,
&self.debug_line_buffer,
0,
bytemuck::cast_slice(&all),
);
}
let outline_edges = frame.outline.len().min(MAX_OUTLINE_EDGES as usize);
if outline_edges > 0 {
let lines = outline_vertices(&frame.outline[..outline_edges], camera);
self.uploads
.buffer(&mut encoder, &self.outline, 0, bytemuck::cast_slice(&lines));
}
let [entity_quads, crumbling_quads, translucent_crumbling_quads] =
self.entity_batch.update(
frame.entities,
frame.additive,
frame.hand,
frame.see_through,
);
let world_quads = entity_quads + crumbling_quads + translucent_crumbling_quads;
let cloud_quads = if let Some(input) = &frame.clouds {
let (rebuilt, uniform) =
crate::spans::time("clouds", || self.cloud_mesh.prepare(input));
let vertices = self.cloud_mesh.vertices.len() as u64;
if rebuilt && vertices > 0 {
if vertices > self.cloud_capacity {
self.cloud_capacity = vertices.next_power_of_two();
self.cloud_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Cloud vertices"),
size: self.cloud_capacity * std::mem::size_of::<Vertex>() as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
}
self.uploads.buffer(
&mut encoder,
&self.cloud_buffer,
0,
bytemuck::cast_slice(&self.cloud_mesh.vertices),
);
}
self.uploads.buffer(
&mut encoder,
&self.cloud_uniform,
0,
bytemuck::bytes_of(&uniform),
);
(vertices / 4) as u32
} else {
0
};
let all_entities = &self.entity_batch.combined;
let hand_quads = (frame.hand.len() / 4) as u32;
let additive_quads = (frame.additive.len() / 4) as u32;
let see_through_quads = (frame.see_through.len() / 4) as u32;
let entity_vertices = all_entities.len() as u64;
if entity_vertices > self.entity_capacity {
self.entity_capacity = entity_vertices.next_power_of_two();
self.entity_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Entity vertices"),
size: self.entity_capacity * std::mem::size_of::<Vertex>() as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
}
if entity_vertices > 0 {
self.uploads.buffer(
&mut encoder,
&self.entity_buffer,
0,
bytemuck::cast_slice(all_entities),
);
}
let celestial_vertices = frame.celestial.len().min(2048 * 4);
if celestial_vertices > 0 {
self.uploads.buffer(
&mut encoder,
&self.celestial_buffer,
0,
bytemuck::cast_slice(&frame.celestial[..celestial_vertices]),
);
}
let max_quads =
(world_quads + additive_quads + hand_quads + see_through_quads).max(cloud_quads);
if max_quads > self.index_quads {
self.index_quads = max_quads.next_power_of_two();
self.indices = Self::quad_indices(&self.device, self.index_quads);
}
if let Some(b) = &frame.border {
if b.rebuilt {
self.uploads.buffer(
&mut encoder,
&self.border_vertices,
0,
bytemuck::cast_slice(&b.vertices),
);
}
let t = &b.transforms;
let uniform = BorderUniform {
color: t.color,
offset: [
t.model_offset[0],
t.model_offset[1],
t.model_offset[2],
t.texture_offset,
],
};
self.uploads.buffer(
&mut encoder,
&self.border_uniform,
0,
bytemuck::bytes_of(&uniform),
);
}
let view_target = target_texture.create_view(&wgpu::TextureViewDescriptor {
format: Some(self.config.format.remove_srgb_suffix()),
..Default::default()
});
if let Some(timer) = &mut self.gpu_timer {
timer.begin(&mut encoder);
}
// The world's targets: the screen, or the scaled target of `post`.
let pack = self.pack.is_some() && !frame.title;
let scaled =
self.world_post
.prepare(&self.device, [self.config.width, self.config.height], pack);
let (world_view, world_depth) = match &scaled {
Some((color, depth)) => (color, depth),
None => (&view_target, &self.depth),
};
{
let attachments = [Some(wgpu::RenderPassColorAttachment {
view: world_view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(
if frame.title || (frame.end_sky && !frame.underwater) {
wgpu::Color::BLACK
} else {
wgpu::Color {
r: f64::from(fog_color[0]),
g: f64::from(fog_color[1]),
b: f64::from(fog_color[2]),
a: 1.0,
}
},
),
store: wgpu::StoreOp::Store,
},
})];
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Horizon world"),
color_attachments: &attachments,
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: world_depth,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(0.0),
// A shader pack reads the world's depth.
store: if pack {
wgpu::StoreOp::Store
} else {
wgpu::StoreOp::Discard
},
}),
stencil_ops: None,
}),
..Default::default()
});
pass.set_bind_group(0, &self.group, &[]);
// LevelRenderer: no sky inside lava or powder snow (sky fog ends within 2 blocks).
let sky_visible = match frame.fog {
Some(f) => f.sky_end > 2.0,
None => !frame.underwater,
};
if frame.title || (sky_visible && (frame.skybox || frame.end_sky)) {
if !frame.title && frame.skybox {
pass.set_pipeline(&self.sky);
pass.draw(0..3, 0..1);
}
if frame.title {
self.panorama.draw(&mut pass);
pass.set_bind_group(0, &self.group, &[]);
} else if celestial_vertices > 0 {
pass.set_pipeline(&self.celestial_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
pass.set_vertex_buffer(0, self.celestial_buffer.slice(..));
pass.draw_indexed(0..(celestial_vertices as u32 / 4) * 6, 0, 0..1);
pass.set_bind_group(0, &self.group, &[]);
}
if !frame.title && frame.dark_disc {
pass.set_pipeline(&self.dark_disc);
pass.draw(0..3, 0..1);
}
}
pass.set_pipeline(&self.solid);
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
pass.set_vertex_buffer(1, self.instances.slice(..));
self.draw_sections(&mut pass, 0, solid_draws);
if entity_quads > 0 {
pass.set_pipeline(&self.entity_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
pass.draw_indexed(0..entity_quads * 6, 0, 0..1);
pass.set_bind_group(0, &self.group, &[]);
}
if crumbling_quads > 0 {
pass.set_pipeline(&self.crumbling_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
pass.draw_indexed(0..crumbling_quads * 6, (entity_quads * 4) as i32, 0..1);
pass.set_bind_group(0, &self.group, &[]);
}
if additive_quads > 0 {
pass.set_pipeline(&self.additive_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
pass.draw_indexed(0..additive_quads * 6, (world_quads * 4) as i32, 0..1);
pass.set_bind_group(0, &self.group, &[]);
}
if outline_edges > 0 {
pass.set_pipeline(&self.lines);
pass.set_vertex_buffer(0, self.outline.slice(..));
pass.draw(0..4, 0..outline_edges as u32);
}
if debug_depth > 0 {
pass.set_pipeline(&self.debug_lines);
pass.set_vertex_buffer(0, self.debug_line_buffer.slice(..));
pass.draw(0..4, 0..debug_depth);
}
if debug_top > 0 {
pass.set_pipeline(&self.debug_lines_on_top);
pass.set_vertex_buffer(0, self.debug_line_buffer.slice(..));
pass.draw(0..4, debug_depth..debug_depth + debug_top);
}
pass.set_pipeline(&self.translucent);
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
pass.set_vertex_buffer(1, self.instances.slice(..));
self.draw_sections(&mut pass, solid_draws, translucent_draws);
// LevelRenderer: the world border after translucent terrain and weather.
if let Some(b) = frame.border.as_ref().filter(|_| !frame.title) {
pass.set_pipeline(&self.border_pipeline);
pass.set_bind_group(0, &self.border_group, &[]);
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
pass.set_vertex_buffer(0, self.border_vertices.slice(..));
for &side in &b.sides {
let first = side as u32 * 6;
pass.draw_indexed(first..first + 6, 0, 0..1);
}
pass.set_bind_group(0, &self.group, &[]);
}
if translucent_crumbling_quads > 0 {
pass.set_pipeline(&self.crumbling_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
pass.draw_indexed(
0..translucent_crumbling_quads * 6,
((entity_quads + crumbling_quads) * 4) as i32,
0..1,
);
}
if cloud_quads > 0 {
pass.set_pipeline(&self.cloud_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_bind_group(1, &self.cloud_group, &[]);
pass.set_vertex_buffer(0, self.cloud_buffer.slice(..));
pass.draw_indexed(0..cloud_quads * 6, 0, 0..1);
}
// LevelRenderer.executeSeeThrough, after the rest of the world.
if see_through_quads > 0 {
pass.set_pipeline(&self.see_through_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
pass.draw_indexed(
0..see_through_quads * 6,
((world_quads + additive_quads + hand_quads) * 4) as i32,
0..1,
);
}
}
if let (true, Some((color, depth)), Some(size), Some(stages)) =
(pack, &scaled, self.world_post.size(), self.pack.as_mut())
{
let output = match stages {
Pack::Horizon(stages) => stages.run(
&self.device,
&self.queue,
&mut encoder,
color,
depth,
size,
&self.world_post,
pack_uniform,
),
Pack::Java(stages) => stages.run(
&self.device,
&self.queue,
&mut encoder,
color,
depth,
size,
&self.world_post,
pack_uniform,
),
};
self.world_post
.finish_with(&mut encoder, &view_target, output);
} else if scaled.is_some() {
self.world_post.finish(&mut encoder, &view_target);
}
if hand_quads > 0 {
let attachments = [Some(wgpu::RenderPassColorAttachment {
view: &view_target,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})];
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("First-person hand"),
color_attachments: &attachments,
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(0.0),
store: wgpu::StoreOp::Discard,
}),
stencil_ops: None,
}),
..Default::default()
});
pass.set_pipeline(&self.entity_pipeline);
pass.set_bind_group(0, &self.hand_group, &[]);
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
pass.draw_indexed(
0..hand_quads * 6,
((world_quads + additive_quads) * 4) as i32,
0..1,
);
}
if !frame.screen.is_empty() {
let vertices: Vec<crate::screen_effects::ScreenVertex> =
frame.screen.iter().flat_map(|q| q.vertices).collect();
if vertices.len() as u64 > self.screen_capacity {
self.screen_capacity = (vertices.len() as u64).next_power_of_two();
self.screen_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Screen effect vertices"),
size: self.screen_capacity
* std::mem::size_of::<crate::screen_effects::ScreenVertex>() as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
}
self.uploads.buffer(
&mut encoder,
&self.screen_buffer,
0,
bytemuck::cast_slice(&vertices),
);
let attachments = [Some(wgpu::RenderPassColorAttachment {
view: &view_target,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})];
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Screen effects"),
color_attachments: &attachments,
..Default::default()
});
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
pass.set_vertex_buffer(0, self.screen_buffer.slice(..));
for (i, quad) in frame.screen.iter().enumerate() {
let pipeline = match quad.blend {
crate::screen_effects::Blend::Alpha => &self.screen_pipelines[0],
crate::screen_effects::Blend::Vignette => &self.screen_pipelines[1],
};
pass.set_pipeline(pipeline);
pass.draw_indexed(0..6, (i * 4) as i32, 0..1);
}
}
// GameRenderer.render3dHud: the debug crosshair after the hand and
// the screen effects.
if crosshair > 0 {
let attachments = [Some(wgpu::RenderPassColorAttachment {
view: &view_target,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})];
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("3d crosshair"),
color_attachments: &attachments,
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(0.0),
store: wgpu::StoreOp::Discard,
}),
stencil_ops: None,
}),
..Default::default()
});
pass.set_pipeline(&self.debug_lines_on_top);
pass.set_bind_group(0, &self.crosshair_group, &[]);
pass.set_vertex_buffer(0, self.debug_line_buffer.slice(..));
let first = debug_depth + debug_top;
pass.draw(0..4, first..first + crosshair);
}
if let Some(radius) = frame.menu_blur
&& self.config.usage.contains(wgpu::TextureUsages::COPY_SRC)
{
let format = self.config.format;
let device = &self.device;
self.menu_blur
.get_or_insert_with(|| crate::menu_blur::MenuBlur::new(device, format))
.apply(
&self.device,
&self.queue,
&mut encoder,
&target_texture,
&view_target,
[self.config.width, self.config.height],
radius,
);
}
if let Some(grade) = &frame.post
&& self.config.usage.contains(wgpu::TextureUsages::COPY_SRC)
{
let format = self.config.format;
let device = &self.device;
self.post
.get_or_insert_with(|| crate::post::Post::new(device, format))
.apply(
&self.device,
&self.queue,
&mut encoder,
&target_texture,
&view_target,
[self.config.width, self.config.height],
grade,
);
}
self.hud.draw(
&self.device,
&self.queue,
&mut self.uploads,
&mut encoder,
&view_target,
frame.hud,
[self.config.width, self.config.height],
);
if let Some(timer) = &mut self.gpu_timer {
timer.end(&mut encoder);
}
let readback = self
.screenshot
.take()
.map(|path| (path, self.copy_frame(&mut encoder, &target_texture)));
self.uploads.finish(&encoder);
let submission = self.queue.submit([encoder.finish()]);
if let Some(timer) = &mut self.gpu_timer {
timer.submitted();
timer.collect(&self.device, &mut self.gpu_times);
}
if let Some((path, buffer)) = readback {
self.screenshot_result = Some(
self.write_screenshot(&path, &buffer)
.map_err(|e| e.to_string()),
);
}
let present = Instant::now();
if let Some(surface_frame) = surface_frame {
// On Wayland this ties RedrawRequested to the compositor's frame
// callbacks, one per refresh. Only VSync (Fifo) waits for the
// display: with it off, vanilla's window draws uncapped.
if self.config.present_mode == wgpu::PresentMode::Fifo {
self.window.pre_present_notify();
}
self.queue.present(surface_frame);
if reconfigure && let Some(surface) = &self.surface {
surface.configure(&self.device, &self.config);
}
} else {
// No swapchain paces offscreen frames: keep two on the GPU at most.
self.in_flight.push_back(submission);
while self.in_flight.len() > 2 {
let index = self.in_flight.pop_front();
let _ = self.device.poll(wgpu::PollType::Wait {
submission_index: index,
timeout: Some(std::time::Duration::from_secs(5)),
});
}
}
self.last_wait += present.elapsed();
self.last_encode = started.elapsed().saturating_sub(self.last_wait);
let _ = self.started;
self.visible = visible;
Ok(true)
}
}
impl Renderer {
fn padded_row(&self) -> u32 {
(self.config.width * 4).next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)
}
fn copy_frame(
&self,
encoder: &mut wgpu::CommandEncoder,
texture: &wgpu::Texture,
) -> wgpu::Buffer {
let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Horizon screenshot"),
size: u64::from(self.padded_row()) * u64::from(self.config.height),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
encoder.copy_texture_to_buffer(
texture.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &buffer,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(self.padded_row()),
rows_per_image: None,
},
},
wgpu::Extent3d {
width: self.config.width,
height: self.config.height,
depth_or_array_layers: 1,
},
);
buffer
}
fn write_screenshot(&self, path: &std::path::Path, buffer: &wgpu::Buffer) -> Result<[u32; 2]> {
if !self.config.usage.contains(wgpu::TextureUsages::COPY_SRC) {
return Err("this surface does not support frame readback".into());
}
let (sender, receiver) = std::sync::mpsc::channel();
buffer.map_async(wgpu::MapMode::Read, .., move |r| {
let _ = sender.send(r);
});
self.device
.poll(wgpu::PollType::wait_indefinitely())
.map_err(|e| e.to_string())?;
receiver
.recv()
.map_err(|e| e.to_string())?
.map_err(|e| e.to_string())?;
let (width, height, row) = (
self.config.width,
self.config.height,
self.padded_row() as usize,
);
let bgra = matches!(
self.config.format.remove_srgb_suffix(),
wgpu::TextureFormat::Bgra8Unorm
);
let mut pixels = Vec::with_capacity((width * height * 4) as usize);
{
let data = buffer.get_mapped_range(..).map_err(|e| e.to_string())?;
for y in 0..height as usize {
for px in data[y * row..y * row + width as usize * 4]
.as_chunks::<4>()
.0
{
let (r, b) = if bgra { (px[2], px[0]) } else { (px[0], px[2]) };
pixels.extend_from_slice(&[r, px[1], b, 255]);
}
}
}
buffer.unmap();
let mut encoder = png::Encoder::new(
std::io::BufWriter::new(std::fs::File::create(path)?),
width,
height,
);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder.write_header()?.write_image_data(&pixels)?;
Ok([width, height])
}
}
/// Camera-relative clip planes (`Frustum`).
#[derive(Clone, Copy, Debug)]
pub struct Frustum {
planes: [Vec4; 6],
}
impl Frustum {
/// Whether the camera-relative box `min..max` is at least partly inside.
pub fn intersects(&self, min: Vec3, max: Vec3) -> bool {
!self.planes.iter().any(|p| {
let v = Vec3::new(
if p.x >= 0.0 { max.x } else { min.x },
if p.y >= 0.0 { max.y } else { min.y },
if p.z >= 0.0 { max.z } else { min.z },
);
p.truncate().dot(v) + p.w < 0.0
})
}
}
/// Vanilla's `Projection`: reversed depth (near maps to 1, far to 0, tests
/// are GREATER_THAN_OR_EQUAL), which keeps far faces a hair apart, like
/// fire_side's 0.01 pixel in front of its block, from z-fighting.
/// The prelude's `Frame` (`shader_pack_prelude.wgsl`); `resolution` and the
/// time are filled per stage.
fn shader_pack_uniform(
frame: &Frame,
view: Mat4,
projection: Mat4,
sun: Vec3,
fog_color: [f32; 4],
fog: [f32; 4],
fog_ends: [f32; 4],
) -> pack_stages::FrameUniform {
let s = frame.shader;
let sky = frame.sky.sky_color;
pack_stages::FrameUniform {
view: view.to_cols_array_2d(),
projection: projection.to_cols_array_2d(),
inverse_view: view.inverse().to_cols_array_2d(),
inverse_projection: projection.inverse().to_cols_array_2d(),
camera_position: [
frame.camera.x as f32,
frame.camera.y as f32,
frame.camera.z as f32,
0.0,
],
time: [0.0, 0.0, s.day_fraction, s.partial_tick],
sun: [sun.x, sun.y, sun.z, frame.sky.sun_angle.to_radians()],
moon: [-sun.x, -sun.y, -sun.z, f32::from(s.moon_phase)],
sky_color: [sky[0], sky[1], sky[2], 1.0],
fog_color,
fog: [fog[0], fog[1], fog_ends[0], fog_ends[1]],
weather: [s.rain, s.thunder, 0.0, 0.0],
camera_state: [
f32::from(s.submerged),
frame.night_vision,
frame.darkness.1,
0.0,
],
view_params: [
0.05,
frame.depth_far,
frame.distance,
frame.fov_degrees.to_radians(),
],
dimension: [
f32::from(s.dimension),
f32::from(u8::from(s.has_sky_light)),
0.0,
0.0,
],
..Default::default()
}
}
/// The selected shader pack on the GPU: a Horizon pack's WGSL stages, or a
/// Java pack's translated programs.
enum Pack {
Horizon(pack_stages::PackStages),
Java(java_stages::JavaStages),
}
fn world_projection(fov_degrees: f32, aspect: f32, far: f32) -> Mat4 {
Mat4::perspective_rh(fov_degrees.to_radians(), aspect, far, 0.05)
}
fn frustum(m: Mat4) -> [Vec4; 6] {
let r = |i| m.row(i);
let planes = [
r(3) + r(0),
r(3) - r(0),
r(3) + r(1),
r(3) - r(1),
r(2),
r(3) - r(2),
];
planes.map(|p| p / p.truncate().length())
}
#[cfg(test)]
mod tests {
#[test]
fn special_material_batches_preserve_quad_order_and_offsets() {
let quad = |layer, id| {
[super::Vertex {
pos: [0.0; 3],
uv: [0.0; 2],
layer,
color: 0xffff_ffff,
light: id,
normal: [0; 4],
}; 4]
};
let entities: Vec<_> = [(0, 0), (4, 1), (11, 2), (7, 3), (4, 4), (12, 7)]
.into_iter()
.flat_map(|(layer, id)| quad(layer, id))
.collect();
let mut batch = super::EntityBatch::default();
let counts = batch.update(&entities, &quad(3, 5), &quad(0, 6), &quad(0, 8));
let vertices = &batch.combined;
assert_eq!(counts, [4, 1, 1]);
assert_eq!(
vertices
.as_chunks::<4>()
.0
.iter()
.map(|q| q[0].light)
.collect::<Vec<_>>(),
[0, 1, 3, 4, 2, 7, 5, 6, 8]
);
}
#[test]
fn entity_shader_validates_with_its_overlay_constants() {
let module = naga::front::wgsl::parse_str(&super::entity_shader()).unwrap();
naga::valid::Validator::new(
naga::valid::ValidationFlags::all(),
naga::valid::Capabilities::all(),
)
.validate(&module)
.unwrap();
}
#[test]
fn terrain_attributes_follow_the_terrain_vertex() {
use super::TerrainVertex;
use std::mem::offset_of;
let offsets = super::TERRAIN_ATTRIBUTES.map(|a| (a.shader_location, a.offset as usize));
assert_eq!(
offsets,
[
(0, offset_of!(TerrainVertex, pos)),
(1, offset_of!(TerrainVertex, uv)),
(2, offset_of!(TerrainVertex, layer)),
(4, offset_of!(TerrainVertex, light)),
(3, offset_of!(TerrainVertex, color)),
]
);
assert_eq!(std::mem::size_of::<TerrainVertex>(), 28);
}
#[test]
fn cracks_multiply_instead_of_covering_the_block() {
let blend = super::CRUMBLING_BLEND;
assert_eq!(blend.color.src_factor, wgpu::BlendFactor::Dst);
assert_eq!(blend.color.dst_factor, wgpu::BlendFactor::Src);
assert_eq!(blend.alpha.src_factor, wgpu::BlendFactor::One);
assert_eq!(blend.alpha.dst_factor, wgpu::BlendFactor::Zero);
}
#[test]
fn shader_globals_match_the_rust_layout() {
// terrain.wgsl and entity.wgsl bind the same buffer: same fields, same order.
let fields = |source: &str| -> Vec<String> {
let body = source.split("struct Globals {").nth(1).unwrap();
body[..body.find('}').unwrap()]
.lines()
.filter_map(|l| l.trim().split_once(':').map(|(name, _)| name.to_string()))
.filter(|name| !name.starts_with("//"))
.collect()
};
let terrain = fields(include_str!("terrain.wgsl"));
assert_eq!(terrain, fields(include_str!("entity.wgsl")));
let rust = fields(include_str!("gfx.rs"));
assert_eq!(terrain, rust);
}
#[test]
fn selection_outline_uses_vanilla_pixel_width() {
for width in [640, 1280, 1920] {
assert_eq!(super::outline_width(width), 2.5);
}
assert_eq!(super::outline_width(2560), 2560.0 / 1920.0 * 2.5);
assert_eq!(super::outline_width(3840), 5.0);
}
#[test]
fn indirect_draws_are_validated_only_in_debug_builds() {
if std::env::var_os("WGPU_VALIDATION_INDIRECT_CALL").is_none() {
let flags = super::instance_descriptor().flags;
assert_eq!(
flags.contains(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL),
cfg!(debug_assertions)
);
}
}
#[test]
fn far_faces_a_hair_apart_keep_their_depth_order() {
let m = super::world_projection(70.0, 16.0 / 9.0, 768.0);
let depth = |distance: f32| {
let clip = m * glam::Vec4::new(0.0, 0.0, -distance, 1.0);
clip.z / clip.w
};
// fire_side at 150 blocks, 0.01 pixel in front of the block it burns on.
let (block, fire) = (depth(150.0), depth(150.0 - 0.01 / 16.0));
assert!(fire > block, "{fire} {block}");
assert!((0.0..=1.0).contains(&block));
assert!((depth(0.05) - 1.0).abs() < 1e-6);
}
#[test]
fn selection_outline_has_vanilla_perspective_layering() {
assert_eq!(
super::outline_params(1280, 720),
[1280.0, 720.0, 2.5, 0.99975586]
);
assert_eq!(
super::outline_params(3840, 0),
[3840.0, 1.0, 5.0, 0.99975586]
);
}
#[test]
fn selection_outline_preserves_shape_edges_without_inflation() {
let edges = [[2.0, 97.5, 3.0, 3.0, 97.5, 3.0]];
assert_eq!(
super::outline_vertices(&edges, glam::DVec3::new(0.5, 98.62, 0.5)),
vec![[
1.5,
(97.5 - 98.62) as f32,
2.5,
2.5,
(97.5 - 98.62) as f32,
2.5
]]
);
assert!(super::outline_vertices(&[], glam::DVec3::ZERO).is_empty());
}
}
pub(crate) fn sprite_mipmap_limit(requested: u32, size: u32, minimum: u32, available: u32) -> u32 {
// Only the atlas native minimum determines how many resampling-only mips to skip.
let upscale = (size / minimum.max(1)).max(1).ilog2();
requested.saturating_add(upscale).min(available - 1)
}
/// Room for every frame of the vanilla animations (594 frames, 13 MB of mip
/// chains in 64-pixel layers), so no frame's chain is rebuilt on the render
/// thread when its animation comes back to it; larger packs stay bounded.
const ANIMATION_MIP_BUDGET: usize = 32 << 20;
const ANIMATION_MIP_ENTRIES: usize = 4096;
/// One immutable resource snapshot and its lazily generated frame mips. A new
/// renderer on resource reload drops this entire snapshot, including its cache:
/// frame indices can never alias another resource's pixels, size or settings.
struct AnimatedSprites {
/// Each animated sprite and what its layer holds (`None`: not uploaded yet).
animations: Vec<(SpriteAnimation, Option<crate::sprites::FrameBlend>)>,
size: u32,
settings: Vec<crate::mipmap::Settings>,
// Cache bookkeeping must not consume randomness or affect other maps' seeding.
cache: crate::fast_hash::FxHashMap<(usize, usize), Vec<u8>>,
/// Retained pixel-buffer capacities, not just their initialized lengths.
cache_bytes: usize,
budget: usize,
}
impl AnimatedSprites {
fn new(
animations: &[SpriteAnimation],
size: u32,
settings: &[crate::mipmap::Settings],
) -> Self {
Self {
animations: animations.iter().cloned().map(|a| (a, None)).collect(),
size,
settings: settings.to_vec(),
cache: Default::default(),
cache_bytes: 0,
budget: ANIMATION_MIP_BUDGET,
}
}
}
fn animate_sprites(
state: &mut AnimatedSprites,
tick: u64,
max_levels: u32,
mut write: impl FnMut(u32, u32, u32, &[u8]),
) {
let size = state.size;
let levels = size.trailing_zeros() + 1;
let AnimatedSprites {
animations,
settings,
cache,
cache_bytes,
budget,
..
} = state;
for (index, (animation, previous)) in animations.iter_mut().enumerate() {
let blend = animation.blend(tick);
if *previous == Some(blend) {
continue;
}
*previous = Some(blend);
let (animation, settings) = (&*animation, &**settings);
let chain = |frame: usize| {
move || mip_chain(animation.pixels(frame), size, settings, animation.layer, 1).0
};
let (current, mixed);
let mips: &[u8] = if blend.millis > 0 {
let mut mix = frame_mips(
cache,
cache_bytes,
*budget,
(index, blend.frame),
chain(blend.frame),
)
.into_owned();
let next = frame_mips(
cache,
cache_bytes,
*budget,
(index, blend.next),
chain(blend.next),
);
mix_frames(&mut mix, &next, blend.millis);
mixed = mix;
&mixed
} else {
current = frame_mips(
cache,
cache_bytes,
*budget,
(index, blend.frame),
chain(blend.frame),
);
&current
};
let mut offset = 0;
for level in 0..levels.min(max_levels) {
let edge = size >> level;
let bytes = (edge * edge * 4) as usize;
write(animation.layer, level, edge, &mips[offset..offset + bytes]);
offset += bytes;
}
}
}
/// `animate_sprite_interpolate.fsh`: `mix(current, next, millis / 1000)` per
/// channel of every mipmap level, stored as 8-bit unorm.
/// One frame's mip chain: from the cache, or generated and kept while the budget has room.
/// Frames that do not fit still go through the same generation path.
fn frame_mips<'a>(
cache: &'a mut crate::fast_hash::FxHashMap<(usize, usize), Vec<u8>>,
cache_bytes: &mut usize,
budget: usize,
key: (usize, usize),
generate: impl FnOnce() -> Vec<u8>,
) -> std::borrow::Cow<'a, [u8]> {
let room = cache.len() < ANIMATION_MIP_ENTRIES;
match cache.entry(key) {
std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut().as_slice().into(),
std::collections::hash_map::Entry::Vacant(entry) => {
let pixels = generate();
// Bound both pixel storage and map metadata. Keep admitted frames
// rather than churning them on large/unique workloads.
if room && pixels.capacity() <= budget - *cache_bytes {
*cache_bytes += pixels.capacity();
entry.insert(pixels).as_slice().into()
} else {
pixels.into()
}
}
}
}
fn mix_frames(current: &mut [u8], next: &[u8], millis: u32) {
let t = millis as f32 / 1000.0;
for (c, n) in current.iter_mut().zip(next) {
let (a, b) = (f32::from(*c) / 255.0, f32::from(*n) / 255.0);
*c = ((a * (1.0 - t) + b * t) * 255.0).round() as u8;
}
}
#[cfg(test)]
mod sprite_upload_tests {
use super::*;
#[test]
fn real_rail_mips_do_not_change_with_larger_array_layers() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client/26.3");
if !root
.join("assets/minecraft/textures/block/rail.png")
.exists()
{
return;
}
let mut sprites = crate::sprites::Sprites::default();
let layers: Vec<_> = [
"rail",
"powered_rail",
"powered_rail_on",
"detector_rail",
"activator_rail",
]
.map(|name| {
sprites
.insert(&root, &format!("minecraft:block/{name}"))
.unwrap()
})
.into();
sprites.finish();
assert_eq!(sprites.size, 16);
let native: Vec<_> = layers
.iter()
.map(|&layer| {
let start = layer as usize * 16 * 16 * 4;
mip_chain(
&sprites.pixels[start..start + 16 * 16 * 4],
16,
&sprites.mips,
layer,
1,
)
.0
})
.collect();
sprites.insert(&root, "minecraft:block/oak_sign").unwrap();
sprites.finish();
assert_eq!(sprites.size, 32);
for (&layer, expected) in layers.iter().zip(native) {
let start = layer as usize * 32 * 32 * 4;
let (actual, _) = mip_chain(
&sprites.pixels[start..start + 32 * 32 * 4],
32,
&sprites.mips,
layer,
1,
);
assert_eq!(&actual[32 * 32 * 4..], expected, "rail layer {layer}");
}
}
#[test]
fn mipmap_option_keeps_real_16px_reductions() {
for levels in 0..=4 {
assert_eq!(sprite_mipmap_limit(levels, 32, 16, 6), levels + 1);
assert_eq!(sprite_mipmap_limit(levels, 16, 16, 5), levels);
}
}
#[test]
fn animation_updates_entire_layer_every_mip_once() {
for size in [16, 32] {
let animation = crate::sprites::test_animation(size, 7);
let pixels = animation.pixels(animation.frame(1)).to_vec();
let settings = [];
let (expected, levels) = mip_chain(&pixels, size, &settings, 7, 1);
let mut animations = AnimatedSprites::new(&[animation], size, &settings);
animations.animations[0].1 = Some(animations.animations[0].0.blend(0));
let mut writes = Vec::new();
let mut record = |layer, level, edge, data: &[u8]| {
assert_eq!(layer, 7);
assert_eq!(edge, size >> level);
assert_eq!(data.len(), (edge * edge * 4) as usize);
writes.push(data.to_vec());
};
animate_sprites(&mut animations, 0, levels, &mut record);
animate_sprites(&mut animations, 1, levels, &mut record);
animate_sprites(&mut animations, 1, levels, &mut record);
assert_eq!(writes.len(), levels as usize);
assert_eq!(writes[0], pixels);
assert_eq!(writes.concat(), expected);
}
}
#[test]
fn cached_and_uncached_uploads_match_through_loops_and_mip_changes() {
for size in [16, 32] {
let animations = [crate::sprites::test_animation(size, 7)];
let settings = vec![
crate::mipmap::Settings {
strategy: crate::mipmap::Strategy::StrictCutout,
alpha_cutoff_bias: -0.2,
..Default::default()
};
8
];
let mut cached = AnimatedSprites::new(&animations, size, &settings);
let mut uncached = AnimatedSprites::new(&animations, size, &settings);
uncached.budget = 0;
for tick in [0, 0, 1, 2, 3, 33, 32, 32, 1, 0] {
let levels = (tick % 7) as u32;
let mut expected = Vec::new();
let mut actual = Vec::new();
animate_sprites(&mut uncached, tick, levels, |layer, level, edge, bytes| {
expected.push((layer, level, edge, bytes.to_vec()));
});
animate_sprites(&mut cached, tick, levels, |layer, level, edge, bytes| {
actual.push((layer, level, edge, bytes.to_vec()));
});
assert_eq!(actual, expected);
}
assert_eq!(cached.cache.len(), 2);
assert_eq!(uncached.cache_bytes, 0);
assert_eq!(
cached.cache_bytes,
cached.cache.values().map(Vec::capacity).sum::<usize>()
);
}
}
#[test]
fn budget_exhaustion_keeps_admitted_frames_and_uploads_misses() {
let size = 16;
let animation = crate::sprites::test_animation(size, 0);
let bytes = mip_chain(animation.pixels(0), size, &[], 0, 1).0.capacity();
let mut state = AnimatedSprites::new(&[animation], size, &[]);
state.budget = bytes;
for tick in 0..8 {
let mut writes = 0;
animate_sprites(&mut state, tick, 5, |_, _, _, _| writes += 1);
assert_eq!(writes, 5);
assert_eq!(state.cache_bytes, bytes);
assert_eq!(state.cache.len(), 1);
assert!(state.cache.contains_key(&(0, 0)));
}
}
#[test]
fn mip_chain_allocates_exactly_its_size() {
for size in [16, 64] {
let animation = crate::sprites::test_animation(size, 0);
let (chain, _) = mip_chain(animation.pixels(0), size, &[], 0, 1);
assert_eq!(chain.capacity(), chain.len());
}
}
#[test]
fn every_vanilla_animation_frame_stays_cached() {
// Vanilla's 594 animation frames in 64-pixel layers: 297 two-frame clips.
let animations: Vec<_> = (0..297)
.map(|layer| crate::sprites::test_animation(64, layer))
.collect();
let mut state = AnimatedSprites::new(&animations, 64, &[]);
for tick in 0..4 {
animate_sprites(&mut state, tick, 7, |_, _, _, _| {});
}
assert_eq!(state.cache.len(), 594);
assert!(state.cache_bytes <= ANIMATION_MIP_BUDGET);
}
#[test]
fn entry_limit_also_bounds_metadata_for_tiny_frames() {
let animation = crate::sprites::test_animation(1, 0);
let animations = vec![animation; ANIMATION_MIP_ENTRIES + 1];
let mut state = AnimatedSprites::new(&animations, 1, &[]);
for tick in 0..2 {
let mut writes = 0;
animate_sprites(&mut state, tick, 1, |_, _, _, _| writes += 1);
assert_eq!(writes, animations.len());
assert_eq!(state.cache.len(), ANIMATION_MIP_ENTRIES);
assert!(state.cache_bytes <= ANIMATION_MIP_BUDGET);
}
}
#[test]
fn resource_snapshot_replacement_discards_pixels_size_and_settings() {
let old = crate::sprites::test_animation(16, 0);
let mut state = AnimatedSprites::new(&[old], 16, &[]);
animate_sprites(&mut state, 0, 5, |_, _, _, _| {});
assert!(!state.cache.is_empty());
let animation = crate::sprites::test_animation(32, 0);
let settings = [crate::mipmap::Settings {
strategy: crate::mipmap::Strategy::StrictCutout,
alpha_cutoff_bias: -0.4,
..Default::default()
}];
let expected = mip_chain(animation.pixels(0), 32, &settings, 0, 1).0;
state = AnimatedSprites::new(&[animation], 32, &settings);
assert_eq!(state.cache_bytes, 0);
assert!(state.cache.is_empty());
let mut actual = Vec::new();
animate_sprites(&mut state, 0, 6, |_, _, _, bytes| {
actual.extend_from_slice(bytes)
});
assert_eq!(actual, expected);
}
#[test]
fn interpolated_animation_uploads_the_mix_every_tick() {
let animation = crate::sprites::test_clip(16, 3, r#"{"frametime":4,"interpolate":true}"#);
let settings = [];
let (_, levels) = mip_chain(animation.pixels(0), 16, &settings, 3, 1);
let mut cached = AnimatedSprites::new(std::slice::from_ref(&animation), 16, &settings);
let mut uncached = AnimatedSprites::new(std::slice::from_ref(&animation), 16, &settings);
uncached.budget = 0;
for state in [&mut cached, &mut uncached] {
state.animations[0].1 = Some(animation.blend(0));
}
let mut blues = Vec::new();
let mut uncached_blues = Vec::new();
let mut record = |_, level, _, data: &[u8]| {
if level == 0 {
blues.push(data[2]);
}
};
for tick in [0, 1, 1, 2, 4] {
animate_sprites(&mut cached, tick, levels, &mut record);
animate_sprites(&mut uncached, tick, levels, |_, level, _, data: &[u8]| {
if level == 0 {
uncached_blues.push(data[2]);
}
});
}
// Frame 0 is blue 0, frame 1 blue 99: a quarter, a half, then frame 1.
assert_eq!(blues, [25, 50, 99]);
assert_eq!(uncached_blues, blues);
}
}