Compare commits

...

2 Commits

6 changed files with 445 additions and 113 deletions
+135 -93
View File
@@ -183,7 +183,7 @@ pub struct FfxBackdropUpscale {
pub enabled: bool,
}
/// Optional highlight-only bloom, enabled by the renderer only in a live world.
/// Optional HDR highlights added to the zone glow, enabled only in a live world.
#[derive(Resource, Clone, Default, ExtractResource)]
pub struct FfxHighlightBloom {
/// Positive finite effect strength; zero leaves the reference FFX path intact.
@@ -559,6 +559,7 @@ fn init_pipelines(
texture_2d(TextureSampleType::Float { filterable: true }),
sampler(SamplerBindingType::Filtering),
texture_2d(TextureSampleType::Float { filterable: true }),
texture_2d(TextureSampleType::Float { filterable: true }),
),
),
);
@@ -657,20 +658,34 @@ fn init_pipelines(
/// `0x6ca9d0`) and the GPU objects built from it, kept across frames.
#[derive(Component)]
struct FfxGlowTextures {
quarter_a: CachedTexture,
quarter_b: CachedTexture,
stock: FfxBlurTextures,
highlight: Option<FfxBlurTextures>,
/// The combine's 48-byte uniform, `(gain, death, haze, dither)` then the wave phases,
/// rewritten each frame by a queue write, which lands before the graph's submit.
gain_buf: Buffer,
/// Cached: the Gauss passes bind only the ¼-res pair. The downsample and combine bind the main
/// texture, which `post_process_write` flips per call on a `Write` view, so bind per frame.
gauss_h_bind: BindGroup,
gauss_v_bind: BindGroup,
/// This view's combine pair, keyed on its camera's output (`FinalPassTarget::format`), or
/// `None` while an [`FfxBackdrop`] claims the view.
combine: Option<FfxCombinePair>,
}
struct FfxBlurTextures {
quarter_a: CachedTexture,
quarter_b: CachedTexture,
gauss_h_bind: BindGroup,
gauss_v_bind: BindGroup,
}
impl FfxGlowTextures {
fn highlight_view(&self) -> &TextureView {
&self
.highlight
.as_ref()
.unwrap_or(&self.stock)
.quarter_a
.default_view
}
}
/// One view's dry and underwater combine pipelines, and the key they were specialised on.
#[derive(Clone, Copy)]
struct FfxCombinePair {
@@ -744,17 +759,16 @@ fn prepare_textures(
render_device: Res<RenderDevice>,
mut specializer: CombineSpecializer,
claims: Res<FfxBackdropClaims>,
views: Query<
(
Entity,
&ExtractedCamera,
&ViewTarget,
Option<&FfxGlowTextures>,
),
With<FfxGlow>,
>,
highlight_bloom: Res<FfxHighlightBloom>,
views: Query<(
Entity,
&ExtractedCamera,
&ViewTarget,
&FfxGlow,
Option<&FfxGlowTextures>,
)>,
) {
for (entity, camera, target, existing) in &views {
for (entity, camera, target, glow, existing) in &views {
let Some(vp) = camera.physical_viewport_size else {
continue;
};
@@ -785,10 +799,25 @@ fn prepare_textures(
};
let quarter_a = tex("ffx_glow_quarter_a", vp.x / 4, vp.y / 4);
let quarter_b = tex("ffx_glow_quarter_b", vp.x / 4, vp.y / 4);
let highlight = (glow.state == FfxState::Player
&& glow.gain_scale > 0.0
&& highlight_bloom.strength > 0.0)
.then(|| {
(
tex("ffx_glow_highlight_a", vp.x / 4, vp.y / 4),
tex("ffx_glow_highlight_b", vp.x / 4, vp.y / 4),
)
});
// The cache returns the same textures while the viewport holds: rebuild only on a change.
if existing.is_some_and(|t| {
t.quarter_a.texture.id() == quarter_a.texture.id()
&& t.quarter_b.texture.id() == quarter_b.texture.id()
t.stock.quarter_a.texture.id() == quarter_a.texture.id()
&& t.stock.quarter_b.texture.id() == quarter_b.texture.id()
&& t.highlight
.as_ref()
.map(|h| (h.quarter_a.texture.id(), h.quarter_b.texture.id()))
== highlight
.as_ref()
.map(|(a, b)| (a.texture.id(), b.texture.id()))
&& t.combine.as_ref().map(|c| c.format) == combine.as_ref().map(|c| c.format)
}) {
continue;
@@ -797,16 +826,26 @@ fn prepare_textures(
let layout_filter = specializer
.pipeline_cache
.get_bind_group_layout(&pipelines.layout_filter);
let gauss_h_bind = render_device.create_bind_group(
"ffx_glow_gauss_h",
&layout_filter,
&BindGroupEntries::sequential((&quarter_a.default_view, &pipelines.sampler)),
);
let gauss_v_bind = render_device.create_bind_group(
"ffx_glow_gauss_v",
&layout_filter,
&BindGroupEntries::sequential((&quarter_b.default_view, &pipelines.sampler)),
);
let blur = |quarter_a: CachedTexture, quarter_b: CachedTexture| {
let gauss_h_bind = render_device.create_bind_group(
"ffx_glow_gauss_h",
&layout_filter,
&BindGroupEntries::sequential((&quarter_a.default_view, &pipelines.sampler)),
);
let gauss_v_bind = render_device.create_bind_group(
"ffx_glow_gauss_v",
&layout_filter,
&BindGroupEntries::sequential((&quarter_b.default_view, &pipelines.sampler)),
);
FfxBlurTextures {
quarter_a,
quarter_b,
gauss_h_bind,
gauss_v_bind,
}
};
let stock = blur(quarter_a, quarter_b);
let highlight = highlight.map(|(a, b)| blur(a, b));
let gain_buf = render_device.create_buffer(&BufferDescriptor {
label: Some("ffx_glow_gain"),
size: 48,
@@ -814,11 +853,9 @@ fn prepare_textures(
mapped_at_creation: false,
});
commands.entity(entity).insert(FfxGlowTextures {
quarter_a,
quarter_b,
stock,
highlight,
gain_buf,
gauss_h_bind,
gauss_v_bind,
combine,
});
}
@@ -933,7 +970,7 @@ impl ViewNode for FfxGlowNode {
) -> Result<(), NodeRunError> {
let pipelines = world.resource::<FfxGlowPipelines>();
let pipeline_cache = world.resource::<PipelineCache>();
let (uniform, wave) = live_combine(world, glow);
let (uniform, wave) = live_combine(world, glow, textures);
let (Some(downsample), Some(gauss_h), Some(gauss_v)) = (
pipeline_cache.get_render_pipeline(pipelines.downsample),
pipeline_cache.get_render_pipeline(pipelines.gauss_h),
@@ -941,14 +978,11 @@ impl ViewNode for FfxGlowNode {
) else {
return Ok(()); // pipelines still compiling: the frame draws un-glowed
};
let downsample = if uniform[8] > 0.0 {
// The same readiness gate is used by the backdrop combine.
pipeline_cache
.get_render_pipeline(pipelines.highlight_downsample)
.unwrap_or(downsample)
} else {
downsample
};
let highlight = textures
.highlight
.as_ref()
.filter(|_| uniform[8] > 0.0)
.zip(pipeline_cache.get_render_pipeline(pipelines.highlight_downsample));
// A `Skip` camera's combine lands in its output texture, a `Write` camera's in the
// ping-pong bevy's blit copies out ([`crate::final_pass`]); a claimed view has none here.
let out = match textures.combine.as_ref() {
@@ -967,9 +1001,27 @@ impl ViewNode for FfxGlowNode {
let render_device = render_context.render_device().clone();
let diagnostics = render_context.diagnostic_recorder();
// With both zero the filter passes are skipped, and the stale, finite ¼-res target is
// multiplied by zero.
if blur_read(&uniform) {
let stock = blur_read(&uniform).then_some((
&textures.stock,
downsample,
[
"ffx_glow_down_quarter",
"ffx_glow_gauss_h",
"ffx_glow_gauss_v",
],
));
let highlights = highlight.map(|(blur, downsample)| {
(
blur,
downsample,
[
"ffx_glow_highlight_down_quarter",
"ffx_glow_highlight_gauss_h",
"ffx_glow_highlight_gauss_v",
],
)
});
if stock.is_some() || highlights.is_some() {
let layout_filter = pipeline_cache.get_bind_group_layout(&pipelines.layout_filter);
// Per frame: a `Write` view flips its main texture per call ([`FfxGlowTextures`]).
let down_bind = render_device.create_bind_group(
@@ -980,26 +1032,25 @@ impl ViewNode for FfxGlowNode {
// source → ¼a (one Box4), ¼a → ¼b (Gauss H), ¼b → ¼a (Gauss V), each in its own
// diagnostic span; the journal's `gpu_glow` column is their sum.
let filter_passes: [(&'static str, &RenderPipeline, &BindGroup, &TextureView); 3] = [
(
"ffx_glow_down_quarter",
downsample,
&down_bind,
&textures.quarter_a.default_view,
),
(
"ffx_glow_gauss_h",
gauss_h,
&textures.gauss_h_bind,
&textures.quarter_b.default_view,
),
(
"ffx_glow_gauss_v",
gauss_v,
&textures.gauss_v_bind,
&textures.quarter_a.default_view,
),
];
let filter_passes = [stock, highlights].into_iter().flatten().flat_map(
|(blur, downsample, [down, horizontal, vertical])| {
[
(down, downsample, &down_bind, &blur.quarter_a.default_view),
(
horizontal,
gauss_h,
&blur.gauss_h_bind,
&blur.quarter_b.default_view,
),
(
vertical,
gauss_v,
&blur.gauss_v_bind,
&blur.quarter_a.default_view,
),
]
},
);
for (label, pipeline, bind, dst) in filter_passes {
let mut pass =
render_context
@@ -1041,11 +1092,12 @@ impl ViewNode for FfxGlowNode {
&BindGroupEntries::sequential((
out.source,
&pipelines.sampler,
&textures.quarter_a.default_view,
&textures.stock.quarter_a.default_view,
textures.gain_buf.as_entire_binding(),
&pipelines.wave_view,
&pipelines.wave_sampler,
out.source,
textures.highlight_view(),
)),
);
let scissor = out.scissor_rect();
@@ -1073,7 +1125,7 @@ impl ViewNode for FfxGlowNode {
/// Whether a combine reads the blur: only through `w` (`x`) and the haze (`z`), so with both zero
/// the three filter passes (Box4, Gauss4 H and V) do not run.
fn blur_read(uniform: &[f32]) -> bool {
uniform[0] != 0.0 || uniform[2] != 0.0 || uniform.get(8).is_some_and(|v| *v > 0.0)
uniform[0] != 0.0 || uniform[2] != 0.0
}
/// One view's combine uniform and whether its underwater entry is armed, for both combine nodes.
@@ -1096,7 +1148,7 @@ fn highlight_armed(
&& !wave.active
}
fn live_combine(world: &World, glow: &FfxGlow) -> ([f32; 12], bool) {
fn live_combine(world: &World, glow: &FfxGlow, textures: &FfxGlowTextures) -> ([f32; 12], bool) {
let switches = *world.resource::<FfxSwitches>();
let wave = *world.resource::<FfxWave>();
let player = FfxPassState::world(
@@ -1113,7 +1165,8 @@ fn live_combine(world: &World, glow: &FfxGlow) -> ([f32; 12], bool) {
);
let pipes = world.resource::<FfxGlowPipelines>();
let cache = world.resource::<PipelineCache>();
let ready = cache.get_render_pipeline(pipes.downsample).is_some()
let ready = textures.highlight.is_some()
&& cache.get_render_pipeline(pipes.downsample).is_some()
&& cache
.get_render_pipeline(pipes.highlight_downsample)
.is_some()
@@ -1257,7 +1310,7 @@ impl ViewNode for FfxTransparent2dNode {
};
let pipelines = world.resource::<FfxGlowPipelines>();
let pipeline_cache = world.resource::<PipelineCache>();
let (mut uniform, wave) = live_combine(world, glow);
let (mut uniform, wave) = live_combine(world, glow, textures);
let source_size = world_target.main_texture().size();
let dest_size = target.main_texture().size();
let enabled = world
@@ -1310,13 +1363,14 @@ impl ViewNode for FfxTransparent2dNode {
&BindGroupEntries::sequential((
world_target.main_texture_view(),
&pipelines.sampler,
&textures.quarter_a.default_view,
&textures.stock.quarter_a.default_view,
textures.gain_buf.as_entire_binding(),
&pipelines.wave_view,
&pipelines.wave_sampler,
resolved
.as_ref()
.map_or_else(|| world_target.main_texture_view(), |(view, _)| view),
textures.highlight_view(),
)),
);
if resolved.is_some() && camera.viewport.is_none() {
@@ -1547,28 +1601,16 @@ mod tests {
}
#[test]
fn highlight_shoulder_bounds_nonfinite_and_is_monotone() {
fn highlights_add_to_zone_glow_in_the_living_combine() {
let shader = include_str!("shaders/ffx_glow.wgsl");
assert!(shader.contains("input >= vec3<f32>(0.0)"));
assert!(shader.contains("excess / (excess + 0.15)"));
let shoulder = |v: f32| {
let c = if v >= 0.0 { v.min(65504.0) } else { 0.0 };
if c <= 0.85 {
c
} else {
let e = c - 0.85;
0.85 + 0.15 * e / (e + 0.15)
}
};
let mut last = 0.0;
for v in [0.0, 0.5, 0.85, 0.851, 1.0, 2.0, 8.0, 65504.0, f32::INFINITY] {
let mapped = shoulder(v);
assert!(mapped.is_finite() && mapped >= last && mapped <= 1.0);
last = mapped;
}
assert_eq!(shoulder(f32::NAN), 0.0);
assert_eq!(shoulder(f32::NEG_INFINITY), 0.0);
assert!((shoulder(0.85001) - shoulder(0.85) - 0.00001).abs() < 1e-6);
let combine = shader.split_once("fn combine_body(").unwrap().1;
let ghost = combine.find("return combine_out(outg,").unwrap();
let zone_glow = combine.find("var outg = hazed + zone_glow;").unwrap();
let highlight = combine
.find("let hdr = scene_hdr + zone_glow + halo;")
.unwrap();
let output = combine.rfind("return combine_out(outg,").unwrap();
assert!(ghost < zone_glow && zone_glow < highlight && highlight < output);
}
#[test]
@@ -1606,7 +1648,7 @@ mod tests {
] {
assert!(!highlight_armed(0.6, &FfxGlow::WORLD, state, dry, true));
}
assert!(blur_read(&[
assert!(!blur_read(&[
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.6, 0.0, 0.0, 0.0
]));
}
+11 -15
View File
@@ -25,6 +25,7 @@ struct FfxCombine {
@group(0) @binding(4) var wave_tex: texture_2d<f32>;
@group(0) @binding(5) var wave_samp: sampler;
@group(0) @binding(6) var resolved_tex: texture_2d<f32>;
@group(0) @binding(7) var highlight_tex: texture_2d<f32>;
@@ -68,16 +69,6 @@ fn fs_highlight_downsample(in: FullscreenVertexOutput) -> @location(0) vec4<f32>
return vec4<f32>((a + b + c + d) * (1.0 / 16.0), 1.0);
}
// A C1 monotone shoulder that preserves finite channel ratios and maps NaN/negative to zero.
fn hdr_shoulder(input: vec3<f32>) -> vec3<f32> {
let c = select(vec3<f32>(0.0), min(input, vec3<f32>(65504.0)), input >= vec3<f32>(0.0));
let peak = max(max(c.r, c.g), c.b);
if peak <= 0.85 { return c; }
let excess = peak - 0.85;
let mapped = 0.85 + 0.15 * excess / (excess + 0.15);
return c * (mapped / peak);
}
// Gauss4: taps at ±0.5 and ±2.5 source texels (0x6cad10), weights from FFXGauss4.bls.
fn gauss4(uv: vec2<f32>, axis: vec2<f32>) -> vec4<f32> {
let texel = axis / vec2<f32>(textureDimensions(in_tex));
@@ -174,10 +165,6 @@ fn combine_body(uv: vec2<f32>, frag_coord: vec2<f32>) -> vec4<f32> {
// Clamped like the downsample taps: the screen term must saturate before the glow add.
let sg = clamp(scene.rgb, vec3<f32>(0.0), vec3<f32>(1.0));
let bg = max(textureSample(blur_tex, in_samp, sample_uv).rgb, vec3<f32>(0.0));
if ffx.highlight.x > 0.0 {
let color = max(scene.rgb, vec3<f32>(0.0)) + bg * ffx.highlight.x;
return combine_out(hdr_shoulder(color), scene.a, frag_coord);
}
// Scene alpha passes through; only the transparent-clear create booth reads it.
if ffx.lane.y > 0.0 {
// FFXDeath replaces the glow while a ghost, unhazed (one pass slot, `[0xce8bb4]`). The
@@ -192,7 +179,16 @@ fn combine_body(uv: vec2<f32>, frag_coord: vec2<f32>) -> vec4<f32> {
// The haze fades toward the blur before the glow add; z is the larger of the drunk fraction
// and 84/255 while submerged.
let hazed = mix(sg, min(bg, vec3<f32>(1.0)), ffx.lane.z);
let outg = min(hazed + ffx.lane.x * bg * bg, vec3<f32>(1.0));
let zone_glow = ffx.lane.x * bg * bg;
var outg = hazed + zone_glow;
if ffx.highlight.x > 0.0 {
let halo = textureSample(highlight_tex, in_samp, sample_uv).rgb * ffx.highlight.x;
let scene_hdr = select(vec3<f32>(0.0), min(scene.rgb, vec3<f32>(65504.0)), scene.rgb >= vec3<f32>(0.0));
let hdr = scene_hdr + zone_glow + halo;
// Fit over-white highlights in display range while keeping their hue and the soft halo.
outg = hdr / max(1.0, max(max(hdr.r, hdr.g), hdr.b));
}
outg = min(outg, vec3<f32>(1.0));
return combine_out(outg, scene.a, frag_coord);
}
+11
View File
@@ -65,6 +65,13 @@ fn school(path: &str, hue: Option<[f32; 3]>) -> Option<[f32; 3]> {
if !(p.starts_with("SPELLS\\") || p.contains("\\SPELLS\\")) {
return None;
}
// Food and drink share small star particles that do not light the character.
if matches!(
p.rsplit('\\').next(),
Some("FOOD_HEALEFFECT_BASE.M2" | "FOOD_HEALEFFECT_BASE.MDX")
) {
return None;
}
const DARK: &[&str] = &[
"LIGHTNING",
"STARFIRE",
@@ -576,6 +583,10 @@ mod tests {
assert!(school("Spells/Frostbolt.m2", Some([1.0, 0.4, 0.0])).is_none());
assert!(school("World/Fire.m2", Some([1.0, 0.4, 0.0])).is_none());
assert_eq!(school("Spells/HolyLight.m2", None), Some([1.0, 0.95, 0.78]));
let food_star = Some([0.988, 1.0, 0.0]);
assert!(school("Spells/Food_HealEffect_Base.m2", food_star).is_none());
assert!(school("Spells\\Food_HealEffect_Base.mdx", food_star).is_none());
assert_eq!(school("Spells/Heal_Impact_Base.m2", food_star), food_star);
}
#[test]
fn authored_dark_points_block_synthesis_and_invalid_candidates_are_skipped() {
+50 -5
View File
@@ -1,10 +1,13 @@
//! Rain and retained liquid wetness for world units and their explicitly owned worn rigs.
//! Facing law adapted from pkuzic/benilla-everwood_graphics `wet_hook.wgsl` (MIT OR Apache-2.0).
mod drips;
use std::collections::HashMap;
use std::sync::Arc;
use benilla_world::liquid::LiquidClaim;
use benilla_world::mesh_tag::MAX_RIG_SLOTS;
use benilla_world::particles::buffer::{begin_effect_frame, EffectFog, WorldEffectDraw};
use benilla_world::rig_palette::RigSkin;
use benilla_world::rig_rider::WornRigOwner;
use benilla_world::schedule::WorldLive;
@@ -13,6 +16,7 @@ use benilla_world::wmo_portal::WmoPvsSet;
use benilla_world::world_map::CurrentMap;
use benilla_world::world_point::UnitLiquid;
use benilla_world::world_unit::WorldUnit;
use bevy::asset::AssetId;
use bevy::prelude::*;
use crate::frame::{row, GfxFrame};
@@ -125,6 +129,8 @@ pub(crate) fn register(app: &mut App) {
publish
.after(crate::wet_terrain::publish)
.after(bevy::transform::TransformSystems::Propagate)
.after(bevy::camera::visibility::VisibilitySystems::VisibilityPropagate)
.after(begin_effect_frame)
.after(WmoPvsSet),
);
}
@@ -135,18 +141,20 @@ fn publish(
live: Option<Res<WorldLive>>,
map: Option<Res<CurrentMap>>,
time: Res<Time<Real>>,
camera: Query<(&Camera, &GlobalTransform), With<WorldCamera>>,
camera: Query<(Entity, &Camera, &GlobalTransform), With<WorldCamera>>,
units: Query<(
Entity,
&WorldUnit,
&GlobalTransform,
Option<&RigSkin>,
Has<benilla_world::world_unit::ViewerUnit>,
Option<&InheritedVisibility>,
)>,
worn: Query<(&WornRigOwner, &RigSkin)>,
liquid: UnitLiquid,
mut frame: ResMut<GfxFrame>,
mut state: Local<State>,
mut effects: WorldEffectDraw,
) {
frame.rows[row::WET_BODY] = [0.0; 4];
let map_id = map.as_deref().map(|m| m.0);
@@ -159,18 +167,22 @@ fn publish(
state.units.clear();
state.map = map_id;
}
let Ok((camera_entity, camera, eye)) = camera.single() else {
state.units.clear();
return;
};
if !settings.weather.wet_character
|| strength <= 0.0
|| !live.is_some_and(|l| l.0)
|| map_id.is_none()
|| !camera.single().is_ok_and(|(c, _)| c.is_active)
|| !camera.is_active
{
state.units.clear();
return;
}
state.clear_rows();
state.units.retain(|entity, _| {
units.get(*entity).is_ok_and(|(_, unit, t, _, _)| {
units.get(*entity).is_ok_and(|(_, unit, t, _, _, _)| {
unit.wades
&& unit.height.is_finite()
&& unit.height > 0.0
@@ -180,7 +192,13 @@ fn publish(
let mut used = 0usize;
let mut example = None;
let rain_on = frame.rows[row::WET][0] > 0.0 && frame.rows[row::WET][3] > 0.0;
for (entity, unit, transform, skin, viewer) in &units {
let now = time.elapsed_secs_f64();
let mut drops = effects
.batch(camera_entity, AssetId::default())
.fog(EffectFog::Scene)
.anchored(eye.translation());
let mut drop_count = 0;
for (entity, unit, transform, skin, viewer, visible) in &units {
let at = transform.translation();
if !unit.wades || !at.is_finite() || !unit.height.is_finite() || unit.height <= 0.0 {
continue;
@@ -204,6 +222,32 @@ fn publish(
if !needs_row(wet, rain_on, outdoors) {
continue;
}
let drop_limit = drips::MAX_VISIBLE - usize::from(!viewer);
if drop_count < drop_limit && skin.is_some() && visible.is_none_or(|v| v.get()) {
let to_eye = eye.translation() - at;
let fade = drips::distance_fade(to_eye, height, viewer);
if fade > 0.0 && to_eye.dot(eye.forward().as_vec3()) < 0.0 {
let rain = if rain_on && outdoors {
crate::wet_terrain::rain_on_body(&frame, at + Vec3::Y * (height * 0.75))
} else {
0.0
};
if let Some(drop) = drips::sample(
wet,
strength,
rain,
height,
depth,
now,
entity.to_bits() as u32,
) {
if let Some(vertices) = drop.vertices(unit, transform, eye, fade) {
drops.extend(vertices);
drop_count += 1;
}
}
}
}
let payload = wet.row(at.y, outdoors);
if viewer || example.is_none() {
example = Some((entity, skin.map(|s| s.slot), payload, viewer));
@@ -217,6 +261,7 @@ fn publish(
}
}
}
drops.tris();
for (owner, skin) in &worn {
let slot = skin.slot as usize;
if slot == 0 || slot >= MAX_RIG_SLOTS {
@@ -228,13 +273,13 @@ fn publish(
}
}
publish_snapshot(&mut frame, &state.rows, used);
let now = time.elapsed_secs_f64();
if now - state.last_log >= 1.0 {
debug!(
?example,
affected = state.owners.len(),
slots = used,
rain = frame.rows[row::WET][0],
drops = drop_count,
strength,
"world unit wetness"
);
+203
View File
@@ -0,0 +1,203 @@
//! Sparse runoff along a wet world unit's outline.
use benilla_world::{particles::buffer::EffectVertex, world_unit::WorldUnit};
use bevy::prelude::*;
use super::Wetness;
use crate::fog::smoothstep;
pub(super) const MAX_VISIBLE: usize = 24;
const PERIOD: f64 = 0.75;
const LIFE: f32 = 0.32;
fn random(seed: u32) -> f32 {
let x = (seed ^ (seed >> 16)).wrapping_mul(0x7feb_352d);
let x = (x ^ (x >> 15)).wrapping_mul(0x846c_a68b);
((x ^ (x >> 16)) >> 8) as f32 / 16_777_216.0
}
pub(super) fn distance_fade(to_eye: Vec3, height: f32, viewer: bool) -> f32 {
let distance = to_eye.length();
let near = if viewer {
let horizontal = Vec2::new(to_eye.x, to_eye.z).length();
smoothstep(0.27 * height, 0.65 * height, horizontal)
} else {
smoothstep(0.65, 1.2, distance)
};
near * (1.0 - smoothstep(7.0, 13.0, distance))
}
#[derive(Debug)]
pub(super) struct Drop {
height: f32,
alpha: f32,
/// Local radial direction from the body towards the drop.
side: Vec2,
}
pub(super) fn sample(
wet: Wetness,
scale: f32,
rain: f32,
height: f32,
depth: Option<f32>,
now: f64,
entity_seed: u32,
) -> Option<Drop> {
let upper = (wet.whole * scale).max(rain);
let lower = wet.lower * scale;
let surface = depth.filter(|d| d.is_finite()).unwrap_or(0.0).max(0.0);
let floor = surface + 0.08;
if upper.max(lower) <= 0.08 || height * 0.77 <= floor {
return None;
}
// A fixed cadence keeps the motion continuous during drying. Fewer cycles pass as water fades.
let clock = now + f64::from(random(entity_seed)) * PERIOD;
let age = clock.rem_euclid(PERIOD) as f32;
if age >= LIFE {
return None;
}
let cycle = (clock / PERIOD) as u32;
let seed = entity_seed.wrapping_mul(0x9e37_79b9).wrapping_add(cycle);
let chance = random(seed);
let upper_height = height * (0.69 + 0.08 * random(seed ^ 0xa9a9_3829));
let lower_height = (wet.line * 0.88).min(upper_height);
let (source, amount) = if upper >= lower || lower_height <= floor {
(upper_height, upper)
} else {
(lower_height, lower)
};
if amount <= 0.08 || chance >= smoothstep(0.08, 0.72, amount) {
return None;
}
let height = source - age * (0.32 + 2.6 * age);
if height <= floor {
return None;
}
let fade = smoothstep(0.0, 0.06, age) * (1.0 - smoothstep(0.19, LIFE, age));
let angle = random(seed ^ 0x8d47_3361) * std::f32::consts::TAU;
Some(Drop {
height,
alpha: 0.56 * fade * amount.sqrt(),
side: Vec2::from_angle(angle),
})
}
impl Drop {
pub(super) fn vertices(
&self,
unit: &WorldUnit,
body: &GlobalTransform,
eye: &GlobalTransform,
fade: f32,
) -> Option<[EffectVertex; 12]> {
let bounds = unit.bound?;
let at = body.translation();
let local_eye = body
.affine()
.inverse()
.transform_vector3(eye.translation() - at);
let near = Vec2::new(local_eye.x, local_eye.z).normalize_or_zero();
// Mirror the hidden half around the body so a thin drop reads against the visible outline.
let side =
(self.side + near * (0.3 - 2.0 * self.side.dot(near).min(0.0))).normalize_or_zero();
let center = Vec2::new(bounds.center.x, bounds.center.z);
let half = Vec2::new(bounds.half_extents.x, bounds.half_extents.z);
let offset = center + side * half * 0.95;
let end = body.transform_point(Vec3::new(offset.x, 0.0, offset.y));
// Keep authored hands, tails and unusually wide poses from moving the drop off the body.
let lateral = Vec2::new(end.x - at.x, end.z - at.z).clamp_length_max(unit.height * 0.29);
let center = at + Vec3::new(lateral.x, self.height, lateral.y);
if !center.is_finite() {
return None;
}
let right = eye.right().as_vec3() * 0.019;
let rim = [
center + Vec3::Y * 0.082,
center - right,
center - Vec3::Y * 0.037,
center + right,
];
let vertex = |position: Vec3, alpha| EffectVertex {
pos: position.to_array(),
uv: [0.5; 2],
color: [0.62, 0.77, 0.85, alpha],
};
Some(std::array::from_fn(|i| match i % 3 {
0 => vertex(center, self.alpha * fade),
1 => vertex(rim[i / 3], 0.0),
_ => vertex(rim[(i / 3 + 1) % 4], 0.0),
}))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn runoff_falls_and_leaves_a_gap_between_drops() {
let wet = Wetness {
whole: 1.0,
lower: 1.0,
line: 2.0,
};
let at = |time| sample(wet, 1.0, 0.0, 2.0, None, time, 0);
let early = at(0.08).unwrap();
let late = at(0.23).unwrap();
assert!(late.height < early.height && late.alpha < early.alpha);
assert!(at(0.40).is_none());
assert!(at(0.83).is_some());
}
#[test]
fn runoff_respects_the_wet_part_of_the_body_and_water_surface() {
let wet = Wetness {
whole: 0.0,
lower: 1.0,
line: 0.45,
};
let at = |depth| sample(wet, 1.0, 0.0, 2.0, depth, 0.10, 0);
let drop = at(None).unwrap();
assert!(drop.height < wet.line && drop.height > 0.08);
assert!(at(Some(0.45)).is_none());
let wet = Wetness { whole: 1.0, ..wet };
assert!(sample(wet, 1.0, 1.0, 2.0, Some(2.0), 0.1, 0).is_none());
}
#[test]
fn dry_bodies_and_first_person_stay_clear() {
let dry = Wetness::default();
assert!(sample(dry, 1.0, 0.0, 2.0, None, 0.08, 0).is_none());
assert!(sample(dry, 1.0, 1.0, 2.0, None, 0.08, 0).is_some());
assert_eq!(distance_fade(Vec3::new(0.05, 1.8, 0.0), 2.0, true), 0.0);
assert_eq!(distance_fade(Vec3::Z * 5.0, 2.0, true), 1.0);
assert_eq!(distance_fade(Vec3::Z * 14.0, 2.0, false), 0.0);
}
#[test]
fn runoff_reads_on_the_visible_side_of_the_body() {
let unit = WorldUnit {
wades: true,
scale: 1.0,
height: 2.0,
bound: Some(bevy::camera::primitives::Aabb::from_min_max(
Vec3::new(-0.4, 0.0, -0.3),
Vec3::new(0.4, 2.0, 0.3),
)),
};
let drop = Drop {
height: 1.3,
alpha: 0.3,
side: -Vec2::Y,
};
let body = GlobalTransform::IDENTITY;
let eye = GlobalTransform::from_translation(Vec3::Z * 5.0);
let vertices = drop.vertices(&unit, &body, &eye, 1.0).unwrap();
assert!(vertices[0].pos[2] > 0.2);
assert_eq!(vertices[0].color[3], 0.3);
assert_eq!(vertices[1].color[3], 0.0);
}
}
+35
View File
@@ -272,6 +272,29 @@ pub(crate) fn publish(
frame.shelter.copy_from_slice(rows);
}
/// Rain at an upright body's sample height, using the same roof grid as its wet surface.
pub(super) fn rain_on_body(frame: &GfxFrame, at: Vec3) -> f32 {
let [strength, x, z, spacing] = frame.rows[row::WET];
if strength <= 0.0 || spacing <= 0.0 {
return 0.0;
}
let grid = (Vec2::new(at.x, at.z) - Vec2::new(x, z)) / spacing;
if !grid.is_finite() {
return 0.0;
}
if grid.min_element() < 0.0 || grid.max_element() >= (SIDE - 1) as f32 {
return strength;
}
let cell = grid.floor();
let fraction = grid - cell;
let first = cell.y as usize * SIDE + cell.x as usize;
let cover = |i: usize| crate::fog::smoothstep(0.35, 1.2, frame.shelter[i / 4][i % 4] - at.y);
let top = cover(first) * (1.0 - fraction.x) + cover(first + 1) * fraction.x;
let bottom = cover(first + SIDE) * (1.0 - fraction.x) + cover(first + SIDE + 1) * fraction.x;
let cover = top * (1.0 - fraction.y) + bottom * fraction.y;
strength * (1.0 - ((cover - 0.25) / 0.75).clamp(0.0, 1.0))
}
const SHELTER_WGSL: &str = r#"
// Compare the receiver's height with each sampled roof before blending the corners.
fn mw_wet_exposure(world: vec3<f32>, normal: vec3<f32>) -> f32 {
@@ -391,6 +414,18 @@ pub(crate) fn static_gx_edits(binding: &'static str) -> Vec<Edit> {
mod tests {
use super::*;
#[test]
fn body_rain_respects_shelter_height() {
let mut frame = GfxFrame::default();
frame.rows[row::WET] = [0.65, 0.0, 0.0, SPACING];
let point = Vec3::new(SPACING * 0.5, 2.0, SPACING * 0.5);
assert_eq!(rain_on_body(&frame, point), 0.65);
frame.shelter[0][..2].fill(4.0);
frame.shelter[SIDE / 4][SIDE % 4..SIDE % 4 + 2].fill(4.0);
assert_eq!(rain_on_body(&frame, point), 0.0);
assert_eq!(rain_on_body(&frame, point + Vec3::Y * 3.0), 0.65);
}
#[test]
fn envelope_uses_elapsed_time() {
let mut wet = 0.0;