From 8894846fe220ec2e8310661439e3bc9fe3b0d40e Mon Sep 17 00:00:00 2001 From: chexit Date: Wed, 28 Oct 2026 22:31:00 +0300 Subject: [PATCH] Mod cameras: render.set-views draws the world from other points into pictures that HUD view shapes show (API level 9) Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 3 + crates/horizon-client/src/game/mod_models.rs | 39 ++- crates/horizon-client/src/game/mod_render.rs | 9 + crates/horizon-client/src/gfx.rs | 192 ++++++++++- crates/horizon-client/src/gfx/mod_views.rs | 318 +++++++++++++++++++ crates/horizon-client/src/hud.rs | 15 + crates/horizon-mod-sdk/wit/horizon.wit | 30 ++ crates/horizon-mods/src/api_level.rs | 5 +- crates/horizon-mods/src/runtime.rs | 30 +- 9 files changed, 624 insertions(+), 17 deletions(-) create mode 100644 crates/horizon-client/src/gfx/mod_views.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index ca6a8c266..e5ffb30c4 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -11806,7 +11806,9 @@ impl Game<'_> { hud.patches.append(&mut self.map_patches); let entity_spans = std::mem::take(self.entity_spans.get_mut()); let glowing = std::mem::take(self.glowing_vertices.get_mut()); + let mod_views = self.mod_views(alpha); let frame = Frame { + mod_views: &mod_views, weather: &weather, weather_time: horizon_client::weather::Time::new(self.world.game_time, alpha as f32), nether_lighting: self.dim == Dim::Nether, @@ -14725,6 +14727,7 @@ fn loading_renderer( /// A title-shaped frame: black clear and panorama, only the HUD is drawn. fn loading_frame(hud: &HudBatch) -> Frame<'_> { Frame { + mod_views: &[], weather: &[], weather_time: horizon_client::weather::Time::new(0, 0.0), camera: glam::DVec3::new(0.5, 100.0, 0.5), diff --git a/crates/horizon-client/src/game/mod_models.rs b/crates/horizon-client/src/game/mod_models.rs index 6cd55afc6..7ae58f664 100644 --- a/crates/horizon-client/src/game/mod_models.rs +++ b/crates/horizon-client/src/game/mod_models.rs @@ -11,7 +11,7 @@ use { particles::{ParticleOptions, ParticleType}, }, horizon_core::random::RandomSource, - horizon_mods::ParticleSpawn, + horizon_mods::{CameraView, ParticleSpawn}, horizon_world::registry::BlockStateId, std::collections::HashMap, }; @@ -38,6 +38,8 @@ pub(super) struct ModModels { states: HashMap>, /// The version of the mod post pass the renderer has (0: none). post: u64, + /// The mods' cameras by id: a tick ago and now. + views: Vec<(CameraView, CameraView)>, } /// Full brightness: sky and block light 15, as the entity shader packs them. @@ -55,6 +57,9 @@ impl Game<'_> { ) { } pub(super) fn apply_mod_post(&mut self, _partial: f32) {} + pub(super) fn mod_views(&self, _alpha: f64) -> Vec { + Vec::new() + } } #[cfg(feature = "mods")] @@ -111,6 +116,38 @@ impl Game<'_> { let seen: std::collections::HashSet<_> = seen.into_iter().collect(); models.poses.retain(|k, _| seen.contains(k)); } + let views: Vec = self.mods.mods.views().map(|(_, v)| *v).collect(); + let old = std::mem::take(&mut self.mods.models.views); + self.mods.models.views = views + .into_iter() + .map(|v| { + let before = old.iter().find(|(_, o)| o.id == v.id).map_or(v, |(_, o)| *o); + (before, v) + }) + .collect(); + } + + /// The mods' cameras between their last two settings, for this frame. + pub(super) fn mod_views(&self, alpha: f64) -> Vec { + let t = alpha.clamp(0.0, 1.0); + let lerp = |a: f32, b: f32| a + (b - a) * t as f32; + self.mods + .models + .views + .iter() + .map(|(a, b)| { + // The short way round. + let turn = (b.yaw - a.yaw + 540.0).rem_euclid(360.0) - 180.0; + horizon_client::gfx::ModView { + id: b.id, + camera: DVec3::new(a.x, a.y, a.z).lerp(DVec3::new(b.x, b.y, b.z), t), + yaw: a.yaw + turn * t as f32, + pitch: lerp(a.pitch, b.pitch), + fov: lerp(a.fov, b.fov), + size: [b.width, b.height], + } + }) + .collect() } /// Draws every mod model between its last two poses, lit by the world diff --git a/crates/horizon-client/src/game/mod_render.rs b/crates/horizon-client/src/game/mod_render.rs index 931aec641..85aae67e7 100644 --- a/crates/horizon-client/src/game/mod_render.rs +++ b/crates/horizon-client/src/game/mod_render.rs @@ -120,6 +120,15 @@ impl Game<'_> { self.draw_item_model(batch, &stack, x, y); batch.scale_since(start, x, y, i.scale, i.scale); } + Shape::View(v) => { + let r = v.rect; + batch.views.push(horizon_client::hud::HudView { + at: batch.vertices.len() as u32, + id: v.view, + rect: [ox + r.x, oy + r.y, r.w, r.h], + mode: v.mode, + }); + } Shape::Text(t) => { let text = Text::literal(t.text.clone()); let centre = if t.centered { diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 4c5005615..3ad257728 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -78,6 +78,8 @@ mod native_material; mod native_pack; mod native_post; mod mod_post; +mod mod_views; +pub use mod_views::ModView; mod native_sky; mod occlusion; mod pack_atlas; @@ -214,6 +216,8 @@ const SECTION_UPLOAD_CHUNK: u64 = 4 << 20; const SECTION_COPY_LIMIT: u64 = 64 << 20; pub struct Frame<'a> { pub camera: DVec3, + /// Mods' cameras (AirDef fork), drawn into the pictures the HUD shows. + pub mod_views: &'a [ModView], pub yaw: f32, pub pitch: f32, pub fov_degrees: f32, @@ -546,6 +550,7 @@ pub struct Renderer { native: Option, /// AirDef fork: a mod's post pass, its parameters and the partial tick they are for. mod_post: Option, + mod_views: Option, mod_params: (Vec, f32), /// Time the shader pack's passes on the GPU (F3, or `HORIZON_SHADER_PACK_TIMING`). pass_timing: bool, @@ -2651,6 +2656,7 @@ impl Renderer { pack_post: None, native: None, mod_post: None, + mod_views: None, mod_params: (Vec::new(), 0.0), pass_timing: pack_timing::PassTiming::logging(), pack_entity_rest: Vec::new(), @@ -3019,6 +3025,128 @@ impl Renderer { self.section_uploads.finish(&encoder); Some(encoder.finish()) } + /// The HUD's vertices in `range`, with the mod cameras' pictures between + /// them where their shapes were. + fn draw_hud( + &self, + encoder: &mut wgpu::CommandEncoder, + target: &wgpu::TextureView, + batch: &crate::hud::HudBatch, + range: std::ops::Range, + ) { + let size = [self.config.width, self.config.height]; + let last = batch.vertices.len() as u32; + let mut at = range.start; + if let Some(views) = &self.mod_views { + for v in batch.views.iter().filter(|v| { + v.at >= range.start && (v.at < range.end || (v.at == range.end && range.end == last)) + }) { + self.hud.draw_range(encoder, target, &self.depth, batch, size, at..v.at); + views.blit(encoder, target, size, v, batch.scale); + at = v.at; + } + } + self.hud.draw_range(encoder, target, &self.depth, batch, size, at..range.end); + } + /// The mod cameras due this frame, each into its picture: sky, solid + /// terrain and entities, through the world's own pipelines with the + /// camera's globals in the world's buffer (the player's put back after). + fn draw_mod_views( + &mut self, + encoder: &mut wgpu::CommandEncoder, + frame: &Frame, + globals: &Globals, + due: &[mod_views::Due], + entity_quads: u32, + ) { + let Some(views) = &mut self.mod_views else { + return; + }; + let size = std::mem::size_of::() as u64; + self.uploads + .buffer(encoder, &views.main, 0, bytemuck::bytes_of(globals)); + for d in due { + let Some(t) = views.targets.get(&d.id) else { + continue; + }; + let own = Globals { + view_proj: d.view_proj.to_cols_array_2d(), + inverse_view: d.view.inverse().to_cols_array_2d(), + misc: [ + globals.misc[0], + globals.misc[1], + d.aspect, + (d.fov.to_radians() / 2.0).tan(), + ], + ..*globals + }; + self.uploads + .buffer(encoder, &t.globals, 0, bytemuck::bytes_of(&own)); + } + let fog = globals.fog_color; + let clear = wgpu::Color { + r: f64::from(fog[0]), + g: f64::from(fog[1]), + b: f64::from(fog[2]), + a: 1.0, + }; + for d in due { + let Some(t) = views.targets.get_mut(&d.id) else { + continue; + }; + t.drawn = true; + encoder.copy_buffer_to_buffer(&t.globals, 0, &self.globals, 0, size); + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Mod view"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &t.color, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(clear), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &t.depth, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(0.0), + store: wgpu::StoreOp::Discard, + }), + stencil_ops: None, + }), + ..Default::default() + }); + pass.set_bind_group(0, &self.group, &[]); + if frame.skybox { + pass.set_pipeline(&self.sky); + pass.draw(0..3, 0..1); + } + pass.set_pipeline(&self.solid); + pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); + pass.set_vertex_buffer(1, self.instances.slice(..)); + let mut page = None; + for (k, v) in d.visible.iter().enumerate() { + let s = self.sections.get(v.slot); + if s.solid == 0 { + continue; + } + if page != Some(s.page) { + pass.set_vertex_buffer(0, self.arena.buffer(s.page).slice(..)); + page = Some(s.page); + } + let instance = d.first + k as u32; + pass.draw_indexed(0..s.solid * 6, s.start as i32, instance..instance + 1); + } + if entity_quads > 0 { + pass.set_pipeline(&self.entity_pipeline); + pass.set_bind_group(0, &self.entity_group, &[]); + pass.set_vertex_buffer(0, self.entity_buffer.slice(..)); + pass.draw_indexed(0..entity_quads * 6, 0, 0..1); + } + } + encoder.copy_buffer_to_buffer(&views.main, 0, &self.globals, 0, size); + } /// Draws `count` section draws from `first` with the arena and section /// origins bound: one indirect multi-draw, or a loop without it. /// Consecutive draws in one arena page share a vertex buffer binding, @@ -3827,7 +3955,46 @@ impl Renderer { }); } self.drawn_sections = visible.len() + visible_lods.len(); - let instances = self.drawn_sections + shadow_visible.len(); + // Mods' cameras: their sections round them, all of them (no occlusion), after the shadow's. + let globals_size = std::mem::size_of::() as u64; + let mut views_due = Vec::new(); + if !frame.title && !frame.mod_views.is_empty() { + let format = self.config.format.remove_srgb_suffix(); + let device = &self.device; + let views = self + .mod_views + .get_or_insert_with(|| mod_views::Views::new(device, format, globals_size)); + let mut first = (self.drawn_sections + shadow_visible.len()) as u32; + let radius = ((frame.detail_distance / 16.0) as i32).min(mod_views::RADIUS); + for v in views.choose(device, frame.mod_views, globals_size) { + let (view_proj, view, aspect) = mod_views::matrices(v, camera, frame.depth_far); + let own = world_projection(v.fov, aspect, frame.depth_far) * view; + let planes = Frustum { planes: frustum(own) }; + let mut seen = Vec::new(); + self.sections + .visible(v.camera, radius, &planes, |_| true, |_, _| false, &mut seen); + // Relative to the player's camera, as the rest of the frame. + let shift = (v.camera - camera).as_vec3(); + for s in &mut seen { + s.origin = [s.origin[0] + shift.x, s.origin[1] + shift.y, s.origin[2] + shift.z]; + } + let n = seen.len() as u32; + views_due.push(mod_views::Due { + id: v.id, + view_proj, + view, + aspect, + fov: v.fov, + visible: seen, + first, + }); + first += n; + } + } else if frame.mod_views.is_empty() { + self.mod_views = None; + } + let view_sections: usize = views_due.iter().map(|d| d.visible.len()).sum(); + let instances = self.drawn_sections + shadow_visible.len() + view_sections; if instances as u64 > self.instance_capacity { self.instance_capacity = (instances as u64).next_power_of_two(); self.instances = self.device.create_buffer(&wgpu::BufferDescriptor { @@ -3845,7 +4012,12 @@ impl Renderer { .iter() .map(|v| section_instance(v.origin)) .chain(visible_lods.iter().map(|v| lod::instance(v.origin))) - .chain(shadow_visible.iter().map(|v| section_instance(v.origin))), + .chain(shadow_visible.iter().map(|v| section_instance(v.origin))) + .chain( + views_due + .iter() + .flat_map(|d| d.visible.iter().map(|v| section_instance(v.origin))), + ), ); if !self.origins.is_empty() { self.uploads.buffer( @@ -4461,6 +4633,9 @@ impl Renderer { bytemuck::cast_slice(&self.draws), ); } + if !views_due.is_empty() { + self.draw_mod_views(&mut encoder, frame, &globals, &views_due, entity_quads); + } let view_target = target_texture.create_view(&wgpu::TextureViewDescriptor { format: Some(self.config.format.remove_srgb_suffix()), ..Default::default() @@ -5167,14 +5342,7 @@ impl Renderer { .menu_blur .filter(|_| self.config.usage.contains(wgpu::TextureUsages::COPY_SRC)); let blur_at = menu_blur.map_or(0, |_| frame.hud.blur_at); - self.hud.draw_range( - &mut encoder, - &view_target, - &self.depth, - frame.hud, - [self.config.width, self.config.height], - 0..blur_at, - ); + self.draw_hud(&mut encoder, &view_target, frame.hud, 0..blur_at); if let Some(radius) = menu_blur { let format = self.config.format; let device = &self.device; @@ -5190,12 +5358,10 @@ impl Renderer { radius, ); } - self.hud.draw_range( + self.draw_hud( &mut encoder, &view_target, - &self.depth, frame.hud, - [self.config.width, self.config.height], blur_at..frame.hud.vertices.len() as u32, ); if culling && let Some(cull) = &mut self.cull { diff --git a/crates/horizon-client/src/gfx/mod_views.rs b/crates/horizon-client/src/gfx/mod_views.rs new file mode 100644 index 000000000..91ae103a8 --- /dev/null +++ b/crates/horizon-client/src/gfx/mod_views.rs @@ -0,0 +1,318 @@ +//! AirDef fork: mods' cameras (`render.set-views`). The world is drawn from +//! another point into a small picture (sky, solid terrain, entities), which +//! the HUD's `view` shapes show. The picture's passes reuse the world's +//! pipelines and bind groups: its globals are copied into the world's +//! buffer before them and the camera's copied back after. +use glam::{DVec3, Mat4}; +use std::collections::HashMap; + +/// One camera of a mod, as the game interpolated it for this frame. +#[derive(Clone, Copy, Debug)] +pub struct ModView { + pub id: u32, + pub camera: DVec3, + /// Degrees, as the player's. + pub yaw: f32, + pub pitch: f32, + pub fov: f32, + pub size: [u32; 2], +} + +pub use crate::hud::HudView; + +/// The most cameras drawn a frame; the others wait their turn. +pub(super) const PER_FRAME: usize = 3; +/// Sections round a camera it draws, in chunks. +pub(super) const RADIUS: i32 = 12; + +pub(super) struct Target { + size: [u32; 2], + pub color: wgpu::TextureView, + pub depth: wgpu::TextureView, + pub globals: wgpu::Buffer, + blit: wgpu::BindGroup, + /// Drawn at least once: the HUD shows nothing before. + pub drawn: bool, +} + +/// A camera drawn this frame. +pub(super) struct Due { + pub id: u32, + /// Camera-relative to the player's camera, as the entities and the + /// world's other geometry are. + pub view_proj: Mat4, + pub view: Mat4, + pub aspect: f32, + pub fov: f32, + pub visible: Vec, + /// The instance of `visible[0]` in the section origins. + pub first: u32, +} + +pub(super) struct Views { + pub targets: HashMap, + /// The player's camera's globals, copied back after the pictures. + pub main: wgpu::Buffer, + cursor: usize, + format: wgpu::TextureFormat, + layout: wgpu::BindGroupLayout, + sampler: wgpu::Sampler, + pipeline: wgpu::RenderPipeline, +} + +const BLIT: &str = r#" +@group(0) @binding(0) var picture: texture_2d; +@group(0) @binding(1) var picture_sampler: sampler; +struct Out { + @builtin(position) position: vec4, + @location(0) uv: vec2, + @location(1) @interpolate(flat) mode: u32, +} +@vertex +fn vs(@builtin(vertex_index) i: u32, @builtin(instance_index) mode: u32) -> Out { + let uv = vec2(f32((i << 1u) & 2u), f32(i & 2u)); + var out: Out; + out.position = vec4(uv * vec2(2.0, -2.0) + vec2(-1.0, 1.0), 0.0, 1.0); + out.uv = uv; + out.mode = mode; + return out; +} +fn hash(p: vec2) -> f32 { + return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.547); +} +@fragment +fn fs(in: Out) -> @location(0) vec4 { + let c = textureSample(picture, picture_sampler, in.uv).rgb; + let l = dot(c, vec3(0.299, 0.587, 0.114)); + let grain = (hash(in.position.xy + vec2(c.r * 91.0, c.g * 37.0)) - 0.5) * 0.06; + if in.mode == 1u { + // White hot: the cold sky dark, the land grey, flames and engines burning white. + let warm = max(c.r - c.b, 0.0) * 2.2; + let cold = max(c.b - c.r, 0.0) * 2.5; + let glow = smoothstep(0.8, 1.0, max(c.r, c.g)); + // High gain: a thermal camera sees as well by night. + let v = clamp(0.06 + pow(l, 0.4) * 0.55 + warm + glow * 0.9 - cold + grain, 0.0, 1.0); + return vec4(v, v * 0.98, v * 0.94, 1.0); + } + if in.mode == 2u { + let v = clamp(pow(l, 0.45) * 1.5 + grain, 0.0, 1.0); + return vec4(v * 0.3, v, v * 0.35, 1.0); + } + return vec4(c, 1.0); +} +"#; + +impl Views { + pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat, globals_size: u64) -> Self { + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Mod view picture"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Mod view blit"), + source: wgpu::ShaderSource::Wgsl(BLIT.into()), + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Mod view blit"), + bind_group_layouts: &[Some(&layout)], + ..Default::default() + }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Mod view blit"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &module, + entry_point: Some("vs"), + compilation_options: Default::default(), + buffers: &[], + }, + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some("fs"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + multiview_mask: None, + cache: None, + }); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("Mod view picture"), + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + let main = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Camera globals"), + size: globals_size, + usage: wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + Self { + targets: HashMap::new(), + main, + cursor: 0, + format, + layout, + sampler, + pipeline, + } + } + + /// The cameras to draw this frame, in turn, at most `PER_FRAME`; their + /// targets made or remade to size, the gone ones' dropped. + pub fn choose<'a>( + &mut self, + device: &wgpu::Device, + views: &'a [ModView], + globals_size: u64, + ) -> Vec<&'a ModView> { + self.targets.retain(|id, _| views.iter().any(|v| v.id == *id)); + for v in views { + if self.targets.get(&v.id).is_none_or(|t| t.size != v.size) { + let t = self.target(device, v.size, globals_size); + self.targets.insert(v.id, t); + } + } + if views.is_empty() { + return Vec::new(); + } + let n = views.len().min(PER_FRAME); + let start = self.cursor % views.len(); + self.cursor = self.cursor.wrapping_add(n); + (0..n).map(|k| &views[(start + k) % views.len()]).collect() + } + + fn target(&self, device: &wgpu::Device, size: [u32; 2], globals_size: u64) -> Target { + let extent = wgpu::Extent3d { + width: size[0], + height: size[1], + depth_or_array_layers: 1, + }; + let texture = |label, format, usage| { + device + .create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: extent, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats: &[], + }) + .create_view(&Default::default()) + }; + let color = texture( + "Mod view colour", + self.format, + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, + ); + let depth = texture( + "Mod view depth", + wgpu::TextureFormat::Depth32Float, + wgpu::TextureUsages::RENDER_ATTACHMENT, + ); + let blit = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Mod view picture"), + layout: &self.layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(&color), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Sampler(&self.sampler), + }, + ], + }); + let globals = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Mod view globals"), + size: globals_size, + usage: wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + Target { + size, + color, + depth, + globals, + blit, + drawn: false, + } + } + + /// Shows a camera's picture in `rect` (framebuffer pixels) of `screen`. + pub fn blit( + &self, + encoder: &mut wgpu::CommandEncoder, + screen: &wgpu::TextureView, + screen_size: [u32; 2], + view: &HudView, + scale: f32, + ) { + let Some(t) = self.targets.get(&view.id).filter(|t| t.drawn) else { + return; + }; + let [x, y, w, h] = view.rect.map(|v| v * scale); + let (x0, y0) = (x.max(0.0), y.max(0.0)); + let x1 = (x + w).min(screen_size[0] as f32); + let y1 = (y + h).min(screen_size[1] as f32); + if x1 - x0 < 1.0 || y1 - y0 < 1.0 { + return; + } + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Mod view picture"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: screen, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, + }, + })], + ..Default::default() + }); + pass.set_viewport(x, y, w, h, 0.0, 1.0); + pass.set_scissor_rect(x0 as u32, y0 as u32, (x1 - x0) as u32, (y1 - y0) as u32); + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, &t.blit, &[]); + let mode = view.mode.min(2); + pass.draw(0..3, mode..mode + 1); + } +} + +/// A camera's view and projection: the view from `camera`, moved so that +/// geometry relative to `eye` (the player's camera) lands right. +pub(super) fn matrices(v: &ModView, eye: DVec3, far: f32) -> (Mat4, Mat4, f32) { + let aspect = v.size[0] as f32 / v.size[1].max(1) as f32; + let view = crate::camera::view_matrix(v.yaw, v.pitch); + let projection = super::world_projection(v.fov, aspect, far); + let offset = (eye - v.camera).as_vec3(); + (projection * view * Mat4::from_translation(offset), view, aspect) +} diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index fda0094d8..41af0650e 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -625,6 +625,17 @@ pub struct HudVertex { } /// The GUI Scale option (0 = auto). pub static GUI_SCALE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); +/// Where the HUD shows a mod camera's picture (AirDef fork): before its +/// vertex `at`, over what was drawn before. +#[derive(Clone, Copy, Debug)] +pub struct HudView { + pub at: u32, + pub id: u32, + /// GUI pixels: x, y, width, height. + pub rect: [f32; 4], + /// 0 as seen, 1 thermal, 2 night vision. + pub mode: u32, +} /// One frame of overlay geometry in GUI pixels. pub struct HudBatch { pub vertices: Vec, @@ -641,6 +652,8 @@ pub struct HudBatch { pub glint_alpha: f32, /// Screen's first vertex: the preceding HUD is part of its blurred background. pub blur_at: u32, + /// Mod cameras' pictures, in vertex order. + pub views: Vec, } /// How a run of HUD vertices blends and tests depth. #[derive(Clone, Copy, PartialEq, Eq, Debug)] @@ -692,6 +705,7 @@ impl HudBatch { end_portal: EndPortalFill::default(), glint_alpha: 0.75, blur_at: 0, + views: Vec::new(), } } /// Draw the vertices added since `start` with the inverting blend. @@ -2008,6 +2022,7 @@ mod tests { end_portal: EndPortalFill::default(), glint_alpha: 0.75, blur_at: 0, + views: Vec::new(), }; for (image_width, image_height) in [(195, 136), (176, 166), (176, 222)] { assert_eq!( diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index 1b167c7f7..436455a19 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -338,12 +338,21 @@ interface render { centered: bool, shadow: bool, } + /// A picture of one of the mod's `set-views` cameras (AirDef fork). + record view-shape { + /// The camera's id; an unknown one draws nothing. + view: u32, + rect: rect, + /// 0 as seen, 1 thermal (white hot), 2 night vision (green). + mode: u32, + } variant shape { fill(fill-shape), quad(quad-shape), sprite(sprite-shape), item(item-shape), text(text-shape), + view(view-shape), } /// Replaces the mod's HUD shapes: up to 1024, drawn every frame in /// order over the HUD (after the hotbar, under chat and screens), hidden @@ -500,6 +509,27 @@ interface render { /// replaced; call it once a tick (the pass gets the partial tick in /// `frame.time.y`). set-params: func(params: list); + /// A camera the game renders the world from besides the player's eye + /// (AirDef fork): the land, the sky and the entities near the player. + record camera-view { + /// Stays the same while the camera lives: the game turns it smoothly + /// between the last two `set-views`. + id: u32, + x: f64, + y: f64, + z: f64, + /// Degrees, as the player's: yaw 0 looks south (+z), pitch 90 down. + yaw: f32, + pitch: f32, + /// Vertical field of view, degrees (1 to 110). + fov: f32, + /// The picture's size in pixels (16 to 640 × 16 to 480). + width: u32, + height: u32, + } + /// Replaces the mod's cameras: up to 8. A `view` shape shows one; the + /// game renders up to three a frame, in turn. + set-views: func(views: list); } /// What the game calls. Only the hooks `init` asks for are ever called. diff --git a/crates/horizon-mods/src/api_level.rs b/crates/horizon-mods/src/api_level.rs index 68487e600..9d15851b4 100644 --- a/crates/horizon-mods/src/api_level.rs +++ b/crates/horizon-mods/src/api_level.rs @@ -7,13 +7,13 @@ //! version's level so the launcher can tell before it installs. /// The newest level this Horizon serves. -pub const LEVEL: u32 = 8; +pub const LEVEL: u32 = 9; /// Every function the game offers mods, as `interface.function`, with its /// level. Level 0 is the contract of Horizon 0.2.67 to 0.2.69. A new /// function takes the next level and raises [`LEVEL`] (the `api_reference` /// test fails until it is listed here). -pub const FUNCTIONS: [(&str, u32); 54] = [ +pub const FUNCTIONS: [(&str, u32); 55] = [ ("log.write", 0), ("game.get-player", 0), ("game.get-clock", 0), @@ -69,6 +69,7 @@ pub const FUNCTIONS: [(&str, u32); 54] = [ ("render.set-post", 8), ("render.clear-post", 8), ("render.set-params", 8), + ("render.set-views", 9), ]; /// What the game's program carries so the launcher can read its level diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index 55c1fd13f..01000dfeb 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -81,7 +81,7 @@ pub use render_bindings::horizon::mods::input::{Event as InputEvent, HeldItem, I pub use render_bindings::horizon::mods::render::{ Corner as RenderCorner, FarTerrain as ModFarTerrain, FillShape, FrameRate, ItemShape, Minimap as ModMinimap, ModelInstance, ParticleSpawn, Point as RenderPoint, QuadShape, - Rect as RenderRect, Shape, SpriteShape, TextShape, Zoom as ModZoom, + CameraView, Rect as RenderRect, Shape, SpriteShape, TextShape, ViewShape, Zoom as ModZoom, }; use render_bindings::{RenderHost, horizon::mods::render}; /// Capability `recipes`'s imports (docs/mods.md): the game's recipes and items. @@ -435,6 +435,8 @@ struct State { /// `render.set-post`'s source, with a number that changes with it. post: Option<(u64, String)>, post_params: Vec, + /// `render.set-views`' cameras (AirDef fork). + views: Vec, input: InputState, browser: BrowserState, /// Capability `storage`'s folder; made on first `set`. @@ -643,6 +645,7 @@ impl Mods { ground: Vec::new(), post: None, post_params: Vec::new(), + views: Vec::new(), input: InputState::default(), browser: BrowserState::default(), data_dir, @@ -1206,6 +1209,14 @@ impl Mods { .flat_map(move |r| r.store.data().models.iter().map(move |m| (i, m))) }) } + /// Every running mod's cameras (AirDef fork), with the mod's index. + pub fn views(&self) -> impl Iterator { + self.entries.iter().enumerate().flat_map(|(i, e)| { + e.run + .iter() + .flat_map(move |r| r.store.data().views.iter().map(move |v| (i, v))) + }) + } /// The columns each running mod asked the ground height of, taken. pub fn take_ground_queries(&mut self) -> Vec<(usize, Vec<(i32, i32)>)> { self.entries @@ -1969,6 +1980,23 @@ impl render::Host for State { .map(|v| if v.is_finite() { v } else { 0.0 }) .collect(); } + fn set_views(&mut self, views: Vec) { + let finite = |v: f64| v.is_finite() && v.abs() < 30_000_000.0; + let angle = |v: f32| if v.is_finite() { v } else { 0.0 }; + self.views = views + .into_iter() + .filter(|v| finite(v.x) && finite(v.y) && finite(v.z)) + .take(8) + .map(|mut v| { + v.yaw = angle(v.yaw); + v.pitch = angle(v.pitch).clamp(-90.0, 90.0); + v.fov = if v.fov.is_finite() { v.fov.clamp(1.0, 110.0) } else { 70.0 }; + v.width = v.width.clamp(16, 640); + v.height = v.height.clamp(16, 480); + v + }) + .collect(); + } fn query_ground(&mut self, columns: Vec<(i32, i32)>) { let room = 512usize.saturating_sub(self.ground_queries.len()); self.ground_queries.extend(columns.into_iter().take(room));