From 9a72d52c487755ac43db8704dec7f68349c2c51f Mon Sep 17 00:00:00 2001 From: Joshua Barretto Date: Tue, 6 Jun 2023 15:27:52 +0100 Subject: [PATCH] Began adding tether visuals --- assets/voxygen/shaders/tether-frag.glsl | 248 ++++++++++++++++++ assets/voxygen/shaders/tether-vert.glsl | 43 +++ common/net/src/synced_components.rs | 20 +- common/src/comp/body/ship.rs | 4 +- voxygen/src/render/mesh.rs | 14 +- voxygen/src/render/pipelines/mod.rs | 1 + voxygen/src/render/pipelines/tether.rs | 201 ++++++++++++++ voxygen/src/render/renderer.rs | 5 +- voxygen/src/render/renderer/binding.rs | 7 +- voxygen/src/render/renderer/drawer.rs | 33 ++- .../src/render/renderer/pipeline_creation.rs | 37 ++- voxygen/src/render/renderer/shaders.rs | 2 + voxygen/src/scene/mod.rs | 10 + voxygen/src/scene/tether.rs | 96 +++++++ 14 files changed, 703 insertions(+), 18 deletions(-) create mode 100644 assets/voxygen/shaders/tether-frag.glsl create mode 100644 assets/voxygen/shaders/tether-vert.glsl create mode 100644 voxygen/src/render/pipelines/tether.rs create mode 100644 voxygen/src/scene/tether.rs diff --git a/assets/voxygen/shaders/tether-frag.glsl b/assets/voxygen/shaders/tether-frag.glsl new file mode 100644 index 0000000000..dcf3c971ab --- /dev/null +++ b/assets/voxygen/shaders/tether-frag.glsl @@ -0,0 +1,248 @@ +#version 420 core + +#define FIGURE_SHADER + +#include + +#define LIGHTING_TYPE LIGHTING_TYPE_REFLECTION + +#define LIGHTING_REFLECTION_KIND LIGHTING_REFLECTION_KIND_GLOSSY + +#if (FLUID_MODE == FLUID_MODE_LOW) + #define LIGHTING_TRANSPORT_MODE LIGHTING_TRANSPORT_MODE_IMPORTANCE +#elif (FLUID_MODE >= FLUID_MODE_MEDIUM) + #define LIGHTING_TRANSPORT_MODE LIGHTING_TRANSPORT_MODE_RADIANCE +#endif + +#define LIGHTING_DISTRIBUTION_SCHEME LIGHTING_DISTRIBUTION_SCHEME_MICROFACET + +#define LIGHTING_DISTRIBUTION LIGHTING_DISTRIBUTION_BECKMANN + +#define HAS_SHADOW_MAPS + +#include +#include +#include +#include + +layout(location = 0) in vec3 f_pos; +// in float dummy; +// in vec3 f_col; +// in float f_ao; +// flat in uint f_pos_norm; +layout(location = 1) in vec3 f_norm; +// in float f_alt; +// in vec4 f_shadow; +// in vec3 light_pos[2]; + +// #if (SHADOW_MODE == SHADOW_MODE_MAP) +// in vec4 sun_pos; +// #elif (SHADOW_MODE == SHADOW_MODE_CHEAP || SHADOW_MODE == SHADOW_MODE_NONE) +// const vec4 sun_pos = vec4(0.0); +// #endif + +//struct ShadowLocals { +// mat4 shadowMatrices; +// mat4 texture_mat; +//}; +// +//layout (std140) +//uniform u_light_shadows { +// ShadowLocals shadowMats[/*MAX_LAYER_FACES*/192]; +//}; + +layout (std140, set = 2, binding = 0) +uniform u_locals { + vec4 pos_a; + vec4 pos_b; +}; + +layout(location = 0) out vec4 tgt_color; +layout(location = 1) out uvec4 tgt_mat; + +void main() { + // vec2 texSize = textureSize(t_col_light, 0); + // vec4 col_light = texture(t_col_light, (f_uv_pos + 0.5) / texSize); + // vec3 f_col = col_light.rgb; + // float f_ao = col_light.a; + + // vec4 f_col_light = texture(t_col_light, (f_uv_pos + 0.5) / textureSize(t_col_light, 0)); + // vec3 f_col = f_col_light.rgb; + // float f_ao = f_col_light.a; + + float f_ao = 1.0; + uint material = 0xFFu; + vec3 f_col = vec3(0.1); + + #ifdef EXPERIMENTAL_BAREMINIMUM + tgt_color = vec4(simple_lighting(f_pos.xyz, f_col, f_ao), 1); + return; + #endif + + // float /*f_light*/f_ao = textureProj(t_col_light, vec3(f_uv_pos, texSize)).a;//1.0;//f_col_light.a * 4.0;// f_light = float(v_col_light & 0x3Fu) / 64.0; + + // vec3 my_chunk_pos = (vec3((uvec3(f_pos_norm) >> uvec3(0, 9, 18)) & uvec3(0x1FFu)) - 256.0) / 2.0; + // tgt_color = vec4(hash(floor(vec4(my_chunk_pos.x, 0, 0, 0))), hash(floor(vec4(0, my_chunk_pos.y, 0, 1))), hash(floor(vec4(0, 0, my_chunk_pos.z, 2))), 1.0); + // float f_ao = 0; + // tgt_color = vec4(vec3(f_ao), 1.0); + // tgt_color = vec4(f_col, 1.0); + // return; + + // vec3 du = dFdx(f_pos); + // vec3 dv = dFdy(f_pos); + // vec3 f_norm = normalize(cross(du, dv)); + + // vec4 light_pos[2]; +//#if (SHADOW_MODE == SHADOW_MODE_MAP) +// // for (uint i = 0u; i < light_shadow_count.z; ++i) { +// // light_pos[i] = /*vec3(*/shadowMats[i].texture_mat * vec4(f_pos, 1.0)/*)*/; +// // } +// vec4 sun_pos = /*vec3(*/shadowMats[0].texture_mat * vec4(f_pos, 1.0)/*)*/; +//#elif (SHADOW_MODE == SHADOW_MODE_CHEAP || SHADOW_MODE == SHADOW_MODE_NONE) +// vec4 sun_pos = vec4(0.0); +//#endif + + vec3 cam_to_frag = normalize(f_pos - cam_pos.xyz); + // vec4 vert_pos4 = view_mat * vec4(f_pos, 1.0); + // vec3 view_dir = normalize(-vec3(vert_pos4)/* / vert_pos4.w*/); + vec3 view_dir = -cam_to_frag; + + /* vec3 sun_dir = get_sun_dir(time_of_day.x); + vec3 moon_dir = get_moon_dir(time_of_day.x); */ + // float sun_light = get_sun_brightness(sun_dir); + // float moon_light = get_moon_brightness(moon_dir); + /* float sun_shade_frac = horizon_at(f_pos, sun_dir); + float moon_shade_frac = horizon_at(f_pos, moon_dir); */ +#if (SHADOW_MODE == SHADOW_MODE_CHEAP || SHADOW_MODE == SHADOW_MODE_MAP || FLUID_MODE >= FLUID_MODE_MEDIUM) + float f_alt = alt_at(f_pos.xy); +#elif (SHADOW_MODE == SHADOW_MODE_NONE || FLUID_MODE == FLUID_MODE_LOW) + float f_alt = f_pos.z; +#endif + +#if (SHADOW_MODE == SHADOW_MODE_CHEAP || SHADOW_MODE == SHADOW_MODE_MAP) + vec4 f_shadow = textureBicubic(t_horizon, s_horizon, pos_to_tex(f_pos.xy)); + float sun_shade_frac = horizon_at2(f_shadow, f_alt, f_pos, sun_dir); +#elif (SHADOW_MODE == SHADOW_MODE_NONE) + float sun_shade_frac = 1.0;//horizon_at2(f_shadow, f_alt, f_pos, sun_dir); +#endif + float moon_shade_frac = 1.0;// horizon_at2(f_shadow, f_alt, f_pos, moon_dir); + // Globbal illumination "estimate" used to light the faces of voxels which are parallel to the sun or moon (which is a very common occurrence). + // Will be attenuated by k_d, which is assumed to carry any additional ambient occlusion information (e.g. about shadowing). + // float ambient_sides = clamp(mix(0.5, 0.0, abs(dot(-f_norm, sun_dir)) * 10000.0), 0.0, 0.5); + // NOTE: current assumption is that moon and sun shouldn't be out at the sae time. + // This assumption is (or can at least easily be) wrong, but if we pretend it's true we avoids having to explicitly pass in a separate shadow + // for the sun and moon (since they have different brightnesses / colors so the shadows shouldn't attenuate equally). + // float shade_frac = /*1.0;*/sun_shade_frac + moon_shade_frac; + + // DirectionalLight sun_info = get_sun_info(sun_dir, sun_shade_frac, light_pos); + DirectionalLight sun_info = get_sun_info(sun_dir, sun_shade_frac, /*sun_pos*/f_pos); + DirectionalLight moon_info = get_moon_info(moon_dir, moon_shade_frac/*, light_pos*/); + + vec3 surf_color = f_col; + + float alpha = 1.0; + const float n2 = 1.5; + + const float R_s2s0 = pow((1.0 - n2) / (1.0 + n2), 2); + const float R_s1s0 = pow((1.3325 - n2) / (1.3325 + n2), 2); + const float R_s2s1 = pow((1.0 - 1.3325) / (1.0 + 1.3325), 2); + const float R_s1s2 = pow((1.3325 - 1.0) / (1.3325 + 1.0), 2); + float R_s = (f_pos.z < f_alt) ? mix(R_s2s1 * R_s1s0, R_s1s0, medium.x) : mix(R_s2s0, R_s1s2 * R_s2s0, medium.x); + + vec3 k_a = vec3(1.0); + vec3 k_d = vec3(1.0); + vec3 k_s = vec3(R_s); + + vec3 emitted_light, reflected_light; + + // vec3 light_frac = /*vec3(1.0);*//*vec3(max(dot(f_norm, -sun_dir) * 0.5 + 0.5, 0.0));*/light_reflection_factor(f_norm, view_dir, vec3(0, 0, -1.0), vec3(1.0), vec3(R_s), alpha); + // vec3 point_light = light_at(f_pos, f_norm); + // vec3 light, diffuse_light, ambient_light; + //get_sun_diffuse(f_norm, time_of_day.x, view_dir, k_a * point_shadow * (shade_frac * 0.5 + light_frac * 0.5), k_d * point_shadow * shade_frac, k_s * point_shadow * shade_frac, alpha, emitted_light, reflected_light); + float max_light = 0.0; + // reflected_light *= point_shadow * shade_frac; + // emitted_light *= point_shadow * max(shade_frac, MIN_SHADOW); + // max_light *= point_shadow * shade_frac; + // reflected_light *= point_shadow; + // emitted_light *= point_shadow; + // max_light *= point_shadow; + + vec3 cam_attenuation = vec3(1); + float fluid_alt = max(f_pos.z + 1, floor(f_alt + 1)); + vec3 mu = medium.x == MEDIUM_WATER ? MU_WATER : vec3(0.0); + #if (FLUID_MODE >= FLUID_MODE_MEDIUM) + cam_attenuation = + medium.x == MEDIUM_WATER ? compute_attenuation_point(cam_pos.xyz, view_dir, mu, fluid_alt, /*cam_pos.z <= fluid_alt ? cam_pos.xyz : f_pos*/f_pos) + : compute_attenuation_point(f_pos, -view_dir, mu, fluid_alt, /*cam_pos.z <= fluid_alt ? cam_pos.xyz : f_pos*/cam_pos.xyz); + #endif + + // Prevent the sky affecting light when underground + float not_underground = clamp((f_pos.z - f_alt) / 128.0 + 1.0, 0.0, 1.0); + + max_light += get_sun_diffuse2(sun_info, moon_info, f_norm, view_dir, f_pos, mu, cam_attenuation, fluid_alt, k_a, k_d, k_s, alpha, f_norm, 1.0, emitted_light, reflected_light); + + max_light += lights_at(f_pos, f_norm, view_dir, mu, cam_attenuation, fluid_alt, k_a, k_d, k_s, alpha, f_norm, 1.0, emitted_light, reflected_light); + + // TODO: Hack to add a small amount of underground ambient light to the scene + reflected_light += vec3(0.01, 0.02, 0.03) * (1.0 - not_underground); + + // Apply baked AO + float ao = f_ao * sqrt(f_ao);//0.25 + f_ao * 0.75; ///*pow(f_ao, 0.5)*/f_ao * 0.85 + 0.15; + reflected_light *= ao; + emitted_light *= ao; + + // Apply point light AO + float point_shadow = shadow_at(f_pos, f_norm); + reflected_light *= point_shadow; + emitted_light *= point_shadow; + + // Apply emissive glow + // For now, just make glowing material light be the same colour as the surface + // TODO: Add a way to control this better outside the shaders + if ((material & (1u << 0u)) > 0u) { + emitted_light += 20 * surf_color; + } + + /* reflected_light *= cloud_shadow(f_pos); */ + /* vec3 point_light = light_at(f_pos, f_norm); + emitted_light += point_light; + reflected_light += point_light; */ + // get_sun_diffuse(f_norm, time_of_day.x, cam_to_frag, surf_color * f_light * point_shadow, 0.5 * surf_color * f_light * point_shadow, 0.5 * surf_color * f_light * point_shadow, 2.0, emitted_light, reflected_light); + + // get_sun_diffuse(f_norm, time_of_day.x, light, diffuse_light, ambient_light, 1.0); + // diffuse_light *= point_shadow; + // ambient_light *= point_shadow; + // vec3 point_light = light_at(f_pos, f_norm); + // light += point_light; + // diffuse_light += point_light; + // reflected_light += point_light; + // vec3 surf_color = illuminate(srgb_to_linear(highlight_col.rgb * f_col), light, diffuse_light, ambient_light); + + float reflectance = 0.0; + // TODO: Do reflectance properly like this later + vec3 reflect_color = vec3(0); + /* + if ((material & (1u << 1u)) > 0u && false) { + vec3 reflect_ray_dir = reflect(cam_to_frag, f_norm); + reflect_color = get_sky_color(reflect_ray_dir, time_of_day.x, f_pos, vec3(-100000), 0.125, true); + reflect_color = get_cloud_color(reflect_color, reflect_ray_dir, cam_pos.xyz, time_of_day.x, 100000.0, 0.25); + reflectance = 1.0; + } + */ + + surf_color = illuminate(max_light, view_dir, mix(surf_color * emitted_light, reflect_color, reflectance), mix(surf_color * reflected_light, reflect_color, reflectance)); + + // if ((flags & 1) == 1 && int(cam_mode) == 1) { + // float distance = distance(vec3(cam_pos), focus_pos.xyz) - 2; + + // float opacity = clamp(distance / distance_divider, 0, 1); + + // // if(threshold_matrix[int(gl_FragCoord.x) % 4][int(gl_FragCoord.y) % 4] > opacity) { + // // discard; + // // return; + // // } + // } + + tgt_color = vec4(surf_color, 1.0); + tgt_mat = uvec4(uvec3((f_norm + 1.0) * 127.0), MAT_FIGURE); +} diff --git a/assets/voxygen/shaders/tether-vert.glsl b/assets/voxygen/shaders/tether-vert.glsl new file mode 100644 index 0000000000..281224d856 --- /dev/null +++ b/assets/voxygen/shaders/tether-vert.glsl @@ -0,0 +1,43 @@ +#version 420 core + +#include + +#define FIGURE_SHADER + +#define LIGHTING_TYPE LIGHTING_TYPE_REFLECTION + +#define LIGHTING_REFLECTION_KIND LIGHTING_REFLECTION_KIND_GLOSSY + +#define LIGHTING_TRANSPORT_MODE LIGHTING_TRANSPORT_MODE_IMPORTANCE + +#define LIGHTING_DISTRIBUTION_SCHEME LIGHTING_DISTRIBUTION_SCHEME_MICROFACET + +#define LIGHTING_DISTRIBUTION LIGHTING_DISTRIBUTION_BECKMANN + +#include + +layout(location = 0) in vec3 v_pos; +layout(location = 1) in vec3 v_norm; + +layout (std140, set = 2, binding = 0) +uniform u_locals { + vec4 pos_a; + vec4 pos_b; +}; + +layout(location = 0) out vec3 f_pos; +layout(location = 1) out vec3 f_norm; + +void main() { + vec3 pos = pos_a.xyz + v_pos * vec3(1, 1, 5); + + f_pos = pos + focus_pos.xyz; + + #ifdef EXPERIMENTAL_CURVEDWORLD + f_pos.z -= pow(distance(f_pos.xy + focus_off.xy, focus_pos.xy + focus_off.xy) * 0.05, 2); + #endif + + f_norm = v_norm; + + gl_Position = all_mat * vec4(f_pos, 1); +} diff --git a/common/net/src/synced_components.rs b/common/net/src/synced_components.rs index 4011bcecbc..ffa398087e 100755 --- a/common/net/src/synced_components.rs +++ b/common/net/src/synced_components.rs @@ -35,6 +35,8 @@ macro_rules! synced_components { is_mount: IsMount, is_rider: IsRider, is_volume_rider: IsVolumeRider, + is_leader: IsLeader, + is_follower: IsFollower, mass: Mass, density: Density, collider: Collider, @@ -73,8 +75,12 @@ macro_rules! reexport_comps { ($($name:ident: $type:ident,)*) => { mod inner { pub use common::comp::*; - use common::link::Is; - use common::mounting::{Mount, Rider, VolumeRider}; + use common::link::Is + use common::{ + mounting::{Mount, Rider, VolumeRider}, + tether::{Leader, Follower}, + }; + // We alias these because the identifier used for the // component's type is reused as an enum variant name // in the macro's that we pass to `synced_components!`. @@ -84,6 +90,8 @@ macro_rules! reexport_comps { pub type IsMount = Is; pub type IsRider = Is; pub type IsVolumeRider = Is; + pub type IsLeader = Is; + pub type IsFollower = Is; } // Re-export all the component types. So that uses of `synced_components!` outside this @@ -182,6 +190,14 @@ impl NetSync for IsVolumeRider { const SYNC_FROM: SyncFrom = SyncFrom::AnyEntity; } +impl NetSync for IsLeader { + const SYNC_FROM: SyncFrom = SyncFrom::AnyEntity; +} + +impl NetSync for IsFollower { + const SYNC_FROM: SyncFrom = SyncFrom::AnyEntity; +} + impl NetSync for Mass { const SYNC_FROM: SyncFrom = SyncFrom::AnyEntity; } diff --git a/common/src/comp/body/ship.rs b/common/src/comp/body/ship.rs index 1247146540..9c7d2dc24b 100644 --- a/common/src/comp/body/ship.rs +++ b/common/src/comp/body/ship.rs @@ -123,8 +123,8 @@ impl Body { Body::DefaultAirship | Body::AirBalloon | Body::Volume => Density(AIR_DENSITY), Body::Submarine => Density(WATER_DENSITY), // Neutrally buoyant Body::Carriage => Density(WATER_DENSITY * 0.5), - Body::Cart => Density(500.0 / self.dimensions().product()), /* Carts get a constant - * mass */ + Body::Cart => Density(500.0 / self.dimensions().product()), /* Carts get a constant */ + // mass _ => Density(AIR_DENSITY * 0.95 + WATER_DENSITY * 0.05), /* Most boats should be very * buoyant */ } diff --git a/voxygen/src/render/mesh.rs b/voxygen/src/render/mesh.rs index 5b4be54db1..7f0b3d811f 100644 --- a/voxygen/src/render/mesh.rs +++ b/voxygen/src/render/mesh.rs @@ -151,9 +151,9 @@ impl FromIterator> for Mesh { /// Represents a triangle stored on the CPU. pub struct Tri { - a: V, - b: V, - c: V, + pub a: V, + pub b: V, + pub c: V, } impl Tri { @@ -162,10 +162,10 @@ impl Tri { /// Represents a quad stored on the CPU. pub struct Quad { - a: V, - b: V, - c: V, - d: V, + pub a: V, + pub b: V, + pub c: V, + pub d: V, } impl Quad { diff --git a/voxygen/src/render/pipelines/mod.rs b/voxygen/src/render/pipelines/mod.rs index 7b4d60518b..6a97e7e555 100644 --- a/voxygen/src/render/pipelines/mod.rs +++ b/voxygen/src/render/pipelines/mod.rs @@ -13,6 +13,7 @@ pub mod shadow; pub mod skybox; pub mod sprite; pub mod terrain; +pub mod tether; pub mod trail; pub mod ui; diff --git a/voxygen/src/render/pipelines/tether.rs b/voxygen/src/render/pipelines/tether.rs new file mode 100644 index 0000000000..54ef6413d6 --- /dev/null +++ b/voxygen/src/render/pipelines/tether.rs @@ -0,0 +1,201 @@ +use super::super::{AaMode, Bound, Consts, GlobalsLayouts, Vertex as VertexTrait}; +use bytemuck::{Pod, Zeroable}; +use std::mem; +use vek::*; + +#[repr(C)] +#[derive(Copy, Clone, Debug, Zeroable, Pod)] +pub struct Locals { + pos_a: [f32; 4], + pos_b: [f32; 4], +} + +impl Locals { + pub fn new(pos_a: Vec3, pos_b: Vec3) -> Self { + Self { + pos_a: pos_a.with_w(0.0).into_array(), + pos_b: pos_b.with_w(0.0).into_array(), + } + } +} + +impl Default for Locals { + fn default() -> Self { Self::new(Vec3::zero(), Vec3::zero()) } +} + +pub type BoundLocals = Bound>; + +#[repr(C)] +#[derive(Copy, Clone, Debug, Zeroable, Pod)] +pub struct Vertex { + pub pos: [f32; 3], + pub norm: [f32; 3], +} + +impl Vertex { + pub fn new(pos: Vec3, norm: Vec3) -> Self { + Self { + pos: pos.into_array(), + norm: norm.into_array(), + } + } + + fn desc<'a>() -> wgpu::VertexBufferLayout<'a> { + const ATTRIBUTES: [wgpu::VertexAttribute; 2] = + wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3]; + wgpu::VertexBufferLayout { + array_stride: Self::STRIDE, + step_mode: wgpu::InputStepMode::Vertex, + attributes: &ATTRIBUTES, + } + } +} + +impl VertexTrait for Vertex { + const QUADS_INDEX: Option = Some(wgpu::IndexFormat::Uint16); + const STRIDE: wgpu::BufferAddress = mem::size_of::() as wgpu::BufferAddress; +} + +pub struct TetherLayout { + pub locals: wgpu::BindGroupLayout, +} + +impl TetherLayout { + pub fn new(device: &wgpu::Device) -> Self { + Self { + locals: device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: None, + entries: &[ + // locals + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + ], + }), + } + } + + pub fn bind_locals(&self, device: &wgpu::Device, locals: Consts) -> BoundLocals { + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &self.locals, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: locals.buf().as_entire_binding(), + }], + }); + + BoundLocals { + bind_group, + with: locals, + } + } +} + +pub struct TetherPipeline { + pub pipeline: wgpu::RenderPipeline, +} + +impl TetherPipeline { + pub fn new( + device: &wgpu::Device, + vs_module: &wgpu::ShaderModule, + fs_module: &wgpu::ShaderModule, + global_layout: &GlobalsLayouts, + layout: &TetherLayout, + aa_mode: AaMode, + ) -> Self { + common_base::span!(_guard, "TetherPipeline::new"); + let render_pipeline_layout = + device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Tether pipeline layout"), + push_constant_ranges: &[], + bind_group_layouts: &[ + &global_layout.globals, + &global_layout.shadow_textures, + &layout.locals, + ], + }); + + let samples = aa_mode.samples(); + + let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Tether pipeline"), + layout: Some(&render_pipeline_layout), + vertex: wgpu::VertexState { + module: vs_module, + entry_point: "main", + buffers: &[Vertex::desc()], + }, + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + strip_index_format: None, + front_face: wgpu::FrontFace::Ccw, + cull_mode: Some(wgpu::Face::Back), + clamp_depth: false, + polygon_mode: wgpu::PolygonMode::Fill, + conservative: false, + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: true, + depth_compare: wgpu::CompareFunction::GreaterEqual, + stencil: wgpu::StencilState { + front: wgpu::StencilFaceState::IGNORE, + back: wgpu::StencilFaceState::IGNORE, + read_mask: !0, + write_mask: !0, + }, + bias: wgpu::DepthBiasState { + constant: 0, + slope_scale: 0.0, + clamp: 0.0, + }, + }), + multisample: wgpu::MultisampleState { + count: samples, + mask: !0, + alpha_to_coverage_enabled: false, + }, + fragment: Some(wgpu::FragmentState { + module: fs_module, + entry_point: "main", + targets: &[ + wgpu::ColorTargetState { + // TODO: use a constant and/or pass in this format on pipeline construction + format: wgpu::TextureFormat::Rgba16Float, + blend: Some(wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::SrcAlpha, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::One, + dst_factor: wgpu::BlendFactor::One, + operation: wgpu::BlendOperation::Add, + }, + }), + write_mask: wgpu::ColorWrite::ALL, + }, + wgpu::ColorTargetState { + format: wgpu::TextureFormat::Rgba8Uint, + blend: None, + write_mask: wgpu::ColorWrite::ALL, + }, + ], + }), + }); + + Self { + pipeline: render_pipeline, + } + } +} diff --git a/voxygen/src/render/renderer.rs b/voxygen/src/render/renderer.rs index ad9e15c7c4..30bc753a2e 100644 --- a/voxygen/src/render/renderer.rs +++ b/voxygen/src/render/renderer.rs @@ -25,7 +25,7 @@ use super::{ model::{DynamicModel, Model}, pipelines::{ blit, bloom, clouds, debug, figure, postprocess, rain_occlusion, shadow, sprite, terrain, - ui, GlobalsBindGroup, GlobalsLayouts, ShadowTexturesBindGroup, + tether, ui, GlobalsBindGroup, GlobalsLayouts, ShadowTexturesBindGroup, }, texture::Texture, AddressMode, FilterMode, OtherModes, PipelineModes, RenderError, RenderMode, ShadowMapMode, @@ -54,6 +54,7 @@ struct ImmutableLayouts { rain_occlusion: rain_occlusion::RainOcclusionLayout, sprite: sprite::SpriteLayout, terrain: terrain::TerrainLayout, + tether: tether::TetherLayout, clouds: clouds::CloudsLayout, bloom: bloom::BloomLayout, ui: ui::UiLayout, @@ -383,6 +384,7 @@ impl Renderer { let rain_occlusion = rain_occlusion::RainOcclusionLayout::new(&device); let sprite = sprite::SpriteLayout::new(&device); let terrain = terrain::TerrainLayout::new(&device); + let tether = tether::TetherLayout::new(&device); let clouds = clouds::CloudsLayout::new(&device); let bloom = bloom::BloomLayout::new(&device); let postprocess = Arc::new(postprocess::PostProcessLayout::new( @@ -402,6 +404,7 @@ impl Renderer { rain_occlusion, sprite, terrain, + tether, clouds, bloom, ui, diff --git a/voxygen/src/render/renderer/binding.rs b/voxygen/src/render/renderer/binding.rs index 12281309b7..49bca03b07 100644 --- a/voxygen/src/render/renderer/binding.rs +++ b/voxygen/src/render/renderer/binding.rs @@ -3,7 +3,7 @@ use crate::render::pipelines::rain_occlusion; use super::{ super::{ pipelines::{ - debug, figure, lod_terrain, shadow, sprite, terrain, ui, AtlasTextures, + debug, figure, lod_terrain, shadow, sprite, terrain, tether, ui, AtlasTextures, FigureSpriteAtlasData, GlobalModel, GlobalsBindGroup, TerrainAtlasData, }, texture::Texture, @@ -67,6 +67,11 @@ impl Renderer { .bind_locals(&self.device, locals, bone_data) } + pub fn create_tether_bound_locals(&mut self, locals: &[tether::Locals]) -> tether::BoundLocals { + let locals = self.create_consts(locals); + self.layouts.tether.bind_locals(&self.device, locals) + } + pub fn create_terrain_bound_locals( &mut self, locals: &[terrain::Locals], diff --git a/voxygen/src/render/renderer/drawer.rs b/voxygen/src/render/renderer/drawer.rs index 15e87c4441..27ecd1f2bd 100644 --- a/voxygen/src/render/renderer/drawer.rs +++ b/voxygen/src/render/renderer/drawer.rs @@ -7,7 +7,7 @@ use super::{ model::{DynamicModel, Model, SubModel}, pipelines::{ blit, bloom, clouds, debug, figure, fluid, lod_object, lod_terrain, particle, shadow, - skybox, sprite, terrain, trail, ui, AtlasTextures, FigureSpriteAtlasData, + skybox, sprite, terrain, tether, trail, ui, AtlasTextures, FigureSpriteAtlasData, GlobalsBindGroup, TerrainAtlasData, }, AltIndices, CullingMode, @@ -966,6 +966,15 @@ impl<'pass> FirstPassDrawer<'pass> { ParticleDrawer { render_pass } } + pub fn draw_tethers(&mut self) -> TetherDrawer<'_, 'pass> { + let mut render_pass = self.render_pass.scope("tethers", self.borrow.device); + + render_pass.set_pipeline(&self.pipelines.tether.pipeline); + set_quad_index_buffer::(&mut render_pass, self.borrow); + + TetherDrawer { render_pass } + } + pub fn draw_sprites<'data: 'pass>( &mut self, globals: &'data sprite::SpriteGlobalsBindGroup, @@ -1111,6 +1120,28 @@ impl<'pass_ref, 'pass: 'pass_ref> ParticleDrawer<'pass_ref, 'pass> { } } +#[must_use] +pub struct TetherDrawer<'pass_ref, 'pass: 'pass_ref> { + render_pass: Scope<'pass_ref, wgpu::RenderPass<'pass>>, +} + +impl<'pass_ref, 'pass: 'pass_ref> TetherDrawer<'pass_ref, 'pass> { + // Note: if we ever need to draw less than the whole model, these APIs can be + // changed + pub fn draw<'data: 'pass>( + &mut self, + model: &'data Model, + locals: &'data tether::BoundLocals, + ) { + self.render_pass.set_vertex_buffer(0, model.buf().slice(..)); + self.render_pass.set_bind_group(2, &locals.bind_group, &[]); + // TODO: since we cast to u32 maybe this should returned by the len/count + // functions? + self.render_pass + .draw_indexed(0..model.len() as u32 / 4 * 6, 0, 0..1); + } +} + #[must_use] pub struct SpriteDrawer<'pass_ref, 'pass: 'pass_ref> { render_pass: Scope<'pass_ref, wgpu::RenderPass<'pass>>, diff --git a/voxygen/src/render/renderer/pipeline_creation.rs b/voxygen/src/render/renderer/pipeline_creation.rs index 7d1b0617f8..cbf01e7306 100644 --- a/voxygen/src/render/renderer/pipeline_creation.rs +++ b/voxygen/src/render/renderer/pipeline_creation.rs @@ -4,7 +4,7 @@ use super::{ super::{ pipelines::{ blit, bloom, clouds, debug, figure, fluid, lod_object, lod_terrain, particle, - postprocess, shadow, skybox, sprite, terrain, trail, ui, + postprocess, shadow, skybox, sprite, terrain, tether, trail, ui, }, AaMode, BloomMode, CloudMode, FluidMode, LightingMode, PipelineModes, ReflectionMode, RenderError, ShadowMode, @@ -23,6 +23,7 @@ pub struct Pipelines { pub fluid: fluid::FluidPipeline, pub lod_terrain: lod_terrain::LodTerrainPipeline, pub particle: particle::ParticlePipeline, + pub tether: tether::TetherPipeline, pub trail: trail::TrailPipeline, pub clouds: clouds::CloudsPipeline, pub bloom: Option, @@ -46,6 +47,7 @@ pub struct IngamePipelines { fluid: fluid::FluidPipeline, lod_terrain: lod_terrain::LodTerrainPipeline, particle: particle::ParticlePipeline, + tether: tether::TetherPipeline, trail: trail::TrailPipeline, clouds: clouds::CloudsPipeline, pub bloom: Option, @@ -93,6 +95,7 @@ impl Pipelines { fluid: ingame.fluid, lod_terrain: ingame.lod_terrain, particle: ingame.particle, + tether: ingame.tether, trail: ingame.trail, clouds: ingame.clouds, bloom: ingame.bloom, @@ -127,6 +130,8 @@ struct ShaderModules { lod_object_frag: wgpu::ShaderModule, particle_vert: wgpu::ShaderModule, particle_frag: wgpu::ShaderModule, + tether_vert: wgpu::ShaderModule, + tether_frag: wgpu::ShaderModule, trail_vert: wgpu::ShaderModule, trail_frag: wgpu::ShaderModule, ui_vert: wgpu::ShaderModule, @@ -339,6 +344,8 @@ impl ShaderModules { lod_object_frag: create_shader("lod-object-frag", ShaderKind::Fragment)?, particle_vert: create_shader("particle-vert", ShaderKind::Vertex)?, particle_frag: create_shader("particle-frag", ShaderKind::Fragment)?, + tether_vert: create_shader("tether-vert", ShaderKind::Vertex)?, + tether_frag: create_shader("tether-frag", ShaderKind::Fragment)?, trail_vert: create_shader("trail-vert", ShaderKind::Vertex)?, trail_frag: create_shader("trail-frag", ShaderKind::Fragment)?, ui_vert: create_shader("ui-vert", ShaderKind::Vertex)?, @@ -500,7 +507,7 @@ fn create_ingame_and_shadow_pipelines( needs: PipelineNeeds, pool: &rayon::ThreadPool, // TODO: Reduce the boilerplate in this file - tasks: [Task; 19], + tasks: [Task; 20], ) -> IngameAndShadowPipelines { prof_span!(_guard, "create_ingame_and_shadow_pipelines"); @@ -521,6 +528,7 @@ fn create_ingame_and_shadow_pipelines( sprite_task, lod_object_task, particle_task, + tether_task, trail_task, lod_terrain_task, clouds_task, @@ -665,6 +673,22 @@ fn create_ingame_and_shadow_pipelines( "particle pipeline creation", ) }; + // Pipeline for rendering tethers + let create_tether = || { + tether_task.run( + || { + tether::TetherPipeline::new( + device, + &shaders.tether_vert, + &shaders.tether_frag, + &layouts.global, + &layouts.tether, + pipeline_modes.aa, + ) + }, + "tether pipeline creation", + ) + }; // Pipeline for rendering weapon trails let create_trail = || { trail_task.run( @@ -888,6 +912,7 @@ fn create_ingame_and_shadow_pipelines( ) }) }; + let j8 = create_tether; // Ignore this let ( @@ -900,11 +925,14 @@ fn create_ingame_and_shadow_pipelines( (postprocess, point_shadow), (terrain_directed_shadow, (figure_directed_shadow, debug_directed_shadow)), ), - (lod_object, (terrain_directed_rain_occlusion, figure_directed_rain_occlusion)), + ( + (lod_object, (terrain_directed_rain_occlusion, figure_directed_rain_occlusion)), + tether, + ), ), ) = pool.join( || pool.join(|| pool.join(j1, j2), || pool.join(j3, j4)), - || pool.join(|| pool.join(j5, j6), j7), + || pool.join(|| pool.join(j5, j6), || pool.join(j7, j8)), ); IngameAndShadowPipelines { @@ -914,6 +942,7 @@ fn create_ingame_and_shadow_pipelines( fluid, lod_terrain, particle, + tether, trail, clouds, bloom, diff --git a/voxygen/src/render/renderer/shaders.rs b/voxygen/src/render/renderer/shaders.rs index 83a27a22e4..dfff639ada 100644 --- a/voxygen/src/render/renderer/shaders.rs +++ b/voxygen/src/render/renderer/shaders.rs @@ -59,6 +59,8 @@ impl assets::Compound for Shaders { "debug-vert", "debug-frag", "figure-frag", + "tether-vert", + "tether-frag", "terrain-vert", "terrain-frag", "fluid-vert", diff --git a/voxygen/src/scene/mod.rs b/voxygen/src/scene/mod.rs index fcbcb78dba..efa6c761ed 100644 --- a/voxygen/src/scene/mod.rs +++ b/voxygen/src/scene/mod.rs @@ -7,6 +7,7 @@ pub mod particle; pub mod simple; pub mod smoke_cycle; pub mod terrain; +pub mod tether; pub mod trail; pub use self::{ @@ -16,6 +17,7 @@ pub use self::{ lod::Lod, particle::ParticleMgr, terrain::{SpriteRenderContextLazy, Terrain}, + tether::TetherMgr, trail::TrailMgr, }; use crate::{ @@ -105,6 +107,7 @@ pub struct Scene { particle_mgr: ParticleMgr, trail_mgr: TrailMgr, figure_mgr: FigureMgr, + tether_mgr: TetherMgr, pub sfx_mgr: SfxMgr, pub music_mgr: MusicMgr, ambient_mgr: AmbientMgr, @@ -340,6 +343,7 @@ impl Scene { particle_mgr: ParticleMgr::new(renderer), trail_mgr: TrailMgr::default(), figure_mgr: FigureMgr::new(renderer), + tether_mgr: TetherMgr::new(renderer), sfx_mgr: SfxMgr::default(), music_mgr: MusicMgr::new(&calendar), ambient_mgr: AmbientMgr { @@ -880,6 +884,9 @@ impl Scene { // Maintain LoD. self.lod.maintain(renderer, client, focus_pos, &self.camera); + // Maintain tethers. + self.tether_mgr.maintain(renderer, client, focus_pos); + // Maintain debug shapes self.debug.maintain(renderer); @@ -1439,6 +1446,9 @@ impl Scene { ); drop(sprite_drawer); + // Render tethers. + self.tether_mgr.render(&mut first_pass); + // Draws translucent self.terrain.render_translucent(&mut first_pass, focus_pos); diff --git a/voxygen/src/scene/tether.rs b/voxygen/src/scene/tether.rs new file mode 100644 index 0000000000..d4db462fb3 --- /dev/null +++ b/voxygen/src/scene/tether.rs @@ -0,0 +1,96 @@ +use crate::{ + render::{ + pipelines::tether::{BoundLocals, Locals, Vertex}, + Consts, CullingMode, FirstPassDrawer, Instances, LodObjectInstance, LodObjectVertex, Mesh, + Model, Quad, Renderer, Tri, + }, + scene::{camera, Camera}, + settings::Settings, +}; +use client::Client; +use common::{ + assets::{AssetExt, ObjAsset}, + comp, + link::Is, + tether::Follower, + uid::Uid, + util::srgba_to_linear, +}; +use hashbrown::HashMap; +use specs::Join; +use vek::*; + +pub struct TetherMgr { + model: Model, + stale_flag: bool, + tethers: HashMap<(Uid, Uid), (BoundLocals, bool)>, +} + +impl TetherMgr { + pub fn new(renderer: &mut Renderer) -> Self { + Self { + model: renderer.create_model(&create_tether_mesh()).unwrap(), + stale_flag: true, + tethers: HashMap::default(), + } + } + + pub fn maintain(&mut self, renderer: &mut Renderer, client: &Client, focus_off: Vec3) { + let positions = client.state().read_storage::(); + let is_followers = client.state().read_storage::>(); + for (pos, is_follower) in (&positions, &is_followers).join() { + let (locals, stale_flag) = self + .tethers + .entry((is_follower.leader, is_follower.follower)) + .or_insert_with(|| { + ( + renderer.create_tether_bound_locals(&[Locals::new( + pos.0 - focus_off, + pos.0 - focus_off, + )]), + self.stale_flag, + ) + }); + + renderer.update_consts(locals, &[Locals::new(pos.0 - focus_off, pos.0 - focus_off)]); + + *stale_flag = self.stale_flag; + } + + self.tethers.retain(|_, (_, flag)| *flag == self.stale_flag); + + self.stale_flag ^= true; + } + + pub fn render<'a>(&'a self, drawer: &mut FirstPassDrawer<'a>) { + let mut tether_drawer = drawer.draw_tethers(); + for (locals, _) in self.tethers.values() { + tether_drawer.draw(&self.model, locals); + } + } +} + +fn create_tether_mesh() -> Mesh { + const SEGMENTS: usize = 10; + const RADIAL_SEGMENTS: usize = 6; + + (0..RADIAL_SEGMENTS) + .flat_map(|i| { + let at_angle = |x: f32| { + let theta = x / RADIAL_SEGMENTS as f32 * std::f32::consts::TAU; + Vec2::new(theta.sin(), theta.cos()) + }; + let start = at_angle(i as f32); + let end = at_angle(i as f32 + 1.0); + (0..SEGMENTS).map(move |s| { + let z = s as f32 / SEGMENTS as f32; + Quad { + a: Vertex::new(start.with_z(z), start.with_z(0.0)), + b: Vertex::new(start.with_z(z + 1.0), start.with_z(0.0)), + c: Vertex::new(end.with_z(z + 1.0), end.with_z(0.0)), + d: Vertex::new(end.with_z(z), end.with_z(0.0)), + } + }) + }) + .collect() +}