diff --git a/client/BodyRenderer.cs b/client/BodyRenderer.cs index f09e3c6..3383139 100644 --- a/client/BodyRenderer.cs +++ b/client/BodyRenderer.cs @@ -16,8 +16,8 @@ public partial class BodyRenderer : Node3D private readonly Dictionary _carriers = new(); private readonly HashSet _seen = new(); - private readonly StandardMaterial3D _figure = Look.Matte(Look.Figure); - private readonly StandardMaterial3D _scenery = Look.Matte(Look.Scenery); + private readonly ShaderMaterial _figure = Look.Ps1(Look.SkinTexture, Colors.White); + private readonly ShaderMaterial _scenery = Look.Ps1(Look.TileTexture, Colors.White, tile: 1f); /// Bodies drawn, static and dynamic. public int BodyCount => _carriers.Count; @@ -25,7 +25,7 @@ public partial class BodyRenderer : Node3D /// How many MeshInstance3D this renderer has made: a Reset with the same bodies makes none. public int MeshBuilds { get; private set; } - public BaseMaterial3D SceneryMaterial => _scenery; + public ShaderMaterial SceneryMaterial => _scenery; /// The world centre of the union of the dynamic bodies' drawn bounds (each primitive's box in its carrier's pose, interpolated), or null while there are none: where the camera orbits. public Vector3? PuppetCentre @@ -98,11 +98,18 @@ public partial class BodyRenderer : Node3D return true; } + /// The extra cuts along a box edge of half length : a cell is at most a metre, so affine texturing on the big floor stays small per cell, as the console's own floors were tiled. + private static int Cells(float half) => Math.Max(0, (int)(2f * half) - 1); + /// The body's own primitive, or null for a body with no shape. A capsule's lane is its radius and half-length along Y; a box's its half extents. private static Mesh? PrimitiveOf(Box3DSoaKind kind, float size0, float size1, float size2) => kind switch { Box3DSoaKind.Capsule => new CapsuleMesh { Radius = size0, Height = 2f * (size1 + size0), RadialSegments = 6, Rings = 1 }, - Box3DSoaKind.Box or Box3DSoaKind.StaticBox => new BoxMesh { Size = new Vector3(2f * size0, 2f * size1, 2f * size2) }, + Box3DSoaKind.Box or Box3DSoaKind.StaticBox => new BoxMesh + { + Size = new Vector3(2f * size0, 2f * size1, 2f * size2), + SubdivideWidth = Cells(size0), SubdivideHeight = Cells(size1), SubdivideDepth = Cells(size2), + }, Box3DSoaKind.Sphere => new SphereMesh { Radius = size0, Height = 2f * size0, RadialSegments = 6, Rings = 4 }, _ => null, }; diff --git a/client/Chamber.cs b/client/Chamber.cs index 2f0104c..cdfc18c 100644 --- a/client/Chamber.cs +++ b/client/Chamber.cs @@ -4,30 +4,23 @@ using Godot; namespace BadDay.Client; -/// The Synaptic Induction Chamber: the stimulus volume drawn as a translucent box, its glow following the box's intensity. +/// The Synaptic Induction Chamber: the stimulus volume drawn as a translucent box, its glow following the box's intensity, and the light it casts: the shader globals ps1_glow_*, which every surface reads per vertex. public partial class Chamber : Node3D { private readonly MeshInstance3D _volume = new() { Mesh = new BoxMesh { Size = Vector3.One } }; - private readonly OmniLight3D _glow = new() { OmniRange = 0.9f, LightColor = Look.Glow, LightEnergy = 0f }; - private readonly StandardMaterial3D _material = new() - { - Transparency = BaseMaterial3D.TransparencyEnum.Alpha, - AlbedoColor = new Color(Look.Glow, 0.2f), - EmissionEnabled = true, - Emission = Look.Glow, - CullMode = BaseMaterial3D.CullModeEnum.Disabled, - }; + private readonly ShaderMaterial _material = Look.Ps1(null, Look.Glow, 0.06f, emissive: true); public override void _Ready() { _volume.MaterialOverride = _material; - _volume.CastShadow = GeometryInstance3D.ShadowCastingSetting.Off; AddChild(_volume); - AddChild(_glow); } + /// The translucent box. + public MeshInstance3D Volume => _volume; + /// The material of the volume. - public StandardMaterial3D Material => _material; + public ShaderMaterial Material => _material; /// The glow last drawn, 0 (dark) to 1. public float Glow { get; private set; } @@ -40,8 +33,9 @@ public partial class Chamber : Node3D _volume.Scale = new Vector3(2f * box.HalfX, 2f * box.HalfY, 2f * box.HalfZ); float glow = (float)Math.Min(1.0, intensity / 1.5); Glow = glow; - _material.AlbedoColor = new Color(Look.Glow, 0.06f + 0.3f * glow); - _material.EmissionEnergyMultiplier = 0.1f + 2.5f * glow; - _glow.LightEnergy = Look.GlowLightEnergy * glow; + _material.SetShaderParameter("alpha", 0.06f + 0.3f * glow); + Look.Set("ps1_glow_pos", new Vector3(box.CenterX, box.CenterY, box.CenterZ)); + Look.Set("ps1_glow_color", Look.Rgb(Look.Glow)); + Look.Set("ps1_glow_energy", Look.GlowLightEnergy * glow); } } diff --git a/client/Look.cs b/client/Look.cs index ab797b8..a5a0fc5 100644 --- a/client/Look.cs +++ b/client/Look.cs @@ -1,34 +1,102 @@ +using System; using Godot; namespace BadDay.Client; -/// The scene's colours and its colour environment: dark grey, a colour ambient, linear tone mapping, no sky and no glow. +/// +/// The scene's look: PlayStation-1-era 3D (lodur:ruling:bds-look-ps1-anatomy). Every number the look has is here. ps1.gdshader draws every +/// surface (vertices snapped to the line grid, affine texture, unfiltered texels, Gouraud light and fog, all per vertex) and ps1_post.gdshader +/// the framebuffer (15-bit colour, ordered dither, one colour per block of the grid). Colours are raw sRGB values: the console's arithmetic +/// had no colour management and neither does the shader. +/// public static class Look { + /// The framebuffer's height in lines (lodur:question:bds-render-lines): the window is divided into blocks of round(H / Lines) pixels. + public const int Lines = 240; + public static readonly Color Background = new(0.10f, 0.10f, 0.11f); - public static readonly Color Scenery = new(0.15f, 0.15f, 0.16f); - public static readonly Color Figure = new(0.9f, 0.9f, 0.88f); + /// The floor's tile: noise on this colour, grouted with . + public static readonly Color Scenery = Color.Color8(0x1b, 0x26, 0x32); + public static readonly Color Grout = Color.Color8(0x0d, 0x15, 0x1d); + public static readonly Color Skin = Color.Color8(196, 146, 120); public static readonly Color Glow = new(0.85f, 0.95f, 1f); - /// The chamber light at full glow. At 3 it washed the whole dummy out to white (56% of its pixels clipped at near full glow); at 0.1 under 1% clip. - public const float GlowLightEnergy = 0.1f; + /// The key light's direction (where it comes from, in the world), its colour and the ambient: ps1.js's. + public static readonly Vector3 KeyDirection = new Vector3(-0.4f, 0.8f, 0.45f).Normalized(); + public static readonly Color KeyColor = new(0.95f, 0.90f, 0.82f); + public static readonly Color AmbientColor = new(0.30f, 0.34f, 0.42f); - public const float AmbientEnergy = 0.06f; - public static readonly Color AmbientColor = new(0.9f, 0.93f, 1f); + /// Fog toward , by view depth in metres. + public const float FogNear = 4f, FogFar = 14f; - /// The scene's environment: a colour background, a colour ambient, linear, no glow. + /// The chamber's light at full glow (it reaches 0.9 m): added per vertex to the key and the ambient. + public const float GlowLightEnergy = 4f; + + /// Pixels per block of the line grid for a window pixels high: never less than 1. + public static int BlockSize(int height) => Math.Max(1, (int)Math.Round(height / (double)Lines, MidpointRounding.AwayFromZero)); + + private static ImageTexture? _skinTexture, _tileTexture; + + /// The skin: 8 x 8 texels of with a little noise. + public static ImageTexture SkinTexture => _skinTexture ??= Noise(8, 8, Skin, 0.035f, 7); + + /// The floor's tile: 32 x 32 texels of with noise and a texel of grout on two edges. + public static ImageTexture TileTexture => _tileTexture ??= Noise(32, 32, Scenery, 0.02f, 11, (x, y) => x == 0 || y == 0, Grout); + + /// The scene's environment: a colour background, linear, no sky and no glow. Every surface is unshaded, so it lights nothing. public static WorldEnvironment World() => new() { Environment = new Godot.Environment { BackgroundMode = Godot.Environment.BGMode.Color, BackgroundColor = Background, - AmbientLightSource = Godot.Environment.AmbientSource.Color, - AmbientLightColor = AmbientColor, - AmbientLightEnergy = AmbientEnergy, TonemapMode = Godot.Environment.ToneMapper.Linear, }, }; - public static StandardMaterial3D Matte(Color color) => new() { AlbedoColor = color, Roughness = 1f, MetallicSpecular = 0f }; + /// Sets the look's constant shader globals, once. Main sets ps1_res, Chamber the glow. + public static void Apply() + { + Set("ps1_key_dir", KeyDirection); + Set("ps1_key_color", Rgb(KeyColor)); + Set("ps1_ambient", Rgb(AmbientColor)); + Set("ps1_fog_color", Rgb(Background)); + Set("ps1_fog_near", FogNear); + Set("ps1_fog_far", FogFar); + } + + public static void Set(string name, Variant value) => RenderingServer.GlobalShaderParameterSet(name, value); + + public static Vector3 Rgb(Color c) => new(c.R, c.G, c.B); + + /// + /// The PS1 material: (white if null) times , lit and fogged per vertex. Below alpha 1 it is + /// the translucent variant of the same shader. is the world's metres per texture repeat (0: the mesh's UV). + /// + public static ShaderMaterial Ps1(Texture2D? texture, Color tint, float alpha = 1f, bool emissive = false, float tile = 0f) + { + var source = GD.Load("res://ps1.gdshader"); + var shader = alpha < 1f ? new Shader { Code = "#define TRANSLUCENT\n" + source.Code } : source; + var material = new ShaderMaterial { Shader = shader }; + material.SetShaderParameter("albedo_tex", texture); + material.SetShaderParameter("tint", Rgb(tint)); + material.SetShaderParameter("alpha", alpha); + material.SetShaderParameter("emissive", emissive); + material.SetShaderParameter("tile", tile); + return material; + } + + private static ImageTexture Noise(int w, int h, Color baseColour, float spread, ulong seed, Func? grouted = null, Color? groutColour = null) + { + var rng = new RandomNumberGenerator { Seed = seed }; + var image = Image.CreateEmpty(w, h, false, Image.Format.Rgb8); + for (int y = 0; y < h; y++) + for (int x = 0; x < w; x++) + { + var c = grouted?.Invoke(x, y) == true ? groutColour ?? baseColour : baseColour; + float k = rng.RandfRange(-spread, spread); + image.SetPixel(x, y, new Color(Math.Clamp(c.R + k, 0, 1), Math.Clamp(c.G + k, 0, 1), Math.Clamp(c.B + k, 0, 1))); + } + return ImageTexture.CreateFromImage(image); + } } diff --git a/client/Main.cs b/client/Main.cs index 307f164..d951126 100644 --- a/client/Main.cs +++ b/client/Main.cs @@ -50,6 +50,7 @@ public partial class Main : Node3D public override void _Ready() { + Look.Apply(); _bodies = new BodyRenderer { Name = "Bodies" }; AddChild(_bodies); _chamber = new Chamber { Name = "Chamber" }; @@ -59,11 +60,41 @@ public partial class Main : Node3D AddChild(Look.World()); _hud = new Hud(this) { Name = "Hud" }; AddChild(_hud); + AddChild(Post()); + SetLines(); + GetWindow().SizeChanged += SetLines; Reset(Seed); } + /// The line grid: the window's size over its block size, the one value ps1_res ever holds. + public Vector2 Ps1Res { get; private set; } + + private void SetLines() + { + var size = GetWindow().Size; + float block = Look.BlockSize(size.Y); + Ps1Res = new Vector2(size.X / block, size.Y / block); + Look.Set("ps1_res", Ps1Res); + } + + /// The framebuffer pass: a full-screen rect under the HUD (its layer is above this one) that quantises what the 3D drew. + private static CanvasLayer Post() + { + var layer = new CanvasLayer { Name = "Post", Layer = -1 }; + layer.AddChild(new ColorRect + { + Name = "Quantise", + Material = new ShaderMaterial { Shader = GD.Load("res://ps1_post.gdshader") }, + MouseFilter = Control.MouseFilterEnum.Ignore, + AnchorRight = 1, + AnchorBottom = 1, + }); + return layer; + } + public override void _ExitTree() { + if (IsInstanceValid(GetWindow())) GetWindow().SizeChanged -= SetLines; Engine.PhysicsTicksPerSecond = StepsPerSecond(1.0); _session?.Dispose(); _session = null; diff --git a/client/project.godot b/client/project.godot index 12b1c93..236b7ea 100644 --- a/client/project.godot +++ b/client/project.godot @@ -31,3 +31,46 @@ common/physics_interpolation=true renderer/rendering_method="gl_compatibility" renderer/rendering_method.mobile="gl_compatibility" + +[shader_globals] + +ps1_res={ +"type": "vec2", +"value": Vector2(426.667, 240) +} +ps1_key_dir={ +"type": "vec3", +"value": Vector3(-0.4, 0.8, 0.45) +} +ps1_key_color={ +"type": "vec3", +"value": Vector3(0.95, 0.9, 0.82) +} +ps1_ambient={ +"type": "vec3", +"value": Vector3(0.3, 0.34, 0.42) +} +ps1_fog_color={ +"type": "vec3", +"value": Vector3(0.1, 0.1, 0.11) +} +ps1_fog_near={ +"type": "float", +"value": 4.0 +} +ps1_fog_far={ +"type": "float", +"value": 14.0 +} +ps1_glow_pos={ +"type": "vec3", +"value": Vector3(0, 0, 0) +} +ps1_glow_color={ +"type": "vec3", +"value": Vector3(0.85, 0.95, 1) +} +ps1_glow_energy={ +"type": "float", +"value": 0.0 +} diff --git a/client/ps1.gdshader b/client/ps1.gdshader new file mode 100644 index 0000000..4defb82 --- /dev/null +++ b/client/ps1.gdshader @@ -0,0 +1,66 @@ +// The PS1 look, a port of eureka-site prototype/ps1.js (MIT): every vertex snapped to the low-res grid, affine texture coordinates, +// unfiltered texels, per-vertex (Gouraud) light and fog. The arithmetic is the console's, in raw sRGB values with no colour management: +// the compatibility renderer writes ALBEDO to the screen as it is, so nothing converts. The framebuffer's colour depth and dither are ps1_post.gdshader. Look owns every number. +// Look.Ps1 makes the translucent variant by defining TRANSLUCENT ahead of this source: blended, no depth write, both faces. +shader_type spatial; +#ifdef TRANSLUCENT +render_mode unshaded, blend_mix, depth_draw_never, cull_disabled; +#else +render_mode unshaded, cull_back; +#endif + +global uniform vec2 ps1_res; +global uniform vec3 ps1_key_dir; +global uniform vec3 ps1_key_color; +global uniform vec3 ps1_ambient; +global uniform vec3 ps1_fog_color; +global uniform float ps1_fog_near; +global uniform float ps1_fog_far; +global uniform vec3 ps1_glow_pos; +global uniform vec3 ps1_glow_color; +global uniform float ps1_glow_energy; + +uniform sampler2D albedo_tex : hint_default_white, filter_nearest, repeat_enable; +uniform vec3 tint = vec3(1.0); +uniform float alpha = 1.0; +uniform bool emissive = false; +uniform float tile = 0.0; // metres per texture repeat on the world's axes; 0 takes the mesh's own UV + +varying vec3 auv; +varying vec3 light; +varying float fog; + +void vertex() { + vec4 mv = MODELVIEW_MATRIX * vec4(VERTEX, 1.0); + vec4 clip = PROJECTION_MATRIX * mv; + if (clip.w > 0.05) { + vec2 h = ps1_res * 0.5; + clip.xy = floor(clip.xy / clip.w * h + 0.5) / h * clip.w; // the GTE had no sub-pixel precision + } + POSITION = clip; + + vec3 p = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz; + vec3 n = normalize((MODEL_MATRIX * vec4(NORMAL, 0.0)).xyz); + vec2 uv = UV; + if (tile > 0.0) { + vec3 a = abs(n); + uv = (a.y >= a.x && a.y >= a.z ? p.xz : (a.x >= a.z ? p.zy : p.xy)) / tile; + } + auv = vec3(uv * clip.w, clip.w); // pre-multiplied by w: the GPU's perspective division cancels, the texture is affine + + vec3 to_glow = ps1_glow_pos - p; + float d = length(to_glow); + float near = clamp(1.0 - d / 0.9, 0.0, 1.0); + vec3 glow = ps1_glow_color * ps1_glow_energy * max(dot(n, to_glow / max(d, 1e-4)), 0.0) * near * near; + light = emissive ? vec3(1.0) : ps1_ambient + ps1_key_color * max(dot(n, ps1_key_dir), 0.0) + glow; + fog = smoothstep(ps1_fog_near, ps1_fog_far, -mv.z); +} + +void fragment() { + vec3 c = texture(albedo_tex, auv.xy / auv.z).rgb * tint * light; + c = mix(c, ps1_fog_color, fog); + ALBEDO = c; +#ifdef TRANSLUCENT + ALPHA = alpha; +#endif +} diff --git a/client/ps1_post.gdshader b/client/ps1_post.gdshader new file mode 100644 index 0000000..8abd30c --- /dev/null +++ b/client/ps1_post.gdshader @@ -0,0 +1,18 @@ +// The PS1 framebuffer: one colour per block of the line grid, 15-bit colour with the console's 4x4 ordered dither. The block grid is +// anchored at the screen centre, as the vertex snap is. A full-screen ColorRect under the HUD runs it. +shader_type canvas_item; + +uniform sampler2D screen_tex : hint_screen_texture, filter_nearest; +global uniform vec2 ps1_res; + +const mat4 D = mat4(vec4(-4., 0., -3., 1.), vec4(2., -2., 3., -1.), vec4(-3., 1., -4., 0.), vec4(3., -1., 2., -2.)); + +void fragment() { + vec2 size = 1.0 / SCREEN_PIXEL_SIZE; + float s = size.y / ps1_res.y; + vec2 b = floor((FRAGCOORD.xy - size * 0.5) / s); + vec3 c = textureLod(screen_tex, (size * 0.5 + (b + 0.5) * s) / size, 0.0).rgb * 255.0; + ivec2 q = ivec2(mod(b, 4.0)); + c = clamp(c + D[q.x][q.y], 0.0, 255.0); + COLOR = vec4(floor(c / 8.0) * 8.0 / 255.0, 1.0); +} diff --git a/client/tests/Smoke.cs b/client/tests/Smoke.cs index 5b81dbc..b8cc7d4 100644 --- a/client/tests/Smoke.cs +++ b/client/tests/Smoke.cs @@ -174,10 +174,19 @@ public partial class Smoke : Node Check(_main.IsPhysicsInterpolatedAndEnabled() && (bool)ProjectSettings.GetSetting("physics/common/physics_interpolation"), "physics interpolation is off"); Check(_main.Seed == Seed, "Main did not start from the smoke's seed"); - // The look: dark grey. - Check(_main.Bodies.SceneryMaterial.AlbedoColor.Luminance < 0.3f, "the floor is not dark"); - var glow = _main.Chamber.Material.AlbedoColor; - Check(glow.V > 0.7f && glow.S < 0.3f, $"the chamber is {glow}, not light"); + // The look: PS1. Every surface is the PS1 shader and the shader lights it (no Light3D), the quantising pass sits below the HUD, the + // 3D has no MSAA, and ps1_res is the window over its block size. + var ps1 = GD.Load("res://ps1.gdshader"); + var meshes = _main.FindChildren("*", "MeshInstance3D", true, false).Cast().ToArray(); + Check(meshes.Length > 0 && meshes.All(m => m.MaterialOverride is ShaderMaterial sm && (sm.Shader == ps1 || sm.Shader.Code.EndsWith(ps1.Code))), "a mesh is not drawn with res://ps1.gdshader"); + Check(Count(_main, n => n is Light3D) == 0, "the scene has a Light3D; the shader lights it"); + Check(_main.GetNode("Post").Layer < Hud.Layer, "the post pass does not sit below the HUD"); + Check((int)ProjectSettings.GetSetting("rendering/anti_aliasing/quality/msaa_3d", 0) == 0, "msaa_3d is on"); + int height = GetWindow().Size.Y, block = Math.Max(1, (int)Math.Round(height / (double)Look.Lines, MidpointRounding.AwayFromZero)); + Check(Math.Abs(_main.Ps1Res.Y - height / (float)block) < 1e-4f, $"ps1_res.y is {_main.Ps1Res.Y}, not {height} / {block}"); + Check(Look.Scenery.Luminance < 0.3f, "the floor is not dark"); + var glow = (Vector3)_main.Chamber.Material.GetShaderParameter("tint"); + Check(Math.Max(glow.X, Math.Max(glow.Y, glow.Z)) > 0.7f, $"the chamber is {glow}, not light"); var environment = _main.GetChildren().OfType().Single().Environment; Check(environment.BackgroundColor.Luminance < 0.2f, "the background is not dark grey"); Check(environment.Sky is null && environment.TonemapMode == Godot.Environment.ToneMapper.Linear && !environment.GlowEnabled, "the environment is not a linear colour environment with no sky and no glow");