Merge pull request #78 from ludovic111/fix/rain-length-71

Rain and snow: tile the weather texture like WeatherEffectRenderer (fixes #71)
This commit is contained in:
Ludovic Marie
2026-10-14 15:09:11 +02:00
committed by GitHub
6 changed files with 517 additions and 62 deletions
@@ -0,0 +1,59 @@
//! WeatherEffectRenderer column instances and quads, without a GPU.
use horizon_client::weather;
use std::{fmt::Write, fs};
fn bits(value: f32) -> String {
if value.is_nan() {
"nan".into()
} else {
format!("{:x}", value.to_bits())
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().collect();
let mut output = String::new();
for (case, line) in fs::read_to_string(&args[1])?.lines().enumerate() {
let p: Vec<&str> = line.split_whitespace().collect();
let int = |i: usize| p[i].parse::<i32>().unwrap();
let kind = int(0);
let ticks: i64 = p[1].parse()?;
let (x, bottom, top, z, light) = (int(2), int(3), int(4), int(5), int(6));
let partial: f32 = p[7].parse()?;
let camera = [p[8].parse()?, p[9].parse()?, p[10].parse()?];
let radius = int(11);
let intensity: f32 = p[12].parse()?;
let mut random = weather::column_random(x, z);
let column = if kind == 0 {
weather::rain_column(&mut random, ticks, x, bottom, top, z, light, partial)
} else {
weather::snow_column(&mut random, ticks, x, bottom, top, z, light, partial)
};
write!(
output,
"{case} {} {} {} {} {} {} {}",
column.x,
column.z,
column.bottom_y,
column.top_y,
bits(column.u_offset),
bits(column.v_offset),
column.light_coords
)?;
let max_alpha = if kind == 0 { 1.0 } else { 0.8 };
for v in weather::column_quad(&column, camera, max_alpha, radius, intensity) {
write!(
output,
" |{},{},{},{},{},{:x},{}",
bits(v.pos[0]),
bits(v.pos[1]),
bits(v.pos[2]),
bits(v.uv[0]),
bits(v.uv[1]),
v.color,
v.light_coords
)?;
}
output.push('\n');
}
fs::write(&args[2], output)?;
Ok(())
}
+58 -62
View File
@@ -6695,10 +6695,11 @@ impl Game<'_> {
}
}
}
/// WeatherEffectRenderer: rain/snow columns within 10 blocks.
/// WeatherEffectRenderer: rain and snow columns within the weather radius.
fn weather_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
let (rain, _) = self.world.weather.levels(alpha as f32);
if rain <= 0.0 {
use horizon_client::weather;
let (intensity, _) = self.world.weather.levels(alpha as f32);
if intensity <= 0.0 {
return;
}
let atlas = &self.res.atlas;
@@ -6713,76 +6714,71 @@ impl Game<'_> {
camera.y.floor() as i32,
camera.z.floor() as i32,
);
let radius = 10;
let time = self.ticks as f32 + alpha as f32;
for dz in -radius..=radius {
for dx in -radius..=radius {
let (x, z) = (cx + dx, cz + dz);
let d2 = (dx * dx + dz * dz) as f32;
if d2 > (radius * radius) as f32 {
continue;
}
let radius = self.settings.weather_radius;
let ticks = self.world.game_time;
let partial = alpha as f32;
let eye = [camera.x, camera.y, camera.z];
// Vanilla draws every rain column before the snow ones.
let mut columns = (Vec::new(), Vec::new());
for z in cz - radius..=cz + radius {
for x in cx - radius..=cx + radius {
let top = self.rain_height(x, z, cy + radius + 10);
let y0 = (cy - radius).max(top);
let y1 = (cy + radius).max(top);
if y0 >= y1 {
if y1 == y0 {
continue;
}
let Some(snow) = self.precipitation(x, top, z) else {
let Some(snow) = self.precipitation(x, cy, z) else {
continue;
};
let hash = (x
.wrapping_mul(x)
.wrapping_mul(3121)
.wrapping_add(x.wrapping_mul(45_238_971))
^ z.wrapping_mul(z)
.wrapping_mul(418_711)
.wrapping_add(z.wrapping_mul(13761)))
& 31;
let r = if snow { snow_tex } else { rain_tex };
// Columns face the camera horizontally.
let (fx, fz) = (f64::from(x) + 0.5 - camera.x, f64::from(z) + 0.5 - camera.z);
let len = (fx * fx + fz * fz).sqrt().max(1e-3);
let (sx, sz) = ((-fz / len * 0.5) as f32, (fx / len * 0.5) as f32);
let center = glam::Vec3::new(fx as f32, 0.0, fz as f32);
let scroll = if snow {
(time / 512.0 + hash as f32 / 32.0) % 1.0
} else {
((time + hash as f32) / 32.0 * (3.0 + (hash % 5) as f32 * 0.25)) % 1.0
};
let fade = ((1.0 - d2 / (radius * radius) as f32) * 0.5 + 0.5) * rain;
let a = (fade.clamp(0.0, 1.0) * 255.0) as u32;
let color = a << 24 | 0xFF_FFFF;
let mut random = weather::column_random(x, z);
let light = self.world.light(x, top.max(cy), z);
let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8);
let (b, t) = (
(f64::from(y0) - camera.y) as f32,
(f64::from(y1) - camera.y) as f32,
);
let vh = r.v1 - r.v0;
let corners = [
center + glam::Vec3::new(-sx, b, -sz),
center + glam::Vec3::new(sx, b, sz),
center + glam::Vec3::new(sx, t, sz),
center + glam::Vec3::new(-sx, t, -sz),
];
// The rain texture is a vertical strip; sample a scrolling window of it.
let s0 = scroll * 0.75;
let uv0 = r.v0 + vh * s0;
let uv1 = r.v0 + vh * (s0 + 0.25);
let uvs = [[r.u0, uv1], [r.u1, uv1], [r.u1, uv0], [r.u0, uv0]];
for (p, uv) in corners.iter().zip(uvs) {
out.push(Vertex {
normal: [0; 4],
pos: p.to_array(),
uv,
layer: 0,
color,
light: packed,
});
let coords = i32::from(light & 15) << 4 | i32::from(light >> 4) << 20;
if snow {
columns.1.push(weather::snow_column(
&mut random,
ticks,
x,
y0,
y1,
z,
coords,
partial,
));
} else {
columns.0.push(weather::rain_column(
&mut random,
ticks,
x,
y0,
y1,
z,
coords,
partial,
));
}
}
}
let rain = columns.0.iter().map(|c| (c, 1.0, rain_tex));
let snow = columns.1.iter().map(|c| (c, 0.8, snow_tex));
for (column, max_alpha, r) in rain.chain(snow) {
let quad = weather::column_quad(column, eye, max_alpha, radius, intensity);
let color = quad[0].color;
let lc = quad[0].light_coords;
let light = ((lc >> 20 & 15) * 16) as u32 | (((lc >> 4 & 15) * 16) as u32) << 8;
weather::tile(&quad, |pos, uvs| {
for (p, [u, v]) in pos.into_iter().zip(uvs) {
out.push(Vertex {
normal: [0; 4],
pos: p,
uv: [r.u0 + (r.u1 - r.u0) * u, r.v0 + (r.v1 - r.v0) * v],
layer: 0,
color,
light,
});
}
});
}
}
/// Player.startSleepInBed: night or thunder, no monsters within 8 blocks;
/// the bed becomes the respawn point either way.
+1
View File
@@ -130,6 +130,7 @@ pub mod title;
pub mod ui;
pub mod ui_theme;
pub mod vanillagen;
pub mod weather;
pub mod widgets;
pub mod window;
pub mod world;
+273
View File
@@ -0,0 +1,273 @@
//! Rain and snow columns around the camera (`WeatherEffectRenderer`).
//!
//! Vanilla draws each column as one camera-facing quad whose texture
//! coordinates run past 0..1 (`v` advances a quarter of the texture per block,
//! so `rain.png` repeats every 4 blocks) and relies on a repeating sampler.
//! Horizon samples the sprite from its atlas, so [`tile`] splits a quad at
//! every whole texture repeat into pieces that stay inside the sprite.
use horizon_core::random::{LegacyRandom, RandomSource};
/// `WeatherEffectRenderer.ColumnInstance`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Column {
pub x: i32,
pub z: i32,
pub bottom_y: i32,
pub top_y: i32,
pub u_offset: f32,
pub v_offset: f32,
/// Vanilla packed light (`LightCoordsUtil.pack`: block << 4 | sky << 20).
pub light_coords: i32,
}
/// One vertex of a column quad, in vanilla's emission order.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ColumnVertex {
/// Camera-relative position.
pub pos: [f32; 3],
/// Texture coordinates before wrapping (the sampler repeats).
pub uv: [f32; 2],
/// ARGB (`ARGB.white(alpha)`).
pub color: u32,
pub light_coords: i32,
}
/// The random seed of a column (`extractRenderState`).
pub fn column_seed(x: i32, z: i32) -> i32 {
(x.wrapping_mul(x)
.wrapping_mul(3121)
.wrapping_add(x.wrapping_mul(45_238_971)))
^ (z.wrapping_mul(z)
.wrapping_mul(418_711)
.wrapping_add(z.wrapping_mul(13761)))
}
/// The column's random source, seeded as `random.setSeed(seed)`.
pub fn column_random(x: i32, z: i32) -> LegacyRandom {
LegacyRandom::new(i64::from(column_seed(x, z)))
}
/// `createRainColumnInstance`.
#[allow(clippy::too_many_arguments)]
pub fn rain_column(
random: &mut impl RandomSource,
ticks: i64,
x: i32,
bottom_y: i32,
top_y: i32,
z: i32,
light_coords: i32,
partial: f32,
) -> Column {
let wrapped_ticks = (ticks & 131_071) as i32;
let tick_offset = x
.wrapping_mul(x)
.wrapping_mul(3121)
.wrapping_add(x.wrapping_mul(45_238_971))
.wrapping_add(z.wrapping_mul(z).wrapping_mul(418_711))
.wrapping_add(z.wrapping_mul(13761))
& 0xFF;
let speed = 3.0 + random.next_float();
let offset = -((wrapped_ticks + tick_offset) as f32 + partial) / 32.0 * speed;
Column {
x,
z,
bottom_y,
top_y,
u_offset: 0.0,
v_offset: offset % 32.0,
light_coords,
}
}
/// `createSnowColumnInstance`: snow drifts sideways and is brightened.
#[allow(clippy::too_many_arguments)]
pub fn snow_column(
random: &mut impl RandomSource,
ticks: i64,
x: i32,
bottom_y: i32,
top_y: i32,
z: i32,
light_coords: i32,
partial: f32,
) -> Column {
let wrapped_ticks = (ticks & 131_071) as i32;
let time = wrapped_ticks as f32 + partial;
let u = random.next_double();
let u = (u + f64::from(time * 0.01 * random.next_gaussian() as f32)) as f32;
let v = random.next_double();
let v = (v + f64::from(time * random.next_gaussian() as f32 * 0.001)) as f32;
let v_offset = -((ticks & 511) as f32 + partial) / 512.0;
let (block, sky) = (light_coords >> 4 & 15, light_coords >> 20 & 15);
Column {
x,
z,
bottom_y,
top_y,
u_offset: u,
v_offset: v_offset + v,
light_coords: ((block * 3 + 15) / 4) << 4 | ((sky * 3 + 15) / 4) << 20,
}
}
/// The constructor's 32x32 table of horizontal column half-widths, indexed
/// relative to the camera block. The camera's own column divides 0 by 0.
fn column_size(index: usize) -> (f32, f32) {
let delta_x = (index % 32) as f32 - 16.0;
let delta_z = (index / 32) as f32 - 16.0;
let distance = f64::from(delta_x * delta_x + delta_z * delta_z).sqrt() as f32;
(-delta_z / distance, delta_x / distance)
}
/// `prepareInstances` for one column: rain uses `max_alpha` 1, snow 0.8.
pub fn column_quad(
column: &Column,
camera: [f64; 3],
max_alpha: f32,
radius: i32,
intensity: f32,
) -> [ColumnVertex; 4] {
let radius_sq = (radius * radius) as f32;
let relative_x = (f64::from(column.x) + 0.5 - camera[0]) as f32;
let relative_z = (f64::from(column.z) + 0.5 - camera[2]) as f32;
let distance_sq = relative_x * relative_x + relative_z * relative_z;
let t = (distance_sq / radius_sq).min(1.0);
let alpha = (max_alpha + t * (0.5 - max_alpha)) * intensity;
let color = ((alpha * 255.0).floor() as i32 as u32) << 24 | 0xFF_FFFF;
let index =
(column.z - camera[2].floor() as i32 + 16) * 32 + column.x - camera[0].floor() as i32 + 16;
let (size_x, size_z) = column_size(index as usize);
let (half_x, half_z) = (size_x / 2.0, size_z / 2.0);
let (x0, x1) = (relative_x - half_x, relative_x + half_x);
let y1 = (f64::from(column.top_y) - camera[1]) as f32;
let y0 = (f64::from(column.bottom_y) - camera[1]) as f32;
let (z0, z1) = (relative_z - half_z, relative_z + half_z);
let (u0, u1) = (column.u_offset, column.u_offset + 1.0);
let v0 = column.bottom_y as f32 * 0.25 + column.v_offset;
let v1 = column.top_y as f32 * 0.25 + column.v_offset;
let vertex = |pos, uv| ColumnVertex {
pos,
uv,
color,
light_coords: column.light_coords,
};
[
vertex([x0, y1, z0], [u0, v0]),
vertex([x1, y1, z1], [u1, v0]),
vertex([x1, y0, z1], [u1, v1]),
vertex([x0, y0, z0], [u0, v1]),
]
}
/// Split a column quad (vertices as [`column_quad`] emits them: top edge
/// `u0..u1` at `v0`, bottom edge at `v1`) at every whole texture repeat.
/// Each piece gets positions on the quad and texture coordinates in `0..=1`
/// of one repeat, ready to map onto an atlas sprite.
pub fn tile(quad: &[ColumnVertex; 4], mut emit: impl FnMut([[f32; 3]; 4], [[f32; 2]; 4])) {
let [u0, v0] = quad[0].uv;
let [u1, v1] = quad[2].uv;
let (top_left, top_right) = (quad[0].pos, quad[1].pos);
let (bottom_right, bottom_left) = (quad[2].pos, quad[3].pos);
let lerp3 = |a: [f32; 3], b: [f32; 3], t: f32| -> [f32; 3] {
std::array::from_fn(|i| a[i] + (b[i] - a[i]) * t)
};
// Position at fraction s across (u) and t down (v) the quad.
let at = |s: f32, t: f32| {
lerp3(
lerp3(top_left, top_right, s),
lerp3(bottom_left, bottom_right, s),
t,
)
};
let cuts = |a: f32, b: f32| {
let mut cuts = vec![a];
let mut k = a.floor() + 1.0;
while k < b {
cuts.push(k);
k += 1.0;
}
cuts.push(b);
cuts
};
if !(u1 > u0 && v1 > v0) {
return;
}
let (us, vs) = (cuts(u0, u1), cuts(v0, v1));
for v in vs.windows(2) {
let repeat_v = v[0].floor();
let (ta, tb) = ((v[0] - v0) / (v1 - v0), (v[1] - v0) / (v1 - v0));
let (la, lb) = (v[0] - repeat_v, v[1] - repeat_v);
for u in us.windows(2) {
let repeat_u = u[0].floor();
let (sa, sb) = ((u[0] - u0) / (u1 - u0), (u[1] - u0) / (u1 - u0));
let (ka, kb) = (u[0] - repeat_u, u[1] - repeat_u);
emit(
[at(sa, ta), at(sb, ta), at(sb, tb), at(sa, tb)],
[[ka, la], [kb, la], [kb, lb], [ka, lb]],
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rain_repeats_every_four_blocks() {
let column = Column {
x: 3,
z: 0,
bottom_y: 60,
top_y: 80,
u_offset: 0.0,
v_offset: 0.0,
light_coords: 15 << 20,
};
let quad = column_quad(&column, [0.5, 70.0, 0.5], 1.0, 10, 1.0);
// 20 blocks of rain: five repeats of the texture, split at each seam.
let mut pieces = Vec::new();
tile(&quad, |pos, uv| pieces.push((pos, uv)));
assert_eq!(pieces.len(), 5);
for (pos, uv) in &pieces {
assert!(((pos[0][1] - pos[3][1]) - 4.0).abs() < 1e-4);
assert_eq!(uv[0], [0.0, 0.0]);
assert_eq!(uv[2], [1.0, 1.0]);
}
}
#[test]
fn snow_drifts_across_one_seam() {
let column = Column {
x: 3,
z: 2,
bottom_y: 64,
top_y: 66,
u_offset: 0.25,
v_offset: 0.0,
light_coords: 0,
};
let quad = column_quad(&column, [0.5, 70.0, 0.5], 0.8, 10, 1.0);
let mut pieces = Vec::new();
tile(&quad, |pos, uv| pieces.push((pos, uv)));
assert_eq!(pieces.len(), 2);
assert_eq!(pieces[0].1[0], [0.25, 0.0]);
assert_eq!(pieces[1].1[2], [0.25, 0.5]);
}
#[test]
fn camera_column_is_degenerate() {
let column = Column {
x: 0,
z: 0,
bottom_y: 60,
top_y: 80,
u_offset: 0.0,
v_offset: 0.0,
light_coords: 0,
};
let quad = column_quad(&column, [0.5, 70.0, 0.5], 1.0, 10, 1.0);
assert!(quad[0].pos[0].is_nan());
}
}
@@ -0,0 +1,87 @@
package dev.horizonlab.parity;
import com.mojang.blaze3d.vertex.VertexConsumer;
import java.lang.reflect.Proxy;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import net.minecraft.client.renderer.WeatherEffectRenderer;
import net.minecraft.util.RandomSource;
import net.minecraft.world.phys.Vec3;
/** Build rain and snow column quads with the shipped renderer, without a GPU or a level. */
public final class VanillaWeatherRenderOracle {
public static void main(String[] args) throws Exception {
Class<?> unsafeClass = Class.forName("sun.misc.Unsafe");
var theUnsafe = unsafeClass.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
Object renderer = unsafeClass.getMethod("allocateInstance", Class.class)
.invoke(theUnsafe.get(null), WeatherEffectRenderer.class);
// The constructor's column table, built the same way before it reaches Minecraft.getInstance().
float[] sizeX = new float[1024], sizeZ = new float[1024];
for (int z = 0; z < 32; z++) {
for (int x = 0; x < 32; x++) {
float deltaX = x - 16, deltaZ = z - 16;
float distance = net.minecraft.util.Mth.length(deltaX, deltaZ);
sizeX[z * 32 + x] = -deltaZ / distance;
sizeZ[z * 32 + x] = deltaX / distance;
}
}
for (String name : new String[]{"columnSizeX", "columnSizeZ"}) {
var field = WeatherEffectRenderer.class.getDeclaredField(name);
field.setAccessible(true);
field.set(renderer, name.endsWith("X") ? sizeX : sizeZ);
}
var rain = WeatherEffectRenderer.class.getDeclaredMethod("createRainColumnInstance",
RandomSource.class, long.class, int.class, int.class, int.class, int.class, int.class, float.class);
var snow = WeatherEffectRenderer.class.getDeclaredMethod("createSnowColumnInstance",
RandomSource.class, long.class, int.class, int.class, int.class, int.class, int.class, float.class);
var prepare = WeatherEffectRenderer.class.getDeclaredMethod("prepareInstances",
VertexConsumer.class, List.class, Vec3.class, float.class, int.class, float.class);
rain.setAccessible(true);
snow.setAccessible(true);
prepare.setAccessible(true);
StringBuilder output = new StringBuilder();
int index = 0;
for (String line : Files.readAllLines(Path.of(args[0]))) {
String[] p = line.split(" ");
int kind = Integer.parseInt(p[0]);
long ticks = Long.parseLong(p[1]);
int x = Integer.parseInt(p[2]), bottom = Integer.parseInt(p[3]), top = Integer.parseInt(p[4]);
int z = Integer.parseInt(p[5]), light = Integer.parseInt(p[6]);
float partial = Float.parseFloat(p[7]);
Vec3 camera = new Vec3(Double.parseDouble(p[8]), Double.parseDouble(p[9]), Double.parseDouble(p[10]));
int radius = Integer.parseInt(p[11]);
float intensity = Float.parseFloat(p[12]);
// extractRenderState: the column random is reseeded per column.
RandomSource random = RandomSource.createThreadLocalInstance(0L);
random.setSeed(x * x * 3121 + x * 45238971 ^ z * z * 418711 + z * 13761);
Object column = (kind == 0 ? rain : snow).invoke(renderer, random, ticks, x, bottom, top, z, light, partial);
var record = (WeatherEffectRenderer.ColumnInstance) column;
output.append(index++).append(' ').append(record.x()).append(' ').append(record.z()).append(' ')
.append(record.bottomY()).append(' ').append(record.topY()).append(' ')
.append(bits(record.uOffset())).append(' ').append(bits(record.vOffset())).append(' ')
.append(record.lightCoords());
StringBuilder vertices = new StringBuilder();
VertexConsumer consumer = (VertexConsumer) Proxy.newProxyInstance(
VertexConsumer.class.getClassLoader(), new Class<?>[]{VertexConsumer.class}, (proxy, method, a) -> {
switch (method.getName()) {
case "addVertex" -> vertices.append(" |").append(bits((Float) a[0])).append(',')
.append(bits((Float) a[1])).append(',').append(bits((Float) a[2]));
case "setUv" -> vertices.append(',').append(bits((Float) a[0])).append(',').append(bits((Float) a[1]));
case "setColor" -> vertices.append(',').append(Integer.toHexString((Integer) a[0]));
case "setLight" -> vertices.append(',').append((Integer) a[0]);
default -> throw new IllegalStateException("unexpected " + method);
}
return proxy;
});
prepare.invoke(renderer, consumer, List.of(column), camera, kind == 0 ? 1.0F : 0.8F, radius, intensity);
output.append(vertices).append('\n');
}
Files.writeString(Path.of(args[1]), output);
}
private static String bits(float value) {
return Float.isNaN(value) ? "nan" : Integer.toHexString(Float.floatToRawIntBits(value));
}
}
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python3
"""Compare rain and snow column instances and quads (positions, texture coordinates, alpha, light) with 26.3."""
import random
try:
from . import lab, oracle_harness as harness
except ImportError:
import lab, oracle_harness as harness
def make_input(build):
rng = random.Random(71)
cases = []
for kind in (0, 1):
for ticks in (0, 1, 511, 512, 131071, 131072, 24000 * 37 + 5, 9_000_000_123):
for x, z in ((0, 0), (1, 0), (0, -1), (3, 7), (-10, 10), (10, -10), (-4, -9), (1_000_003, -2_000_011)):
for bottom, top in ((60, 80), (64, 65), (-64, -44), (300, 310)):
light = (rng.randrange(16) << 4) | (rng.randrange(16) << 20)
partial = rng.choice(("0.0", "0.5", "0.999", f"{rng.random():.6f}"))
cam = (x + rng.uniform(-10.5, 10.5), rng.uniform(bottom - 5, top + 5), z + rng.uniform(-10.5, 10.5))
camera = " ".join(f"{c:.9f}" for c in cam)
radius = rng.choice((3, 5, 10))
intensity = rng.choice(("1.0", "0.25", f"{rng.random():.6f}"))
cases.append(f"{kind} {ticks} {x} {bottom} {top} {z} {light} {partial} {camera} {radius} {intensity}\n")
# The camera's own column: the size table divides 0 by 0.
cases.append("0 100 5 60 80 5 240 0.0 5.5 70.0 5.5 10 1.0\n")
inputs = build / "inputs.txt"
inputs.write_text("".join(cases))
return inputs, len(cases)
def main():
harness.differential("weather-render-parity", "VanillaWeatherRenderOracle", "weather_fixture", make_input,
"Rain/snow column instances and quad vertices; not full framebuffer parity.",
sources=[lab.ROOT / "crates/horizon-client/src/weather.rs"])
if __name__ == "__main__":
main()