From c45fe0b0874cafa41eeac16d4f7ee7bb37a1d397 Mon Sep 17 00:00:00 2001 From: leonidarider <358984476+leonidarider@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:08:00 +0100 Subject: [PATCH] refactor: group viewport/bridge state bags and decouple meta/shader boot order (desloppify wave 5D-1) - Group RenderBridge (56 -> 11 fields) and ViewportRenderer (59 -> 14 fields) into cohesive pipeline-owned sub-structs in src/render/viewport/state.rs and crates/runtime/or-renderer/src/viewport/state.rs, replacing the raw 4-tuple deferred_pipelines with named DeferredPipelines. - Consolidate metadata host bootstrap into or_title::schema::init_meta_host so ragepar_names::load_from, install_names_snapshot, and install_snapshot run in guaranteed order inside a single Once for GUI, photo/self-check, and CLI; split TITLE_INDEX/TITLE_PUBLIC_INDEX in hash_index.rs and remove the GUI-only src/main.rs ordering call. - Eliminate global DRAWN_BY_HARDWARE / drawn_by_hardware in favor of explicit hardware: bool plumbing through rdna_bind::shading, or-cli, gta6_shaders, gta6_frame_light, and RenderBridge::with_hardware_adapter; replace silent-ignore OnceLock caches in kept.rs and kept_dx12.rs with reconfigurable stores and regression tests. --- crates/io/or-io/src/meta/binary/hash_index.rs | 23 +- crates/io/or-io/src/meta/snapshot.rs | 6 + .../or-renderer/src/game_shaders/kept_dx12.rs | 81 ++- .../src/game_shaders/kept_dx12/tests.rs | 30 ++ crates/runtime/or-renderer/src/viewport.rs | 363 +++++-------- .../runtime/or-renderer/src/viewport/build.rs | 100 ++-- .../or-renderer/src/viewport/game_frame.rs | 227 ++++---- .../runtime/or-renderer/src/viewport/state.rs | 274 ++++++++++ .../or-renderer/src/viewport/states_taken.rs | 9 +- .../runtime/or-renderer/src/viewport/tests.rs | 15 +- .../src/viewport/world_fed_tests.rs | 6 +- .../src/viewport/world_post_tests.rs | 12 +- .../or-renderer/src/viewport/world_water.rs | 22 +- .../src/viewport/world_water_tests.rs | 6 +- crates/title/or-title/Cargo.toml | 5 +- crates/title/or-title/src/schema.rs | 153 +++++- crates/tools/or-cli/src/gta6/frame_pass.rs | 52 +- crates/tools/or-cli/src/gta6/shading.rs | 42 +- crates/tools/or-cli/src/lib.rs | 1 - crates/tools/or-cli/src/meta.rs | 20 +- .../or-cli/tests/gta6_shaded_stage_census.rs | 10 +- .../src/rdna_bind/forward_frame.rs | 9 +- .../or-shader-front/src/rdna_bind/kept.rs | 263 ++++++++-- .../or-shader-front/src/rdna_bind/lighting.rs | 20 +- .../or-shader-front/src/rdna_bind/shading.rs | 52 +- .../tools/or-shader-tool/src/rdna_devices.rs | 4 +- src/app/editor_window.rs | 2 + src/app/gpu.rs | 1 - src/main.rs | 2 - src/render/gta6_frame_light.rs | 30 +- src/render/viewport/day.rs | 14 +- src/render/viewport/dressed.rs | 48 +- src/render/viewport/game_shaders.rs | 195 +++---- src/render/viewport/gta6_ahead_tests.rs | 24 +- src/render/viewport/gta6_late_maps.rs | 28 +- src/render/viewport/gta6_late_maps_tests.rs | 14 +- src/render/viewport/mod.rs | 488 +++++++----------- src/render/viewport/photo.rs | 86 +-- src/render/viewport/state.rs | 197 +++++++ src/render/viewport/usage.rs | 11 +- src/render/viewport/world.rs | 14 +- src/render/viewport/world_plain.rs | 4 +- src/render/viewport/world_shown_tests.rs | 8 +- src/self_check.rs | 11 +- src/state/document/meta.rs | 33 +- src/state/document/mod.rs | 2 +- src/state/gta6_shader_translator.rs | 47 +- src/state/gta6_shaders.rs | 71 ++- src/state/gta6_shaders_tests.rs | 26 +- 49 files changed, 1974 insertions(+), 1187 deletions(-) create mode 100644 crates/runtime/or-renderer/src/viewport/state.rs create mode 100644 src/render/viewport/state.rs diff --git a/crates/io/or-io/src/meta/binary/hash_index.rs b/crates/io/or-io/src/meta/binary/hash_index.rs index c28518248..7a156f861 100644 --- a/crates/io/or-io/src/meta/binary/hash_index.rs +++ b/crates/io/or-io/src/meta/binary/hash_index.rs @@ -176,10 +176,14 @@ static INSTALLED_INDEX: OnceLock = OnceLock::new(); static PUBLIC_INDEX: OnceLock = OnceLock::new(); static CLEAN_INDEX: OnceLock = OnceLock::new(); static TITLE_INDEX: OnceLock = OnceLock::new(); +static TITLE_PUBLIC_INDEX: OnceLock = OnceLock::new(); /// Whether any default hash index has already been built for this process. pub(crate) fn has_default_index() -> bool { - INSTALLED_INDEX.get().is_some() || PUBLIC_INDEX.get().is_some() || TITLE_INDEX.get().is_some() + INSTALLED_INDEX.get().is_some() + || PUBLIC_INDEX.get().is_some() + || TITLE_INDEX.get().is_some() + || TITLE_PUBLIC_INDEX.get().is_some() } /// The names the default library and [`crate::meta::binary::public_names`] give. @@ -199,11 +203,18 @@ pub fn default_hash_index() -> &'static HashIndex { let installed = crate::meta::snapshot::installed(); let title = crate::meta::snapshot::names_library().filter(|_| TITLE_NAMES.with(Cell::get)); if let Some(title) = title { - return TITLE_INDEX.get_or_init(|| { - let mut index = HashIndex::from_library(title); - installed.into_iter().for_each(|l| index.add_library(l)); - index.with_public_names().with_parser_names() - }); + return match installed { + Some(library) => TITLE_INDEX.get_or_init(|| { + let mut index = HashIndex::from_library(title); + index.add_library(library); + index.with_public_names().with_parser_names() + }), + None => TITLE_PUBLIC_INDEX.get_or_init(|| { + HashIndex::from_library(title) + .with_public_names() + .with_parser_names() + }), + }; } match installed { Some(library) => INSTALLED_INDEX.get_or_init(|| { diff --git a/crates/io/or-io/src/meta/snapshot.rs b/crates/io/or-io/src/meta/snapshot.rs index 3fb93a9b6..42629929f 100644 --- a/crates/io/or-io/src/meta/snapshot.rs +++ b/crates/io/or-io/src/meta/snapshot.rs @@ -175,6 +175,12 @@ pub fn install_names_snapshot(path: &Path) -> Result<&'static SchemaLibrary> { if let Some(held) = NAMES.get() { return Ok(held); } + if crate::meta::binary::hash_index::has_default_index() { + tracing::warn!( + path = %path.display(), + "a default hash index was already built before GTA VI's names snapshot was installed" + ); + } let library = load_snapshot(path)?; Ok(NAMES.get_or_init(|| library)) } diff --git a/crates/runtime/or-renderer/src/game_shaders/kept_dx12.rs b/crates/runtime/or-renderer/src/game_shaders/kept_dx12.rs index bf8924330..5151a567b 100644 --- a/crates/runtime/or-renderer/src/game_shaders/kept_dx12.rs +++ b/crates/runtime/or-renderer/src/game_shaders/kept_dx12.rs @@ -7,7 +7,7 @@ use std::cell::{Cell, RefCell}; use std::num::NonZeroU32; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::OnceLock; +use std::sync::{PoisonError, RwLock}; use naga::back::hlsl; use naga::ShaderStage; @@ -48,10 +48,66 @@ const MOST: hlsl::ShaderModel = hlsl::ShaderModel::V6_6; /// The features a device is asked for where its adapter has them, to be handed a kept stage. pub(super) const FEATURES: wgpu::Features = wgpu::Features::PASSTHROUGH_SHADERS; -static FOLDER: OnceLock = OnceLock::new(); -/// The file whose being there says that the device refused a stage compiled here, named by its -/// adapter, driver and compiler. -static MARK: OnceLock = OnceLock::new(); +struct FolderState { + folder: Option, + /// The file whose being there says that the device refused a stage compiled here, named by its + /// adapter, driver and compiler. + mark: Option, +} + +struct FolderSlot(RwLock); + +impl FolderSlot { + const fn new() -> Self { + Self(RwLock::new(FolderState { + folder: None, + mark: None, + })) + } + + fn set(&self, folder: PathBuf) { + let mut state = self.0.write().unwrap_or_else(PoisonError::into_inner); + if state.folder.as_ref() == Some(&folder) { + return; + } + state.folder = Some(folder); + state.mark = None; + } + + fn folder(&self) -> Option { + self.0 + .read() + .unwrap_or_else(PoisonError::into_inner) + .folder + .clone() + } + + fn mark(&self) -> Option { + self.0 + .read() + .unwrap_or_else(PoisonError::into_inner) + .mark + .clone() + } + + fn mark_for(&self, folder: &Path, adapter: &str, compiler: &str) -> PathBuf { + let named = hex(&digest(&[MIRRORED, adapter, compiler])); + let mark = folder.join(format!("refused-{named}")); + let cached = self + .0 + .read() + .unwrap_or_else(PoisonError::into_inner) + .mark + .as_ref() + == Some(&mark); + if !cached { + self.0.write().unwrap_or_else(PoisonError::into_inner).mark = Some(mark.clone()); + } + mark + } +} + +static STATE: FolderSlot = FolderSlot::new(); static REFUSED: AtomicBool = AtomicBool::new(false); static PARTS: AtomicU64 = AtomicU64::new(0); @@ -62,9 +118,9 @@ thread_local! { static OFF: Cell = const { Cell::new(false) }; } -/// Keep the compiled stages in `folder`; the first call of a process decides. +/// Keep the compiled stages in `folder`. pub(super) fn keep_in(folder: PathBuf) { - let _ = FOLDER.set(folder); + STATE.set(folder); } /// Whether a device of `backend` with `features` is handed stages compiled here. @@ -123,8 +179,8 @@ pub(super) fn without(build: impl FnOnce() -> Result) -> Result Mat pub struct ViewportRenderer { pub colour_format: wgpu::TextureFormat, - width: u32, - height: u32, - dirty: bool, - colour: wgpu::Texture, - colour_view: wgpu::TextureView, - /// The colour target as the post-processing writes it, which gamma-encodes by itself where the target is sRGB. - colour_display_view: wgpu::TextureView, - depth_view: wgpu::TextureView, - pipeline: wgpu::RenderPipeline, - bind_group: wgpu::BindGroup, - camera_buffer: wgpu::Buffer, - camera_bgl: Arc, - line_buffer: Option, - line_count: u32, - /// How many of the lines, at the end of the buffer, draw over everything else. - lines_in_front: u32, - line_buffer_capacity: u64, - front_line_pipeline: wgpu::RenderPipeline, - solid_pipeline: wgpu::RenderPipeline, - material_pipeline: wgpu::RenderPipeline, - /// The material's translucent texels, drawn after every opaque one and writing no depth. - material_blend_pipeline: wgpu::RenderPipeline, - /// The material of a mesh whose texture is a normal map. - bump_pipeline: wgpu::RenderPipeline, - channel_pipeline: wgpu::RenderPipeline, - material_bgl: Arc, - fallback_material_bg: Arc, - fallback_material_bytes: u64, - meshes: Vec, + targets: ViewportTargets, + camera: CameraUniformGpu, + lines: LineOverlayGpu, + plain: PlainPipelines, /// The placed meshes of a world, drawn once for each instance. pub(crate) world: crate::world::World, game_scene: Option, - /// A GTA VI model drawn by its own mesh and pixel programs, which Shaded draws in place of `game_scene` where there is one. - gta6_scene: Option, - gta6_sky: crate::game_shaders::meshlets::Sky, - /// The scene drawn by the game's deferred passes, which Shaded draws in place of `game_scene` where there is one. - deferred: Option, - deferred_scene: Option, - /// Whether the deferred scene holds water, which reads a copy of the frame behind it and so is prepared again when the targets are made anew. - refracts: bool, - refraction_stale: bool, - /// The pipelines built for the deferred scenes, for the next to take. - deferred_pipelines: ( - crate::game_shaders::mesh::PipelineCache, - crate::game_shaders::mesh::PipelineCache, - crate::game_shaders::mesh::PipelineCache, - crate::game_shaders::mesh::PipelineCache, - ), - /// The sun's colour and the ambient light the game's passes are lit by. - game_light: (Vec3, Vec3), - /// The way towards the sun the game's passes are lit from; over the camera's shoulder where none is set. - game_sun: Option, - /// The seconds of the game's clock a frame of the game's programs is fed. - game_seconds: Option, - /// The way towards the key light of the plain modes, and its strength. - key_light: (Vec3, f32), - /// Whether the game's own sky is drawn where nothing else is, in place of the background colour. - sky_background: bool, - /// Whether the sun's shadow is cast and received by the game's passes. - shadows: bool, - /// The moment of the day the game's passes are lit by, which takes the place of the sun and the ambient light above. - day: Option, - /// How many days have been set, so that what depends on the day knows it has changed. - day_revision: u64, - /// The sprites, trails and models of the particle batches drawn with the game's own passes; none where there is no pack. - game_particles: Option, + gta6: Gta6GpuState, + deferred: DeferredResources, + lighting: SceneLighting, + env: EnvironmentState, + particles: ParticleGpuState, + skinning: SkinningState, /// How long each stage of a frame took on the device, where the device can time them. gpu_timer: Option, - particle_batches: Vec, - trail_batches: Vec, - model_batches: Vec, - /// The lights the particles give, which light what the frame draws. - point_lights: Vec, - spot_lights: Vec, - capsule_lights: Vec, - distant_lights: ( - crate::game_shaders::distant_lights::SpriteLook, - Arc<[crate::game_shaders::distant_lights::DistantLight]>, - ), - /// The coronas of the lights, and how the pass reads the depth about each; none draws no corona. - coronas: Option<(crate::CoronaLook, Vec)>, - /// The lights of a world's models and maps, which light a Shaded frame of it beside the particles'. - world_lights: crate::world::WorldLights, - fog_volumes: Vec, - /// The stars and the face of the moon the install gives, which a sky background draws at night. - sky_textures: crate::game_shaders::dome::SkyTextures, - /// The ripples and the foam of the game's water. - water_textures: crate::game_shaders::water::WaterTextures, - /// The skin matrices of the pose the skinned surfaces of the game's passes are drawn in, by bone of the skeleton; none draws them at rest. - skin: Vec, - /// What the colour target is cleared to before anything is drawn. - background: wgpu::Color, } /// The depth and stencil target: the stencil tells what the G-buffer passes drew from what nothing did, and the lighting passes read both. @@ -343,26 +271,6 @@ const DEPTH_FORMAT: wgpu::TextureFormat = crate::game_shaders::deferred::DEPTH_S const REFLECTION_WIDTH: u32 = 256; const REFLECTION_LEVELS: u32 = 8; -/// The game's deferred passes for the drawable Shaded shows, with the G-buffer they write and read. -struct DeferredFrame { - passes: crate::game_shaders::deferred::FramePasses, - gbuffer: crate::game_shaders::deferred::GBuffer, - depth: crate::game_shaders::deferred::DepthViews, - /// Where the light is summed before it is mapped to the screen. - hdr: wgpu::TextureView, - /// Where the light is mapped to before the game's anti-aliasing draws it to the screen. - ldr: wgpu::TextureView, - /// The map of the sky that surfaces reflect, and the revision of the day it shows. - reflection: crate::game_shaders::deferred::ReflectionTarget, - reflection_of: Option, - /// Whether the targets were made again since the scene read them. - stale: bool, - /// A copy of the lit frame that water reads behind itself, made when a scene holds water and made again with the targets. - refraction: Option, - /// Where the second colour the water fog pass writes goes, which nothing reads; made with the copy. - fog_sink: Option, -} - /// A pass over `colour` that reads the depth and the stencil of the frame and writes neither, as the lighting, the sky and what blends are drawn: `stencil` says what it does with the stencil where it marks it. fn over_the_frame<'a>( encoder: &'a mut wgpu::CommandEncoder, @@ -396,39 +304,39 @@ fn over_the_frame<'a>( impl ViewportRenderer { pub fn set_particle_batches(&mut self, batches: Vec) { - self.particle_batches = batches; + self.particles.sprites = batches; } pub fn set_trail_batches(&mut self, batches: Vec) { - self.trail_batches = batches; + self.particles.trails = batches; } pub fn set_model_batches(&mut self, batches: Vec) { - self.model_batches = batches; + self.particles.models = batches; } /// The stars and the face of the moon the install gives, which a sky background draws at night; none by default. pub fn set_sky_textures(&mut self, textures: crate::game_shaders::dome::SkyTextures) { - if let Some(frame) = self.deferred.as_mut() { + if let Some(frame) = self.deferred.frame.as_mut() { frame.passes.set_sky_textures(textures.clone()); } - self.sky_textures = textures; + self.env.sky_textures = textures; } /// The ripples and the foam the install gives its water, which a scene that holds water is prepared again to read. pub fn set_water_textures(&mut self, textures: crate::game_shaders::water::WaterTextures) { - self.water_textures = textures; - self.refraction_stale = self.refracts; + self.env.water_textures = textures; + self.deferred.refraction_stale = self.deferred.refracts; } /// The lights the particles give, which light what is drawn in Shaded; none by default. pub fn set_point_lights(&mut self, lights: Vec) { - self.point_lights = lights; + self.lighting.point_lights = lights; } /// Light Shaded with `lights` that shine in a cone, which the game's spot pass draws. pub fn set_spot_lights(&mut self, lights: Vec) { - self.spot_lights = lights; + self.lighting.spot_lights = lights; } /// Light Shaded with `lights` that shine from a segment, which the game's capsule pass draws. @@ -436,7 +344,7 @@ impl ViewportRenderer { &mut self, lights: Vec, ) { - self.capsule_lights = lights; + self.lighting.capsule_lights = lights; } /// Show `lights` seen from afar in Shaded as sprites of `size`, which the game's distant lights pass draws. @@ -445,22 +353,22 @@ impl ViewportRenderer { size: crate::game_shaders::distant_lights::SpriteLook, lights: Arc<[crate::game_shaders::distant_lights::DistantLight]>, ) { - self.distant_lights = (size, lights); + self.lighting.distant_lights = (size, lights); } /// Show the glow of the lights' sources in Shaded, which the game's corona pass draws where nothing nearer hides them. pub fn set_coronas(&mut self, coronas: Option<(crate::CoronaLook, Vec)>) { - self.coronas = coronas; + self.lighting.coronas = coronas; } /// Light a Shaded frame of the world with `lights`, each kind by the game's own pass for it, beside what the particles give; an empty set lights it by the sun alone. pub fn set_world_lights(&mut self, lights: crate::world::WorldLights) { - self.world_lights = lights; + self.lighting.world_lights = lights; } /// How many lights of the world the last set holds: those that shine all round, in a cone and from a segment, and the glows about their sources. pub fn world_lights(&self) -> [usize; 4] { - let lights = &self.world_lights; + let lights = &self.lighting.world_lights; let glows = lights.coronas.as_ref().map_or(0, |(_, glows)| glows.len()); [ lights.points.len(), @@ -472,12 +380,12 @@ impl ViewportRenderer { /// Fill the air of Shaded with `volumes`, which the game's fog volume pass draws over the lit frame. pub fn set_fog_volumes(&mut self, volumes: Vec) { - self.fog_volumes = volumes; + self.env.fog_volumes = volumes; } /// Draw the sprites, trails and models of particle batches with this pack's `ptfx_sprite`, `ptfx_trail` and `ptfx_model` passes; `None` draws no particles. pub fn set_game_pack(&mut self, pack: Option>) { - self.game_particles = + self.particles.game = pack.map(|pack| crate::particle_game::GameParticles::new(&pack, self.game_target())); self.refresh_soft_depth(); } @@ -485,13 +393,14 @@ impl ViewportRenderer { /// Hand the particles the depth of this frame to fade out against, made anew with the targets. fn refresh_soft_depth(&mut self) { let depth = self + .targets .depth_view .texture() .create_view(&wgpu::TextureViewDescriptor { aspect: wgpu::TextureAspect::DepthOnly, ..Default::default() }); - if let Some(particles) = self.game_particles.as_mut() { + if let Some(particles) = self.particles.game.as_mut() { particles.trails.set_depth(Some(depth.clone())); particles.sprites.set_depth(Some(depth)); } @@ -504,60 +413,60 @@ impl ViewportRenderer { queue: &wgpu::Queue, camera: &OrbitCamera, ) { - let aspect = self.width as f32 / self.height as f32; + let aspect = self.targets.aspect(); let scene = self.game_constants(camera, aspect); - if let Some(particles) = self.game_particles.as_mut() { + if let Some(particles) = self.particles.game.as_mut() { let batches = crate::particle_game::FrameBatches { - sprites: &self.particle_batches, - trails: &self.trail_batches, - models: &self.model_batches, + sprites: &self.particles.sprites, + trails: &self.particles.trails, + models: &self.particles.models, }; particles.prepare(device, queue, &batches, &scene, camera.eye()); } } pub fn material_bind_group_layout(&self) -> Arc { - self.material_bgl.clone() + self.plain.material_bgl.clone() } pub fn camera_bind_group_layout(&self) -> Arc { - self.camera_bgl.clone() + self.camera.bgl.clone() } pub fn colour_texture(&self) -> &wgpu::Texture { - &self.colour + &self.targets.colour } pub fn colour_view(&self) -> &wgpu::TextureView { - &self.colour_view + &self.targets.colour_view } /// The view of the colour target a frame of `mode` is shown through by what lays it on a screen and takes a texel for the bytes it holds, as egui does. // ⚠ The last of a game's programs writes what a screen shows, encoded for it already, so its frame is handed as the bytes it holds: read through the target's own view they would be decoded once more, and the frame shown too dark. A frame of OpenRage's own shaders is handed as it always was. pub fn shown_view(&self, mode: ShadingMode) -> &wgpu::TextureView { match self.deferred_in(mode) { - Some(_) => &self.colour_display_view, - None => &self.colour_view, + Some(_) => &self.targets.colour_display_view, + None => &self.targets.colour_view, } } pub fn depth_view(&self) -> &wgpu::TextureView { - &self.depth_view + &self.targets.depth_view } pub fn size(&self) -> (u32, u32) { - (self.width, self.height) + (self.targets.width, self.targets.height) } /// The bytes of the targets this renderer holds; sized by the viewport and never evicted. pub fn target_bytes(&self) -> u64 { - let deferred = self.deferred.iter().flat_map(|d| { + let deferred = self.deferred.frame.iter().flat_map(|d| { d.gbuffer .textures() .chain([d.hdr.texture(), d.ldr.texture()]) .chain(d.passes.textures()) }); - [&self.colour, self.depth_view.texture()] + [&self.targets.colour, self.targets.depth_view.texture()] .into_iter() .chain(deferred) .map(texture_bytes) @@ -567,14 +476,14 @@ impl ViewportRenderer { /// The bytes this renderer holds outside its targets and mesh draws, by class. pub fn resident_bytes(&self) -> ResidentBytes { let own = ResidentBytes { - line_buffers: self.line_buffer.as_ref().map_or(0, wgpu::Buffer::size), - uniform_buffers: buffer_bytes([Some(&self.camera_buffer)]), - default_textures: self.fallback_material_bytes, + line_buffers: self.lines.buffer.as_ref().map_or(0, wgpu::Buffer::size), + uniform_buffers: buffer_bytes([Some(&self.camera.buffer)]), + default_textures: self.plain.fallback_material_bytes, ..Default::default() }; [ Some(own), - self.game_particles.as_ref().map(|p| p.resident_bytes()), + self.particles.game.as_ref().map(|p| p.resident_bytes()), ] .into_iter() .flatten() @@ -582,7 +491,7 @@ impl ViewportRenderer { } pub fn take_dirty(&mut self) -> bool { - std::mem::replace(&mut self.dirty, false) + std::mem::replace(&mut self.targets.dirty, false) } pub fn resize(&mut self, device: &wgpu::Device, width: u32, height: u32) { @@ -591,22 +500,22 @@ impl ViewportRenderer { height.max(1), device.limits().max_texture_dimension_2d, ); - if width == self.width && height == self.height { + if width == self.targets.width && height == self.targets.height { return; } - self.width = width; - self.height = height; + self.targets.width = width; + self.targets.height = height; let (colour, colour_view, colour_display_view, depth_view) = create_targets(device, self.colour_format, width, height); - self.colour = colour; - self.colour_view = colour_view; - self.colour_display_view = colour_display_view; - self.depth_view = depth_view; + self.targets.colour = colour; + self.targets.colour_view = colour_view; + self.targets.colour_display_view = colour_display_view; + self.targets.depth_view = depth_view; self.refresh_soft_depth(); - if let Some(scene) = self.gta6_scene.as_mut() { + if let Some(scene) = self.gta6.scene.as_mut() { scene.resize(device, (width, height)); } - if let Some(deferred) = self.deferred.as_mut() { + if let Some(deferred) = self.deferred.frame.as_mut() { deferred.gbuffer = crate::game_shaders::deferred::GBuffer::new(device, width, height); deferred.hdr = crate::game_shaders::deferred::hdr_target(device, width, height); deferred.ldr = crate::game_shaders::deferred::ldr_target( @@ -616,13 +525,13 @@ impl ViewportRenderer { height, ); deferred.depth = - crate::game_shaders::deferred::DepthViews::of(self.depth_view.texture()); + crate::game_shaders::deferred::DepthViews::of(self.targets.depth_view.texture()); deferred.stale = true; deferred.refraction = None; deferred.fog_sink = None; - self.refraction_stale = self.refracts; + self.deferred.refraction_stale = self.deferred.refracts; } - self.dirty = true; + self.targets.dirty = true; } /// The lines to draw, the last `in_front` of them over everything else. @@ -633,15 +542,15 @@ impl ViewportRenderer { vertices: &[LineVertex], in_front: usize, ) { - self.line_count = vertices.len() as u32; - self.lines_in_front = in_front.min(vertices.len()) as u32; + self.lines.count = vertices.len() as u32; + self.lines.in_front = in_front.min(vertices.len()) as u32; if vertices.is_empty() { return; } let needed_bytes = std::mem::size_of_val(vertices) as wgpu::BufferAddress; - if self.line_buffer.is_none() || self.line_buffer_capacity < needed_bytes { + if self.lines.buffer.is_none() || self.lines.capacity < needed_bytes { let cap = needed_bytes.next_power_of_two().max(4096); let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("viewport-line-buffer"), @@ -649,28 +558,28 @@ impl ViewportRenderer { usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); - self.line_buffer = Some(buffer); - self.line_buffer_capacity = cap; + self.lines.buffer = Some(buffer); + self.lines.capacity = cap; } - if let Some(buffer) = &self.line_buffer { + if let Some(buffer) = &self.lines.buffer { queue.write_buffer(buffer, 0, bytemuck::cast_slice(vertices)); } } pub fn set_meshes(&mut self, meshes: Vec) { - self.meshes = meshes; + self.plain.meshes = meshes; } /// The colour the target is cleared to before anything is drawn. pub fn set_background(&mut self, rgba: [f32; 4]) { let [r, g, b, a] = rgba.map(f64::from); - self.background = wgpu::Color { r, g, b, a }; + self.env.background = wgpu::Color { r, g, b, a }; } /// The background colour, as it was set. pub fn background(&self) -> wgpu::Color { - self.background + self.env.background } /// The colour and depth target a scene drawn in [`ShadingMode::Shaded`] is prepared for: this viewport's own, with its reversed depth. @@ -695,34 +604,34 @@ impl ViewportRenderer { /// The GTA VI model [`ShadingMode::Shaded`] draws by its own programs, prepared for [`Self::game_target`] and [`Self::size`]; `None` takes it away. pub fn set_gta6_scene(&mut self, scene: Option) { - self.gta6_scene = scene; + self.gta6.scene = scene; } /// The GTA VI model [`ShadingMode::Shaded`] draws by its own programs, where one is set. pub fn gta6_scene(&self) -> Option<&crate::game_shaders::meshlets::MeshletScene> { - self.gta6_scene.as_ref() + self.gta6.scene.as_ref() } /// Take the GTA VI model away, for [`ViewportRenderer::set_gta6_scene`] to hand back or another. pub fn take_gta6_scene(&mut self) -> Option { - self.gta6_scene.take() + self.gta6.scene.take() } /// The sun and the sky a GTA VI drawable's own passes are lit by. pub fn set_gta6_sky(&mut self, sky: crate::game_shaders::meshlets::Sky) { - self.gta6_sky = sky; + self.gta6.sky = sky; } /// The light the plain modes (solid, material) light a surface by: the way towards it and how strongly it lights. A way of no length puts it where it began. /// /// ⚠ Only a key light: the head light that follows the camera and the ambient light stay as they are, and the channel and wireframe modes are unlit. pub fn set_key_light(&mut self, towards: Vec3, strength: f32) { - self.key_light = (towards, strength); + self.lighting.key_light = (towards, strength); } /// The way towards the key light and its strength, as they were set. pub fn key_light(&self) -> (Vec3, f32) { - self.key_light + self.lighting.key_light } /// The stages of the last frame the device timed, with the milliseconds each took; none where it cannot time them. @@ -738,13 +647,13 @@ impl ViewportRenderer { queue: &wgpu::Queue, camera: &OrbitCamera, ) { - let Some(scene) = &self.gta6_scene else { + let Some(scene) = &self.gta6.scene else { return; }; - let aspect = self.width as f32 / self.height as f32; + let aspect = self.targets.aspect(); let lighting = crate::game_shaders::meshlets::Lighting { view_proj: camera.view_proj(aspect), - sky: self.gta6_sky, + sky: self.gta6.sky, camera: camera.eye(), }; scene.update(queue, &lighting); @@ -758,13 +667,13 @@ impl ViewportRenderer { camera: &OrbitCamera, mode: ShadingMode, ) { - let aspect = self.width as f32 / self.height as f32; + let aspect = self.targets.aspect(); // Where the frame is anti-aliased over time, everything drawn takes the camera's offset of this frame let view_proj = camera.view_proj(aspect); let inv_view_proj = view_proj.inverse(); let eye = camera.eye(); queue.write_buffer( - &self.camera_buffer, + &self.camera.buffer, 0, bytemuck::cast_slice(&[CameraUniform { view_proj: view_proj.to_cols_array_2d(), @@ -773,10 +682,10 @@ impl ViewportRenderer { camera_misc: [ camera.near, camera.far, - self.width as f32, - self.height as f32, + self.targets.width as f32, + self.targets.height as f32, ], - key_light: key_light_uniform(self.key_light.0, self.key_light.1), + key_light: key_light_uniform(self.lighting.key_light.0, self.lighting.key_light.1), }]), ); @@ -786,10 +695,10 @@ impl ViewportRenderer { let deferred = self.deferred_in(mode); if let Some((deferred, scene)) = deferred { self.render_deferred(encoder, queue, camera, aspect, deferred, scene); - } else if let (ShadingMode::Shaded, Some(scene)) = (mode, &self.gta6_scene) { + } else if let (ShadingMode::Shaded, Some(scene)) = (mode, &self.gta6.scene) { let lighting = crate::game_shaders::meshlets::Lighting { view_proj, - sky: self.gta6_sky, + sky: self.gta6.sky, camera: eye, }; scene.update(queue, &lighting); @@ -802,20 +711,20 @@ impl ViewportRenderer { let mut pass = encoder.noted_render_pass(&wgpu::RenderPassDescriptor { label: Some("viewport-opaque-pass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: &self.colour_view, + view: &self.targets.colour_view, depth_slice: None, resolve_target: None, ops: wgpu::Operations { // What the deferred passes lit is kept, and the lines and models are drawn over it load: match deferred { Some(_) => wgpu::LoadOp::Load, - None => wgpu::LoadOp::Clear(self.background), + None => wgpu::LoadOp::Clear(self.env.background), }, store: wgpu::StoreOp::Store, }, })], depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { - view: &self.depth_view, + view: &self.targets.depth_view, depth_ops: Some(wgpu::Operations { load: match deferred { Some(_) => wgpu::LoadOp::Load, @@ -836,19 +745,20 @@ impl ViewportRenderer { multiview_mask: None, }); - let depth_tested = self.line_count - self.lines_in_front; - if let (Some(buffer), true) = (&self.line_buffer, depth_tested > 0) { - pass.set_pipeline(&self.pipeline); - pass.set_bind_group(0, &self.bind_group, &[]); + let depth_tested = self.lines.count - self.lines.in_front; + if let (Some(buffer), true) = (&self.lines.buffer, depth_tested > 0) { + pass.set_pipeline(&self.lines.pipeline); + pass.set_bind_group(0, &self.camera.bind_group, &[]); pass.set_vertex_buffer(0, buffer.slice(..)); pass.draw(0..depth_tested, 0..1); } self.draw_surface_meshes(&mut pass, mode); - self.world.draw_forward(&mut pass, &self.bind_group, mode); + self.world + .draw_forward(&mut pass, &self.camera.bind_group, mode); - if let Some(game) = &self.game_particles { - game.models.draw(&mut pass, &self.model_batches); + if let Some(game) = &self.particles.game { + game.models.draw(&mut pass, &self.particles.models); } self.draw_lines_in_front(&mut pass); } @@ -858,7 +768,7 @@ impl ViewportRenderer { let mut pass = encoder.noted_render_pass(&wgpu::RenderPassDescriptor { label: Some("viewport-transparent-pass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: &self.colour_view, + view: &self.targets.colour_view, depth_slice: None, resolve_target: None, ops: wgpu::Operations { @@ -867,7 +777,7 @@ impl ViewportRenderer { }, })], depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { - view: &self.depth_view, + view: &self.targets.depth_view, depth_ops: None, stencil_ops: None, }), @@ -875,23 +785,25 @@ impl ViewportRenderer { occlusion_query_set: None, multiview_mask: None, }); - if let Some(game) = &self.game_particles { + if let Some(game) = &self.particles.game { game.sprites - .draw(&mut pass, &self.particle_batches, &|b| !b.depth_write); - game.trails.draw(&mut pass, &self.trail_batches, &|_| true); + .draw(&mut pass, &self.particles.sprites, &|b| !b.depth_write); + game.trails + .draw(&mut pass, &self.particles.trails, &|_| true); } } self.gpu_mark(encoder, "particles"); let has_write_enabled = self - .particle_batches + .particles + .sprites .iter() .any(|b| b.depth_write && !b.instances.is_empty()); if has_write_enabled { let mut write_pass = encoder.noted_render_pass(&wgpu::RenderPassDescriptor { label: Some("viewport-transparent-pass-depth-write"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: &self.colour_view, + view: &self.targets.colour_view, depth_slice: None, resolve_target: None, ops: wgpu::Operations { @@ -900,7 +812,7 @@ impl ViewportRenderer { }, })], depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { - view: &self.depth_view, + view: &self.targets.depth_view, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store, @@ -914,9 +826,9 @@ impl ViewportRenderer { occlusion_query_set: None, multiview_mask: None, }); - if let Some(game) = &self.game_particles { + if let Some(game) = &self.particles.game { game.sprites - .draw(&mut write_pass, &self.particle_batches, &|b| b.depth_write); + .draw(&mut write_pass, &self.particles.sprites, &|b| b.depth_write); } } if let Some(timer) = &self.gpu_timer { @@ -925,13 +837,16 @@ impl ViewportRenderer { } fn draw_lines_in_front<'pass>(&'pass self, pass: &mut wgpu::RenderPass<'pass>) { - let (Some(buffer), true) = (&self.line_buffer, self.lines_in_front > 0) else { + let (Some(buffer), true) = (&self.lines.buffer, self.lines.in_front > 0) else { return; }; - pass.set_pipeline(&self.front_line_pipeline); - pass.set_bind_group(0, &self.bind_group, &[]); + pass.set_pipeline(&self.lines.front_pipeline); + pass.set_bind_group(0, &self.camera.bind_group, &[]); pass.set_vertex_buffer(0, buffer.slice(..)); - pass.draw(self.line_count - self.lines_in_front..self.line_count, 0..1); + pass.draw( + self.lines.count - self.lines.in_front..self.lines.count, + 0..1, + ); } fn draw_surface_meshes<'pass>( @@ -944,17 +859,22 @@ impl ViewportRenderer { (ShadingMode::Shaded, _) if self.deferred_in(ShadingMode::Shaded).is_some() => return, // A GTA VI model its lighting passes do not light yet is drawn as a material would (ShadingMode::Shaded, _) - if (self.gta6_scene.as_ref()).is_some_and(|scene| !scene.lit_by_game()) => + if (self.gta6.scene.as_ref()).is_some_and(|scene| !scene.lit_by_game()) => { ShadingMode::Material } - (ShadingMode::Shaded, _) if self.gta6_scene.is_some() => { - if let Some(scene) = &self.gta6_scene { + (ShadingMode::Shaded, _) if self.gta6.scene.is_some() => { + if let Some(scene) = &self.gta6.scene { scene.record(pass); // What its programs do not draw is drawn as a material, over the same depth - let rest = || scene.rest.iter().filter_map(|mesh| self.meshes.get(*mesh)); - pass.set_bind_group(0, &self.bind_group, &[]); - for pipeline in [&self.material_pipeline, &self.material_blend_pipeline] { + let rest = || { + scene + .rest + .iter() + .filter_map(|mesh| self.plain.meshes.get(*mesh)) + }; + pass.set_bind_group(0, &self.camera.bind_group, &[]); + for pipeline in [&self.plain.material, &self.plain.material_blend] { pass.set_pipeline(pipeline); for draw in rest() { self.draw_mesh(pass, draw, ShadingMode::Material); @@ -973,24 +893,24 @@ impl ViewportRenderer { }; let default_pipeline = match mode { ShadingMode::Wireframe | ShadingMode::Shaded => return, - ShadingMode::Solid => &self.solid_pipeline, - ShadingMode::Material => &self.material_pipeline, - ShadingMode::Channel => &self.channel_pipeline, + ShadingMode::Solid => &self.plain.solid, + ShadingMode::Material => &self.plain.material, + ShadingMode::Channel => &self.plain.channel, }; let material = matches!(mode, ShadingMode::Material); - pass.set_bind_group(0, &self.bind_group, &[]); - for draw in &self.meshes { + pass.set_bind_group(0, &self.camera.bind_group, &[]); + for draw in &self.plain.meshes { pass.set_pipeline(match material && draw.bump { - true => &self.bump_pipeline, + true => &self.plain.bump, false => default_pipeline, }); self.draw_mesh(pass, draw, mode); } // In the order the drawable lists them, as the game's alpha bucket is if material { - pass.set_pipeline(&self.material_blend_pipeline); + pass.set_pipeline(&self.plain.material_blend); // A normal map has no translucent texel: its alpha is no coverage. - for draw in self.meshes.iter().filter(|draw| !draw.bump) { + for draw in self.plain.meshes.iter().filter(|draw| !draw.bump) { self.draw_mesh(pass, draw, mode); } } @@ -1004,7 +924,7 @@ impl ViewportRenderer { ) { let bg = match (mode, draw.texture_bind_group.as_ref()) { (ShadingMode::Material, Some(bg)) => bg.as_ref(), - _ => self.fallback_material_bg.as_ref(), + _ => self.plain.fallback_material_bg.as_ref(), }; pass.set_bind_group(1, bg, &[]); pass.set_vertex_buffer(0, draw.vertex_buffer.slice(..)); @@ -1306,6 +1226,7 @@ fn fs_main(in: VsOut) -> @location(0) vec4 { mod build; mod game_frame; +mod state; mod world_water; pub use world_water::{FOG_PASS, SEA_COPY, SEA_PASS}; #[cfg(any(test, feature = "test-support"))] diff --git a/crates/runtime/or-renderer/src/viewport/build.rs b/crates/runtime/or-renderer/src/viewport/build.rs index ea98efd81..06e90d09f 100644 --- a/crates/runtime/or-renderer/src/viewport/build.rs +++ b/crates/runtime/or-renderer/src/viewport/build.rs @@ -224,70 +224,48 @@ impl ViewportRenderer { ); Self { colour_format, - width, - height, - dirty: true, - colour, - colour_view, - colour_display_view, - depth_view, - pipeline, - bind_group, - camera_buffer, - camera_bgl, - line_buffer: None, - line_count: 0, - lines_in_front: 0, - line_buffer_capacity: 0, - front_line_pipeline, - solid_pipeline, - material_pipeline, - material_blend_pipeline, - bump_pipeline, - channel_pipeline, - material_bgl, - fallback_material_bg: Arc::new(fallback_material_bg), - fallback_material_bytes, - meshes: Vec::new(), + targets: ViewportTargets { + width, + height, + dirty: true, + colour, + colour_view, + colour_display_view, + depth_view, + }, + camera: CameraUniformGpu { + buffer: camera_buffer, + bgl: camera_bgl, + bind_group, + }, + lines: LineOverlayGpu { + pipeline, + front_pipeline: front_line_pipeline, + buffer: None, + count: 0, + in_front: 0, + capacity: 0, + }, + plain: PlainPipelines { + solid: solid_pipeline, + material: material_pipeline, + material_blend: material_blend_pipeline, + bump: bump_pipeline, + channel: channel_pipeline, + material_bgl, + fallback_material_bg: Arc::new(fallback_material_bg), + fallback_material_bytes, + meshes: Vec::new(), + }, world, game_scene: None, - gta6_scene: None, - gta6_sky: Default::default(), - deferred: None, - deferred_scene: None, - refracts: false, - refraction_stale: false, - deferred_pipelines: Default::default(), - game_light: { - let day = crate::game_shaders::engine::EngineConstants::default(); - (day.sun_colour, day.ambient) - }, - game_sun: None, - game_seconds: None, - key_light: ( - crate::viewport::KEY_LIGHT_TOWARDS, - crate::viewport::KEY_LIGHT_STRENGTH, - ), - sky_background: false, - shadows: true, - day: None, - day_revision: 0, - game_particles: None, + gta6: Gta6GpuState::default(), + deferred: DeferredResources::default(), + lighting: SceneLighting::default(), + env: EnvironmentState::default(), + particles: ParticleGpuState::default(), + skinning: SkinningState::default(), gpu_timer: crate::gpu_timer::GpuTimer::new(device, queue), - particle_batches: Vec::new(), - trail_batches: Vec::new(), - model_batches: Vec::new(), - point_lights: Vec::new(), - spot_lights: Vec::new(), - capsule_lights: Vec::new(), - distant_lights: Default::default(), - coronas: None, - world_lights: Default::default(), - fog_volumes: Vec::new(), - sky_textures: Default::default(), - water_textures: Default::default(), - skin: Vec::new(), - background: CLEAR_COLOR, } } } diff --git a/crates/runtime/or-renderer/src/viewport/game_frame.rs b/crates/runtime/or-renderer/src/viewport/game_frame.rs index fec56d7f8..c3dc12209 100644 --- a/crates/runtime/or-renderer/src/viewport/game_frame.rs +++ b/crates/runtime/or-renderer/src/viewport/game_frame.rs @@ -17,18 +17,18 @@ impl ViewportRenderer { )], ) -> Result<(usize, Vec<(String, String)>), String> { use crate::game_shaders::deferred::{ - hdr_target, ldr_target, DeferredScene, DepthViews, FramePasses, GBuffer, Inputs, - ReflectionTarget, HDR_FORMAT, + hdr_target, ldr_target, DepthViews, FramePasses, GBuffer, Inputs, ReflectionTarget, + HDR_FORMAT, }; - if self.deferred.is_none() { - let gbuffer = GBuffer::new(device, self.width, self.height); - let depth = DepthViews::of(self.depth_view.texture()); - let hdr = hdr_target(device, self.width, self.height); + if self.deferred.frame.is_none() { + let gbuffer = GBuffer::new(device, self.targets.width, self.targets.height); + let depth = DepthViews::of(self.targets.depth_view.texture()); + let hdr = hdr_target(device, self.targets.width, self.targets.height); let ldr = ldr_target( device, self.colour_format.remove_srgb_suffix(), - self.width, - self.height, + self.targets.width, + self.targets.height, ); let reflection = ReflectionTarget::new(device, REFLECTION_WIDTH, REFLECTION_LEVELS); let passes = FramePasses::new( @@ -47,8 +47,8 @@ impl ViewportRenderer { ) .map_err(|e| e.to_string())?; let mut passes = passes; - passes.set_sky_textures(self.sky_textures.clone()); - self.deferred = Some(DeferredFrame { + passes.set_sky_textures(self.env.sky_textures.clone()); + self.deferred.frame = Some(DeferredFrame { passes, gbuffer, depth, @@ -64,8 +64,8 @@ impl ViewportRenderer { self.rebind_deferred(device, queue); // Water reads the lit frame behind it and how far that lies, which are made as the frame is drawn let has_water = surfaces.iter().any(|(_, m)| is_water(m)); - self.refracts = has_water; - self.refraction_stale = false; + self.deferred.refracts = has_water; + self.deferred.refraction_stale = false; let dressed; let surfaces = if has_water { dressed = self.dress_water(device, queue, surfaces); @@ -73,16 +73,12 @@ impl ViewportRenderer { } else { surfaces }; - let scene = DeferredScene::prepare( - device, - queue, - pack, - &mut self.deferred_pipelines, - HDR_FORMAT, - surfaces, - ); + let scene = self + .deferred + .pipelines + .prepare(device, queue, pack, HDR_FORMAT, surfaces); let report = scene.report(); - self.deferred_scene = Some(scene); + self.deferred.scene = Some(scene); Ok(report) } @@ -100,9 +96,10 @@ impl ViewportRenderer { crate::game_shaders::mesh::Material, )> { use crate::game_shaders::stand_in::constant_view; - let size = (self.width, self.height); + let size = self.size(); let frame = self .deferred + .frame .as_mut() .expect("the frame is made before its water is dressed"); let refraction = frame @@ -163,7 +160,7 @@ impl ViewportRenderer { image.srgb, ) }; - let maps = &self.water_textures; + let maps = &self.env.water_textures; if let Some(bump) = &maps.bump { inputs.push(("StaticBumpSampler", uploaded(bump))); } @@ -190,36 +187,29 @@ impl ViewportRenderer { /// Whether the scene holds water that reads a copy of the frame made before the targets were made anew, so that it is to be prepared again. pub fn deferred_needs_prepare(&self) -> bool { - self.refraction_stale + self.deferred.refraction_stale } /// Take the deferred scene away. pub fn clear_deferred(&mut self) { - self.refracts = false; - self.refraction_stale = false; - self.deferred_scene = None; - let (gbuffer, blended, shadow, fog) = &mut self.deferred_pipelines; - for cache in [gbuffer, blended, shadow, fog] { - cache.forget_textures(); - } + self.deferred.refracts = false; + self.deferred.refraction_stale = false; + self.deferred.scene = None; + self.deferred.pipelines.forget_textures(); } pub fn has_deferred(&self) -> bool { - self.deferred_scene.is_some() + self.deferred.scene.is_some() } /// Forget what was built for the deferred passes, such as pipelines the device refused or ones made for another pack. pub fn reset_deferred_pipelines(&mut self) { - self.refracts = false; - self.refraction_stale = false; - self.deferred_pipelines = Default::default(); - self.deferred = None; - self.deferred_scene = None; + self.deferred = DeferredResources::default(); } /// Make the deferred passes read the targets again where they were made anew. fn rebind_deferred(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) { - let Some(frame) = self.deferred.as_mut().filter(|frame| frame.stale) else { + let Some(frame) = self.deferred.frame.as_mut().filter(|frame| frame.stale) else { return; }; frame.passes.bind( @@ -248,8 +238,8 @@ impl ViewportRenderer { let _ = self.collect_gpu_times(device); self.rebind_deferred(device, queue); let sky = self.sky(); - let revision = self.day_revision; - let Some(frame) = self.deferred.as_mut() else { + let revision = self.env.day_revision; + let Some(frame) = self.deferred.frame.as_mut() else { return; }; if frame.reflection_of != Some(revision) { @@ -272,7 +262,7 @@ impl ViewportRenderer { pub(super) fn sky(&self) -> crate::game_shaders::sky::Sky { use crate::game_shaders::lighting::View; use crate::game_shaders::sky::Sky; - let Some(day) = &self.day else { + let Some(day) = &self.env.day else { return Sky::new(&Default::default(), Vec3::Z, Vec3::ZERO); }; let lighting = day.lighting(&View { @@ -299,42 +289,46 @@ impl ViewportRenderer { &crate::game_shaders::deferred::DeferredScene, )> { match mode { - ShadingMode::Shaded => self.deferred.as_ref().zip(self.deferred_scene.as_ref()), + ShadingMode::Shaded => self + .deferred + .frame + .as_ref() + .zip(self.deferred.scene.as_ref()), _ => None, } } /// The colour of the sun and of the ambient light the game's passes are lit by; a clear day until set. pub fn set_game_light(&mut self, sun_colour: Vec3, ambient: Vec3) { - self.game_light = (sun_colour, ambient); + self.lighting.game_light = (sun_colour, ambient); } /// The colour of the sun and of the ambient light the game's passes are lit by. pub fn game_light(&self) -> (Vec3, Vec3) { - self.game_light + self.lighting.game_light } /// The way towards the sun the game's passes are lit from; none puts it over the camera's shoulder. /// Draw the game's own sky of the moment of the day where nothing else is drawn, in place of the background colour; it needs the passes of the game and a moment of the day. pub fn set_sky_background(&mut self, on: bool) { - self.sky_background = on; + self.env.sky_background = on; } /// Whether the sun's shadow is cast and received by the game's passes; on until set. pub fn set_shadows(&mut self, on: bool) { - self.shadows = on; + self.lighting.shadows = on; } /// Whether the sun's shadow is cast and received by the game's passes. pub fn shadows(&self) -> bool { - self.shadows + self.lighting.shadows } /// What the cycle of the day gives the cascades of the sun's shadow over a world; the split as it is where no day is set. pub(crate) fn cycle_shadow(&self) -> crate::world::shadow::CycleShadow { use crate::world::shadow::{CycleShadow, CASCADE0_SCALE, DISTANCE_MULTIPLIER, SOFTNESS}; let none = CycleShadow::default(); - (self.day.as_ref()).map_or(none, |day| CycleShadow { + (self.env.day.as_ref()).map_or(none, |day| CycleShadow { distance: day.keyframe.get_or(DISTANCE_MULTIPLIER, none.distance), cascade0: day.keyframe.get_or(CASCADE0_SCALE, none.cascade0), softness: day.keyframe.get_or(SOFTNESS, none.softness), @@ -344,7 +338,7 @@ impl ViewportRenderer { /// What the frame gives a program that draws what blends in a world, each by its sampler's name: the map of what is reflected, and the map of the sun's shadow where one is `cast`. // ⚠ The fog's rays have no map here: a program that reads one reads the stand-in of a map nothing gives. pub(crate) fn forward_maps(&self, cast: bool) -> Vec<(&'static str, wgpu::TextureView)> { - let Some(frame) = &self.deferred else { + let Some(frame) = &self.deferred.frame else { return Vec::new(); }; let mut maps = vec![("ReflectionSampler", frame.reflection.view().clone())]; @@ -360,12 +354,12 @@ impl ViewportRenderer { engine: &crate::game_shaders::engine::EngineConstants, ) -> Vec<(&'static str, Vec)> { use crate::game_shaders::deferred::{lighting_values, Screen, OF_THE_SCREEN}; - let Some(frame) = &self.deferred else { + let Some(frame) = &self.deferred.frame else { return Vec::new(); }; let screen = Screen { - width: self.width, - height: self.height, + width: self.targets.width, + height: self.targets.height, near: camera.near, far: camera.far, reflection_levels: frame.reflection.levels(), @@ -379,54 +373,40 @@ impl ViewportRenderer { /// Whether the sky is what shows where nothing is drawn. pub(super) fn shows_sky(&self, deferred: &DeferredFrame) -> bool { - self.sky_background && self.day.is_some() && deferred.passes.has_sky() + self.env.sky_background && self.env.day.is_some() && deferred.passes.has_sky() } pub fn set_game_sun(&mut self, towards: Option) { - self.game_sun = towards; + self.lighting.game_sun = towards; } /// The seconds of the game's clock a frame of the game's programs is fed; none leaves the timer where a drawable alone has it. pub fn set_game_seconds(&mut self, seconds: Option) { - self.game_seconds = seconds; + self.env.game_seconds = seconds; } /// The game's clock the frames are drawn at, in seconds; nought where a host set none. pub(crate) fn game_clock(&self) -> f32 { - self.game_seconds.unwrap_or(0.0) + self.env.game_seconds.unwrap_or(0.0) } /// The moment of the day the game's passes are lit by, with the sun, the ambient light and the fog the game's own day gives it; none lights them by the colours and the sun set above. pub fn set_day(&mut self, day: Option) { - self.day = day; - self.day_revision += 1; + self.env.day = day; + self.env.day_revision += 1; } /// The skin matrices of the pose, one for each bone of the palette of the scene; none where there is no pose or no skinned surface. fn posed_bones(&self) -> Option> { - let scene = self.deferred_scene.as_ref()?; - if self.skin.is_empty() || scene.palette().is_empty() { - return None; - } - Some( - scene - .palette() - .iter() - .map(|bone| { - self.skin - .get(usize::from(*bone)) - .copied() - .unwrap_or(Mat4::IDENTITY) - }) - .collect(), - ) + let scene = self.deferred.scene.as_ref()?; + self.skinning.posed_bones(scene.palette()) } /// Draw the skinned surfaces of the game's passes in the pose `skin` gives, one skin matrix for each bone of the skeleton; an empty pose draws them at rest. /// /// ⚠ Not a change of the targets: `take_dirty` says the colour texture was made again, which its owner registers anew, and a pose changes every frame of a clip. pub fn set_skin(&mut self, skin: Vec) { - self.skin = skin; + self.skinning.matrices = skin; } /// The constants the game's shaders read, from the camera of this frame. @@ -437,7 +417,7 @@ impl ViewportRenderer { ) -> crate::game_shaders::engine::EngineConstants { let projection = perspective_reverse_z_rh(camera.fov_y, aspect.max(0.0001), camera.near, camera.far); - let lighting = self.day.as_ref().map(|day| { + let lighting = self.env.day.as_ref().map(|day| { day.lighting(&crate::game_shaders::lighting::View { camera_height: camera.eye().z, projection, @@ -448,26 +428,26 @@ impl ViewportRenderer { world: Mat4::IDENTITY, view: camera.view(), projection, - sun_direction: self.game_sun.unwrap_or_else(|| { + sun_direction: self.lighting.game_sun.unwrap_or_else(|| { crate::game_shaders::mesh::light_towards( camera.eye(), camera.target, OrbitCamera::WORLD_UP, ) }), - sun_colour: self.game_light.0, - ambient: self.game_light.1, + sun_colour: self.lighting.game_light.0, + ambient: self.lighting.game_light.1, lighting, bones: self.posed_bones(), - screen: [self.width as f32, self.height as f32], - seconds: self.game_seconds, + screen: [self.targets.width as f32, self.targets.height as f32], + seconds: self.env.game_seconds, } } /// The background as a target written through [`Self::colour_display_view`] takes it: such a view does not encode what is written, so a colour of an sRGB target is encoded here. pub(super) fn display_background(&self) -> wgpu::Color { if !self.colour_format.is_srgb() { - return self.background; + return self.env.background; } let encode = |linear: f64| { if linear <= 0.003_130_8 { @@ -477,10 +457,10 @@ impl ViewportRenderer { } }; wgpu::Color { - r: encode(self.background.r), - g: encode(self.background.g), - b: encode(self.background.b), - a: self.background.a, + r: encode(self.env.background.r), + g: encode(self.env.background.g), + b: encode(self.env.background.b), + a: self.env.background.a, } } @@ -505,7 +485,7 @@ impl ViewportRenderer { ), None => (engine.sun_colour, engine.sun_direction.z), }; - let (day_fog, ground) = self.day.as_ref().map_or((1.0, glam::Vec3::ONE), |day| { + let (day_fog, ground) = self.env.day.as_ref().map_or((1.0, glam::Vec3::ONE), |day| { ( day.keyframe.get_or("fog_hdr", 1.0), glam::Vec3::new( @@ -529,7 +509,7 @@ impl ViewportRenderer { engine: &crate::game_shaders::engine::EngineConstants, ) -> crate::game_shaders::tone::Tone { use crate::game_shaders::tone::{Tone, ToneSettings}; - match (&self.day, &engine.lighting) { + match (&self.env.day, &engine.lighting) { (Some(day), Some(lighting)) => day.tone(lighting), _ => { let lighting = crate::game_shaders::lighting::Lighting { @@ -553,11 +533,11 @@ impl ViewportRenderer { scene: &crate::game_shaders::deferred::DeferredScene, ) { let engine = self.game_constants(camera, aspect); - let occlusion = self.day.as_ref().map_or(0.0, |day| day.occlusion()); + let occlusion = self.env.day.as_ref().map_or(0.0, |day| day.occlusion()); scene.update(queue, &engine); let screen = crate::game_shaders::deferred::Screen { - width: self.width, - height: self.height, + width: self.targets.width, + height: self.targets.height, near: camera.near, far: camera.far, reflection_levels: deferred.reflection.levels(), @@ -565,11 +545,11 @@ impl ViewportRenderer { // Where the sun shines the drawable shades itself: its surfaces are cast from the sun, and the G-buffer keeps what reaches each pixel let shadow = scene .sphere() - .filter(|_| self.shadows) + .filter(|_| self.lighting.shadows) .and_then(|sphere| deferred.passes.shadow_fit(&engine, sphere)); // A world is shadowed by the four cascades fitted about what the camera sees, each cast by every entity's own technique. - let cascades = - (self.world.cascades()).filter(|_| self.shadows && deferred.passes.has_shadow()); + let cascades = (self.world.cascades()) + .filter(|_| self.lighting.shadows && deferred.passes.has_shadow()); if let Some(cascades) = cascades { let shadow = cascades.values(camera.eye()); (deferred.passes).write_shadow_with(queue, &engine, &screen, shadow); @@ -579,7 +559,7 @@ impl ViewportRenderer { } let tone = self.tone_of(&engine); // A world's exposure is measured from its lit frame by the game's own passes; one drawable alone keeps the exposure worked out for its light. - let measured = match self.world.is_fed() && self.day.is_some() { + let measured = match self.world.is_fed() && self.env.day.is_some() { true => (deferred.passes).write_meter(queue, &engine, &tone, self.game_clock()), false => None, }; @@ -591,17 +571,17 @@ impl ViewportRenderer { (occlusion, measured.is_some()), ); // The lights of a world's models and maps are drawn with the particles', each kind by its pass, where the world is drawn by the game's programs. - let of_the_world = self.world.is_fed().then_some(&self.world_lights); + let of_the_world = self.world.is_fed().then_some(&self.lighting.world_lights); let points = with( - &self.point_lights, + &self.lighting.point_lights, of_the_world.map(|lights| &lights.points[..]), ); let spots = with( - &self.spot_lights, + &self.lighting.spot_lights, of_the_world.map(|lights| &lights.spots[..]), ); let capsules = with( - &self.capsule_lights, + &self.lighting.capsule_lights, of_the_world.map(|lights| &lights.capsules[..]), ); deferred @@ -613,11 +593,12 @@ impl ViewportRenderer { deferred .passes .write_capsule_lights(queue, &engine, &screen, &capsules); - let (look, distant) = &self.distant_lights; + let (look, distant) = &self.lighting.distant_lights; (deferred.passes).write_distant_lights(queue, &engine, &screen, (*look, distant)); let glows = of_the_world.and_then(|lights| lights.coronas.as_ref()); let glows = glows.filter(|(_, glows)| !glows.is_empty()); - let coronas = (glows.or(self.coronas.as_ref())).map(|(look, c)| (*look, c.as_slice())); + let coronas = + (glows.or(self.lighting.coronas.as_ref())).map(|(look, c)| (*look, c.as_slice())); let coronas = coronas.filter(|(_, c)| !c.is_empty()); let none = ( crate::CoronaLook { @@ -634,14 +615,14 @@ impl ViewportRenderer { &engine, &screen, &self.fog_sky(&engine), - &self.fog_volumes, + &self.env.fog_volumes, ); { let mut pass = encoder.noted_render_pass(&wgpu::RenderPassDescriptor { label: Some("viewport-gbuffer-pass"), color_attachments: &deferred.gbuffer.attachments(), depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { - view: &self.depth_view, + view: &self.targets.depth_view, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(0.0), store: wgpu::StoreOp::Store, @@ -670,13 +651,15 @@ impl ViewportRenderer { scene.record_shadow(pass); }), } - deferred - .passes - .record_shadow_receive(encoder, &deferred.gbuffer, &self.depth_view); + deferred.passes.record_shadow_receive( + encoder, + &deferred.gbuffer, + &self.targets.depth_view, + ); self.gpu_mark(encoder, "shadows"); } // Water reads how far the opaque surfaces lie, where the pass that works that out has no occlusion to give - let refracts = self.refracts; + let refracts = self.deferred.refracts; // The coronas read how far the opaque surfaces lie as well let depth_wanted = refracts || has_coronas || self.draws_world_sea(); deferred @@ -689,7 +672,7 @@ impl ViewportRenderer { "viewport-lighting-pass", &deferred.hdr, wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), - &self.depth_view, + &self.targets.depth_view, None, ); deferred.passes.record_lighting(&mut pass, &engine); @@ -711,14 +694,18 @@ impl ViewportRenderer { "viewport-sky-pass", &deferred.hdr, wgpu::LoadOp::Load, - &self.depth_view, + &self.targets.depth_view, None, ); deferred.passes.record_sky(&mut pass); } self.gpu_mark(encoder, "sky"); // The water's fog gives it its colour before the copy is taken: its own pass lays the colour of the water into the frame where it lies in front of what is opaque, scaled by the light the water takes - if let (true, true, Some(sink)) = (self.refracts, scene.has_water(), &deferred.fog_sink) { + if let (true, true, Some(sink)) = ( + self.deferred.refracts, + scene.has_water(), + &deferred.fog_sink, + ) { let attachment = |view, load| { Some(wgpu::RenderPassColorAttachment { view, @@ -737,7 +724,7 @@ impl ViewportRenderer { attachment(sink, wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT)), ], depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { - view: &self.depth_view, + view: &self.targets.depth_view, depth_ops: None, stencil_ops: None, }), @@ -762,7 +749,7 @@ impl ViewportRenderer { "viewport-glow-pass", &deferred.hdr, wgpu::LoadOp::Load, - &self.depth_view, + &self.targets.depth_view, Some(wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store, @@ -778,8 +765,8 @@ impl ViewportRenderer { deferred.hdr.texture().as_image_copy(), refraction.texture().as_image_copy(), wgpu::Extent3d { - width: self.width, - height: self.height, + width: self.targets.width, + height: self.targets.height, depth_or_array_layers: 1, }, ); @@ -792,7 +779,7 @@ impl ViewportRenderer { "viewport-blended-pass", &deferred.hdr, wgpu::LoadOp::Load, - &self.depth_view, + &self.targets.depth_view, Some(wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store, @@ -807,13 +794,13 @@ impl ViewportRenderer { } self.gpu_mark(encoder, "blended"); // The fog the particles fill the air with is laid over what blends, testing the depth and leaving the stencil be - if !self.fog_volumes.is_empty() { + if !self.env.fog_volumes.is_empty() { let mut pass = over_the_frame( encoder, "viewport-fog-volume-pass", &deferred.hdr, wgpu::LoadOp::Load, - &self.depth_view, + &self.targets.depth_view, None, ); deferred.passes.record_fog(&mut pass); @@ -839,7 +826,7 @@ impl ViewportRenderer { view: if antialiased { &deferred.ldr } else { - &self.colour_display_view + &self.targets.colour_display_view }, depth_slice: None, resolve_target: None, @@ -853,7 +840,7 @@ impl ViewportRenderer { }, })], depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { - view: &self.depth_view, + view: &self.targets.depth_view, depth_ops: None, stencil_ops: None, }), @@ -873,7 +860,7 @@ impl ViewportRenderer { let mut pass = encoder.noted_render_pass(&wgpu::RenderPassDescriptor { label: Some("viewport-antialias-pass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: &self.colour_display_view, + view: &self.targets.colour_display_view, depth_slice: None, resolve_target: None, ops: wgpu::Operations { diff --git a/crates/runtime/or-renderer/src/viewport/state.rs b/crates/runtime/or-renderer/src/viewport/state.rs new file mode 100644 index 000000000..c05df3ba6 --- /dev/null +++ b/crates/runtime/or-renderer/src/viewport/state.rs @@ -0,0 +1,274 @@ +//! Cohesive per-pipeline state sub-structs owned by [`super::ViewportRenderer`]. + +use std::sync::Arc; + +use glam::{Mat4, Vec3}; + +use crate::context::CLEAR_COLOR; +use crate::viewport::{MeshDraw, KEY_LIGHT_STRENGTH, KEY_LIGHT_TOWARDS}; + +/// The colour and depth targets sized to the viewport, and whether they were recreated. +pub(super) struct ViewportTargets { + pub width: u32, + pub height: u32, + pub dirty: bool, + pub colour: wgpu::Texture, + pub colour_view: wgpu::TextureView, + /// The colour target as the post-processing writes it, which gamma-encodes by itself where the target is sRGB. + pub colour_display_view: wgpu::TextureView, + pub depth_view: wgpu::TextureView, +} + +impl ViewportTargets { + pub(super) fn aspect(&self) -> f32 { + self.width as f32 / self.height as f32 + } +} + +/// Shared camera uniform buffer, layout, and bind group read by lines, plain meshes, and forward world passes. +pub(super) struct CameraUniformGpu { + pub buffer: wgpu::Buffer, + pub bgl: Arc, + pub bind_group: wgpu::BindGroup, +} + +/// Depth-tested and always-in-front line overlay pipelines and vertex buffer. +pub(super) struct LineOverlayGpu { + pub pipeline: wgpu::RenderPipeline, + pub front_pipeline: wgpu::RenderPipeline, + pub buffer: Option, + pub count: u32, + /// How many of the lines, at the end of the buffer, draw over everything else. + pub in_front: u32, + pub capacity: u64, +} + +/// Plain (non-game-shader) mesh render pipelines, material bind group layout, fallback texture, and current draws. +pub(super) struct PlainPipelines { + pub solid: wgpu::RenderPipeline, + pub material: wgpu::RenderPipeline, + /// The material's translucent texels, drawn after every opaque one and writing no depth. + pub material_blend: wgpu::RenderPipeline, + /// The material of a mesh whose texture is a normal map. + pub bump: wgpu::RenderPipeline, + pub channel: wgpu::RenderPipeline, + pub material_bgl: Arc, + pub fallback_material_bg: Arc, + pub fallback_material_bytes: u64, + pub meshes: Vec, +} + +/// GTA VI meshlet scene and sky parameters drawn when Shaded renders a GTA VI drawable. +#[derive(Default)] +pub(super) struct Gta6GpuState { + /// A GTA VI model drawn by its own mesh and pixel programs, which Shaded draws in place of `game_scene` where there is one. + pub scene: Option, + pub sky: crate::game_shaders::meshlets::Sky, +} + +/// The game's deferred passes for the drawable Shaded shows, with the G-buffer they write and read. +pub(super) struct DeferredFrame { + pub passes: crate::game_shaders::deferred::FramePasses, + pub gbuffer: crate::game_shaders::deferred::GBuffer, + pub depth: crate::game_shaders::deferred::DepthViews, + /// Where the light is summed before it is mapped to the screen. + pub hdr: wgpu::TextureView, + /// Where the light is mapped to before the game's anti-aliasing draws it to the screen. + pub ldr: wgpu::TextureView, + /// The map of the sky that surfaces reflect, and the revision of the day it shows. + pub reflection: crate::game_shaders::deferred::ReflectionTarget, + pub reflection_of: Option, + /// Whether the targets were made again since the scene read them. + pub stale: bool, + /// A copy of the lit frame that water reads behind itself, made when a scene holds water and made again with the targets. + pub refraction: Option, + /// Where the second colour the water fog pass writes goes, which nothing reads; made with the copy. + pub fog_sink: Option, +} + +/// The pipeline caches built for the deferred scenes, for the next to take. +#[derive(Default)] +pub(super) struct DeferredPipelines { + pub gbuffer: crate::game_shaders::mesh::PipelineCache, + pub blended: crate::game_shaders::mesh::PipelineCache, + pub shadow: crate::game_shaders::mesh::PipelineCache, + pub fog: crate::game_shaders::mesh::PipelineCache, +} + +impl DeferredPipelines { + pub(super) fn forget_textures(&mut self) { + for cache in [ + &mut self.gbuffer, + &mut self.blended, + &mut self.shadow, + &mut self.fog, + ] { + cache.forget_textures(); + } + } + + pub(super) fn prepare( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + pack: &crate::game_shaders::pack::GamePack, + hdr: wgpu::TextureFormat, + surfaces: &[( + crate::game_shaders::mesh::Surface, + crate::game_shaders::mesh::Material, + )], + ) -> crate::game_shaders::deferred::DeferredScene { + let mut caches = ( + std::mem::take(&mut self.gbuffer), + std::mem::take(&mut self.blended), + std::mem::take(&mut self.shadow), + std::mem::take(&mut self.fog), + ); + let scene = crate::game_shaders::deferred::DeferredScene::prepare( + device, + queue, + pack, + &mut caches, + hdr, + surfaces, + ); + (self.gbuffer, self.blended, self.shadow, self.fog) = caches; + scene + } + + #[cfg(any(test, feature = "test-support"))] + pub(super) fn taking(taken: crate::game_shaders::states::Taken) -> Self { + use crate::game_shaders::mesh::PipelineCache; + Self { + gbuffer: PipelineCache::taking(taken), + blended: PipelineCache::taking(taken), + shadow: PipelineCache::taking(taken), + fog: PipelineCache::taking(taken), + } + } +} + +/// Deferred G-buffer frame targets, prepared deferred scene, refraction tracking, and pipeline caches. +#[derive(Default)] +pub(super) struct DeferredResources { + /// The scene drawn by the game's deferred passes, which Shaded draws in place of `game_scene` where there is one. + pub frame: Option, + pub scene: Option, + /// Whether the deferred scene holds water, which reads a copy of the frame behind it and so is prepared again when the targets are made anew. + pub refracts: bool, + pub refraction_stale: bool, + pub pipelines: DeferredPipelines, +} + +/// Sun, ambient, plain key light, shadow toggle, dynamic light collections, and coronas. +pub(super) struct SceneLighting { + /// The sun's colour and the ambient light the game's passes are lit by. + pub game_light: (Vec3, Vec3), + /// The way towards the sun the game's passes are lit from; over the camera's shoulder where none is set. + pub game_sun: Option, + /// The way towards the key light of the plain modes, and its strength. + pub key_light: (Vec3, f32), + /// Whether the sun's shadow is cast and received by the game's passes. + pub shadows: bool, + /// The lights the particles give, which light what the frame draws. + pub point_lights: Vec, + pub spot_lights: Vec, + pub capsule_lights: Vec, + pub distant_lights: ( + crate::game_shaders::distant_lights::SpriteLook, + Arc<[crate::game_shaders::distant_lights::DistantLight]>, + ), + /// The coronas of the lights, and how the pass reads the depth about each; none draws no corona. + pub coronas: Option<(crate::CoronaLook, Vec)>, + /// The lights of a world's models and maps, which light a Shaded frame of it beside the particles'. + pub world_lights: crate::world::WorldLights, +} + +impl Default for SceneLighting { + fn default() -> Self { + let day = crate::game_shaders::engine::EngineConstants::default(); + Self { + game_light: (day.sun_colour, day.ambient), + game_sun: None, + key_light: (KEY_LIGHT_TOWARDS, KEY_LIGHT_STRENGTH), + shadows: true, + point_lights: Vec::new(), + spot_lights: Vec::new(), + capsule_lights: Vec::new(), + distant_lights: Default::default(), + coronas: None, + world_lights: Default::default(), + } + } +} + +/// Time-of-day, clock, sky/water textures, fog volumes, and clear background colour. +pub(super) struct EnvironmentState { + /// The seconds of the game's clock a frame of the game's programs is fed. + pub game_seconds: Option, + /// Whether the game's own sky is drawn where nothing else is, in place of the background colour. + pub sky_background: bool, + /// The moment of the day the game's passes are lit by, which takes the place of the sun and the ambient light above. + pub day: Option, + /// How many days have been set, so that what depends on the day knows it has changed. + pub day_revision: u64, + pub fog_volumes: Vec, + /// The stars and the face of the moon the install gives, which a sky background draws at night. + pub sky_textures: crate::game_shaders::dome::SkyTextures, + /// The ripples and the foam of the game's water. + pub water_textures: crate::game_shaders::water::WaterTextures, + /// What the colour target is cleared to before anything is drawn. + pub background: wgpu::Color, +} + +impl Default for EnvironmentState { + fn default() -> Self { + Self { + game_seconds: None, + sky_background: false, + day: None, + day_revision: 0, + fog_volumes: Vec::new(), + sky_textures: Default::default(), + water_textures: Default::default(), + background: CLEAR_COLOR, + } + } +} + +/// Game-shader particle passes and their prepared sprite, trail, and model batches. +#[derive(Default)] +pub(super) struct ParticleGpuState { + /// The sprites, trails and models of the particle batches drawn with the game's own passes; none where there is no pack. + pub game: Option, + pub sprites: Vec, + pub trails: Vec, + pub models: Vec, +} + +/// Bone matrices of the active animation pose for game-shader skinned passes. +#[derive(Default)] +pub(super) struct SkinningState { + /// The skin matrices of the pose the skinned surfaces of the game's passes are drawn in, by bone of the skeleton; none draws them at rest. + pub matrices: Vec, +} + +impl SkinningState { + /// The skin matrices of the pose, one for each bone of `palette`; none where there is no pose or no skinned surface. + pub(super) fn posed_bones(&self, palette: &[u16]) -> Option> { + if self.matrices.is_empty() || palette.is_empty() { + return None; + } + Some( + palette + .iter() + .map(|bone| { + self.matrices + .get(usize::from(*bone)) + .copied() + .unwrap_or(Mat4::IDENTITY) + }) + .collect(), + ) + } +} diff --git a/crates/runtime/or-renderer/src/viewport/states_taken.rs b/crates/runtime/or-renderer/src/viewport/states_taken.rs index 872c9c45a..4976abcb5 100644 --- a/crates/runtime/or-renderer/src/viewport/states_taken.rs +++ b/crates/runtime/or-renderer/src/viewport/states_taken.rs @@ -1,7 +1,7 @@ //! What a test has the Shaded frame take of the render states its passes state, in place of what a frame is drawn with. +use super::state::DeferredPipelines; use super::ViewportRenderer; -use crate::game_shaders::mesh::PipelineCache; use crate::game_shaders::states::Taken; impl ViewportRenderer { @@ -9,11 +9,6 @@ impl ViewportRenderer { /// /// ⚠ What builds the pipelines again, such as a pack read anew, puts back what a frame is drawn with. pub fn take_states(&mut self, taken: Taken) { - self.deferred_pipelines = ( - PipelineCache::taking(taken), - PipelineCache::taking(taken), - PipelineCache::taking(taken), - PipelineCache::taking(taken), - ); + self.deferred.pipelines = DeferredPipelines::taking(taken); } } diff --git a/crates/runtime/or-renderer/src/viewport/tests.rs b/crates/runtime/or-renderer/src/viewport/tests.rs index 6f308d8c3..baabdc7d0 100644 --- a/crates/runtime/or-renderer/src/viewport/tests.rs +++ b/crates/runtime/or-renderer/src/viewport/tests.rs @@ -128,7 +128,7 @@ fn lines_drawn_in_front_show_through_a_mesh_nearer_the_camera() { renderer.render(&mut encoder, &queue, &camera, ShadingMode::Solid); encoder.copy_texture_to_buffer( wgpu::TexelCopyTextureInfo { - texture: &renderer.colour, + texture: &renderer.targets.colour, mip_level: 0, origin: wgpu::Origin3d { x: 28, y: 32, z: 0 }, aspect: wgpu::TextureAspect::All, @@ -173,7 +173,7 @@ fn image_after( camera: &OrbitCamera, mode: ShadingMode, ) -> Vec<[u8; 4]> { - let (width, height) = (renderer.width, renderer.height); + let (width, height) = renderer.size(); let row = width * 4; assert_eq!(row % wgpu::COPY_BYTES_PER_ROW_ALIGNMENT, 0); let readback = device.create_buffer(&wgpu::BufferDescriptor { @@ -185,7 +185,7 @@ fn image_after( let mut encoder = device.create_command_encoder(&Default::default()); renderer.render(&mut encoder, queue, camera, mode); encoder.copy_texture_to_buffer( - renderer.colour.as_image_copy(), + renderer.targets.colour.as_image_copy(), wgpu::TexelCopyBufferInfo { buffer: &readback, layout: wgpu::TexelCopyBufferLayout { @@ -227,7 +227,8 @@ fn middle_pixel( mode: ShadingMode, ) -> [u8; 4] { let image = image_after(device, queue, renderer, camera, mode); - image[(renderer.height / 2 * renderer.width + renderer.width / 2) as usize] + let (width, height) = renderer.size(); + image[(height / 2 * width + width / 2) as usize] } #[cfg_attr( @@ -285,7 +286,7 @@ fn water_reads_the_frame_behind_it_and_how_far_that_lies_and_is_prepared_again_w middle_pixel(&device, &queue, renderer, &camera, ShadingMode::Shaded); let error = pollster::block_on(validation.pop()); assert!(error.is_none(), "{error:?}"); - let frame = renderer.deferred.as_ref().expect("the frame is made"); + let frame = renderer.deferred.frame.as_ref().expect("the frame is made"); let half = |bytes: &[u8], at: usize| { or_io::half::half_to_f32(u16::from_le_bytes([bytes[at], bytes[at + 1]])) }; @@ -336,7 +337,7 @@ fn water_reads_the_frame_behind_it_and_how_far_that_lies_and_is_prepared_again_w // What it reflects is the map of the sky the frame is lit by, not a colour of its own let dressed = renderer.dress_water(&device, &queue, &behind); let reflected = dressed[0].1.views["ReflectionSampler"].texture(); - let sky = renderer.deferred.as_ref().expect("the frame is made"); + let sky = renderer.deferred.frame.as_ref().expect("the frame is made"); assert_eq!(reflected, sky.reflection.view().texture()); // How thick it lies is what the fog pass wrote beside the colour, and how much a ray reflects is the game's curve let thick = dressed[0].1.views["LightingSampler"].texture(); @@ -390,7 +391,7 @@ fn water_reads_the_frame_behind_it_and_how_far_that_lies_and_is_prepared_again_w .prepare_deferred(&device, &queue, &pack, &behind) .expect("the scene is prepared again"); assert!(!renderer.deferred_needs_prepare()); - let frame = renderer.deferred.as_ref().expect("the frame is made"); + let frame = renderer.deferred.frame.as_ref().expect("the frame is made"); let size = frame .refraction .as_ref() diff --git a/crates/runtime/or-renderer/src/viewport/world_fed_tests.rs b/crates/runtime/or-renderer/src/viewport/world_fed_tests.rs index 24ee6ef14..1239a5780 100644 --- a/crates/runtime/or-renderer/src/viewport/world_fed_tests.rs +++ b/crates/runtime/or-renderer/src/viewport/world_fed_tests.rs @@ -103,7 +103,11 @@ pub(super) fn targets( let mut encoder = device.create_command_encoder(&Default::default()); renderer.render(&mut encoder, queue, camera, ShadingMode::Shaded); queue.submit([encoder.finish()]); - let frame = renderer.deferred.as_ref().expect("the frame's passes"); + let frame = renderer + .deferred + .frame + .as_ref() + .expect("the frame's passes"); let read = |texture: &wgpu::Texture| { let format = crate::game_shaders::deferred::GBUFFER_FORMAT; crate::game_shaders::frame::read_back(device, queue, texture, format, SIDE).bytes diff --git a/crates/runtime/or-renderer/src/viewport/world_post_tests.rs b/crates/runtime/or-renderer/src/viewport/world_post_tests.rs index 31e47c661..8db036ae1 100644 --- a/crates/runtime/or-renderer/src/viewport/world_post_tests.rs +++ b/crates/runtime/or-renderer/src/viewport/world_post_tests.rs @@ -11,7 +11,11 @@ use crate::game_shaders::meter; /// The stops the frame's meter keeps. fn kept_stops(device: &wgpu::Device, queue: &wgpu::Queue, renderer: &ViewportRenderer) -> f32 { - let frame = renderer.deferred.as_ref().expect("the frame's passes"); + let frame = renderer + .deferred + .frame + .as_ref() + .expect("the frame's passes"); let kept = frame.passes.measured_exposure().expect("the pack meters"); let read = crate::game_shaders::frame::read_back; let texel = read(device, queue, kept, meter::EXPOSURE_FORMAT, 1).bytes; @@ -142,7 +146,11 @@ fn a_world_under_a_day_is_mapped_by_the_composite_pass_which_darkens_its_corners renderer.set_sky_background(true); renderer.prepare_game_frame(&device, &queue); prepared(&device, &queue, &mut renderer, &camera); - let frame = renderer.deferred.as_ref().expect("the frame's passes"); + let frame = renderer + .deferred + .frame + .as_ref() + .expect("the frame's passes"); assert!(frame.passes.composites(), "the pack has the composite pass"); let pixels = shown(&device, &queue, &renderer, &camera); let green = |x: usize, y: usize| f32::from(pixels[4 * (y * 128 + x) + 1]); diff --git a/crates/runtime/or-renderer/src/viewport/world_water.rs b/crates/runtime/or-renderer/src/viewport/world_water.rs index 2f80976b4..1119444d6 100644 --- a/crates/runtime/or-renderer/src/viewport/world_water.rs +++ b/crates/runtime/or-renderer/src/viewport/world_water.rs @@ -33,7 +33,7 @@ impl ViewportRenderer { lighting: Option<&Lighting>, ) -> Option>> { let given = self.world.sea_given()?; - let day = self.day.as_ref(); + let day = self.env.day.as_ref(); let cycle = cycle_water(&|name, default| { day.map_or(default, |day| day.keyframe.get_or(name, default)) }); @@ -43,7 +43,7 @@ impl ViewportRenderer { &cycle, lighting, ( - self.game_seconds.unwrap_or(0.0), + self.env.game_seconds.unwrap_or(0.0), day.map_or(12.0, |day| day.hours), ), (camera.near, camera.far), @@ -53,7 +53,7 @@ impl ViewportRenderer { /// What the frame lends the water: how far the opaque surfaces lie, the map of the sky, and the map of the sun's shadow. fn lent_to_the_water(&self) -> Option { - let frame = self.deferred.as_ref()?; + let frame = self.deferred.frame.as_ref()?; Some(Lent { depth: frame.passes.half_depth()?.clone(), reflection: frame.reflection.view().clone(), @@ -69,7 +69,7 @@ impl ViewportRenderer { ) -> Vec<(u32, wgpu::TextureView)> { let lent = self.lent_to_the_water(); let size = self.size(); - let maps = &self.water_textures; + let maps = &self.env.water_textures; let Some(sea) = self.world.sea_made(device, queue, maps) else { return Vec::new(); }; @@ -90,7 +90,7 @@ impl ViewportRenderer { let aspect = size.0 as f32 / size.1.max(1) as f32; let seen = Frustum::of(camera.view_proj(aspect)); let reach = camera.far.min(REACH); - let maps = &self.water_textures; + let maps = &self.env.water_textures; if let Some(sea) = self.world.sea_made(device, queue, maps) { let about = (&seen, camera.eye(), reach); sea.prepare(device, queue, view, size, lent, about); @@ -135,7 +135,7 @@ impl ViewportRenderer { }, })], depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { - view: &self.depth_view, + view: &self.targets.depth_view, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Load, store: kept, @@ -155,16 +155,16 @@ impl ViewportRenderer { /// Whether a frame lays the game's fog over the depth of a world: one drawn by the game's programs under a day, where the pack has the pass. pub fn world_fog_applied(&self) -> bool { - let passes = self.deferred.as_ref().map(|frame| &frame.passes); + let passes = self.deferred.frame.as_ref().map(|frame| &frame.passes); self.world.is_fed() - && self.day.is_some() + && self.env.day.is_some() && passes.is_some_and(|passes| passes.has_depth_fog()) } /// Whether a frame of a world measures its exposure from its lit frame by the game's passes, and whether the game's composite pass maps it to the screen: both for a world drawn by the game's programs under a day, each where the pack has its passes. pub fn world_post_chain(&self) -> (bool, bool) { - let passes = self.deferred.as_ref().map(|frame| &frame.passes); - let of_a_world = self.world.is_fed() && self.day.is_some(); + let passes = self.deferred.frame.as_ref().map(|frame| &frame.passes); + let of_a_world = self.world.is_fed() && self.env.day.is_some(); ( of_a_world && passes.is_some_and(|passes| passes.meters()), of_a_world && passes.is_some_and(|passes| passes.meters() && passes.composites()), @@ -185,7 +185,7 @@ impl ViewportRenderer { FOG_PASS, &deferred.hdr, wgpu::LoadOp::Load, - &self.depth_view, + &self.targets.depth_view, None, ); deferred.passes.record_depth_fog(&mut pass); diff --git a/crates/runtime/or-renderer/src/viewport/world_water_tests.rs b/crates/runtime/or-renderer/src/viewport/world_water_tests.rs index a30cf8080..d6541dda8 100644 --- a/crates/runtime/or-renderer/src/viewport/world_water_tests.rs +++ b/crates/runtime/or-renderer/src/viewport/world_water_tests.rs @@ -210,7 +210,11 @@ fn the_sea_of_a_world_is_drawn_by_the_water_effect_after_the_light_and_before_th assert_ne!(low(&with_sea), low(&without_sea), "the sea shows"); // Above the horizon both are the sky: the same light in the lit frame, which each frame then exposes by what it measures of itself. let high = |renderer: &ViewportRenderer| { - let lit = renderer.deferred.as_ref().expect("the frame's passes"); + let lit = renderer + .deferred + .frame + .as_ref() + .expect("the frame's passes"); let format = crate::game_shaders::deferred::HDR_FORMAT; let read = crate::game_shaders::frame::read_back; let texels = read(on.0, on.1, lit.hdr.texture(), format, SIDE).bytes; diff --git a/crates/title/or-title/Cargo.toml b/crates/title/or-title/Cargo.toml index df119a79d..6d18cc80d 100644 --- a/crates/title/or-title/Cargo.toml +++ b/crates/title/or-title/Cargo.toml @@ -10,8 +10,9 @@ publish.workspace = true [dependencies] # Archives and the crypto that opens them, with the executable mapped and the -# key scan spread across threads; `gta6` is the scan the GTA VI mount finds its documents by. -or-io = { workspace = true, features = ["fxc", "gta6", "mmap", "rayon"] } +# key scan spread across threads; `gta6` is the scan the GTA VI mount finds its +# documents by, and `meta` is the shared schema-snapshot / parser-names bootstrap. +or-io = { workspace = true, features = ["fxc", "gta6", "meta", "mmap", "rayon"] } serde.workspace = true thiserror.workspace = true tracing.workspace = true diff --git a/crates/title/or-title/src/schema.rs b/crates/title/or-title/src/schema.rs index dbb0c3ab0..d11253dd3 100644 --- a/crates/title/or-title/src/schema.rs +++ b/crates/title/or-title/src/schema.rs @@ -1,8 +1,10 @@ -//! Where the editor and the CLI find the metadata schema snapshot: the -//! variable, then the user's configuration directory, then, from a source -//! tree only, the shared store beside the checkout. +//! Where the editor and the CLI find and install the metadata host: mined +//! parser names, GTA VI's names snapshot, and the default schema snapshot +//! (the variable, then the user's configuration directory, then, from a source +//! tree only, the shared store beside the checkout). use std::path::{Path, PathBuf}; +use std::sync::Once; /// Names a snapshot file, or `none` to run with no schema. pub const SCHEMA_ENV: &str = "OPENRAGE_SCHEMA"; @@ -30,6 +32,16 @@ pub const GTA6_CONFIG_SNAPSHOT: &str = "gta6_schema_snapshot.bin"; /// GTA VI's snapshot in the shared store, of the same shape as [`STORE_FILE`]. pub const GTA6_STORE_FILE: &str = "or-meta/v3/gta6_schema_snapshot.bin"; +/// The subfolder under the user's configuration directory holding GTA VI's mined names table. +pub const MINED_NAMES_DIR: &str = "gta6_names"; + +/// Where the mined parser-names table sits under `config_dir`. +pub fn mined_names_path(config_dir: &Path) -> PathBuf { + config_dir + .join(MINED_NAMES_DIR) + .join(or_io::meta::binary::ragepar_names::RESOLVED_NAMES_FILE) +} + /// ⚠ A word, not an empty value: PowerShell deletes a variable assigned `""`, /// so an empty-string convention would silently mean "unset". pub const NO_SCHEMA: &[&str] = &["none", "off"]; @@ -121,6 +133,58 @@ fn gta6_candidates( paths } +/// Initialise the metadata host once per process, in the fixed order its +/// singletons require: +/// +/// 1. Register the mined parser-names file via +/// [`or_io::meta::binary::ragepar_names::load_from`] before anything can +/// resolve [`or_io::meta::binary::ragepar_names::installed`] or build the +/// default hash index. +/// 2. Discover and install GTA VI's names snapshot via +/// [`or_io::meta::install_names_snapshot`]. +/// 3. Discover and install the default schema snapshot via +/// [`or_io::meta::install_snapshot`]. +/// +/// `config_dir` is evaluated only on the first call, so repeat lookups (such as +/// per-frame UI calls) allocate nothing. +pub fn init_meta_host( + config_dir: impl FnOnce() -> Option, +) -> &'static or_io::meta::SchemaLibrary { + static INIT: Once = Once::new(); + INIT.call_once(|| { + let config = config_dir(); + let mined = config.as_deref().map(mined_names_path); + install_meta_host(config.as_deref(), mined.as_deref()); + }); + or_io::meta::default_library() +} + +fn install_meta_host(config_dir: Option<&Path>, mined_names_file: Option<&Path>) { + if let Some(path) = mined_names_file { + or_io::meta::binary::ragepar_names::load_from(path); + } + if let Some(path) = find_gta6_snapshot(config_dir) { + if let Err(error) = or_io::meta::install_names_snapshot(&path) { + tracing::warn!( + path = %path.display(), + %error, + "GTA VI's schema snapshot is unusable" + ); + } + } + let Some(path) = find_snapshot(config_dir) else { + tracing::info!("no metadata schema snapshot found; field names read as hashes"); + return; + }; + if let Err(error) = or_io::meta::install_snapshot(&path) { + tracing::warn!( + path = %path.display(), + %error, + "the schema snapshot is unusable; field names read as hashes" + ); + } +} + #[cfg(test)] mod tests { use super::*; @@ -144,4 +208,87 @@ mod tests { "one shape, one directory" ); } + + #[test] + fn mined_names_path_lives_under_gta6_names_folder() { + let config = PathBuf::from("C:/cfg"); + assert_eq!( + mined_names_path(&config), + config + .join(MINED_NAMES_DIR) + .join(or_io::meta::binary::ragepar_names::RESOLVED_NAMES_FILE) + ); + } + + #[test] + fn init_meta_host_registers_mined_names_and_snapshots_in_order_once() { + use or_io::meta::binary::hash_index::{default_hash_index, title_names}; + use or_io::meta::schema::{SchemaLibrary, StructDef}; + + let dir = tempfile::tempdir().expect("scratch config dir"); + let mined_name = "or_title_meta_host_test_name"; + let mined_hash = or_io::string_hash(mined_name.as_bytes()); + let mined_file = mined_names_path(dir.path()); + std::fs::create_dir_all(mined_file.parent().expect("parent")).expect("create dir"); + std::fs::write(&mined_file, format!("0x{mined_hash:08x}\t{mined_name}\n")) + .expect("write mined names"); + + let make_lib = |struct_name: &str| { + let mut lib = SchemaLibrary::new(); + lib.insert_struct(StructDef { + name: struct_name.to_string(), + base: None, + abstract_: false, + simple: true, + fields: Vec::new(), + source_path: String::new(), + }); + or_io::meta::encode_snapshot(&lib).expect("encode snapshot") + }; + std::fs::write( + dir.path().join(CONFIG_SNAPSHOT), + make_lib("OrTitleTestDefaultStruct"), + ) + .expect("write default snapshot"); + std::fs::write( + dir.path().join(GTA6_CONFIG_SNAPSHOT), + make_lib("OrTitleTestGta6Struct"), + ) + .expect("write gta6 snapshot"); + + let first = init_meta_host(|| Some(dir.path().to_path_buf())); + let second = init_meta_host(|| panic!("meta host bootstrap must run only once")); + assert!(std::ptr::eq(first, second)); + + assert_eq!( + default_hash_index().lookup(mined_hash), + Some(mined_name), + "mined parser names must be registered before the hash index is built" + ); + + let schema_env_unset = std::env::var(SCHEMA_ENV) + .map(|v| v.trim().is_empty()) + .unwrap_or(true); + let gta6_env_unset = std::env::var(GTA6_SCHEMA_ENV) + .map(|v| v.trim().is_empty()) + .unwrap_or(true); + if schema_env_unset { + assert!(first.structs.contains_key("OrTitleTestDefaultStruct")); + if gta6_env_unset { + assert!(or_io::meta::names_library() + .is_some_and(|l| l.structs.contains_key("OrTitleTestGta6Struct"))); + let _guard = title_names(); + let idx = default_hash_index(); + assert_eq!( + idx.lookup(or_io::literal_string_hash(b"OrTitleTestGta6Struct")), + Some("OrTitleTestGta6Struct") + ); + assert_eq!( + idx.lookup(or_io::literal_string_hash(b"OrTitleTestDefaultStruct")), + Some("OrTitleTestDefaultStruct") + ); + assert_eq!(idx.lookup(mined_hash), Some(mined_name)); + } + } + } } diff --git a/crates/tools/or-cli/src/gta6/frame_pass.rs b/crates/tools/or-cli/src/gta6/frame_pass.rs index 14f24c607..a9eb57ef2 100644 --- a/crates/tools/or-cli/src/gta6/frame_pass.rs +++ b/crates/tools/or-cli/src/gta6/frame_pass.rs @@ -86,19 +86,21 @@ pub fn gta6_table_program(file: &Sgd5File, table: Gta6Table) -> Result Result { let native = rdna_bind::native(pixel).map_err(|why| why.to_string())?; let lowered = rdna_bind::kept::lower(&native, &BTreeSet::new()).map_err(|why| said("pixel", &why))?; let mut stage = - feed_table(&native, lowered, table, effect).map_err(|why| said("pixel", &why))?; + feed_table(&native, lowered, table, effect, hardware).map_err(|why| said("pixel", &why))?; let slots = (native.program.inputs.iter()) .map(|input| u32::from(input.slot)) .collect(); @@ -136,19 +138,22 @@ pub fn gta6_post_programs<'f>( /// A pass that draws a step of the frame after its lighting, of the inflated containers /// `vertex` and `pixel`, translated and linked, with what fills each binding; `tables` are the -/// programs' own and `effects` the first table of the effect that runs each. `Err` says why the -/// renderer cannot be handed it. +/// programs' own, `effects` the first table of the effect that runs each, and `hardware` whether +/// the drawing adapter is hardware rather than software. `Err` says why the renderer cannot be +/// handed it. pub fn translate_gta6_draw_step( vertex: &[u8], pixel: &[u8], tables: [&Sgd5Table; 2], effects: [&Sgd5Table; 2], + hardware: bool, ) -> Result { let native = |container: &[u8]| rdna_bind::native(container).map_err(|why| why.to_string()); let (first, second) = (native(vertex)?, native(pixel)?); let stage = |native: &rdna_bind::Native, at: usize, word: &str| -> Result { let lowered = lighting::lower(native, tables[at]).map_err(|why| said(word, &why))?; - feed_table(native, lowered, tables[at], effects[at]).map_err(|why| said(word, &why)) + feed_table(native, lowered, tables[at], effects[at], hardware) + .map_err(|why| said(word, &why)) }; let (mut vertex, mut pixel) = (stage(&first, 0, "vertex")?, stage(&second, 1, "pixel")?); // The pixel program reads each parameter at the register the two stages' signature gives it. @@ -182,16 +187,21 @@ pub fn gta6_step_program<'f>(file: &'f Sgd5File, name: &str) -> Result<&'f Sgd5P } /// The compute program of the inflated container `compute` translated as a step of the frame, -/// with what fills each binding; `table` is the program's own. `Err` says why the renderer -/// cannot be handed it. -pub fn translate_gta6_compute_step(compute: &[u8], table: &Sgd5Table) -> Result { +/// with what fills each binding; `table` is the program's own, and `hardware` whether the +/// drawing adapter is hardware rather than software. `Err` says why the renderer cannot be +/// handed it. +pub fn translate_gta6_compute_step( + compute: &[u8], + table: &Sgd5Table, + hardware: bool, +) -> Result { let native = rdna_bind::native(compute).map_err(|why| why.to_string())?; if native.program.kind != or_shader_front::dxil::ShaderKind::Compute { return Err("it is no compute program".to_string()); } let lowered = lighting::lower(&native, table).map_err(|why| said("compute", &why))?; // No effect's table tells a material's constants from the frame's here: the program's own. - feed_table(&native, lowered, table, table).map_err(|why| said("compute", &why)) + feed_table(&native, lowered, table, table, hardware).map_err(|why| said("compute", &why)) } fn said(stage: &str, why: &dyn std::fmt::Display) -> String { @@ -200,7 +210,8 @@ fn said(stage: &str, why: &dyn std::fmt::Display) -> String { /// The lighting pass of the inflated containers `vertex` and `pixel` translated, with what /// fills each binding; `tables` are the programs' own and `effects` the first table of the -/// effect that runs each. The pass lights the pixels `lights` says and discards the rest. +/// effect that runs each. The pass lights the pixels `lights` says and discards the rest; +/// `hardware` says whether the drawing adapter is hardware rather than software. /// `Err` says why the renderer cannot be handed it. pub fn translate_gta6_frame_pass( vertex: &[u8], @@ -208,16 +219,17 @@ pub fn translate_gta6_frame_pass( tables: [&Sgd5Table; 2], effects: [&Sgd5Table; 2], lights: &Lights, + hardware: bool, ) -> Result { let native = |container: &[u8]| rdna_bind::native(container).map_err(|why| why.to_string()); let (first, second) = (native(vertex)?, native(pixel)?); let lowered = lighting::lower(&second, tables[1]).map_err(|why| said("pixel", &why))?; - let mut pixel = - feed(&second, lowered, tables[1], effects[1]).map_err(|why| said("pixel", &why))?; + let mut pixel = feed(&second, lowered, tables[1], effects[1], hardware) + .map_err(|why| said("pixel", &why))?; let lowered = rdna_bind::kept::lower(&first, &BTreeSet::new()).map_err(|why| said("vertex", &why))?; - let mut vertex = - feed(&first, lowered, tables[0], effects[0]).map_err(|why| said("vertex", &why))?; + let mut vertex = feed(&first, lowered, tables[0], effects[0], hardware) + .map_err(|why| said("vertex", &why))?; let linked = link::link( std::sync::Arc::make_mut(&mut vertex.module), std::sync::Arc::make_mut(&mut pixel.module), @@ -278,7 +290,7 @@ pub(crate) fn cmd_scan_frame_pass(args: &[String]) -> Result<(), String> { ); }; // As the app binds for a hardware adapter: no stage is refused for its size. - or_shader_front::rdna_bind::shading::drawn_by_hardware(true); + let hardware = true; let offset = crate::rpf::parse_offset(offset)?; let file = std::fs::File::open(path).map_err(|e| format!("open({path}): {e}"))?; let (_, bytes) = read_rpf9_body(&file, offset, limit).map_err(|e| e.to_string())?; @@ -292,7 +304,7 @@ pub(crate) fn cmd_scan_frame_pass(args: &[String]) -> Result<(), String> { let stream = bytes.get(program.stream.clone()); let inflated = stream.and_then(|stream| program.inflate(stream).ok()); let inflated = inflated.ok_or("the program does not inflate")?; - let stage = translate_gta6_compute_step(&inflated, &program.variables)?; + let stage = translate_gta6_compute_step(&inflated, &program.variables, hardware)?; return said_stage("compute", &stage, folder.as_deref(), &name); } if let Some(name) = post { @@ -306,7 +318,7 @@ pub(crate) fn cmd_scan_frame_pass(args: &[String]) -> Result<(), String> { return Err("a program does not inflate".to_string()); }; let tables = [&vertex.variables, &pixel.variables]; - let pass = translate_gta6_draw_step(&a, &b, tables, [effect, effect])?; + let pass = translate_gta6_draw_step(&a, &b, tables, [effect, effect], hardware)?; said_stage("vertex", &pass.vertex, folder.as_deref(), &name)?; return said_stage("pixel", &pass.pixel, folder.as_deref(), &name); } @@ -322,8 +334,8 @@ pub(crate) fn cmd_scan_frame_pass(args: &[String]) -> Result<(), String> { let started = std::time::Instant::now(); let tables = [&vertex.variables, &pixel.variables]; let lights = Lights::of(kind as u32, &LIT_KINDS); - let pass = - translate_gta6_frame_pass(&a, &b, tables, [screen, lit], &lights).inspect_err(|_| { + let pass = translate_gta6_frame_pass(&a, &b, tables, [screen, lit], &lights, hardware) + .inspect_err(|_| { // What the pixel stage picks by a number, for the binding a refusal is about. let lowered = rdna_bind::native(&b) .ok() diff --git a/crates/tools/or-cli/src/gta6/shading.rs b/crates/tools/or-cli/src/gta6/shading.rs index 3ff5be5cd..ff577818f 100644 --- a/crates/tools/or-cli/src/gta6/shading.rs +++ b/crates/tools/or-cli/src/gta6/shading.rs @@ -106,16 +106,18 @@ pub fn is_gta6_forward_pass(first: &[u8], pixel: &[u8]) -> bool { } /// The pass of the inflated containers `first` and `pixel` translated, with what fills each -/// binding; the tables are the programs' own, in that order, and `effect` is the first table of -/// the effect that runs them. `Err` says why the renderer cannot be handed it. +/// binding; the tables are the programs' own, in that order, `effect` is the first table of +/// the effect that runs them, and `hardware` whether the drawing adapter is hardware rather than +/// software. `Err` says why the renderer cannot be handed it. pub fn translate_gta6_shading( first: &[u8], pixel: &[u8], tables: [&Sgd5Table; 2], effect: &Sgd5Table, + hardware: bool, ) -> Result { - let pixel = translate_gta6_pixel_stage(pixel, tables[1], effect)?; - translate_gta6_mesh_stage(first, tables[0], effect, &pixel) + let pixel = translate_gta6_pixel_stage(pixel, tables[1], effect, hardware)?; + translate_gta6_mesh_stage(first, tables[0], effect, &pixel, hardware) } /// The pixel stage of a model's shading pass, which several passes of an effect share: the @@ -140,11 +142,13 @@ fn said(stage: &str, why: &dyn std::fmt::Display) -> String { } /// The inflated container `pixel` translated as the pixel stage of a shading pass; `table` is -/// its own and `effect` the first table of the effect that runs it. +/// its own, `effect` the first table of the effect that runs it, and `hardware` whether the +/// drawing adapter is hardware rather than software. pub fn translate_gta6_pixel_stage( pixel: &[u8], table: &Sgd5Table, effect: &Sgd5Table, + hardware: bool, ) -> Result { let pixel = native(pixel)?; // A forward stage whose blend no effect states is refused before it is lowered, as the @@ -158,12 +162,12 @@ pub fn translate_gta6_pixel_stage( let half_slots = fragment.half_slots.clone(); let (stage, merged) = match stage_budget(false) { Some(budget) => { - let (stage, fitted) = feed_within(&pixel, fragment, table, effect, &budget) + let (stage, fitted) = feed_within(&pixel, fragment, table, effect, &budget, hardware) .map_err(|why| said("pixel", &why))?; (stage, fitted.merged) } None => ( - feed(&pixel, fragment, table, effect).map_err(|why| said("pixel", &why))?, + feed(&pixel, fragment, table, effect, hardware).map_err(|why| said("pixel", &why))?, Vec::new(), ), }; @@ -176,12 +180,14 @@ pub fn translate_gta6_pixel_stage( } /// The pass whose mesh program is the inflated container `first` and whose pixel stage is -/// `pixel`; `table` is the mesh program's own. +/// `pixel`; `table` is the mesh program's own, and `hardware` whether the drawing adapter is +/// hardware rather than software. pub fn translate_gta6_mesh_stage( first: &[u8], table: &Sgd5Table, effect: &Sgd5Table, pixel: &Gta6PixelStage, + hardware: bool, ) -> Result { let first = native(first)?; // The mesh stage exports as halves what the pixel stage reads as halves. @@ -193,12 +199,12 @@ pub fn translate_gta6_mesh_stage( lowered_to_feed(&first, &halves, table, effect).map_err(|why| said("mesh", &why))?; let (mut mesh, mut merged) = match stage_budget(true) { Some(budget) => { - let (mesh, fitted) = feed_within(&first, geometry, table, effect, &budget) + let (mesh, fitted) = feed_within(&first, geometry, table, effect, &budget, hardware) .map_err(|why| said("mesh", &why))?; (mesh, fitted.merged) } None => ( - feed(&first, geometry, table, effect).map_err(|why| said("mesh", &why))?, + feed(&first, geometry, table, effect, hardware).map_err(|why| said("mesh", &why))?, Vec::new(), ), }; @@ -297,10 +303,12 @@ pub(crate) fn cmd_scan_shading(args: &[String]) -> Result<(), String> { _ => None, }; // As the app binds for a hardware adapter: no stage is refused for its size. - if let Some(at) = args.iter().position(|a| a == "--hardware") { + let hardware = if let Some(at) = args.iter().position(|a| a == "--hardware") { args.remove(at); - or_shader_front::rdna_bind::shading::drawn_by_hardware(true); - } + true + } else { + false + }; let [path, offset, wanted] = args.as_slice() else { return Err( "usage: rpf scan-shading [--wgsl ] [--hardware] [--limit ]" @@ -362,7 +370,7 @@ pub(crate) fn cmd_scan_shading(args: &[String]) -> Result<(), String> { } let started = std::time::Instant::now(); let tables = [&first.variables, &pixel.variables]; - match translate_gta6_shading(&a, &b, tables, &effect.parameters) { + match translate_gta6_shading(&a, &b, tables, &effect.parameters, hardware) { Err(why) => report_untranslated_pass(&why, &a, &b, tables), Ok(pass) => report_translated_pass( &pass, @@ -741,12 +749,14 @@ pub fn mesh_streams( first: &[u8], table: &Sgd5Table, effect: &Sgd5Table, + hardware: bool, ) -> Result, String> { let first = native(first)?; // Which slots cross as halves is the pixel stage's to say, and it moves no read of a stream. let geometry = lowered_to_feed(&first, &BTreeSet::new(), table, effect) .map_err(|why| said("mesh", &why))?; - let stage = feed(&first, geometry, table, effect).map_err(|why| said("mesh", &why))?; + let stage = + feed(&first, geometry, table, effect, hardware).map_err(|why| said("mesh", &why))?; Ok(stage.streams) } @@ -1001,7 +1011,7 @@ pub(crate) fn cmd_scan_effect_use(args: &[String]) -> Result<(), String> { let tables = [&first.variables, &pixel.variables]; // A translation that panics is a refusal of its own, and the census goes on. let translated = std::panic::catch_unwind(|| { - translate_gta6_shading(&a, &b, tables, &effect.parameters) + translate_gta6_shading(&a, &b, tables, &effect.parameters, false) }); match translated { Ok(Ok(pass)) => passes.push(pass), diff --git a/crates/tools/or-cli/src/lib.rs b/crates/tools/or-cli/src/lib.rs index 421927d2e..289a49af5 100644 --- a/crates/tools/or-cli/src/lib.rs +++ b/crates/tools/or-cli/src/lib.rs @@ -95,7 +95,6 @@ pub use or_shader_front::rdna_bind::instances::{ }; pub use or_shader_front::rdna_bind::ped_layers as gta6_ped_layers; pub use or_shader_front::rdna_bind::ped_skin as gta6_ped_skin; -pub use or_shader_front::rdna_bind::shading::drawn_by_hardware as gta6_drawn_by_hardware; pub use or_shader_front::rdna_bind::shading::LAYER_TILE_ENTRIES as GTA6_LAYER_TILE_ENTRIES; pub use or_shader_front::rdna_bind::terrain as gta6_terrain; pub use project::resource::check_resource_folder; diff --git a/crates/tools/or-cli/src/meta.rs b/crates/tools/or-cli/src/meta.rs index 2a933d332..730194791 100644 --- a/crates/tools/or-cli/src/meta.rs +++ b/crates/tools/or-cli/src/meta.rs @@ -1146,25 +1146,7 @@ impl Options { /// The metadata schema, installed on first use from where `or_title::schema` finds it. pub(crate) fn schema() -> &'static or_io::meta::SchemaLibrary { - static FOUND: std::sync::Once = std::sync::Once::new(); - FOUND.call_once(|| { - if let Some(path) = or_title::schema::find_gta6_snapshot(config_dir().as_deref()) { - if let Err(error) = or_io::meta::install_names_snapshot(&path) { - tracing::warn!(path = %path.display(), %error, "GTA VI's schema snapshot is unusable"); - } - } - let Some(path) = or_title::schema::find_snapshot(config_dir().as_deref()) else { - return; - }; - if let Err(e) = or_io::meta::install_snapshot(&path) { - tracing::warn!( - path = %path.display(), - error = %e, - "the schema snapshot is unusable; field names read as hashes" - ); - } - }); - or_io::meta::default_library() + or_title::schema::init_meta_host(config_dir) } pub(crate) fn has_schema() -> bool { diff --git a/crates/tools/or-cli/tests/gta6_shaded_stage_census.rs b/crates/tools/or-cli/tests/gta6_shaded_stage_census.rs index 28d4b679d..95ecd88b6 100644 --- a/crates/tools/or-cli/tests/gta6_shaded_stage_census.rs +++ b/crates/tools/or-cli/tests/gta6_shaded_stage_census.rs @@ -206,8 +206,9 @@ fn translate_effect(bytes: &[u8], file: &Sgd5File, effect: &Sgd5Effect, tally: & } seen.insert(first.at); let stage = pixels.entry(pixel.at).or_insert_with(|| { - let stage = - guarded(|| translate_gta6_pixel_stage(&fragment, &pixel.variables, parameters)); + let stage = guarded(|| { + translate_gta6_pixel_stage(&fragment, &pixel.variables, parameters, false) + }); (tally.entry(("own", "pixel")).or_default()) .count(stage.as_ref().map(|_| ()).map_err(Clone::clone)); stage @@ -218,8 +219,9 @@ fn translate_effect(bytes: &[u8], file: &Sgd5File, effect: &Sgd5Effect, tally: & .or_default() += 1; continue; }; - let pass = - guarded(|| translate_gta6_mesh_stage(&mesh, &first.variables, parameters, stage)); + let pass = guarded(|| { + translate_gta6_mesh_stage(&mesh, &first.variables, parameters, stage, false) + }); draws |= pass.is_ok(); (tally.entry(("own", "vertex")).or_default()).count(pass.map(|_| ())); } diff --git a/crates/tools/or-shader-front/src/rdna_bind/forward_frame.rs b/crates/tools/or-shader-front/src/rdna_bind/forward_frame.rs index 8bfc2d25e..c3394df56 100644 --- a/crates/tools/or-shader-front/src/rdna_bind/forward_frame.rs +++ b/crates/tools/or-shader-front/src/rdna_bind/forward_frame.rs @@ -253,12 +253,19 @@ return vec4(f32(s25_), f32(cb1_[3].w), f32(cb2_[98].x), f32(cb3_.x)); lowered("cb0_[114].w"), &table, &Sgd5Table::default(), + false, ); assert_eq!(fed.err(), Some(Unfed::Loop(DIRECTIONAL_LIGHT))); // A place of the view's record nothing states (+0x40) is refused by the record's name. let names = [VIEW_LIGHTING, CASCADES, FRAME_RECORD, PROBES]; let (stage, table) = native(&names); - let fed = feed(&stage, lowered("cb0_[4].x"), &table, &Sgd5Table::default()); + let fed = feed( + &stage, + lowered("cb0_[4].x"), + &table, + &Sgd5Table::default(), + false, + ); assert_eq!(fed.err(), Some(Unfed::Unread(VIEW_LIGHTING))); } } diff --git a/crates/tools/or-shader-front/src/rdna_bind/kept.rs b/crates/tools/or-shader-front/src/rdna_bind/kept.rs index 1accada7d..1a1a54681 100644 --- a/crates/tools/or-shader-front/src/rdna_bind/kept.rs +++ b/crates/tools/or-shader-front/src/rdna_bind/kept.rs @@ -3,28 +3,176 @@ use std::io::{Read, Write}; use std::path::PathBuf; -use std::sync::OnceLock; +use std::sync::{Arc, Mutex, PoisonError}; use or_io::gta5::shaders::sgd5::Sgd5File; use super::Native; -use crate::rdna::Lowered; -use crate::rdna_cache::{Cache, Cached}; +use crate::rdna::{Lowered, Options, Program}; +use crate::rdna_cache::{Cache, Cached, Key}; /// The stored form of the containers: a change to what a container reads as takes a new number. const CONTAINERS: u32 = 1; -static TRANSLATIONS: OnceLock = OnceLock::new(); +struct ActiveCache { + dir: Option, + cache: Arc, + /// Entries cached in memory before a disk folder was configured, so configuring one later + /// preserves and persists them without re-translating. + pre_disk: Vec<(Key, Arc)>, +} + +struct TranslationStore { + inner: Mutex>, +} + +impl TranslationStore { + const fn new() -> Self { + Self { + inner: Mutex::new(None), + } + } -/// Keep translations in files under `dir` as well as in memory. The first call of a process -/// decides, and one made after a program was lowered changes nothing. + fn keep_in(&self, dir: PathBuf) { + let mut guard = self.inner.lock().unwrap_or_else(PoisonError::into_inner); + match guard.as_mut() { + Some(active) if active.dir.as_ref() == Some(&dir) => {} + Some(active) => { + let next = Arc::new(Cache::on_disk(dir.clone())); + for (key, cached) in active.pre_disk.drain(..) { + next.put(key, (*cached).clone()); + } + active.dir = Some(dir); + active.cache = next; + } + None => { + *guard = Some(ActiveCache { + dir: Some(dir.clone()), + cache: Arc::new(Cache::on_disk(dir)), + pre_disk: Vec::new(), + }); + } + } + } + + fn active(&self) -> (Arc, bool) { + let mut guard = self.inner.lock().unwrap_or_else(PoisonError::into_inner); + let active = guard.get_or_insert_with(|| ActiveCache { + dir: None, + cache: Arc::new(Cache::in_memory()), + pre_disk: Vec::new(), + }); + (Arc::clone(&active.cache), active.dir.is_some()) + } + + fn record_pre_disk(&self, cache: &Arc, key: Key, cached: &Arc) { + let seed = { + let mut guard = self.inner.lock().unwrap_or_else(PoisonError::into_inner); + let Some(active) = guard.as_mut() else { + return; + }; + if active.dir.is_none() { + if !active.pre_disk.iter().any(|(kept, _)| *kept == key) { + active.pre_disk.push((key, Arc::clone(cached))); + } + None + } else if !Arc::ptr_eq(&active.cache, cache) { + // `keep_in` raced while this entry was translating in memory. + Some(Arc::clone(&active.cache)) + } else { + None + } + }; + if let Some(disk) = seed { + disk.put(key, (**cached).clone()); + } + } + + fn get_or_translate(&self, program: &Program, options: &Options) -> (Arc, bool) { + let (cache, has_dir) = self.active(); + let (cached, hit) = cache.get_or_translate(program, options); + if !has_dir { + self.record_pre_disk(&cache, Key::of(program, options), &cached); + } + (cached, hit) + } + + fn lower( + &self, + native: &Native, + half_slots: &std::collections::BTreeSet, + ) -> Result { + super::lower_by(half_slots, |options| { + match &*self.get_or_translate(&native.program, options).0 { + Cached::Translated(lowered) => Ok((**lowered).clone()), + Cached::Refused { message, .. } => Err(message.clone()), + } + }) + } + + fn lower_unless( + &self, + native: &Native, + half_slots: &std::collections::BTreeSet, + refused: &dyn Fn(&Lowered) -> Option, + ) -> Result { + // ⚠ The second lowering `lower_by` makes states floats for the textures it loads, the kind + // the first declares them as where none is stated: both bind the same resources, so a + // refusal by its bindings of the first is the second's, and neither is optimised. + super::lower_by(half_slots, |options| { + let (cache, has_dir) = self.active(); + match cache.get_or_translate_unless(&native.program, options, refused) { + Ok((cached, _)) => { + if !has_dir { + self.record_pre_disk(&cache, Key::of(&native.program, options), &cached); + } + match &*cached { + Cached::Translated(lowered) => Ok((**lowered).clone()), + Cached::Refused { message, .. } => Err(message.clone()), + } + } + Err(why) => { + if !has_dir && !options.unoptimised { + let unoptimised = Options { + unoptimised: true, + ..options.clone() + }; + let key = Key::of(&native.program, &unoptimised); + if let Some(cached) = cache.get(&key) { + self.record_pre_disk(&cache, key, &cached); + } + } + Err(why) + } + } + }) + } +} + +static TRANSLATIONS: TranslationStore = TranslationStore::new(); + +/// Keep translations in files under `dir` as well as in memory. Calling this after a program was +/// already lowered upgrades the cache to `dir` while preserving entries already cached in memory. pub fn keep_translations_in(dir: impl Into) { - let _ = TRANSLATIONS.set(Cache::on_disk(dir)); + TRANSLATIONS.keep_in(dir.into()); +} + +/// Handle to the translations a session keeps, reading the current backing cache on each lookup. +pub(super) struct Translations; + +impl Translations { + pub(super) fn get_or_translate( + &self, + program: &Program, + options: &Options, + ) -> (Arc, bool) { + TRANSLATIONS.get_or_translate(program, options) + } } /// The translations a session keeps, of whatever options a program is lowered under. -pub(super) fn translations() -> &'static Cache { - TRANSLATIONS.get_or_init(Cache::in_memory) +pub(super) fn translations() -> Translations { + Translations } pub use super::walk_file::{shadow_walk, LoweredWalk, WALKS}; @@ -35,13 +183,7 @@ pub fn lower( native: &Native, half_slots: &std::collections::BTreeSet, ) -> Result { - let cache = TRANSLATIONS.get_or_init(Cache::in_memory); - super::lower_by(half_slots, |options| { - match &*cache.get_or_translate(&native.program, options).0 { - Cached::Translated(lowered) => Ok((**lowered).clone()), - Cached::Refused { message, .. } => Err(message.clone()), - } - }) + TRANSLATIONS.lower(native, half_slots) } /// [`lower`], where `refused` says why the caller refuses the lowering it feeds a stage from @@ -51,19 +193,7 @@ pub fn lower_unless( half_slots: &std::collections::BTreeSet, refused: &dyn Fn(&Lowered) -> Option, ) -> Result { - let cache = TRANSLATIONS.get_or_init(Cache::in_memory); - // ⚠ The second lowering `lower_by` makes states floats for the textures it loads, the kind - // the first declares them as where none is stated: both bind the same resources, so a - // refusal by its bindings of the first is the second's, and neither is optimised. - super::lower_by(half_slots, |options| { - match &*cache - .get_or_translate_unless(&native.program, options, refused)? - .0 - { - Cached::Translated(lowered) => Ok((**lowered).clone()), - Cached::Refused { message, .. } => Err(message.clone()), - } - }) + TRANSLATIONS.lower_unless(native, half_slots, refused) } /// The effect containers of an archive, each with its offset there, as the bytes a file holds. @@ -81,3 +211,78 @@ pub fn decode_containers(bytes: &[u8]) -> Option> { let (form, containers): (u32, Vec<(u64, Sgd5File)>) = bincode::deserialize(&plain).ok()?; (form == CONTAINERS).then_some(containers) } + +#[cfg(test)] +mod tests { + use std::collections::BTreeSet; + use std::path::Path; + + use super::*; + use crate::dxil::ShaderKind; + + const S_ENDPGM: u32 = 0xBF81_0000; + + fn native_program(words: Vec) -> Native { + Native { + program: Program { + kind: ShaderKind::Pixel, + slot: 0, + words, + wave32: false, + inputs: Vec::new(), + vertex_inputs: Vec::new(), + position_read: 0, + front_face: false, + launch: None, + }, + records: Vec::new(), + inputs: Vec::new(), + outputs: Vec::new(), + } + } + + fn cache_file(dir: &Path, key: &Key) -> PathBuf { + let hex = key.hex(); + dir.join(&hex[..2]).join(&hex[2..]) + } + + #[test] + fn lowering_before_keep_translations_in_still_persists_and_reads_from_dir() { + let dir = tempfile::tempdir().unwrap(); + let first = native_program(vec![S_ENDPGM]); + let second = native_program(vec![S_ENDPGM, S_ENDPGM]); + let options = Options::default(); + let first_key = Key::of(&first.program, &options); + let second_key = Key::of(&second.program, &options); + + // Lower before configuring a disk directory: cached in memory first. + let store = TranslationStore::new(); + let _ = store.lower(&first, &BTreeSet::new()); + let (_, hit_in_memory) = store.get_or_translate(&first.program, &options); + assert!(hit_in_memory); + assert!(!cache_file(dir.path(), &first_key).exists()); + + // Late configuration upgrades to disk, preserving and persisting the pre-disk entry. + store.keep_in(dir.path().to_path_buf()); + assert!(cache_file(dir.path(), &first_key).is_file()); + let (_, preserved) = store.get_or_translate(&first.program, &options); + assert!(preserved); + + // Calling keep_in with the same folder is a no-op and keeps in-memory entries. + store.keep_in(dir.path().to_path_buf()); + let (_, still_cached) = store.get_or_translate(&first.program, &options); + assert!(still_cached); + + // Subsequent lowerings persist to the configured folder too. + let _ = store.lower(&second, &BTreeSet::new()); + assert!(cache_file(dir.path(), &second_key).is_file()); + + // A fresh store that also lowers before keep_in reads existing entries from dir afterwards. + let third = native_program(vec![S_ENDPGM, S_ENDPGM, S_ENDPGM]); + let fresh = TranslationStore::new(); + let _ = fresh.lower(&third, &BTreeSet::new()); + fresh.keep_in(dir.path().to_path_buf()); + let (_, hit_from_disk) = fresh.get_or_translate(&second.program, &options); + assert!(hit_from_disk); + } +} diff --git a/crates/tools/or-shader-front/src/rdna_bind/lighting.rs b/crates/tools/or-shader-front/src/rdna_bind/lighting.rs index ad7769982..c5915a10e 100644 --- a/crates/tools/or-shader-front/src/rdna_bind/lighting.rs +++ b/crates/tools/or-shader-front/src/rdna_bind/lighting.rs @@ -565,7 +565,7 @@ mod tests { let names = [VIEW_LIGHTING, LIGHTS, FRAME_RECORD, DIRECTIONAL_LIGHT]; let (native, table) = exporting(&LIGHTING, &names); let none = Sgd5Table::default(); - let stage = feed(&native, lowered(OCCLUSION), &table, &none) + let stage = feed(&native, lowered(OCCLUSION), &table, &none, false) .expect("a lighting stage is fed whole"); let feeds: Vec = stage.feeds.into_iter().map(|fed| fed.feed).collect(); assert_eq!(feeds[0], Feed::Frame(Frame::ViewLighting)); @@ -574,29 +574,30 @@ mod tests { assert_eq!(feeds[3], Feed::Frame(Frame::DirectionalLight)); // One channel fewer of the second target is no lighting pass, and no pass the frame knows. let (other, table) = exporting(&[(9, 0), (0, 15), (1, 1)], &names); - let fed = feed(&other, lowered(OCCLUSION), &table, &none); + let fed = feed(&other, lowered(OCCLUSION), &table, &none, false); assert_eq!(fed.err(), Some(Unfed::Targets)); // A name the table does not state is refused by that name. let other = [VIEW_LIGHTING, LIGHTS, FRAME_RECORD, UNSTATED]; let (native, table) = exporting(&LIGHTING, &other); - let fed = feed(&native, lowered(OCCLUSION), &table, &none); + let fed = feed(&native, lowered(OCCLUSION), &table, &none, false); assert_eq!(fed.err(), Some(Unfed::Unlit(UNSTATED))); // A pass that bakes a table is fed whatever one target it writes, and only when asked. let (bake, table) = exporting(&[(0, 15)], &[UNSTATED; 4]); - let fed = crate::rdna_bind::shading::feed_table(&bake, lowered(OCCLUSION), &table, &none); + let fed = + crate::rdna_bind::shading::feed_table(&bake, lowered(OCCLUSION), &table, &none, false); assert_eq!(fed.err(), Some(Unfed::Unlit(UNSTATED))); let (bake, table) = exporting(&[(0, 3)], &[LIGHTS; 4]); assert_eq!( - feed(&bake, lowered(OCCLUSION), &table, &none).err(), + feed(&bake, lowered(OCCLUSION), &table, &none, false).err(), Some(Unfed::Targets) ); // The occlusion's strength is a lighting pass's to read: a lit forward one is refused it, // and a lighting pass is refused a place of the record nothing states. let (forward, table) = exporting(&[(9, 0), (0, 15), (1, 15)], &names); - let fed = feed(&forward, lowered(OCCLUSION), &table, &none); + let fed = feed(&forward, lowered(OCCLUSION), &table, &none, false); assert_eq!(fed.err(), Some(Unfed::Unread(VIEW_LIGHTING))); let (native, table) = exporting(&LIGHTING, &names); - let fed = feed(&native, lowered("cb0_[4].x"), &table, &none); + let fed = feed(&native, lowered("cb0_[4].x"), &table, &none, false); assert_eq!(fed.err(), Some(Unfed::Unread(VIEW_LIGHTING))); } @@ -696,7 +697,8 @@ mod tests { fn a_compute_program_is_fed_what_the_frame_keeps_and_one_of_an_unstated_name_is_not() { let (native, table, lowered) = computing([METER_CONSTANTS, BINS, MEANS]); // A compute program is a step of the frame whether or not a caller says it bakes. - let stage = feed(&native, lowered, &table, &table).expect("a compute program is fed"); + let stage = + feed(&native, lowered, &table, &table, false).expect("a compute program is fed"); let feeds: Vec = (stage.feeds.iter()).map(|fed| fed.feed.clone()).collect(); let kept = |hash| Feed::Frame(Frame::Kept(hash)); assert_eq!(feeds, [kept(METER_CONSTANTS), kept(BINS), kept(MEANS)]); @@ -710,7 +712,7 @@ mod tests { assert!(text.contains("@compute"), "{text}"); // A texture it writes under a name nothing states is refused by that name. let (native, table, lowered) = computing([METER_CONSTANTS, BINS, UNSTATED]); - let fed = feed(&native, lowered, &table, &table); + let fed = feed(&native, lowered, &table, &table, false); assert_eq!(fed.err(), Some(Unfed::Unlit(UNSTATED))); // The frame without its surfaces' colours is at rest: the meter's constants state none. assert_eq!(rest_of(0xE714_702C), Some(Rest::Noughts)); diff --git a/crates/tools/or-shader-front/src/rdna_bind/shading.rs b/crates/tools/or-shader-front/src/rdna_bind/shading.rs index 7fedccf52..0064e7d94 100644 --- a/crates/tools/or-shader-front/src/rdna_bind/shading.rs +++ b/crates/tools/or-shader-front/src/rdna_bind/shading.rs @@ -480,16 +480,6 @@ const CHECKED_ON_SOFTWARE: u64 = 800_000; // first frame; a three-layer one of 7,746 and 2,152, the largest that draws, is under it. const PIXEL_CHECKED_ON_SOFTWARE: u64 = 17_000_000; -/// Whether the stages bound here are drawn by a hardware adapter, as the program that draws them said. -// ponytail: one switch a process; stages bound before a device is made anew on another kind of -// adapter are not bound again. Hand the kind to `feed` if a session ever changes adapters. -static DRAWN_BY_HARDWARE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - -/// Says whether the adapter that draws is a hardware one: a stage past what the software adapter draws is refused only where it is not. -pub fn drawn_by_hardware(hardware: bool) { - DRAWN_BY_HARDWARE.store(hardware, std::sync::atomic::Ordering::Relaxed); -} - /// Whether a stage is refused for its size: past what the software adapter draws, where that adapter draws it. fn unchecked(hardware: bool, mesh: bool, stores: u32, branches: u32) -> bool { !hardware && past_the_software_adapter(mesh, stores, branches) @@ -856,8 +846,9 @@ fn one_entry(module: &mut naga::Module, group: u32, binding: u32) -> bool { /// `lowered`, a program of a model's shading pass, with what fills each of its bindings; the /// pixel stage's bindings are moved to group 1, and each stage's arrays to the group two above -/// its own, since a device binds no array beside a constant buffer. `table` is the program's own variable table and -/// `effect` the first table of the effect that runs it. +/// its own, since a device binds no array beside a constant buffer. `table` is the program's own variable table, +/// `effect` the first table of the effect that runs it, and `hardware` whether the drawing adapter +/// is hardware rather than software (a stage past what the software adapter draws is refused only when false). // The object's matrix is told by shape: the one buffer of 64-byte elements a mesh program binds // that the effect's own table names. pub fn feed( @@ -865,8 +856,9 @@ pub fn feed( lowered: Lowered, table: &Sgd5Table, effect: &Sgd5Table, + hardware: bool, ) -> Result { - feed_noting(native, lowered, table, effect).map(|(stage, _)| stage) + feed_noting(native, lowered, table, effect, hardware).map(|(stage, _)| stage) } /// [`feed`], with what it did to the stage's buffers to hold it to a device with default limits. @@ -875,8 +867,9 @@ pub fn feed_noting( lowered: Lowered, table: &Sgd5Table, effect: &Sgd5Table, + hardware: bool, ) -> Result<(Stage, Fitted), Unfed> { - fed(native, lowered, table, effect, None, false) + fed(native, lowered, table, effect, None, false, hardware) } /// [`feed`] for a program of a pass that bakes a table a lighting pass reads, or that draws a @@ -887,8 +880,9 @@ pub fn feed_table( lowered: Lowered, table: &Sgd5Table, effect: &Sgd5Table, + hardware: bool, ) -> Result { - fed(native, lowered, table, effect, None, true).map(|(stage, _)| stage) + fed(native, lowered, table, effect, None, true, hardware).map(|(stage, _)| stage) } /// [`feed`] for a device that gives a stage `budget`: where the bindings the editor leaves at @@ -900,8 +894,17 @@ pub fn feed_within( table: &Sgd5Table, effect: &Sgd5Table, budget: &Budget, + hardware: bool, ) -> Result<(Stage, Fitted), Unfed> { - fed(native, lowered, table, effect, Some(budget), false) + fed( + native, + lowered, + table, + effect, + Some(budget), + false, + hardware, + ) } /// Why [`feed`] refuses a stage of `native` whose lowering binds `resources`, where its program and @@ -1019,6 +1022,7 @@ fn fed( effect: &Sgd5Table, merging: Option<&Budget>, baked: bool, + hardware: bool, ) -> Result<(Stage, Fitted), Unfed> { // First, so that a caller that asked it before the optimiser ran is told the same. if let Some(why) = refused(native, &lowered.resources, table, effect, baked) { @@ -1316,7 +1320,6 @@ fn fed( } } let (stores, branches) = stores_and_branches(&module); - let hardware = DRAWN_BY_HARDWARE.load(std::sync::atomic::Ordering::Relaxed); if !unguarded() && unchecked(hardware, mesh, stores, branches) { return Err(Unfed::Unchecked(stores, branches)); } @@ -1521,7 +1524,14 @@ mod tests { intersections: Vec::new(), region: None, }; - feed(&bare_mesh(), lowered, &program(), &Sgd5Table::default()).map(|_| ()) + feed( + &bare_mesh(), + lowered, + &program(), + &Sgd5Table::default(), + false, + ) + .map(|_| ()) }; assert_eq!(fed(BTreeMap::new()), Ok(())); assert_eq!( @@ -1598,13 +1608,13 @@ mod tests { resources: vec![resource(0x05, 0, super::super::forward::FRAME_SCALE)], ..Sgd5Table::default() }; - let deferred = - feed(&native, lowered(), &table, &Sgd5Table::default()).expect("deferred pixel feeds"); + let deferred = feed(&native, lowered(), &table, &Sgd5Table::default(), false) + .expect("deferred pixel feeds"); assert_eq!( deferred.feeds[0].feed, Feed::Stated(super::super::forward::frame_scale_at_rest()) ); - let lit = feed_table(&native, lowered(), &table, &Sgd5Table::default()) + let lit = feed_table(&native, lowered(), &table, &Sgd5Table::default(), false) .expect("lighting pixel feeds"); assert_eq!( lit.feeds[0].feed, diff --git a/crates/tools/or-shader-tool/src/rdna_devices.rs b/crates/tools/or-shader-tool/src/rdna_devices.rs index f2b476fa6..77288a35a 100644 --- a/crates/tools/or-shader-tool/src/rdna_devices.rs +++ b/crates/tools/or-shader-tool/src/rdna_devices.rs @@ -1547,14 +1547,14 @@ fn fed_pair( }; if !metal { let (fed, done) = - shading::feed_noting(native, lowered, table, effect).map_err(unfed)?; + shading::feed_noting(native, lowered, table, effect, false).map_err(unfed)?; notes.extend(metal::fed_notes(word, &done)); return Ok::<_, String>(fed); } // The renderer draws a mesh program lowered to a vertex stage with no vertex buffer. let budget = metal::metal_budget(stage, 0); let (fed, done) = - shading::feed_within(native, lowered, table, effect, &budget).map_err(unfed)?; + shading::feed_within(native, lowered, table, effect, &budget, false).map_err(unfed)?; notes.extend(metal::fit_notes(word, &done, &budget, &fed.module)); Ok(fed) }; diff --git a/src/app/editor_window.rs b/src/app/editor_window.rs index a26495d87..4b3e325bc 100644 --- a/src/app/editor_window.rs +++ b/src/app/editor_window.rs @@ -91,6 +91,7 @@ impl App { let mut bridge = RenderBridge::new(gpu.device.clone(), gpu.queue.clone(), gpu.surface_format) .with_instance(gpu.instance.clone()) + .with_hardware_adapter(gpu.adapter.get_info().device_type != wgpu::DeviceType::Cpu) .warm_thumbnails(); bridge.set_game_pack_path(self.app_state.game_pack.root()); @@ -213,6 +214,7 @@ impl App { let mut bridge = RenderBridge::new(gpu.device.clone(), gpu.queue.clone(), gpu.surface_format) .with_instance(gpu.instance.clone()) + .with_hardware_adapter(gpu.adapter.get_info().device_type != wgpu::DeviceType::Cpu) .warm_thumbnails(); bridge.set_game_pack_path(self.app_state.game_pack.root()); bridge.set_mode(or_renderer::ShadingMode::Material); diff --git a/src/app/gpu.rs b/src/app/gpu.rs index 02ca5c3ff..80e27bb38 100644 --- a/src/app/gpu.rs +++ b/src/app/gpu.rs @@ -370,7 +370,6 @@ impl App { anyhow::anyhow!("Failed to find suitable GPU adapter: {e}. {needs}") })?; tracing::info!("Using GPU: {}", adapter.get_info().name); - or_cli::gta6_drawn_by_hardware(adapter.get_info().device_type != wgpu::DeviceType::Cpu); if or_renderer::instance::fell_back_to_fxc(adapter.get_info().backend) { notice_fxc(&mut self.app_state.toasts, &FXC_NOTICED); } diff --git a/src/main.rs b/src/main.rs index 98c042558..043c067b1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -50,8 +50,6 @@ fn main() { } tracing::info!("Starting OpenRage"); - // ⚠ Before any panel builds the hash index, which reads the user's mined names only once. - state::read_the_mined_names(); let open = state::file_io::command_line_paths(std::env::args_os().skip(1)); // ⚠ A project keeps its own window, so only a launch naming files alone goes to the window already open. diff --git a/src/render/gta6_frame_light.rs b/src/render/gta6_frame_light.rs index 1ae21d761..4481c1688 100644 --- a/src/render/gta6_frame_light.rs +++ b/src/render/gta6_frame_light.rs @@ -93,6 +93,8 @@ struct Glue { given_up: Option, /// The device the tables and the passes were built for: another's are built anew. device: Option, + /// Whether the passes were bound for a hardware adapter rather than a software one. + hardware: Option, /// Where the last frame's scene stood, which the Shaded line says. stood: Option, } @@ -222,7 +224,7 @@ fn programs(archive: &Path) -> Result { } /// The pass that lights the pixels of `kind`, translated, linked and guarded. -fn stages_of(programs: &Programs, kind: u32) -> Result { +fn stages_of(programs: &Programs, kind: u32, hardware: bool) -> Result { let (vertex, pixel) = (&programs.vertex, &programs.kinds[&kind]); let pass = or_cli::translate_gta6_frame_pass( &vertex.container, @@ -230,6 +232,7 @@ fn stages_of(programs: &Programs, kind: u32) -> Result [&vertex.table, &pixel.table], [&vertex.effect, &pixel.effect], &Gta6Lights::of(kind, &LIT_KINDS), + hardware, )?; let mut fed = BTreeMap::new(); feeds(&pass.vertex, &mut fed); @@ -243,9 +246,10 @@ fn stages_of(programs: &Programs, kind: u32) -> Result } /// The steps that meter, expose and tone the lit frame, each translated. -fn tone_stages(programs: &Programs) -> Result { +fn tone_stages(programs: &Programs, hardware: bool) -> Result { let counts = |program: &Program| -> Result { - let stage = or_cli::translate_gta6_compute_step(&program.container, &program.table)?; + let stage = + or_cli::translate_gta6_compute_step(&program.container, &program.table, hardware)?; let mut fed = BTreeMap::new(); feeds(&stage, &mut fed); Ok(FrameComputeStages { @@ -259,6 +263,7 @@ fn tone_stages(programs: &Programs) -> Result { &pixel.container, [&vertex.table, &pixel.table], [&vertex.effect, &pixel.effect], + hardware, )?; let mut fed = BTreeMap::new(); feeds(&pass.vertex, &mut fed); @@ -282,7 +287,7 @@ fn tone_stages(programs: &Programs) -> Result { } /// The passes that bake the tables, each translated and linked to [`TABLE_VERTEX`]. -fn table_stages(programs: &Programs) -> Result { +fn table_stages(programs: &Programs, hardware: bool) -> Result { let stages = |wanted: Gta6Table| -> Result, String> { let Some((_, program)) = programs.tables.iter().find(|(table, _)| *table == wanted) else { return Ok(None); @@ -294,6 +299,7 @@ fn table_stages(programs: &Programs) -> Result { &program.container, &program.table, &program.effect, + hardware, )?; Ok(Some((Arc::new(producer), stage.module))) }; @@ -334,23 +340,26 @@ pub(crate) fn said(said: String) -> String { } /// Advance the passes for this frame of `scene`: whether where it stands with them moved, which -/// the Shaded line says. +/// the Shaded line says. `hardware` says whether the drawing adapter is hardware rather than +/// software. pub(crate) fn refresh( devices: (&wgpu::Device, &wgpu::Queue), scene: Option<&MeshletScene>, archive: impl FnOnce() -> Option, + hardware: bool, ) -> bool { let mut held = GLUE.lock().unwrap_or_else(PoisonError::into_inner); let glue = held.get_or_insert_with(Glue::default); // What was built for a device that went is of no use to this one; the programs read are. - if glue.device.as_ref() != Some(devices.0) { + if glue.device.as_ref() != Some(devices.0) || glue.hardware != Some(hardware) { *glue = Glue { programs: glue.programs.take(), device: Some(devices.0.clone()), + hardware: Some(hardware), ..Glue::default() }; } - advance(glue, devices, scene, archive); + advance(glue, devices, scene, archive, hardware); let lit = scene.is_none_or(MeshletScene::lit_by_game); SETTLED.store(lit, Ordering::Relaxed); let stood = scene.map(|_| match (lit, &glue.given_up) { @@ -368,6 +377,7 @@ fn advance( (device, queue): (&wgpu::Device, &wgpu::Queue), scene: Option<&MeshletScene>, archive: impl FnOnce() -> Option, + hardware: bool, ) { let read = Arc::clone(glue.programs.get_or_insert_with(|| { let archive = archive(); @@ -379,14 +389,14 @@ fn advance( let tables = Arc::clone(glue.tables.get_or_insert_with(|| { let (read, device, queue) = (Arc::clone(&read), device.clone(), queue.clone()); start(move || { - let stages = table_stages(&*made_before(&read)?)?; + let stages = table_stages(&*made_before(&read)?, hardware)?; FrameLightTables::bake(&device, &queue, &stages).map_err(|e| e.to_string()) }) })); let tone = Arc::clone(glue.tone.get_or_insert_with(|| { let (read, device) = (Arc::clone(&read), device.clone()); start(move || { - FrameTone::build(&device, &tone_stages(&*made_before(&read)?)?) + FrameTone::build(&device, &tone_stages(&*made_before(&read)?, hardware)?) .map_err(|e| e.to_string()) }) })); @@ -425,7 +435,7 @@ fn advance( let slot = glue.passes.entry(kind).or_insert_with(|| { let (read, device) = (Arc::clone(&read), device.clone()); start(move || { - let stages = stages_of(&*made_before(&read)?, kind)?; + let stages = stages_of(&*made_before(&read)?, kind, hardware)?; FrameLightPass::build(&device, &stages).map_err(|e| e.to_string()) }) }); diff --git a/src/render/viewport/day.rs b/src/render/viewport/day.rs index e228a478d..63d46d6ae 100644 --- a/src/render/viewport/day.rs +++ b/src/render/viewport/day.rs @@ -203,12 +203,12 @@ impl RenderBridge { let (hour, weather) = (session.hour(), session.weather()); let data = state.clip_regions.timecycle(); let key = (Arc::as_ptr(&data) as usize, hour.to_bits(), weather); - if self.world_day_key == Some(key) { + if self.game_scene.world_day_key == Some(key) { return; } - self.world_day_key = Some(key); + self.game_scene.world_day_key = Some(key); // The day a drawable's viewport set is not the world's, and is worked out again when that viewport is shown. - self.day_key = None; + self.game_scene.day_key = None; let named = session .weathers() .into_iter() @@ -242,12 +242,12 @@ impl RenderBridge { /// Hand the renderer the day the drivers say, worked out again only when the hour, the weather or the install's timecycle changed; a world drawn by the game's own programs is lit by its session's hour and weather, and a world in a plain mode by no day. pub(super) fn refresh_day(&mut self, state: &AppState) { if self.world.shown { - if self.world.plain.shown && self.mode == or_renderer::ShadingMode::Shaded { + if self.world.plain.shown && self.frame.mode == or_renderer::ShadingMode::Shaded { self.refresh_world_day(state); } return; } - self.world_day_key = None; + self.game_scene.world_day_key = None; let data = state.clip_regions.timecycle(); let hour = state.drivers.time_of_day.hour; let weather = state.drivers.weather.state; @@ -270,10 +270,10 @@ impl RenderBridge { days.to_bits(), weather, ); - if self.day_key == Some(key) { + if self.game_scene.day_key == Some(key) { return; } - self.day_key = Some(key); + self.game_scene.day_key = Some(key); self.renderer.set_day(day_of(&data, hour, days, weather)); } diff --git a/src/render/viewport/dressed.rs b/src/render/viewport/dressed.rs index bdfe4e2f6..69b9824d7 100644 --- a/src/render/viewport/dressed.rs +++ b/src/render/viewport/dressed.rs @@ -98,12 +98,12 @@ impl RenderBridge { scene: Option<&DressedScene>, channel: Option, ) { - self.mesh_cache_key = None; - self.cached_mesh_uploads.clear(); + self.doc_cache.mesh_key = None; + self.doc_cache.mesh_uploads.clear(); let Some(scene) = scene else { - self.cached_mesh_draws.clear(); - self.dressed_key = None; - self.held = Held::default(); + self.doc_cache.mesh_draws.clear(); + self.dressed.key = None; + self.dressed.held = Held::default(); return; }; // ⚠ The channel is part of what is drawn: its colours are packed into the vertices. @@ -111,10 +111,10 @@ impl RenderBridge { ^ channel .map_or(0, |c| 1 + c.channel() as u64) .rotate_left(48); - if self.dressed_key == Some(key) { + if self.dressed.key == Some(key) { return; } - self.dressed_key = Some(key); + self.dressed.key = Some(key); let mut draws = Vec::new(); let mut held = Held { channel, @@ -135,20 +135,20 @@ impl RenderBridge { } } // A texture no part draws with any more is let go of, so reading one again does not grow the cache. - self.dressed_textures.retain(|id, _| kept.contains(id)); - self.cached_mesh_draws = draws; - self.held = held; - self.skinned_revision = None; + self.dressed.textures.retain(|id, _| kept.contains(id)); + self.doc_cache.mesh_draws = draws; + self.dressed.held = held; + self.doc_cache.skinned_revision = None; } /// Put the skinned meshes of `scene` in the pose `skin` stands for, named by `revision`, or at rest for none; a pose already held is not written again. pub fn pose_dressed(&mut self, scene: &DressedScene, pose: Option<(u64, &[Mat4])>) { let wanted = pose.map(|(revision, _)| revision); - if self.held.pose == wanted { + if self.dressed.held.pose == wanted { return; } - self.held.pose = wanted; - for (at, &(part, mesh)) in self.held.meshes.iter().enumerate() { + self.dressed.held.pose = wanted; + for (at, &(part, mesh)) in self.dressed.held.meshes.iter().enumerate() { if !scene.is_skinned_mesh(part, mesh) { continue; } @@ -160,21 +160,21 @@ impl RenderBridge { let vertices = styled( source, posed.as_deref().unwrap_or(rest), - self.held.channel, + self.dressed.held.channel, scene.aux(part, mesh), ); - if let Some(draw) = self.cached_mesh_draws.get(at) { + if let Some(draw) = self.doc_cache.mesh_draws.get(at) { self.queue .write_buffer(&draw.vertex_buffer, 0, bytemuck::cast_slice(&vertices)); } - self.held.vertices[at] = vertices; + self.dressed.held.vertices[at] = vertices; } } /// The edges of the dressed ped where it stands now, for the wireframe view. pub(super) fn dressed_wire_lines(&self) -> Vec { - let at = |draw: usize, end: u32| self.held.vertices[draw][end as usize].position; - (self.held.edges.iter().enumerate()) + let at = |draw: usize, end: u32| self.dressed.held.vertices[draw][end as usize].position; + (self.dressed.held.edges.iter().enumerate()) .flat_map(|(draw, edges)| { edges.iter().flat_map(move |[a, b]| { [ @@ -215,7 +215,7 @@ impl RenderBridge { draws.push(self.dressed_draw(&vertices, &geometry.indices, bind_group.clone())); } } - self.dressed_textures.retain(|id, _| kept.contains(id)); + self.dressed.textures.retain(|id, _| kept.contains(id)); self.shoot(draws, camera, px, alpha, game) } @@ -227,19 +227,19 @@ impl RenderBridge { ) -> Option> { let diffuse = part.diffuse.as_ref()?; kept.insert(diffuse.id); - if let Some(held) = self.dressed_textures.get(&diffuse.id) { + if let Some(held) = self.dressed.textures.get(&diffuse.id) { return Some(held.clone()); } let (group, _) = upload_rgba( &self.device, &self.queue, - &self.material_bgl, + &self.frame.material_bgl, (diffuse.width, diffuse.height), &diffuse.rgba, diffuse.srgb, ); let group = Arc::new(group); - self.dressed_textures.insert(diffuse.id, group.clone()); + self.dressed.textures.insert(diffuse.id, group.clone()); Some(group) } @@ -298,7 +298,7 @@ mod tests { wgpu::TextureFormat::Rgba8UnormSrgb, ); assert!(bridge.set_game_pack_path(std::path::Path::new(&pack))); - bridge.mode = ShadingMode::Shaded; + bridge.frame.mode = ShadingMode::Shaded; bridge.renderer.resize(&device, PX, PX); Some((device, bridge)) } diff --git a/src/render/viewport/game_shaders.rs b/src/render/viewport/game_shaders.rs index e63939ab0..a3858c4db 100644 --- a/src/render/viewport/game_shaders.rs +++ b/src/render/viewport/game_shaders.rs @@ -69,10 +69,10 @@ impl RenderBridge { tracing::info!(root = %root.display(), effects = pack.manifest().effects.len(), "loaded the game shader pack"); let pack = Arc::new(pack); self.renderer.set_game_pack(Some(pack.clone())); - self.game_pack = Some(pack); - self.game_pack_epoch = self.game_pack_epoch.wrapping_add(1); + self.game_scene.pack = Some(pack); + self.game_scene.pack_epoch = self.game_scene.pack_epoch.wrapping_add(1); // What was built is for the pack that was read before - self.game_pipelines = Default::default(); + self.game_scene.pipelines = Default::default(); self.renderer.reset_deferred_pipelines(); self.drop_game_scene(); true @@ -92,11 +92,11 @@ impl RenderBridge { surfaces: scene.drawn(), meshlets: scene.meshlets(), waiting: scene.waiting.len(), - passes: self.gta6_pipelines.len(), + passes: self.gta6.pipelines.len(), casts: !scene.casts_no_shadow(), size: self.renderer.size(), made: scene.uploads(), - maps: self.gta6_maps, + maps: self.gta6.maps, rays: scene.traced_rays(), capped: scene.traced_capped(), }) @@ -137,12 +137,12 @@ impl RenderBridge { /// Forget every pass built of a GTA VI drawable's own programs and the scene made of them: the next frames build them again, with its maps decoded already. // ⚠ For a script's step, which times what a model waits for once its maps are in. pub fn rebuild_model_passes(&mut self) { - self.gta6_pipelines = gta6_pipelines(); + self.gta6.pipelines = gta6_pipelines(); self.renderer.set_gta6_scene(None); - self.game_scene_key = None; - self.gta6_since = None; - self.gta6_own = None; - self.gta6_building = None; + self.game_scene.key = None; + self.gta6.since = None; + self.gta6.own = None; + self.gta6.building = None; } /// Have the next frame of the active GTA VI drawable's own passes draw every pass again, whatever moved. @@ -169,34 +169,31 @@ impl RenderBridge { /// Whether there is a pack of the game's shaders to draw with. pub fn game_shaders_available(&self) -> bool { - self.game_pack.is_some() + self.game_scene.pack.is_some() } /// What the last scene of the game's passes came to; `None` where there is none. pub fn game_scene_report(&self) -> Option<&GameSceneReport> { - self.game_scene_report.as_ref() + self.game_scene.report.as_ref() } /// Give the game's passes the pose the animation holds, which is by bone of the skeleton the surfaces were bound to, when it has changed. fn refresh_skin(&mut self, state: &AppState) { let key = (state.anim.skin_revision(), state.anim.skin_matrices.len()); - if self.skin_key == Some(key) { + if self.game_scene.skin_key == Some(key) { return; } - self.skin_key = Some(key); - self.held.skin_key = None; + self.game_scene.skin_key = Some(key); + self.dressed.held.skin_key = None; self.renderer.set_skin(state.anim.skin_matrices.clone()); } pub(super) fn drop_game_scene(&mut self) { - self.game_scene_key = None; - self.held.game_key = None; - self.decoded = Default::default(); - self.game_scene_report = None; - self.gta6_own = None; - self.gta6_building = None; - self.gta6_decoding = false; - self.gta6_fallback.clear(); + self.game_scene.key = None; + self.dressed.held.game_key = None; + self.game_scene.decoded = Default::default(); + self.game_scene.report = None; + self.gta6.clear_scene(); self.renderer.set_game_scene(None); self.renderer.set_gta6_scene(None); self.renderer.clear_deferred(); @@ -205,8 +202,8 @@ impl RenderBridge { /// Hand the renderer the stars, the moon's face and the water's maps of the install, when they were read again. pub(super) fn refresh_sky_textures(&mut self, state: &AppState) { let revision = state.clip_regions.sky_revision(); - if self.sky_textures_of != revision { - self.sky_textures_of = revision; + if self.game_scene.sky_textures_of != revision { + self.game_scene.sky_textures_of = revision; self.renderer .set_sky_textures((*state.clip_regions.sky_textures()).clone()); self.renderer @@ -217,8 +214,8 @@ impl RenderBridge { /// Prepare the active drawable for the game's own passes when the mode draws them, and again when what it is made from changes. pub fn refresh_game_scene(&mut self, state: &AppState) { self.refresh_sky_textures(state); - if self.mode != ShadingMode::Shaded { - if self.game_scene_key.is_some() { + if self.frame.mode != ShadingMode::Shaded { + if self.game_scene.key.is_some() { self.drop_game_scene(); } return; @@ -230,25 +227,26 @@ impl RenderBridge { self.refresh_gta6_scene(state, doc, &hashes); return; } - if self.game_pack.is_none() { + if self.game_scene.pack.is_none() { // What a GTA VI drawable's programs drew is not this document's - if self.game_scene_key.is_some() { + if self.game_scene.key.is_some() { self.drop_game_scene(); } return; } self.refresh_skin(state); - let key = MeshCacheKey::of(state, doc, self.game_pack_epoch); - if self.game_scene_key == Some(key) && !self.renderer.deferred_needs_prepare() { + let key = MeshCacheKey::of(state, doc, self.game_scene.pack_epoch); + if self.game_scene.key == Some(key) && !self.renderer.deferred_needs_prepare() { return; } - self.game_scene_key = Some(key); - self.held.game_key = None; - let Some(surfaces) = crate::render::game_scene::surfaces_shown(state, &mut self.decoded) + self.game_scene.key = Some(key); + self.dressed.held.game_key = None; + let Some(surfaces) = + crate::render::game_scene::surfaces_shown(state, &mut self.game_scene.decoded) else { self.renderer.set_game_scene(None); self.renderer.clear_deferred(); - self.game_scene_report = None; + self.game_scene.report = None; return; }; self.prepare_game_surfaces(surfaces); @@ -256,8 +254,8 @@ impl RenderBridge { /// The dressed ped for the game's own passes when the mode draws them, and again when what is worn changes; the ped stands at rest. pub fn refresh_dressed_game(&mut self, scene: Option<&crate::render::dressed::DressedScene>) { - if self.mode != ShadingMode::Shaded { - if self.held.game_key.take().is_some() { + if self.frame.mode != ShadingMode::Shaded { + if self.dressed.held.game_key.take().is_some() { self.drop_game_scene(); } return; @@ -265,20 +263,20 @@ impl RenderBridge { let Some(scene) = scene else { return; }; - if self.game_pack.is_none() { + if self.game_scene.pack.is_none() { return; } - let key = (scene.key, self.game_pack_epoch); - if self.held.game_key == Some(key) && !self.renderer.deferred_needs_prepare() { + let key = (scene.key, self.game_scene.pack_epoch); + if self.dressed.held.game_key == Some(key) && !self.renderer.deferred_needs_prepare() { return; } - self.held.game_key = Some(key); - self.game_scene_key = None; + self.dressed.held.game_key = Some(key); + self.game_scene.key = None; let surfaces = scene.shaded_surfaces(); if surfaces.is_empty() { self.renderer.set_game_scene(None); self.renderer.clear_deferred(); - self.game_scene_report = None; + self.game_scene.report = None; return; } self.prepare_game_surfaces(surfaces); @@ -287,10 +285,10 @@ impl RenderBridge { /// Put the game's passes' ped in the pose `pose` stands for, numbered by its revision, or at rest for none; a pose already held is not written again. pub fn pose_dressed_game(&mut self, pose: Option<(u64, &[glam::Mat4])>) { let key = pose.map_or((0, 0), |(revision, skin)| (revision, skin.len())); - if self.held.skin_key == Some(key) { + if self.dressed.held.skin_key == Some(key) { return; } - self.held.skin_key = Some(key); + self.dressed.held.skin_key = Some(key); self.renderer .set_skin(pose.map(|(_, skin)| skin.to_vec()).unwrap_or_default()); } @@ -298,10 +296,10 @@ impl RenderBridge { /// Prepare `surfaces` for the game's own passes, lit by its deferred passes where the pack has them and by each pass alone where a pass will not build. fn prepare_game_surfaces(&mut self, surfaces: Vec<(Surface, Material)>) { // What a GTA VI drawable's own programs drew is not this scene's - if self.gta6_own.take().is_some() { + if self.gta6.own.take().is_some() { self.renderer.set_gta6_scene(None); } - let Some(pack) = &self.game_pack else { + let Some(pack) = &self.game_scene.pack else { return; }; // The game's deferred passes light it where the pack has them; a pass the device refuses is reported by its error scope and not by a panic @@ -312,7 +310,7 @@ impl RenderBridge { match (pollster::block_on(validation.pop()), deferred) { (None, Ok((drawn, left_out))) => { self.renderer.set_game_scene(None); - self.game_scene_report = Some(GameSceneReport { + self.game_scene.report = Some(GameSceneReport { drawn, left_out, gta6: None, @@ -328,7 +326,7 @@ impl RenderBridge { } let validation = self.device.push_error_scope(wgpu::ErrorFilter::Validation); let scene = MeshScene::prepare_with( - &mut self.game_pipelines, + &mut self.game_scene.pipelines, &self.device, &self.queue, pack, @@ -338,12 +336,12 @@ impl RenderBridge { if let Some(error) = pollster::block_on(validation.pop()) { tracing::warn!(%error, "the game's passes did not prepare"); // A pipeline the device refused is not one to build the next scene with - self.game_pipelines = Default::default(); + self.game_scene.pipelines = Default::default(); self.renderer.set_game_scene(None); - self.game_scene_report = None; + self.game_scene.report = None; return; } - self.game_scene_report = Some(GameSceneReport { + self.game_scene.report = Some(GameSceneReport { drawn: scene.drawn(), left_out: scene .skipped() @@ -376,11 +374,15 @@ impl RenderBridge { .find(|archive| archive.is_file()) }) }; - gta6_shaders::request(&crate::render::gta6_meshlets::worn(state), install); - if self.gta6_since.is_none_or(|(of, ..)| of != doc) { + gta6_shaders::request( + &crate::render::gta6_meshlets::worn(state), + install, + self.gta6.hardware_adapter, + ); + if self.gta6.since.is_none_or(|(of, ..)| of != doc) { tracing::info!(%doc, "Shaded was asked for a GTA VI drawable"); - self.gta6_since = Some((doc, std::time::Instant::now(), false, false)); - self.gta6_maps = Default::default(); + self.gta6.since = Some((doc, std::time::Instant::now(), false, false)); + self.gta6.maps = Default::default(); crate::render::gta6_meshlets::start_decoding(state); } let running = gta6_shaders::running(); @@ -389,19 +391,23 @@ impl RenderBridge { // A map learnt or decoded since the scene was bound is bound where it is read self.take_on_gta6_maps(state, key); // The pack's passes drew without maps a worker decoded: prepared again once all are in - let fallen = &mut self.gta6_fallback; + let fallen = &mut self.gta6.fallback; if !fallen.is_empty() && crate::render::gta6_meshlets::all_in(fallen) { fallen.clear(); - self.game_scene_key = None; + self.game_scene.key = None; } - let fresh = self.game_scene_key != Some(key); - let report = self.game_scene_report.as_ref(); + let fresh = self.game_scene.key != Some(key); + let report = self.game_scene.report.as_ref(); let was = report.and_then(|r| r.gta6.as_ref()).map(|(was, _)| *was); - let building = self.gta6_building.is_some(); + let building = self.gta6.building.is_some(); let devices = (&*self.device, &*self.queue); let traced = crate::render::gta6_trace::refresh(devices, self.renderer.gta6_scene(), state); - let lighting = - crate::render::gta6_frame_light::refresh(devices, self.renderer.gta6_scene(), install); + let lighting = crate::render::gta6_frame_light::refresh( + devices, + self.renderer.gta6_scene(), + install, + self.gta6.hardware_adapter, + ); if !fresh && was == Some(running) && !building && !traced && !lighting { return; } @@ -415,14 +421,14 @@ impl RenderBridge { } Some(kept) => kept, None => { - self.gta6_building = None; - self.gta6_decoding = false; - self.game_scene_key = Some(key); - self.held.game_key = None; + self.gta6.building = None; + self.gta6.decoding = false; + self.game_scene.key = Some(key); + self.dressed.held.game_key = None; self.renderer.clear_deferred(); - self.gta6_own = self.prepare_gta6_meshlets(state); - self.gta6_fallback.clear(); - let fallback = match (&self.gta6_own, &pack) { + self.gta6.own = self.prepare_gta6_meshlets(state); + self.gta6.fallback.clear(); + let fallback = match (&self.gta6.own, &pack) { // Drawn by its own programs, it needs no pass of the pack; with no pack yet, // there is none to prepare for (Some(Ok(_)), _) | (_, None) => None, @@ -434,7 +440,7 @@ impl RenderBridge { }; match (&pack, fallback) { (Some((_, pack)), Some(fallback)) => { - self.gta6_fallback = fallback.decoding; + self.gta6.fallback = fallback.decoding; let (drawn, mut left_out) = self.prepare_gta6_surfaces(pack, &fallback.surfaces); left_out.extend(fallback.left_out); @@ -448,12 +454,12 @@ impl RenderBridge { } }; if let (Some(Ok(_)), Some((_, since, first, every))) = - (&self.gta6_own, self.gta6_since.as_mut()) + (&self.gta6.own, self.gta6.since.as_mut()) { if !std::mem::replace(first, true) { tracing::info!(elapsed = ?since.elapsed(), "a GTA VI drawable's first frame by its own programs"); } - if self.gta6_building.is_none() && !std::mem::replace(every, true) { + if self.gta6.building.is_none() && !std::mem::replace(every, true) { tracing::info!(elapsed = ?since.elapsed(), "a GTA VI drawable's last surface by its own programs"); } } @@ -464,6 +470,7 @@ impl RenderBridge { (&*self.device, &*self.queue), self.renderer.gta6_scene(), install, + self.gta6.hardware_adapter, ); } let said = crate::render::gta6_shaded::said( @@ -473,10 +480,10 @@ impl RenderBridge { ); let by_cycles = crate::state::gta6_shaders::timecycle::timecycle(state) .is_some_and(|tables| super::gta6_day::lights(&tables, state.drivers.weather.state)); - let said = crate::render::gta6_shaded::said_of_own(said, self.gta6_own.as_ref(), by_cycles); + let said = crate::render::gta6_shaded::said_of_own(said, self.gta6.own.as_ref(), by_cycles); let said = crate::render::gta6_trace::said(said); let said = crate::render::gta6_frame_light::said(said); - self.game_scene_report = Some(GameSceneReport { + self.game_scene.report = Some(GameSceneReport { drawn, left_out, gta6: Some((running, said)), @@ -490,9 +497,9 @@ impl RenderBridge { read: impl FnOnce() -> Option>, kept: (usize, Vec<(String, String)>), ) -> (usize, Vec<(String, String)>) { - let drew = matches!(self.gta6_own, Some(Ok(_))); - self.gta6_own = self.prepare_gta6_meshlets_of(read); - match self.gta6_own { + let drew = matches!(self.gta6.own, Some(Ok(_))); + self.gta6.own = self.prepare_gta6_meshlets_of(read); + match self.gta6.own { Some(Ok(_)) => { self.renderer.set_game_scene(None); (0, Vec::new()) @@ -500,7 +507,7 @@ impl RenderBridge { // What some of its passes drew and none does now is prepared from nothing by the // next frame, as a drawable they never drew is _ if drew => { - self.game_scene_key = None; + self.game_scene.key = None; kept } _ => kept, @@ -524,12 +531,12 @@ impl RenderBridge { ) -> Option> { use or_renderer::game_shaders::meshlets::MeshletScene; // The drawable a worker builds for is the one asked about again, as it was read then - let meshlets = match self.gta6_building.take() { + let meshlets = match self.gta6.building.take() { Some(meshlets) => meshlets, None => { self.renderer.set_gta6_scene(None); // A map decoded from here on is bound by a later frame - self.gta6_maps.seen = crate::render::gta6_maps::arrived(); + self.gta6.maps.seen = crate::render::gta6_maps::arrived(); match read()? { Ok(meshlets) => meshlets, Err(why) => return Some(Err(why)), @@ -538,11 +545,11 @@ impl RenderBridge { }; // A surface draws by its pass once it is built, a map still decoded as its blank // texel; the map is bound into the scene as it comes in - self.gta6_decoding = meshlets.decoding; + self.gta6.decoding = meshlets.decoding; // What some of its passes draw takes on the surfaces a worker has built the pass of // since, each alone: a prepare makes every buffer and texture of every surface anew, on // this thread - let live = match self.gta6_own { + let live = match self.gta6.own { Some(Ok(_)) => self.renderer.take_gta6_scene(), _ => None, }; @@ -551,8 +558,8 @@ impl RenderBridge { let internal = self.device.push_error_scope(wgpu::ErrorFilter::Internal); let validation = self.device.push_error_scope(wgpu::ErrorFilter::Validation); let started = std::time::Instant::now(); - let built = self.gta6_pipelines.len(); - let (device, queue, pipelines) = (&self.device, &self.queue, &mut self.gta6_pipelines); + let built = self.gta6.pipelines.len(); + let (device, queue, pipelines) = (&self.device, &self.queue, &mut self.gta6.pipelines); let mut more = true; let anew = live.is_none(); let scene = match live { @@ -573,27 +580,27 @@ impl RenderBridge { }; let refused = pollster::block_on(validation.pop()); let refused = refused.or(pollster::block_on(internal.pop())); - self.gta6_maps.prepares += u32::from(anew && matches!(scene, Ok(Some(_)))); + self.gta6.maps.prepares += u32::from(anew && matches!(scene, Ok(Some(_)))); if more && !matches!(scene, Ok(None)) { tracing::info!( elapsed = ?started.elapsed(), surfaces = meshlets.surfaces.len(), decoding = meshlets.decoding, drawn = scene.as_ref().map_or(0, |scene| scene.as_ref().map_or(0, MeshletScene::drawn)), - passes = self.gta6_pipelines.len(), + passes = self.gta6.pipelines.len(), "a GTA VI drawable's own passes were prepared" ); } - if self.gta6_pipelines.len() > built { + if self.gta6.pipelines.len() > built { tracing::info!( - passes = self.gta6_pipelines.len() - built, + passes = self.gta6.pipelines.len() - built, "a worker builds a GTA VI drawable's own passes" ); } let building = tr!("a worker is still building its passes for this device"); let own = match (scene, refused) { (Ok(None), None) => { - self.gta6_building = Some(meshlets); + self.gta6.building = Some(meshlets); return Some(Err(building.to_string())); } (Ok(Some(mut scene)), None) => { @@ -631,7 +638,7 @@ impl RenderBridge { self.said_all_in(meshlets.decoding); // The drawable is asked about again until every pass of its surfaces is built if !scene.waiting.is_empty() { - self.gta6_building = Some(meshlets); + self.gta6.building = Some(meshlets); } scene.rest = rest; self.renderer.set_gta6_scene(Some(scene)); @@ -641,7 +648,7 @@ impl RenderBridge { (_, Some(error)) => { tracing::warn!(%error, "a GTA VI drawable's own programs did not prepare"); // A pipeline the device refused is not one to draw the next model with - self.gta6_pipelines = gta6_pipelines(); + self.gta6.pipelines = gta6_pipelines(); Err(error.to_string()) } }; @@ -660,7 +667,7 @@ impl RenderBridge { ) -> (usize, Vec<(String, String)>) { let validation = self.device.push_error_scope(wgpu::ErrorFilter::Validation); let scene = MeshScene::prepare_with( - &mut self.game_pipelines, + &mut self.game_scene.pipelines, &self.device, &self.queue, pack, @@ -670,7 +677,7 @@ impl RenderBridge { if let Some(error) = pollster::block_on(validation.pop()) { tracing::warn!(%error, "the GTA VI programs' passes did not prepare"); // A pipeline the device refused is not one to build the next scene with - self.game_pipelines = Default::default(); + self.game_scene.pipelines = Default::default(); self.renderer.set_game_scene(None); return (0, Vec::new()); } diff --git a/src/render/viewport/gta6_ahead_tests.rs b/src/render/viewport/gta6_ahead_tests.rs index fa129061b..61cd01dfc 100644 --- a/src/render/viewport/gta6_ahead_tests.rs +++ b/src/render/viewport/gta6_ahead_tests.rs @@ -95,7 +95,7 @@ fn bridged(what: &str) -> Option<(Arc, Arc, RenderBri wgpu::TextureFormat::Rgba8UnormSrgb, ); // Nothing a driver compiled is read from, or kept in, the configuration's folder. - bridge.gta6_pipelines = Default::default(); + bridge.gta6.pipelines = Default::default(); bridge.renderer.resize(&device, PX, PX); Some((device, queue, bridge)) } @@ -163,11 +163,11 @@ fn a_drawable_some_passes_drew_and_none_can_once_all_are_built_ends_as_one_they_ crate::state::DocumentId(7), 0, ); - bridge.game_scene_key = Some(key); + bridge.game_scene.key = Some(key); - bridge.gta6_pipelines.hold(&surfaces[0], true); + bridge.gta6.pipelines.hold(&surfaces[0], true); for _ in 0..4000 { - if matches!(bridge.gta6_own, Some(Ok(_))) { + if matches!(bridge.gta6.own, Some(Ok(_))) { break; } // Its own passes draw it: the pack's draw none of it. @@ -175,33 +175,33 @@ fn a_drawable_some_passes_drew_and_none_can_once_all_are_built_ends_as_one_they_ assert!(drawn == kept || drawn == (0, Vec::new())); std::thread::sleep(std::time::Duration::from_millis(5)); } - let own = bridge.gta6_own.clone().expect("a drawable").expect("drawn"); + let own = bridge.gta6.own.clone().expect("a drawable").expect("drawn"); assert_eq!((own.drawn, own.rest), (1, 1)); - assert_eq!(bridge.game_scene_key, Some(key)); + assert_eq!(bridge.game_scene.key, Some(key)); // Once the other pass is built the two cannot be one scene: the drawable is drawn by none // of its passes, and the next frame prepares it from nothing. - bridge.gta6_pipelines.hold(&surfaces[0], false); + bridge.gta6.pipelines.hold(&surfaces[0], false); let mut drawn = (0, Vec::new()); for _ in 0..4000 { - if bridge.gta6_building.is_none() { + if bridge.gta6.building.is_none() { break; } drawn = bridge.ask_again(read, kept.clone()); std::thread::sleep(std::time::Duration::from_millis(5)); } let shapes = "two pixel programs write targets of different shapes"; - assert_eq!(bridge.gta6_own, Some(Err(shapes.to_string()))); + assert_eq!(bridge.gta6.own, Some(Err(shapes.to_string()))); assert_eq!(drawn, kept); - assert_eq!(bridge.game_scene_key, None); - assert!(bridge.renderer.gta6_scene().is_none() && bridge.gta6_building.is_none()); + assert_eq!(bridge.game_scene.key, None); + assert!(bridge.renderer.gta6_scene().is_none() && bridge.gta6.building.is_none()); // As that frame asks, it is the drawable every pass of which was built before it was // prepared: the same reason, and no scene of its own. assert_eq!( bridge.prepare_gta6_meshlets_of(read), Some(Err(shapes.to_string())) ); - assert!(bridge.renderer.gta6_scene().is_none() && bridge.gta6_building.is_none()); + assert!(bridge.renderer.gta6_scene().is_none() && bridge.gta6.building.is_none()); let camera = OrbitCamera::default(); let mut encoder = device.create_command_encoder(&Default::default()); (bridge.renderer).render(&mut encoder, &queue, &camera, ShadingMode::Shaded); diff --git a/src/render/viewport/gta6_late_maps.rs b/src/render/viewport/gta6_late_maps.rs index 77aa8969a..58f553423 100644 --- a/src/render/viewport/gta6_late_maps.rs +++ b/src/render/viewport/gta6_late_maps.rs @@ -32,19 +32,19 @@ impl RenderBridge { /// were read, where nothing else it was prepared from moved; whether it did, which makes `key` /// the scene's. pub(super) fn take_on_gta6_maps(&mut self, state: &AppState, key: MeshCacheKey) -> bool { - let Some(was) = self.game_scene_key else { + let Some(was) = self.game_scene.key else { return false; }; let now = crate::render::gta6_maps::arrived(); - let drawn = matches!(self.gta6_own, Some(Ok(_))); - if !drawn || !came_in(was, key, self.gta6_decoding, self.gta6_maps.seen, now) { + let drawn = matches!(self.gta6.own, Some(Ok(_))); + if !drawn || !came_in(was, key, self.gta6.decoding, self.gta6.maps.seen, now) { return false; } let Some(mut scene) = self.renderer.take_gta6_scene() else { return false; }; // A map decoded from here on is taken on by a later frame. - self.gta6_maps.seen = now; + self.gta6.maps.seen = now; let read = crate::render::gta6_meshlets::meshlets(state); let validation = self.device.push_error_scope(wgpu::ErrorFilter::Validation); let rebound = match &read { @@ -55,19 +55,19 @@ impl RenderBridge { self.renderer.set_gta6_scene(Some(scene)); let (Some(Ok(meshlets)), Ok(Some(groups)), None) = (read, rebound, refused) else { // Not the surfaces the scene draws, or not bound: this frame prepares it from nothing. - self.game_scene_key = None; + self.game_scene.key = None; return false; }; - self.game_scene_key = Some(key); - self.gta6_decoding = meshlets.decoding; + self.game_scene.key = Some(key); + self.gta6.decoding = meshlets.decoding; let decoding = meshlets.decoding; // A pass a worker still builds is bound with the maps in now. - if let Some(building) = self.gta6_building.as_mut() { + if let Some(building) = self.gta6.building.as_mut() { *building = meshlets; } if groups > 0 { - self.gta6_maps.late += 1; - let elapsed = self.gta6_since.map(|(_, since, ..)| since.elapsed()); + self.gta6.maps.late += 1; + let elapsed = self.gta6.since.map(|(_, since, ..)| since.elapsed()); tracing::debug!( groups, ?elapsed, @@ -80,14 +80,14 @@ impl RenderBridge { /// Say once, with the time since Shaded was asked, that the active GTA VI drawable's maps are all bound, unless one is `decoding`. pub(super) fn said_all_in(&mut self, decoding: bool) { - if decoding || std::mem::replace(&mut self.gta6_maps.all_in, true) { + if decoding || std::mem::replace(&mut self.gta6.maps.all_in, true) { return; } - let elapsed = self.gta6_since.map(|(_, since, ..)| since.elapsed()); + let elapsed = self.gta6.since.map(|(_, since, ..)| since.elapsed()); tracing::info!( ?elapsed, - late = self.gta6_maps.late, - prepares = self.gta6_maps.prepares, + late = self.gta6.maps.late, + prepares = self.gta6.maps.prepares, "a GTA VI drawable's last map was bound" ); } diff --git a/src/render/viewport/gta6_late_maps_tests.rs b/src/render/viewport/gta6_late_maps_tests.rs index 6efbd81fd..e9b680a71 100644 --- a/src/render/viewport/gta6_late_maps_tests.rs +++ b/src/render/viewport/gta6_late_maps_tests.rs @@ -50,7 +50,7 @@ fn a_surface_whose_pass_is_built_draws_by_it_while_its_map_is_still_decoded() { wgpu::TextureFormat::Rgba8UnormSrgb, ); // Nothing a driver compiled is read from, or kept in, the configuration's folder. - bridge.gta6_pipelines = Default::default(); + bridge.gta6.pipelines = Default::default(); bridge.renderer.resize(&device, 64, 64); let validation = device.push_error_scope(wgpu::ErrorFilter::Validation); let stage = @@ -80,21 +80,21 @@ fn a_surface_whose_pass_is_built_draws_by_it_while_its_map_is_still_decoded() { })) }; for _ in 0..4000 { - bridge.gta6_own = bridge.prepare_gta6_meshlets_of(read); - if bridge.gta6_building.is_none() { + bridge.gta6.own = bridge.prepare_gta6_meshlets_of(read); + if bridge.gta6.building.is_none() { break; } std::thread::sleep(std::time::Duration::from_millis(5)); } - let own = bridge.gta6_own.clone().expect("a drawable"); + let own = bridge.gta6.own.clone().expect("a drawable"); let own = own.expect("drawn by its own pass while its map is decoded"); assert_eq!((own.drawn, own.rest, own.why), (1, 0, None)); let scene = bridge.renderer.gta6_scene().expect("a scene"); assert_eq!((scene.drawn(), scene.waiting.len()), (1, 0)); // It waits for the map, and was prepared once. - assert!(bridge.gta6_decoding); - assert_eq!(bridge.gta6_maps.prepares, 1); - assert!(!bridge.gta6_maps.all_in, "a map is still decoded"); + assert!(bridge.gta6.decoding); + assert_eq!(bridge.gta6.maps.prepares, 1); + assert!(!bridge.gta6.maps.all_in, "a map is still decoded"); let refused = pollster::block_on(validation.pop()).map(|e| e.to_string()); assert_eq!(refused, None); } diff --git a/src/render/viewport/mod.rs b/src/render/viewport/mod.rs index 8884501d9..4f2608724 100644 --- a/src/render/viewport/mod.rs +++ b/src/render/viewport/mod.rs @@ -1,8 +1,7 @@ use std::sync::Arc; use or_renderer::game_shaders::mesh::{Material as GameMaterial, MeshScene, Surface}; -use or_renderer::game_shaders::pack::GamePack; -use or_renderer::{LineVertex, MeshDraw, OrbitCamera, ShadingMode, ViewportRenderer}; +use or_renderer::{MeshDraw, OrbitCamera, ShadingMode, ViewportRenderer}; use wgpu::util::DeviceExt; use crate::render::lines::{build_axes, build_grid, document_lines}; @@ -24,6 +23,7 @@ mod pick_gta6_bound; mod pick_lines; mod posing; mod retarget; +mod state; mod texture_upload; mod usage; mod world; @@ -31,6 +31,10 @@ mod world_lights; mod world_sea; use retarget::{anim_scene_signature, retarget_uploads}; +use state::{ + DocumentMeshCache, DressedPedGpu, FrameState, GameSceneCache, Gta6MeshletState, + ParticleGpuCache, PhotoCaptureState, +}; pub(crate) use day::light_as_a_studio; pub(crate) use framing::bound_rows; @@ -188,113 +192,16 @@ impl LinesCacheKey { pub struct RenderBridge { device: Arc, queue: Arc, - renderer: ViewportRenderer, - - thumbnails: crate::render::thumbnails::ThumbnailRenderer, - - /// The active document's camera as of the last `end_frame`; the state owns it. - camera: OrbitCamera, - - texture_id: Option, - /// The view of the frame egui was last handed. - shown: Option, - - desired_size: (u32, u32), - - lines: Vec, - /// How many of `lines`, at their end, are bones and what plugins draw, which draw in front of the meshes. - bone_lines: usize, - - cached_doc_lines: Vec, - doc_lines_cache_key: Option, - - mode: ShadingMode, - - cached_mesh_draws: Vec, - offered_channels: Vec, - /// What the last mesh build's palette retarget did, for a panel to report. - palette_retarget: Option, - mesh_cache_key: Option, - cached_mesh_uploads: Vec, - skin_positions: Vec<[f32; 3]>, - skin_normals: Vec<[f32; 3]>, - /// The `skin_revision` of the pose `cached_mesh_uploads` hold. - skinned_revision: Option, - /// The game's shaders as a SPIR-V pack, which `ShadingMode::Shaded` draws with. - game_pack: Option>, - game_pack_epoch: u64, - /// The revision of the sky maps the renderer holds, which the install load moves when it reads them. - sky_textures_of: u64, - /// What the scene the viewport holds was prepared from. - game_scene_key: Option, - /// The pose the game's passes hold: its number and how many bones it has. - skin_key: Option<(u64, usize)>, - /// The textures the last game scene was made from, as decoded for it. - decoded: crate::render::game_scene::DecodedTextures, - game_scene_report: Option, - /// How the active GTA VI drawable's own mesh and pixel programs came out: the surfaces they - /// draw and the bindings left at nought, or why it draws without them; `None` where they - /// were not tried. - gta6_own: Option>, - /// The pipelines of the game's passes built for this pack and this viewport, kept across the scenes an edit makes again. - game_pipelines: or_renderer::game_shaders::mesh::PipelineCache, - /// The passes of GTA VI's own programs built so far, kept across the models opened. - gta6_pipelines: or_renderer::game_shaders::meshlets::MeshletPipelines, - /// The active GTA VI drawable while a worker still builds a pass of its own programs: asked - /// for again each frame, and the surfaces of that pass drawn as Material until then. - gta6_building: Option, - /// Whether a worker still decodes a map of the active GTA VI drawable: its surfaces draw with - /// the blank texel there, and it is read again once a map comes in. - gta6_decoding: bool, - /// The maps a worker still decodes for the active GTA VI drawable's surfaces the pack's passes - /// draw: they are prepared again once all are in. - gta6_fallback: Vec, - /// The GTA VI drawable Shaded was last asked for, since when, and whether its own programs - /// have drawn a surface of it since, and every surface they draw: how long a model takes to - /// each is said once. - gta6_since: Option<(crate::state::DocumentId, std::time::Instant, bool, bool)>, - /// What came of the active GTA VI drawable's maps since Shaded was asked for it. - gta6_maps: gta6_late_maps::LateMaps, - /// What the day the renderer holds was worked out from: the install's timecycle, the hour and the weather. - day_key: Option<(usize, u32, u32, crate::state::drivers::WeatherState)>, - /// What the day of a world drawn by the game's own programs was worked out for: the install's timecycle, the session's hour and its weather. - world_day_key: Option<(usize, u32, u64)>, - - gpu_textures: crate::render::gpu_budget::GpuTextures>, - /// The maps of open packs a worker still read when the meshes were last built without them. - maps_waiting: Vec<(u64, bool)>, - /// The bytes of those maps the build of the meshes uploaded so far. - maps_uploaded: usize, - /// What the draws are, when they are the dressed ped's and not a document's. - dressed_key: Option, - /// The bind group of each texture the dressed ped is drawn with, by the id its pixels were given. - dressed_textures: std::collections::HashMap>, - /// What the dressed ped's draws are made of, which a pose rewrites and the wireframe view draws. - held: dressed::Held, - cache_doc: Option, - cache_selected_entry: Option, - texture_report: crate::state::TextureResolutionReport, - material_bgl: Arc, - - particle_textures: crate::render::particles::ParticleTextureCache, - model_meshes: crate::render::particle_models::ParticleModelMeshCache, - - inputs: CameraInputs, - - visible: bool, - + frame: FrameState, + doc_cache: DocumentMeshCache, + game_scene: GameSceneCache, + gta6: Gta6MeshletState, + dressed: DressedPedGpu, + particles: ParticleGpuCache, + photo: PhotoCaptureState, /// The GTA VI world viewer's models on the device. world: world::WorldGpu, - - /// What the device came from, which `with_instance` gives for wgpu to count its objects through. - instance: Option, - - /// Set once the device is lost: nothing drawn on it after that is seen. - lost: Arc, - - /// Reusable staging buffers for headless photo readbacks `(px, primary, secondary)`. - photo_readback: Option<(u32, wgpu::Buffer, wgpu::Buffer)>, } impl RenderBridge { @@ -312,75 +219,45 @@ impl RenderBridge { told.store(true, std::sync::atomic::Ordering::Relaxed); }); Self { - lost, device, queue, renderer, - thumbnails: crate::render::thumbnails::ThumbnailRenderer::new(colour_format), - camera: OrbitCamera::default(), - texture_id: None, - shown: None, - desired_size: (1, 1), - lines: Vec::new(), - bone_lines: 0, - cached_doc_lines: Vec::new(), - doc_lines_cache_key: None, - mode: ShadingMode::default(), - cached_mesh_draws: Vec::new(), - offered_channels: Vec::new(), - palette_retarget: None, - mesh_cache_key: None, - cached_mesh_uploads: Vec::new(), - skin_positions: Vec::new(), - skin_normals: Vec::new(), - skinned_revision: None, - game_pack: None, - game_pack_epoch: 0, - sky_textures_of: 0, - game_scene_key: None, - skin_key: None, - decoded: Default::default(), - game_scene_report: None, - gta6_own: None, - game_pipelines: Default::default(), - gta6_pipelines: game_shaders::gta6_pipelines(), - gta6_building: None, - gta6_decoding: false, - gta6_fallback: Vec::new(), - gta6_since: None, - gta6_maps: Default::default(), - day_key: None, - world_day_key: None, - maps_waiting: Vec::new(), - maps_uploaded: 0, - gpu_textures: crate::render::gpu_budget::GpuTextures::new( - crate::state::DEFAULT_GPU_TEXTURE_MIB as usize * 1024 * 1024, - ), - dressed_key: None, - dressed_textures: Default::default(), - held: Default::default(), - cache_doc: None, - cache_selected_entry: None, - texture_report: Default::default(), - material_bgl, - inputs: CameraInputs::default(), - visible: false, + frame: FrameState { + camera: OrbitCamera::default(), + inputs: CameraInputs::default(), + mode: ShadingMode::default(), + desired_size: (1, 1), + visible: false, + texture_id: None, + shown: None, + material_bgl, + instance: None, + lost, + }, + doc_cache: DocumentMeshCache::new(), + game_scene: GameSceneCache::default(), + gta6: Gta6MeshletState::new(), + dressed: DressedPedGpu::default(), + particles: ParticleGpuCache::new(), + photo: PhotoCaptureState::new(colour_format), world: Default::default(), - instance: None, - particle_textures: crate::render::particles::ParticleTextureCache::new(), - model_meshes: crate::render::particle_models::ParticleModelMeshCache::new(), - photo_readback: None, } } + /// Record whether this bridge's device runs on a hardware adapter rather than a software fallback. + pub(crate) fn with_hardware_adapter(mut self, hardware: bool) -> Self { + self.gta6.hardware_adapter = hardware; + self + } + /// The colour of the sun and of the ambient light the game's passes are lit by. pub fn set_game_light(&mut self, sun_colour: glam::Vec3, ambient: glam::Vec3) { self.renderer.set_game_light(sun_colour, ambient); } pub fn refresh_particles(&mut self, state: &mut AppState) { - let cam_eye = self.camera.eye(); - let cam_forward = (self.camera.target - cam_eye).normalize_or(glam::Vec3::Z); + let cam_eye = self.frame.camera.eye(); + let cam_forward = (self.frame.camera.target - cam_eye).normalize_or(glam::Vec3::Z); let world_up = or_renderer::OrbitCamera::WORLD_UP; let cam_right = cam_forward.cross(world_up).normalize_or(glam::Vec3::X); let cam_up = cam_right.cross(cam_forward).normalize_or(world_up); @@ -409,14 +286,14 @@ impl RenderBridge { crate::render::particle_air::clear(&mut self.renderer); return; }; - self.particle_textures.invalidate_for_doc(doc_id); - crate::render::particles::gta6::prime(&mut self.particle_textures, state, doc_id); - self.model_meshes.invalidate_for_doc(doc_id); + self.particles.textures.invalidate_for_doc(doc_id); + crate::render::particles::gta6::prime(&mut self.particles.textures, state, doc_id); + self.particles.model_meshes.invalidate_for_doc(doc_id); let clip_regions = state.clip_regions.table(); - let retail_parity = matches!(self.mode, ShadingMode::Shaded); + let retail_parity = matches!(self.frame.mode, ShadingMode::Shaded); let batches = crate::render::particles::build_batches( - &mut self.particle_textures, + &mut self.particles.textures, Some(asset), &state.sim.manager, &clip_regions, @@ -424,10 +301,10 @@ impl RenderBridge { ); self.renderer.set_particle_batches(batches); - let camera_dir = (self.camera.target - self.camera.eye()).normalize_or_zero(); - let camera_pos = self.camera.eye(); + let camera_dir = (self.frame.camera.target - self.frame.camera.eye()).normalize_or_zero(); + let camera_pos = self.frame.camera.eye(); let trail_batches = crate::render::trails::build_trail_batches( - &mut self.particle_textures, + &mut self.particles.textures, Some(asset), &state.sim.manager, camera_dir, @@ -437,11 +314,11 @@ impl RenderBridge { self.renderer.set_trail_batches(trail_batches); let model_batches = crate::render::particle_models::build_model_batches( - &mut self.model_meshes, - &mut self.particle_textures, + &mut self.particles.model_meshes, + &mut self.particles.textures, Some(asset), &state.sim.manager, - self.camera.eye(), + self.frame.camera.eye(), retail_parity, ); self.renderer.set_model_batches(model_batches); @@ -450,30 +327,30 @@ impl RenderBridge { } pub fn texture_id(&self) -> Option { - self.texture_id + self.frame.texture_id } pub fn camera(&self) -> &OrbitCamera { - &self.camera + &self.frame.camera } pub fn mode(&self) -> ShadingMode { - self.mode + self.frame.mode } /// Whether the device this draws on is lost. Its owner draws nothing more on it: a painter /// that cannot write a buffer panics. pub fn device_lost(&self) -> bool { - self.lost.load(std::sync::atomic::Ordering::Relaxed) + self.frame.lost.load(std::sync::atomic::Ordering::Relaxed) } /// Every channel the meshes now on screen carry, in menu order. pub fn debug_channels(&self) -> &[crate::render::debug_channel::DebugChannel] { - &self.offered_channels + &self.doc_cache.offered_channels } pub fn debug_channels_available(&self) -> bool { - !self.offered_channels.is_empty() + !self.doc_cache.offered_channels.is_empty() } /// What the last mesh build's palette retarget did. @@ -481,87 +358,99 @@ impl RenderBridge { /// `None` where no mesh carried the skeleton its palette indexes, which is /// a different answer from "nothing resolved". pub fn palette_retarget(&self) -> Option<&or_anim::PaletteRetarget> { - self.palette_retarget.as_ref() + self.doc_cache.palette_retarget.as_ref() } pub fn set_mode(&mut self, mode: ShadingMode) { - self.mode = mode; + self.frame.mode = mode; } pub fn push_inputs(&mut self, inputs: CameraInputs) { - self.inputs.merge(inputs); + self.frame.inputs.merge(inputs); } pub fn set_desired_size(&mut self, width: u32, height: u32) { - self.desired_size = (width.max(1), height.max(1)); - self.visible = true; + self.frame.desired_size = (width.max(1), height.max(1)); + self.frame.visible = true; } /// How many line vertices the last `refresh_lines` assembled. pub fn drawn_lines(&self) -> usize { - self.lines.len() + self.doc_cache.lines.len() } /// The line vertices the last `refresh_lines` assembled, in the order they are drawn. #[cfg(test)] - pub(crate) fn line_vertices(&self) -> &[LineVertex] { - &self.lines + pub(crate) fn line_vertices(&self) -> &[or_renderer::LineVertex] { + &self.doc_cache.lines } /// The mesh draws and line vertices the active document last built. pub fn document_geometry(&self) -> (usize, usize) { - (self.cached_mesh_draws.len(), self.cached_doc_lines.len()) + ( + self.doc_cache.mesh_draws.len(), + self.doc_cache.cached_doc_lines.len(), + ) } pub fn begin_frame(&mut self) { - self.lines.clear(); - self.inputs = CameraInputs::default(); - self.visible = false; + self.doc_cache.lines.clear(); + self.frame.inputs = CameraInputs::default(); + self.frame.visible = false; self.world.shown = false; self.world.plain.shown = false; self.world.shaded_offered = false; } pub fn refresh_lines(&mut self, state: &AppState) { - self.lines.clear(); + self.doc_cache.lines.clear(); const GRID_CELLS: i32 = 10; const GRID_STEP: f32 = 1.0; if state.prefs.viewport.show_grid && state.active_workspace != crate::state::Workspace::Map { - self.lines.extend(build_grid(GRID_CELLS, GRID_STEP)); + self.doc_cache + .lines + .extend(build_grid(GRID_CELLS, GRID_STEP)); } // The dressed ped is a clothing preview: the garment is the strongest thing in it, so the modelling axes are left out there. if state.prefs.viewport.show_axis && state.active_workspace != crate::state::Workspace::Wardrobe { let half_extent = GRID_CELLS as f32 * GRID_STEP; - self.lines.extend(build_axes(half_extent)); + self.doc_cache.lines.extend(build_axes(half_extent)); } self.refresh_doc_lines_cache(state); - if !self.cached_doc_lines.is_empty() { - self.lines.extend_from_slice(&self.cached_doc_lines); + if !self.doc_cache.cached_doc_lines.is_empty() { + self.doc_cache + .lines + .extend_from_slice(&self.doc_cache.cached_doc_lines); } - if self.mode == ShadingMode::Wireframe + if self.frame.mode == ShadingMode::Wireframe && matches!( state.active_workspace, crate::state::Workspace::Wardrobe | crate::state::Workspace::Weapons ) { - self.lines.extend(self.dressed_wire_lines()); + let wire = self.dressed_wire_lines(); + self.doc_cache.lines.extend(wire); } - crate::render::particle_gizmos::append_gizmo_lines(&mut self.lines, &state.sim.manager); - let depth_tested = self.lines.len(); + crate::render::particle_gizmos::append_gizmo_lines( + &mut self.doc_cache.lines, + &state.sim.manager, + ); + let depth_tested = self.doc_cache.lines.len(); self.append_skeleton_lines(state); - crate::render::plugin_overlay::append(&mut self.lines, state); - crate::render::map_overlay::append(&mut self.lines, state); - self.bone_lines = self.lines.len() - depth_tested; + crate::render::plugin_overlay::append(&mut self.doc_cache.lines, state); + crate::render::map_overlay::append(&mut self.doc_cache.lines, state); + self.doc_cache.bone_lines = self.doc_cache.lines.len() - depth_tested; } fn append_skeleton_lines(&mut self, state: &AppState) { - self.lines.extend(bones::lines(state)); + self.doc_cache.lines.extend(bones::lines(state)); if state.active_workspace == crate::state::Workspace::Wardrobe { let ped = state.dressed_ped(); - self.lines + self.doc_cache + .lines .extend(crate::render::skeleton_lines::dressed_bones( &state.workbench.wardrobe.dressed, ped, @@ -572,8 +461,8 @@ impl RenderBridge { fn refresh_doc_lines_cache(&mut self, state: &AppState) { // The dressed ped has no document, and the one left active is not what the Wardrobe shows: its lines are the floor its heels stand on. if state.active_workspace == crate::state::Workspace::Wardrobe { - self.cached_doc_lines = crate::render::heel_floor::of(state); - self.doc_lines_cache_key = None; + self.doc_cache.cached_doc_lines = crate::render::heel_floor::of(state); + self.doc_cache.doc_lines_key = None; return; } // The assembled weapon has no document either, and draws no lines of its own; nor does the set of maps shown on the Map screen, whose lines are its overlay. @@ -581,12 +470,12 @@ impl RenderBridge { state.active_workspace, crate::state::Workspace::Weapons | crate::state::Workspace::Map ) { - self.cached_doc_lines.clear(); - self.doc_lines_cache_key = None; + self.doc_cache.cached_doc_lines.clear(); + self.doc_cache.doc_lines_key = None; return; } // A navmesh's lines are its polygons' outlines and its sectors, not a wireframe of the fill, and a cloth record's strands, edges and boxes have no surface, so both draw in every mode. - let wireframe = matches!(self.mode, ShadingMode::Wireframe) + let wireframe = matches!(self.frame.mode, ShadingMode::Wireframe) || state .active_document() .is_some_and(|d| d.kind() == crate::state::DocumentKind::Ynv) @@ -594,26 +483,26 @@ impl RenderBridge { .active_document() .is_some_and(|d| crate::render::gta6_cloth::is_cloth(&d.payload)); let Some(doc_id) = state.active_document else { - self.cached_doc_lines.clear(); - self.doc_lines_cache_key = None; + self.doc_cache.cached_doc_lines.clear(); + self.doc_cache.doc_lines_key = None; return; }; if !wireframe && !state.preview_scene.show_collision { - if !self.cached_doc_lines.is_empty() { - self.cached_doc_lines.clear(); + if !self.doc_cache.cached_doc_lines.is_empty() { + self.doc_cache.cached_doc_lines.clear(); } - self.doc_lines_cache_key = None; + self.doc_cache.doc_lines_key = None; return; } let key = LinesCacheKey { wireframe, ..LinesCacheKey::of(state, doc_id) }; - if self.doc_lines_cache_key == Some(key) { + if self.doc_cache.doc_lines_key == Some(key) { return; } - self.cached_doc_lines = document_lines(state, wireframe); - self.doc_lines_cache_key = Some(key); + self.doc_cache.cached_doc_lines = document_lines(state, wireframe); + self.doc_cache.doc_lines_key = Some(key); } pub fn refresh_meshes(&mut self, state: &AppState) { @@ -629,31 +518,34 @@ impl RenderBridge { fn refresh_meshes_inner(&mut self, state: &AppState, with_textures: bool) { let active = state.active_document; let active_entry = active.and_then(|id| selected_dictionary_entry(state, id)); - if active != self.cache_doc || active_entry != self.cache_selected_entry { - if active != self.cache_doc { - self.gpu_textures.clear(); + if active != self.doc_cache.cache_doc || active_entry != self.doc_cache.cache_selected_entry + { + if active != self.doc_cache.cache_doc { + self.doc_cache.gpu_textures.clear(); } else { - self.gpu_textures.retain(|(entry, _)| entry.is_some()); + self.doc_cache + .gpu_textures + .retain(|(entry, _)| entry.is_some()); } - self.cache_doc = active; - self.cache_selected_entry = active_entry; + self.doc_cache.cache_doc = active; + self.doc_cache.cache_selected_entry = active_entry; } let Some(doc_id) = active else { - self.cached_mesh_draws.clear(); - self.cached_mesh_uploads.clear(); - self.mesh_cache_key = None; + self.doc_cache.mesh_draws.clear(); + self.doc_cache.mesh_uploads.clear(); + self.doc_cache.mesh_key = None; self.clear_texture_report(); return; }; let key = MeshCacheKey::of(state, doc_id, 0); let maps_in = with_textures - && !self.maps_waiting.is_empty() - && material_maps::all_in(&self.maps_waiting); - if with_textures && self.mesh_cache_key == Some(key) && !maps_in { + && !self.doc_cache.maps_waiting.is_empty() + && material_maps::all_in(&self.doc_cache.maps_waiting); + if with_textures && self.doc_cache.mesh_key == Some(key) && !maps_in { return; } - self.dressed_key = None; + self.dressed.key = None; let mut uploads = build_meshes_for_active_document(state); // ⚠ **Here and nowhere else.** A palette is an index into the @@ -661,12 +553,12 @@ impl RenderBridge { // skeleton source — so this runs once per pairing, before any pose is // applied. Doing it in `refresh_skinning` would compose the mapping // with itself on every frame. - self.palette_retarget = retarget_uploads(&mut uploads, state); + self.doc_cache.palette_retarget = retarget_uploads(&mut uploads, state); let any_skinned = uploads.iter().any(|u| u.is_skinned()); // ⚠ Taken before the uploads are dropped. They are retained only for - // a skinned asset, so reading the channels off `cached_mesh_uploads` + // a skinned asset, so reading the channels off `mesh_uploads` // would report none for every static drawable. - self.offered_channels = { + self.doc_cache.offered_channels = { let mut all: Vec<_> = uploads .iter() .flat_map(|upload| upload.channels.iter().copied()) @@ -675,38 +567,38 @@ impl RenderBridge { all.dedup(); all }; - self.cached_mesh_draws = if with_textures { + self.doc_cache.mesh_draws = if with_textures { self.upload_meshes(&uploads, state, None) } else { self.upload_meshes_untextured(&uploads) }; - self.cached_mesh_uploads = if any_skinned { uploads } else { Vec::new() }; - self.skinned_revision = None; - self.mesh_cache_key = with_textures.then_some(key); + self.doc_cache.mesh_uploads = if any_skinned { uploads } else { Vec::new() }; + self.doc_cache.skinned_revision = None; + self.doc_cache.mesh_key = with_textures.then_some(key); } pub fn refresh_skinning(&mut self, state: &AppState) { - if self.cached_mesh_uploads.is_empty() { + if self.doc_cache.mesh_uploads.is_empty() { return; } if posing::skin_of(state).1.is_empty() { - if self.skinned_revision.take().is_some() { + if self.doc_cache.skinned_revision.take().is_some() { self.write_bind_positions(); } return; } let moved = pose_uploads( - &mut self.cached_mesh_uploads, - &mut self.skinned_revision, + &mut self.doc_cache.mesh_uploads, + &mut self.doc_cache.skinned_revision, state, - &mut self.skin_positions, - &mut self.skin_normals, + &mut self.doc_cache.skin_positions, + &mut self.doc_cache.skin_normals, ); for index in moved { if let (Some(draw), Some(upload)) = ( - self.cached_mesh_draws.get(index), - self.cached_mesh_uploads.get(index), + self.doc_cache.mesh_draws.get(index), + self.doc_cache.mesh_uploads.get(index), ) { self.queue.write_buffer( &draw.vertex_buffer, @@ -718,7 +610,7 @@ impl RenderBridge { } fn write_bind_positions(&mut self) { - for (index, upload) in self.cached_mesh_uploads.iter_mut().enumerate() { + for (index, upload) in self.doc_cache.mesh_uploads.iter_mut().enumerate() { let Some(skinning) = upload.skinning.as_ref() else { continue; }; @@ -731,7 +623,7 @@ impl RenderBridge { vertex.position = *position; vertex.normal = *normal; } - if let Some(draw) = self.cached_mesh_draws.get(index) { + if let Some(draw) = self.doc_cache.mesh_draws.get(index) { self.queue.write_buffer( &draw.vertex_buffer, 0, @@ -742,23 +634,28 @@ impl RenderBridge { } pub fn end_frame(&mut self, encoder: &mut wgpu::CommandEncoder, state: &mut AppState) -> bool { - self.camera = state.step_viewport_camera(self.inputs).clone(); - self.gpu_textures + self.frame.camera = state.step_viewport_camera(self.frame.inputs).clone(); + self.doc_cache + .gpu_textures .set_budget(state.prefs.gpu_texture_budget()); state.gpu_usage = self.gpu_usage(); state.gpu_stages = self.renderer.gpu_stages(); - if !self.visible { + if !self.frame.visible { return false; } - let (w, h) = self.desired_size; + let (w, h) = self.frame.desired_size; self.renderer.resize(&self.device, w, h); - self.renderer - .set_lines(&self.device, &self.queue, &self.lines, self.bone_lines); + self.renderer.set_lines( + &self.device, + &self.queue, + &self.doc_cache.lines, + self.doc_cache.bone_lines, + ); - let mesh_draws = if draws_meshes(self.mode) { - self.cached_mesh_draws.clone() + let mesh_draws = if draws_meshes(self.frame.mode) { + self.doc_cache.mesh_draws.clone() } else { Vec::new() }; @@ -771,29 +668,33 @@ impl RenderBridge { .set_sky_background( state.drivers.world_background.sky || (self.world.shown && !self.world.plain.shown) - || (self.world.plain.shown && self.mode == ShadingMode::Shaded), + || (self.world.plain.shown && self.frame.mode == ShadingMode::Shaded), ); self.refresh_day(state); // A world the game's own programs draw is fed the game's clock; a drawable alone keeps the timer it had. - let fed = self.world.plain.shown && self.mode == ShadingMode::Shaded; + let fed = self.world.plain.shown && self.frame.mode == ShadingMode::Shaded; (self.renderer).set_game_seconds(fed.then(|| or_transport::clock::game_seconds() as f32)); self.refresh_key_light(state); // The sprites are laid out for the camera of this frame self.renderer - .prepare_game_particles(&self.device, &self.queue, &self.camera); + .prepare_game_particles(&self.device, &self.queue, &self.frame.camera); self.end_world(); self.renderer.prepare_game_frame(&self.device, &self.queue); let started = std::time::Instant::now(); - self.renderer - .prepare_world_fed(&self.device, &self.queue, &self.camera, self.mode); + self.renderer.prepare_world_fed( + &self.device, + &self.queue, + &self.frame.camera, + self.frame.mode, + ); let prepared = started.elapsed(); self.renderer - .render(encoder, &self.queue, &self.camera, self.mode); + .render(encoder, &self.queue, &self.frame.camera, self.frame.mode); self.world.cost.fed = (prepared, started.elapsed() - prepared); // A frame of a game's programs is shown through another view of the target than one of OpenRage's own: egui is handed it anew. - let shown = self.renderer.shown_view(self.mode).clone(); - let another = self.shown.as_ref() != Some(&shown); - self.shown = Some(shown); + let shown = self.renderer.shown_view(self.frame.mode).clone(); + let another = self.frame.shown.as_ref() != Some(&shown); + self.frame.shown = Some(shown); self.renderer.take_dirty() || another } @@ -836,8 +737,8 @@ impl RenderBridge { ) -> Vec { if texture_entry.is_none() { self.rebuild_texture_report(uploads, state); - self.maps_waiting.clear(); - self.maps_uploaded = 0; + self.doc_cache.maps_waiting.clear(); + self.doc_cache.maps_uploaded = 0; } // ⚠ Each name once for each mesh source: binding a texture hashes every byte it stores. let mut bound = std::collections::HashMap::new(); @@ -906,54 +807,58 @@ impl RenderBridge { .flatten(); if let Some(map) = in_pack { let stamp = map.stamp(); - if let Some(bg) = self.gpu_textures.get(&key, stamp) { + if let Some(bg) = self.doc_cache.gpu_textures.get(&key, stamp) { return Some(bg); } let read = map.read(bump); // Past the build's share of uploads a map waits for the next build, a frame later. - let spent = self.maps_uploaded > material_maps::UPLOAD_BYTES; + let spent = self.doc_cache.maps_uploaded > material_maps::UPLOAD_BYTES; let prepared = match material_maps::prepared(map, bump) { Ok(prepared) if !spent => prepared?, _ => { - self.maps_waiting.push(read); + self.doc_cache.maps_waiting.push(read); return None; } }; - self.maps_uploaded += prepared.rgba.len(); + self.doc_cache.maps_uploaded += prepared.rgba.len(); let (bg, bytes) = texture_upload::upload_rgba( &self.device, &self.queue, - &self.material_bgl, + &self.frame.material_bgl, prepared.size, &prepared.rgba, prepared.srgb, ); let bg = Arc::new(bg); - self.gpu_textures.insert(key, bg.clone(), bytes, stamp); + self.doc_cache + .gpu_textures + .insert(key, bg.clone(), bytes, stamp); return Some(bg); } let found = bound_texture(state, from, entry, &name); let Some((texture, stamp)) = found else { - self.gpu_textures.remove(&key); + self.doc_cache.gpu_textures.remove(&key); return None; }; - if let Some(bg) = self.gpu_textures.get(&key, stamp) { + if let Some(bg) = self.doc_cache.gpu_textures.get(&key, stamp) { return Some(bg); } let (bg, bytes) = upload_texture( &self.device, &self.queue, - &self.material_bgl, + &self.frame.material_bgl, &texture, bump, )?; let bg = Arc::new(bg); - self.gpu_textures.insert(key, bg.clone(), bytes, stamp); + self.doc_cache + .gpu_textures + .insert(key, bg.clone(), bytes, stamp); Some(bg) } pub fn texture_report(&self) -> &crate::state::TextureResolutionReport { - &self.texture_report + &self.doc_cache.texture_report } fn rebuild_texture_report(&mut self, uploads: &[MeshUpload], state: &AppState) { @@ -963,32 +868,32 @@ impl RenderBridge { let wanted = uploads .iter() .filter_map(|u| Some((u.source, u.texture_name.clone()?))); - let epoch = self.texture_report.epoch.wrapping_add(1); - self.texture_report = + let epoch = self.doc_cache.texture_report.epoch.wrapping_add(1); + self.doc_cache.texture_report = crate::state::texture_resolution::report(state, selection, wanted, epoch); } fn clear_texture_report(&mut self) { - let epoch = self.texture_report.epoch.wrapping_add(1); - self.texture_report = crate::state::TextureResolutionReport { + let epoch = self.doc_cache.texture_report.epoch.wrapping_add(1); + self.doc_cache.texture_report = crate::state::TextureResolutionReport { epoch, ..Default::default() }; } pub fn invalidate_texture_resolution(&mut self) { - self.gpu_textures.clear(); - self.mesh_cache_key = None; - self.game_scene_key = None; + self.doc_cache.gpu_textures.clear(); + self.doc_cache.mesh_key = None; + self.game_scene.key = None; } /// The view of the frame egui is handed: made again where [`Self::end_frame`] says so, which it does when another view shows the frame. pub fn colour_texture_view(&self) -> &wgpu::TextureView { - self.renderer.shown_view(self.mode) + self.renderer.shown_view(self.frame.mode) } pub fn set_texture_id(&mut self, id: egui::TextureId) { - self.texture_id = Some(id); + self.frame.texture_id = Some(id); } } @@ -1027,7 +932,7 @@ mod tests { wgpu::TextureFormat::Rgba8UnormSrgb, ); assert!(bridge.set_game_pack_path(std::path::Path::new(&pack))); - bridge.mode = ShadingMode::Shaded; + bridge.frame.mode = ShadingMode::Shaded; bridge.renderer.resize(&device, PX, PX); let validation = device.push_error_scope(wgpu::ErrorFilter::Validation); @@ -1114,10 +1019,11 @@ mod tests { wgpu::TextureFormat::Rgba8UnormSrgb, ); assert!(bridge.set_game_pack_path(std::path::Path::new(&pack))); - bridge.mode = ShadingMode::Shaded; + bridge.frame.mode = ShadingMode::Shaded; bridge.renderer.resize(&device, PX, PX); let manifest = bridge - .game_pack + .game_scene + .pack .as_ref() .expect("a pack") .manifest() @@ -1245,7 +1151,7 @@ mod tests { Arc::new(queue), wgpu::TextureFormat::Rgba8UnormSrgb, ); - bridge.mode = ShadingMode::Shaded; + bridge.frame.mode = ShadingMode::Shaded; bridge.renderer.resize(&device, PX, PX); let mut state = AppState::new(); diff --git a/src/render/viewport/photo.rs b/src/render/viewport/photo.rs index 44ed8c597..501312264 100644 --- a/src/render/viewport/photo.rs +++ b/src/render/viewport/photo.rs @@ -164,11 +164,11 @@ impl RenderBridge { &mut self, key: crate::render::thumbnails::ThumbKey, ) -> Option<&crate::render::thumbnails::Thumbnail> { - self.thumbnails.get(&key) + self.photo.thumbnails.get(&key) } pub fn request_thumbnail(&mut self, key: crate::render::thumbnails::ThumbKey) { - self.thumbnails.request(key); + self.photo.thumbnails.request(key); } /// Ask for a tile of geometry no open document holds, such as a model inside an archive. @@ -177,11 +177,11 @@ impl RenderBridge { key: crate::render::thumbnails::ThumbKey, uploads: Vec, ) { - self.thumbnails.request_with(key, uploads); + self.photo.thumbnails.request_with(key, uploads); } pub fn thumbnail_pending(&self, key: crate::render::thumbnails::ThumbKey) -> bool { - self.thumbnails.is_pending(&key) + self.photo.thumbnails.is_pending(&key) } pub fn thumbnail_key( @@ -190,7 +190,7 @@ impl RenderBridge { doc: &crate::state::Document, selection: crate::state::SelectionKey, ) -> crate::render::thumbnails::ThumbKey { - crate::render::thumbnails::ThumbKey::of(doc, selection).drawn_by(state, self.mode) + crate::render::thumbnails::ThumbKey::of(doc, selection).drawn_by(state, self.frame.mode) } pub fn forget_document_thumbnails( @@ -198,13 +198,13 @@ impl RenderBridge { doc: DocumentId, egui_renderer: &mut egui_wgpu::Renderer, ) { - self.thumbnails.forget_document(doc, egui_renderer); + self.photo.thumbnails.forget_document(doc, egui_renderer); } /// Starts building the thumbnails' renderer on a worker, which the first model otherwise builds on its frame. pub fn warm_thumbnails(mut self) -> Self { let (device, queue) = (self.device.clone(), self.queue.clone()); - self.thumbnails.warm(device, queue); + self.photo.thumbnails.warm(device, queue); self } @@ -216,15 +216,15 @@ impl RenderBridge { ) { use crate::render::thumbnails::{camera_for, geometry_for, tile_mode, Thumbnail}; - if !self.thumbnails.has_pending() { + if !self.photo.thumbnails.has_pending() { return; } let device = self.device.clone(); let queue = self.queue.clone(); - let mode = tile_mode(self.mode); + let mode = tile_mode(self.frame.mode); let (lod, channel) = (state.preview_scene.lod, state.preview_scene.debug_channel); - let next = self.thumbnails.next_to_draw(|key| { + let next = self.photo.thumbnails.next_to_draw(|key| { let payload = &state.document(key.doc)?.payload; crate::render::meshes::tile_job(payload, key.selection, lod, channel) }); @@ -241,19 +241,21 @@ impl RenderBridge { let triangles: usize = uploads.iter().map(|u| u.indices.len() / 3).sum(); let Some(camera) = camera_for(&uploads) else { - self.thumbnails + self.photo + .thumbnails .insert(key, Thumbnail::empty(), egui_renderer); return; }; let draws = self.upload_meshes(&uploads, state, Some(key.selection)); let texture = self + .photo .thumbnails .render_one(&device, &queue, encoder, draws, &camera, mode); let view = texture.create_view(&Default::default()); let id = egui_renderer.register_native_texture(&device, &view, wgpu::FilterMode::Linear); - self.thumbnails.insert( + self.photo.thumbnails.insert( key, Thumbnail::rendered(id, triangles, texture), egui_renderer, @@ -267,14 +269,14 @@ impl RenderBridge { pub fn prepare_gta6(&mut self, state: &mut AppState, px: u32) -> bool { self.set_desired_size(px, px); self.renderer.resize(&self.device, px, px); - self.mode = ShadingMode::Shaded; + self.frame.mode = ShadingMode::Shaded; self.refresh_game_scene(state); - let report = self.game_scene_report.as_ref(); + let report = self.game_scene.report.as_ref(); let translated = matches!(report.and_then(|r| r.gta6.as_ref()), Some((false, _))); translated - && self.gta6_building.is_none() - && !self.gta6_decoding - && self.gta6_fallback.is_empty() + && self.gta6.building.is_none() + && !self.gta6.decoding + && self.gta6.fallback.is_empty() } /// Render only the active GTA VI scene's deferred G-buffer targets (skipping shadow map, @@ -282,14 +284,14 @@ impl RenderBridge { pub fn render_gta6_targets_only(&mut self, state: &mut AppState, px: u32) { self.begin_frame(); self.set_desired_size(px, px); - self.mode = ShadingMode::Shaded; - self.camera = state.step_viewport_camera(self.inputs).clone(); + self.frame.mode = ShadingMode::Shaded; + self.frame.camera = state.step_viewport_camera(self.frame.inputs).clone(); self.renderer.resize(&self.device, px, px); self.refresh_day(state); self.refresh_key_light(state); let mut encoder = self.device.create_command_encoder(&Default::default()); self.renderer - .render_gta6_targets_only(&mut encoder, &self.queue, &self.camera); + .render_gta6_targets_only(&mut encoder, &self.queue, &self.frame.camera); self.queue.submit(std::iter::once(encoder.finish())); } @@ -317,7 +319,7 @@ impl RenderBridge { } /// Whether the active GTA VI scene has fallback Material surfaces (or no meshlet scene) that - /// need textured `cached_mesh_draws`. + /// need textured `mesh_draws`. pub fn gta6_needs_material_meshes(&self) -> bool { self.renderer .gta6_scene() @@ -326,17 +328,17 @@ impl RenderBridge { /// Whether Material fallback textures are still decoding in `material_maps`. pub fn material_maps_waiting(&self) -> bool { - !self.maps_waiting.is_empty() + !self.doc_cache.maps_waiting.is_empty() } fn ensure_photo_readback(&mut self, px: u32) -> &(u32, wgpu::Buffer, wgpu::Buffer) { - let needs = !matches!(self.photo_readback, Some((held, _, _)) if held == px); + let needs = !matches!(self.photo.readback, Some((held, _, _)) if held == px); if needs { let a = crate::render::read_back::staging_buffer(&self.device, px, px); let b = crate::render::read_back::staging_buffer(&self.device, px, px); - self.photo_readback = Some((px, a, b)); + self.photo.readback = Some((px, a, b)); } - self.photo_readback.as_ref().unwrap() + self.photo.readback.as_ref().unwrap() } /// Render the prepared GTA VI Shaded scene and read back `(picture, whole)` in the minimum @@ -353,12 +355,12 @@ impl RenderBridge { self.refresh_meshes(state); self.refresh_skinning(state); } else if ground && !forward_pair { - // Only `ShadingMode::Solid` uses `cached_mesh_draws` here; skip Material texture decode. + // Only `ShadingMode::Solid` uses `mesh_draws` here; skip Material texture decode. self.refresh_meshes_untextured(state); self.refresh_skinning(state); } else { - self.cached_mesh_draws.clear(); - self.cached_mesh_uploads.clear(); + self.doc_cache.mesh_draws.clear(); + self.doc_cache.mesh_uploads.clear(); } }); @@ -369,13 +371,13 @@ impl RenderBridge { // Submission 1: lit scene with ground shadow -> buf_whole. self.begin_frame(); self.set_desired_size(px, px); - self.mode = ShadingMode::Shaded; + self.frame.mode = ShadingMode::Shaded; let mut enc_whole = self.device.create_command_encoder(&Default::default()); crate::photo::timing::time("12b cap: end_frame", || { self.end_frame(&mut enc_whole, state); }); { - let (_, buf_whole, _) = self.photo_readback.as_ref().unwrap(); + let (_, buf_whole, _) = self.photo.readback.as_ref().unwrap(); crate::render::read_back::encode_copy( &mut enc_whole, self.renderer.colour_texture(), @@ -393,14 +395,14 @@ impl RenderBridge { state.drivers.world_background.ground = false; self.begin_frame(); self.set_desired_size(px, px); - self.mode = ShadingMode::Shaded; + self.frame.mode = ShadingMode::Shaded; let mut enc_pic = self.device.create_command_encoder(&Default::default()); crate::photo::timing::time("12b cap: end_frame", || { self.end_frame(&mut enc_pic, state); }); state.drivers.world_background.ground = was; { - let (_, _, buf_pic) = self.photo_readback.as_ref().unwrap(); + let (_, _, buf_pic) = self.photo.readback.as_ref().unwrap(); crate::render::read_back::encode_copy( &mut enc_pic, self.renderer.colour_texture(), @@ -418,7 +420,7 @@ impl RenderBridge { }) { return Err(format!("the readback was refused: {error}")); } - let (_, buf_whole, buf_pic) = self.photo_readback.as_ref().unwrap(); + let (_, buf_whole, buf_pic) = self.photo.readback.as_ref().unwrap(); let mut imgs = crate::photo::timing::time("12e cap: map_and_read", || { crate::render::read_back::map_and_read( &self.device, @@ -438,13 +440,13 @@ impl RenderBridge { // Single submission: lit scene -> buf_whole, and optional Solid silhouette -> buf_solid. self.begin_frame(); self.set_desired_size(px, px); - self.mode = ShadingMode::Shaded; + self.frame.mode = ShadingMode::Shaded; let mut encoder = self.device.create_command_encoder(&Default::default()); crate::photo::timing::time("12b cap: end_frame", || { self.end_frame(&mut encoder, state); }); { - let (_, buf_whole, _) = self.photo_readback.as_ref().unwrap(); + let (_, buf_whole, _) = self.photo.readback.as_ref().unwrap(); crate::render::read_back::encode_copy( &mut encoder, self.renderer.colour_texture(), @@ -454,10 +456,10 @@ impl RenderBridge { ); } if ground { - let camera = self.camera.clone(); + let camera = self.frame.camera.clone(); self.renderer .render(&mut encoder, &self.queue, &camera, ShadingMode::Solid); - let (_, _, buf_solid) = self.photo_readback.as_ref().unwrap(); + let (_, _, buf_solid) = self.photo.readback.as_ref().unwrap(); crate::render::read_back::encode_copy( &mut encoder, self.renderer.colour_texture(), @@ -474,7 +476,7 @@ impl RenderBridge { { return Err(format!("the readback was refused: {error}")); } - let (_, buf_whole, buf_solid) = self.photo_readback.as_ref().unwrap(); + let (_, buf_whole, buf_solid) = self.photo.readback.as_ref().unwrap(); let (mut whole, covered) = crate::photo::timing::time("12e cap: map_and_read", || -> Result<_, String> { if ground { @@ -547,13 +549,13 @@ impl RenderBridge { self.renderer.resize(&self.device, px, px); self.renderer.set_background([0.0; 4]); self.renderer.set_meshes(draws); - let colour = match (game, self.game_pack.clone()) { + let colour = match (game, self.game_scene.pack.clone()) { (Some(surfaces), Some(pack)) if !surfaces.is_empty() => { // A pass the device refuses is reported by its error scope and not by a panic let validation = self.device.push_error_scope(wgpu::ErrorFilter::Validation); let scene = crate::photo::timing::time("30 prepare game scene", || { MeshScene::prepare_with( - &mut self.game_pipelines, + &mut self.game_scene.pipelines, &self.device, &self.queue, &pack, @@ -562,7 +564,7 @@ impl RenderBridge { ) }); if let Some(error) = pollster::block_on(validation.pop()) { - self.game_pipelines = Default::default(); + self.game_scene.pipelines = Default::default(); return Err(format!("the game's passes did not prepare: {error}")); } self.renderer.set_game_scene(Some(scene)); @@ -685,7 +687,7 @@ impl RenderBridge { let (group, _) = texture_upload::upload_rgba( &self.device, &self.queue, - &self.material_bgl, + &self.frame.material_bgl, (image.width, image.height), &rgba, image.srgb, diff --git a/src/render/viewport/state.rs b/src/render/viewport/state.rs new file mode 100644 index 000000000..bd0eae9ac --- /dev/null +++ b/src/render/viewport/state.rs @@ -0,0 +1,197 @@ +//! Cohesive per-pipeline state sub-structs owned by [`super::RenderBridge`]. + +use std::sync::Arc; + +use or_renderer::game_shaders::pack::GamePack; +use or_renderer::{LineVertex, MeshDraw, OrbitCamera, ShadingMode}; + +use super::game_shaders::GameSceneReport; +use super::{CameraInputs, LinesCacheKey, MeshCacheKey}; +use crate::render::meshes::MeshUpload; +use crate::state::DocumentId; + +/// Camera, shading mode, sizing, presentation handle, and device-health state for the viewport. +pub(super) struct FrameState { + /// The active document's camera as of the last `end_frame`; the state owns it. + pub camera: OrbitCamera, + pub inputs: CameraInputs, + pub mode: ShadingMode, + pub desired_size: (u32, u32), + pub visible: bool, + pub texture_id: Option, + /// The view of the frame egui was last handed. + pub shown: Option, + pub material_bgl: Arc, + /// What the device came from, which `with_instance` gives for wgpu to count its objects through. + pub instance: Option, + /// Set once the device is lost: nothing drawn on it after that is seen. + pub lost: Arc, +} + +/// Cached document lines, meshes, CPU skinning scratch buffers, material textures, and invalidation keys. +pub(super) struct DocumentMeshCache { + pub lines: Vec, + /// How many of `lines`, at their end, are bones and what plugins draw, which draw in front of the meshes. + pub bone_lines: usize, + pub cached_doc_lines: Vec, + pub doc_lines_key: Option, + pub mesh_draws: Vec, + pub mesh_uploads: Vec, + pub mesh_key: Option, + pub offered_channels: Vec, + /// What the last mesh build's palette retarget did, for a panel to report. + pub palette_retarget: Option, + pub skin_positions: Vec<[f32; 3]>, + pub skin_normals: Vec<[f32; 3]>, + /// The `skin_revision` of the pose `mesh_uploads` hold. + pub skinned_revision: Option, + pub gpu_textures: crate::render::gpu_budget::GpuTextures>, + /// The maps of open packs a worker still read when the meshes were last built without them. + pub maps_waiting: Vec<(u64, bool)>, + /// The bytes of those maps the build of the meshes uploaded so far. + pub maps_uploaded: usize, + pub cache_doc: Option, + pub cache_selected_entry: Option, + pub texture_report: crate::state::TextureResolutionReport, +} + +impl DocumentMeshCache { + pub(super) fn new() -> Self { + Self { + lines: Vec::new(), + bone_lines: 0, + cached_doc_lines: Vec::new(), + doc_lines_key: None, + mesh_draws: Vec::new(), + mesh_uploads: Vec::new(), + mesh_key: None, + offered_channels: Vec::new(), + palette_retarget: None, + skin_positions: Vec::new(), + skin_normals: Vec::new(), + skinned_revision: None, + gpu_textures: crate::render::gpu_budget::GpuTextures::new( + crate::state::DEFAULT_GPU_TEXTURE_MIB as usize * 1024 * 1024, + ), + maps_waiting: Vec::new(), + maps_uploaded: 0, + cache_doc: None, + cache_selected_entry: None, + texture_report: Default::default(), + } + } +} + +/// GTA V game-shader pack, prepared scene/skin/day invalidation keys, decoded textures, and pipeline cache. +#[derive(Default)] +pub(super) struct GameSceneCache { + /// The game's shaders as a SPIR-V pack, which `ShadingMode::Shaded` draws with. + pub pack: Option>, + pub pack_epoch: u64, + /// What the scene the viewport holds was prepared from. + pub key: Option, + /// The pose the game's passes hold: its number and how many bones it has. + pub skin_key: Option<(u64, usize)>, + /// The textures the last game scene was made from, as decoded for it. + pub decoded: crate::render::game_scene::DecodedTextures, + pub report: Option, + /// The pipelines of the game's passes built for this pack and this viewport, kept across the scenes an edit makes again. + pub pipelines: or_renderer::game_shaders::mesh::PipelineCache, + /// The revision of the sky maps the renderer holds, which the install load moves when it reads them. + pub sky_textures_of: u64, + /// What the day the renderer holds was worked out from: the install's timecycle, the hour and the weather. + pub day_key: Option<(usize, u32, u32, crate::state::drivers::WeatherState)>, + /// What the day of a world drawn by the game's own programs was worked out for: the install's timecycle, the session's hour and its weather. + pub world_day_key: Option<(usize, u32, u64)>, +} + +/// GTA VI meshlet async pipeline build, late-map binding, and fallback decode state. +pub(crate) struct Gta6MeshletState { + /// How the active GTA VI drawable's own mesh and pixel programs came out: the surfaces they + /// draw and the bindings left at nought, or why it draws without them; `None` where they + /// were not tried. + pub(super) own: Option>, + /// The passes of GTA VI's own programs built so far, kept across the models opened. + pub(super) pipelines: or_renderer::game_shaders::meshlets::MeshletPipelines, + /// The active GTA VI drawable while a worker still builds a pass of its own programs: asked + /// for again each frame, and the surfaces of that pass drawn as Material until then. + pub(super) building: Option, + /// Whether a worker still decodes a map of the active GTA VI drawable: its surfaces draw with + /// the blank texel there, and it is read again once a map comes in. + pub(super) decoding: bool, + /// The maps a worker still decodes for the active GTA VI drawable's surfaces the pack's passes + /// draw: they are prepared again once all are in. + pub(super) fallback: Vec, + /// The GTA VI drawable Shaded was last asked for, since when, and whether its own programs + /// have drawn a surface of it since, and every surface they draw: how long a model takes to + /// each is said once. + pub(super) since: Option<(DocumentId, std::time::Instant, bool, bool)>, + /// What came of the active GTA VI drawable's maps since Shaded was asked for it. + pub(super) maps: super::gta6_late_maps::LateMaps, + /// Whether the graphics device sits on a hardware adapter rather than a software fallback. + pub(crate) hardware_adapter: bool, +} + +impl Gta6MeshletState { + pub(super) fn new() -> Self { + Self { + own: None, + pipelines: super::game_shaders::gta6_pipelines(), + building: None, + decoding: false, + fallback: Vec::new(), + since: None, + maps: Default::default(), + hardware_adapter: false, + } + } + + pub(super) fn clear_scene(&mut self) { + self.own = None; + self.building = None; + self.decoding = false; + self.fallback.clear(); + } +} + +/// Dressed-ped draw key, uploaded diffuse bind groups, and poseable mesh/wireframe state. +#[derive(Default)] +pub(super) struct DressedPedGpu { + /// What the draws are, when they are the dressed ped's and not a document's. + pub key: Option, + /// The bind group of each texture the dressed ped is drawn with, by the id its pixels were given. + pub textures: std::collections::HashMap>, + /// What the dressed ped's draws are made of, which a pose rewrites and the wireframe view draws. + pub held: super::dressed::Held, +} + +/// Particle texture and model mesh caches owned by the viewport bridge. +pub(super) struct ParticleGpuCache { + pub textures: crate::render::particles::ParticleTextureCache, + pub model_meshes: crate::render::particle_models::ParticleModelMeshCache, +} + +impl ParticleGpuCache { + pub(super) fn new() -> Self { + Self { + textures: crate::render::particles::ParticleTextureCache::new(), + model_meshes: crate::render::particle_models::ParticleModelMeshCache::new(), + } + } +} + +/// Offscreen thumbnail renderer and reusable photo readback staging buffers. +pub(super) struct PhotoCaptureState { + pub thumbnails: crate::render::thumbnails::ThumbnailRenderer, + /// Reusable staging buffers for headless photo readbacks `(px, primary, secondary)`. + pub readback: Option<(u32, wgpu::Buffer, wgpu::Buffer)>, +} + +impl PhotoCaptureState { + pub(super) fn new(colour_format: wgpu::TextureFormat) -> Self { + Self { + thumbnails: crate::render::thumbnails::ThumbnailRenderer::new(colour_format), + readback: None, + } + } +} diff --git a/src/render/viewport/usage.rs b/src/render/viewport/usage.rs index bc258d826..e078ebada 100644 --- a/src/render/viewport/usage.rs +++ b/src/render/viewport/usage.rs @@ -6,7 +6,7 @@ use crate::render::gpu_budget::{DriverObjects, GpuUsage}; impl RenderBridge { /// Count the device's objects through `instance`, which made it. pub fn with_instance(mut self, instance: wgpu::Instance) -> Self { - self.instance = Some(instance); + self.frame.instance = Some(instance); self } @@ -18,15 +18,16 @@ impl RenderBridge { particle_instance_bytes: resident.particle_instance_buffers as usize, uniform_buffer_bytes: resident.uniform_buffers as usize, default_texture_bytes: resident.default_textures as usize, - texture_bytes: self.gpu_textures.bytes(), + texture_bytes: self.doc_cache.gpu_textures.bytes(), buffer_bytes: self - .cached_mesh_draws + .doc_cache + .mesh_draws .iter() .map(|d| (d.vertex_buffer.size() + d.index_buffer.size()) as usize) .sum(), target_bytes: self.renderer.target_bytes() as usize, - thumbnail_bytes: self.thumbnails.bytes() as usize, - driver: DriverObjects::read(self.instance.as_ref(), &self.device), + thumbnail_bytes: self.photo.thumbnails.bytes() as usize, + driver: DriverObjects::read(self.frame.instance.as_ref(), &self.device), } } } diff --git a/src/render/viewport/world.rs b/src/render/viewport/world.rs index f356ae1af..8cd023ade 100644 --- a/src/render/viewport/world.rs +++ b/src/render/viewport/world.rs @@ -242,7 +242,7 @@ impl RenderBridge { /// Whether a frame of the world on screen can be drawn by the game's own programs: its panel offers it and a pack of them is read. pub fn world_shaded_drawable(&self) -> bool { - self.world.shaded_offered && self.game_pack.is_some() + self.world.shaded_offered && self.game_scene.pack.is_some() } /// Whether the world is drawn in Shaded this frame: a person chose it and it can be. @@ -281,7 +281,7 @@ impl RenderBridge { /// Make the frame of the game's own programs ready for a world where `shaded`, with no drawable's surfaces in it, and give it back to a drawable's viewport where not. pub(super) fn frame_world_shaded(&mut self, shaded: bool) { - let pack = self.game_pack.clone().filter(|_| shaded); + let pack = self.game_scene.pack.clone().filter(|_| shaded); let Some(pack) = pack else { if self.world.shaded_for.take().is_some() { self.renderer.set_world_pack(&self.device, None); @@ -290,8 +290,8 @@ impl RenderBridge { return; }; // ⚠ A drawable's viewport drawn in the same frame prepares its own surfaces into the one frame of the game's programs: they are no part of a world, and the frame is made empty again. - let of_a_drawable = self.game_scene_key.is_some() || self.held.game_key.is_some(); - let made = self.world.shaded_for == Some(self.game_pack_epoch); + let of_a_drawable = self.game_scene.key.is_some() || self.dressed.held.game_key.is_some(); + let made = self.world.shaded_for == Some(self.game_scene.pack_epoch); if made && self.renderer.has_deferred() && !of_a_drawable { return; } @@ -303,7 +303,7 @@ impl RenderBridge { match made { Ok(_) => { self.renderer.set_world_pack(&self.device, Some(pack)); - self.world.shaded_for = Some(self.game_pack_epoch); + self.world.shaded_for = Some(self.game_scene.pack_epoch); } Err(error) => { tracing::warn!(%error, "the frame of the game's programs did not prepare, so the world is drawn in Material"); @@ -367,7 +367,7 @@ impl RenderBridge { self.world.frame += 1; // No program of GTA VI draws its world yet. self.frame_world_shaded(false); - self.mode = self.world_plain_mode(); + self.frame.mode = self.world_plain_mode(); let bc = (self.device.features()).contains(wgpu::Features::TEXTURE_COMPRESSION_BC); let budgets = self.world_budgets(); let mut viewer = crate::state::gta6_world::worldview::viewer(); @@ -391,7 +391,7 @@ impl RenderBridge { self.world.release_whole(viewer.reads_textures()); self.world.cost.taking = taking.elapsed(); - let (width, height) = self.desired_size; + let (width, height) = self.frame.desired_size; let aspect = width.max(1) as f32 / height.max(1) as f32; viewer.aspect = aspect; let selected = viewer.selected(&mut self.world.told); diff --git a/src/render/viewport/world_plain.rs b/src/render/viewport/world_plain.rs index 189b966e1..9bd7dfa53 100644 --- a/src/render/viewport/world_plain.rs +++ b/src/render/viewport/world_plain.rs @@ -480,7 +480,7 @@ impl RenderBridge { self.frame_world_shaded(shaded); // ⚠ Asked again: a frame that did not prepare is drawn in Material. let shaded = self.world_shaded(); - self.mode = if shaded { + self.frame.mode = if shaded { ShadingMode::Shaded } else { self.world_plain_mode() @@ -501,7 +501,7 @@ impl RenderBridge { self.upload_arrived_models(feed, &budgets, (taken, time, more)); let camera = feed.camera(); - let (width, height) = self.desired_size; + let (width, height) = self.frame.desired_size; let aspect = width.max(1) as f32 / height.max(1) as f32; let view_proj = camera.view_proj(aspect); // What is picked is laid out again with its tint, as anything that changed on the device is. diff --git a/src/render/viewport/world_shown_tests.rs b/src/render/viewport/world_shown_tests.rs index b0817155e..fcbbef41c 100644 --- a/src/render/viewport/world_shown_tests.rs +++ b/src/render/viewport/world_shown_tests.rs @@ -183,7 +183,7 @@ fn a_shaded_frame_of_the_games_programs_is_seen_as_the_bytes_their_last_program_ let (device, queue) = (Arc::new(device), Arc::new(queue)); let format = wgpu::TextureFormat::Rgba8UnormSrgb; let mut bridge = RenderBridge::new(Arc::clone(&device), Arc::clone(&queue), format); - bridge.desired_size = (SIDE, SIDE); + bridge.frame.desired_size = (SIDE, SIDE); bridge.renderer.resize(&device, SIDE, SIDE); assert!(bridge.set_game_pack_path(std::path::Path::new(&pack))); let mut fed = wall(); @@ -247,7 +247,7 @@ fn a_drawable_in_shaded_is_seen_as_the_bytes_the_games_last_program_wrote() { let mut bridge = RenderBridge::new(Arc::clone(&device), Arc::clone(&queue), format); bridge.renderer.resize(&device, SIDE, SIDE); assert!(bridge.set_game_pack_path(std::path::Path::new(&pack))); - let pack = bridge.game_pack.clone().expect("the pack is read"); + let pack = bridge.game_scene.pack.clone().expect("the pack is read"); // A square that fills the view of the camera a viewport begins with, drawn by the game's `default` effect with no map of its own. let corners = [[-9.0f32, -9.0], [9.0, -9.0], [9.0, 9.0], [-9.0, 9.0]]; let square = Drawn { @@ -266,7 +266,7 @@ fn a_drawable_in_shaded_is_seen_as_the_bytes_the_games_last_program_wrote() { (bridge.renderer) .prepare_deferred(&device, &queue, &pack, &[(square, material)]) .expect("the frame of one drawable prepares"); - bridge.mode = ShadingMode::Shaded; + bridge.frame.mode = ShadingMode::Shaded; let camera = or_renderer::OrbitCamera { pitch: std::f32::consts::FRAC_PI_2 - 0.3, ..or_renderer::OrbitCamera::default() @@ -310,7 +310,7 @@ fn a_shaded_world_is_handed_what_casts_into_its_view_from_out_of_sight() { let (device, queue) = (Arc::new(device), Arc::new(queue)); let format = wgpu::TextureFormat::Rgba8UnormSrgb; let mut bridge = RenderBridge::new(Arc::clone(&device), Arc::clone(&queue), format); - bridge.desired_size = (SIDE, SIDE); + bridge.frame.desired_size = (SIDE, SIDE); bridge.renderer.resize(&device, SIDE, SIDE); assert!(bridge.set_game_pack_path(std::path::Path::new(&pack))); // The wall ahead, and the same model 12 m behind the camera, on the sun's side of the first cascade: out of the camera's sight, and across the light from what it sees. diff --git a/src/self_check.rs b/src/self_check.rs index 31674e81d..d674e041e 100644 --- a/src/self_check.rs +++ b/src/self_check.rs @@ -977,11 +977,11 @@ fn describe_panic(payload: Box) -> String { /// A `RenderBridge` over a `wgpu` device with no surface behind it. pub(crate) fn headless_bridge() -> Result { let (device, queue) = headless_gpu()?; - Ok(crate::render::RenderBridge::new( - device, - queue, - wgpu::TextureFormat::Rgba8UnormSrgb, - )) + let hardware = device.adapter_info().device_type != wgpu::DeviceType::Cpu; + Ok( + crate::render::RenderBridge::new(device, queue, wgpu::TextureFormat::Rgba8UnormSrgb) + .with_hardware_adapter(hardware), + ) } /// A `wgpu` device and queue with no surface behind them. @@ -998,7 +998,6 @@ fn headless_gpu() -> Result<(std::sync::Arc, std::sync::Arc &'static or_io::meta::SchemaLibrary { - static FOUND: std::sync::Once = std::sync::Once::new(); - FOUND.call_once(|| { - let config = crate::state::prefs::config_root(); - if let Some(path) = or_title::schema::find_gta6_snapshot(config.as_deref()) { - if let Err(error) = or_io::meta::install_names_snapshot(&path) { - tracing::warn!(path = %path.display(), %error, "GTA VI's schema snapshot is unusable"); - } - } - let Some(path) = or_title::schema::find_snapshot(config.as_deref()) else { - tracing::info!("no metadata schema snapshot found; field names read as hashes"); - return; - }; - if let Err(e) = or_io::meta::install_snapshot(&path) { - tracing::warn!( - path = %path.display(), - error = %e, - "the schema snapshot is unusable; field names read as hashes" - ); - } - }); - or_io::meta::default_library() + or_title::schema::init_meta_host(crate::state::prefs::config_root) } /// The name of the first element `bytes` open, without its namespace prefix, read from the first 8 KiB. diff --git a/src/state/document/mod.rs b/src/state/document/mod.rs index 5f71da162..37334abd1 100644 --- a/src/state/document/mod.rs +++ b/src/state/document/mod.rs @@ -78,7 +78,7 @@ pub enum LoadingState { #[allow(clippy::large_enum_variant)] mod meta; -pub use meta::{meta_schema, read_the_mined_names, MetaDocument}; +pub use meta::{meta_schema, MetaDocument}; mod gta6_meta_names; diff --git a/src/state/gta6_shader_translator.rs b/src/state/gta6_shader_translator.rs index 18618cb55..8bd5cfcc5 100644 --- a/src/state/gta6_shader_translator.rs +++ b/src/state/gta6_shader_translator.rs @@ -1,11 +1,46 @@ //! What reads a GTA VI effect's programs as shading passes: the translator, or a test's stand-in. -use std::collections::BTreeSet; +use std::collections::{BTreeSet, HashMap}; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; use or_cli::Gta6ShadingPass; use or_io::gta5::shaders::sgd5::Sgd5Table; +/// The stages of the session's passes by what they hold: two effects whose passes come to the +/// same two modules hold the same two, and the device builds one pass for both. +pub(super) type Stages = Arc>>>; + +/// Put the session's stage that holds what `module` holds in its place, or keep `module` as that +/// stage; whether the session held one. +pub(super) fn share(stages: &Stages, module: &mut Arc) -> bool { + let held = digest(module); + let mut stages = stages.lock().unwrap_or_else(|p| p.into_inner()); + let known = stages.contains_key(&held); + *module = Arc::clone(stages.entry(held).or_insert_with(|| Arc::clone(module))); + known +} + +/// Two hashes of `module` as it prints, which is all it holds: a stage the binder or one of its +/// options changed prints otherwise. +fn digest(module: &wgpu::naga::Module) -> [u64; 2] { + use std::hash::Hasher; + struct Both([std::collections::hash_map::DefaultHasher; 2]); + impl std::fmt::Write for Both { + fn write_str(&mut self, text: &str) -> std::fmt::Result { + self.0 + .iter_mut() + .for_each(|hash| hash.write(text.as_bytes())); + Ok(()) + } + } + let mut both = Both(Default::default()); + // The second starts from another state, so that the two do not meet together by chance. + both.0[1].write_u8(1); + let _ = std::fmt::Write::write_fmt(&mut both, format_args!("{module:?}")); + both.0.map(|hash| hash.finish()) +} + /// What reads an effect's programs as shading passes: the translator, or a test's stand-in. pub(super) trait Translate: Sync { /// A pixel stage, which several passes of an effect share. @@ -39,7 +74,9 @@ pub(super) trait Translate: Sync { ) -> Result; } -pub(super) struct Translator; +pub(super) struct Translator { + pub(super) hardware: bool, +} /// A job's stop, and the workers it spares beyond the one each effect is read on. pub(super) struct Workers<'c> { @@ -78,7 +115,7 @@ impl Translate for Translator { table: &Sgd5Table, effect: &Sgd5Table, ) -> Result, String> { - or_cli::gta6_mesh_streams(mesh, table, effect) + or_cli::gta6_mesh_streams(mesh, table, effect, self.hardware) } fn pixel( @@ -87,7 +124,7 @@ impl Translate for Translator { table: &Sgd5Table, effect: &Sgd5Table, ) -> Result { - or_cli::translate_gta6_pixel_stage(pixel, table, effect) + or_cli::translate_gta6_pixel_stage(pixel, table, effect, self.hardware) } fn mesh( @@ -97,6 +134,6 @@ impl Translate for Translator { effect: &Sgd5Table, pixel: &Self::Pixel, ) -> Result { - or_cli::translate_gta6_mesh_stage(mesh, table, effect, pixel) + or_cli::translate_gta6_mesh_stage(mesh, table, effect, pixel, self.hardware) } } diff --git a/src/state/gta6_shaders.rs b/src/state/gta6_shaders.rs index 27bbc56bb..32188a291 100644 --- a/src/state/gta6_shaders.rs +++ b/src/state/gta6_shaders.rs @@ -71,40 +71,6 @@ pub(crate) type Shading = Option, String>>; /// ([`gta6_held_streams`]): what a pass is picked by. pub(crate) type Worn = (u32, u32); -/// The stages of the session's passes by what they hold: two effects whose passes come to the -/// same two modules hold the same two, and the device builds one pass for both. -type Stages = Arc>>>; - -/// Put the session's stage that holds what `module` holds in its place, or keep `module` as that -/// stage; whether the session held one. -fn share(stages: &Stages, module: &mut Arc) -> bool { - let held = digest(module); - let mut stages = stages.lock().unwrap_or_else(|p| p.into_inner()); - let known = stages.contains_key(&held); - *module = Arc::clone(stages.entry(held).or_insert_with(|| Arc::clone(module))); - known -} - -/// Two hashes of `module` as it prints, which is all it holds: a stage the binder or one of its -/// options changed prints otherwise. -fn digest(module: &wgpu::naga::Module) -> [u64; 2] { - use std::hash::Hasher; - struct Both([std::collections::hash_map::DefaultHasher; 2]); - impl std::fmt::Write for Both { - fn write_str(&mut self, text: &str) -> std::fmt::Result { - self.0 - .iter_mut() - .for_each(|hash| hash.write(text.as_bytes())); - Ok(()) - } - } - let mut both = Both(Default::default()); - // The second starts from another state, so that the two do not meet together by chance. - both.0[1].write_u8(1); - let _ = std::fmt::Write::write_fmt(&mut both, format_args!("{module:?}")); - both.0.map(|hash| hash.finish()) -} - /// A program translated or refused, with the stage its pass runs it at. struct Done { stage: ShaderStage, @@ -128,6 +94,8 @@ struct Shaders { shading: HashMap>, /// What a job has looked for since the containers last changed, found or not. tried: HashSet, + /// Whether the current `shading` entries were bound for a hardware adapter. + hardware: Option, stages: Stages, running: Option, /// The pack of what is done, numbered so that a new one is told from the last. @@ -158,6 +126,7 @@ struct Input { shading: HashMap>, stages: Stages, install: Option, + hardware: bool, } /// What a job found: the containers its search added and the archive it searched, the programs @@ -230,10 +199,11 @@ fn keep(s: &mut Shaders, sources: Vec>) { /// Start translating, on a worker, the pass that draws each geometry of `worn` and the vertex /// and pixel passes of an effect with none, unless each was looked for already; a job running /// for others is stopped. `install` is the GTA VI install's `shaders.rpf`, asked for when a job -/// starts and searched once a session where no container read holds one. -pub(crate) fn request(worn: &[Worn], install: impl FnOnce() -> Option) { +/// starts and searched once a session where no container read holds one. `hardware` says whether +/// the drawing adapter is hardware rather than software. +pub(crate) fn request(worn: &[Worn], install: impl FnOnce() -> Option, hardware: bool) { with(|s| { - if let Some((input, wanted)) = asked(s, worn, install) { + if let Some((input, wanted)) = asked(s, worn, install, hardware) { s.running = Some(Running::start(input, wanted)); } }); @@ -244,10 +214,17 @@ pub(crate) fn request(worn: &[Worn], install: impl FnOnce() -> Option) // ⚠ Looked for is an effect with the streams of a geometry, never the effect alone: a second // geometry that wears it with other streams draws by another pass, which no job translated. fn asked( - s: &Shaders, + s: &mut Shaders, worn: &[Worn], install: impl FnOnce() -> Option, + hardware: bool, ) -> Option<(Input, Vec)> { + if s.hardware.is_some_and(|was| was != hardware) { + s.shading.clear(); + s.tried.clear(); + s.running = None; + } + s.hardware = Some(hardware); let mut wanted = worn.to_vec(); wanted.sort_unstable(); wanted.dedup(); @@ -255,11 +232,16 @@ fn asked( if running || wanted.iter().all(|h| s.tried.contains(h)) { return None; } - Some((input_of(s, &wanted, install), wanted)) + Some((input_of(s, &wanted, install, hardware), wanted)) } /// What a job for `wanted` is given of the session's translations. -fn input_of(s: &Shaders, wanted: &[Worn], install: impl FnOnce() -> Option) -> Input { +fn input_of( + s: &Shaders, + wanted: &[Worn], + install: impl FnOnce() -> Option, + hardware: bool, +) -> Input { // What a job has looked for is not translated again beside what none has. let fresh: Vec = (wanted.iter().copied()) .filter(|worn| !s.tried.contains(worn)) @@ -275,6 +257,7 @@ fn input_of(s: &Shaders, wanted: &[Worn], install: impl FnOnce() -> Option Option<&Sgd5Effect> { /// Each program the wanted effects' vertex and pixel passes run, read and translated unless read /// before, and each effect built of the passes whose two programs read. fn work(input: Input, cancel: &Cancel, progress: &Progress) -> Result { - work_with(&Translator, input, cancel, progress) + let translator = Translator { + hardware: input.hardware, + }; + work_with(&translator, input, cancel, progress) } /// [`work`], its shading passes read by `translate`. @@ -403,6 +389,7 @@ fn work_with( mut shading, stages, install, + hardware: _, } = input; // Each effect wanted, with the streams the geometries that wear it hold. let mut worn: BTreeMap> = BTreeMap::new(); @@ -1081,7 +1068,7 @@ pub(crate) mod layer_index; #[path = "gta6_shader_translator.rs"] mod translator; -use translator::{Translate, Translator, Workers}; +use translator::{share, Stages, Translate, Translator, Workers}; #[path = "gta6_forward_passes.rs"] mod forward_passes; diff --git a/src/state/gta6_shaders_tests.rs b/src/state/gta6_shaders_tests.rs index e88654424..d3d51f29d 100644 --- a/src/state/gta6_shaders_tests.rs +++ b/src/state/gta6_shaders_tests.rs @@ -132,6 +132,7 @@ fn input(source: ShaderSource, wanted: Vec) -> Input { shading: HashMap::new(), stages: Stages::default(), install: None, + hardware: false, } } @@ -410,7 +411,7 @@ fn holding(slots: &[u32]) -> u32 { /// A request for `worn` as a frame makes it: the job [`request`] starts for it, run to its end by /// `translate` and taken into `s` as [`poll`] takes it. Whether it started one. fn looked_for(s: &mut Shaders, translate: &Told, worn: &[Worn]) -> bool { - let Some((input, wanted)) = asked(s, worn, || None) else { + let Some((input, wanted)) = asked(s, worn, || None, false) else { return false; }; let found = work_with(translate, input, &Cancel::new(), &Progress::new()); @@ -556,3 +557,26 @@ fn a_refused_pass_gives_way_to_the_one_drawn_were_every_pass_translated() { // No mesh stage is linked to a pixel stage that was refused. assert_eq!(told.passes.load(SeqCst), 1); } + +#[test] +fn switching_hardware_adapter_flag_rebinds_previously_tried_effects() { + let dir = tempfile::tempdir().unwrap(); + let passes: Listed = &[(b"M\x01\x02", b"P")]; + let mut s = Shaders::default(); + keep( + &mut s, + vec![Arc::new(shaded(dir.path(), &[("switch_t", passes)]))], + ); + let hash = name_hash32(b"switch_t"); + let worn = [(hash, holding(&[1, 2]))]; + let told = Told::default(); + assert!(looked_for(&mut s, &told, &worn)); + // Asking again with the same adapter kind does not rebind. + assert!(asked(&mut s, &worn, || None, false).is_none()); + // Switching to a hardware adapter clears prior bindings and passes `hardware = true`. + let (input, wanted) = asked(&mut s, &worn, || None, true) + .expect("switching adapter kind triggers a fresh translation"); + assert!(input.hardware); + assert_eq!(wanted, worn); + assert!(s.shading.is_empty()); +}