Transfer planetary geometry into GameCult.Geometry

This commit is contained in:
Meta Vens 2026-07-22 03:47:57 +01:00
commit 756f5a3337
70 changed files with 4105 additions and 31 deletions

View file

@ -7,6 +7,9 @@ depends on `org.gamecult.cultmath` for numeric primitives and
Build it with `scripts/build-geometry-unity-package.ps1`. Do not edit generated
plugin assemblies in the package output.
CultLib-authored files are MIT licensed. Geometry sources transferred from
CultMath retain their MPL-2.0 notices and provenance; those files will be listed
here as they enter this package. No transferred CultMath source is relicensed.
CultLib-authored integration files are MIT licensed. The planetary C# compiled
into `GameCult.Geometry.dll` and the geometry HLSL under `Shaders` are
MPL-2.0 and retain their source notices and provenance. See `LICENSES.md` and
`THIRD-PARTY-NOTICES.md` in the staged package. No MPL-covered source is
relicensed. The package manifest therefore uses `SEE LICENSES IN README.md`
rather than claiming one license for every file.

View file

@ -0,0 +1,8 @@
{
"name": "GameCult.Geometry.Unity",
"rootNamespace": "GameCult.Geometry.Unity",
"references": ["CultMath", "GameCult.Geometry"],
"includePlatforms": [], "excludePlatforms": [], "allowUnsafeCode": false,
"overrideReferences": false, "precompiledReferences": [], "autoReferenced": true,
"defineConstraints": [], "versionDefines": [], "noEngineReferences": false
}

View file

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using CultMath;
using UnityEngine;
namespace GameCult.Geometry.Unity;
[StructLayout(LayoutKind.Sequential)] public readonly struct PlanetaryPageInputGpu { public PlanetaryPageInputGpu(Vector4 directionRadius, Vector4 sampling) { DirectionRadius = directionRadius; Sampling = sampling; } public readonly Vector4 DirectionRadius; public readonly Vector4 Sampling; }
[StructLayout(LayoutKind.Sequential)] public readonly struct PlanetaryPageMetadataGpu { public PlanetaryPageMetadataGpu(Vector4 address, Vector4 layout, Vector4 bounds, Vector4 state) { Address = address; Layout = layout; Bounds = bounds; State = state; } public readonly Vector4 Address; public readonly Vector4 Layout; public readonly Vector4 Bounds; public readonly Vector4 State; }
public readonly struct PlanetaryPageUpload { public PlanetaryPageUpload(PlanetaryPageInputGpu[] inputs, PlanetaryPageMetadataGpu[] metadata, int outputSampleCount, ulong contentVersion, ulong presentationVersion) { Inputs = inputs; Metadata = metadata; OutputSampleCount = outputSampleCount; ContentVersion = contentVersion; PresentationVersion = presentationVersion; } public PlanetaryPageInputGpu[] Inputs { get; } public PlanetaryPageMetadataGpu[] Metadata { get; } public int OutputSampleCount { get; } public ulong ContentVersion { get; } public ulong PresentationVersion { get; } }
public static class PlanetaryPageUploadBuilder
{
public static PlanetaryPageUpload Build(in PlanetaryResidencySnapshot snapshot, int interiorSize, int borderSize, float radius)
{
if (!float.IsFinite(radius) || radius <= 0) throw new ArgumentOutOfRangeException(nameof(radius));
var inputs = new List<PlanetaryPageInputGpu>(); var metadata = new PlanetaryPageMetadataGpu[snapshot.Tiles.Length];
foreach (var (resident, pageIndex) in snapshot.Tiles.Select((resident, index) => (resident, index)))
{
var content = PlanetaryGpuPageBuilder.BuildContent(new PlanetaryPageLayout(resident.Tile, interiorSize, borderSize).Validate(), radius); var outputOffset = inputs.Count;
foreach (var input in content.Inputs) inputs.Add(new(ToUnity(input.DirectionRadius), ToUnity(input.Sampling)));
var common = PlanetaryGpuPageBuilder.Metadata(content, outputOffset, resident.Blend);
metadata[pageIndex] = new(ToUnity(common.Address), ToUnity(common.Layout), ToUnity(common.Bounds), ToUnity(common.State));
}
return new(inputs.ToArray(), metadata, inputs.Count, snapshot.ContentVersion, snapshot.PresentationVersion);
}
private static Vector4 ToUnity(float4 value) => new(value.x, value.y, value.z, value.w);
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7edd3bb2edb2e6448a2d54fc082c27dc

View file

@ -0,0 +1,27 @@
using System;
using CultMath;
using UnityEngine;
using UnityEngine.Rendering;
namespace GameCult.Geometry.Unity;
public static class PlanetaryPatchMeshAdapter
{
public static Mesh CreateFaceMesh(PlanetaryCubeFace face, int cellsPerAxis, float radius = 1)
{
if (!float.IsFinite(radius) || radius <= 0) throw new ArgumentOutOfRangeException(nameof(radius));
var source = PlanetaryPatch.CreateFace(face, cellsPerAxis);
var vertices = new Vector3[source.Vertices.Length];
var normals = new Vector3[source.Vertices.Length];
var uv = new Vector2[source.Vertices.Length];
for (var i = 0; i < source.Vertices.Length; i++)
{
var direction = source.Vertices[i].UnitDirection;
var normal = new Vector3(direction.x, direction.y, direction.z);
vertices[i] = normal * radius; normals[i] = normal;
uv[i] = new Vector2(source.Vertices[i].LocalCoordinate.x, source.Vertices[i].LocalCoordinate.y);
}
var mesh = new Mesh { name = $"GameCult.Geometry Planetary {face} {cellsPerAxis}x{cellsPerAxis}", indexFormat = vertices.Length > ushort.MaxValue ? IndexFormat.UInt32 : IndexFormat.UInt16, vertices = vertices, normals = normals, uv = uv, triangles = source.Indices };
mesh.RecalculateBounds(); return mesh;
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9ad7b581e14ef774d8435069bb77ca6a

View file

@ -0,0 +1 @@
{"name":"GameCult.Geometry.PlanetaryViewer.Editor","rootNamespace":"GameCult.Geometry.Unity.Samples.Editor","references":["GameCult.Geometry.PlanetaryViewer"],"includePlatforms":["Editor"],"excludePlatforms":[],"allowUnsafeCode":false,"overrideReferences":false,"precompiledReferences":[],"autoReferenced":true,"defineConstraints":[],"versionDefines":[],"noEngineReferences":false}

View file

@ -0,0 +1,27 @@
using UnityEditor;
using UnityEngine;
using GameCult.Geometry.Unity.Samples;
namespace GameCult.Geometry.Unity.Samples.Editor;
public static class GameCultGeometryPlanetaryViewerMenu
{
[MenuItem("GameObject/GameCult.Geometry/Planetary Field Viewer", false, 10)]
public static void CreateViewer()
{
var root = new GameObject("GameCult.Geometry Planetary Field Viewer");
Undo.RegisterCreatedObjectUndo(root, "Create GameCult.Geometry Planetary Viewer");
root.AddComponent<GameCultGeometryPlanetaryViewer>();
Selection.activeGameObject = root;
if (Camera.main != null) return;
var cameraObject = new GameObject("Planetary Viewer Camera");
Undo.RegisterCreatedObjectUndo(cameraObject, "Create Planetary Viewer Camera");
cameraObject.tag = "MainCamera";
cameraObject.transform.position = new Vector3(0, 0, -24);
cameraObject.transform.LookAt(root.transform);
var camera = cameraObject.AddComponent<Camera>();
camera.nearClipPlane = 0.01f;
camera.farClipPlane = 1000;
}
}

View file

@ -0,0 +1,7 @@
# Planetary Field Viewer
Import this sample through Unity Package Manager, then choose
`GameObject > GameCult.Geometry > Planetary Field Viewer`.
The six-face mesh and planetary field are owned by GameCult.Geometry and use
CultMath numeric primitives. This is a renderer fixture, not gameplay state.

View file

@ -0,0 +1 @@
{"name":"GameCult.Geometry.PlanetaryViewer","rootNamespace":"GameCult.Geometry.Unity.Samples","references":["CultMath","GameCult.Geometry","GameCult.Geometry.Unity"],"includePlatforms":[],"excludePlatforms":[],"allowUnsafeCode":false,"overrideReferences":false,"precompiledReferences":[],"autoReferenced":true,"defineConstraints":[],"versionDefines":[],"noEngineReferences":false}

View file

@ -0,0 +1,141 @@
using System;
using System.Collections.Generic;
using CultMath;
using GameCult.Geometry;
using UnityEngine;
namespace GameCult.Geometry.Unity.Samples;
[ExecuteAlways]
public sealed class GameCultGeometryPlanetaryViewer : MonoBehaviour
{
[Min(0.001f)] public float Radius = 8.4f;
[Range(1, 256)] public int CellsPerFace = 64;
public int Seed = 42;
[Min(0.0001f)] public float SampleFootprint = 0.01f;
public Shader? PlanetShader;
public Vector3 LightDirection = new(-0.4f, 0.7f, -0.6f);
public Color LowColor = new(0.055f, 0.16f, 0.09f, 1);
public Color HighColor = new(0.62f, 0.48f, 0.28f, 1);
public Color RidgeColor = new(0.88f, 0.83f, 0.7f, 1);
private readonly List<Mesh> meshes = new();
private Material? material;
private int builtCells;
public PlanetaryFieldDefinition Definition => PlanetaryFieldDefinition.Create(
1,
Radius,
Seed,
ViewerErosion(Radius));
public PlanetarySurfaceSample Sample(float3 direction)
{
var source = new ViewerBaseField(Radius);
var normalized = math.normalize(direction);
return PlanetaryField.Sample(Definition, normalized, source.Sample(normalized), PlanetaryQueryScale.AtFootprint(SampleFootprint));
}
private void OnEnable() => Rebuild();
private void OnValidate()
{
Radius = Mathf.Max(Radius, 0.001f);
CellsPerFace = Mathf.Clamp(CellsPerFace, 1, 256);
SampleFootprint = Mathf.Max(SampleFootprint, 0.0001f);
if (isActiveAndEnabled) Rebuild();
}
private void Update()
{
if (builtCells != CellsPerFace || material == null) Rebuild();
ApplyMaterial();
}
private void Rebuild()
{
ClearGenerated();
PlanetShader ??= Shader.Find("GameCult.Geometry/Planetary Field Viewer");
if (PlanetShader == null) return;
material = new Material(PlanetShader) { name = "CultMath Planetary Viewer Material", hideFlags = HideFlags.HideAndDontSave };
foreach (var face in (PlanetaryCubeFace[])Enum.GetValues(typeof(PlanetaryCubeFace)))
{
var mesh = PlanetaryPatchMeshAdapter.CreateFaceMesh(face, CellsPerFace);
mesh.hideFlags = HideFlags.HideAndDontSave;
meshes.Add(mesh);
var child = new GameObject(face.ToString()) { hideFlags = HideFlags.DontSave };
child.transform.SetParent(transform, false);
child.AddComponent<MeshFilter>().sharedMesh = mesh;
child.AddComponent<MeshRenderer>().sharedMaterial = material;
}
builtCells = CellsPerFace;
ApplyMaterial();
}
private void ApplyMaterial()
{
if (material == null) return;
var p = ViewerErosion(Radius);
material.SetFloat("_Radius", Radius);
material.SetFloat("_SampleFootprint", SampleFootprint);
material.SetInt("_Seed", Seed);
material.SetFloat("_ErosionScale", p.Scale);
material.SetFloat("_ErosionStrength", p.Strength);
material.SetFloat("_GullyWeight", p.GullyWeight);
material.SetFloat("_Detail", p.Detail);
material.SetVector("_Rounding", new(p.Rounding.x, p.Rounding.y, p.Rounding.z, p.Rounding.w));
material.SetVector("_Onset", new(p.Onset.x, p.Onset.y, p.Onset.z, p.Onset.w));
material.SetVector("_AssumedSlope", new(p.AssumedSlope.x, p.AssumedSlope.y, 0, 0));
material.SetFloat("_CellScale", p.CellScale);
material.SetFloat("_Normalization", p.Normalization);
material.SetInt("_Octaves", p.Octaves);
material.SetFloat("_Lacunarity", p.Lacunarity);
material.SetFloat("_Gain", p.Gain);
material.SetVector("_LightDirection", LightDirection.normalized);
material.SetColor("_LowColor", LowColor);
material.SetColor("_HighColor", HighColor);
material.SetColor("_RidgeColor", RidgeColor);
}
private void OnDisable() => ClearGenerated();
private void OnDestroy() => ClearGenerated();
private void ClearGenerated()
{
for (var i = transform.childCount - 1; i >= 0; i--) DestroyGenerated(transform.GetChild(i).gameObject);
foreach (var mesh in meshes) DestroyGenerated(mesh);
meshes.Clear();
if (material != null) DestroyGenerated(material);
material = null;
builtCells = 0;
}
private static void DestroyGenerated(UnityEngine.Object value)
{
if (Application.isPlaying) Destroy(value);
else DestroyImmediate(value);
}
private static AdvancedErosionParameters ViewerErosion(float radius) => new(
radius * 0.075f, 0.12f, 0.58f, 1.45f,
new float4(0.1f, 0.015f, 0.1f, 2),
new float4(1.25f, 1.25f, 2.8f, 1.5f),
new float2(0.7f, 0.85f), 0.7f, 0.5f, 7, 2, 0.5f);
private readonly struct ViewerBaseField : IPlanetaryBaseField
{
private readonly float radius;
public ViewerBaseField(float radius) => this.radius = radius;
public PlanetaryBaseFieldSample Sample(float3 direction)
{
var value = direction.x * 0.6f + direction.y * direction.z * 0.3f;
var angularGradient = new float3(0.6f, direction.z * 0.3f, direction.y * 0.3f);
angularGradient -= direction * math.dot(angularGradient, direction);
var fieldGradient = angularGradient / radius;
var radialDisplacement = value * radius * 0.035f;
var radialGradient = angularGradient * 0.035f;
return new(radialDisplacement, radialGradient, value, fieldGradient, math.clamp(value, -1, 1));
}
}
}

View file

@ -0,0 +1,91 @@
Shader "GameCult.Geometry/Planetary Field Viewer"
{
Properties
{
_LowColor ("Low Color", Color) = (0.055, 0.16, 0.09, 1)
_HighColor ("High Color", Color) = (0.62, 0.48, 0.28, 1)
_RidgeColor ("Ridge Color", Color) = (0.88, 0.83, 0.7, 1)
}
SubShader
{
Tags { "RenderType"="Opaque" "Queue"="Geometry" }
Pass
{
Cull Back
ZWrite On
HLSLPROGRAM
#pragma target 5.0
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
#define GAMECULT_GEOMETRY_CULTMATH_INCLUDE "Packages/org.gamecult.cultmath/shaders/CultMath.hlsl"
#include "Packages/org.gamecult.geometry/Shaders/GameCult.Geometry.hlsl"
float _Radius;
float _SampleFootprint;
int _Seed;
float _ErosionScale, _ErosionStrength, _GullyWeight, _Detail;
float4 _Rounding, _Onset, _AssumedSlope;
float _CellScale, _Normalization, _Lacunarity, _Gain;
int _Octaves;
float3 _LightDirection;
float4 _LowColor, _HighColor, _RidgeColor;
struct Attributes { float4 vertex : POSITION; };
struct Varyings
{
float4 position : SV_POSITION;
float3 worldNormal : TEXCOORD0;
float height : TEXCOORD1;
float ridge : TEXCOORD2;
};
GameCultGeometryPlanetarySurfaceSample viewer_sample(float3 direction)
{
direction = normalize(direction);
float value = direction.x * 0.6 + direction.y * direction.z * 0.3;
float3 angular_gradient = float3(0.6, direction.z * 0.3, direction.y * 0.3);
angular_gradient -= direction * dot(angular_gradient, direction);
GameCultGeometryPlanetaryBaseFieldSample base_sample;
base_sample.radial_displacement = value * _Radius * 0.035;
base_sample.radial_gradient = angular_gradient * 0.035;
base_sample.field_value = value;
base_sample.field_gradient = angular_gradient / _Radius;
base_sample.fade_target = clamp(value, -1.0, 1.0);
GameCultGeometryAdvancedErosionParameters erosion;
erosion.scale = _ErosionScale; erosion.strength = _ErosionStrength;
erosion.gully_weight = _GullyWeight; erosion.detail = _Detail;
erosion.rounding = _Rounding; erosion.onset = _Onset;
erosion.assumed_slope = _AssumedSlope.xy; erosion.cell_scale = _CellScale;
erosion.normalization = _Normalization; erosion.octaves = _Octaves;
erosion.lacunarity = _Lacunarity; erosion.gain = _Gain;
GameCultGeometryPlanetaryFieldDefinition definition;
definition.radius = _Radius; definition.seed = _Seed; definition.erosion = erosion;
return gamecult_geometry_planetary_field_sample(definition, direction, base_sample, _SampleFootprint);
}
Varyings vert(Attributes input)
{
float3 direction = normalize(input.vertex.xyz);
GameCultGeometryPlanetarySurfaceSample sample = viewer_sample(direction);
float3 local = direction * (_Radius + sample.radial_displacement);
Varyings output;
output.position = UnityObjectToClipPos(float4(local, 1));
output.worldNormal = UnityObjectToWorldNormal(sample.surface_normal);
output.height = sample.radial_displacement / max(_Radius * 0.1, 1.0e-5);
output.ridge = sample.ridge;
return output;
}
float4 frag(Varyings input) : SV_Target
{
float height = saturate(input.height * 0.5 + 0.5);
float3 albedo = lerp(_LowColor.rgb, _HighColor.rgb, height);
albedo = lerp(albedo, _RidgeColor.rgb, saturate((input.ridge - 0.55) * 2.5));
float diffuse = saturate(dot(normalize(input.worldNormal), normalize(-_LightDirection))) * 0.82 + 0.08;
return float4(albedo * diffuse, 1);
}
ENDHLSL
}
}
}

View file

@ -11,5 +11,6 @@
"dependencies": {
"org.gamecult.cultmath": "0.1.0",
"org.gamecult.cultlib": "1.0.7"
}
},
"samples": [{"displayName":"Planetary Field Viewer","description":"Planetary geometry CPU/HLSL parity viewer.","path":"Samples~/PlanetaryViewer"}]
}