Merge remote-tracking branch 'origin/nibu/rtd-prototype' into nibu/rtd-cut11b-walker

# Conflicts:
#	src/RustToDust.Net/RemoteArenaSession.cs
#	src/RustToDust.Ymir/ArenaSession.cs
#	src/RustToDust.Ymir/WalkerLocomotion.cs
#	tests/RustToDust.Tests/CultNetMultiplayerTests.cs
This commit is contained in:
Meta Vens 2026-12-06 06:04:25 +01:00
commit c61b0b6a3b
250 changed files with 29333 additions and 4118 deletions

3
.gitignore vendored
View file

@ -2,7 +2,10 @@
__pycache__/
/out/
/scratch/
/dist/
bin/
obj/
artifacts/
build/
.godot/
.vs/

View file

@ -2,6 +2,7 @@
<Folder Name="/src/">
<Project Path="src/RustToDust.Core/RustToDust.Core.csproj" />
<Project Path="src/RustToDust.Ymir/RustToDust.Ymir.csproj" />
<Project Path="src/RustToDust.HbGpu/RustToDust.HbGpu.csproj" />
<Project Path="src/RustToDust.Net/RustToDust.Net.csproj" />
<Project Path="src/RustToDust.Server/RustToDust.Server.csproj" />
<Project Path="src/RustToDust.Directory/RustToDust.Directory.csproj" />

20
THIRD_PARTY_NOTICES.txt Normal file
View file

@ -0,0 +1,20 @@
THIRD-PARTY SOFTWARE NOTICES AND INFORMATION
This product incorporates or bundles the following third-party software and
font assets under their respective licenses:
1. Monaspace Krypton (Krypton.ttf — Monaspace Krypton Var.ttf v1.400)
Copyright (c) 2023, GitHub (https://github.com/githubnext/monaspace)
Reserved Font Names: 'Monaspace', 'Argon', 'Neon', 'Xenon', 'Radon', 'Krypton'
License: SIL Open Font License, Version 1.1
Full license text: assets/fonts/OFL-1.1.txt
2. HarfBuzz (15.2.0) — shaping and hb-gpu shader/curve encoder (rtd_hbgpu)
Copyright (C) HarfBuzz Authors (Behdad Esfahbod, Google Inc., Red Hat Inc., et al.)
License: HarfBuzz "Old MIT" License
Full license text: assets/fonts/HARFBUZZ-COPYING.txt
3. Cosmo Tree Gen (upstream commit 33d6dc819ae79d5fff21d8b98407857cc2fc4d99, extended for RustToDust)
Copyright (c) 2026 CosmonautFrog (https://github.com/FrogCosmonaut/cosmo_tree_gen)
License: MIT License
Full license text: third_party/cosmo_tree_gen/LICENSE.md

View file

@ -0,0 +1,42 @@
HarfBuzz is licensed under the so-called "Old MIT" license. Details follow.
For parts of HarfBuzz that are licensed under different licenses see individual
files names COPYING in subdirectories where applicable.
Copyright © 2010-2022 Google, Inc.
Copyright © 2015-2020 Ebrahim Byagowi
Copyright © 2019,2020 Facebook, Inc.
Copyright © 2012,2015 Mozilla Foundation
Copyright © 2011 Codethink Limited
Copyright © 2008,2010 Nokia Corporation and/or its subsidiary(-ies)
Copyright © 2009 Keith Stribley
Copyright © 2011 Martin Hosken and SIL International
Copyright © 2007 Chris Wilson
Copyright © 2005,2006,2020,2021,2022,2023 Behdad Esfahbod
Copyright © 2004,2007,2008,2009,2010,2013,2021,2022,2023 Red Hat, Inc.
Copyright © 1998-2005 David Turner and Werner Lemberg
Copyright © 2016 Igalia S.L.
Copyright © 2022 Matthias Clasen
Copyright © 2018,2021 Khaled Hosny
Copyright © 2018,2019,2020 Adobe, Inc
Copyright © 2013-2015 Alexei Podtelezhnikov
For full copyright notices consult the individual files in the package.
Permission is hereby granted, without written agreement and without
license or royalty fees, to use, copy, modify, and distribute this
software and its documentation for any purpose, provided that the
above copyright notice and the following two paragraphs appear in
all copies of this software.
IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

BIN
assets/fonts/Krypton.ttf Normal file

Binary file not shown.

94
assets/fonts/OFL-1.1.txt Normal file
View file

@ -0,0 +1,94 @@
Copyright (c) 2023, GitHub (https://github.com/githubnext/monaspace)
with Reserved Font Names 'Monaspace', 'Argon', 'Neon', 'Xenon', 'Radon', 'Krypton'.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSIONS & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to remain
under this license does not apply to any document created using the fonts
or their derivatives.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

Binary file not shown.

Binary file not shown.

View file

@ -2,7 +2,7 @@
"name": "Sion, Valais, Switzerland",
"attribution": "Federal Office of Topography swisstopo",
"sources": [
"ch.swisstopo.swissalti3d (2m DTM, Open Government Data)",
"ch.swisstopo.swissalti3d (0.5m DTM, Open Government Data)",
"ch.swisstopo.swissbuildings3d_3_0 (LOD2 3D Buildings, Open Government Data)"
],
"stacItems": [
@ -27,24 +27,33 @@
"swissbuildings3d_3_0_2020_1306-21",
"swissbuildings3d_3_0_2020_1306-23"
],
"demAssetHash": "a0dae3310058004e43a071290b3972ae4e0919e0958be5ec56320ea1a204c5de",
"crs": "EPSG:2056",
"originE": 2592614.0,
"originN": 1118514.0,
"centerE": 2594150.0,
"centerN": 1120050.0,
"baseElevationM": 483.41,
"minY": -5.863,
"maxY": 304.92,
"reliefM": 310.783,
"minY": -5.885,
"maxY": 304.957,
"reliefM": 310.841,
"sizeMeters": 3072.0,
"tileGrid": 6,
"tileSizeMeters": 512.0,
"gridRes": 1025,
"cellSizeMeters": 3.0,
"heightmapFormat": "float32_le_row_major",
"tileGrid": 16,
"tileSizeMeters": 192.0,
"buildingTileGrid": 6,
"buildingTileSizeMeters": 512.0,
"gridRes": 6145,
"cellSizeMeters": 0.5,
"heightmapFile": "heightmap_05m.u16z",
"heightmapFormat": "rdhm_v2_u16_zigzag_zlib",
"heightmapMinY": -5.884674072265625,
"heightmapScale": 0.004743136931210756,
"surfaceTexture": "terrain_surface.png",
"surfaceTextureSize": 2048,
"surfaceTextureSize": 4096,
"surfaceTextureFormat": "png_rgb_north_to_south_west_to_east",
"surfaceMaskTexture": "terrain_surface_mask.png",
"surfaceMaskTextureSize": 2048,
"surfaceMaskFormat": "png_rgba_rock_grass_asphalt_water",
"collisionFormat": {
"magic": "RCOL",
"version": 1,

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 MiB

After

Width:  |  Height:  |  Size: 9.7 MiB

Before After
Before After

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 MiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 124 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 129 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

View file

@ -0,0 +1,501 @@
{
"archetypes": [
{
"barkTexture": "textures/bark.png",
"barkTint": [
0.759999990463257,
0.540000021457672,
0.400000005960464
],
"canonicalHeightM": 19.94,
"canonicalRadiusM": 0.34,
"glb": "pinus_sylvestris_v0.glb",
"impostorAlbedo": "pinus_sylvestris_v0_impostor_albedo.png",
"impostorFrames": 6,
"impostorNormal": "pinus_sylvestris_v0_impostor_normal.png",
"impostorOffsetY": 9.8,
"impostorScale": 10.86,
"leafTexture": "textures/branchlet_pine.png",
"leafTint": [
0.560000002384186,
0.680000007152557,
0.439999997615814
],
"lod0Tris": 906,
"lod1Tris": 222,
"lod2Tris": 30,
"slug": "pinus_sylvestris_v0",
"speciesId": 0,
"speciesName": "PinusSylvestris",
"variant": 0
},
{
"barkTexture": "textures/bark.png",
"barkTint": [
0.759999990463257,
0.540000021457672,
0.400000005960464
],
"canonicalHeightM": 17.19,
"canonicalRadiusM": 0.29,
"glb": "pinus_sylvestris_v1.glb",
"impostorAlbedo": "pinus_sylvestris_v1_impostor_albedo.png",
"impostorFrames": 6,
"impostorNormal": "pinus_sylvestris_v1_impostor_normal.png",
"impostorOffsetY": 8.42,
"impostorScale": 9.41,
"leafTexture": "textures/branchlet_pine.png",
"leafTint": [
0.560000002384186,
0.680000007152557,
0.439999997615814
],
"lod0Tris": 766,
"lod1Tris": 188,
"lod2Tris": 34,
"slug": "pinus_sylvestris_v1",
"speciesId": 0,
"speciesName": "PinusSylvestris",
"variant": 1
},
{
"barkTexture": "textures/bark.png",
"barkTint": [
0.560000002384186,
0.5,
0.439999997615814
],
"canonicalHeightM": 15.37,
"canonicalRadiusM": 0.36,
"glb": "quercus_pubescens_v0.glb",
"impostorAlbedo": "quercus_pubescens_v0_impostor_albedo.png",
"impostorFrames": 6,
"impostorNormal": "quercus_pubescens_v0_impostor_normal.png",
"impostorOffsetY": 7.51,
"impostorScale": 9.38,
"leafTexture": "textures/branchlet_oak.png",
"leafTint": [
0.620000004768372,
0.699999988079071,
0.400000005960464
],
"lod0Tris": 626,
"lod1Tris": 156,
"lod2Tris": 34,
"slug": "quercus_pubescens_v0",
"speciesId": 1,
"speciesName": "QuercusPubescens",
"variant": 0
},
{
"barkTexture": "textures/bark.png",
"barkTint": [
0.560000002384186,
0.5,
0.439999997615814
],
"canonicalHeightM": 14.83,
"canonicalRadiusM": 0.3,
"glb": "quercus_pubescens_v1.glb",
"impostorAlbedo": "quercus_pubescens_v1_impostor_albedo.png",
"impostorFrames": 6,
"impostorNormal": "quercus_pubescens_v1_impostor_normal.png",
"impostorOffsetY": 7.24,
"impostorScale": 8.83,
"leafTexture": "textures/branchlet_oak.png",
"leafTint": [
0.620000004768372,
0.699999988079071,
0.400000005960464
],
"lod0Tris": 666,
"lod1Tris": 166,
"lod2Tris": 32,
"slug": "quercus_pubescens_v1",
"speciesId": 1,
"speciesName": "QuercusPubescens",
"variant": 1
},
{
"barkTexture": "textures/bark.png",
"barkTint": [
0.680000007152557,
0.649999976158142,
0.579999983310699
],
"canonicalHeightM": 22.99,
"canonicalRadiusM": 0.38,
"glb": "populus_nigra_v0.glb",
"impostorAlbedo": "populus_nigra_v0_impostor_albedo.png",
"impostorFrames": 6,
"impostorNormal": "populus_nigra_v0_impostor_normal.png",
"impostorOffsetY": 11.32,
"impostorScale": 12.46,
"leafTexture": "textures/branchlet_broadleaf.png",
"leafTint": [
0.660000026226044,
0.779999971389771,
0.46000000834465
],
"lod0Tris": 1066,
"lod1Tris": 262,
"lod2Tris": 46,
"slug": "populus_nigra_v0",
"speciesId": 2,
"speciesName": "PopulusNigra",
"variant": 0
},
{
"barkTexture": "textures/bark.png",
"barkTint": [
0.680000007152557,
0.649999976158142,
0.579999983310699
],
"canonicalHeightM": 20.41,
"canonicalRadiusM": 0.33,
"glb": "populus_nigra_v1.glb",
"impostorAlbedo": "populus_nigra_v1_impostor_albedo.png",
"impostorFrames": 6,
"impostorNormal": "populus_nigra_v1_impostor_normal.png",
"impostorOffsetY": 10.03,
"impostorScale": 11.1,
"leafTexture": "textures/branchlet_broadleaf.png",
"leafTint": [
0.660000026226044,
0.779999971389771,
0.46000000834465
],
"lod0Tris": 906,
"lod1Tris": 226,
"lod2Tris": 50,
"slug": "populus_nigra_v1",
"speciesId": 2,
"speciesName": "PopulusNigra",
"variant": 1
},
{
"barkTexture": "textures/bark.png",
"barkTint": [
0.759999990463257,
0.720000028610229,
0.620000004768372
],
"canonicalHeightM": 25.98,
"canonicalRadiusM": 0.42,
"glb": "platanus_acerifolia_v0.glb",
"impostorAlbedo": "platanus_acerifolia_v0_impostor_albedo.png",
"impostorFrames": 6,
"impostorNormal": "platanus_acerifolia_v0_impostor_normal.png",
"impostorOffsetY": 12.81,
"impostorScale": 14.44,
"leafTexture": "textures/branchlet_broadleaf.png",
"leafTint": [
0.639999985694885,
0.759999990463257,
0.419999986886978
],
"lod0Tris": 826,
"lod1Tris": 206,
"lod2Tris": 46,
"slug": "platanus_acerifolia_v0",
"speciesId": 3,
"speciesName": "PlatanusAcerifolia",
"variant": 0
},
{
"barkTexture": "textures/bark.png",
"barkTint": [
0.759999990463257,
0.720000028610229,
0.620000004768372
],
"canonicalHeightM": 23.87,
"canonicalRadiusM": 0.36,
"glb": "platanus_acerifolia_v1.glb",
"impostorAlbedo": "platanus_acerifolia_v1_impostor_albedo.png",
"impostorFrames": 6,
"impostorNormal": "platanus_acerifolia_v1_impostor_normal.png",
"impostorOffsetY": 11.76,
"impostorScale": 13.17,
"leafTexture": "textures/branchlet_broadleaf.png",
"leafTint": [
0.639999985694885,
0.759999990463257,
0.419999986886978
],
"lod0Tris": 826,
"lod1Tris": 206,
"lod2Tris": 54,
"slug": "platanus_acerifolia_v1",
"speciesId": 3,
"speciesName": "PlatanusAcerifolia",
"variant": 1
},
{
"barkTexture": "textures/bark.png",
"barkTint": [
0.920000016689301,
0.899999976158142,
0.860000014305115
],
"canonicalHeightM": 18.06,
"canonicalRadiusM": 0.21,
"glb": "betula_pendula_v0.glb",
"impostorAlbedo": "betula_pendula_v0_impostor_albedo.png",
"impostorFrames": 6,
"impostorNormal": "betula_pendula_v0_impostor_normal.png",
"impostorOffsetY": 8.88,
"impostorScale": 9.79,
"leafTexture": "textures/branchlet_birch.png",
"leafTint": [
0.699999988079071,
0.819999992847443,
0.46000000834465
],
"lod0Tris": 906,
"lod1Tris": 220,
"lod2Tris": 42,
"slug": "betula_pendula_v0",
"speciesId": 4,
"speciesName": "BetulaPendula",
"variant": 0
},
{
"barkTexture": "textures/bark.png",
"barkTint": [
0.920000016689301,
0.899999976158142,
0.860000014305115
],
"canonicalHeightM": 16.02,
"canonicalRadiusM": 0.18,
"glb": "betula_pendula_v1.glb",
"impostorAlbedo": "betula_pendula_v1_impostor_albedo.png",
"impostorFrames": 6,
"impostorNormal": "betula_pendula_v1_impostor_normal.png",
"impostorOffsetY": 7.86,
"impostorScale": 8.82,
"leafTexture": "textures/branchlet_birch.png",
"leafTint": [
0.699999988079071,
0.819999992847443,
0.46000000834465
],
"lod0Tris": 906,
"lod1Tris": 220,
"lod2Tris": 42,
"slug": "betula_pendula_v1",
"speciesId": 4,
"speciesName": "BetulaPendula",
"variant": 1
},
{
"barkTexture": "textures/bark.png",
"barkTint": [
0.540000021457672,
0.419999986886978,
0.340000003576279
],
"canonicalHeightM": 20.52,
"canonicalRadiusM": 0.32,
"glb": "picea_abies_v0.glb",
"impostorAlbedo": "picea_abies_v0_impostor_albedo.png",
"impostorFrames": 6,
"impostorNormal": "picea_abies_v0_impostor_normal.png",
"impostorOffsetY": 10.08,
"impostorScale": 12.19,
"leafTexture": "textures/branchlet_spruce.png",
"leafTint": [
0.419999986886978,
0.560000002384186,
0.360000014305115
],
"lod0Tris": 622,
"lod1Tris": 150,
"lod2Tris": 66,
"slug": "picea_abies_v0",
"speciesId": 5,
"speciesName": "PiceaAbies",
"variant": 0
},
{
"barkTexture": "textures/bark.png",
"barkTint": [
0.540000021457672,
0.419999986886978,
0.340000003576279
],
"canonicalHeightM": 17.52,
"canonicalRadiusM": 0.27,
"glb": "picea_abies_v1.glb",
"impostorAlbedo": "picea_abies_v1_impostor_albedo.png",
"impostorFrames": 6,
"impostorNormal": "picea_abies_v1_impostor_normal.png",
"impostorOffsetY": 8.58,
"impostorScale": 10.2,
"leafTexture": "textures/branchlet_spruce.png",
"leafTint": [
0.419999986886978,
0.560000002384186,
0.360000014305115
],
"lod0Tris": 542,
"lod1Tris": 130,
"lod2Tris": 50,
"slug": "picea_abies_v1",
"speciesId": 5,
"speciesName": "PiceaAbies",
"variant": 1
},
{
"barkTexture": "textures/bark.png",
"barkTint": [
0.620000004768372,
0.540000021457672,
0.46000000834465
],
"canonicalHeightM": 8.87,
"canonicalRadiusM": 0.18,
"glb": "malus_orchard_v0.glb",
"impostorAlbedo": "malus_orchard_v0_impostor_albedo.png",
"impostorFrames": 6,
"impostorNormal": "malus_orchard_v0_impostor_normal.png",
"impostorOffsetY": 4.31,
"impostorScale": 4.9,
"leafTexture": "textures/branchlet_orchard.png",
"leafTint": [
0.680000007152557,
0.779999971389771,
0.439999997615814
],
"lod0Tris": 666,
"lod1Tris": 164,
"lod2Tris": 30,
"slug": "malus_orchard_v0",
"speciesId": 6,
"speciesName": "MalusOrchard",
"variant": 0
},
{
"barkTexture": "textures/bark.png",
"barkTint": [
0.620000004768372,
0.540000021457672,
0.46000000834465
],
"canonicalHeightM": 7.66,
"canonicalRadiusM": 0.15,
"glb": "malus_orchard_v1.glb",
"impostorAlbedo": "malus_orchard_v1_impostor_albedo.png",
"impostorFrames": 6,
"impostorNormal": "malus_orchard_v1_impostor_normal.png",
"impostorOffsetY": 3.71,
"impostorScale": 4.72,
"leafTexture": "textures/branchlet_orchard.png",
"leafTint": [
0.680000007152557,
0.779999971389771,
0.439999997615814
],
"lod0Tris": 666,
"lod1Tris": 164,
"lod2Tris": 34,
"slug": "malus_orchard_v1",
"speciesId": 6,
"speciesName": "MalusOrchard",
"variant": 1
},
{
"barkTexture": "textures/bark.png",
"barkTint": [
0.720000028610229,
0.419999986886978,
0.300000011920929
],
"canonicalHeightM": 29.09,
"canonicalRadiusM": 0.88,
"glb": "sequoiadendron_v0.glb",
"impostorAlbedo": "sequoiadendron_v0_impostor_albedo.png",
"impostorFrames": 6,
"impostorNormal": "sequoiadendron_v0_impostor_normal.png",
"impostorOffsetY": 14.29,
"impostorScale": 15.87,
"leafTexture": "textures/branchlet_spruce.png",
"leafTint": [
0.46000000834465,
0.600000023841858,
0.379999995231628
],
"lod0Tris": 662,
"lod1Tris": 160,
"lod2Tris": 74,
"slug": "sequoiadendron_v0",
"speciesId": 7,
"speciesName": "Sequoiadendron",
"variant": 0
},
{
"barkTexture": "textures/bark.png",
"barkTint": [
0.579999983310699,
0.519999980926514,
0.46000000834465
],
"canonicalHeightM": 25.51,
"canonicalRadiusM": 0.68,
"glb": "cedrus_v0.glb",
"impostorAlbedo": "cedrus_v0_impostor_albedo.png",
"impostorFrames": 6,
"impostorNormal": "cedrus_v0_impostor_normal.png",
"impostorOffsetY": 12.53,
"impostorScale": 13.92,
"leafTexture": "textures/branchlet_spruce.png",
"leafTint": [
0.479999989271164,
0.639999985694885,
0.46000000834465
],
"lod0Tris": 986,
"lod1Tris": 244,
"lod2Tris": 38,
"slug": "cedrus_v0",
"speciesId": 8,
"speciesName": "Cedrus",
"variant": 0
},
{
"barkTexture": "textures/bark.png",
"barkTint": [
0.779999971389771,
0.740000009536743,
0.639999985694885
],
"canonicalHeightM": 36.57,
"canonicalRadiusM": 0.72,
"glb": "platanus_monumental_v0.glb",
"impostorAlbedo": "platanus_monumental_v0_impostor_albedo.png",
"impostorFrames": 6,
"impostorNormal": "platanus_monumental_v0_impostor_normal.png",
"impostorOffsetY": 18.06,
"impostorScale": 20.0,
"leafTexture": "textures/branchlet_broadleaf.png",
"leafTint": [
0.639999985694885,
0.759999990463257,
0.419999986886978
],
"lod0Tris": 906,
"lod1Tris": 226,
"lod2Tris": 50,
"slug": "platanus_monumental_v0",
"speciesId": 9,
"speciesName": "PlatanusMonumental",
"variant": 0
}
],
"beechPresent": false,
"impostorFrames": 6,
"impostorResolution": 384,
"version": 1
}

Binary file not shown.

View file

@ -24,9 +24,7 @@ public partial class ArenaRenderer : Node3D
public required VehicleVisualInstance Visual;
public MeshInstance3D? HaloMesh;
public StandardMaterial3D? HaloMat;
public MeshInstance3D? LaserMesh;
public SpectatorStance? LastHaloStance;
public bool LastLaserVisible;
public float RigDtAccum;
public int RigSkipFrames;
}
@ -70,7 +68,7 @@ public partial class ArenaRenderer : Node3D
}
private const int MaxVfxBeams = 512;
private const int MaxVfxSpheres = 512;
private const int MaxVfxSpheres = 64;
private const int MaxVfxRings = 128;
private VehicleAssetCache _assetCache = null!;
@ -80,6 +78,8 @@ public partial class ArenaRenderer : Node3D
private PomDecalPool _pomDecals = null!;
private DebrisSystem _debris = null!;
private ParticlePool _particles = null!;
private readonly VolumetricEmitterPool _volumetrics = new();
private GpuSparksSystem _gpuSparks = null!;
private MeshInstance3D _safeRingMesh = null!;
private ImmediateMesh _safeRingImm = null!;
@ -89,8 +89,9 @@ public partial class ArenaRenderer : Node3D
private MultiMesh _dropPillarMm = null!;
private MultiMeshInstance3D _dropPillarMmi = null!;
// Pooled weapon VFX MultiMeshes (beams/tracers, explosive detonation cores, shockwave rings)
// Pooled weapon VFX MultiMeshes (analytic volumetric capsule beams, optional spheres, shockwave rings)
private ShaderMaterial _vfxMat = null!;
private ShaderMaterial _vfxBeamMat = null!;
private MultiMesh _vfxBeamMm = null!;
private MultiMeshInstance3D _vfxBeamMmi = null!;
private MultiMesh _vfxSphereMm = null!;
@ -99,8 +100,9 @@ public partial class ArenaRenderer : Node3D
private MultiMeshInstance3D _vfxRingMmi = null!;
private readonly List<TransientVfx> _transientVfx = new(128);
private readonly ClientOrdnanceMirror _ordnanceMirror = new();
private readonly List<(Transform3D Xf, Color Col)> _mirrorSpheres = new(64);
private readonly List<(Transform3D Xf, Color Col)> _mirrorSpheres = new(32);
private readonly List<(Transform3D Xf, Color Col)> _mirrorRings = new(128);
private readonly List<ClientOrdnanceMirror.ActiveBeamSpec> _mirrorBeams = new(64);
private int _activeBeamCount;
// Continuous emitter rate limiters (keyed by (IsContender, EntityId))
@ -120,12 +122,15 @@ public partial class ArenaRenderer : Node3D
private StandardMaterial3D _coverMat = null!;
private StandardMaterial3D _bermMat = null!;
private StandardMaterial3D _imperialBeaconMat = null!;
private ArrayMesh? _fallingLogMesh;
private MatchState? _builtForState;
private float _lastSafeRingRadius = -1f;
public VehicleAssetCache AssetCache => _assetCache;
public DebrisSystem Debris => _debris;
public ParticlePool Particles => _particles;
public VolumetricEmitterPool Volumetrics => _volumetrics;
public GpuSparksSystem GpuSparks => _gpuSparks;
internal MultiMeshPartPool PartPool => _partPool;
internal PomDecalPool PomDecals => _pomDecals;
internal ClientOrdnanceMirror OrdnanceMirror => _ordnanceMirror;
@ -167,12 +172,15 @@ public partial class ArenaRenderer : Node3D
_pomDecals = new PomDecalPool { Name = "PomDecals" };
_debris = new DebrisSystem { Name = "Debris" };
_particles = new ParticlePool { Name = "ParticlePool" };
_gpuSparks = new GpuSparksSystem { Name = "GpuSparks" };
_particles.BindTargets(_volumetrics, _gpuSparks);
AddChild(_staticGroup);
AddChild(_actorsGroup);
AddChild(_partPool);
AddChild(_pomDecals);
AddChild(_debris);
AddChild(_particles);
AddChild(_gpuSparks);
_coverMat = new StandardMaterial3D { AlbedoColor = CoverRust, Roughness = 0.88f, Metallic = 0.25f };
_bermMat = new StandardMaterial3D { AlbedoColor = BermDark, Roughness = 0.94f, Metallic = 0.1f };
@ -229,9 +237,14 @@ public partial class ArenaRenderer : Node3D
};
_vfxMat = new ShaderMaterial { Shader = vfxShader };
Shader beamShader = GD.Load<Shader>("res://volumetric_capsule_beam.gdshader")
?? throw new InvalidOperationException("Failed to load res://volumetric_capsule_beam.gdshader");
_vfxBeamMat = new ShaderMaterial { Shader = beamShader };
_vfxBeamMm = new MultiMesh
{
TransformFormat = MultiMesh.TransformFormatEnum.Transform3D,
UseColors = true,
UseCustomData = true,
Mesh = new BoxMesh { Size = Vector3.One },
InstanceCount = MaxVfxBeams,
@ -241,7 +254,7 @@ public partial class ArenaRenderer : Node3D
{
Name = "VfxBeams",
Multimesh = _vfxBeamMm,
MaterialOverride = _vfxMat,
MaterialOverride = _vfxBeamMat,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off,
CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)),
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off,
@ -357,17 +370,19 @@ public partial class ArenaRenderer : Node3D
SyncOrbitalPods(session, alpha, hasCam, camPos);
_mirrorSpheres.Clear();
_mirrorRings.Clear();
_mirrorBeams.Clear();
_ordnanceMirror.StepAndSubmit(
dt,
session,
_assetCache,
_partPool,
_particles,
_volumetrics,
state.Terrain,
hasCam,
camPos,
(xf, col) => _mirrorRings.Add((xf, col)),
(xf, col) => _mirrorSpheres.Add((xf, col)));
beam => _mirrorBeams.Add(beam));
_debris.Step(dt, state.Terrain);
_debris.SubmitToPool(_partPool);
_partPool.EndFrame();
@ -397,6 +412,7 @@ public partial class ArenaRenderer : Node3D
_assetCache,
_debris,
_particles,
_volumetrics,
hasCam,
camPos,
spec => AddTransient(new TransientVfx
@ -422,8 +438,68 @@ public partial class ArenaRenderer : Node3D
EmitContinuousActorParticles(session, hasCam, camPos, sampleGroundTint);
ConsumeDropPodEvents(session, events, camPos, hasCam);
ConsumeTreeEvents(state, events, camPos, hasCam);
UpdateExplosiveRingsAndCores(events, stepDt);
_particles.AdvanceAndCommit(stepDt);
_volumetrics.Step(stepDt);
}
private void ConsumeTreeEvents(MatchState state, IReadOnlyList<ISimEvent> events, Vector3 camPos, bool hasCam)
{
if (state.SionTrees is null)
{
return;
}
var trees = state.SionTrees.Catalog;
for (int i = 0; i < events.Count; i++)
{
if (events[i] is not TreeStateEvent te || te.TreeId >= trees.Count)
{
continue;
}
var placement = trees.Trees[te.TreeId];
Vector3 canopyPos = new(placement.X, placement.Y + placement.HeightM * 0.55f, placement.Z);
var st = (SionTreeState)te.State;
if (st == SionTreeState.Snapped)
{
_fallingLogMesh ??= BuildFallingLogMesh();
float trunkLen = Math.Clamp(placement.HeightM * 0.48f, 2.2f, 6.5f);
float trunkW = Math.Clamp(placement.TrunkRadiusM * 2.0f, 0.28f, 1.4f);
Basis rot = Basis.FromEuler(new Vector3(0.25f, placement.Yaw, 0.18f))
.Scaled(new Vector3(trunkW, trunkLen, trunkW));
Transform3D xf = new(rot, new Vector3(placement.X, placement.Y + 2.6f, placement.Z));
_debris.SpawnDetachedPart(
_fallingLogMesh,
xf,
new Vector3(te.ImpactX, te.ImpactY, te.ImpactZ),
Vector3.Up * 2.5f,
roleIndex: 2f,
impulseScale: 0.75f,
applyScorch: true,
lifetime: 5.0f);
_particles.EmitTreeImpactBurst(canopyPos, placement.HeightM, isChar: false, camPos, hasCam);
}
else if (st == SionTreeState.Charred)
{
_particles.EmitTreeImpactBurst(canopyPos, placement.HeightM, isChar: true, camPos, hasCam);
}
}
}
private static ArrayMesh BuildFallingLogMesh()
{
var cyl = new CylinderMesh
{
TopRadius = 0.36f,
BottomRadius = 0.52f,
Height = 1.0f,
RadialSegments = 6,
Rings = 1
};
var st = new SurfaceTool();
st.Begin(Mesh.PrimitiveType.Triangles);
st.AppendFrom(cyl, 0, Transform3D.Identity);
return st.Commit();
}
private VehicleVisualInstance? ResolveEntityVisual(bool isContender, int id) =>
@ -513,10 +589,13 @@ public partial class ArenaRenderer : Node3D
_pomDecals.ClearAll();
_debris.ClearAll();
_particles.ClearAll();
_volumetrics.ClearAll();
_gpuSparks.ClearAll();
_transientVfx.Clear();
_ordnanceMirror.Clear();
_mirrorSpheres.Clear();
_mirrorRings.Clear();
_mirrorBeams.Clear();
_tireDustNextTime.Clear();
_thermalVentNextTime.Clear();
_damageSmokeNextTime.Clear();
@ -712,10 +791,6 @@ public partial class ArenaRenderer : Node3D
hiddenVis.Visual.SyncDamageAndHeat(s.Grid, _debris, Vector3.Zero);
}
hiddenVis.Visual.Root.Visible = false;
if (hiddenVis.LaserMesh is not null)
{
hiddenVis.LaserMesh.Visible = false;
}
}
continue;
}
@ -837,42 +912,6 @@ public partial class ArenaRenderer : Node3D
vis.HaloMat.EmissionEnergyMultiplier = pulse;
}
}
// Lock-on laser beam when Cleared or Provoked
if (vis.LaserMesh is not null)
{
if (s.Stance != SpectatorStance.Neutral && s.HasTargetLos && target is { Alive: true } &&
(target.Id == session.LocalContenderId || session.IsContenderVisible(target.Id)))
{
Vector3 start = specPos + new Vector3(0f, s.Grid.Spec.HalfHeight * 0.7f, 0f);
var (targetPos, _, _) = session.GetInterpolatedContenderPose(target.Id, alpha);
Vector3 end = new Vector3(targetPos.X, targetPos.Y + target.Grid.Spec.HalfHeight * 0.3f, targetPos.Z);
float dist = start.DistanceTo(end);
if (dist > 0.5f)
{
if (!vis.LastLaserVisible)
{
vis.LastLaserVisible = true;
vis.LaserMesh.Visible = true;
}
vis.LaserMesh.GlobalPosition = (start + end) * 0.5f;
Vector3 dir = (end - start).Normalized();
Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.99f ? Vector3.Right : Vector3.Up;
vis.LaserMesh.LookAt(end, up);
vis.LaserMesh.Scale = new Vector3(1f, 1f, dist);
}
else if (vis.LastLaserVisible)
{
vis.LastLaserVisible = false;
vis.LaserMesh.Visible = false;
}
}
else if (vis.LastLaserVisible)
{
vis.LastLaserVisible = false;
vis.LaserMesh.Visible = false;
}
}
}
}
@ -894,30 +933,11 @@ public partial class ArenaRenderer : Node3D
};
instance.Root.AddChild(halo);
var laserMat = new StandardMaterial3D
{
AlbedoColor = new Color(2.2f, 0.24f, 0.20f, 0.85f),
EmissionEnabled = true,
Emission = new Color(1f, 0.12f, 0.1f),
EmissionEnergyMultiplier = 2.2f,
ShadingMode = BaseMaterial3D.ShadingModeEnum.Unshaded,
Transparency = BaseMaterial3D.TransparencyEnum.Alpha
};
var laser = new MeshInstance3D
{
Mesh = new BoxMesh { Size = new Vector3(0.08f, 0.08f, 1.0f) },
MaterialOverride = laserMat,
Visible = false,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off
};
_actorsGroup.AddChild(laser);
return new ActorVisual
{
Visual = instance,
HaloMesh = halo,
HaloMat = haloMat,
LaserMesh = laser
HaloMat = haloMat
};
}
@ -1261,7 +1281,7 @@ public partial class ArenaRenderer : Node3D
lifetime: petalLife);
}
// Touchdown retro shockwave ring + brief detonation core
// Touchdown retro shockwave ring (fireball & radial dust handled by VolumetricEmitterPool + GpuSparksSystem)
Vector3 upRef = MathF.Abs(normal.Y) > 0.92f ? Vector3.Forward : Vector3.Up;
Vector3 right = upRef.Cross(normal).Normalized();
Vector3 fwd = normal.Cross(right).Normalized();
@ -1279,19 +1299,6 @@ public partial class ArenaRenderer : Node3D
Age = 0f,
Lifetime = isContender ? 0.42f : 0.30f
});
AddTransient(new TransientVfx
{
Shape = VfxShape.Sphere,
Position = pos + normal * 0.65f,
Velocity = normal * 1.8f,
BaseRotation = Basis.Identity,
StartScale = Vector3.One * (isContender ? 1.2f : 0.7f),
EndScale = Vector3.One * (isContender ? 4.4f : 2.6f),
ColorStart = new Color(3.8f, 2.2f, 0.65f, 0.90f),
ColorEnd = new Color(0.85f, 0.25f, 0.06f, 0.0f),
Age = 0f,
Lifetime = isContender ? 0.28f : 0.20f
});
}
}
@ -1304,90 +1311,69 @@ public partial class ArenaRenderer : Node3D
var t = tracers[i];
Vector3 start = new(t.StartX, t.StartY, t.StartZ);
Vector3 end = new(t.EndX, t.EndY, t.EndZ);
Vector3 delta = end - start;
float dist = delta.Length();
if (dist < 0.1f)
if (start.DistanceSquaredTo(end) < 0.01f)
{
continue;
}
Vector3 dir = delta / dist;
Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.95f ? Vector3.Right : Vector3.Up;
Basis lookBasis = Basis.LookingAt(dir, up);
Vector3 mid = (start + end) * 0.5f;
switch (t.WeaponClass)
{
case WeaponVisualClass.KineticLight:
{
bool isPd = string.Equals(t.WeaponId, "pd_flak", StringComparison.Ordinal);
Color col = isPd
? new Color(2.8f, 1.35f, 0.35f, 0.94f)
: new Color(2.6f, 2.35f, 1.15f, 0.92f);
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(isPd ? 0.09f : 0.06f, isPd ? 0.09f : 0.06f, dist), col);
? new Color(3.2f, 1.55f, 0.42f, 0.94f)
: new Color(3.0f, 2.55f, 1.25f, 0.92f);
SubmitCapsuleBeam(ref beamIdx, start, end, isPd ? 0.075f : 0.055f, col, coreSharpness: 3.0f, coreRadiusFrac: 0.36f, tailFade: 1.0f);
break;
}
case WeaponVisualClass.Autocannon:
{
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.20f, 0.20f, dist), new Color(2.5f, 0.85f, 0.14f, 0.72f));
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.08f, 0.08f, dist), new Color(3.6f, 2.7f, 1.3f, 0.98f));
SubmitCapsuleBeam(ref beamIdx, start, end, 0.14f, new Color(3.4f, 1.35f, 0.28f, 0.96f), coreSharpness: 2.8f, coreRadiusFrac: 0.36f, tailFade: 1.0f);
break;
}
case WeaponVisualClass.Explosive:
{
bool isRecoilless = string.Equals(t.WeaponId, "recoilless", StringComparison.Ordinal);
float w = isRecoilless ? 0.22f : 0.12f;
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(w, w, dist), new Color(3.2f, 1.25f, 0.25f, 0.96f));
SubmitCapsuleBeam(ref beamIdx, start, end, isRecoilless ? 0.17f : 0.10f, new Color(3.6f, 1.45f, 0.32f, 0.96f), coreSharpness: 2.6f, coreRadiusFrac: 0.34f, tailFade: 1.0f);
break;
}
case WeaponVisualClass.ThermalBeam:
{
bool isLance = string.Equals(t.WeaponId, "gilded_lance", StringComparison.Ordinal);
float outerW = isLance ? 0.34f : 0.20f;
float coreW = isLance ? 0.13f : 0.08f;
Color outerCol = isLance
? new Color(2.8f, 1.95f, 0.45f, 0.62f)
: new Color(0.45f, 2.35f, 2.95f, 0.65f);
Color coreCol = isLance
? new Color(1.6f, 3.6f, 3.8f, 0.98f)
: new Color(2.4f, 3.4f, 3.8f, 0.98f);
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(outerW, outerW, dist), outerCol);
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(coreW, coreW, dist), coreCol);
float outerR = isLance ? 0.24f : 0.15f;
Color beamCol = isLance
? new Color(3.4f, 2.35f, 0.55f, 0.96f)
: new Color(0.55f, 2.80f, 3.60f, 0.96f);
SubmitCapsuleBeam(ref beamIdx, start, end, outerR, beamCol, coreSharpness: 3.2f, coreRadiusFrac: 0.38f, tailFade: 0.0f, pulsePhase: 12f);
break;
}
case WeaponVisualClass.GaussRail:
{
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.30f, 0.30f, dist), new Color(0.25f, 1.85f, 3.4f, 0.68f));
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.10f, 0.10f, dist), new Color(2.2f, 3.6f, 4.0f, 0.98f));
SubmitCapsuleBeam(ref beamIdx, start, end, 0.22f, new Color(0.42f, 2.45f, 3.80f, 0.98f), coreSharpness: 3.6f, coreRadiusFrac: 0.34f, tailFade: 0.0f, pulsePhase: 18f);
break;
}
case WeaponVisualClass.PlasmaPpc:
{
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.36f, 0.36f, dist), new Color(0.18f, 2.25f, 2.65f, 0.65f));
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.14f, 0.14f, dist), new Color(1.2f, 3.5f, 3.8f, 0.98f));
SubmitCapsuleBeam(ref beamIdx, start, end, 0.25f, new Color(0.28f, 2.85f, 3.40f, 0.96f), coreSharpness: 2.6f, coreRadiusFrac: 0.40f, tailFade: 0.0f, pulsePhase: 14f);
break;
}
case WeaponVisualClass.RocketSalvo:
{
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.22f, 0.22f, dist), new Color(3.2f, 1.45f, 0.30f, 0.92f));
SubmitCapsuleBeam(ref beamIdx, start, end, 0.16f, new Color(3.6f, 1.65f, 0.38f, 0.94f), coreSharpness: 2.6f, coreRadiusFrac: 0.36f, tailFade: 1.0f);
break;
}
case WeaponVisualClass.SwarmSmart:
{
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.16f, 0.16f, dist), new Color(1.4f, 2.8f, 0.45f, 0.85f));
EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.07f, 0.07f, dist), new Color(2.0f, 0.95f, 3.2f, 0.96f));
SubmitCapsuleBeam(ref beamIdx, start, end, 0.12f, new Color(1.65f, 3.20f, 0.58f, 0.95f), coreSharpness: 2.8f, coreRadiusFrac: 0.36f, tailFade: 1.0f);
break;
}
}
}
for (int i = 0; i < _mirrorBeams.Count; i++)
{
var b = _mirrorBeams[i];
SubmitCapsuleBeam(ref beamIdx, b.Start, b.End, b.Radius, b.HdrTint, b.CoreSharpness, b.CoreRadiusFrac, b.TailFade);
}
_activeBeamCount = beamIdx;
_vfxBeamMm.VisibleInstanceCount = beamIdx;
_vfxBeamMmi.Visible = beamIdx > 0;
@ -1426,7 +1412,6 @@ public partial class ArenaRenderer : Node3D
normal = normal.Normalized();
bool isRecoilless = string.Equals(ev.WeaponId, "recoilless", StringComparison.Ordinal);
float detSize = isRecoilless || wClass == WeaponVisualClass.RocketSalvo ? 3.2f : 1.9f;
float ringSize = isRecoilless || wClass == WeaponVisualClass.RocketSalvo ? 6.2f : 3.4f;
Color coreStart = wClass switch
{
@ -1440,19 +1425,6 @@ public partial class ArenaRenderer : Node3D
WeaponVisualClass.SwarmSmart => new Color(0.55f, 0.25f, 0.85f, 0f),
_ => new Color(0.85f, 0.28f, 0.08f, 0f)
};
AddTransient(new TransientVfx
{
Shape = VfxShape.Sphere,
Position = pos + normal * 0.25f,
Velocity = normal * 1.4f,
BaseRotation = Basis.Identity,
StartScale = Vector3.One * 0.5f,
EndScale = Vector3.One * detSize,
ColorStart = coreStart,
ColorEnd = coreEnd,
Age = 0f,
Lifetime = isRecoilless ? 0.28f : 0.22f
});
Vector3 upRef = MathF.Abs(normal.Y) > 0.92f ? Vector3.Forward : Vector3.Up;
Vector3 right = upRef.Cross(normal).Normalized();
@ -1694,14 +1666,34 @@ public partial class ArenaRenderer : Node3D
return fallbackPos + new Vector3(0f, halfHeight * 0.7f, 0f);
}
private void EmitBeam(ref int beamIdx, Basis lookBasis, Vector3 mid, Vector3 scale, Color color)
private void SubmitCapsuleBeam(
ref int beamIdx,
Vector3 start,
Vector3 end,
float outerRadius,
Color hdrTint,
float coreSharpness,
float coreRadiusFrac,
float tailFade,
float pulsePhase = 0f)
{
if (beamIdx >= MaxVfxBeams)
{
return;
}
Vector3 delta = end - start;
float len = delta.Length();
Vector3 dir = len > 0.01f ? delta / len : Vector3.Forward;
Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.95f ? Vector3.Right : Vector3.Up;
Basis lookBasis = Basis.LookingAt(dir, up);
Vector3 mid = (start + end) * 0.5f;
float r = MathF.Max(0.01f, outerRadius);
Vector3 scale = new(2f * r, 2f * r, len + 2f * r);
_vfxBeamMm.SetInstanceTransform(beamIdx, new Transform3D(lookBasis * Basis.FromScale(scale), mid));
_vfxBeamMm.SetInstanceCustomData(beamIdx, color);
_vfxBeamMm.SetInstanceColor(beamIdx, hdrTint);
_vfxBeamMm.SetInstanceCustomData(beamIdx, new Color(coreSharpness, coreRadiusFrac, tailFade, pulsePhase));
beamIdx++;
}

View file

@ -90,12 +90,12 @@ public static class AtmosphereLutBaker
MieScattering: new Vector3(3.2e-6f, 3.2e-6f, 3.2e-6f),
MieG: 0.78f,
SolarIrradiance: 17.5f,
CalibratedSunEnergy: 1.28f,
CalibratedSunEnergy: 2.85f,
FogMaxLengthMeters: 460f,
VolumetricFogDensity: 0.0008f,
VolumetricFogDetailSpread: 2.4f,
VolumetricFogAnisotropy: 0.62f,
VolumetricFogEmissionEnergy: 0.18f,
VolumetricFogEmissionEnergy: 0f,
ValleyVolumeSize: new Vector3(3100f, 110f, 3100f),
ValleyVolumePosition: new Vector3(0f, 20f, 0f),
ValleyVolumeDensity: 0.0038f,
@ -108,7 +108,7 @@ public static class AtmosphereLutBaker
DepthFogAerialPerspective: 0.88f,
DepthFogSunScatter: 0.45f,
ShadowMaxDistance: 320f,
AmbientLightEnergy: 0.48f,
AmbientLightEnergy: 0.0f,
SunDiscIntensity: 8.5f,
MieAureoleStrength: 0.24f)
: new AtmospherePreset(
@ -120,12 +120,12 @@ public static class AtmosphereLutBaker
MieScattering: new Vector3(10.5e-6f, 8.8e-6f, 6.6e-6f),
MieG: 0.74f,
SolarIrradiance: 16.0f,
CalibratedSunEnergy: 1.42f,
CalibratedSunEnergy: 2.55f,
FogMaxLengthMeters: 380f,
VolumetricFogDensity: 0.0012f,
VolumetricFogDetailSpread: 2.2f,
VolumetricFogAnisotropy: 0.68f,
VolumetricFogEmissionEnergy: 0.22f,
VolumetricFogEmissionEnergy: 0f,
ValleyVolumeSize: new Vector3(1600f, 56f, 1600f),
ValleyVolumePosition: new Vector3(0f, 2f, 0f),
ValleyVolumeDensity: 0.0052f,
@ -138,7 +138,7 @@ public static class AtmosphereLutBaker
DepthFogAerialPerspective: 0.22f,
DepthFogSunScatter: 0.65f,
ShadowMaxDistance: 280f,
AmbientLightEnergy: 0.55f,
AmbientLightEnergy: 0.0f,
SunDiscIntensity: 8.0f,
MieAureoleStrength: 0.30f);

View file

@ -21,6 +21,11 @@ public partial class AtmosphereSystem : Node
private CanvasLayer _filmGrainLayer = null!;
private ColorRect _filmGrainRect = null!;
private ShaderMaterial _filmGrainMat = null!;
private Texture3Drd? _flowTexRd;
private ImageTexture3D? _dummyFlowTex;
private VolumetricCompositorEffect? _volumetricEffect;
private Compositor? _compositor;
private VolumetricEmitterPool _emitterPool = new();
private bool _initialized;
public WorldEnvironment WorldEnvironment => _worldEnv;
@ -29,6 +34,8 @@ public partial class AtmosphereSystem : Node
public FogVolume ValleyFogVolume => _valleyFog;
public CanvasLayer FilmGrainLayer => _filmGrainLayer;
public AtmosphereLutBaker.BakedAtmosphere? CurrentBaked { get; private set; }
public VolumetricCompositorEffect? VolumetricEffect => _volumetricEffect;
public VolumetricEmitterPool EmitterPool => _emitterPool;
public override void _Ready()
{
@ -58,14 +65,24 @@ public partial class AtmosphereSystem : Node
{
BackgroundMode = Godot.Environment.BGMode.Sky,
Sky = _sky,
AmbientLightSource = Godot.Environment.AmbientSource.Sky,
AmbientLightEnergy = 0.48f,
AmbientLightSource = Godot.Environment.AmbientSource.Disabled,
AmbientLightEnergy = 0.0f,
// Option 1 (Low-Gamma): SDFGI multi-bounce + occlusion with zero flat ambient
SdfgiEnabled = true,
SdfgiUseOcclusion = true,
SdfgiReadSkyLight = true,
SdfgiBounceFeedback = 0.60f,
SdfgiCascades = 3,
SdfgiMinCellSize = 0.8f,
SdfgiYScale = Godot.Environment.SdfgiyScale.Scale75Percent,
SdfgiEnergy = 0.85f,
// AgX tonemapping preserves orange/amber combat hues while rolling off HDR emitters smoothly
TonemapMode = Godot.Environment.ToneMapper.Agx,
TonemapAgxWhite = 6.0f,
TonemapAgxContrast = 1.22f,
TonemapExposure = 1.0f,
TonemapAgxContrast = 1.50f,
TonemapExposure = 0.84f,
// Normalized additive bloom strictly above GlowHdrThreshold=1.0 (zero diffuse screen smear)
GlowEnabled = true,
@ -100,7 +117,7 @@ public partial class AtmosphereSystem : Node
VolumetricFogEnabled = true,
VolumetricFogTemporalReprojectionEnabled = true,
VolumetricFogTemporalReprojectionAmount = 0.88f,
VolumetricFogAmbientInject = 0.25f,
VolumetricFogAmbientInject = 0.0f,
VolumetricFogSkyAffect = 0.10f,
// Tier 2: Far aerial perspective (340/400m .. horizon peaks)
@ -122,6 +139,38 @@ public partial class AtmosphereSystem : Node
Name = "WorldEnv",
Environment = _env
};
Vector3 defaultInvExtent = new(
1f / (VolumetricCompositorEffect.FlowDimX * VolumetricCompositorEffect.FlowVoxelSizeMeters),
1f / (VolumetricCompositorEffect.FlowDimY * VolumetricCompositorEffect.FlowVoxelSizeMeters),
1f / (VolumetricCompositorEffect.FlowDimZ * VolumetricCompositorEffect.FlowVoxelSizeMeters));
RegisterGlobalParamIfMissing("rtd_flow_origin", RenderingServer.GlobalShaderParameterType.Vec3, Vector3.Zero);
RegisterGlobalParamIfMissing("rtd_flow_inv_extent", RenderingServer.GlobalShaderParameterType.Vec3, defaultInvExtent);
if (RenderingServer.GetRenderingDevice() is not null)
{
RenderingServer.GISetUseHalfResolution(true);
RenderingServer.EnvironmentSetSdfgiRayCount(RenderingServer.EnvironmentSdfgiRayCount.Count4);
RenderingServer.EnvironmentSetSdfgiFramesToConverge(RenderingServer.EnvironmentSdfgiFramesToConverge.In10Frames);
RenderingServer.EnvironmentSetSdfgiFramesToUpdateLight(RenderingServer.EnvironmentSdfgiFramesToUpdateLight.In8Frames);
_flowTexRd = new Texture3Drd();
RegisterGlobalParamIfMissing("rtd_flow_field", RenderingServer.GlobalShaderParameterType.Sampler3D, _flowTexRd);
_volumetricEffect = new VolumetricCompositorEffect(_flowTexRd, _emitterPool);
_compositor = new Compositor
{
CompositorEffects = new Godot.Collections.Array<CompositorEffect> { _volumetricEffect }
};
_worldEnv.Compositor = _compositor;
}
else
{
var dummyImg = Image.CreateEmpty(1, 1, false, Image.Format.Rgbah);
dummyImg.SetPixel(0, 0, new Color(0f, 0f, 0f, 0f));
_dummyFlowTex = new ImageTexture3D();
_dummyFlowTex.Create(Image.Format.Rgbah, 1, 1, 1, false, new Godot.Collections.Array<Image> { dummyImg });
RegisterGlobalParamIfMissing("rtd_flow_field", RenderingServer.GlobalShaderParameterType.Sampler3D, _dummyFlowTex);
}
AddChild(_worldEnv);
_sun = new DirectionalLight3D
@ -161,6 +210,7 @@ public partial class AtmosphereSystem : Node
?? throw new InvalidOperationException("Failed to load res://film_grain.gdshader");
_filmGrainMat = new ShaderMaterial { Shader = grainShader };
_filmGrainMat.SetShaderParameter("grain_strength", 0.018f);
_filmGrainMat.SetShaderParameter("post_gamma", 1.32f);
_filmGrainLayer = new CanvasLayer
{
@ -214,9 +264,9 @@ public partial class AtmosphereSystem : Node
_env.VolumetricFogDensity = preset.VolumetricFogDensity;
_env.VolumetricFogDetailSpread = preset.VolumetricFogDetailSpread;
_env.VolumetricFogAnisotropy = preset.VolumetricFogAnisotropy;
_env.VolumetricFogEmissionEnergy = preset.VolumetricFogEmissionEnergy;
_env.VolumetricFogEmissionEnergy = 0f;
_env.VolumetricFogAlbedo = haze;
_env.VolumetricFogEmission = new Color(haze.R * 0.45f, haze.G * 0.45f, haze.B * 0.45f, 1.0f);
_env.VolumetricFogEmission = Colors.Black;
_valleyFog.Size = preset.ValleyVolumeSize;
_valleyFog.Position = preset.ValleyVolumePosition;
@ -224,7 +274,7 @@ public partial class AtmosphereSystem : Node
_valleyFogMat.HeightFalloff = preset.ValleyVolumeHeightFalloff;
_valleyFogMat.EdgeFade = preset.ValleyVolumeEdgeFade;
_valleyFogMat.Albedo = haze;
_valleyFogMat.Emission = new Color(haze.R * 0.35f, haze.G * 0.35f, haze.B * 0.35f, 1.0f);
_valleyFogMat.Emission = Colors.Black;
_env.FogLightColor = haze;
_env.FogDepthBegin = preset.DepthFogBegin;
@ -233,5 +283,106 @@ public partial class AtmosphereSystem : Node
_env.FogDensity = preset.DepthFogDensity;
_env.FogAerialPerspective = preset.DepthFogAerialPerspective;
_env.FogSunScatter = preset.DepthFogSunScatter;
if (_volumetricEffect is not null)
{
Color ambCol = new(
MathF.Max(0.10f, haze.R * 0.55f),
MathF.Max(0.12f, haze.G * 0.55f),
MathF.Max(0.14f, haze.B * 0.58f));
_volumetricEffect.SetAtmosphere(
baked.SunDirection,
baked.SunLightEnergy,
baked.SunLightColor,
ambCol,
extinctionScale: mapKind == ArenaMapKind.Sion ? 0.95f : 0.85f);
}
}
public void BindEmitterPool(VolumetricEmitterPool pool)
{
_emitterPool = pool ?? throw new ArgumentNullException(nameof(pool));
_volumetricEffect?.SetEmitterPool(pool);
}
public void ApplyGraphicsSettings(GraphicsSettings settings)
{
ArgumentNullException.ThrowIfNull(settings);
EnsureInitialized();
_volumetricEffect?.ApplyGraphicsSettings(settings);
SdfgiSettingsConfig sdfgi = GraphicsSettings.GetSdfgiConfig(settings.SdfgiQuality);
_env.SdfgiEnabled = sdfgi.Enabled;
if (sdfgi.Enabled)
{
_env.SdfgiMinCellSize = sdfgi.MinCellSize;
_env.SdfgiCascades = sdfgi.Cascades;
}
if (RenderingServer.GetRenderingDevice() is not null)
{
RenderingServer.GISetUseHalfResolution(sdfgi.HalfResolution);
RenderingServer.EnvironmentSetSdfgiRayCount(
sdfgi.RayCount >= 8
? RenderingServer.EnvironmentSdfgiRayCount.Count8
: RenderingServer.EnvironmentSdfgiRayCount.Count4);
}
}
public override void _ExitTree()
{
if (_worldEnv is not null && GodotObject.IsInstanceValid(_worldEnv))
{
_worldEnv.Compositor = null;
}
if (_flowTexRd is not null)
{
_flowTexRd.TextureRdRid = new Rid();
}
if (AreFlowGlobalsRegistered && RenderingServer.Singleton is not null)
{
_dummyFlowTex ??= CreateDummyFlowTexture();
RenderingServer.GlobalShaderParameterSet("rtd_flow_field", _dummyFlowTex);
}
if (_volumetricEffect is not null)
{
_volumetricEffect.Enabled = false;
if (RenderingServer.GetRenderingDevice() is not null)
{
RenderingServer.CallOnRenderThread(Callable.From(_volumetricEffect.DisposeRdResources));
RenderingServer.ForceSync();
}
}
}
private static ImageTexture3D CreateDummyFlowTexture()
{
var dummyImg = Image.CreateEmpty(1, 1, false, Image.Format.Rgbah);
dummyImg.SetPixel(0, 0, new Color(0f, 0f, 0f, 0f));
var tex = new ImageTexture3D();
tex.Create(Image.Format.Rgbah, 1, 1, 1, false, new Godot.Collections.Array<Image> { dummyImg });
return tex;
}
private static readonly System.Collections.Generic.HashSet<string> RegisteredGlobals = new();
public static bool AreFlowGlobalsRegistered =>
RegisteredGlobals.Contains("rtd_flow_field") &&
RegisteredGlobals.Contains("rtd_flow_origin") &&
RegisteredGlobals.Contains("rtd_flow_inv_extent");
private static void RegisterGlobalParamIfMissing(
StringName name,
RenderingServer.GlobalShaderParameterType type,
Variant defaultValue)
{
string key = name.ToString();
if (RegisteredGlobals.Contains(key))
{
RenderingServer.GlobalShaderParameterSet(name, defaultValue);
return;
}
RegisteredGlobals.Add(key);
RenderingServer.GlobalShaderParameterAdd(name, type, defaultValue);
}
}

View file

@ -17,11 +17,15 @@ namespace RustToDust.Client;
public sealed class CameraJuiceState
{
public const float BaseFovDeg = 58.0f;
public const float DropFreefallFovDeg = 82.0f;
public const float DropRetroFovDeg = 76.0f;
private const float ZeroEpsilon = 1e-4f;
private const float TraumaDecayPerSec = 1.95f;
private const float RecoilDecayRate = 14.0f;
private const float FootstepDecayRate = 16.0f;
private const float FovBlendRate = 6.0f;
private const float DropFovBlendInRate = 5.0f;
private const float DropFovBlendOutRate = 3.8f;
private float _time;
@ -236,7 +240,7 @@ public sealed class CameraJuiceState
}
}
public void Update(float dt, float localSpeedMps, bool isVtol)
public void Update(float dt, float localSpeedMps, bool isVtol, bool isInDropPod = false, OrbitalPodPhase podPhase = OrbitalPodPhase.Freefall)
{
float stepDt = float.IsFinite(dt) && dt > 0f ? Math.Clamp(dt, 0f, 0.1f) : 0f;
if (stepDt > 0f)
@ -258,15 +262,28 @@ public sealed class CameraJuiceState
}
float speed = float.IsFinite(localSpeedMps) ? MathF.Max(0f, localSpeedMps) : 0f;
float speedStart = isVtol ? 14f : 12f;
float speedFull = isVtol ? 46f : 36f;
float targetFovOffset = speed > speedStart
? Math.Clamp((speed - speedStart) / (speedFull - speedStart), 0f, 1f) * (isVtol ? 4.8f : 3.4f)
: 0f;
float targetFovOffset;
float blendRate;
if (isInDropPod)
{
targetFovOffset = podPhase == OrbitalPodPhase.RetroBurn
? (DropRetroFovDeg - BaseFovDeg)
: (DropFreefallFovDeg - BaseFovDeg) + Math.Clamp(speed / 62f, 0f, 2.0f);
blendRate = DropFovBlendInRate;
}
else
{
float speedStart = isVtol ? 14f : 12f;
float speedFull = isVtol ? 46f : 36f;
targetFovOffset = speed > speedStart
? Math.Clamp((speed - speedStart) / (speedFull - speedStart), 0f, 1f) * (isVtol ? 4.8f : 3.4f)
: 0f;
blendRate = FovOffsetDeg > targetFovOffset + 0.5f ? DropFovBlendOutRate : FovBlendRate;
}
if (stepDt > 0f)
{
float blend = 1f - MathF.Exp(-FovBlendRate * stepDt);
float blend = 1f - MathF.Exp(-blendRate * stepDt);
FovOffsetDeg += (targetFovOffset - FovOffsetDeg) * blend;
if (MathF.Abs(FovOffsetDeg) < 0.002f && targetFovOffset == 0f)
{

42
client/ClientAssets.cs Normal file
View file

@ -0,0 +1,42 @@
using System;
using System.IO;
using Godot;
using RustToDust.Core;
namespace RustToDust.Client;
internal static class ClientAssets
{
private static bool _registered;
internal static void EnsureAssetsRootRegistered()
{
if (_registered)
{
return;
}
_registered = true;
if (OS.HasFeature("template"))
{
string exeAssets = Path.Combine(OS.GetExecutablePath().GetBaseDir(), "assets");
if (Directory.Exists(exeAssets))
{
AssetPathResolver.RegisterAssetsRoot(exeAssets);
return;
}
}
string baseAssets = Path.Combine(AppContext.BaseDirectory, "assets");
if (Directory.Exists(baseAssets))
{
AssetPathResolver.RegisterAssetsRoot(baseAssets);
}
}
internal static string LocateAssetsDirectory()
{
EnsureAssetsRootRegistered();
return AssetPathResolver.LocateAssetsRoot();
}
}

View file

@ -27,6 +27,15 @@ public sealed class ClientOrdnanceMirror
Color ColorEnd,
float Lifetime);
public readonly record struct ActiveBeamSpec(
Vector3 Start,
Vector3 End,
float Radius,
Color HdrTint,
float CoreSharpness,
float CoreRadiusFrac,
float TailFade);
private struct MirroredSlot
{
public bool Active;
@ -39,6 +48,7 @@ public sealed class ClientOrdnanceMirror
public Color Color;
public float ManufacturerRoleIndex;
public Vector3 Pos;
public Vector3 TailPos;
public Vector3 Vel;
public Vector3 AnchorPos;
public int TargetEntityId;
@ -82,6 +92,7 @@ public sealed class ClientOrdnanceMirror
VehicleAssetCache cache,
DebrisSystem debris,
ParticlePool particles,
VolumetricEmitterPool volumetrics,
bool hasCam,
Vector3 camPos,
Action<TransientVfxSpec> emitTransient)
@ -186,16 +197,10 @@ public sealed class ClientOrdnanceMirror
RemoveById(ev.OrdnanceId);
float splashR = def is not null && def.SplashRadius > 0.5f ? def.SplashRadius : 4.2f;
particles.EmitOrdnanceBurst(pos, col, sparkCount: 6, radiusScale: Math.Clamp(splashR / 4.5f, 0.7f, 1.6f), camPos, hasCam);
emitTransient(new TransientVfxSpec(
IsSphere: true,
Position: pos + Vector3.Up * 0.2f,
Velocity: Vector3.Up * 1.2f,
Rotation: Basis.Identity,
StartScale: Vector3.One * 0.55f,
EndScale: Vector3.One * Math.Clamp(splashR * 0.75f, 1.8f, 4.8f),
ColorStart: new Color(col.R * 3.2f, col.G * 3.2f, col.B * 3.2f, 0.92f),
ColorEnd: new Color(col.R * 0.8f, col.G * 0.3f, col.B * 0.2f, 0f),
Lifetime: 0.26f));
if (!hasCam || pos.DistanceSquaredTo(camPos) <= 280f * 280f)
{
volumetrics.EmitOrdnanceDetonation(pos, col, splashR);
}
emitTransient(new TransientVfxSpec(
IsSphere: false,
Position: pos + Vector3.Up * 0.16f,
@ -227,11 +232,12 @@ public sealed class ClientOrdnanceMirror
VehicleAssetCache cache,
MultiMeshPartPool partPool,
ParticlePool particles,
VolumetricEmitterPool volumetrics,
TerrainField terrain,
bool hasCam,
Vector3 camPos,
Action<Transform3D, Color> submitActiveRing,
Action<Transform3D, Color> submitActiveSphere)
Action<ActiveBeamSpec> submitActiveBeam)
{
if (_activeCount == 0)
{
@ -273,6 +279,8 @@ public sealed class ClientOrdnanceMirror
}
AdvanceSlotKinematics(ref s, def, state, terrain, stepDt);
float tailLerp = 1f - MathF.Exp(-stepDt * 18f);
s.TailPos = s.TailPos.Lerp(s.Pos, tailLerp);
}
if (hasCam && s.Pos.DistanceSquaredTo(camPos) > 340f * 340f)
@ -293,9 +301,6 @@ public sealed class ClientOrdnanceMirror
Transform3D ringXf = new(Basis.FromScale(new Vector3(radius * 2f * pulse, 0.35f, radius * 2f * pulse)), poolPos);
submitActiveRing(ringXf, new Color(s.Color.R * 2.6f, s.Color.G * 2.6f, s.Color.B * 2.6f, 0.78f));
Transform3D discXf = new(Basis.FromScale(new Vector3(radius * 1.4f * pulse, 0.14f, radius * 1.4f * pulse)), poolPos - new Vector3(0f, 0.04f, 0f));
submitActiveSphere(discXf, new Color(s.Color.R * 2.1f, s.Color.G * 2.1f, s.Color.B * 2.1f, 0.42f));
if (stepDt > 0f)
{
s.EmberTimer += stepDt;
@ -303,6 +308,10 @@ public sealed class ClientOrdnanceMirror
{
s.EmberTimer = 0f;
particles.EmitThermalPoolEmber(poolPos, radius, s.Color, camPos, hasCam);
if (!hasCam || poolPos.DistanceSquaredTo(camPos) <= 220f * 220f)
{
volumetrics.EmitThermalPoolPlume(poolPos, radius, s.Color);
}
}
}
continue;
@ -349,10 +358,13 @@ public sealed class ClientOrdnanceMirror
if (stepDt > 0f)
{
s.TrailTimer += stepDt;
if (s.TrailTimer >= 0.055f)
if (s.TrailTimer >= 0.075f)
{
s.TrailTimer = 0f;
particles.EmitOrdnanceTrail(s.Pos, s.Vel, s.Color, isRocket: def?.Motion != OrdnanceMotion.LoiterOrbit, camPos, hasCam);
if (!hasCam || s.Pos.DistanceSquaredTo(camPos) <= 240f * 240f)
{
volumetrics.EmitOrdnanceTrailCapsule(s.TailPos, s.Pos, s.Vel, s.Color, isRocket: def?.Motion != OrdnanceMotion.LoiterOrbit);
}
}
}
continue;
@ -382,19 +394,30 @@ public sealed class ClientOrdnanceMirror
def?.Motion is OrdnanceMotion.RocketBoosted or OrdnanceMotion.HomingMissile;
partPool.Submit(projMesh, in projXf, new Color(0f, isRocket ? 0.65f : 0.25f, s.ManufacturerRoleIndex, 1f), wantsShadow: false);
if (isRocket)
{
Transform3D thrusterXf = new(Basis.FromScale(Vector3.One * 0.42f), s.Pos - dir * 0.22f);
submitActiveSphere(thrusterXf, new Color(s.Color.R * 3.2f, s.Color.G * 3.2f, s.Color.B * 3.2f, 0.90f));
}
// Connected [TailPos, Pos] volumetric capsule streak
Vector3 tailStart = s.Pos.DistanceSquaredTo(s.TailPos) > 0.04f ? s.TailPos : s.Pos - dir * 1.4f;
Color beamCol = isRocket
? new Color(s.Color.R * 3.4f, s.Color.G * 2.4f, s.Color.B * 1.4f, 0.94f)
: new Color(s.Color.R * 3.0f, s.Color.G * 3.0f, s.Color.B * 3.0f, 0.92f);
submitActiveBeam(new ActiveBeamSpec(
Start: tailStart,
End: s.Pos - dir * 0.16f,
Radius: isRocket ? 0.24f : 0.15f,
HdrTint: beamCol,
CoreSharpness: 2.8f,
CoreRadiusFrac: 0.36f,
TailFade: 1.0f));
if (stepDt > 0f)
{
s.TrailTimer += stepDt;
if (s.TrailTimer >= (isRocket ? 0.035f : 0.055f))
if (s.TrailTimer >= (isRocket ? 0.055f : 0.075f))
{
s.TrailTimer = 0f;
particles.EmitOrdnanceTrail(s.Pos - dir * 0.18f, s.Vel, s.Color, isRocket, camPos, hasCam);
if (!hasCam || s.Pos.DistanceSquaredTo(camPos) <= 240f * 240f)
{
volumetrics.EmitOrdnanceTrailCapsule(s.TailPos, s.Pos - dir * 0.18f, s.Vel, s.Color, isRocket);
}
}
}
}
@ -565,6 +588,7 @@ public sealed class ClientOrdnanceMirror
Color = col,
ManufacturerRoleIndex = mfgRole,
Pos = pos,
TailPos = pos,
Vel = vel,
AnchorPos = pos,
TargetEntityId = ev.TargetEntityId,

698
client/FoliageRenderer.cs Normal file
View file

@ -0,0 +1,698 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using Godot;
using RustToDust.Core;
namespace RustToDust.Client;
/// <summary>
/// GPU-instanced MultiMesh + 6x6 octahedral impostor renderer for real Sion trees
/// baked via vendored cosmo_tree_gen (MIT) with hierarchical COLOR.rgba wind weights
/// bound to global <c>rtd_flow_field</c>.
/// </summary>
public partial class FoliageRenderer : Node3D
{
public const float Lod0MaxDistanceM = 28f;
public const float Lod1MaxDistanceM = 76f;
public const float Lod2MaxDistanceM = 230f;
public const float ImpostorMaxDistanceM = 1450f;
public const float StumpMaxDistanceM = 230f;
private const float RebuildMoveThresholdSq = 8.0f * 8.0f;
private const float RebuildTurnCosThreshold = 0.866f; // ~30 degrees
private const float FrustumCullMinDistSq = 48.0f * 48.0f;
private const float FrustumRearConeCosSq = 0.35f * 0.35f; // cull rear ~139 deg cone behind camera
private sealed class TreeArchetype
{
public int SpeciesId;
public int Variant;
public string Slug = string.Empty;
public float CanonicalHeightM;
public float ImpostorScale;
public float ImpostorOffsetY;
public int ImpostorFrames = 6;
public ArrayMesh Lod0 = null!;
public ArrayMesh Lod1 = null!;
public ArrayMesh Lod2 = null!;
public ArrayMesh SnappedStump = null!;
public ArrayMesh CharredSkeleton = null!;
public QuadMesh ImpostorQuad = null!;
public BucketState BucketLod0 = null!;
public BucketState? BucketLod1;
public BucketState? BucketLod2;
public BucketState? BucketImpostor;
public BucketState? BucketStump;
public BucketState? BucketCharred;
public int CanonicalArchIdx;
}
private sealed class BucketState
{
public MultiMesh MultiMesh = null!;
public MultiMeshInstance3D Instance = null!;
public readonly List<int> Indices = new(128);
}
private struct PrecomputedTree
{
public int ArchetypeIdx;
public Transform3D WorldXform;
public Transform3D WorldXformCanon;
public Vector3 Position;
public Color CustomDataBase; // (0, phase, height, 1)
}
private readonly List<TreeArchetype> _archetypes = new(17);
private readonly int[,] _archetypeLookup = new int[10, 2];
private readonly Dictionary<string, Texture2D> _textureCache = new(StringComparer.OrdinalIgnoreCase);
private Shader _leavesShader = null!;
private Shader _barkShader = null!;
private Shader _impostorShader = null!;
private SionTreeCatalog? _boundCatalog;
private PrecomputedTree[] _precomputed = Array.Empty<PrecomputedTree>();
private int _lastRenderVersion = -1;
private Vector3 _lastCamPos = new(float.NaN, float.NaN, float.NaN);
private Vector2 _lastCamFwdXz = new(0f, 1f);
private bool _lastCamConeActive;
private bool _assetsLoaded;
private bool _assetsLoadAttempted;
public bool IsBuilt => _assetsLoaded && _boundCatalog is not null;
public int ArchetypeCount => _archetypes.Count;
public int TotalTreeCount => _boundCatalog?.Count ?? 0;
public int VisibleLod0Count { get; private set; }
public int VisibleLod1Count { get; private set; }
public int VisibleLod2Count { get; private set; }
public int VisibleImpostorCount { get; private set; }
public int VisibleStumpCount { get; private set; }
public int VisibleCharredCount { get; private set; }
public override void _Ready()
{
for (int s = 0; s < 10; s++)
{
for (int v = 0; v < 2; v++)
{
_archetypeLookup[s, v] = -1;
}
}
}
public void Invalidate()
{
_lastRenderVersion = -1;
_lastCamPos = new Vector3(float.NaN, float.NaN, float.NaN);
_lastCamFwdXz = new Vector2(0f, 1f);
_lastCamConeActive = false;
}
public bool VerifyAllLodsHaveVertexColor(out string error)
{
foreach (var arch in _archetypes)
{
ArrayMesh[] lods = { arch.Lod0, arch.Lod1, arch.Lod2 };
for (int l = 0; l < lods.Length; l++)
{
var mesh = lods[l];
if (mesh is null || mesh.GetSurfaceCount() == 0)
{
error = $"{arch.Slug} LOD{l} missing mesh surfaces";
return false;
}
for (int s = 0; s < mesh.GetSurfaceCount(); s++)
{
var arr = mesh.SurfaceGetArrays(s);
if (arr.Count <= (int)Mesh.ArrayType.Color ||
arr[(int)Mesh.ArrayType.Color].VariantType != Variant.Type.PackedColorArray)
{
error = $"{arch.Slug} LOD{l} surface {s} missing ARRAY_COLOR";
return false;
}
var colors = arr[(int)Mesh.ArrayType.Color].AsColorArray();
bool hasFlexGrad = false;
for (int k = 0; k < colors.Length; k++)
{
if (colors[k].G > 0.05f)
{
hasFlexGrad = true;
break;
}
}
if (!hasFlexGrad)
{
error = $"{arch.Slug} LOD{l} surface {s} has zero wind flex gradient in COLOR.G";
return false;
}
}
}
}
error = string.Empty;
return _archetypes.Count == 17;
}
public void Sync(MatchState state, Vector3 camPos)
{
if (state.MapKind != ArenaMapKind.Sion || state.SionMap is null || state.SionMap.Trees.Count == 0)
{
Visible = false;
return;
}
SyncInternal(state.SionMap, state.SionTrees, camPos);
}
public void SyncBackdrop(SionMapData sionMap, Vector3 camPos)
{
if (sionMap.Trees.Count == 0)
{
Visible = false;
return;
}
SyncInternal(sionMap, null, camPos);
}
private void SyncInternal(SionMapData sionMap, SionTreeDestructionState? destruction, Vector3 camPos)
{
Visible = true;
EnsureAssetsLoaded(sionMap.DirectoryPath);
if (!_assetsLoaded)
{
return;
}
var catalog = sionMap.Trees;
if (!ReferenceEquals(_boundCatalog, catalog))
{
BindCatalog(catalog);
}
int curVer = destruction?.RenderVersion ?? 0;
Vector2 camFwdXz = new(0f, 1f);
bool useCamCone = false;
var cam = GetViewport()?.GetCamera3D();
if (cam is not null)
{
Vector3 fwd = -cam.GlobalTransform.Basis.Z;
if (MathF.Abs(fwd.Y) <= 0.50f)
{
float lenSq = fwd.X * fwd.X + fwd.Z * fwd.Z;
if (lenSq > 1e-4f)
{
float inv = 1f / MathF.Sqrt(lenSq);
camFwdXz = new Vector2(fwd.X * inv, fwd.Z * inv);
useCamCone = true;
}
}
}
bool movedFar = !_lastCamPos.IsFinite() || _lastCamPos.DistanceSquaredTo(camPos) >= RebuildMoveThresholdSq;
bool coneToggled = useCamCone != _lastCamConeActive;
bool turnedFar = useCamCone && (_lastCamFwdXz.X * camFwdXz.X + _lastCamFwdXz.Y * camFwdXz.Y) < RebuildTurnCosThreshold;
if (!movedFar && !coneToggled && !turnedFar && curVer == _lastRenderVersion)
{
return;
}
_lastCamPos = camPos;
_lastCamConeActive = useCamCone;
if (useCamCone)
{
_lastCamFwdXz = camFwdXz;
}
_lastRenderVersion = curVer;
RebuildBuckets(destruction, camPos, useCamCone ? camFwdXz : null);
}
private void EnsureAssetsLoaded(string sionDir)
{
if (_assetsLoadAttempted)
{
return;
}
_assetsLoadAttempted = true;
string treesDir = Path.Combine(sionDir, "trees");
string catalogPath = Path.Combine(treesDir, "trees_catalog.json");
if (!File.Exists(catalogPath))
{
GD.PrintErr($"FoliageRenderer: missing tree catalog at '{catalogPath}'.");
return;
}
_leavesShader = GD.Load<Shader>("res://tree_leaves.gdshader")
?? throw new InvalidOperationException("Missing res://tree_leaves.gdshader");
_barkShader = GD.Load<Shader>("res://tree_bark.gdshader")
?? throw new InvalidOperationException("Missing res://tree_bark.gdshader");
_impostorShader = GD.Load<Shader>("res://tree_impostor.gdshader")
?? throw new InvalidOperationException("Missing res://tree_impostor.gdshader");
using var stream = File.OpenRead(catalogPath);
using var doc = JsonDocument.Parse(stream);
var arr = doc.RootElement.GetProperty("archetypes");
foreach (var item in arr.EnumerateArray())
{
int speciesId = item.GetProperty("speciesId").GetInt32();
int variant = item.GetProperty("variant").GetInt32();
string slug = item.GetProperty("slug").GetString() ?? "";
string glbRel = item.GetProperty("glb").GetString() ?? "";
string leafRel = item.GetProperty("leafTexture").GetString() ?? "";
string barkRel = item.GetProperty("barkTexture").GetString() ?? "";
string impAlbRel = item.GetProperty("impostorAlbedo").GetString() ?? "";
string impNrmRel = item.GetProperty("impostorNormal").GetString() ?? "";
float canonH = item.GetProperty("canonicalHeightM").GetSingle();
float impScale = item.GetProperty("impostorScale").GetSingle();
float impOffsetY = item.GetProperty("impostorOffsetY").GetSingle();
int impFrames = item.GetProperty("impostorFrames").GetInt32();
Color barkTint = ReadColor3(item.GetProperty("barkTint"));
Color leafTint = ReadColor3(item.GetProperty("leafTint"));
var meshes = LoadArchetypeMeshes(Path.Combine(treesDir, glbRel));
if (meshes is null)
{
continue;
}
Texture2D barkTex = LoadTextureCached(Path.Combine(treesDir, barkRel));
Texture2D leafTex = LoadTextureCached(Path.Combine(treesDir, leafRel));
var barkMat = new ShaderMaterial { Shader = _barkShader };
barkMat.SetShaderParameter("albedo", barkTint);
barkMat.SetShaderParameter("albedo_texture", barkTex);
var leafMat = new ShaderMaterial { Shader = _leavesShader };
leafMat.SetShaderParameter("albedo", leafTint);
leafMat.SetShaderParameter("albedo_texture", leafTex);
ApplyTreeMaterials(meshes.Value.Lod0, barkMat, leafMat);
ApplyTreeMaterials(meshes.Value.Lod1, barkMat, leafMat);
ApplyTreeMaterials(meshes.Value.Lod2, barkMat, leafMat);
ApplyTreeMaterials(meshes.Value.SnappedStump, barkMat, leafMat);
ApplyTreeMaterials(meshes.Value.CharredSkeleton, barkMat, leafMat);
var impMat = new ShaderMaterial { Shader = _impostorShader };
string impAlbPath = Path.Combine(treesDir, impAlbRel);
string impNrmPath = Path.Combine(treesDir, impNrmRel);
if (File.Exists(impAlbPath) && File.Exists(impNrmPath))
{
impMat.SetShaderParameter("albedo_texture", LoadTextureCached(impAlbPath));
impMat.SetShaderParameter("normal_texture", LoadTextureCached(impNrmPath));
}
impMat.SetShaderParameter("impostor_frames", new Vector2(impFrames, impFrames));
impMat.SetShaderParameter("scale", impScale);
impMat.SetShaderParameter("position_offset", new Vector3(0f, impOffsetY, 0f));
var impQuad = new QuadMesh { Size = Vector2.One, Material = impMat };
var arch = new TreeArchetype
{
SpeciesId = speciesId,
Variant = variant,
Slug = slug,
CanonicalHeightM = MathF.Max(1f, canonH),
ImpostorScale = impScale,
ImpostorOffsetY = impOffsetY,
ImpostorFrames = impFrames,
Lod0 = meshes.Value.Lod0,
Lod1 = meshes.Value.Lod1,
Lod2 = meshes.Value.Lod2,
SnappedStump = meshes.Value.SnappedStump,
CharredSkeleton = meshes.Value.CharredSkeleton,
ImpostorQuad = impQuad
};
arch.BucketLod0 = CreateBucket($"{slug}_LOD0", arch.Lod0, castShadows: true, visibilityEndM: Lod0MaxDistanceM + 8f);
if (variant == 0)
{
arch.BucketLod1 = CreateBucket($"{slug}_LOD1", arch.Lod1, castShadows: true, visibilityEndM: Lod1MaxDistanceM + 10f);
arch.BucketLod2 = CreateBucket($"{slug}_LOD2", arch.Lod2, castShadows: false, visibilityEndM: Lod2MaxDistanceM + 12f);
arch.BucketImpostor = CreateBucket($"{slug}_Impostor", arch.ImpostorQuad, castShadows: false, visibilityEndM: ImpostorMaxDistanceM + 20f);
arch.BucketStump = CreateBucket($"{slug}_Stump", arch.SnappedStump, castShadows: false, visibilityEndM: StumpMaxDistanceM + 10f);
arch.BucketCharred = CreateBucket($"{slug}_Charred", arch.CharredSkeleton, castShadows: true, visibilityEndM: Lod2MaxDistanceM + 12f);
}
int idx = _archetypes.Count;
_archetypes.Add(arch);
if ((uint)speciesId < 10 && (uint)variant < 2)
{
_archetypeLookup[speciesId, variant] = idx;
}
}
for (int a = 0; a < _archetypes.Count; a++)
{
var arch = _archetypes[a];
int canon = _archetypeLookup[Math.Clamp(arch.SpeciesId, 0, 9), 0];
arch.CanonicalArchIdx = canon >= 0 ? canon : a;
}
_assetsLoaded = _archetypes.Count > 0;
}
private BucketState CreateBucket(string name, Mesh mesh, bool castShadows, float visibilityEndM)
{
var mm = new MultiMesh
{
TransformFormat = MultiMesh.TransformFormatEnum.Transform3D,
UseColors = false,
UseCustomData = true,
Mesh = mesh,
InstanceCount = 0,
VisibleInstanceCount = 0
};
var mmi = new MultiMeshInstance3D
{
Name = name,
Multimesh = mm,
CastShadow = castShadows
? GeometryInstance3D.ShadowCastingSetting.On
: GeometryInstance3D.ShadowCastingSetting.Off,
VisibilityRangeEnd = visibilityEndM,
VisibilityRangeFadeMode = GeometryInstance3D.VisibilityRangeFadeModeEnum.Disabled,
CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)),
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off,
Visible = false
};
AddChild(mmi);
return new BucketState { MultiMesh = mm, Instance = mmi };
}
private void BindCatalog(SionTreeCatalog catalog)
{
_boundCatalog = catalog;
var trees = catalog.Trees;
_precomputed = new PrecomputedTree[trees.Count];
for (int i = 0; i < trees.Count; i++)
{
var t = trees[i];
int sp = Math.Clamp((int)t.Species, 0, 9);
int vr = Math.Clamp((int)t.Variant, 0, 1);
int archIdx = _archetypeLookup[sp, vr];
if (archIdx < 0)
{
archIdx = _archetypeLookup[sp, 0];
}
if (archIdx < 0)
{
archIdx = 0;
}
var arch = _archetypes[archIdx];
var canonArch = _archetypes[arch.CanonicalArchIdx];
Basis yawBasis = Basis.FromEuler(new Vector3(0f, t.Yaw, 0f));
float scaleY = Math.Clamp(t.HeightM / arch.CanonicalHeightM, 0.35f, 2.2f);
float canonScaleY = Math.Clamp(t.HeightM / canonArch.CanonicalHeightM, 0.35f, 2.2f);
Basis rot = yawBasis.Scaled(new Vector3(scaleY, scaleY, scaleY));
Basis canonRot = ReferenceEquals(arch, canonArch)
? rot
: yawBasis.Scaled(new Vector3(canonScaleY, canonScaleY, canonScaleY));
Vector3 pos = new(t.X, t.Y, t.Z);
float phase = ((t.TreeId * 0x9E3779B9u) & 0xFFFFu) / 65536f;
_precomputed[i] = new PrecomputedTree
{
ArchetypeIdx = archIdx,
WorldXform = new Transform3D(rot, pos),
WorldXformCanon = new Transform3D(canonRot, pos),
Position = pos,
CustomDataBase = new Color(0f, phase, t.HeightM, 1f)
};
}
Invalidate();
}
private void RebuildBuckets(SionTreeDestructionState? destruction, Vector3 camPos, Vector2? camFwdXz)
{
for (int a = 0; a < _archetypes.Count; a++)
{
var arch = _archetypes[a];
arch.BucketLod0.Indices.Clear();
arch.BucketLod1?.Indices.Clear();
arch.BucketLod2?.Indices.Clear();
arch.BucketImpostor?.Indices.Clear();
arch.BucketStump?.Indices.Clear();
arch.BucketCharred?.Indices.Clear();
}
const float lod0Sq = Lod0MaxDistanceM * Lod0MaxDistanceM;
const float lod1Sq = Lod1MaxDistanceM * Lod1MaxDistanceM;
const float lod2Sq = Lod2MaxDistanceM * Lod2MaxDistanceM;
const float impSq = ImpostorMaxDistanceM * ImpostorMaxDistanceM;
const float stumpSq = StumpMaxDistanceM * StumpMaxDistanceM;
bool cullCone = camFwdXz.HasValue;
Vector2 fwd = camFwdXz ?? default;
for (int i = 0; i < _precomputed.Length; i++)
{
ref readonly var pt = ref _precomputed[i];
float dx = pt.Position.X - camPos.X;
float dz = pt.Position.Z - camPos.Z;
float dSq = dx * dx + dz * dz;
if (dSq > impSq)
{
continue;
}
if (cullCone && dSq > FrustumCullMinDistSq)
{
float dot = dx * fwd.X + dz * fwd.Y;
if (dot < 0f && dot * dot > FrustumRearConeCosSq * dSq)
{
continue;
}
}
SionTreeState st = destruction is not null
? destruction.GetState((ushort)i)
: SionTreeState.Intact;
var arch = _archetypes[pt.ArchetypeIdx];
var canonArch = _archetypes[arch.CanonicalArchIdx];
if (st == SionTreeState.Snapped)
{
if (dSq <= stumpSq && canonArch.BucketStump is not null)
{
canonArch.BucketStump.Indices.Add(i);
}
}
else if (st == SionTreeState.Charred)
{
if (dSq <= lod2Sq && canonArch.BucketCharred is not null)
{
canonArch.BucketCharred.Indices.Add(i);
}
else if (canonArch.BucketImpostor is not null)
{
canonArch.BucketImpostor.Indices.Add(i);
}
}
else
{
if (dSq <= lod0Sq)
{
arch.BucketLod0.Indices.Add(i);
}
else if (dSq <= lod1Sq && canonArch.BucketLod1 is not null)
{
canonArch.BucketLod1.Indices.Add(i);
}
else if (dSq <= lod2Sq && canonArch.BucketLod2 is not null)
{
canonArch.BucketLod2.Indices.Add(i);
}
else if (canonArch.BucketImpostor is not null)
{
canonArch.BucketImpostor.Indices.Add(i);
}
}
}
int c0 = 0, c1 = 0, c2 = 0, cImp = 0, cStump = 0, cChar = 0;
for (int a = 0; a < _archetypes.Count; a++)
{
var arch = _archetypes[a];
c0 += CommitBucket(arch.BucketLod0, destruction, forceCharred: false, useCanonXform: false);
if (arch.BucketLod1 is not null) c1 += CommitBucket(arch.BucketLod1, destruction, forceCharred: false, useCanonXform: true);
if (arch.BucketLod2 is not null) c2 += CommitBucket(arch.BucketLod2, destruction, forceCharred: false, useCanonXform: true);
if (arch.BucketImpostor is not null) cImp += CommitBucket(arch.BucketImpostor, destruction, forceCharred: false, useCanonXform: true);
if (arch.BucketStump is not null) cStump += CommitBucket(arch.BucketStump, destruction, forceCharred: false, useCanonXform: true);
if (arch.BucketCharred is not null) cChar += CommitBucket(arch.BucketCharred, destruction, forceCharred: true, useCanonXform: true);
}
VisibleLod0Count = c0;
VisibleLod1Count = c1;
VisibleLod2Count = c2;
VisibleImpostorCount = cImp;
VisibleStumpCount = cStump;
VisibleCharredCount = cChar;
}
private int CommitBucket(BucketState bucket, SionTreeDestructionState? destruction, bool forceCharred, bool useCanonXform)
{
int count = bucket.Indices.Count;
if (count == 0)
{
bucket.MultiMesh.VisibleInstanceCount = 0;
bucket.Instance.Visible = false;
return 0;
}
if (bucket.MultiMesh.InstanceCount < count)
{
int cap = Math.Max(16, (int)BitOperationsRoundUp((uint)count));
bucket.MultiMesh.InstanceCount = cap;
}
bucket.MultiMesh.VisibleInstanceCount = count;
bucket.Instance.Visible = true;
float minX = float.PositiveInfinity, minY = float.PositiveInfinity, minZ = float.PositiveInfinity;
float maxX = float.NegativeInfinity, maxY = float.NegativeInfinity, maxZ = float.NegativeInfinity;
for (int k = 0; k < count; k++)
{
int treeIdx = bucket.Indices[k];
ref readonly var pt = ref _precomputed[treeIdx];
bucket.MultiMesh.SetInstanceTransform(k, useCanonXform ? pt.WorldXformCanon : pt.WorldXform);
Vector3 p = pt.Position;
if (p.X < minX) minX = p.X;
if (p.Y < minY) minY = p.Y;
if (p.Z < minZ) minZ = p.Z;
if (p.X > maxX) maxX = p.X;
if (p.Y > maxY) maxY = p.Y;
if (p.Z > maxZ) maxZ = p.Z;
float isChar = forceCharred || (destruction is not null && destruction.GetState((ushort)treeIdx) == SionTreeState.Charred)
? 1f
: 0f;
Color c = pt.CustomDataBase;
c.R = isChar;
bucket.MultiMesh.SetInstanceCustomData(k, c);
}
var tightAabb = new Aabb(
new Vector3(minX - 14f, minY - 2f, minZ - 14f),
new Vector3((maxX - minX) + 28f, (maxY - minY) + 42f, (maxZ - minZ) + 28f));
bucket.MultiMesh.CustomAabb = tightAabb;
bucket.Instance.CustomAabb = tightAabb;
return count;
}
private static uint BitOperationsRoundUp(uint v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
return v + 1;
}
private Texture2D LoadTextureCached(string absPath)
{
if (_textureCache.TryGetValue(absPath, out var tex))
{
return tex;
}
var img = Image.LoadFromFile(absPath);
if (img is null)
{
throw new InvalidOperationException($"FoliageRenderer: failed to load texture '{absPath}'.");
}
img.GenerateMipmaps();
var itex = ImageTexture.CreateFromImage(img);
_textureCache[absPath] = itex;
return itex;
}
private static Color ReadColor3(JsonElement arr) =>
new(arr[0].GetSingle(), arr[1].GetSingle(), arr[2].GetSingle(), 1f);
private static void ApplyTreeMaterials(ArrayMesh mesh, ShaderMaterial barkMat, ShaderMaterial leafMat)
{
for (int s = 0; s < mesh.GetSurfaceCount(); s++)
{
string sName = mesh.SurfaceGetName(s) ?? string.Empty;
if (sName.Contains("foliage", StringComparison.OrdinalIgnoreCase) || s == 1)
{
mesh.SurfaceSetMaterial(s, leafMat);
}
else
{
mesh.SurfaceSetMaterial(s, barkMat);
}
}
}
private readonly record struct ArchetypeMeshes(
ArrayMesh Lod0,
ArrayMesh Lod1,
ArrayMesh Lod2,
ArrayMesh SnappedStump,
ArrayMesh CharredSkeleton);
private static ArchetypeMeshes? LoadArchetypeMeshes(string glbPath)
{
if (!File.Exists(glbPath))
{
GD.PrintErr($"FoliageRenderer: missing GLB '{glbPath}'.");
return null;
}
var doc = new GltfDocument();
var state = new GltfState();
Error err = doc.AppendFromFile(glbPath, state, flags: 0, basePath: Path.GetDirectoryName(glbPath) ?? string.Empty);
if (err != Error.Ok)
{
GD.PrintErr($"FoliageRenderer: GltfDocument failed on '{glbPath}': {err}");
return null;
}
Node? root = doc.GenerateScene(state);
if (root is null)
{
return null;
}
try
{
ArrayMesh? lod0 = null, lod1 = null, lod2 = null, stump = null, charred = null;
var stack = new Stack<Node>();
stack.Push(root);
while (stack.Count > 0)
{
Node n = stack.Pop();
if (n is MeshInstance3D mi && mi.Mesh is ArrayMesh am)
{
string name = mi.Name.ToString();
if (name.Contains("Intact_LOD0", StringComparison.OrdinalIgnoreCase)) lod0 = am;
else if (name.Contains("Intact_LOD1", StringComparison.OrdinalIgnoreCase)) lod1 = am;
else if (name.Contains("Intact_LOD2", StringComparison.OrdinalIgnoreCase)) lod2 = am;
else if (name.Contains("SnappedStump", StringComparison.OrdinalIgnoreCase)) stump = am;
else if (name.Contains("CharredSkeleton", StringComparison.OrdinalIgnoreCase)) charred = am;
}
for (int i = 0; i < n.GetChildCount(); i++)
{
stack.Push(n.GetChild(i));
}
}
if (lod0 is null || lod1 is null || lod2 is null || stump is null || charred is null)
{
GD.PrintErr($"FoliageRenderer: incomplete meshes in '{glbPath}'.");
return null;
}
return new ArchetypeMeshes(lod0, lod1, lod2, stump, charred);
}
finally
{
root.Free();
}
}
}

214
client/GpuSparksSystem.cs Normal file
View file

@ -0,0 +1,214 @@
using System;
using Godot;
namespace RustToDust.Client;
/// <summary>
/// Flow-coupled GPU particle system (<see cref="GpuParticles3D"/>, 65,536 capacity) driven by
/// the global <c>rtd_flow_field</c> <see cref="Texture3Drd"/> + <c>Tri3D</c> curl streams for
/// stochastic opaque HDR sparks, buoyant embers, flow-entrained dust motes, and muzzle starbursts.
/// </summary>
public partial class GpuSparksSystem : Node3D
{
public const int Capacity = 65536;
public const int TypeVelocitySpark = 0;
public const int TypeBuoyantEmber = 1;
public const int TypeDustMote = 2;
public const int TypeMuzzleStarburst = 3;
private const uint EmitFlagsAll = (uint)(
GpuParticles3D.EmitFlags.Position |
GpuParticles3D.EmitFlags.Velocity |
GpuParticles3D.EmitFlags.Color |
GpuParticles3D.EmitFlags.Custom);
private GpuParticles3D _particles = null!;
private ShaderMaterial _processMat = null!;
private ShaderMaterial _drawMat = null!;
private bool _initialized;
private uint _rng = 0x9E3779B9u;
public int TotalEmittedCount { get; private set; }
public GpuParticles3D ParticlesNode => _particles;
public override void _Ready()
{
EnsureInitialized();
}
public void EnsureInitialized()
{
if (_initialized)
{
return;
}
_initialized = true;
Shader processShader = GD.Load<Shader>("res://gpu_sparks_process.gdshader")
?? throw new InvalidOperationException("Failed to load res://gpu_sparks_process.gdshader");
Shader drawShader = GD.Load<Shader>("res://gpu_sparks_draw.gdshader")
?? throw new InvalidOperationException("Failed to load res://gpu_sparks_draw.gdshader");
_processMat = new ShaderMaterial { Shader = processShader };
_drawMat = new ShaderMaterial { Shader = drawShader };
var quad = new QuadMesh
{
Size = Vector2.One,
Material = _drawMat
};
_particles = new GpuParticles3D
{
Name = "GpuSparks3D",
Amount = Capacity,
LocalCoords = false,
Emitting = true,
AmountRatio = 0.0f, // Keep GPU process active with zero automatic spawns
Lifetime = 2.5f,
FixedFps = 0,
Explosiveness = 0.0f,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off,
VisibilityAabb = new Aabb(new Vector3(-1800f, -200f, -1800f), new Vector3(3600f, 2200f, 3600f)),
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off,
ProcessMaterial = _processMat,
DrawPass1 = quad
};
AddChild(_particles);
}
public void ClearAll()
{
EnsureInitialized();
TotalEmittedCount = 0;
_particles.Restart();
_particles.Emitting = true;
_particles.AmountRatio = 0.0f;
}
public void Prewarm(Vector3 nearPos)
{
EnsureInitialized();
EmitRaw(nearPos + new Vector3(0f, -20f, 0f), Vector3.Up * 0.1f, new Color(1f, 1f, 1f, 0.01f), 0.02f, 0.05f, TypeVelocitySpark, 1.0f);
TotalEmittedCount = 0;
}
public void EmitMuzzleStarburst(Vector3 pos, Color hdrColor, float sizeM, float lifetimeSec)
{
EnsureInitialized();
EmitRaw(pos, Vector3.Zero, hdrColor, Math.Clamp(sizeM, 0.25f, 0.90f), Math.Clamp(lifetimeSec, 0.05f, 0.14f), TypeMuzzleStarburst, 0f);
}
public void EmitSparkBurst(Vector3 pos, Vector3 normal, int count, Color hdrColor, float speed, float widthM = 0.026f)
{
EnsureInitialized();
Vector3 n = normal.LengthSquared() > 1e-4f ? normal.Normalized() : Vector3.Up;
for (int i = 0; i < count; i++)
{
Vector3 rand = new(NextSigned(), MathF.Abs(NextSigned()) + 0.28f, NextSigned());
Vector3 dir = (n * 0.65f + rand).Normalized();
float spd = speed * (0.55f + 0.85f * NextFloat());
float life = 0.24f + 0.34f * NextFloat();
Vector3 spawnPos = pos + new Vector3(NextSigned() * 0.14f, NextFloat() * 0.12f, NextSigned() * 0.14f);
EmitRaw(spawnPos, dir * spd, hdrColor, widthM, life, TypeVelocitySpark, 0.85f);
}
}
public void EmitEmberBurst(Vector3 pos, int count, Color hdrColor, float spreadSpeed, float widthM = 0.030f)
{
EnsureInitialized();
for (int i = 0; i < count; i++)
{
Vector3 vel = new(NextSigned() * spreadSpeed, 2.5f + NextFloat() * 5.5f, NextSigned() * spreadSpeed);
float life = 0.90f + NextFloat() * 1.25f;
EmitRaw(pos + new Vector3(NextSigned() * 0.7f, NextFloat() * 0.6f, NextSigned() * 0.7f), vel, hdrColor, widthM, life, TypeBuoyantEmber, 1.5f);
}
}
public void EmitDustMotes(Vector3 pos, Vector3 normal, int count, Color dustColor, float speed, float widthM = 0.065f)
{
EnsureInitialized();
Vector3 n = normal.LengthSquared() > 1e-4f ? normal.Normalized() : Vector3.Up;
for (int i = 0; i < count; i++)
{
float ang = NextFloat() * MathF.Tau;
float spd = speed * (0.55f + 0.70f * NextFloat());
Vector3 vel = new Vector3(MathF.Cos(ang) * spd, 0.8f + NextFloat() * 1.4f, MathF.Sin(ang) * spd) + n * (0.4f * spd);
float life = 0.45f + NextFloat() * 0.45f;
EmitRaw(pos + new Vector3(NextSigned() * 0.35f, 0.08f, NextSigned() * 0.35f), vel, dustColor, widthM, life, TypeDustMote, 3.6f);
}
}
public void EmitThermalPoolEmber(Vector3 pos, float radius, Color accentCol)
{
EnsureInitialized();
float ang = NextFloat() * MathF.Tau;
float r = MathF.Sqrt(NextFloat()) * MathF.Max(0.5f, radius * 0.85f);
Vector3 p = pos + new Vector3(MathF.Cos(ang) * r, 0.18f, MathF.Sin(ang) * r);
Vector3 vel = new(NextSigned() * 0.7f, 2.0f + NextFloat() * 1.8f, NextSigned() * 0.7f);
Color hdr = new(accentCol.R * 3.8f, accentCol.G * 3.8f, accentCol.B * 3.8f, 0.95f);
EmitRaw(p, vel, hdr, 0.055f, 0.65f + NextFloat() * 0.45f, TypeBuoyantEmber, 1.4f);
}
public void EmitPodRetroSparksAndDust(Vector3 podBasePos, float agl, Color groundTint, bool isContender)
{
EnsureInitialized();
float scale = isContender ? 1.2f : 0.85f;
Color sparkHdr = new(4.8f, 2.6f, 0.65f, 0.98f);
int sparkCount = isContender ? 14 : 8;
for (int i = 0; i < sparkCount; i++)
{
Vector3 vel = new(NextSigned() * 7.5f, -(11f + NextFloat() * 7f), NextSigned() * 7.5f);
EmitRaw(podBasePos + new Vector3(NextSigned() * 0.7f, 0.1f, NextSigned() * 0.7f), vel, sparkHdr, 0.028f * scale, 0.24f + NextFloat() * 0.16f, TypeVelocitySpark, 1.2f);
}
if (agl < 60f)
{
float washT = Math.Clamp(1f - agl / 60f, 0.2f, 1f);
Vector3 groundPos = podBasePos - new Vector3(0f, MathF.Max(0f, agl), 0f) + new Vector3(0f, 0.22f, 0f);
Color dustCol = new(groundTint.R * 1.1f, groundTint.G * 1.1f, groundTint.B * 1.1f, 0.78f * washT);
int moteCount = isContender ? 24 : 14;
for (int d = 0; d < moteCount; d++)
{
float ang = NextFloat() * MathF.Tau;
float spd = (7.5f + NextFloat() * 8.5f) * washT * scale;
Vector3 vel = new(MathF.Cos(ang) * spd, 1.0f + NextFloat() * 1.6f, MathF.Sin(ang) * spd);
EmitRaw(groundPos + new Vector3(MathF.Cos(ang) * 0.9f, 0f, MathF.Sin(ang) * 0.9f), vel, dustCol, 0.055f * scale, 0.55f + NextFloat() * 0.30f, TypeDustMote, 3.4f);
}
}
}
public void EmitPodTouchdownSparksAndDust(Vector3 pos, Vector3 normal, Color groundTint, bool isContender)
{
EnsureInitialized();
float scale = isContender ? 1.3f : 0.95f;
EmitSparkBurst(pos + normal * 0.45f, normal, isContender ? 160 : 90, new Color(5.2f, 2.8f, 0.70f, 0.98f), 19f * scale, 0.028f);
EmitEmberBurst(pos + normal * 0.45f, isContender ? 85 : 48, new Color(4.0f, 1.6f, 0.35f, 0.95f), 7.5f * scale, 0.032f);
EmitDustMotes(pos + normal * 0.25f, normal, isContender ? 75 : 45, groundTint with { A = 0.82f }, 10f * scale, 0.058f);
}
private void EmitRaw(Vector3 pos, Vector3 vel, Color hdrColor, float widthM, float lifetimeSec, int type, float drag)
{
float packedTypeAndDrag = type + Math.Clamp(drag, 0f, 19.9f) * 0.05f;
_particles.EmitParticle(
new Transform3D(Basis.Identity, pos),
vel,
hdrColor,
new Color(widthM, 0f, lifetimeSec, packedTypeAndDrag),
EmitFlagsAll);
TotalEmittedCount++;
}
private float NextFloat()
{
uint x = _rng;
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
_rng = x;
return (x & 0x00FFFFFFu) / 16777216f;
}
private float NextSigned() => NextFloat() * 2f - 1f;
}

270
client/GraphicsSettings.cs Normal file
View file

@ -0,0 +1,270 @@
using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace RustToDust.Client;
public enum VfxResolutionScale
{
Half = 0,
ThreeQuarter = 1,
Full = 2
}
public enum VolumetricSamples
{
Low = 0,
Medium = 1,
High = 2,
Ultra = 3
}
public enum SdfgiQuality
{
Off = 0,
Balanced = 1,
High = 2
}
public readonly record struct SdfgiSettingsConfig(
bool Enabled,
float MinCellSize,
int Cascades,
bool HalfResolution,
int RayCount);
public sealed record GraphicsSettingsData
{
[JsonPropertyName("vfxResolutionScale")]
public VfxResolutionScale VfxResolution { get; init; } = VfxResolutionScale.Half;
[JsonPropertyName("volumetricSamples")]
public VolumetricSamples VolumetricSamples { get; init; } = VolumetricSamples.Medium;
[JsonPropertyName("sdfgiQuality")]
public SdfgiQuality SdfgiQuality { get; init; } = SdfgiQuality.Balanced;
[JsonPropertyName("borderlessFullscreen")]
public bool BorderlessFullscreen { get; init; } = true;
}
/// <summary>
/// Single persisted authority for live graphics and display settings (<c>user://graphics_settings.json</c>).
/// Pure .NET so unit tests and headless runs share the exact same schema, defaults, and event flow.
/// </summary>
public sealed class GraphicsSettings
{
public const string DefaultFileName = "graphics_settings.json";
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true,
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter() }
};
private readonly string? _storagePath;
public GraphicsSettings(string? storagePath = null)
{
_storagePath = string.IsNullOrWhiteSpace(storagePath) ? null : storagePath;
ResetFieldsToDefaults();
}
public VfxResolutionScale VfxResolution { get; private set; }
public VolumetricSamples VolumetricSamples { get; private set; }
public SdfgiQuality SdfgiQuality { get; private set; }
public bool BorderlessFullscreen { get; private set; }
public string? StoragePath => _storagePath;
public event Action<GraphicsSettings>? Changed;
public GraphicsSettingsData ToData() => new()
{
VfxResolution = VfxResolution,
VolumetricSamples = VolumetricSamples,
SdfgiQuality = SdfgiQuality,
BorderlessFullscreen = BorderlessFullscreen
};
public static GraphicsSettings Load(string? storagePath)
{
var settings = new GraphicsSettings(storagePath);
if (string.IsNullOrWhiteSpace(storagePath))
{
return settings;
}
try
{
if (File.Exists(storagePath))
{
string json = File.ReadAllText(storagePath);
settings.LoadFromJson(json);
}
}
catch
{
settings.ResetFieldsToDefaults();
}
return settings;
}
public bool LoadFromJson(string? json)
{
if (string.IsNullOrWhiteSpace(json))
{
ResetFieldsToDefaults();
return false;
}
try
{
var parsed = JsonSerializer.Deserialize<GraphicsSettingsData>(json, JsonOptions);
if (parsed is null)
{
ResetFieldsToDefaults();
return false;
}
VfxResolution = Enum.IsDefined(parsed.VfxResolution)
? parsed.VfxResolution
: VfxResolutionScale.Half;
VolumetricSamples = Enum.IsDefined(parsed.VolumetricSamples)
? parsed.VolumetricSamples
: VolumetricSamples.Medium;
SdfgiQuality = Enum.IsDefined(parsed.SdfgiQuality)
? parsed.SdfgiQuality
: SdfgiQuality.Balanced;
BorderlessFullscreen = parsed.BorderlessFullscreen;
return true;
}
catch
{
ResetFieldsToDefaults();
return false;
}
}
public string ToJson() => JsonSerializer.Serialize(ToData(), JsonOptions);
public bool Save()
{
if (string.IsNullOrWhiteSpace(_storagePath))
{
return false;
}
try
{
string? dir = Path.GetDirectoryName(_storagePath);
if (!string.IsNullOrEmpty(dir))
{
Directory.CreateDirectory(dir);
}
string json = ToJson();
string tempPath = _storagePath + ".tmp";
File.WriteAllText(tempPath, json);
File.Move(tempPath, _storagePath, overwrite: true);
return true;
}
catch
{
return false;
}
}
public void Apply(
VfxResolutionScale vfxResolution,
VolumetricSamples volumetricSamples,
SdfgiQuality sdfgiQuality,
bool borderlessFullscreen,
bool persist = true,
bool forcePersist = false)
{
VfxResolutionScale safeRes = Enum.IsDefined(vfxResolution) ? vfxResolution : VfxResolutionScale.Half;
VolumetricSamples safeSamples = Enum.IsDefined(volumetricSamples) ? volumetricSamples : VolumetricSamples.Medium;
SdfgiQuality safeSdfgi = Enum.IsDefined(sdfgiQuality) ? sdfgiQuality : SdfgiQuality.Balanced;
bool changed = VfxResolution != safeRes
|| VolumetricSamples != safeSamples
|| SdfgiQuality != safeSdfgi
|| BorderlessFullscreen != borderlessFullscreen;
if (!changed)
{
if (persist && forcePersist)
{
Save();
}
return;
}
VfxResolution = safeRes;
VolumetricSamples = safeSamples;
SdfgiQuality = safeSdfgi;
BorderlessFullscreen = borderlessFullscreen;
if (persist)
{
Save();
}
Changed?.Invoke(this);
}
public void SetVfxResolution(VfxResolutionScale value, bool persist = true) =>
Apply(value, VolumetricSamples, SdfgiQuality, BorderlessFullscreen, persist);
public void SetVolumetricSamples(VolumetricSamples value, bool persist = true) =>
Apply(VfxResolution, value, SdfgiQuality, BorderlessFullscreen, persist);
public void SetSdfgiQuality(SdfgiQuality value, bool persist = true) =>
Apply(VfxResolution, VolumetricSamples, value, BorderlessFullscreen, persist);
public void SetBorderlessFullscreen(bool value, bool persist = true) =>
Apply(VfxResolution, VolumetricSamples, SdfgiQuality, value, persist);
public void ResetToDefaults(bool persist = true) =>
Apply(
VfxResolutionScale.Half,
VolumetricSamples.Medium,
SdfgiQuality.Balanced,
borderlessFullscreen: true,
persist: persist,
forcePersist: persist);
public static float GetResolutionScaleFactor(VfxResolutionScale scale) => scale switch
{
VfxResolutionScale.Half => 0.50f,
VfxResolutionScale.ThreeQuarter => 0.75f,
VfxResolutionScale.Full => 1.00f,
_ => 0.50f
};
public static (int MaxSteps, int MaxIter) GetVolumetricStepBudget(VolumetricSamples samples) => samples switch
{
VolumetricSamples.Low => (8, 12),
VolumetricSamples.Medium => (10, 15),
VolumetricSamples.High => (16, 24),
VolumetricSamples.Ultra => (24, 36),
_ => (10, 15)
};
public static SdfgiSettingsConfig GetSdfgiConfig(SdfgiQuality quality) => quality switch
{
SdfgiQuality.Off => new SdfgiSettingsConfig(false, 0.8f, 3, true, 4),
SdfgiQuality.Balanced => new SdfgiSettingsConfig(true, 0.8f, 3, true, 4),
SdfgiQuality.High => new SdfgiSettingsConfig(true, 0.4f, 4, false, 8),
_ => new SdfgiSettingsConfig(true, 0.8f, 3, true, 4)
};
private void ResetFieldsToDefaults()
{
VfxResolution = VfxResolutionScale.Half;
VolumetricSamples = VolumetricSamples.Medium;
SdfgiQuality = SdfgiQuality.Balanced;
BorderlessFullscreen = true;
}
}

1099
client/HbGpuCanvas.cs Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using Godot;
using RustToDust.Core;
using RustToDust.HbGpu;
namespace RustToDust.Client;
@ -38,8 +39,14 @@ public partial class InventoryGridControl : Control
private static Shader? _sharedShader;
private readonly TextureRect _gridSurface;
private readonly LabelsOverlay _labelsOverlay;
private readonly ShaderMaterial _material;
private HbGpuCanvas? _standaloneCanvas;
private readonly Dictionary<string, string> _lastEmittedTags = new(StringComparer.Ordinal);
private readonly char[] _tagScratch = new char[32];
private int _overlayEmitCount;
private float _standaloneTime;
private bool _standaloneDirty = true;
private Image? _dataImage;
private ImageTexture? _dataTex;
@ -83,17 +90,10 @@ public partial class InventoryGridControl : Control
_gridSurface.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(_gridSurface);
_labelsOverlay = new LabelsOverlay(this)
{
Name = "GridLabelsOverlay",
MouseFilter = MouseFilterEnum.Ignore
};
_labelsOverlay.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(_labelsOverlay);
MouseExited += OnMouseExited;
}
public bool ExternalHbGpuOwner { get; set; }
public ShaderMaterial ShaderMaterial => _material;
public Control ShaderSurface => _gridSurface;
public ChassisGrid? Grid => _grid;
@ -103,9 +103,24 @@ public partial class InventoryGridControl : Control
? _hardpointLookup[c.X, c.Y]
: null;
internal int LabelsDrawCount => _labelsOverlay.DrawCount;
internal string? GetLastDrawnLabel(string hardpointId) =>
_labelsOverlay.LastDrawnTags.TryGetValue(hardpointId, out string? tag) ? tag : null;
internal int OverlayEmitCount => _overlayEmitCount;
internal HbGpuCanvas? StandaloneCanvas => _standaloneCanvas;
internal string? GetLastEmittedLabel(string hardpointId) =>
_lastEmittedTags.TryGetValue(hardpointId, out string? tag) ? tag : null;
public override void _Ready()
{
if (!ExternalHbGpuOwner && _standaloneCanvas is null)
{
_standaloneCanvas = new HbGpuCanvas
{
Name = "StandaloneHbGpuCanvas",
MouseFilter = MouseFilterEnum.Ignore
};
_standaloneCanvas.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(_standaloneCanvas);
}
}
public event Action<int, int>? CellClicked;
public event Action<string>? HardpointClicked;
@ -116,13 +131,14 @@ public partial class InventoryGridControl : Control
if (what == NotificationResized)
{
SyncRectUniform();
_labelsOverlay.QueueRedraw();
_standaloneDirty = true;
}
}
public override void _Process(double delta)
{
float dt = (float)delta;
_standaloneTime += MathF.Max(0f, dt);
bool anyPulse = false;
for (int y = 0; y < _gridHeight; y++)
@ -141,6 +157,19 @@ public partial class InventoryGridControl : Control
{
PackDataTexture(_grid);
FlushTextures();
_standaloneDirty = true;
}
if (!ExternalHbGpuOwner && _standaloneCanvas is not null && _grid is not null)
{
bool hasCompatiblePulse = _selectedCargoIndex >= 0 && _selectedCargoIndex < _grid.Cargo.Count;
if (_standaloneDirty || hasCompatiblePulse)
{
_standaloneDirty = false;
_standaloneCanvas.BeginFrame();
EmitHbGpuOverlay(_standaloneCanvas, Vector2.Zero, _standaloneTime);
_standaloneCanvas.EndFrameAndSubmit();
}
}
}
@ -195,7 +224,7 @@ public partial class InventoryGridControl : Control
PackTempTexture(grid);
FlushTextures();
SyncRectUniform();
_labelsOverlay.QueueRedraw();
_standaloneDirty = true;
return;
}
@ -224,7 +253,7 @@ public partial class InventoryGridControl : Control
}
if (dataChanged || tempChanged)
{
_labelsOverlay.QueueRedraw();
_standaloneDirty = true;
FlushTextures();
}
}
@ -236,6 +265,7 @@ public partial class InventoryGridControl : Control
_hitPulse[x, y] = Math.Clamp(intensity, 0f, 1f);
PackDataTexture(_grid);
FlushTextures();
_standaloneDirty = true;
}
public bool TryGetCellAt(Vector2 localPos, out Vector2I cell)
@ -282,6 +312,7 @@ public partial class InventoryGridControl : Control
{
PackDataTexture(_grid);
FlushTextures();
_standaloneDirty = true;
}
}
}
@ -301,6 +332,7 @@ public partial class InventoryGridControl : Control
{
PackDataTexture(_grid);
FlushTextures();
_standaloneDirty = true;
}
}
@ -685,62 +717,218 @@ public partial class InventoryGridControl : Control
_ => ColTextLight
};
private sealed partial class LabelsOverlay : Control
/// <summary>
/// Emits crisp analytic vector cell borders, hardpoint L-brackets, compatibility pulses,
/// stripped X-marks, and Monaspace Krypton hardpoint labels into <paramref name="canvas"/>.
/// Zero GC allocations on steady-state calls.
/// </summary>
public void EmitHbGpuOverlay(HbGpuCanvas canvas, Vector2 originOffset, float timeSec)
{
private readonly InventoryGridControl _owner;
public int DrawCount { get; private set; }
public readonly Dictionary<string, string> LastDrawnTags = new(StringComparer.Ordinal);
public LabelsOverlay(InventoryGridControl owner) => _owner = owner;
public override void _Draw()
_overlayEmitCount++;
var grid = _grid;
if (grid is null)
{
DrawCount++;
LastDrawnTags.Clear();
var grid = _owner._grid;
if (grid is null) return;
return;
}
_owner.ComputeCellLayout(out float cellSize, out Vector2 origin);
if (cellSize < 14f) return;
ComputeCellLayout(out float cellSize, out Vector2 origin);
if (cellSize < 8f)
{
return;
}
var spec = grid.Spec;
int fontSize = cellSize >= 38f ? 10 : 9;
float alpha = 0.95f;
Vector2 basePos = originOffset + origin;
var spec = grid.Spec;
ModuleSpec? selectedCargo = _selectedCargoIndex >= 0 && _selectedCargoIndex < grid.Cargo.Count
? grid.Cargo[_selectedCargoIndex]
: null;
HardpointSpec? hoveredHp = HoveredHardpoint;
Color flashCol = new(1.0f, 0.76f, 0.38f, 1.0f);
Color redAccent = new(0.92f, 0.26f, 0.18f, 1.0f);
for (int i = 0; i < spec.Hardpoints.Length; i++)
// 1. Hull cell outlines, internal subdivisions, and stripped-cell X marks
for (int y = 0; y < _gridHeight; y++)
{
for (int x = 0; x < _gridWidth; x++)
{
var hp = spec.Hardpoints[i];
var mounted = grid.GetMountedOn(hp.Id);
var pos = origin + new Vector2(hp.X * cellSize, hp.Y * cellSize);
float maxW = MathF.Max(12f, hp.Width * cellSize - 6f);
if (!spec.IsActive(x, y))
{
continue;
}
string tag = mounted is not null
? $"{mounted.Spec.Kind.ToString()[..1]}:{mounted.CurrentTemp:F0}°"
: hp.Kind.ToString()[..3].ToUpperInvariant();
LastDrawnTags[hp.Id] = tag;
float cx = basePos.X + x * cellSize;
float cy = basePos.Y + y * cellSize;
bool stripped = grid.Armor[x, y] <= 0.01f;
var hp = _hardpointLookup[x, y];
if (hp is null)
{
Color edgeCol = grid.BorderCells[x, y]
? ColBorderHull.Lerp(ColBorderRadiatorCell, 0.30f)
: ColBorderHull;
float pulse = Math.Clamp(_hitPulse[x, y], 0f, 1f);
bool isCellHovered = _hoveredCell is { } hc && hc.X == x && hc.Y == y;
if (stripped) edgeCol = edgeCol.Lerp(redAccent, 0.65f);
if (isCellHovered) edgeCol = edgeCol.Lerp(Colors.White, 0.35f);
if (pulse > 0.01f) edgeCol = edgeCol.Lerp(flashCol, pulse * 0.90f);
float inset = 1.5f;
float x0 = cx + inset;
float y0 = cy + inset;
float x1 = cx + cellSize - inset;
float y1 = cy + cellSize - inset;
// Outer hull perimeter edges get crisp medium lines; internal matched hull edges get faint hairlines
bool nMatch = spec.IsActive(x, y - 1) && _hardpointLookup[x, y - 1] is null;
bool sMatch = spec.IsActive(x, y + 1) && _hardpointLookup[x, y + 1] is null;
bool wMatch = spec.IsActive(x - 1, y) && _hardpointLookup[x - 1, y] is null;
bool eMatch = spec.IsActive(x + 1, y) && _hardpointLookup[x + 1, y] is null;
Color outerCol = new(edgeCol.R, edgeCol.G, edgeCol.B, isCellHovered ? 0.85f : 0.42f);
Color innerCol = new(edgeCol.R, edgeCol.G, edgeCol.B, 0.14f);
if (!nMatch) canvas.DrawLineSegment(x0, y0, x1, y0, 1.2f, outerCol);
if (!sMatch) canvas.DrawLineSegment(x0, y1, x1, y1, 1.2f, outerCol);
else canvas.DrawLineSegment(cx + 2f, cy + cellSize, cx + cellSize - 2f, cy + cellSize, 0.9f, innerCol);
if (!wMatch) canvas.DrawLineSegment(x0, y0, x0, y1, 1.2f, outerCol);
if (!eMatch) canvas.DrawLineSegment(x1, y0, x1, y1, 1.2f, outerCol);
else canvas.DrawLineSegment(cx + cellSize, cy + 2f, cx + cellSize, cy + cellSize - 2f, 0.9f, innerCol);
}
if (stripped)
{
float pad = MathF.Max(4.5f, cellSize * 0.18f);
Color xCol = new(0.95f, 0.28f, 0.20f, 0.78f);
canvas.DrawLineSegment(cx + pad, cy + pad, cx + cellSize - pad, cy + cellSize - pad, 1.5f, xCol);
canvas.DrawLineSegment(cx + cellSize - pad, cy + pad, cx + pad, cy + cellSize - pad, 1.5f, xCol);
}
}
}
// 2. Contiguous hardpoint borders, L-brackets, and Krypton tags
float fontSize = cellSize >= 38f ? 10.5f : 9.2f;
float compatPulse = 0.72f + 0.28f * MathF.Sin(timeSec * 6.5f);
for (int i = 0; i < spec.Hardpoints.Length; i++)
{
var hp = spec.Hardpoints[i];
var mounted = grid.GetMountedOn(hp.Id);
float hx = basePos.X + hp.X * cellSize;
float hy = basePos.Y + hp.Y * cellSize;
float hw = hp.Width * cellSize;
float hh = hp.Height * cellSize;
bool strippedHp = !grid.IsHardpointOperational(hp);
bool isCompatible = selectedCargo is not null && ChassisGrid.CanFit(hp, selectedCargo);
bool isHovered = hoveredHp is not null && ReferenceEquals(hp, hoveredHp);
float maxPulse = 0f;
for (int dy = 0; dy < hp.Height; dy++)
{
for (int dx = 0; dx < hp.Width; dx++)
{
int cx = hp.X + dx;
int cy = hp.Y + dy;
if (cx >= 0 && cy >= 0 && cx < _gridWidth && cy < _gridHeight)
{
maxPulse = MathF.Max(maxPulse, _hitPulse[cx, cy]);
}
}
}
Color accent;
if (isCompatible)
{
accent = ColGold;
}
else if (mounted is { Spec.IsImperial: true })
{
accent = ColGold;
}
else
{
accent = KindColor(hp.Kind);
if (mounted is null)
{
accent = accent.Lerp(ColBorderHull, 0.45f);
}
}
if (strippedHp) accent = accent.Lerp(redAccent, 0.70f);
if (isCompatible) accent = accent.Lerp(new Color(0.96f, 0.82f, 0.30f, 1f), compatPulse);
if (isHovered) accent = accent.Lerp(Colors.White, 0.35f);
if (maxPulse > 0.01f) accent = accent.Lerp(flashCol, maxPulse * 0.90f);
const float inset = 1.8f;
float rx = hx + inset;
float ry = hy + inset;
float rw = MathF.Max(2f, hw - inset * 2f);
float rh = MathF.Max(2f, hh - inset * 2f);
float ruleAlpha = isCompatible ? 0.68f : (isHovered ? 0.60f : 0.34f);
canvas.DrawRectOutline(rx, ry, rw, rh, isCompatible ? 1.5f : 1.0f, new Color(accent.R, accent.G, accent.B, ruleAlpha));
float arm = Math.Clamp(MathF.Min(rw, rh) * 0.28f, 4.5f, 12f);
float bracketThick = (isCompatible || isHovered) ? 2.4f : 1.8f;
Color bracketCol = new(accent.R, accent.G, accent.B, 0.96f);
canvas.DrawTargetBracketCorner(rx, ry, arm, bracketThick, 0, bracketCol);
canvas.DrawTargetBracketCorner(rx + rw, ry, arm, bracketThick, 1, bracketCol);
canvas.DrawTargetBracketCorner(rx + rw, ry + rh, arm, bracketThick, 2, bracketCol);
canvas.DrawTargetBracketCorner(rx, ry + rh, arm, bracketThick, 3, bracketCol);
if (cellSize >= 14f)
{
ReadOnlySpan<char> tagSpan = FormatHardpointTag(hp, mounted, _tagScratch);
if (!_lastEmittedTags.TryGetValue(hp.Id, out string? existingTag) || !tagSpan.SequenceEqual(existingTag))
{
_lastEmittedTags[hp.Id] = new string(tagSpan);
}
Color col = mounted is { Spec.IsImperial: true } ? ColGold : ColTextLight;
col.A = alpha;
col.A = 0.95f;
HbGpuCommandWriter.PackClipRect(hx + 2f, hy + 2f, hw - 4f, hh - 4f, out uint clipMin, out uint clipMax);
// Dark shadow for crisp legibility over bright thermal glow
DrawString(
ThemeDB.FallbackFont,
pos + new Vector2(7f, fontSize + 6f),
tag,
HorizontalAlignment.Left,
maxW - 2f,
fontSize,
new Color(0.04f, 0.05f, 0.04f, alpha * 0.9f));
DrawString(
ThemeDB.FallbackFont,
pos + new Vector2(6f, fontSize + 5f),
tag,
HorizontalAlignment.Left,
maxW - 2f,
fontSize,
col);
float tx = hx + 5f;
float ty = hy + fontSize + 4.5f;
canvas.DrawText(tagSpan, tx + 1f, ty + 1f, fontSize, new Color(0.04f, 0.05f, 0.04f, 0.90f),
wght: 550f, stemDarken: true, clipMinPacked: clipMin, clipMaxPacked: clipMax);
canvas.DrawText(tagSpan, tx, ty, fontSize, col,
wght: 550f, stemDarken: true, clipMinPacked: clipMin, clipMaxPacked: clipMax);
}
}
}
private static ReadOnlySpan<char> FormatHardpointTag(HardpointSpec hp, MountedModule? mounted, char[] buf)
{
if (mounted is null)
{
return hp.Kind switch
{
HardpointKind.Weapon => "WPN",
HardpointKind.Engine => "ENG",
HardpointKind.Radiator => "RAD",
HardpointKind.Armor => "ARM",
HardpointKind.Utility => "UTL",
_ => "MOD"
};
}
buf[0] = mounted.Spec.Kind switch
{
HardpointKind.Weapon => 'W',
HardpointKind.Engine => 'E',
HardpointKind.Radiator => 'R',
HardpointKind.Armor => 'A',
HardpointKind.Utility => 'U',
_ => 'M'
};
buf[1] = ':';
int pos = 2;
if (mounted.CurrentTemp.TryFormat(buf.AsSpan(pos), out int written, "F0", System.Globalization.CultureInfo.InvariantCulture))
{
pos += written;
}
buf[pos++] = '°';
return buf.AsSpan(0, pos);
}
}

View file

@ -16,11 +16,22 @@ public sealed partial class LobbyScreen : CanvasLayer
{
public required PanelContainer Frame;
public required Label IndexLabel;
public required Label SquadBadge;
public required Label NameLabel;
public required Label RoleBadge;
public required Label ReadyBadge;
}
private static readonly Color[] SquadColors =
{
Color.FromHtml("#52e3a8"),
ImperialChrome.CyanCol,
ImperialChrome.GoldCol,
ImperialChrome.OrangeCol,
ImperialChrome.OliveCol,
Color.FromHtml("#d67cff")
};
private readonly SlotRowView[] _slotViews = new SlotRowView[MatchState.ContenderCount];
private Control _root = null!;
@ -32,11 +43,13 @@ public sealed partial class LobbyScreen : CanvasLayer
private OptionButton _mapOption = null!;
private LineEdit _seedEdit = null!;
private OptionButton _squadOption = null!;
private Button _applyConfigBtn = null!;
private Button _randomSeedBtn = null!;
private Label _authorityNoteLabel = null!;
private Label _netStatusLabel = null!;
private Button _switchSquadBtn = null!;
private Button _readyBtn = null!;
private Button _launchBtn = null!;
private Button _leaveBtn = null!;
@ -44,6 +57,7 @@ public sealed partial class LobbyScreen : CanvasLayer
private IClientArenaSession? _activeSession;
private int? _lastSyncedSeed;
private byte? _lastSyncedMap;
private byte? _lastSyncedSquadSize;
public LobbyScreen()
{
@ -72,6 +86,7 @@ public sealed partial class LobbyScreen : CanvasLayer
_activeSession = null;
_lastSyncedSeed = null;
_lastSyncedMap = null;
_lastSyncedSquadSize = null;
_seedEdit?.ReleaseFocus();
}
}
@ -101,9 +116,11 @@ public sealed partial class LobbyScreen : CanvasLayer
_countdownLabel.AddThemeColorOverride("font_color", net.LastError is not null ? ImperialChrome.RedCol : ImperialChrome.OrangeCol);
_rosterSummaryLabel.Text = "Awaiting authoritative lobby roster...";
_readyBtn.Disabled = true;
_switchSquadBtn.Disabled = true;
_launchBtn.Visible = false;
_mapOption.Disabled = true;
_seedEdit.Editable = false;
_squadOption.Disabled = true;
_applyConfigBtn.Disabled = true;
_randomSeedBtn.Disabled = true;
_authorityNoteLabel.Text = "Waiting for server snapshot...";
@ -114,9 +131,11 @@ public sealed partial class LobbyScreen : CanvasLayer
int localId = session.LocalContenderId;
bool isHost = lobby.HostSlotId.HasValue && lobby.HostSlotId.Value == localId;
bool localReady = false;
byte localSquadId = 0;
int humanCount = 0;
int readyCount = 0;
int aiCount = 0;
byte squadSize = (byte)Math.Clamp((int)lobby.SquadSize, 1, 4);
for (int i = 0; i < _slotViews.Length; i++)
{
@ -126,8 +145,19 @@ public sealed partial class LobbyScreen : CanvasLayer
var slot = lobby.Slots[i];
bool isLocalSlot = slot.SlotId == localId;
bool isHostSlot = lobby.HostSlotId.HasValue && slot.SlotId == lobby.HostSlotId.Value;
if (isLocalSlot) localSquadId = slot.SquadId;
view.IndexLabel.Text = $"SLOT {slot.SlotId + 1:00}";
if (squadSize > 1)
{
view.SquadBadge.Text = $"[SQ {slot.SquadId + 1}]";
view.SquadBadge.AddThemeColorOverride("font_color", SquadColors[slot.SquadId % SquadColors.Length]);
}
else
{
view.SquadBadge.Text = "[FFA]";
view.SquadBadge.AddThemeColorOverride("font_color", ImperialChrome.TextMuted);
}
if (slot.IsHuman)
{
humanCount++;
@ -183,7 +213,7 @@ public sealed partial class LobbyScreen : CanvasLayer
_panel.SetAccentColor(ImperialChrome.CyanCol);
}
// Sync Map & Seed without clobbering active typing by host
// Sync Map, Seed & SquadSize without clobbering active typing by host
if (_lastSyncedMap != lobby.SelectedMap)
{
_lastSyncedMap = lobby.SelectedMap;
@ -194,17 +224,28 @@ public sealed partial class LobbyScreen : CanvasLayer
_lastSyncedSeed = lobby.SelectedSeed;
_seedEdit.Text = lobby.SelectedSeed.ToString(CultureInfo.InvariantCulture);
}
if (_lastSyncedSquadSize != squadSize)
{
_lastSyncedSquadSize = squadSize;
_squadOption.Select(squadSize - 1);
}
// Strict host authority gating
_mapOption.Disabled = !isHost;
_seedEdit.Editable = isHost;
_squadOption.Disabled = !isHost;
_applyConfigBtn.Disabled = !isHost;
_randomSeedBtn.Disabled = !isHost;
_authorityNoteLabel.Text = isHost
? "HOST AUTHORITY: You control drop zone, seed, and forced launch."
: "READ-ONLY: Only the match host can edit map, seed, or force launch.";
? "HOST AUTHORITY: You control drop zone, seed, squad mode, and forced launch."
: "READ-ONLY: Only the match host can edit map, seed, squad mode, or force launch.";
_authorityNoteLabel.AddThemeColorOverride("font_color", isHost ? ImperialChrome.GoldCol : ImperialChrome.TextMuted);
_switchSquadBtn.Disabled = squadSize <= 1;
_switchSquadBtn.Text = squadSize > 1
? $"SWITCH SQUAD [SQ {localSquadId + 1}]"
: "SWITCH SQUAD (FFA)";
_readyBtn.Disabled = false;
_readyBtn.Text = localReady ? "READY [ON] — CLICK TO UNREADY" : "READY UP";
ImperialChrome.StyleButton(_readyBtn, localReady ? ImperialChrome.OliveCol : ImperialChrome.CyanCol, 14);
@ -240,10 +281,10 @@ public sealed partial class LobbyScreen : CanvasLayer
_panel.AnchorRight = 0.5f;
_panel.AnchorTop = 0.5f;
_panel.AnchorBottom = 0.5f;
_panel.OffsetLeft = -500f;
_panel.OffsetRight = 500f;
_panel.OffsetTop = -305f;
_panel.OffsetBottom = 305f;
_panel.OffsetLeft = -515f;
_panel.OffsetRight = 515f;
_panel.OffsetTop = -330f;
_panel.OffsetBottom = 330f;
_root.AddChild(_panel);
var vbox = new VBoxContainer();
@ -309,9 +350,13 @@ public sealed partial class LobbyScreen : CanvasLayer
frame.AddChild(row);
var idxLbl = ImperialChrome.CreateLabel($"SLOT {i + 1:00}", 11, ImperialChrome.TextMuted);
idxLbl.CustomMinimumSize = new Vector2(64f, 0f);
idxLbl.CustomMinimumSize = new Vector2(60f, 0f);
row.AddChild(idxLbl);
var sqLbl = ImperialChrome.CreateLabel("[SQ 1]", 11, SquadColors[0]);
sqLbl.CustomMinimumSize = new Vector2(54f, 0f);
row.AddChild(sqLbl);
var nameLbl = ImperialChrome.CreateLabel("AI BACKFILL", 12, ImperialChrome.TextMuted);
nameLbl.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
nameLbl.ClipText = true;
@ -332,6 +377,7 @@ public sealed partial class LobbyScreen : CanvasLayer
{
Frame = frame,
IndexLabel = idxLbl,
SquadBadge = sqLbl,
NameLabel = nameLbl,
RoleBadge = roleLbl,
ReadyBadge = readyLbl
@ -392,7 +438,23 @@ public sealed partial class LobbyScreen : CanvasLayer
};
seedRow.AddChild(_randomSeedBtn);
_applyConfigBtn = ImperialChrome.CreateButton("APPLY MAP & SEED", ImperialChrome.GoldCol, 12, 32f);
var squadRow = new HBoxContainer();
squadRow.AddThemeConstantOverride("separation", 8);
rightCol.AddChild(squadRow);
var squadLbl = ImperialChrome.CreateLabel("SQUAD", 12, ImperialChrome.TextMuted);
squadLbl.CustomMinimumSize = new Vector2(68f, 0f);
squadRow.AddChild(squadLbl);
_squadOption = new OptionButton { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill };
_squadOption.AddItem("FFA (1)", 0);
_squadOption.AddItem("DUO (2)", 1);
_squadOption.AddItem("TRIO (3)", 2);
_squadOption.AddItem("QUAD (4)", 3);
_squadOption.Select(2);
ImperialChrome.StyleOptionButton(_squadOption, ImperialChrome.CyanCol, 13);
_squadOption.ItemSelected += _ => ApplyConfigFromUi();
squadRow.AddChild(_squadOption);
_applyConfigBtn = ImperialChrome.CreateButton("APPLY MAP, SEED & SQUAD", ImperialChrome.GoldCol, 12, 32f);
_applyConfigBtn.Pressed += ApplyConfigFromUi;
rightCol.AddChild(_applyConfigBtn);
@ -405,6 +467,10 @@ public sealed partial class LobbyScreen : CanvasLayer
var spacer = new Control { SizeFlagsVertical = Control.SizeFlags.ExpandFill };
rightCol.AddChild(spacer);
_switchSquadBtn = ImperialChrome.CreateButton("SWITCH SQUAD [SQ 1]", SquadColors[0], 13, 36f);
_switchSquadBtn.Pressed += OnSwitchSquadPressed;
rightCol.AddChild(_switchSquadBtn);
_readyBtn = ImperialChrome.CreateButton("READY UP", ImperialChrome.CyanCol, 14, 42f);
_readyBtn.Pressed += OnReadyPressed;
rightCol.AddChild(_readyBtn);
@ -438,6 +504,27 @@ public sealed partial class LobbyScreen : CanvasLayer
_activeSession.SetLobbyReady(!currentReady);
}
private void OnSwitchSquadPressed()
{
if (_activeSession is null || _activeSession.LobbyState is not { } lobby) return;
byte squadSize = (byte)Math.Clamp((int)lobby.SquadSize, 1, 4);
if (squadSize <= 1) return;
int maxSquads = Math.Max(1, (MatchState.ContenderCount + squadSize - 1) / squadSize);
int localId = _activeSession.LocalContenderId;
byte curSq = 0;
for (int i = 0; i < lobby.Slots.Count; i++)
{
if (lobby.Slots[i].SlotId == localId)
{
curSq = lobby.Slots[i].SquadId;
break;
}
}
byte nextSq = (byte)((curSq + 1) % maxSquads);
_activeSession.RequestLobbySquad(nextSq);
}
private void OnLaunchPressed()
{
_activeSession?.RequestLobbyStart();
@ -452,9 +539,10 @@ public sealed partial class LobbyScreen : CanvasLayer
int seed = int.TryParse(_seedEdit.Text.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsed)
? parsed
: lobby.SelectedSeed;
byte squadSize = (byte)Math.Clamp(_squadOption.Selected + 1, 1, 4);
_seedEdit.ReleaseFocus();
_activeSession.RequestLobbyConfig(seed, mapKind);
_activeSession.RequestLobbyConfig(seed, mapKind, squadSize);
}
private static void ApplyRowFrame(PanelContainer frame, Color borderColor, bool highlighted)

View file

@ -17,7 +17,8 @@ public enum ClientScreenMode
ServerBrowser,
Lobby,
InMatch,
PauseOverlay
PauseOverlay,
Settings
}
/// <summary>
@ -32,18 +33,23 @@ public partial class Main : Node3D
private TerrainRenderer _terrain = null!;
private SionMapRenderer _sionMap = null!;
private FoliageRenderer _foliage = null!;
private ArenaRenderer _arena = null!;
private ArenaAudioSystem _audio = null!;
private Camera3D _camera = null!;
private Hud _hud = null!;
private AtmosphereSystem _atmosphere = null!;
private MainMenu _mainMenu = null!;
private SettingsOverlay _settingsOverlay = null!;
private ServerBrowser _serverBrowser = null!;
private LobbyScreen _lobbyScreen = null!;
private GraphicsSettings _graphicsSettings = new();
private IClientArenaSession? _session;
private MatchState? _boundViewState;
private bool _wasNetConnected;
private ClientScreenMode _screenMode = ClientScreenMode.MainMenu;
private ClientScreenMode _settingsReturnMode = ClientScreenMode.MainMenu;
private bool _hasWindowOverride;
private DirectoryReporter? _directoryReporter;
private string _directoryUrl = ServerBrowser.DefaultDirectoryUrl;
private string _publicHostOverride = "auto";
@ -64,6 +70,7 @@ public partial class Main : Node3D
private readonly List<ISimEvent> _frameEvents = new(128);
private readonly List<FootstepPulse> _frameFootsteps = new(32);
private ArenaMapKind _mapKind = ArenaMapKind.Sion;
private byte _squadSize = 3;
private string _callsign = "Pilot";
private string _lastEndpoint = $"127.0.0.1:{DefaultNetPort}";
@ -102,6 +109,7 @@ public partial class Main : Node3D
private readonly List<double> _perfNodeCount = new();
private readonly List<double> _perfTimeProcess = new();
private readonly List<double> _perfTimePhysicsProcess = new();
private readonly List<double> _perfViewportGpuMs = new();
private double _perfPendingStepMs;
private double _perfPendingTerrainMs;
private double _perfPendingArenaMs;
@ -112,6 +120,7 @@ public partial class Main : Node3D
public ClientScreenMode ScreenMode => _screenMode;
public TerrainRenderer Terrain => _terrain;
public SionMapRenderer SionMap => _sionMap;
public FoliageRenderer Foliage => _foliage;
public ArenaRenderer Arena => _arena;
public ArenaAudioSystem Audio => _audio;
public WalkerFootstepTracker Footsteps => _footsteps;
@ -120,6 +129,8 @@ public partial class Main : Node3D
public Hud Hud => _hud;
public AtmosphereSystem Atmosphere => _atmosphere;
public MainMenu MainMenuOverlay => _mainMenu;
public SettingsOverlay SettingsOverlay => _settingsOverlay;
public GraphicsSettings GraphicsSettings => _graphicsSettings;
public ServerBrowser ServerBrowserOverlay => _serverBrowser;
public LobbyScreen LobbyOverlay => _lobbyScreen;
public ArenaMapKind MapKind => _mapKind;
@ -135,10 +146,16 @@ public partial class Main : Node3D
public override void _Ready()
{
ClientAssets.EnsureAssetsRootRegistered();
GetViewport().UseTaa = true;
_graphicsSettings = GraphicsSettings.Load(ResolveGraphicsSettingsPath());
ApplyGraphicsEnvOverrides(_graphicsSettings);
_graphicsSettings.Changed += OnGraphicsSettingsChanged;
_atmosphere = new AtmosphereSystem { Name = "AtmosphereSystem" };
AddChild(_atmosphere);
_atmosphere.EnsureInitialized();
_atmosphere.ApplyGraphicsSettings(_graphicsSettings);
_terrain = new TerrainRenderer { Name = "Terrain" };
AddChild(_terrain);
@ -146,9 +163,13 @@ public partial class Main : Node3D
_sionMap = new SionMapRenderer { Name = "SionMap" };
AddChild(_sionMap);
_foliage = new FoliageRenderer { Name = "Foliage" };
AddChild(_foliage);
_arena = new ArenaRenderer { Name = "Arena" };
AddChild(_arena);
_arena.AssetCache.PreloadAll();
_atmosphere.BindEmitterPool(_arena.Volumetrics);
_audio = new ArenaAudioSystem { Name = "ArenaAudio" };
AddChild(_audio);
@ -158,11 +179,11 @@ public partial class Main : Node3D
Name = "ShoulderCamera",
Current = true,
Fov = 58f,
Far = 4200f
Far = 4800f
};
AddChild(_camera);
_hud = new Hud(() => _session, OnEquipCargo, () => _cameraYaw) { Name = "Hud" };
_hud = new Hud(() => _session, OnEquipCargo, () => _cameraYaw, ProjectWorldToHud) { Name = "Hud" };
_hud.JoinRequested += OnJoinRequested;
_hud.HostRequested += OnHostRequested;
_hud.SoloRequested += OnSoloRequested;
@ -187,8 +208,22 @@ public partial class Main : Node3D
}
};
_mainMenu.ReturnToMainMenuRequested += ReturnToMainMenu;
_mainMenu.SettingsRequested += OpenSettingsFromCurrentScreen;
AddChild(_mainMenu);
_settingsOverlay = new SettingsOverlay { Name = "SettingsOverlay" };
_settingsOverlay.SetGraphicsValues(
_graphicsSettings.VfxResolution,
_graphicsSettings.VolumetricSamples,
_graphicsSettings.SdfgiQuality,
_graphicsSettings.BorderlessFullscreen);
_settingsOverlay.GraphicsChanged += (res, samples, sdfgi, fullscreen) =>
_graphicsSettings.Apply(res, samples, sdfgi, fullscreen, persist: !IsAutomatedRun);
_settingsOverlay.ResetDefaultsRequested += () =>
_graphicsSettings.ResetToDefaults(persist: !IsAutomatedRun);
_settingsOverlay.BackRequested += CloseSettings;
AddChild(_settingsOverlay);
_serverBrowser = new ServerBrowser { Name = "ServerBrowser" };
_serverBrowser.JoinRequested += OnBrowserJoinRequested;
_serverBrowser.HostRequested += () =>
@ -226,6 +261,11 @@ public partial class Main : Node3D
string? cliName = GetCliArg("--name");
string? cliMap = GetCliArg("--map");
string? cliSeed = GetCliArg("--seed");
string? cliSquadSize = GetCliArg("--squad-size");
if (int.TryParse(cliSquadSize ?? System.Environment.GetEnvironmentVariable("RTD_SQUAD_SIZE"), NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsedSquad))
{
_squadSize = (byte)Math.Clamp(parsedSquad, 1, 4);
}
bool cliSolo = GetCliArg("--solo", allowBareFlag: true) is not null
|| System.Environment.GetEnvironmentVariable("RTD_SOLO") == "1";
bool cliLobby = GetCliArg("--lobby", allowBareFlag: true) is not null
@ -291,13 +331,22 @@ public partial class Main : Node3D
: $"127.0.0.1:{hostTarget.Trim()}";
}
_hud.SetNetworkDefaults(_lastEndpoint, _callsign);
_mainMenu.SetDefaults(_callsign, _directoryUrl, _mapKind, DefaultNetPort);
_mainMenu.SetDefaults(_callsign, _directoryUrl, _mapKind, DefaultNetPort, _squadSize);
_serverBrowser.Configure(_directoryUrl, _callsign, _lastEndpoint);
if (int.TryParse(System.Environment.GetEnvironmentVariable("RTD_PERF_FRAMES"), out int perfFrames) && perfFrames > 0)
{
_perfTargetFrames = perfFrames;
ArenaSession.PerfEnabled = true;
RenderingServer.ViewportSetMeasureRenderTime(GetViewport().GetViewportRid(), true);
if (_atmosphere.VolumetricEffect is not null)
{
_atmosphere.VolumetricEffect.ProfilingEnabled = true;
}
if (_hud?.HbCanvas is not null)
{
_hud.HbCanvas.ProfilingEnabled = true;
}
}
else if (int.TryParse(System.Environment.GetEnvironmentVariable("RTD_AUTO_EXIT_FRAMES"), out int autoExitFrames) && autoExitFrames > 0)
{
@ -310,6 +359,28 @@ public partial class Main : Node3D
}
_menuPreviewOut = System.Environment.GetEnvironmentVariable("RTD_MENU_PREVIEW_OUT");
_hasWindowOverride = GetCliArg("--windowed", allowBareFlag: true) is not null
|| GetCliArg("--resolution", allowBareFlag: true) is not null
|| GetCliArg("-w", allowBareFlag: true) is not null;
if (!IsAutomatedRun && !_hasWindowOverride)
{
ApplyWindowMode(_graphicsSettings.BorderlessFullscreen);
}
else
{
if (IsAutomatedRun && DisplayServer.GetName() != "headless")
{
DisplayServer.WindowSetFlag(DisplayServer.WindowFlags.NoFocus, true);
}
if (_hasWindowOverride && DisplayServer.GetName() != "headless")
{
var winMode = DisplayServer.WindowGetMode();
bool actualFullscreen = winMode == DisplayServer.WindowMode.Fullscreen
|| winMode == DisplayServer.WindowMode.ExclusiveFullscreen;
_graphicsSettings.SetBorderlessFullscreen(actualFullscreen, persist: false);
}
}
bool perfCombat = _perfTargetFrames > 0 && System.Environment.GetEnvironmentVariable("RTD_PERF_COMBAT") == "1";
bool skipInitialDrop = InitialSkipDropOverride || perfCombat;
bool autoBypassMenu = InitialMapKindOverride.HasValue
@ -419,13 +490,17 @@ public partial class Main : Node3D
DisposeSessionAndDirectory();
}
public void Reset(int seed, ArenaMapKind? mapKind = null, bool skipInitialDrop = false)
public void Reset(int seed, ArenaMapKind? mapKind = null, bool skipInitialDrop = false, byte? squadSize = null)
{
_seed = seed;
if (mapKind.HasValue)
{
_mapKind = mapKind.Value;
}
if (squadSize.HasValue)
{
_squadSize = (byte)Math.Clamp((int)squadSize.Value, 1, 4);
}
DisposeSessionAndDirectory();
Failure = null;
@ -433,7 +508,7 @@ public partial class Main : Node3D
try
{
_session = new LocalArenaSession(seed, _mapKind, _callsign, skipInitialDrop);
_session = new LocalArenaSession(seed, _mapKind, _callsign, skipInitialDrop, squadSize: _squadSize);
SetScreenMode(ClientScreenMode.InMatch);
BindSessionPresentation(resetCamera: true);
}
@ -450,7 +525,7 @@ public partial class Main : Node3D
Failure = null;
_hud.SetNetworkError(null);
EnsureMenuSionBackdrop();
_mainMenu.SetDefaults(_callsign, _directoryUrl, _mapKind, DefaultNetPort);
_mainMenu.SetDefaults(_callsign, _directoryUrl, _mapKind, DefaultNetPort, _squadSize);
_mainMenu.SetHostPanelOpen(false);
SetScreenMode(ClientScreenMode.MainMenu);
}
@ -483,23 +558,29 @@ public partial class Main : Node3D
private void EnsureMenuSionBackdrop()
{
_menuSionData ??= SionMapLoader.Load();
_menuSionTerrain ??= TerrainField.LoadHeightmap(
_menuSionTerrain ??= TerrainField.LoadSharedHeightmap(
_menuSionData.Metadata.SizeMeters,
_menuSionData.Metadata.GridRes,
_menuSionData.Heights,
_menuSionData.Metadata.TileGrid,
_menuSionData.BaseDem,
_menuSionData.BaseDemMinY,
_menuSionData.BaseDemScale,
_menuSionData.Metadata.MinY,
_menuSionData.Metadata.MaxY,
42UL);
_terrain.Visible = false;
_terrain.Visible = true;
_sionMap.Visible = true;
_arena.Visible = false;
_dropReticleMesh.Visible = false;
_camera.Far = 4200f;
_atmosphere.ApplyMap(ArenaMapKind.Sion);
_sionMap.EnsureBuilt(_menuSionData, _menuSionTerrain);
_sionMap.EnsureBuilt(_menuSionData);
UpdateLobbyOrMenuOrbitCamera(ArenaMapKind.Sion, _menuSionTerrain);
_terrain.UpdateTileLod(_camera.GlobalPosition);
_terrain.Sync(_menuSionTerrain, _menuSionData);
_sionMap.UpdateLod(_camera.GlobalPosition);
_foliage.SyncBackdrop(_menuSionData, _camera.GlobalPosition);
}
private void UpdateLobbyOrMenuOrbitCamera(ArenaMapKind mapKind, TerrainField terrain)
@ -526,7 +607,9 @@ public partial class Main : Node3D
switch (mode)
{
case ClientScreenMode.MainMenu:
_hud.SetInputBlocked(true);
_hud.SetMatchHudActive(false);
_settingsOverlay.SetSettingsVisible(false);
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(false);
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.MainMenu);
@ -535,7 +618,9 @@ public partial class Main : Node3D
break;
case ClientScreenMode.ServerBrowser:
_hud.SetInputBlocked(true);
_hud.SetMatchHudActive(false);
_settingsOverlay.SetSettingsVisible(false);
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden);
_lobbyScreen.SetLobbyVisible(false);
_serverBrowser.Configure(_directoryUrl, _callsign, _lastEndpoint);
@ -545,7 +630,9 @@ public partial class Main : Node3D
break;
case ClientScreenMode.Lobby:
_hud.SetInputBlocked(true);
_hud.SetMatchHudActive(false);
_settingsOverlay.SetSettingsVisible(false);
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden);
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(true);
@ -554,21 +641,44 @@ public partial class Main : Node3D
break;
case ClientScreenMode.InMatch:
_settingsOverlay.SetSettingsVisible(false);
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden);
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(false);
_arena.Visible = true;
_hud.SetMatchHudActive(true);
_hud.SetInputBlocked(false);
break;
case ClientScreenMode.PauseOverlay:
_settingsOverlay.SetSettingsVisible(false);
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(false);
_arena.Visible = true;
_hud.SetMatchHudActive(true);
_hud.SetInputBlocked(true);
_mainMenu.SetPauseContext(BuildPauseContextLine());
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.PauseOverlay);
break;
case ClientScreenMode.Settings:
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden);
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(false);
bool showMatchBehind = _settingsReturnMode == ClientScreenMode.PauseOverlay;
_arena.Visible = showMatchBehind;
_hud.SetMatchHudActive(showMatchBehind);
if (!showMatchBehind)
{
_dropReticleMesh.Visible = false;
}
_settingsOverlay.SetGraphicsValues(
_graphicsSettings.VfxResolution,
_graphicsSettings.VolumetricSamples,
_graphicsSettings.SdfgiQuality,
_graphicsSettings.BorderlessFullscreen);
_settingsOverlay.SetSettingsVisible(true);
break;
}
SyncMouseMode();
}
@ -593,10 +703,13 @@ public partial class Main : Node3D
string serverName,
bool startInLobby,
bool listOnPublicDirectory,
bool fallbackToLocalOnFailure)
bool fallbackToLocalOnFailure,
byte? squadSize = null)
{
string nextCallsign = string.IsNullOrWhiteSpace(callsign) ? "Host" : callsign.Trim();
string cleanServerName = string.IsNullOrWhiteSpace(serverName) ? "Rust to Dust" : serverName.Trim();
byte activeSquadSize = (byte)Math.Clamp((int)(squadSize ?? _squadSize), 1, 4);
_squadSize = activeSquadSize;
Failure = null;
_hud.SetNetworkError(null);
_mainMenu.SetHostError(null);
@ -612,7 +725,8 @@ public partial class Main : Node3D
mapKind,
startInLobby: startInLobby,
serverName: cleanServerName,
minHumansToStart: 1);
minHumansToStart: 1,
squadSize: activeSquadSize);
hostSession.Host.Session.SetHumanSlot(0, true, nextCallsign);
DisposeSessionAndDirectory();
@ -641,7 +755,7 @@ public partial class Main : Node3D
Failure = ex.Message;
if (fallbackToLocalOnFailure && _session is null)
{
_session = new LocalArenaSession(_seed, _mapKind, _callsign);
_session = new LocalArenaSession(_seed, _mapKind, _callsign, squadSize: _squadSize);
SetScreenMode(ClientScreenMode.InMatch);
BindSessionPresentation(resetCamera: false);
}
@ -677,7 +791,7 @@ public partial class Main : Node3D
Failure = ex.Message;
if (!fromBrowser && _session is null && _screenMode == ClientScreenMode.InMatch)
{
_session = new LocalArenaSession(_seed, _mapKind, _callsign);
_session = new LocalArenaSession(_seed, _mapKind, _callsign, squadSize: _squadSize);
SetScreenMode(ClientScreenMode.InMatch);
BindSessionPresentation(resetCamera: false);
}
@ -737,11 +851,12 @@ public partial class Main : Node3D
}
}
private void OnMainMenuPlaySolo(ArenaMapKind mapKind, string callsign)
private void OnMainMenuPlaySolo(ArenaMapKind mapKind, string callsign, byte squadSize)
{
_callsign = string.IsNullOrWhiteSpace(callsign) ? "Pilot" : callsign.Trim();
_squadSize = (byte)Math.Clamp((int)squadSize, 1, 4);
_hud.SetNetworkDefaults(_lastEndpoint, _callsign);
Reset(_seed, mapKind, skipInitialDrop: false);
Reset(_seed, mapKind, skipInitialDrop: false, squadSize: _squadSize);
}
private void OnMainMenuServerBrowser(string callsign)
@ -751,10 +866,11 @@ public partial class Main : Node3D
SetScreenMode(ClientScreenMode.ServerBrowser);
}
private void OnMainMenuHostLobby(int port, string serverName, ArenaMapKind mapKind, bool listOnPublicDirectory, string callsign)
private void OnMainMenuHostLobby(int port, string serverName, ArenaMapKind mapKind, bool listOnPublicDirectory, string callsign, byte squadSize)
{
string? envBind = System.Environment.GetEnvironmentVariable("RTD_BIND");
string hostArg = !string.IsNullOrWhiteSpace(envBind) ? $"{envBind.Trim()}:{port}" : port.ToString(CultureInfo.InvariantCulture);
_squadSize = (byte)Math.Clamp((int)squadSize, 1, 4);
StartListenHostSession(
hostArg,
callsign,
@ -762,7 +878,8 @@ public partial class Main : Node3D
serverName,
startInLobby: true,
listOnPublicDirectory: listOnPublicDirectory,
fallbackToLocalOnFailure: false);
fallbackToLocalOnFailure: false,
squadSize: _squadSize);
}
private void OnBrowserJoinRequested(string endpointText, string callsign)
@ -810,7 +927,7 @@ public partial class Main : Node3D
_prevLocalLifecycle = p.Lifecycle;
if (p.IsInDropPod)
{
_cameraPitch = Mathf.DegToRad(36f);
_cameraPitch = Mathf.DegToRad(34f);
_orbitalPodCamBlend = 1.0f;
}
else
@ -833,16 +950,20 @@ public partial class Main : Node3D
_audio.ResetForSession(_session);
}
_camera.Far = _mapKind == ArenaMapKind.Sion ? 4200f : 1800f;
_camera.Far = _mapKind == ArenaMapKind.Sion ? 4800f : 2600f;
_atmosphere.ApplyMap(_mapKind);
bool inLobby = _screenMode == ClientScreenMode.Lobby || state.Phase == MatchPhase.Lobby;
_terrain.Visible = true;
_terrain.InvalidateAll();
_terrain.UpdateTileLod(_camera.GlobalPosition);
_terrain.Sync(state.Terrain, state.SionMap);
if (_mapKind == ArenaMapKind.Sion && state.SionMap is not null)
{
_terrain.Visible = false;
_sionMap.Visible = true;
_sionMap.EnsureBuilt(state.SionMap, state.Terrain);
_sionMap.EnsureBuilt(state.SionMap);
if (!inLobby)
{
_arena.Sync(_session, _elapsedSeconds, 0f, 1f);
@ -852,14 +973,14 @@ public partial class Main : Node3D
{
UpdateLobbyOrMenuOrbitCamera(_mapKind, state.Terrain);
}
_terrain.UpdateTileLod(_camera.GlobalPosition);
_sionMap.UpdateLod(_camera.GlobalPosition);
_foliage.Sync(state, _camera.GlobalPosition);
}
else
{
_sionMap.Visible = false;
_terrain.Visible = true;
_terrain.InvalidateAll();
_terrain.Sync(state.Terrain);
_foliage.Visible = false;
if (!inLobby)
{
_arena.Sync(_session, _elapsedSeconds, 0f, 1f);
@ -878,6 +999,7 @@ public partial class Main : Node3D
Vector3 startVec = new(localStart.X, localStart.Y, localStart.Z);
Vector3 startFwd = new(MathF.Sin(localStart.Yaw), 0f, MathF.Cos(localStart.Yaw));
_arena.Particles.PrewarmFlashLights(startVec, startFwd);
_arena.GpuSparks.Prewarm(startVec);
_arena.PomDecals.PrewarmShader(startVec);
_hud.Sync(_session);
}
@ -888,10 +1010,166 @@ public partial class Main : Node3D
SyncMouseMode();
}
private bool IsAutomatedRun =>
DisplayServer.GetName() == "headless"
|| InitialMapKindOverride.HasValue
|| InitialSkipDropOverride
|| InitialSkipMenuOverride
|| _perfTargetFrames > 0
|| _menuPreviewTargetFrames > 0
|| string.Equals(GetCliArg("--audio-driver"), "Dummy", StringComparison.OrdinalIgnoreCase)
|| GetCliArg("--script", allowBareFlag: true) is not null
|| !string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("RTD_NO_CAPTURE"))
|| !string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("RTD_PERF_FRAMES"))
|| !string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("RTD_AUTO_EXIT_FRAMES"))
|| !string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("RTD_MENU_EXIT_FRAMES"));
public override void _Notification(int what)
{
if (what == NotificationApplicationFocusOut || what == NotificationWMWindowFocusOut)
{
Input.MouseMode = Input.MouseModeEnum.Visible;
}
else if (what == NotificationApplicationFocusIn || what == NotificationWMWindowFocusIn)
{
if (IsInsideTree())
{
SyncMouseMode();
}
}
}
private void OpenSettingsFromCurrentScreen()
{
if (_screenMode == ClientScreenMode.PauseOverlay || _screenMode == ClientScreenMode.MainMenu)
{
_settingsReturnMode = _screenMode;
}
SetScreenMode(ClientScreenMode.Settings);
}
private void CloseSettings()
{
if (_screenMode == ClientScreenMode.Settings)
{
SetScreenMode(_settingsReturnMode);
}
}
private void OnGraphicsSettingsChanged(GraphicsSettings settings)
{
_atmosphere.ApplyGraphicsSettings(settings);
_settingsOverlay?.SetGraphicsValues(
settings.VfxResolution,
settings.VolumetricSamples,
settings.SdfgiQuality,
settings.BorderlessFullscreen);
if (!IsAutomatedRun && DisplayServer.GetName() != "headless")
{
ApplyWindowMode(settings.BorderlessFullscreen);
}
}
private static string? ResolveGraphicsSettingsPath()
{
try
{
return ProjectSettings.GlobalizePath("user://" + GraphicsSettings.DefaultFileName);
}
catch
{
return null;
}
}
private static void ApplyGraphicsEnvOverrides(GraphicsSettings settings)
{
string? resEnv = System.Environment.GetEnvironmentVariable("RTD_VFX_RES");
if (!string.IsNullOrWhiteSpace(resEnv))
{
VfxResolutionScale? parsed = resEnv.Trim().ToLowerInvariant() switch
{
"half" or "0.5" or "0.5x" => VfxResolutionScale.Half,
"threequarter" or "three_quarter" or "high" or "0.75" or "0.75x" => VfxResolutionScale.ThreeQuarter,
"full" or "1.0" or "1.0x" or "native" => VfxResolutionScale.Full,
_ => null
};
if (parsed.HasValue)
{
settings.SetVfxResolution(parsed.Value, persist: false);
}
}
string? samplesEnv = System.Environment.GetEnvironmentVariable("RTD_VFX_SAMPLES");
if (!string.IsNullOrWhiteSpace(samplesEnv))
{
VolumetricSamples? parsed = samplesEnv.Trim().ToLowerInvariant() switch
{
"low" or "8" => VolumetricSamples.Low,
"medium" or "10" => VolumetricSamples.Medium,
"high" or "16" => VolumetricSamples.High,
"ultra" or "24" => VolumetricSamples.Ultra,
_ => null
};
if (parsed.HasValue)
{
settings.SetVolumetricSamples(parsed.Value, persist: false);
}
}
string? sdfgiEnv = System.Environment.GetEnvironmentVariable("RTD_SDFGI_QUALITY");
if (!string.IsNullOrWhiteSpace(sdfgiEnv))
{
SdfgiQuality? parsed = sdfgiEnv.Trim().ToLowerInvariant() switch
{
"off" => SdfgiQuality.Off,
"balanced" => SdfgiQuality.Balanced,
"high" => SdfgiQuality.High,
_ => null
};
if (parsed.HasValue)
{
settings.SetSdfgiQuality(parsed.Value, persist: false);
}
}
}
private static void ApplyWindowMode(bool borderlessFullscreen)
{
if (DisplayServer.GetName() == "headless")
{
return;
}
var current = DisplayServer.WindowGetMode();
bool isFullscreen = current == DisplayServer.WindowMode.Fullscreen || current == DisplayServer.WindowMode.ExclusiveFullscreen;
if (isFullscreen != borderlessFullscreen)
{
DisplayServer.WindowSetMode(borderlessFullscreen ? DisplayServer.WindowMode.Fullscreen : DisplayServer.WindowMode.Windowed);
}
}
private void ToggleBorderlessFullscreen()
{
if (IsAutomatedRun || DisplayServer.GetName() == "headless")
{
return;
}
var mode = DisplayServer.WindowGetMode();
bool nextFullscreen = !(mode == DisplayServer.WindowMode.Fullscreen || mode == DisplayServer.WindowMode.ExclusiveFullscreen);
DisplayServer.WindowSetMode(nextFullscreen ? DisplayServer.WindowMode.Fullscreen : DisplayServer.WindowMode.Windowed);
_graphicsSettings.SetBorderlessFullscreen(nextFullscreen, persist: !IsAutomatedRun);
}
private void SyncMouseMode()
{
if (DisplayServer.GetName() == "headless" || _perfTargetFrames > 0)
if (IsAutomatedRun)
{
Input.MouseMode = Input.MouseModeEnum.Visible;
return;
}
if (!IsInsideTree() || GetWindow() is not { } win || !win.HasFocus())
{
Input.MouseMode = Input.MouseModeEnum.Visible;
return;
}
if (_screenMode != ClientScreenMode.InMatch)
@ -905,10 +1183,10 @@ public partial class Main : Node3D
private static string? GetCliArg(string flag, bool allowBareFlag = false)
{
static string? SearchArgs(string[] args, string flagName, bool bare)
static string? SearchArgs(string[] args, string flagName, bool bare, int startIndex = 0)
{
string prefix = flagName + "=";
for (int i = 0; i < args.Length; i++)
for (int i = startIndex; i < args.Length; i++)
{
string a = args[i];
if (a.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
@ -931,7 +1209,8 @@ public partial class Main : Node3D
}
return SearchArgs(OS.GetCmdlineUserArgs(), flag, allowBareFlag)
?? SearchArgs(OS.GetCmdlineArgs(), flag, allowBareFlag);
?? SearchArgs(OS.GetCmdlineArgs(), flag, allowBareFlag)
?? SearchArgs(System.Environment.GetCommandLineArgs(), flag, allowBareFlag, startIndex: 1);
}
private static void ParseBindAndPort(string? raw, IPAddress defaultIp, int defaultPort, out IPAddress bindIp, out int port)
@ -1013,6 +1292,21 @@ public partial class Main : Node3D
public void SetScriptedInput(PlayerInput? input) => _scriptedInput = input;
public override void _Input(InputEvent @event)
{
if (@event is InputEventKey key && key.Pressed && !key.Echo)
{
bool isAltEnter = (key.Keycode == Key.Enter || key.Keycode == Key.KpEnter)
&& key.AltPressed && !key.CtrlPressed && !key.ShiftPressed;
bool isF11 = key.Keycode == Key.F11 && !key.AltPressed && !key.CtrlPressed && !key.ShiftPressed;
if (isAltEnter || isF11)
{
ToggleBorderlessFullscreen();
GetViewport().SetInputAsHandled();
}
}
}
public override void _UnhandledInput(InputEvent @event)
{
if (@event is InputEventKey key && key.Pressed && !key.Echo)
@ -1045,6 +1339,14 @@ public partial class Main : Node3D
}
return;
}
if (_screenMode == ClientScreenMode.Settings)
{
if (key.Keycode == Key.Escape)
{
CloseSettings();
}
return;
}
if (key.Keycode == Key.F9)
{
@ -1125,10 +1427,9 @@ public partial class Main : Node3D
Input.MouseMode == Input.MouseModeEnum.Visible &&
!_hud.GarageExpanded &&
!_hud.NetworkPanelOpen &&
!_hud.IsPointerOverInteractiveHud(mb.Position) &&
DisplayServer.GetName() != "headless")
!_hud.IsPointerOverInteractiveHud(mb.Position))
{
Input.MouseMode = Input.MouseModeEnum.Captured;
SyncMouseMode();
}
}
}
@ -1237,18 +1538,13 @@ public partial class Main : Node3D
{
_frameEvents.Clear();
_session.DrainSimEvents(_frameEvents);
if (_mapKind == ArenaMapKind.Desert)
{
_terrain.Sync(_session.ViewState.Terrain);
}
UpdateLobbyOrMenuOrbitCamera(_mapKind, _session.ViewState.Terrain);
_terrain.UpdateTileLod(_camera.GlobalPosition);
_terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap);
if (_mapKind == ArenaMapKind.Sion)
{
_sionMap.UpdateLod(_camera.GlobalPosition);
}
else
{
_terrain.UpdateTileLod(_camera.GlobalPosition);
_foliage.Sync(_session.ViewState, _camera.GlobalPosition);
}
_lobbyScreen.Sync(_session);
return;
@ -1264,10 +1560,8 @@ public partial class Main : Node3D
}
double toMs = 1000.0 / Stopwatch.Frequency;
long tt0 = Stopwatch.GetTimestamp();
if (_mapKind == ArenaMapKind.Desert)
{
_terrain.Sync(_session.ViewState.Terrain);
}
_terrain.UpdateTileLod(_camera.GlobalPosition);
_terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap);
long tt1 = Stopwatch.GetTimestamp();
_arena.Sync(_session, _elapsedSeconds, (float)delta, alpha);
DrainAndFanSimEvents((float)delta, alpha);
@ -1278,13 +1572,11 @@ public partial class Main : Node3D
long tc0 = Stopwatch.GetTimestamp();
UpdateCamera((float)delta, alpha);
_audio.UpdateFrame(_session, _frameEvents, _frameFootsteps, _camera.GlobalPosition, (float)delta, alpha);
_terrain.UpdateTileLod(_camera.GlobalPosition);
if (_mapKind == ArenaMapKind.Sion)
{
_sionMap.UpdateLod(_camera.GlobalPosition);
}
else
{
_terrain.UpdateTileLod(_camera.GlobalPosition);
_foliage.Sync(_session.ViewState, _camera.GlobalPosition);
}
long th0 = Stopwatch.GetTimestamp();
var localP = _session.LocalContender;
@ -1318,6 +1610,10 @@ public partial class Main : Node3D
_perfNodeCount.Add(Performance.GetMonitor(Performance.Monitor.ObjectNodeCount));
_perfTimeProcess.Add(Performance.GetMonitor(Performance.Monitor.TimeProcess) * 1000.0);
_perfTimePhysicsProcess.Add(Performance.GetMonitor(Performance.Monitor.TimePhysicsProcess) * 1000.0);
if (ArenaSession.PerfEnabled)
{
_perfViewportGpuMs.Add(RenderingServer.ViewportGetMeasuredRenderTimeGpu(GetViewport().GetViewportRid()));
}
_perfFrameCount++;
if (_perfFrameCount >= _perfTargetFrames)
@ -1327,21 +1623,17 @@ public partial class Main : Node3D
}
else
{
if (_mapKind == ArenaMapKind.Desert)
{
_terrain.Sync(_session.ViewState.Terrain);
}
_terrain.UpdateTileLod(_camera.GlobalPosition);
_terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap);
_arena.Sync(_session, _elapsedSeconds, (float)delta, alpha);
DrainAndFanSimEvents((float)delta, alpha);
UpdateCamera((float)delta, alpha);
_audio.UpdateFrame(_session, _frameEvents, _frameFootsteps, _camera.GlobalPosition, (float)delta, alpha);
_terrain.UpdateTileLod(_camera.GlobalPosition);
if (_mapKind == ArenaMapKind.Sion)
{
_sionMap.UpdateLod(_camera.GlobalPosition);
}
else
{
_terrain.UpdateTileLod(_camera.GlobalPosition);
_foliage.Sync(_session.ViewState, _camera.GlobalPosition);
}
var localP = _session.LocalContender;
float coreRatio = localP.Grid.MaxCoreHp > 0f ? localP.Grid.CoreHp / localP.Grid.MaxCoreHp : 1f;
@ -1381,7 +1673,7 @@ public partial class Main : Node3D
var local = _session.LocalContender;
if (local.Lifecycle == ContenderLifecycle.Deploying && _prevLocalLifecycle != ContenderLifecycle.Deploying)
{
_cameraPitch = Mathf.DegToRad(36f);
_cameraPitch = Mathf.DegToRad(34f);
_orbitalPodCamBlend = 1.0f;
}
_prevLocalLifecycle = local.Lifecycle;
@ -1389,28 +1681,34 @@ public partial class Main : Node3D
var localPos = new System.Numerics.Vector3(local.X, local.Y, local.Z);
_camJuice.ConsumeEvents(_frameEvents, _session.LocalContenderId, localPos, _session);
_camJuice.ConsumeFootsteps(_frameFootsteps, _session.LocalContenderId);
OrbitalPodPhase localPodPhase = OrbitalPodPhase.Freefall;
float camHorizSpeed = local.Speed;
if (local.IsInDropPod)
{
var pods = _session.ActivePods;
for (int i = 0; i < pods.Count; i++)
{
if (pods[i].PodKind == OrbitalPodKind.Contender &&
pods[i].ContenderId == _session.LocalContenderId &&
pods[i].Phase == OrbitalPodPhase.RetroBurn)
pods[i].ContenderId == _session.LocalContenderId)
{
_camJuice.ApplyOrbitalBurnRumble(1.0f);
localPodPhase = pods[i].Phase;
camHorizSpeed = MathF.Sqrt(pods[i].VelX * pods[i].VelX + pods[i].VelZ * pods[i].VelZ);
if (pods[i].Phase == OrbitalPodPhase.RetroBurn)
{
_camJuice.ApplyOrbitalBurnRumble(1.0f);
}
break;
}
}
}
_camJuice.Update(dt, local.Speed, local.Grid.Spec.IsVtol);
_camJuice.Update(dt, camHorizSpeed, local.Grid.Spec.IsVtol, local.IsInDropPod, localPodPhase);
}
private static readonly Color DesertDustTint = new(0.76f, 0.59f, 0.40f, 1.0f);
internal Color SampleCurrentMapGroundTint(float worldX, float worldZ) =>
_mapKind == ArenaMapKind.Sion
? _sionMap.SampleGroundTint(worldX, worldZ)
? _terrain.SampleGroundTint(worldX, worldZ)
: DesertDustTint;
private System.Numerics.Vector3? ResolveLiveWalkerFootWorld(bool isContender, int id, int legIndex)
@ -1467,7 +1765,7 @@ public partial class Main : Node3D
double steadyFps = steadyAvgMs > 0 ? 1000.0 / steadyAvgMs : 0;
GD.Print("=== PERF BENCHMARK SUMMARY ===");
GD.Print($"Frames={_perfFrameMs.Count} PhysicsTicks={_perfPhysicsTicks} AvgFPS={fps:F2} SteadyFPS(10..59)={steadyFps:F2} EngineFPS={Engine.GetFramesPerSecond():F1}");
GD.Print($"Frames={_perfFrameMs.Count} PhysicsTicks={_perfPhysicsTicks} AvgFPS={fps:F2} SteadyFPS(10..{_perfFrameMs.Count - 1})={steadyFps:F2} EngineFPS={Engine.GetFramesPerSecond():F1}");
GD.Print($"frameMs: avg={Avg(_perfFrameMs):F2} steadyAvg={steadyAvgMs:F2} p95={P95(_perfFrameMs):F2}");
GD.Print($"physicsStepMs/frame: avg={Avg(_perfPhysicsStepMs):F2} p95={P95(_perfPhysicsStepMs):F2}");
GD.Print($"terrainSyncMs/frame: avg={Avg(_perfTerrainSyncMs):F2} p95={P95(_perfTerrainSyncMs):F2} dirtyRebakesTotal={rebakeTotal} dirtyRebakesAvg={rebakeAvg:F2}");
@ -1482,7 +1780,28 @@ public partial class Main : Node3D
GD.Print($"UpdateCameraMs/frame: avg={_perfCamMsSum / _perfFrameMs.Count:F2}");
int ticks = Math.Max(1, _perfPhysicsTicks);
GD.Print($"StepBreakdownMs/tick: ring={ArenaSession.PerfRingMs / ticks:F2} ai={ArenaSession.PerfAiMs / ticks:F2} drive={ArenaSession.PerfDriveMs / ticks:F2} world={ArenaSession.PerfWorldMs / ticks:F2} sync={ArenaSession.PerfBodySyncMs / ticks:F2} detect={ArenaSession.PerfDetectMs / ticks:F2} weapons={ArenaSession.PerfWeaponsMs / ticks:F2}");
GD.Print($"CombatProbes: syncDamageHeatMsTotal={VehicleVisualInstance.PerfDamageHeatMs:F2} matDups={VehicleVisualInstance.PerfMaterialDupCount} bakeTileMsTotal={TerrainRenderer.PerfBakeTileMs:F2} bakeTileCalls={TerrainRenderer.PerfBakeTileCalls} debrisActive={_arena.Debris.ActiveCount} particlesActive={_arena.Particles.ActiveParticleCount} flashLightsPeak={_arena.Particles.PeakFlashLightCount} tracers={_session?.ViewState.Tracers.Count ?? 0}");
GD.Print($"CombatProbes: syncDamageHeatMsTotal={VehicleVisualInstance.PerfDamageHeatMs:F2} matDups={VehicleVisualInstance.PerfMaterialDupCount} bakeTileMsTotal={TerrainRenderer.PerfBakeTileMs:F2} bakeTileCalls={TerrainRenderer.PerfBakeTileCalls} debrisActive={_arena.Debris.ActiveCount} gpuSparksEmitted={_arena.GpuSparks.TotalEmittedCount} volEmitters={_arena.Volumetrics.ActiveEmitterCount} volImpulses={_arena.Volumetrics.ActiveImpulseCount} flashLightsPeak={_arena.Particles.PeakFlashLightCount} tracers={_session?.ViewState.Tracers.Count ?? 0}");
if (_atmosphere.VolumetricEffect is { } volFx)
{
Rid vpRid = GetViewport().GetViewportRid();
double vpGpuMs = RenderingServer.ViewportGetMeasuredRenderTimeGpu(vpRid);
double vpCpuMs = RenderingServer.ViewportGetMeasuredRenderTimeCpu(vpRid);
GD.Print($"Cut10bGpuMs: total={volFx.LastTotalGpuMs:F3} flow={volFx.LastFlowGpuMs:F3} cull={volFx.LastCullGpuMs:F3} march={volFx.LastMarchGpuMs:F3} comp={volFx.LastCompGpuMs:F3} marchSize={volFx.LastMarchSize.X}x{volFx.LastMarchSize.Y} maxSteps={volFx.CurrentMaxSteps} maxIter={volFx.CurrentMaxIter} vfxRes={_graphicsSettings.VfxResolution} volSamples={_graphicsSettings.VolumetricSamples} sdfgi={_graphicsSettings.SdfgiQuality} viewportGpuMs={vpGpuMs:F2} viewportCpuMs={vpCpuMs:F2}");
if (_perfViewportGpuMs.Count > 10)
{
var steadyGpu = new List<double>(_perfViewportGpuMs.Count - 10);
for (int i = 10; i < _perfViewportGpuMs.Count; i++) steadyGpu.Add(_perfViewportGpuMs[i]);
steadyGpu.Sort();
double gpuP50 = steadyGpu[(int)Math.Clamp(Math.Floor(steadyGpu.Count * 0.50), 0, steadyGpu.Count - 1)];
double gpuP95 = steadyGpu[(int)Math.Clamp(Math.Ceiling(steadyGpu.Count * 0.95) - 1, 0, steadyGpu.Count - 1)];
double gpuMax = steadyGpu[^1];
GD.Print($"viewportGpuMsTimeline(10..{_perfViewportGpuMs.Count - 1}): avg={Avg(steadyGpu):F2} p50={gpuP50:F2} p95={gpuP95:F2} max={gpuMax:F2}");
}
}
if (_hud?.HbCanvas is { } hb)
{
GD.Print($"HbGpuHud: drawCalls={hb.LastDrawCallCount} quads={hb.LastQuadCount} gpuMs={hb.LastHbGpuMs:F4}");
}
if (_session is not null)
{
var net = _session.ConnectionStatus;
@ -1491,7 +1810,7 @@ public partial class Main : Node3D
}
if (_mapKind == ArenaMapKind.Sion)
{
GD.Print($"SionMap: chunks={_sionMap.TerrainChunkCount} tiles={_sionMap.BuildingTileCount} lod1={_sionMap.ActiveLod1TileCount} lod2={_sionMap.ActiveLod2TileCount} culled={_sionMap.CulledTileCount}");
GD.Print($"SionMap: terrainTiles={_terrain.BakedTileCount} gpuScarSlots={_terrain.ActiveGpuScarSlots} bldgTiles={_sionMap.BuildingTileCount} lod1={_sionMap.ActiveLod1TileCount} lod2={_sionMap.ActiveLod2TileCount} culled={_sionMap.CulledTileCount}");
}
foreach (var kv in _arena.AssetCache.Vehicles)
{
@ -1768,11 +2087,11 @@ public partial class Main : Node3D
new Vector3(posInterp.X, surfY + 0.35f, posInterp.Z));
_orbitalPodCamBlend = 1.0f;
float backDist = 23.0f * _cameraZoom;
Vector3 pivot = new(posInterp.X, posInterp.Y + 3.2f, posInterp.Z);
float backDist = 28.0f * _cameraZoom;
Vector3 pivot = new(posInterp.X, posInterp.Y + 4.0f, posInterp.Z);
lookDir = (camFwdHoriz * MathF.Cos(_cameraPitch) - Vector3.Up * MathF.Sin(_cameraPitch)).Normalized();
float effectiveRight = 2.6f;
float effectiveRight = 1.6f;
if (CastStaticCameraRay(pivot, camRight, effectiveRight, out float rightHitDist))
{
effectiveRight = MathF.Min(effectiveRight, SafeCameraPullbackDist(rightHitDist));
@ -1966,7 +2285,7 @@ public partial class Main : Node3D
var pt = new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z);
float distFromOrigin = origin.DistanceTo(pt);
if (hit.StableId < ContenderStableIdBase)
if (ArenaSession.IsStaticWorldStableId(hit.StableId))
{
if (distFromOrigin < hitDist)
{
@ -1993,4 +2312,33 @@ public partial class Main : Node3D
{
_session?.RequestEquipCargo(cargoIndex, hardpointId);
}
private (bool Valid, bool InFront, Vector2 ScreenPos, System.Numerics.Vector3 CamLocal) ProjectWorldToHud(System.Numerics.Vector3 worldPos)
{
if (_camera is null || !GodotObject.IsInstanceValid(_camera) || !_camera.IsInsideTree())
{
return (false, false, Vector2.Zero, System.Numerics.Vector3.Zero);
}
var wp = new Vector3(worldPos.X, worldPos.Y, worldPos.Z);
Transform3D camXform = _camera.GlobalTransform;
Vector3 rel = wp - camXform.Origin;
Basis b = camXform.Basis;
// Godot Camera3D local axes: +X = right, +Y = up, -Z = forward
float localRight = rel.Dot(b.X);
float localUp = rel.Dot(b.Y);
float localForward = -rel.Dot(b.Z);
var camLocal = new System.Numerics.Vector3(localRight, localUp, localForward);
if (localForward <= 0.1f)
{
return (true, false, Vector2.Zero, camLocal);
}
Vector2 sp = _camera.UnprojectPosition(wp);
if (!float.IsFinite(sp.X) || !float.IsFinite(sp.Y))
{
return (true, false, Vector2.Zero, camLocal);
}
return (true, true, sp, camLocal);
}
}

View file

@ -22,11 +22,13 @@ public sealed partial class MainMenu : CanvasLayer
private ImperialChromePanel _menuPanel = null!;
private ImperialChromePanel _hostPanel = null!;
private LineEdit _callsignEdit = null!;
private OptionButton _soloSquadOption = null!;
private Label _statusLabel = null!;
private LineEdit _serverNameEdit = null!;
private LineEdit _portEdit = null!;
private OptionButton _hostMapOption = null!;
private OptionButton _hostSquadOption = null!;
private CheckBox _listPublicCheck = null!;
private Label _directoryHintLabel = null!;
private Label _hostErrorLabel = null!;
@ -42,13 +44,14 @@ public sealed partial class MainMenu : CanvasLayer
Layer = 20;
}
public event Action<ArenaMapKind, string>? PlaySoloRequested;
public event Action<ArenaMapKind, string, byte>? PlaySoloRequested;
public event Action<string>? ServerBrowserRequested;
public event Action<int, string, ArenaMapKind, bool, string>? HostLobbyRequested;
public event Action<int, string, ArenaMapKind, bool, string, byte>? HostLobbyRequested;
public event Action<string>? CallsignChanged;
public event Action? QuitRequested;
public event Action? ResumeRequested;
public event Action? ReturnToMainMenuRequested;
public event Action? SettingsRequested;
public bool IsHostPanelOpen => _hostPanel is not null && _hostPanel.Visible;
public bool IsTextInputFocused =>
@ -97,13 +100,16 @@ public sealed partial class MainMenu : CanvasLayer
}
}
public void SetDefaults(string callsign, string directoryUrl, ArenaMapKind defaultMap = ArenaMapKind.Sion, int defaultPort = 3076)
public void SetDefaults(string callsign, string directoryUrl, ArenaMapKind defaultMap = ArenaMapKind.Sion, int defaultPort = 3076, byte defaultSquadSize = 3)
{
_directoryUrl = directoryUrl ?? string.Empty;
if (_callsignEdit is not null)
{
_callsignEdit.Text = SanitizeCallsign(callsign);
}
int sqIdx = Math.Clamp((int)defaultSquadSize, 1, 4) - 1;
_soloSquadOption?.Select(sqIdx);
_hostSquadOption?.Select(sqIdx);
if (_portEdit is not null)
{
_portEdit.Text = defaultPort.ToString(CultureInfo.InvariantCulture);
@ -120,6 +126,14 @@ public sealed partial class MainMenu : CanvasLayer
}
}
public byte SelectedSoloSquadSize => _soloSquadOption is not null
? (byte)Math.Clamp(_soloSquadOption.Selected + 1, 1, 4)
: (byte)3;
public byte SelectedHostSquadSize => _hostSquadOption is not null
? (byte)Math.Clamp(_hostSquadOption.Selected + 1, 1, 4)
: (byte)3;
public void SetStatus(string? message, bool isError = false)
{
if (_statusLabel is null) return;
@ -213,14 +227,26 @@ public sealed partial class MainMenu : CanvasLayer
_callsignEdit.TextChanged += txt => CallsignChanged?.Invoke(SanitizeCallsign(txt));
callRow.AddChild(_callsignEdit);
var squadRow = new HBoxContainer();
squadRow.AddThemeConstantOverride("separation", 10);
vbox.AddChild(squadRow);
var squadLbl = ImperialChrome.CreateLabel("SQUAD MODE", 12, ImperialChrome.TextMuted);
squadLbl.CustomMinimumSize = new Vector2(82f, 0f);
squadRow.AddChild(squadLbl);
_soloSquadOption = CreateSquadOptionButton();
_soloSquadOption.ItemSelected += idx => _hostSquadOption?.Select((int)idx);
squadRow.AddChild(_soloSquadOption);
vbox.AddChild(ImperialChrome.MakeRule());
var playSionBtn = ImperialChrome.CreateButton("PLAY SOLO — SION", ImperialChrome.OliveCol, 14, 38f);
playSionBtn.Pressed += () => PlaySoloRequested?.Invoke(ArenaMapKind.Sion, Callsign);
playSionBtn.Pressed += () => PlaySoloRequested?.Invoke(ArenaMapKind.Sion, Callsign, SelectedSoloSquadSize);
vbox.AddChild(playSionBtn);
var playDesertBtn = ImperialChrome.CreateButton("PLAY SOLO — DESERT", ImperialChrome.OrangeCol, 14, 38f);
playDesertBtn.Pressed += () => PlaySoloRequested?.Invoke(ArenaMapKind.Desert, Callsign);
playDesertBtn.Pressed += () => PlaySoloRequested?.Invoke(ArenaMapKind.Desert, Callsign, SelectedSoloSquadSize);
vbox.AddChild(playDesertBtn);
var browserBtn = ImperialChrome.CreateButton("SERVER BROWSER", ImperialChrome.CyanCol, 14, 38f);
@ -231,6 +257,14 @@ public sealed partial class MainMenu : CanvasLayer
hostBtn.Pressed += () => SetHostPanelOpen(!IsHostPanelOpen);
vbox.AddChild(hostBtn);
var settingsBtn = ImperialChrome.CreateButton("SETTINGS", ImperialChrome.CyanCol, 14, 38f);
settingsBtn.Pressed += () =>
{
SetHostPanelOpen(false);
SettingsRequested?.Invoke();
};
vbox.AddChild(settingsBtn);
vbox.AddChild(ImperialChrome.MakeRule());
var quitBtn = ImperialChrome.CreateButton("QUIT", ImperialChrome.RedCol, 13, 34f);
@ -314,6 +348,15 @@ public sealed partial class MainMenu : CanvasLayer
ImperialChrome.StyleOptionButton(_hostMapOption, ImperialChrome.OliveCol, 13);
mapRow.AddChild(_hostMapOption);
var hostSqRow = new HBoxContainer();
hostSqRow.AddThemeConstantOverride("separation", 8);
vbox.AddChild(hostSqRow);
var hostSqLbl = ImperialChrome.CreateLabel("SQUAD MODE", 11, ImperialChrome.TextMuted);
hostSqLbl.CustomMinimumSize = new Vector2(106f, 0f);
hostSqRow.AddChild(hostSqLbl);
_hostSquadOption = CreateSquadOptionButton();
hostSqRow.AddChild(_hostSquadOption);
_listPublicCheck = new CheckBox
{
Text = "List on Public Directory",
@ -361,7 +404,22 @@ public sealed partial class MainMenu : CanvasLayer
bool listPublic = _listPublicCheck.ButtonPressed;
SetHostError(null);
HostLobbyRequested?.Invoke(port, serverName, mapKind, listPublic, Callsign);
HostLobbyRequested?.Invoke(port, serverName, mapKind, listPublic, Callsign, SelectedHostSquadSize);
}
private static OptionButton CreateSquadOptionButton()
{
var opt = new OptionButton
{
SizeFlagsHorizontal = Control.SizeFlags.ExpandFill
};
opt.AddItem("FFA (1)", 0);
opt.AddItem("DUO (2)", 1);
opt.AddItem("TRIO (3)", 2);
opt.AddItem("QUAD (4)", 3);
opt.Select(2);
ImperialChrome.StyleOptionButton(opt, ImperialChrome.CyanCol, 13);
return opt;
}
private void BuildPauseRoot()
@ -390,8 +448,8 @@ public sealed partial class MainMenu : CanvasLayer
panel.AnchorBottom = 0.5f;
panel.OffsetLeft = -190f;
panel.OffsetRight = 190f;
panel.OffsetTop = -132f;
panel.OffsetBottom = 132f;
panel.OffsetTop = -156f;
panel.OffsetBottom = 156f;
_pauseRoot.AddChild(panel);
var vbox = new VBoxContainer();
@ -408,6 +466,10 @@ public sealed partial class MainMenu : CanvasLayer
resumeBtn.Pressed += () => ResumeRequested?.Invoke();
vbox.AddChild(resumeBtn);
var settingsBtn = ImperialChrome.CreateButton("SETTINGS", ImperialChrome.CyanCol, 14, 36f);
settingsBtn.Pressed += () => SettingsRequested?.Invoke();
vbox.AddChild(settingsBtn);
var menuBtn = ImperialChrome.CreateButton("RETURN TO MAIN MENU", ImperialChrome.OrangeCol, 14, 36f);
menuBtn.Pressed += () => ReturnToMainMenuRequested?.Invoke();
vbox.AddChild(menuBtn);

View file

@ -4,38 +4,66 @@ using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Godot;
using RustToDust.HbGpu;
using Ymir.Box3D;
namespace RustToDust.Client;
/// <summary>
/// Finds ymir_box3d for Ymir.Box3D's DllImports. Godot loads game assemblies into its own load context, so the
/// default probing does not look beside them. A run from the editor or <c>--path</c> loads the library from the
/// project's build directory; an exported run from the data folder Godot puts beside the executable.
/// Resolves native libraries (ymir_box3d, rtd_hbgpu) for Godot's AssemblyLoadContext.
/// </summary>
internal static class NativeLibraries
{
private const string Library = "ymir_box3d";
private const string YmirLibrary = "ymir_box3d";
private const string HbGpuLibrary = "rtd_hbgpu";
#pragma warning disable CA2255 // application code: the resolver must exist before the first DllImport
[ModuleInitializer]
internal static void Register() =>
internal static void Register()
{
NativeLibrary.SetDllImportResolver(typeof(Box3DSoaWorld).Assembly, Resolve);
NativeLibrary.SetDllImportResolver(typeof(HbGpuNative).Assembly, Resolve);
}
private static IntPtr Resolve(string name, Assembly assembly, DllImportSearchPath? searchPath)
{
if (name != Library) return IntPtr.Zero;
string fileName = FileName();
string? stem = name switch
{
YmirLibrary => YmirLibrary,
HbGpuLibrary => HbGpuLibrary,
_ => null
};
if (stem is null)
{
return IntPtr.Zero;
}
string fileName = FileName(stem);
if (OS.HasFeature("template"))
{
string exportPath = Path.Combine(
Path.GetDirectoryName(OS.GetExecutablePath())!,
$"data_RustToDust.Client_{Platform()}_{Arch()}",
fileName);
return File.Exists(exportPath) && NativeLibrary.TryLoad(exportPath, out var exportHandle)
? exportHandle
: IntPtr.Zero;
string exePath = OS.GetExecutablePath();
string exeDir = exePath.GetBaseDir();
string exeStem = Path.GetFileNameWithoutExtension(exePath);
string platArch = $"{Platform()}_{Arch()}";
string[] candidates =
{
Path.Combine(exeDir, fileName),
Path.Combine(exeDir, $"data_{exeStem}_{platArch}", fileName),
Path.Combine(exeDir, $"data_RustToDust_{platArch}", fileName),
Path.Combine(exeDir, $"data_RustToDust.Client_{platArch}", fileName),
Path.Combine(AppContext.BaseDirectory, fileName),
};
foreach (string candidate in candidates)
{
if (File.Exists(candidate) && NativeLibrary.TryLoad(candidate, out var exportHandle))
{
return exportHandle;
}
}
return IntPtr.Zero;
}
string debugPath = Path.Combine(ProjectSettings.GlobalizePath("res://.godot/mono/temp/bin/Debug"), fileName);
@ -50,8 +78,8 @@ internal static class NativeLibraries
: IntPtr.Zero;
}
private static string FileName() =>
OperatingSystem.IsWindows() ? "ymir_box3d.dll" : OperatingSystem.IsMacOS() ? "libymir_box3d.dylib" : "libymir_box3d.so";
private static string FileName(string stem) =>
OperatingSystem.IsWindows() ? $"{stem}.dll" : OperatingSystem.IsMacOS() ? $"lib{stem}.dylib" : $"lib{stem}.so";
private static string Platform() =>
OperatingSystem.IsWindows() ? "windows" : OperatingSystem.IsMacOS() ? "macos" : "linuxbsd";

File diff suppressed because it is too large Load diff

View file

@ -58,9 +58,7 @@ public partial class PomDecalPool : Node3D
Shader shader = GD.Load<Shader>("res://decal_pom.gdshader")
?? throw new InvalidOperationException("Failed to load res://decal_pom.gdshader");
string vehiclesDir = VehicleCatalogLoader.LocateVehiclesDirectory();
string assetsDir = Directory.GetParent(vehiclesDir)?.FullName
?? throw new DirectoryNotFoundException("Could not locate assets directory.");
string assetsDir = ClientAssets.LocateAssetsDirectory();
string decalsDir = Path.Combine(assetsDir, "decals");
_albedoTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_albedo.png"));

View file

@ -56,9 +56,7 @@ public sealed class ProceduralAudioBank
public static string LocateHavenAudioDirectory()
{
string vehiclesDir = VehicleCatalogLoader.LocateVehiclesDirectory();
string assetsDir = Directory.GetParent(vehiclesDir)?.FullName
?? throw new DirectoryNotFoundException("Could not locate assets directory.");
string assetsDir = ClientAssets.LocateAssetsDirectory();
string havenDir = Path.Combine(assetsDir, "audio", "haven");
if (!Directory.Exists(havenDir))
{

View file

@ -10,6 +10,7 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\src\RustToDust.Ymir\RustToDust.Ymir.csproj" />
<ProjectReference Include="..\src\RustToDust.HbGpu\RustToDust.HbGpu.csproj" AdditionalProperties="HbGpuNativeConfiguration=$(YmirNativeConfiguration)" />
<ProjectReference Include="..\src\RustToDust.Net\RustToDust.Net.csproj" />
<ProjectReference Include="$(YmirRoot)/src/Ymir.Box3D/Ymir.Box3D.csproj" AdditionalProperties="YmirNativeConfiguration=$(YmirNativeConfiguration)" />
</ItemGroup>

407
client/SettingsOverlay.cs Normal file
View file

@ -0,0 +1,407 @@
using System;
using Godot;
namespace RustToDust.Client;
/// <summary>
/// Industrial Imperial Settings overlay with left-rail submenu navigation
/// (<b>GRAPHICS</b> active; Audio/Controls placeholders for future passes).
/// Decoupled from <see cref="GraphicsSettings"/> persistence: receives values via
/// <see cref="SetGraphicsValues"/> and emits change/reset/back events.
/// </summary>
public sealed partial class SettingsOverlay : CanvasLayer
{
public enum SettingsCategory
{
Graphics = 0
}
private Control _root = null!;
private ImperialChromePanel _panel = null!;
private Button _graphicsTabBtn = null!;
private Control _graphicsPane = null!;
private readonly Button[] _vfxResButtons = new Button[3];
private readonly Button[] _volSampleButtons = new Button[4];
private readonly Button[] _sdfgiButtons = new Button[3];
private readonly Button[] _displayModeButtons = new Button[2];
private VfxResolutionScale _vfxRes = VfxResolutionScale.Half;
private VolumetricSamples _volSamples = VolumetricSamples.Medium;
private SdfgiQuality _sdfgi = SdfgiQuality.Balanced;
private bool _borderlessFullscreen = true;
private bool _built;
public SettingsOverlay()
{
Layer = 22;
}
public event Action<VfxResolutionScale, VolumetricSamples, SdfgiQuality, bool>? GraphicsChanged;
public event Action? ResetDefaultsRequested;
public event Action? BackRequested;
public bool IsOpen => Visible;
public override void _Ready()
{
BuildUi();
SetSettingsVisible(false);
}
public void SetSettingsVisible(bool visible)
{
Visible = visible;
if (_root is not null)
{
_root.Visible = visible;
}
}
public void SetGraphicsValues(
VfxResolutionScale vfxRes,
VolumetricSamples volSamples,
SdfgiQuality sdfgi,
bool borderlessFullscreen)
{
_vfxRes = vfxRes;
_volSamples = volSamples;
_sdfgi = sdfgi;
_borderlessFullscreen = borderlessFullscreen;
if (_built)
{
RefreshSelectionVisuals();
}
}
private void BuildUi()
{
_root = new Control
{
Name = "SettingsOverlayRoot",
MouseFilter = Control.MouseFilterEnum.Stop
};
_root.SetAnchorsPreset(Control.LayoutPreset.FullRect);
AddChild(_root);
var scrim = new ColorRect
{
Color = ImperialChrome.ScrimCol,
MouseFilter = Control.MouseFilterEnum.Stop
};
scrim.SetAnchorsPreset(Control.LayoutPreset.FullRect);
_root.AddChild(scrim);
_panel = ImperialChrome.CreatePanel(
ImperialChrome.OrangeCol,
cornerLen: 18f,
borderPx: 2f,
bgAlpha: 0.94f,
padH: 22,
padV: 20);
_panel.Name = "SettingsPanel";
_panel.AnchorLeft = 0.5f;
_panel.AnchorRight = 0.5f;
_panel.AnchorTop = 0.5f;
_panel.AnchorBottom = 0.5f;
_panel.OffsetLeft = -440f;
_panel.OffsetRight = 440f;
_panel.OffsetTop = -255f;
_panel.OffsetBottom = 255f;
_root.AddChild(_panel);
var outerVbox = new VBoxContainer();
outerVbox.AddThemeConstantOverride("separation", 12);
_panel.AddChild(outerVbox);
// Header
var headerRow = new HBoxContainer();
headerRow.AddThemeConstantOverride("separation", 12);
outerVbox.AddChild(headerRow);
var titleCol = new VBoxContainer { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill };
titleCol.AddThemeConstantOverride("separation", 2);
headerRow.AddChild(titleCol);
titleCol.AddChild(ImperialChrome.CreateLabel("SYSTEM CONFIGURATION • SUBMENU", 11, ImperialChrome.GoldCol));
titleCol.AddChild(ImperialChrome.CreateLabel("SETTINGS", 24, ImperialChrome.TextLight));
var liveBadge = ImperialChrome.CreateLabel("LIVE APPLY • NO RESTART", 11, ImperialChrome.CyanCol, HorizontalAlignment.Right);
liveBadge.VerticalAlignment = VerticalAlignment.Bottom;
headerRow.AddChild(liveBadge);
outerVbox.AddChild(ImperialChrome.MakeRule());
// Main Split: Submenu Rail + Content Pane
var split = new HBoxContainer
{
SizeFlagsVertical = Control.SizeFlags.ExpandFill
};
split.AddThemeConstantOverride("separation", 18);
outerVbox.AddChild(split);
var navCol = new VBoxContainer
{
CustomMinimumSize = new Vector2(168f, 0f)
};
navCol.AddThemeConstantOverride("separation", 8);
split.AddChild(navCol);
navCol.AddChild(ImperialChrome.CreateLabel("CATEGORIES", 10, ImperialChrome.TextMuted));
_graphicsTabBtn = ImperialChrome.CreateButton("GRAPHICS", ImperialChrome.CyanCol, 13, 38f);
StyleSegmentedButton(_graphicsTabBtn, selected: true, ImperialChrome.CyanCol);
_graphicsTabBtn.Pressed += () => SelectCategory(SettingsCategory.Graphics);
navCol.AddChild(_graphicsTabBtn);
var audioTabBtn = ImperialChrome.CreateButton("AUDIO [SOON]", ImperialChrome.BorderCol, 12, 34f);
audioTabBtn.Disabled = true;
audioTabBtn.TooltipText = "Audio controls arrive in a future pass";
navCol.AddChild(audioTabBtn);
var controlsTabBtn = ImperialChrome.CreateButton("CONTROLS [SOON]", ImperialChrome.BorderCol, 12, 34f);
controlsTabBtn.Disabled = true;
controlsTabBtn.TooltipText = "Input bindings arrive in a future pass";
navCol.AddChild(controlsTabBtn);
var vSep = new VSeparator();
vSep.AddThemeStyleboxOverride("separator", new StyleBoxLine
{
Color = new Color(ImperialChrome.BorderCol.R, ImperialChrome.BorderCol.G, ImperialChrome.BorderCol.B, 0.75f),
Thickness = 1,
Vertical = true
});
split.AddChild(vSep);
_graphicsPane = new VBoxContainer
{
Name = "GraphicsSettingsPane",
SizeFlagsHorizontal = Control.SizeFlags.ExpandFill,
SizeFlagsVertical = Control.SizeFlags.ExpandFill
};
((VBoxContainer)_graphicsPane).AddThemeConstantOverride("separation", 12);
split.AddChild(_graphicsPane);
_graphicsPane.AddChild(ImperialChrome.CreateLabel("GRAPHICS • VOLUMETRICS, GI & DISPLAY", 14, ImperialChrome.CyanCol));
// 1. VFX / Fog Resolution
AddSettingRow(
_graphicsPane,
"VFX / FOG RESOLUTION",
"Compute resolution for raymarched smoke, fireballs & plumes (Full = 1:1 native)",
new[]
{
("Half (0.5x)", (Action)(() => OnGraphicsOptionSelected(vfxRes: VfxResolutionScale.Half))),
("High (0.75x)", (Action)(() => OnGraphicsOptionSelected(vfxRes: VfxResolutionScale.ThreeQuarter))),
("Full (1.0x)", (Action)(() => OnGraphicsOptionSelected(vfxRes: VfxResolutionScale.Full)))
},
_vfxResButtons);
// 2. Volumetric Sample Count
AddSettingRow(
_graphicsPane,
"VOLUMETRIC SAMPLE COUNT",
"Raymarch step budget per pixel (higher = smoother volume density & gradients)",
new[]
{
("Low (8)", (Action)(() => OnGraphicsOptionSelected(volSamples: VolumetricSamples.Low))),
("Medium (10)", (Action)(() => OnGraphicsOptionSelected(volSamples: VolumetricSamples.Medium))),
("High (16)", (Action)(() => OnGraphicsOptionSelected(volSamples: VolumetricSamples.High))),
("Ultra (24)", (Action)(() => OnGraphicsOptionSelected(volSamples: VolumetricSamples.Ultra)))
},
_volSampleButtons);
// 3. Global Illumination (SDFGI)
AddSettingRow(
_graphicsPane,
"GLOBAL ILLUMINATION (SDFGI)",
"Signed-distance multi-bounce sky & terrain indirect lighting",
new[]
{
("Off", (Action)(() => OnGraphicsOptionSelected(sdfgi: SdfgiQuality.Off))),
("Balanced", (Action)(() => OnGraphicsOptionSelected(sdfgi: SdfgiQuality.Balanced))),
("High", (Action)(() => OnGraphicsOptionSelected(sdfgi: SdfgiQuality.High)))
},
_sdfgiButtons);
// 4. Display Mode
AddSettingRow(
_graphicsPane,
"DISPLAY MODE",
"Window presentation mode (also toggleable anytime via Alt+Enter or F11)",
new[]
{
("Borderless Fullscreen", (Action)(() => OnGraphicsOptionSelected(borderlessFullscreen: true))),
("Windowed", (Action)(() => OnGraphicsOptionSelected(borderlessFullscreen: false)))
},
_displayModeButtons);
outerVbox.AddChild(ImperialChrome.MakeRule());
// Footer
var footerRow = new HBoxContainer();
footerRow.AddThemeConstantOverride("separation", 10);
outerVbox.AddChild(footerRow);
var resetBtn = ImperialChrome.CreateButton("RESET DEFAULTS", ImperialChrome.GoldCol, 13, 36f);
resetBtn.CustomMinimumSize = new Vector2(180f, 36f);
resetBtn.Pressed += () => ResetDefaultsRequested?.Invoke();
footerRow.AddChild(resetBtn);
footerRow.AddChild(new Control { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill });
var backBtn = ImperialChrome.CreateButton("BACK [ESC]", ImperialChrome.OrangeCol, 13, 36f);
backBtn.CustomMinimumSize = new Vector2(160f, 36f);
backBtn.Pressed += () => BackRequested?.Invoke();
footerRow.AddChild(backBtn);
_built = true;
RefreshSelectionVisuals();
}
private static void AddSettingRow(
Control parent,
string labelText,
string hintText,
(string Text, Action OnSelect)[] options,
Button[] targetButtons)
{
var block = new VBoxContainer();
block.AddThemeConstantOverride("separation", 4);
parent.AddChild(block);
var row = new HBoxContainer();
row.AddThemeConstantOverride("separation", 12);
block.AddChild(row);
var lbl = ImperialChrome.CreateLabel(labelText, 12, ImperialChrome.TextLight);
lbl.CustomMinimumSize = new Vector2(228f, 0f);
lbl.VerticalAlignment = VerticalAlignment.Center;
row.AddChild(lbl);
var btnGroup = new HBoxContainer
{
SizeFlagsHorizontal = Control.SizeFlags.ExpandFill
};
btnGroup.AddThemeConstantOverride("separation", 6);
row.AddChild(btnGroup);
for (int i = 0; i < options.Length; i++)
{
var (text, onSelect) = options[i];
var btn = ImperialChrome.CreateButton(text, ImperialChrome.CyanCol, 12, 32f);
btn.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
btn.Pressed += onSelect;
btnGroup.AddChild(btn);
targetButtons[i] = btn;
}
var hint = ImperialChrome.CreateLabel(hintText, 10, ImperialChrome.TextMuted);
block.AddChild(hint);
}
private void SelectCategory(SettingsCategory category)
{
if (category == SettingsCategory.Graphics && _graphicsPane is not null)
{
_graphicsPane.Visible = true;
}
}
private void OnGraphicsOptionSelected(
VfxResolutionScale? vfxRes = null,
VolumetricSamples? volSamples = null,
SdfgiQuality? sdfgi = null,
bool? borderlessFullscreen = null)
{
VfxResolutionScale nextRes = vfxRes ?? _vfxRes;
VolumetricSamples nextSamples = volSamples ?? _volSamples;
SdfgiQuality nextSdfgi = sdfgi ?? _sdfgi;
bool nextFullscreen = borderlessFullscreen ?? _borderlessFullscreen;
if (nextRes == _vfxRes
&& nextSamples == _volSamples
&& nextSdfgi == _sdfgi
&& nextFullscreen == _borderlessFullscreen)
{
return;
}
_vfxRes = nextRes;
_volSamples = nextSamples;
_sdfgi = nextSdfgi;
_borderlessFullscreen = nextFullscreen;
RefreshSelectionVisuals();
GraphicsChanged?.Invoke(_vfxRes, _volSamples, _sdfgi, _borderlessFullscreen);
}
private void RefreshSelectionVisuals()
{
for (int i = 0; i < _vfxResButtons.Length; i++)
{
StyleSegmentedButton(_vfxResButtons[i], i == (int)_vfxRes, ImperialChrome.CyanCol);
}
for (int i = 0; i < _volSampleButtons.Length; i++)
{
StyleSegmentedButton(_volSampleButtons[i], i == (int)_volSamples, ImperialChrome.CyanCol);
}
for (int i = 0; i < _sdfgiButtons.Length; i++)
{
StyleSegmentedButton(_sdfgiButtons[i], i == (int)_sdfgi, ImperialChrome.OliveCol);
}
StyleSegmentedButton(_displayModeButtons[0], _borderlessFullscreen, ImperialChrome.OrangeCol);
StyleSegmentedButton(_displayModeButtons[1], !_borderlessFullscreen, ImperialChrome.OrangeCol);
}
private static void StyleSegmentedButton(Button btn, bool selected, Color accentColor)
{
if (selected)
{
btn.AddThemeFontSizeOverride("font_size", 12);
btn.AddThemeColorOverride("font_color", Colors.White);
btn.AddThemeColorOverride("font_hover_color", Colors.White);
btn.AddThemeColorOverride("font_pressed_color", accentColor);
var activeBox = MakeSegmentBox(
new Color(accentColor.R * 0.24f + ImperialChrome.BgPressed.R * 0.76f,
accentColor.G * 0.24f + ImperialChrome.BgPressed.G * 0.76f,
accentColor.B * 0.24f + ImperialChrome.BgPressed.B * 0.76f,
1f),
accentColor,
borderW: 2);
btn.AddThemeStyleboxOverride("normal", activeBox);
btn.AddThemeStyleboxOverride("hover", activeBox);
btn.AddThemeStyleboxOverride("pressed", activeBox);
btn.AddThemeStyleboxOverride("focus", activeBox);
}
else
{
btn.AddThemeFontSizeOverride("font_size", 12);
btn.AddThemeColorOverride("font_color", ImperialChrome.TextMuted);
btn.AddThemeColorOverride("font_hover_color", ImperialChrome.TextLight);
btn.AddThemeColorOverride("font_pressed_color", accentColor);
var normal = MakeSegmentBox(ImperialChrome.BgInner, ImperialChrome.BorderCol, borderW: 1);
var hover = MakeSegmentBox(ImperialChrome.BgHover, new Color(accentColor.R, accentColor.G, accentColor.B, 0.75f), borderW: 1);
var pressed = MakeSegmentBox(ImperialChrome.BgPressed, accentColor, borderW: 2);
btn.AddThemeStyleboxOverride("normal", normal);
btn.AddThemeStyleboxOverride("hover", hover);
btn.AddThemeStyleboxOverride("pressed", pressed);
btn.AddThemeStyleboxOverride("focus", hover);
}
}
private static StyleBoxFlat MakeSegmentBox(Color bg, Color border, int borderW)
{
var box = new StyleBoxFlat
{
BgColor = bg,
BorderColor = border,
ContentMarginLeft = 8,
ContentMarginRight = 8,
ContentMarginTop = 5,
ContentMarginBottom = 5
};
box.SetBorderWidthAll(borderW);
return box;
}
}

View file

@ -7,17 +7,15 @@ using RustToDust.Core;
namespace RustToDust.Client;
/// <summary>
/// Renders the 3072m x 3072m Sion, Switzerland arena:
/// - 6x6 (512m) seam-free chunked terrain ArrayMeshes from heightmap.f32 textured with terrain_surface.png + micro-grain shader.
/// - 36 spatial building tiles swapping cleanly between LOD1 (&lt;= 650m), LOD2 (650m..2200m), and culled (&gt; 2200m),
/// with shadow casting restricted to &lt;= 450m and shared PBR materials across all tiles.
/// Renders Sion, Switzerland legacy building tiles (swapping cleanly between LOD1 &lt;= 520m, LOD2 520..2200m,
/// and culled &gt; 2200m). Terrain rendering is unified in <see cref="TerrainRenderer"/>.
/// (This class is scheduled for deletion in Cut 13c when <c>WorldCityRenderer</c> lands.)
/// </summary>
public partial class SionMapRenderer : Node3D
{
public const float Lod1DistanceM = 520f;
public const float CullDistanceM = 2200f;
public const float ShadowDistanceM = 360f;
private const int ChunkGridVerts = 129; // 128 quads per 512m chunk (4m spacing)
public const float Lod1DistanceM = 400f;
public const float CullDistanceM = 1750f;
public const float ShadowDistanceM = 280f;
private sealed class BuildingTileEntry
{
@ -30,26 +28,17 @@ public partial class SionMapRenderer : Node3D
public required MeshInstance3D Instance;
}
private const int GroundTintGridSize = 128;
private static readonly Color NeutralAlpineDustTint = new(0.56f, 0.53f, 0.46f, 1.0f);
private readonly List<MeshInstance3D> _terrainChunks = new(36);
private readonly List<BuildingTileEntry> _buildingTiles = new(36);
private readonly Dictionary<string, StandardMaterial3D> _sharedBuildingMaterials = new(StringComparer.Ordinal);
private string? _builtForDir;
private ShaderMaterial? _terrainMat;
private ImageTexture? _surfaceTex;
private Color[]? _groundTintGrid;
private float _groundTintSizeM;
public bool IsBuilt { get; private set; }
public int TerrainChunkCount => _terrainChunks.Count;
public int BuildingTileCount => _buildingTiles.Count;
public int ActiveLod1TileCount { get; private set; }
public int ActiveLod2TileCount { get; private set; }
public int CulledTileCount { get; private set; }
public void EnsureBuilt(SionMapData sion, TerrainField terrain)
public void EnsureBuilt(SionMapData sion)
{
if (IsBuilt && string.Equals(_builtForDir, sion.DirectoryPath, StringComparison.OrdinalIgnoreCase))
{
@ -58,9 +47,6 @@ public partial class SionMapRenderer : Node3D
ClearBuilt();
_builtForDir = sion.DirectoryPath;
BuildTerrainMaterial(sion);
BuildTerrainChunks(sion, terrain);
BuildBuildingTiles(sion);
IsBuilt = true;
}
@ -124,186 +110,6 @@ public partial class SionMapRenderer : Node3D
CulledTileCount = culledCount;
}
private void BuildTerrainMaterial(SionMapData sion)
{
string surfPath = Path.Combine(sion.DirectoryPath, sion.Metadata.SurfaceTexture);
if (!File.Exists(surfPath))
{
throw new FileNotFoundException($"Missing Sion terrain surface texture: {surfPath}", surfPath);
}
var img = Image.LoadFromFile(surfPath);
if (img is null || img.IsEmpty())
{
throw new InvalidOperationException($"Failed to decode Sion terrain surface texture: {surfPath}");
}
// Downsample CPU copy once for zero-readback terrain-tinted dust & impact plumes
var tintImg = (Image)img.Duplicate();
tintImg.Resize(GroundTintGridSize, GroundTintGridSize, Image.Interpolation.Bilinear);
var grid = new Color[GroundTintGridSize * GroundTintGridSize];
for (int y = 0; y < GroundTintGridSize; y++)
{
for (int x = 0; x < GroundTintGridSize; x++)
{
Color c = tintImg.GetPixel(x, y);
grid[y * GroundTintGridSize + x] = new Color(
Math.Clamp(c.R + 0.11f, 0.20f, 0.90f),
Math.Clamp(c.G + 0.11f, 0.20f, 0.88f),
Math.Clamp(c.B + 0.10f, 0.18f, 0.84f),
1.0f);
}
}
_groundTintGrid = grid;
_groundTintSizeM = sion.Metadata.SizeMeters;
img.GenerateMipmaps();
_surfaceTex = ImageTexture.CreateFromImage(img);
var shader = new Shader
{
Code = """
shader_type spatial;
render_mode cull_back, depth_draw_opaque;
uniform sampler2D surface_tex : source_color, filter_linear_mipmap, repeat_disable;
varying vec3 v_world_pos;
varying vec3 v_world_normal;
float hash21(vec2 p) {
p = fract(p * vec2(123.34, 456.21));
p += dot(p, p + 45.32);
return fract(p.x * p.y);
}
float value_noise(vec2 p) {
vec2 i = floor(p);
vec2 f = fract(p);
vec2 u = f * f * (3.0 - 2.0 * f);
float a = hash21(i);
float b = hash21(i + vec2(1.0, 0.0));
float c = hash21(i + vec2(0.0, 1.0));
float d = hash21(i + vec2(1.0, 1.0));
return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
}
void vertex() {
v_world_pos = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz;
v_world_normal = normalize((MODEL_MATRIX * vec4(NORMAL, 0.0)).xyz);
}
void fragment() {
vec3 base_col = texture(surface_tex, UV).rgb;
// Crisp world-space micro-grain for up-close ground readability
float dist = length((INV_VIEW_MATRIX * vec4(0.0, 0.0, 0.0, 1.0)).xyz - v_world_pos);
float near_fade = clamp(1.0 - smoothstep(140.0, 480.0, dist), 0.12, 1.0);
float macro = (value_noise(v_world_pos.xz * 0.28) - 0.5) * 0.07;
float grit = (hash21(floor(v_world_pos.xz * 8.0)) - 0.5) * 0.045;
float slope = 1.0 - clamp(v_world_normal.y, 0.0, 1.0);
vec3 col = clamp(base_col * (1.0 + macro * 1.4 + grit * 1.6 * near_fade), vec3(0.0), vec3(1.0));
ALBEDO = col;
ROUGHNESS = mix(0.88, 0.96, slope);
METALLIC = 0.02;
}
"""
};
_terrainMat = new ShaderMaterial { Shader = shader };
_terrainMat.SetShaderParameter("surface_tex", _surfaceTex);
}
private void BuildTerrainChunks(SionMapData sion, TerrainField terrain)
{
int grid = sion.Metadata.TileGrid;
float sizeM = sion.Metadata.SizeMeters;
float tileSize = sion.Metadata.TileSizeMeters;
float half = sizeM * 0.5f;
int n = ChunkGridVerts;
float step = tileSize / (n - 1);
// Precompute shared index buffer for every terrain chunk (Godot ArrayMesh cull_back uses CW front-facing winding)
int quadCount = (n - 1) * (n - 1);
var indices = new int[quadCount * 6];
int ii = 0;
for (int gz = 0; gz < n - 1; gz++)
{
for (int gx = 0; gx < n - 1; gx++)
{
int i00 = gz * n + gx;
int i10 = i00 + 1;
int i01 = i00 + n;
int i11 = i01 + 1;
indices[ii++] = i00;
indices[ii++] = i10;
indices[ii++] = i01;
indices[ii++] = i10;
indices[ii++] = i11;
indices[ii++] = i01;
}
}
int vertCount = n * n;
for (int tz = 0; tz < grid; tz++)
{
for (int tx = 0; tx < grid; tx++)
{
float x0 = -half + tx * tileSize;
float z0 = -half + tz * tileSize;
float cx = x0 + tileSize * 0.5f;
float cz = z0 + tileSize * 0.5f;
var verts = new Vector3[vertCount];
var normals = new Vector3[vertCount];
var uvs = new Vector2[vertCount];
for (int gz = 0; gz < n; gz++)
{
float wz = z0 + gz * step;
float lx = 0f;
float lz = wz - cz;
float v = (wz + half) / sizeM;
for (int gx = 0; gx < n; gx++)
{
float wx = x0 + gx * step;
lx = wx - cx;
float h = terrain.SampleHeight(wx, wz);
var (nx, ny, nz) = terrain.SampleNormal(wx, wz);
int idx = gz * n + gx;
verts[idx] = new Vector3(lx, h, lz);
normals[idx] = new Vector3(nx, ny, nz);
uvs[idx] = new Vector2((wx + half) / sizeM, v);
}
}
var arrays = new Godot.Collections.Array();
arrays.Resize((int)Mesh.ArrayType.Max);
arrays[(int)Mesh.ArrayType.Vertex] = verts;
arrays[(int)Mesh.ArrayType.Normal] = normals;
arrays[(int)Mesh.ArrayType.TexUV] = uvs;
arrays[(int)Mesh.ArrayType.Index] = indices;
var mesh = new ArrayMesh();
mesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arrays);
var chunkNode = new MeshInstance3D
{
Name = $"SionTerrain_{tx}_{tz}",
Mesh = mesh,
MaterialOverride = _terrainMat,
Position = new Vector3(cx, 0f, cz),
CastShadow = GeometryInstance3D.ShadowCastingSetting.On
};
AddChild(chunkNode);
_terrainChunks.Add(chunkNode);
}
}
}
private void BuildBuildingTiles(SionMapData sion)
{
var tiles = sion.Metadata.Tiles;
@ -498,47 +304,8 @@ public partial class SionMapRenderer : Node3D
return (defaultKey, defMat);
}
public Color SampleGroundTint(float worldX, float worldZ)
{
Color[]? grid = _groundTintGrid;
float sizeM = _groundTintSizeM;
if (grid is null || sizeM <= 1f || !float.IsFinite(worldX) || !float.IsFinite(worldZ))
{
return NeutralAlpineDustTint;
}
float half = sizeM * 0.5f;
float u = (worldX + half) / sizeM;
float v = (worldZ + half) / sizeM;
if (u < 0f || u > 1f || v < 0f || v > 1f)
{
return NeutralAlpineDustTint;
}
float fx = u * (GroundTintGridSize - 1);
float fy = v * (GroundTintGridSize - 1);
int x0 = Math.Clamp((int)MathF.Floor(fx), 0, GroundTintGridSize - 1);
int y0 = Math.Clamp((int)MathF.Floor(fy), 0, GroundTintGridSize - 1);
int x1 = Math.Min(x0 + 1, GroundTintGridSize - 1);
int y1 = Math.Min(y0 + 1, GroundTintGridSize - 1);
float tx = fx - x0;
float ty = fy - y0;
Color c00 = grid[y0 * GroundTintGridSize + x0];
Color c10 = grid[y0 * GroundTintGridSize + x1];
Color c01 = grid[y1 * GroundTintGridSize + x0];
Color c11 = grid[y1 * GroundTintGridSize + x1];
return c00.Lerp(c10, tx).Lerp(c01.Lerp(c11, tx), ty);
}
private void ClearBuilt()
{
for (int i = 0; i < _terrainChunks.Count; i++)
{
_terrainChunks[i].QueueFree();
}
_terrainChunks.Clear();
for (int i = 0; i < _buildingTiles.Count; i++)
{
_buildingTiles[i].Instance.QueueFree();
@ -546,10 +313,6 @@ public partial class SionMapRenderer : Node3D
_buildingTiles.Clear();
_sharedBuildingMaterials.Clear();
_terrainMat = null;
_surfaceTex = null;
_groundTintGrid = null;
_groundTintSizeM = 0f;
_builtForDir = null;
IsBuilt = false;
ActiveLod1TileCount = 0;

File diff suppressed because it is too large Load diff

35
client/UiFonts.cs Normal file
View file

@ -0,0 +1,35 @@
using Godot;
namespace RustToDust.Client;
/// <summary>
/// Central font accessor for custom <c>Control._Draw()</c> canvas calls.
/// Standard controls inherit <c>gui/theme/custom_font</c> from <c>project.godot</c>.
/// </summary>
internal static class UiFonts
{
private const string RegularPath = "res://fonts/MonaspaceKrypton-Regular.otf";
private const string SemiBoldPath = "res://fonts/MonaspaceKrypton-SemiBold.otf";
private const string BoldPath = "res://fonts/MonaspaceKrypton-Bold.otf";
private static Font? _regular;
private static Font? _semiBold;
private static Font? _bold;
public static Font Regular => _regular ??= LoadOrFallback(RegularPath, ThemeDB.FallbackFont);
public static Font SemiBold => _semiBold ??= LoadOrFallback(SemiBoldPath, Regular);
public static Font Bold => _bold ??= LoadOrFallback(BoldPath, SemiBold);
private static Font LoadOrFallback(string path, Font fallback)
{
if (ResourceLoader.Exists(path))
{
var loaded = GD.Load<Font>(path);
if (loaded is not null)
{
return loaded;
}
}
return fallback;
}
}

View file

@ -132,9 +132,9 @@ public sealed class VehicleAssetCache : IDisposable
public VehicleAssetCache()
{
ClientAssets.EnsureAssetsRootRegistered();
_vehiclesDir = VehicleCatalogLoader.LocateVehiclesDirectory();
string assetsDir = Directory.GetParent(_vehiclesDir)?.FullName
?? throw new DirectoryNotFoundException($"Could not locate assets parent directory of '{_vehiclesDir}'.");
string assetsDir = ClientAssets.LocateAssetsDirectory();
_gearDir = Path.Combine(assetsDir, "gear");
if (!Directory.Exists(_gearDir))
{

View file

@ -0,0 +1,724 @@
using System;
using System.Runtime.InteropServices;
using Godot;
namespace RustToDust.Client;
/// <summary>
/// 4-pass Forward+ Vulkan compute pipeline (<c>PostSky</c>) owning:
/// Pass 0: <c>flow_field_step.glsl</c> (camera-snapped 3m 64x24x64 RGBA16F ping-pong -> <see cref="Texture3Drd"/>)
/// Pass 1: <c>volumetric_tile_cull.glsl</c> (16x16 half-res tiles + 128-element Bitonic sort)
/// Pass 2: <c>volumetric_raymarch.glsl</c> (sorted monotonic sweep-line + Aetheria curl/triNoise + shock cavity + 2 shadow taps)
/// Pass 3: <c>volumetric_composite.glsl</c> (2x2 bilateral depth upsample pre-tonemap)
/// </summary>
public sealed partial class VolumetricCompositorEffect : CompositorEffect
{
public const int FlowDimX = 64;
public const int FlowDimY = 24;
public const int FlowDimZ = 64;
public const float FlowVoxelSizeMeters = 3.0f;
public const int TileSizeHalfRes = 16;
public const int TileStrideBytes = 112;
public const int FrameUboBytes = 272;
[StructLayout(LayoutKind.Sequential, Pack = 4)]
private struct VolumetricFrameUbo
{
public Vector4 InvProj0, InvProj1, InvProj2, InvProj3;
public Vector4 CamPosTime;
public Vector4 CamRightAspect;
public Vector4 CamUpTanHalfFov;
public Vector4 CamFwdNearFar;
public Vector4 SunDirIntensity;
public Vector4 SunColorExt;
public Vector4 AmbientColorFog;
public Vector4 ViewportInfo;
public uint HalfW, HalfH, TilesX, FrameIndex;
public Vector4 FlowOriginVoxel;
public Vector4 FlowInvExtentDt;
public int DeltaX, DeltaY, DeltaZ, ImpulseCount;
public uint MaxSteps, MaxIter, IsFullRes, QualityPad;
}
private readonly Texture3Drd _flowTexRd;
private VolumetricEmitterPool _emitterPool;
// Atmosphere parameters updated from game thread via volatile/lock
private readonly object _atmoLock = new();
private Vector3 _sunDir = new Vector3(0.45f, 0.55f, 0.70f).Normalized();
private float _sunEnergy = 1.25f;
private Color _sunColor = Colors.White;
private Color _ambientColor = new(0.28f, 0.34f, 0.42f);
private float _globalExtinctionScale = 0.28f;
private VfxResolutionScale _resolutionScale = VfxResolutionScale.Half;
private VolumetricSamples _volumetricSamples = VolumetricSamples.Medium;
// Render-thread RD state
private RenderingDevice? _rd;
private bool _rdInitialized;
private bool _rdFailed;
private Rid _flowShaderRid, _flowPipeRid;
private Rid _cullShaderRid, _cullPipeRid;
private Rid _marchShaderRid, _marchPipeRid;
private Rid _compShaderRid, _compPipeRid;
private readonly Rid[] _flowTexRids = new Rid[2];
private int _flowReadIdx;
private Vector3I _prevFlowVoxelOrigin;
private bool _hasPrevFlowOrigin;
private Rid _nearestSamplerRid;
private Rid _linearSamplerRid;
private Rid _frameUboRid;
private Rid _emitterSsboRid;
private Rid _impulseSsboRid;
private Rid _tileSsboRid;
private int _tileSsboCapacityTiles;
private Rid _halfVolRid;
private Vector2I _halfVolSize;
private uint _frameCounter;
// Pre-allocated CPU staging buffers (zero per-frame allocations)
private readonly byte[] _uboBytes = new byte[FrameUboBytes];
private readonly byte[] _emitterUploadBytes = new byte[VolumetricEmitterPool.MaxEmitters * VolumetricEmitterPool.EmitterStrideBytes];
private readonly byte[] _impulseUploadBytes = new byte[VolumetricEmitterPool.MaxFlowImpulses * VolumetricEmitterPool.ImpulseStrideBytes];
// Lightweight RD timestamp telemetry (populated when ProfilingEnabled == true)
public bool ProfilingEnabled { get; set; }
private ulong _lastSampledTimestampFrame = ulong.MaxValue;
public double LastFlowGpuMs { get; private set; }
public double LastCullGpuMs { get; private set; }
public double LastMarchGpuMs { get; private set; }
public double LastCompGpuMs { get; private set; }
public double LastTotalGpuMs => LastFlowGpuMs + LastCullGpuMs + LastMarchGpuMs + LastCompGpuMs;
public Vector2I LastMarchSize { get; private set; }
public int CurrentMaxSteps { get; private set; } = 10;
public int CurrentMaxIter { get; private set; } = 15;
public VolumetricCompositorEffect() : this(new Texture3Drd(), new VolumetricEmitterPool())
{
}
public VolumetricCompositorEffect(Texture3Drd flowTexRd, VolumetricEmitterPool emitterPool)
{
_flowTexRd = flowTexRd;
_emitterPool = emitterPool;
EffectCallbackType = EffectCallbackTypeEnum.PostSky;
AccessResolvedColor = true;
AccessResolvedDepth = true;
Enabled = true;
}
public void SetEmitterPool(VolumetricEmitterPool pool)
{
_emitterPool = pool ?? throw new ArgumentNullException(nameof(pool));
}
public void ApplyGraphicsSettings(GraphicsSettings settings)
{
ArgumentNullException.ThrowIfNull(settings);
lock (_atmoLock)
{
_resolutionScale = settings.VfxResolution;
_volumetricSamples = settings.VolumetricSamples;
}
}
public void SetAtmosphere(Vector3 sunDir, float sunEnergy, Color sunColor, Color ambientColor, float extinctionScale = 0.28f)
{
lock (_atmoLock)
{
_sunDir = sunDir.LengthSquared() > 1e-5f ? sunDir.Normalized() : Vector3.Up;
_sunEnergy = MathF.Max(0.05f, sunEnergy);
_sunColor = sunColor;
_ambientColor = ambientColor;
_globalExtinctionScale = Math.Clamp(extinctionScale, 0.05f, 2.0f);
}
}
public override void _RenderCallback(int effectCallbackType, RenderData renderData)
{
if (effectCallbackType != (int)EffectCallbackTypeEnum.PostSky || _rdFailed)
{
return;
}
RenderingDevice? rd = RenderingServer.GetRenderingDevice();
if (rd is null)
{
return;
}
if (!_rdInitialized && !TryInitializeRd(rd))
{
_rdFailed = true;
return;
}
if (renderData.GetRenderSceneBuffers() is not RenderSceneBuffersRD sceneBuffers)
{
return;
}
RenderSceneData sceneData = renderData.GetRenderSceneData();
if (sceneData is null)
{
return;
}
Vector2I fullSize = sceneBuffers.GetInternalSize();
if (fullSize.X < 2 || fullSize.Y < 2)
{
return;
}
VfxResolutionScale resScale;
VolumetricSamples volSamples;
Vector3 sunDir;
float sunEnergy;
Color sunCol, ambCol;
float extScale;
lock (_atmoLock)
{
resScale = _resolutionScale;
volSamples = _volumetricSamples;
sunDir = _sunDir;
sunEnergy = _sunEnergy;
sunCol = _sunColor;
ambCol = _ambientColor;
extScale = _globalExtinctionScale;
}
bool isFullRes = resScale == VfxResolutionScale.Full;
float resFactor = GraphicsSettings.GetResolutionScaleFactor(resScale);
Vector2I marchSize = isFullRes
? fullSize
: new Vector2I(
Math.Max(1, (int)MathF.Round(fullSize.X * resFactor)),
Math.Max(1, (int)MathF.Round(fullSize.Y * resFactor)));
int tilesX = Math.Max(1, (marchSize.X + TileSizeHalfRes - 1) / TileSizeHalfRes);
int tilesY = Math.Max(1, (marchSize.Y + TileSizeHalfRes - 1) / TileSizeHalfRes);
int totalTiles = tilesX * tilesY;
(int maxSteps, int maxIter) = GraphicsSettings.GetVolumetricStepBudget(volSamples);
LastMarchSize = marchSize;
CurrentMaxSteps = maxSteps;
CurrentMaxIter = maxIter;
EnsureHalfResAndTileBuffers(rd, marchSize, totalTiles);
uint viewCount = Math.Max(1u, sceneData.GetViewCount());
const uint view = 0u;
Transform3D camXf = sceneData.GetCamTransform();
Projection rawProj = sceneData.GetViewProjection(view);
// Validate reverse-Z projection convention [1..0]
Vector4 testNear = rawProj * new Vector4(0f, 0f, -0.05f, 1f);
Projection revProj = (testNear.W != 0f && (testNear.Z / testNear.W) < 0f)
? Projection.CreateDepthCorrection(flipY: false) * rawProj
: rawProj;
Projection invProj = revProj.Inverse();
Vector4 nearView = invProj * new Vector4(0f, 0f, 1f, 1f);
Vector4 farView = invProj * new Vector4(0f, 0f, 0f, 1f);
float zNear = MathF.Max(0.01f, MathF.Abs(nearView.W) > 1e-6f ? -nearView.Z / nearView.W : 0.05f);
float zFar = MathF.Abs(farView.W) > 1e-6f && (-farView.Z / farView.W) > zNear + 1f
? -farView.Z / farView.W
: 4800f;
float tanHalfFovY = 1f / MathF.Max(1e-4f, MathF.Abs(rawProj.Y.Y));
float aspect = MathF.Abs(rawProj.Y.Y) / MathF.Max(1e-4f, MathF.Abs(rawProj.X.X));
Vector3 camPos = camXf.Origin;
Vector3 camRight = camXf.Basis.X.Normalized();
Vector3 camUp = camXf.Basis.Y.Normalized();
Vector3 camFwd = (-camXf.Basis.Z).Normalized();
_emitterPool.CopyRenderSnapshot(
_emitterUploadBytes,
_impulseUploadBytes,
out int emitterCount,
out int impulseCount,
out float elapsedTime,
out float dt);
Vector3I newVoxelOrigin = new(
(int)MathF.Floor((camPos.X - 96f) / FlowVoxelSizeMeters),
(int)MathF.Floor((camPos.Y - 24f) / FlowVoxelSizeMeters),
(int)MathF.Floor((camPos.Z - 96f) / FlowVoxelSizeMeters));
Vector3I flowDelta = _hasPrevFlowOrigin ? (newVoxelOrigin - _prevFlowVoxelOrigin) : Vector3I.Zero;
_prevFlowVoxelOrigin = newVoxelOrigin;
_hasPrevFlowOrigin = true;
Vector3 flowOriginWorld = new(
newVoxelOrigin.X * FlowVoxelSizeMeters,
newVoxelOrigin.Y * FlowVoxelSizeMeters,
newVoxelOrigin.Z * FlowVoxelSizeMeters);
Vector3 flowInvExtent = new(
1f / (FlowDimX * FlowVoxelSizeMeters),
1f / (FlowDimY * FlowVoxelSizeMeters),
1f / (FlowDimZ * FlowVoxelSizeMeters));
_frameCounter++;
var ubo = new VolumetricFrameUbo
{
InvProj0 = invProj.X,
InvProj1 = invProj.Y,
InvProj2 = invProj.Z,
InvProj3 = invProj.W,
CamPosTime = new Vector4(camPos.X, camPos.Y, camPos.Z, elapsedTime),
CamRightAspect = new Vector4(camRight.X, camRight.Y, camRight.Z, aspect),
CamUpTanHalfFov = new Vector4(camUp.X, camUp.Y, camUp.Z, tanHalfFovY),
CamFwdNearFar = new Vector4(camFwd.X, camFwd.Y, camFwd.Z, 0f),
SunDirIntensity = new Vector4(sunDir.X, sunDir.Y, sunDir.Z, sunEnergy),
SunColorExt = new Vector4(sunCol.R, sunCol.G, sunCol.B, extScale),
AmbientColorFog = new Vector4(ambCol.R, ambCol.G, ambCol.B, zNear),
ViewportInfo = new Vector4(fullSize.X, fullSize.Y, zFar, emitterCount),
HalfW = (uint)marchSize.X,
HalfH = (uint)marchSize.Y,
TilesX = (uint)tilesX,
FrameIndex = _frameCounter,
FlowOriginVoxel = new Vector4(flowOriginWorld.X, flowOriginWorld.Y, flowOriginWorld.Z, FlowVoxelSizeMeters),
FlowInvExtentDt = new Vector4(flowInvExtent.X, flowInvExtent.Y, flowInvExtent.Z, dt),
DeltaX = flowDelta.X,
DeltaY = flowDelta.Y,
DeltaZ = flowDelta.Z,
ImpulseCount = impulseCount,
MaxSteps = (uint)maxSteps,
MaxIter = (uint)maxIter,
IsFullRes = isFullRes ? 1u : 0u,
QualityPad = 0u
};
MemoryMarshal.Write(_uboBytes, in ubo);
rd.BufferUpdate(_frameUboRid, 0, FrameUboBytes, _uboBytes);
if (emitterCount > 0)
{
uint emBytes = (uint)(emitterCount * VolumetricEmitterPool.EmitterStrideBytes);
rd.BufferUpdate(_emitterSsboRid, 0, emBytes, _emitterUploadBytes);
}
if (impulseCount > 0)
{
uint impBytes = (uint)(impulseCount * VolumetricEmitterPool.ImpulseStrideBytes);
rd.BufferUpdate(_impulseSsboRid, 0, impBytes, _impulseUploadBytes);
}
int writeIdx = 1 - _flowReadIdx;
Rid prevFlowRid = _flowTexRids[_flowReadIdx];
Rid nextFlowRid = _flowTexRids[writeIdx];
bool captureThisFrame = ProfilingEnabled && (_frameCounter & 7u) == 0u && _frameCounter >= 24u && rd.GetCapturedTimestampsCount() < 180;
if (ProfilingEnabled)
{
SamplePreviousFrameTimestamps(rd);
}
if (captureThisFrame)
{
rd.CaptureTimestamp("Cut10b_FlowStart");
}
// Compute pass list (Pass 0 always; Passes 1-3 whenever active emitters exist)
long computeList = rd.ComputeListBegin();
// Pass 0: flow_field_step (64x24x64 / 8x4x8 = 8x6x8 groups)
Rid flowSet = GetPass0UniformSet(prevFlowRid, nextFlowRid);
rd.ComputeListBindComputePipeline(computeList, _flowPipeRid);
rd.ComputeListBindUniformSet(computeList, flowSet, 0);
rd.ComputeListDispatch(computeList, 8, 6, 8);
if (emitterCount > 0)
{
for (uint v = 0; v < viewCount; v++)
{
Rid colorLayer = sceneBuffers.GetColorLayer(v, false);
Rid depthLayer = sceneBuffers.GetDepthLayer(v, false);
if (!colorLayer.IsValid || !depthLayer.IsValid)
{
continue;
}
// Pass 1: volumetric_tile_cull
rd.ComputeListAddBarrier(computeList);
if (captureThisFrame && v == 0)
{
rd.ComputeListEnd();
rd.CaptureTimestamp("Cut10b_CullStart");
computeList = rd.ComputeListBegin();
}
Rid cullSet = GetPass1UniformSet(depthLayer);
rd.ComputeListBindComputePipeline(computeList, _cullPipeRid);
rd.ComputeListBindUniformSet(computeList, cullSet, 0);
rd.ComputeListDispatch(computeList, (uint)tilesX, (uint)tilesY, 1);
// Pass 2: volumetric_raymarch (reading freshly updated nextFlowRid!)
rd.ComputeListAddBarrier(computeList);
if (captureThisFrame && v == 0)
{
rd.ComputeListEnd();
rd.CaptureTimestamp("Cut10b_MarchStart");
computeList = rd.ComputeListBegin();
}
Rid marchSet = GetPass2UniformSet(depthLayer, nextFlowRid);
rd.ComputeListBindComputePipeline(computeList, _marchPipeRid);
rd.ComputeListBindUniformSet(computeList, marchSet, 0);
rd.ComputeListDispatch(computeList, (uint)tilesX, (uint)tilesY, 1);
// Pass 3: volumetric_composite (2x2 bilateral depth upsample -> colorLayer)
rd.ComputeListAddBarrier(computeList);
if (captureThisFrame && v == 0)
{
rd.ComputeListEnd();
rd.CaptureTimestamp("Cut10b_CompStart");
computeList = rd.ComputeListBegin();
}
Rid compSet = GetPass3UniformSet(depthLayer, colorLayer);
rd.ComputeListBindComputePipeline(computeList, _compPipeRid);
rd.ComputeListBindUniformSet(computeList, compSet, 0);
uint compGroupsX = (uint)((fullSize.X + 15) / 16);
uint compGroupsY = (uint)((fullSize.Y + 15) / 16);
rd.ComputeListDispatch(computeList, compGroupsX, compGroupsY, 1);
}
}
rd.ComputeListEnd();
if (captureThisFrame)
{
rd.CaptureTimestamp("Cut10b_End");
}
// Advance ping-pong & update global Texture3Drd + flow origin for GPUParticles3D
_flowReadIdx = writeIdx;
_flowTexRd.TextureRdRid = nextFlowRid;
RenderingServer.GlobalShaderParameterSet("rtd_flow_origin", flowOriginWorld);
RenderingServer.GlobalShaderParameterSet("rtd_flow_inv_extent", flowInvExtent);
}
private void SamplePreviousFrameTimestamps(RenderingDevice rd)
{
uint count = rd.GetCapturedTimestampsCount();
if (count == 0)
{
return;
}
ulong tsFrame = rd.GetCapturedTimestampsFrame();
if (tsFrame == _lastSampledTimestampFrame)
{
return;
}
_lastSampledTimestampFrame = tsFrame;
ulong tFlow = 0, tCull = 0, tMarch = 0, tComp = 0, tEnd = 0;
for (uint i = 0; i < count; i++)
{
string name = rd.GetCapturedTimestampName(i);
switch (name)
{
case "Cut10b_FlowStart": tFlow = rd.GetCapturedTimestampGpuTime(i); break;
case "Cut10b_CullStart": tCull = rd.GetCapturedTimestampGpuTime(i); break;
case "Cut10b_MarchStart": tMarch = rd.GetCapturedTimestampGpuTime(i); break;
case "Cut10b_CompStart": tComp = rd.GetCapturedTimestampGpuTime(i); break;
case "Cut10b_End": tEnd = rd.GetCapturedTimestampGpuTime(i); break;
}
}
// Godot 4.7 Vulkan GetCapturedTimestampGpuTime empirically returns nanoseconds (confirmed vs --gpu-profile; GodotSharp.xml's "microseconds" doc is stale)
if (tFlow > 0 && tEnd >= tFlow)
{
if (tCull > tFlow && tMarch > tCull && tComp > tMarch && tEnd >= tComp)
{
LastFlowGpuMs = (tCull - tFlow) / 1_000_000.0;
LastCullGpuMs = (tMarch - tCull) / 1_000_000.0;
LastMarchGpuMs = (tComp - tMarch) / 1_000_000.0;
LastCompGpuMs = (tEnd - tComp) / 1_000_000.0;
}
else
{
LastFlowGpuMs = (tEnd - tFlow) / 1_000_000.0;
LastCullGpuMs = 0.0;
LastMarchGpuMs = 0.0;
LastCompGpuMs = 0.0;
}
}
}
private bool TryInitializeRd(RenderingDevice rd)
{
_rd = rd;
if (!TryCompileCompute(rd, "res://flow_field_step.glsl", "flow_field_step", out _flowShaderRid, out _flowPipeRid) ||
!TryCompileCompute(rd, "res://volumetric_tile_cull.glsl", "volumetric_tile_cull", out _cullShaderRid, out _cullPipeRid) ||
!TryCompileCompute(rd, "res://volumetric_raymarch.glsl", "volumetric_raymarch", out _marchShaderRid, out _marchPipeRid) ||
!TryCompileCompute(rd, "res://volumetric_composite.glsl", "volumetric_composite", out _compShaderRid, out _compPipeRid))
{
return false;
}
var nearestState = new RDSamplerState
{
MinFilter = RenderingDevice.SamplerFilter.Nearest,
MagFilter = RenderingDevice.SamplerFilter.Nearest,
RepeatU = RenderingDevice.SamplerRepeatMode.ClampToEdge,
RepeatV = RenderingDevice.SamplerRepeatMode.ClampToEdge,
RepeatW = RenderingDevice.SamplerRepeatMode.ClampToEdge
};
_nearestSamplerRid = rd.SamplerCreate(nearestState);
var linearState = new RDSamplerState
{
MinFilter = RenderingDevice.SamplerFilter.Linear,
MagFilter = RenderingDevice.SamplerFilter.Linear,
RepeatU = RenderingDevice.SamplerRepeatMode.ClampToEdge,
RepeatV = RenderingDevice.SamplerRepeatMode.ClampToEdge,
RepeatW = RenderingDevice.SamplerRepeatMode.ClampToEdge
};
_linearSamplerRid = rd.SamplerCreate(linearState);
var flowFmt = new RDTextureFormat
{
TextureType = RenderingDevice.TextureType.Type3D,
Format = RenderingDevice.DataFormat.R16G16B16A16Sfloat,
Width = FlowDimX,
Height = FlowDimY,
Depth = FlowDimZ,
Mipmaps = 1,
ArrayLayers = 1,
Samples = RenderingDevice.TextureSamples.Samples1,
UsageBits = RenderingDevice.TextureUsageBits.SamplingBit | RenderingDevice.TextureUsageBits.StorageBit
};
byte[] zero3d = new byte[FlowDimX * FlowDimY * FlowDimZ * 8];
var initArr = new Godot.Collections.Array<byte[]> { zero3d };
_flowTexRids[0] = rd.TextureCreate(flowFmt, new RDTextureView(), initArr);
_flowTexRids[1] = rd.TextureCreate(flowFmt, new RDTextureView(), initArr);
_flowReadIdx = 0;
_flowTexRd.TextureRdRid = _flowTexRids[0];
_frameUboRid = rd.UniformBufferCreate(FrameUboBytes, new byte[FrameUboBytes]);
_emitterSsboRid = rd.StorageBufferCreate(
(uint)(VolumetricEmitterPool.MaxEmitters * VolumetricEmitterPool.EmitterStrideBytes),
new byte[VolumetricEmitterPool.MaxEmitters * VolumetricEmitterPool.EmitterStrideBytes]);
_impulseSsboRid = rd.StorageBufferCreate(
(uint)(VolumetricEmitterPool.MaxFlowImpulses * VolumetricEmitterPool.ImpulseStrideBytes),
new byte[VolumetricEmitterPool.MaxFlowImpulses * VolumetricEmitterPool.ImpulseStrideBytes]);
_rdInitialized = true;
return true;
}
private static bool TryCompileCompute(
RenderingDevice rd,
string resPath,
string debugName,
out Rid shaderRid,
out Rid pipeRid)
{
shaderRid = new Rid();
pipeRid = new Rid();
string source = FileAccess.GetFileAsString(resPath);
if (string.IsNullOrWhiteSpace(source))
{
GD.PrintErr($"VolumetricCompositorEffect: missing compute shader '{resPath}'");
return false;
}
using var rdSrc = new RDShaderSource
{
Language = RenderingDevice.ShaderLanguage.Glsl,
SourceCompute = source
};
using RDShaderSpirV spirv = rd.ShaderCompileSpirVFromSource(rdSrc, allowCache: true);
string err = spirv.CompileErrorCompute;
if (!string.IsNullOrEmpty(err))
{
GD.PrintErr($"VolumetricCompositorEffect: SPIR-V compile error in '{resPath}': {err}");
return false;
}
shaderRid = rd.ShaderCreateFromSpirV(spirv, debugName);
if (!shaderRid.IsValid)
{
GD.PrintErr($"VolumetricCompositorEffect: ShaderCreateFromSpirV failed for '{resPath}'");
return false;
}
pipeRid = rd.ComputePipelineCreate(shaderRid);
if (!pipeRid.IsValid)
{
GD.PrintErr($"VolumetricCompositorEffect: ComputePipelineCreate failed for '{resPath}'");
return false;
}
return true;
}
private void EnsureHalfResAndTileBuffers(RenderingDevice rd, Vector2I halfSize, int totalTiles)
{
if (!_halfVolRid.IsValid || _halfVolSize != halfSize)
{
if (_halfVolRid.IsValid)
{
rd.FreeRid(_halfVolRid);
}
var fmt = new RDTextureFormat
{
TextureType = RenderingDevice.TextureType.Type2D,
Format = RenderingDevice.DataFormat.R16G16B16A16Sfloat,
Width = (uint)halfSize.X,
Height = (uint)halfSize.Y,
Depth = 1,
Mipmaps = 1,
ArrayLayers = 1,
Samples = RenderingDevice.TextureSamples.Samples1,
UsageBits = RenderingDevice.TextureUsageBits.SamplingBit | RenderingDevice.TextureUsageBits.StorageBit
};
_halfVolRid = rd.TextureCreate(fmt, new RDTextureView());
_halfVolSize = halfSize;
}
if (!_tileSsboRid.IsValid || _tileSsboCapacityTiles < totalTiles)
{
if (_tileSsboRid.IsValid)
{
rd.FreeRid(_tileSsboRid);
}
_tileSsboCapacityTiles = Math.Max(totalTiles, 2048);
uint sizeBytes = (uint)(_tileSsboCapacityTiles * TileStrideBytes);
_tileSsboRid = rd.StorageBufferCreate(sizeBytes, new byte[sizeBytes]);
}
}
private Rid GetPass0UniformSet(Rid prevFlowRid, Rid nextFlowRid)
{
var u0 = new RDUniform { UniformType = RenderingDevice.UniformType.UniformBuffer, Binding = 0 };
u0.AddId(_frameUboRid);
var u1 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 1 };
u1.AddId(_impulseSsboRid);
var u2 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 2 };
u2.AddId(_linearSamplerRid);
u2.AddId(prevFlowRid);
var u3 = new RDUniform { UniformType = RenderingDevice.UniformType.Image, Binding = 3 };
u3.AddId(nextFlowRid);
return UniformSetCacheRD.GetCache(_flowShaderRid, 0, new Godot.Collections.Array<RDUniform> { u0, u1, u2, u3 });
}
private Rid GetPass1UniformSet(Rid depthLayer)
{
var u0 = new RDUniform { UniformType = RenderingDevice.UniformType.UniformBuffer, Binding = 0 };
u0.AddId(_frameUboRid);
var u1 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 1 };
u1.AddId(_emitterSsboRid);
var u2 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 2 };
u2.AddId(_tileSsboRid);
var u3 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 3 };
u3.AddId(_nearestSamplerRid);
u3.AddId(depthLayer);
return UniformSetCacheRD.GetCache(_cullShaderRid, 0, new Godot.Collections.Array<RDUniform> { u0, u1, u2, u3 });
}
private Rid GetPass2UniformSet(Rid depthLayer, Rid flowTexRid)
{
var u0 = new RDUniform { UniformType = RenderingDevice.UniformType.UniformBuffer, Binding = 0 };
u0.AddId(_frameUboRid);
var u1 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 1 };
u1.AddId(_emitterSsboRid);
var u2 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 2 };
u2.AddId(_tileSsboRid);
var u3 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 3 };
u3.AddId(_nearestSamplerRid);
u3.AddId(depthLayer);
var u4 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 4 };
u4.AddId(_linearSamplerRid);
u4.AddId(flowTexRid);
var u5 = new RDUniform { UniformType = RenderingDevice.UniformType.Image, Binding = 5 };
u5.AddId(_halfVolRid);
return UniformSetCacheRD.GetCache(_marchShaderRid, 0, new Godot.Collections.Array<RDUniform> { u0, u1, u2, u3, u4, u5 });
}
private Rid GetPass3UniformSet(Rid depthLayer, Rid colorLayer)
{
var u0 = new RDUniform { UniformType = RenderingDevice.UniformType.UniformBuffer, Binding = 0 };
u0.AddId(_frameUboRid);
var u1 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 1 };
u1.AddId(_nearestSamplerRid);
u1.AddId(depthLayer);
var u2 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 2 };
u2.AddId(_nearestSamplerRid);
u2.AddId(_halfVolRid);
var u3 = new RDUniform { UniformType = RenderingDevice.UniformType.Image, Binding = 3 };
u3.AddId(colorLayer);
var u4 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 4 };
u4.AddId(_tileSsboRid);
return UniformSetCacheRD.GetCache(_compShaderRid, 0, new Godot.Collections.Array<RDUniform> { u0, u1, u2, u3, u4 });
}
public void DisposeRdResources()
{
if (!_rdInitialized || _rd is null)
{
return;
}
_rdInitialized = false;
Enabled = false;
if (_flowTexRd is not null)
{
_flowTexRd.TextureRdRid = new Rid();
}
FreeIfValid(_rd, ref _flowTexRids[0]);
FreeIfValid(_rd, ref _flowTexRids[1]);
FreeIfValid(_rd, ref _halfVolRid);
FreeIfValid(_rd, ref _frameUboRid);
FreeIfValid(_rd, ref _emitterSsboRid);
FreeIfValid(_rd, ref _impulseSsboRid);
FreeIfValid(_rd, ref _tileSsboRid);
FreeIfValid(_rd, ref _nearestSamplerRid);
FreeIfValid(_rd, ref _linearSamplerRid);
// Free shaders (automatically cleans up dependent pipelines in Godot RD)
_flowPipeRid = new Rid();
_cullPipeRid = new Rid();
_marchPipeRid = new Rid();
_compPipeRid = new Rid();
FreeIfValid(_rd, ref _flowShaderRid);
FreeIfValid(_rd, ref _cullShaderRid);
FreeIfValid(_rd, ref _marchShaderRid);
FreeIfValid(_rd, ref _compShaderRid);
_rd = null;
}
public override void _Notification(int what)
{
if (what != NotificationPredelete)
{
return;
}
// Only release if still alive and not already cleaned up in AtmosphereSystem._ExitTree
if (_flowTexRd is not null)
{
_flowTexRd.TextureRdRid = new Rid();
}
if (_rdInitialized && RenderingServer.GetRenderingDevice() is not null)
{
DisposeRdResources();
}
}
private static void FreeIfValid(RenderingDevice rd, ref Rid rid)
{
if (rid.IsValid)
{
rd.FreeRid(rid);
rid = new Rid();
}
}
}

File diff suppressed because it is too large Load diff

48
client/export_presets.cfg Normal file
View file

@ -0,0 +1,48 @@
[preset.0]
name="Windows Desktop"
platform="Windows Desktop"
runnable=true
advanced_options=false
dedicated_server=false
custom_features=""
export_filter="all_resources"
include_filter="*.glsl"
exclude_filter="tests/*,*.uid"
export_path=""
patches=PackedStringArray()
encryption_include_filters=""
encryption_exclude_filters=""
seed=0
encrypt_pck=false
encrypt_directory=false
script_export_mode=2
[preset.0.options]
custom_template/debug=""
custom_template/release=""
debug/export_console_wrapper=1
binary_format/embed_pck=false
texture_format/s3tc_bptc=true
texture_format/etc2_astc=false
shader_baker/enabled=false
binary_format/architecture="x86_64"
codesign/enable=false
application/modify_resources=true
application/icon=""
application/console_wrapper_icon=""
application/icon_interpolation=4
application/file_version=""
application/product_version=""
application/company_name="GameCult"
application/product_name="Rust to Dust"
application/file_description="Rust to Dust"
application/copyright=""
application/trademarks=""
application/export_angle=0
application/export_d3d12=0
application/d3d12_agility_sdk_multiarch=true
ssh_remote_deploy/enabled=false
dotnet/include_scripts_content=false
dotnet/include_debug_symbols=false

View file

@ -6,6 +6,7 @@ render_mode blend_mix;
uniform sampler2D screen_tex : hint_screen_texture, filter_nearest;
uniform float grain_strength : hint_range(0.0, 0.1) = 0.018;
uniform float post_gamma : hint_range(0.5, 2.5) = 1.32;
float interleaved_gradient_noise(vec2 frag_xy, float frame_idx) {
vec2 p = frag_xy + vec2(frame_idx * 17.0, frame_idx * 31.0);
@ -14,12 +15,13 @@ float interleaved_gradient_noise(vec2 frag_xy, float frame_idx) {
void fragment() {
vec4 src = texture(screen_tex, SCREEN_UV);
vec3 graded = pow(max(src.rgb, vec3(0.0)), vec3(post_gamma));
float frame_idx = mod(floor(fract(TIME * 0.001) * 60000.0), 64.0);
float n = interleaved_gradient_noise(FRAGCOORD.xy, frame_idx);
float luma = dot(src.rgb, vec3(0.2126, 0.7152, 0.0722));
float luma = dot(graded, vec3(0.2126, 0.7152, 0.0722));
float midtone_weight = smoothstep(0.02, 0.18, luma) * (1.0 - 0.65 * smoothstep(0.65, 1.0, luma));
vec3 grained = clamp(src.rgb + vec3((n - 0.5) * 2.0 * grain_strength * midtone_weight), vec3(0.0), vec3(1.0));
vec3 grained = clamp(graded + vec3((n - 0.5) * 2.0 * grain_strength * midtone_weight), vec3(0.0), vec3(1.0));
COLOR = vec4(grained, src.a);
}

Some files were not shown because too many files have changed in this diff Show more