Merge origin/master into mining: resolve five conflicts by owner, delete the belt-task machine

Mining owns belts, chunks and target picking; scenarios owns admission and run
staging; master owns ships and fire control (rule scenarios-cut.md S4).

- AetheriaStores.CatalogTypes: nine-type union, master's list plus FieldKindData, no Scenario.
- tools/AetherDb/Program.cs: both cases (ship-authoring, field-kinds), one usage string.
- Zone.cs: master's MineAsteroid dropped (mining deleted its inputs); scenarios' SettleBelts and its three calls deleted.
- RunStartTests: the two belt-task tests deleted (they read belt.Transforms and MineAsteroid).
- FireControlCut124Tests: master's strict Exact assertions; mining's CompatibleDrift allowance and its comment dropped.
- GameData/Aetheria.cc: master's pointer 70a7b0a9. This commit lacks the Asteroid field kind in the catalog, so
  TheShippedCatalogHasAPickableFieldKind fails here by design; the next commit rebuilds it.

Builds: this commit builds (verified at the end with commit 2); the catalog pin test fails at this commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-06 15:29:29 +02:00
commit d9f85dc639
154 changed files with 8764 additions and 4522 deletions

View file

@ -0,0 +1,51 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1 &4001
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4002}
- component: {fileID: 4003}
m_Layer: 0
m_Name: ShipModTemplate
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &4002
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 4001}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &4003
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 4001}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 7c3e9a52d8b14f0e8a6d2b1f4c95e703, type: 3}
m_Name:
m_EditorClassIdentifier:
Shield: {fileID: 8402070500206635106, guid: 897fa55d98f1f7f40b889f93ce9146f4, type: 3}
TractorBeam: {fileID: 2009124798951080406, guid: 1df59848be1db8547bc662080d0d6000, type: 3}
Ping: {fileID: 3496685214803260731, guid: bfcaa66e173f6a44cb640aabbcb5e429, type: 3}
DestroyEffect: {fileID: 1121192042590650, guid: e1b08032bec16ba4eb1ae23cbd572664, type: 3}
Invisible: {fileID: 2100000, guid: c94a225de88e5ce42af01c34df3521e6, type: 2}
MapIcon: {fileID: 2100000, guid: 64d1c3f8a4422884b88363be07521fb0, type: 2}

View file

@ -1,7 +1,6 @@
fileFormatVersion: 2
guid: a6e88469e3b81a541a0bc8a66e60d0c7
folderAsset: yes
DefaultImporter:
guid: 5d1f3a8c7e2b4f60a9c4b7e1d3f2a860
PrefabImporter:
externalObjects: {}
userData:
assetBundleName:

View file

@ -915,7 +915,6 @@ MonoBehaviour:
m_EditorClassIdentifier:
Settings: {fileID: 11400000, guid: cd2344e2001a37544aab0960c164d4ff, type: 2}
Dialog: {fileID: 4533226043449861657}
InGame: 0
PanelPrototype: {fileID: 7329274282942065594}
FadeTime: 0.5
FadeDistance: 1024

View file

@ -9636,11 +9636,6 @@ PrefabInstance:
propertyPath: m_SizeDelta.y
value: 90.91
objectReference: {fileID: 0}
- target: {fileID: 4533226043457584178, guid: 3d8d9cbf10b12214e98891c1f03c1e99,
type: 3}
propertyPath: InGame
value: 1
objectReference: {fileID: 0}
- target: {fileID: 4533226043457584178, guid: 3d8d9cbf10b12214e98891c1f03c1e99,
type: 3}
propertyPath: CloudRenderer

View file

@ -0,0 +1,121 @@
using System;
using System.IO;
using System.Linq;
using GameCult.Caching;
using UnityEditor;
using UnityEngine;
// Batch proof that a mod ship survives the game's own path into a zone, without a scene: the derived catalog composed
// with one package, ShipModShips.Preload over it, then ShipModShips.Instantiate, which is what ZoneRenderer.LoadEntity's
// Body() calls for a hull with a Visual. A plain parent transform stands in for ZoneRoot; nothing else in LoadEntity
// touches the body before it takes its ShipInstance.
//
// The package is installed beside a broken sibling: the same ship under another id, with its map-icon anchor moved onto
// its first muzzle's meshless node. The sibling composes, because no compose-time check reads meshes, and then fails
// assembly. The smoke proves the preload skips it and the good package still spawns.
//
// Unity -batchmode -nographics -projectPath <project> -executeMethod ShipModPlaySmoke.Run
// -shipModPath <mods>/<id>/ship.cc [-shippedCatalog GameData/Aetheria.cc] -logFile <log>
//
// Do not pass -quit: the method is async and exits the Editor itself, 0 on success and 1 on any failure.
public static class ShipModPlaySmoke
{
public static async void Run()
{
var args = Environment.GetCommandLineArgs();
string Option(string name, string fallback = null)
{
var at = Array.IndexOf(args, name);
return at >= 0 && at + 1 < args.Length ? args[at + 1] : fallback;
}
var packagePath = Option("-shipModPath");
var work = Path.Combine(Path.GetTempPath(), $"ship-mod-play-smoke-{Guid.NewGuid():N}");
var derived = Path.Combine(work, "Aetheria.modded.cc");
var modsRoot = Path.Combine(work, "Mods");
GameObject zone = null;
try
{
if (packagePath == null) throw new InvalidOperationException("-shipModPath <package/ship.cc> is required");
var package = ShipModCatalog.ReadPackage(packagePath);
var broken = InstallWithBrokenSibling(packagePath, package, modsRoot);
var composition = ShipModCatalog.Compose(Path.GetFullPath(Option("-shippedCatalog", "GameData/Aetheria.cc")), derived, modsRoot);
foreach (var id in new[] { package.Visual.Id, broken.Visual.Id })
if (!composition.Included.Contains(id))
throw new InvalidOperationException($"{id} was not composed into the catalog: " +
string.Join("; ", composition.Excluded.Select(excluded => $"{excluded.Package}: {excluded.Reason}")));
using (var catalog = AetheriaStores.Open(derived))
{
await ShipModShips.Preload(catalog, modsRoot);
HullData Hull(string name) => catalog.GetAll<HullData>().Single(candidate => candidate.Visual.IsSet() && candidate.Name == name);
var hull = Hull(package.Hull.Name);
// The broken sibling has no prototype, and Loading did not fault for it (await would have thrown).
var refused = false;
try { ShipModShips.Instantiate(Hull(broken.Hull.Name), null); }
catch (InvalidOperationException error) { refused = error.Message.Contains("no mod ship prototype"); }
if (!refused) throw new InvalidOperationException($"{broken.Visual.Id} assembled, or was refused for the wrong reason.");
zone = new GameObject("Play Smoke Zone");
var ship = ShipModShips.Instantiate(hull, zone.transform).GetComponent<ShipInstance>();
if (ship == null) throw new InvalidOperationException("The mod ship body has no ShipInstance.");
var thrusters = ship.ThrusterHardpoints?.Length ?? 0;
var weapons = ship.WeaponHardpoints?.Length ?? 0;
if (thrusters == 0) throw new InvalidOperationException("ThrusterHardpoints is empty.");
if (weapons == 0 || ship.WeaponHardpoints.Any(node => node.FiringPoint == null || node.FiringPoint.Length == 0))
throw new InvalidOperationException("WeaponHardpoints is empty or a weapon has no muzzle.");
if (ship.HullColliders == null || ship.HullColliders.Length != 1)
throw new InvalidOperationException("The ship needs exactly one hull collider.");
var collider = ship.HullColliders[0].GetComponent<MeshCollider>();
if (collider == null || collider.sharedMesh == null || !collider.sharedMesh.isReadable || collider.sharedMesh.vertexCount == 0)
throw new InvalidOperationException("The hull collider is not a MeshCollider over a readable mesh.");
if (ship.MapIcon == null || ship.MapIcon.sharedMaterial == null || ship.MapIcon.gameObject.layer != LayerMask.NameToLayer("Minimap"))
throw new InvalidOperationException("The map icon is missing its renderer, material or Minimap layer.");
Debug.Log($"SHIP_MOD_PLAY_SMOKE thrusters={thrusters} weapons={weapons} collider=ok mapicon=ok skipped={broken.Visual.Id}");
}
Clean(zone, work);
EditorApplication.Exit(0);
}
catch (Exception exception)
{
Debug.LogException(exception);
Clean(zone, work);
EditorApplication.Exit(1);
}
}
// Copies the package into modsRoot and writes its broken sibling beside it. Returns the sibling's records.
private static (HullData Hull, ShipAuthoring Visual) InstallWithBrokenSibling(string packagePath, ShipModCatalog.Package package, string modsRoot)
{
void Install(string id, string shipFile)
{
var model = Path.Combine(modsRoot, id, package.Visual.ModelAsset);
Directory.CreateDirectory(Path.GetDirectoryName(model));
File.Copy(package.ModelPath, model);
if (shipFile != null) File.Copy(shipFile, Path.Combine(modsRoot, id, "ship.cc"));
}
Install(package.Visual.Id, Path.GetFullPath(packagePath));
var (hull, ship) = ShipAuthoringStore.Read(Path.Combine(modsRoot, package.Visual.Id, "ship.cc"));
ship.Id += ".broken";
hull.Name += " Broken";
hull.Visual = new CultRecordRef<ShipAuthoring>(ShipModCatalog.AuthoringKey(ship.Id));
var mapIcon = ship.Anchors.Single(anchor => anchor.Role == "map-icon");
var muzzle = ship.Anchors.First(anchor => anchor.Role == "weapon-muzzle");
(mapIcon.ModelNodeId, muzzle.ModelNodeId) = (muzzle.ModelNodeId, mapIcon.ModelNodeId);
Install(ship.Id, null);
using (var cache = ShipAuthoringStore.Open(Path.Combine(modsRoot, ship.Id, "ship.cc"), writable: true))
{
ShipAuthoringStore.Write(cache, hull, ship);
cache.FlushAsync().GetAwaiter().GetResult();
}
return (hull, ship);
}
private static void Clean(GameObject zone, string work)
{
if (zone != null) UnityEngine.Object.DestroyImmediate(zone);
try { if (Directory.Exists(work)) Directory.Delete(work, true); }
catch (Exception error) { Debug.LogWarning($"Play smoke left {work}: {error.Message}"); }
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a1f2b276e4d6582479c3216cc97a5164

View file

@ -0,0 +1,133 @@
using System;
using System.Linq;
using UnityEditor;
using UnityEngine;
public static class ShipModPreview
{
private const string TemplatePath = "Assets/Content/Prefabs/ShipModTemplate.prefab";
// Batch proof: -executeMethod ShipModPreview.Smoke -shipModPath <package/ship.cc> [-assemble]
// -assemble also builds the game's ShipInstance from the package (ShipModShips.Assemble) and checks it against the
// plan and against a clone, the way Instantiate makes one. That needs a GLB with real meshes on the map-icon,
// hull-collider and emitter anchors; a nodes-only fixture fails it on purpose.
public static async void Smoke()
{
var args = Environment.GetCommandLineArgs();
var option = Array.IndexOf(args, "-shipModPath");
if (option < 0 || option + 1 >= args.Length)
{
Debug.LogError("-shipModPath <package/ship.cc> is required");
EditorApplication.Exit(1);
return;
}
ShipModVisual.Instance visual = null;
try
{
var package = ShipModCatalog.ReadPackage(args[option + 1]);
visual = await ShipModVisual.LoadAsync(package, null);
if (visual.Anchors.Count == 0 || visual.LineMesh == null || visual.LineMesh.vertexCount == 0)
throw new InvalidOperationException("Mod visual did not import anchors and line points.");
Debug.Log($"SHIP_MOD_VISUAL_SMOKE anchors={visual.Anchors.Count} points={visual.LineMesh.vertexCount} segments={visual.LineMesh.GetIndexCount(0) / 2}");
if (Array.IndexOf(args, "-assemble") >= 0) CheckAssembly(visual, package);
visual.Destroy();
EditorApplication.Exit(0);
}
catch (Exception exception)
{
Debug.LogException(exception);
visual?.Destroy();
EditorApplication.Exit(1);
}
}
private static void CheckAssembly(ShipModVisual.Instance visual, ShipModCatalog.Package package)
{
var template = AssetDatabase.LoadAssetAtPath<ShipModTemplate>(TemplatePath);
if (template == null) throw new InvalidOperationException($"{TemplatePath} is missing or has no ShipModTemplate.");
var plan = ShipModPlan.Build(package.Hull, package.Visual);
var ship = ShipModShips.Assemble(visual, package.Hull, package.Visual, template);
CheckShip(ship, plan, "assembled");
// Instantiate clones the assembled root, and Unity must remap every array reference into the clone.
var clone = UnityEngine.Object.Instantiate(ship.gameObject).GetComponent<ShipInstance>();
try { CheckShip(clone, plan, "clone"); CheckExhaust(clone); }
finally { UnityEngine.Object.DestroyImmediate(clone.gameObject); }
Debug.Log($"SHIP_MOD_ASSEMBLY_SMOKE thrusters={plan.Thrusters.Length} exhaust=ok collider=hidden " +
$"weapons={plan.Weapons.Length} radiators={plan.Radiators.Length}");
}
private static void CheckShip(ShipInstance ship, ShipModPlan plan, string what)
{
void Require(bool ok, string claim) { if (!ok) throw new InvalidOperationException($"{what}: {claim}"); }
bool Inside(Component part) => part != null && part.transform.IsChildOf(ship.transform);
Require(ship.HullColliders.Length == 1 && Inside(ship.HullColliders[0]) &&
ship.HullColliders[0].GetComponent<MeshCollider>() != null, "one hull collider with a MeshCollider");
Require(ship.HullColliders[0].GetComponentsInChildren<Renderer>(true).All(renderer =>
renderer.sharedMaterials.All(material => material == ship.InvisibleMaterial)),
"a hull collider that draws nothing");
Require(Inside(ship.MapIcon) && Inside(ship.Shield) && Inside(ship.TractorBeam), "map icon, shield and tractor inside the ship");
Require(ship.ThrusterHardpoints.Select(node => node.name).SequenceEqual(plan.Thrusters) &&
ship.ThrusterHardpoints.All(node => Inside(node) && Inside(node.Emitter) &&
node.Emitter.sharedMaterials.All(material => material == ship.InvisibleMaterial)),
"thruster hardpoints with unrendered emitter meshes");
Require(ship.RadiatorHardpoints.Select(node => node.name).SequenceEqual(plan.Radiators) &&
ship.RadiatorHardpoints.All(node => Inside(node) && Inside(node.Mesh)), "radiator hardpoints with meshes");
Require(ship.WeaponHardpoints.Select(node => node.name).SequenceEqual(plan.Weapons.Select(weapon => weapon.Mount)) &&
ship.WeaponHardpoints.Zip(plan.Weapons, (node, weapon) =>
Inside(node) && node.FiringPoint.Select(point => point.name).SequenceEqual(weapon.Muzzles) &&
node.FiringPoint.All(Inside)).All(ok => ok), "weapon hardpoints with their muzzles in order");
}
// Exhaust from each hidden emitter, wired as ShipInstance wires it, from a particle system left at Unity's defaults
// (Use Mesh Colors on). The emitter's invisible material has alpha 0, so mesh colours would make every particle
// transparent; the wiring must turn them off.
private static void CheckExhaust(ShipInstance ship)
{
const int count = 200;
foreach (var hardpoint in ship.ThrusterHardpoints)
{
var exhaust = new GameObject("Smoke Exhaust").AddComponent<ParticleSystem>();
try
{
exhaust.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);
var main = exhaust.main;
main.playOnAwake = false;
main.startSpeed = 0;
main.startLifetime = 10;
main.maxParticles = count * 2;
var emission = exhaust.emission;
emission.enabled = false;
var shape = exhaust.shape;
shape.enabled = true;
shape.shapeType = ParticleSystemShapeType.MeshRenderer;
if (!shape.useMeshColors) throw new InvalidOperationException("Unity's default Use Mesh Colors is off; the exhaust check proves nothing.");
ThrusterHardpoint.WireExhaust(exhaust, hardpoint);
exhaust.Emit(count);
if (exhaust.particleCount != count)
throw new InvalidOperationException($"clone: exhaust from {hardpoint.name} emitted {exhaust.particleCount} of {count} particles.");
var alive = new ParticleSystem.Particle[count];
exhaust.GetParticles(alive);
if (alive.Any(particle => particle.GetCurrentColor(exhaust).a == 0))
throw new InvalidOperationException($"clone: exhaust from {hardpoint.name} has transparent particles.");
}
finally { UnityEngine.Object.DestroyImmediate(exhaust.gameObject); }
}
}
[MenuItem("Aetheria/Preview Mod Ship Package")]
private static async void Open()
{
var path = EditorUtility.OpenFilePanel("Ship authoring record", "GameData/Mods", "cc");
if (string.IsNullOrEmpty(path)) return;
try
{
var visual = await ShipModVisual.LoadAsync(ShipModCatalog.ReadPackage(path), null);
Undo.RegisterCreatedObjectUndo(visual.Root, "Preview mod ship");
Selection.activeGameObject = visual.Root;
SceneView.FrameLastActiveSceneView();
Debug.Log($"Previewed {path}: {visual.Anchors.Count} anchors, {visual.LineMesh?.vertexCount ?? 0} line points.");
}
catch (Exception exception) { Debug.LogException(exception); }
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4d32248a66f6454a9be20458fa43f3ef

View file

@ -92,7 +92,7 @@ public static class ShipPrefabAuthoring
var combatLayer = LayerMask.NameToLayer("Combat");
if (minimapLayer < 0 || combatLayer < 0) throw new InvalidOperationException("Minimap or Combat layer is missing");
var equipment = new List<Transform>();
var hardpoints = 0;
var thrusters = new List<ThrusterHardpoint>();
var weapons = new List<WeaponHardpoint>();
var radiators = new List<RadiatorHardpoint>();
@ -106,10 +106,9 @@ public static class ShipPrefabAuthoring
var parts = name.Split('.');
if (parts.Length != 3 || string.IsNullOrWhiteSpace(parts[2]))
throw new InvalidOperationException($"Invalid hardpoint name {name}");
equipment.Add(node);
hardpoints++;
switch (parts[1])
{
case "Equipment": break;
case "Thruster":
var emitter = DirectChild(node, "Emitter")?.GetComponent<MeshRenderer>();
if (emitter == null) throw new InvalidOperationException($"{name} needs an Emitter mesh child");
@ -155,13 +154,14 @@ public static class ShipPrefabAuthoring
name != "SHIP.Shield" && name != "SHIP.TractorBeam")
throw new InvalidOperationException($"Unknown ship anchor {name}");
}
if (equipment.Count == 0) throw new InvalidOperationException("Ship has no HP.* hardpoints");
if (hardpoints == 0) throw new InvalidOperationException("Ship has no HP.* hardpoints");
mapIcon.sharedMaterial = mapMaterial;
mapIcon.gameObject.layer = minimapLayer;
hull.gameObject.layer = combatLayer;
var hullRenderer = hull.GetComponent<MeshRenderer>();
if (hullRenderer != null) hullRenderer.forceRenderingOff = true;
// Serialized, so it survives SaveAsPrefabAsset and every clone; forceRenderingOff survives neither.
if (hullRenderer != null) ShipModShips.Hide(hullRenderer, invisible);
var collider = AddOrGet<MeshCollider>(hull.gameObject);
collider.sharedMesh = hullMesh;
collider.convex = true;
@ -182,7 +182,6 @@ public static class ShipPrefabAuthoring
ship.InvisibleMaterial = invisible;
ship.Shield = shield;
ship.HullColliders = new[] { hullSurface };
ship.EquipmentHardpoints = equipment.ToArray();
ship.ThrusterHardpoints = thrusters.ToArray();
ship.WeaponHardpoints = weapons.ToArray();
ship.RadiatorHardpoints = radiators.ToArray();

View file

@ -23,18 +23,18 @@ public static class ShipPrefabAuthoringSmoke
Child(weapon.gameObject, "Muzzle.0");
var radiator = Child(root, "HP.Radiator.Port");
Primitive(radiator.gameObject, "RadiatorMesh");
Child(root, "HP.Equipment.Reactor");
Child(root, "Pivot.2.-90.90.-80.80.60");
ShipPrefabAuthoring.Configure(root);
var ship = root.GetComponent<ShipInstance>();
Require(ship != null && ship.EquipmentHardpoints.Length == 4, "equipment references");
Require(ship.ThrusterHardpoints.Length == 1 && ship.ThrusterHardpoints[0].Emitter != null, "thruster emitter");
Require(ship != null && ship.ThrusterHardpoints.Length == 1 && ship.ThrusterHardpoints[0].Emitter != null, "thruster emitter");
Require(ship.WeaponHardpoints.Length == 1 && ship.WeaponHardpoints[0].FiringPoint.Length == 2, "weapon muzzles");
Require(ship.WeaponHardpoints[0].FiringPoint[0].name == "Muzzle.0", "numeric muzzle order");
Require(ship.RadiatorHardpoints.Length == 1 && ship.RadiatorHardpoints[0].Mesh != null, "radiator mesh");
Require(ship.ArticulationPoints.Length == 1 && ship.ArticulationPoints[0].Group == 2, "articulation");
Require(ship.HullColliders.Length == 1 && ship.HullColliders[0].GetComponent<MeshCollider>().convex, "hull collision");
Require(Array.TrueForAll(ship.HullColliders[0].GetComponent<MeshRenderer>().sharedMaterials,
material => material == ship.InvisibleMaterial), "hull collider drawn with the invisible material only");
Require(ship.Shield != null && ship.Shield.GetComponent<ShieldEnvelope>() != null, "shield envelope");
Require(ship.TractorBeam != null && ship.PingPrefab != null && ship.DestroyEffect != null, "shared assets");
Require(ship.MapIcon != null && ship.MapIcon.gameObject.layer == LayerMask.NameToLayer("Minimap"), "map icon");

View file

@ -42,7 +42,13 @@ public class ActionGameManager : MonoBehaviour
private static CultCache _cultCache;
// Mod packages left out of this boot (a bad package, or a name collision), for the main menu to name.
public static ShipModCatalog.Exclusion[] ModExclusions { get; private set; } = Array.Empty<ShipModCatalog.Exclusion>();
private static string CatalogPath => Path.Combine(GameDataDirectory.FullName, "Aetheria.cc");
private static string ModsPath => Path.Combine(GameDataDirectory.FullName, "Mods");
// Disposable: composed at every boot from the shipped catalog and the mod packages, never authored.
private static string DerivedCatalogPath => Path.Combine(Application.persistentDataPath, "Aetheria.modded.cc");
public static CultCache CultCache
{
@ -52,12 +58,18 @@ public class ActionGameManager : MonoBehaviour
// All three stores attach once and stay attached until the process exits. The run lifecycle is record-level
// inside this cache; reopening would replace the catalog instances the galaxy and live entities hold.
// The catalog is read-only in every build; capturepreset writes through its own cache (Loadouts.Commit).
// The catalog is read-only in every build; capturepreset writes through its own cache (Loadouts.Commit) to the
// shipped file. With mod packages installed the game reads the derived catalog instead.
var (catalog, excluded) = ShipModCatalog.ResolveCatalog(CatalogPath, DerivedCatalogPath, ModsPath);
ModExclusions = excluded;
_cultCache = AetheriaStores.Open(
CatalogPath,
catalog,
runPath: Path.Combine(GameDataDirectory.FullName, "run.cc"),
playerPath: Path.Combine(GameDataDirectory.FullName, "player.cc"));
// Mod ship prototypes import asynchronously from here; entering a game waits on ShipModShips.Loading.
ShipModShips.Preload(_cultCache, ModsPath);
return _cultCache;
}
}
@ -94,7 +106,8 @@ public class ActionGameManager : MonoBehaviour
}
public static Galaxy CurrentGalaxy;
public static bool IsTutorial;
// The scenario a new run starts from: MainMenu.Launch sets it, and StartGame's new-run branch consumes it once.
public static Scenario PendingScenario;
public GameSettings Settings;
//public string StarterShipTemplate = "Longinus";
@ -238,7 +251,7 @@ public class ActionGameManager : MonoBehaviour
{
if (CurrentGalaxy != null)
{
var (game, zones) = RunSave.Capture(CultCache, CurrentGalaxy, Zone, DockedEntity ?? CurrentEntity, IsTutorial,
var (game, zones) = RunSave.Capture(CultCache, CurrentGalaxy, Zone, DockedEntity ?? CurrentEntity,
_actionBarSlots.Select(s => s.Save()).ToArray());
RunSave.Commit(CultCache, game, zones, ItemManager.Lots);
}
@ -257,7 +270,9 @@ public class ActionGameManager : MonoBehaviour
EntityInstance.EffectManagerParent = EffectManagerParent;
ConsoleController.MessageReceiver = this;
ItemManager = new ItemManager(CultCache, RunSave.Lots(CultCache), Settings.GameplaySettings, Debug.Log);
// A new run mints into an empty ledger; the saved run's stays in the store until the new run has started.
ItemManager = new ItemManager(CultCache, PendingScenario != null ? new ProvenanceLedger() : RunSave.Lots(CultCache),
Settings.GameplaySettings, Debug.Log);
ZoneRenderer.ItemManager = ItemManager;
// If hiding minimap asteroids, turn them off to start with
@ -539,26 +554,12 @@ public class ActionGameManager : MonoBehaviour
{
var nearestFaction = CurrentGalaxy.Factions.MinBy(f => CurrentGalaxy.HomeZones[f].Distance[Zone.GalaxyZone]);
var loadoutGenerator = IsTutorial ? new LoadoutGenerator(
ref ItemManager.Random,
ItemManager,
CurrentGalaxy,
Zone.GalaxyZone,
nearestFaction,
.5f) : new LoadoutGenerator(
ref ItemManager.Random,
ItemManager,
CurrentGalaxy,
Zone.GalaxyZone,
nearestFaction,
.5f);
var loadoutGenerator = new LoadoutGenerator(ref ItemManager.Random, ItemManager, CurrentGalaxy, Zone.GalaxyZone, nearestFaction, .5f);
var turret = EntitySerializer.Unpack(ItemManager, Zone, loadoutGenerator.GenerateTurretLoadout());
turret.Position.xz = _currentEntity.Position.xz +
ItemManager.Random.NextFloat2Direction() * ItemManager.Random.NextFloat(50, 500);
turret.Zone = Zone;
Zone.Entities.Add(turret);
turret.Activate();
Zone.Admit(turret, piloted: false);
});
//Temporary, or not
ConsoleController.AddCommand("tow", _ => TowShip());
@ -691,7 +692,7 @@ public class ActionGameManager : MonoBehaviour
Settings.ZoneSettings,
CurrentGalaxy,
galaxyZone,
IsTutorial
CurrentGalaxy.IsPrelude
);
galaxyZone.Contents = new Zone(ItemManager, Settings.PlanetSettings, galaxyZone.PackedContents, galaxyZone, CurrentGalaxy);
}
@ -705,8 +706,7 @@ public class ActionGameManager : MonoBehaviour
CurrentEntity.Deactivate();
CurrentEntity.Zone.Entities.Remove(CurrentEntity);
CurrentEntity.Zone = Zone;
Zone.Entities.Add(CurrentEntity);
CurrentEntity.Activate();
Zone.Admit(CurrentEntity, piloted: false);
}
ZoneRenderer.LoadZone(Zone);
@ -770,25 +770,10 @@ public class ActionGameManager : MonoBehaviour
{
if (CurrentGalaxy != null)
{
var saved = CultCache.GetGlobal<SavedGame>();
if (saved == null)
{
SectorMap.QueueZoneReveal(CurrentGalaxy.Entrance.AdjacentZones.Prepend(CurrentGalaxy.Entrance));
PopulateLevel(CurrentGalaxy.Entrance);
var loadoutGenerator = new LoadoutGenerator(ref ItemManager.Random, ItemManager, CurrentGalaxy, Zone.GalaxyZone, IsTutorial ? CurrentGalaxy.ResolveFaction(Settings.TutorialGenerationSettings.ProtagonistFaction) : null, 2);
var ship = EntitySerializer.Unpack(
ItemManager,
Zone,
loadoutGenerator.GenerateShipLoadout(data => string.IsNullOrEmpty(Settings.StartingHullName) || data.Name==Settings.StartingHullName ));
((Ship) ship).IsPlayerShip = true;
ship.Position = float3.zero;
ship.Zone = Zone;
Zone.Entities.Add(ship);
ship.Activate();
BindToEntity(ship);
}
if (PendingScenario != null) StartScenario();
else
{
var saved = CultCache.GetGlobal<SavedGame>();
foreach(var group in CurrentGalaxy.DiscoveredZones
.GroupBy(dz=>dz.Distance[CurrentGalaxy.Entrance]))
SectorMap.QueueZoneReveal(group);
@ -813,6 +798,41 @@ public class ActionGameManager : MonoBehaviour
}
}
// RunStart owns what a new run starts with (docs/scenarios-cut.md, R.4); this enters and binds. The saved run is
// replaced only once the scenario has staged. A start that fails leaves the saved run as it was and says why on
// the main menu, where Continue still resumes the saved run.
private void StartScenario()
{
var scenario = PendingScenario;
PendingScenario = null;
var failures = new List<string>();
RunStart.Staged staged = null;
try
{
staged = RunSave.Replace(CultCache, () =>
{
RunStart.GenerateArena(ItemManager, Settings.ZoneSettings, CurrentGalaxy, scenario);
PopulateLevel(CurrentGalaxy.Entrance);
return RunStart.Stage(ItemManager, Zone, scenario, Settings.StartingHullName, Settings.TutorialGenerationSettings, failures);
});
}
catch (Exception exception)
{
Debug.LogException(exception);
failures.Add(exception.Message);
}
if (staged == null)
{
CurrentGalaxy = null;
MainMenu.gameObject.SetActive(true);
MainMenu.Refuse($"{scenario.Name} could not start", string.Join("\n", failures));
return;
}
SectorMap.QueueZoneReveal(CurrentGalaxy.Entrance.AdjacentZones.Prepend(CurrentGalaxy.Entrance));
BindToEntity(staged.Player);
}
private IEnumerator IntroCutscene(Ship ship)
{
ZoneRenderer.PerspectiveEntity = ship;
@ -1021,12 +1041,12 @@ public class ActionGameManager : MonoBehaviour
_articulationGroups = CurrentEntity.Equipment
.Where(item => item.Behaviors.Any(x => x.Data is WeaponData && !(x.Data is LauncherData)))
.GroupBy(item => ZoneRenderer.EntityInstances[CurrentEntity]
.GetBarrel(CurrentEntity.Hardpoints[item.Position.x, item.Position.y])
.GetBarrel(item.Hardpoint)
.GetComponentInParent<ArticulationPoint>()?.Group ?? -1)
.Select((group, index) => {
return (
group.Select(item => CurrentEntity.Hardpoints[item.Position.x, item.Position.y]).ToArray(),
group.Select(item => ZoneRenderer.EntityInstances[CurrentEntity].GetBarrel(CurrentEntity.Hardpoints[item.Position.x, item.Position.y])).ToArray(),
group.Select(item => item.Hardpoint).ToArray(),
group.Select(item => ZoneRenderer.EntityInstances[CurrentEntity].GetBarrel(item.Hardpoint)).ToArray(),
Crosshairs[index]
);
}).ToArray();

View file

@ -20,7 +20,6 @@ public class EntityInstance : MonoBehaviour
public ShieldManager Shield;
public HullCollider[] HullColliders;
public Transform[] EquipmentHardpoints;
public RadiatorHardpoint[] RadiatorHardpoints;
public ThrusterHardpoint[] ThrusterHardpoints;
public WeaponHardpoint[] WeaponHardpoints;
@ -241,23 +240,13 @@ public class EntityInstance : MonoBehaviour
_constantWeaponManagers[data].StopFiring(item);
}
}
var hp = Entity.Hardpoints[item.Position.x, item.Position.y];
if (hp != null && item.Data.SoundBank != 0)
{
var hardpointTransform = EquipmentHardpoints.FirstOrDefault(x => x.name == hp.Transform);
if (hardpointTransform != null)
{
var hardpointGameObject = hardpointTransform.gameObject;
}
}
}
RadiatorMeshes = new Dictionary<Radiator, MeshRenderer>();
Barrels = new Dictionary<HardpointData, Transform[]>();
BarrelIndices = new Dictionary<HardpointData, int>();
foreach (var radiator in entity.GetBehaviors<Radiator>())
{
var hp = Entity.Hardpoints[radiator.Item.Position.x, radiator.Item.Position.y];
var hp = radiator.Item.Hardpoint;
if (hp != null && hp.Type == HardpointType.Radiator)
{
var mesh = RadiatorHardpoints.FirstOrDefault(x => x.name == hp.Transform);

View file

@ -65,10 +65,9 @@ public class ShipInstance : EntityInstance
{
var effectData = (ThrusterData) thruster.Data;
var particles = Instantiate(EngineAssets.Load<ParticleSystem>(effectData.ParticlesPrefab), transform, false);
var particlesShape = particles.shape;
var thrusterHardpoint = ThrusterHardpoints
.FirstOrDefault(t => t.name == ship.Hardpoints[thruster.Item.Position.x, thruster.Item.Position.y].Transform);
particlesShape.meshRenderer = thrusterHardpoint?.Emitter;
.FirstOrDefault(t => t.name == thruster.Item.Hardpoint.Transform);
ThrusterHardpoint.WireExhaust(particles, thrusterHardpoint);
// if (!string.IsNullOrEmpty(thruster.Item.Data.SoundEffectTrigger) && thrusterHardpoint != null)
// {
// AkSoundEngine.RegisterGameObj(thrusterHardpoint.gameObject);

View file

@ -0,0 +1,182 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GameCult.Caching;
using UnityEngine;
using Object = UnityEngine.Object;
// Mod ships in the running game. Preload imports each catalog hull's GLB once, at boot, into an inactive assembled
// prototype keyed by the hull's record key; Instantiate then clones it synchronously, so LoadEntity never loads async.
// The prototypes are cache-only: rebuilt every boot from the catalog, the mod GLBs and the template.
public static class ShipModShips
{
private static readonly Dictionary<CultRecordKey, GameObject> Prototypes = new Dictionary<CultRecordKey, GameObject>();
private static CultCache _catalog;
// Set by Preload; complete when every hull that could be built has its prototype. A mod ship that fails to import or
// assemble is skipped and logged, as Compose skips a bad package, so it never stops the rest; Loading faults only
// when the preload itself cannot run.
public static Task Loading { get; private set; } = Task.CompletedTask;
public static Task Preload(CultCache catalog, string modsRoot)
{
Loading = PreloadAsync(catalog, modsRoot);
Loading.ContinueWith(task => Debug.LogException(task.Exception), TaskContinuationOptions.OnlyOnFaulted);
return Loading;
}
private static async Task PreloadAsync(CultCache catalog, string modsRoot)
{
_catalog = catalog;
var hulls = catalog.GetAll<HullData>().Where(hull => hull.Visual.IsSet()).ToArray();
if (hulls.Length == 0) return;
var template = EngineAssets.Load<ShipModTemplate>(ShipModTemplate.Key);
if (template == null)
throw new InvalidOperationException($"The ship mod template prefab ({ShipModTemplate.Key}) is not loadable.");
var root = new GameObject("Mod Ship Prototypes");
root.SetActive(false);
// DontDestroyOnLoad is play-mode only; the edit-mode play smoke builds the same prototypes
// without it, and nothing there loads scenes.
if (Application.isPlaying) Object.DontDestroyOnLoad(root);
foreach (var hull in hulls)
{
ShipModVisual.Instance visual = null;
try
{
var package = ShipModCatalog.PackageOf(catalog, hull, modsRoot);
visual = await ShipModVisual.LoadAsync(package, root.transform);
visual.Root.SetActive(false);
Assemble(visual, package.Hull, package.Visual, template);
Prototypes[catalog.RefOf(hull).Key] = visual.Root;
}
catch (Exception error)
{
visual?.Destroy();
Debug.LogError($"Mod ship {hull.Name} skipped: {error.Message}");
}
}
}
// A live ship body for a mod hull. Refuses loudly when the prototype is missing: nothing is loaded here.
public static GameObject Instantiate(HullData hull, Transform parent)
{
if (!Loading.IsCompletedSuccessfully)
throw new InvalidOperationException($"{hull.Name}: mod ships are not preloaded ({Loading.Status}).");
if (!Prototypes.TryGetValue(_catalog.RefOf(hull).Key, out var prototype))
throw new InvalidOperationException($"{hull.Name}: no mod ship prototype for this hull.");
var body = Object.Instantiate(prototype, parent, false);
body.SetActive(true);
return body;
}
// Fills a ShipInstance on the visual's root from its anchors, as ShipModPlan says; the shared effects come from the
// template. Nothing here decides a slot: the plan does. The schematic lines stay in the prototype but are hidden in
// world; the in-world ship is the GLB.
public static ShipInstance Assemble(ShipModVisual.Instance visual, HullData hull, ShipAuthoring ship, ShipModTemplate template)
{
var plan = ShipModPlan.Build(hull, ship);
var minimap = LayerMask.NameToLayer("Minimap");
var combat = LayerMask.NameToLayer("Combat");
if (minimap < 0 || combat < 0) throw new InvalidOperationException("Minimap or Combat layer is missing");
// The name a catalog hardpoint matches at runtime is its anchor id.
Transform Node(string id)
{
var node = visual.Anchors[id];
node.name = id;
return node;
}
MeshRenderer Renderer(string id)
{
var found = Node(id).GetComponentInChildren<MeshRenderer>(true);
if (found == null) throw new InvalidOperationException($"{ship.Id}: anchor {id} needs a mesh in its GLB node.");
return found;
}
var mapIcon = Renderer(plan.MapIcon);
mapIcon.sharedMaterial = template.MapIcon;
mapIcon.gameObject.layer = minimap;
var hullNode = Node(plan.HullCollider);
var hullFilter = hullNode.GetComponent<MeshFilter>();
var hullMesh = hullFilter != null ? hullFilter.sharedMesh : null;
if (hullMesh == null)
throw new InvalidOperationException($"{ship.Id}: hull-collider anchor {plan.HullCollider} needs a mesh in its GLB node.");
if (!hullMesh.isReadable)
throw new InvalidOperationException($"{ship.Id}: the hull-collider mesh imported unreadable, so it cannot back a MeshCollider.");
hullNode.gameObject.layer = combat;
// The collision hull is never drawn. Its renderer takes the invisible material, which is serialized and so survives
// the prototype's clone; forceRenderingOff would not survive Instantiate.
var hullRenderer = hullNode.GetComponent<MeshRenderer>();
if (hullRenderer != null) Hide(hullRenderer, template.Invisible);
var collider = AddOrGet<MeshCollider>(hullNode.gameObject);
collider.sharedMesh = hullMesh;
collider.convex = true;
var surface = AddOrGet<HullCollider>(hullNode.gameObject);
var shieldMarker = Node(plan.Shield);
var scale = shieldMarker.localScale;
if (!(scale.x > 0 && scale.y > 0 && scale.z > 0))
throw new InvalidOperationException($"{ship.Id}: the shield anchor scale must have three positive radii.");
var shield = Object.Instantiate(template.Shield.GetComponent<ShieldManager>(), shieldMarker, false);
Reset(shield.transform);
AddOrGet<ShieldEnvelope>(shield.gameObject);
var tractor = Object.Instantiate(template.TractorBeam.GetComponent<TractorBeam>(), Node(plan.Tractor), false);
Reset(tractor.transform);
var thrusters = plan.Thrusters.Select(id =>
{
// The thruster's mesh is its exhaust's emission surface, never drawn (ruling thrusters-radiators-are-meshes).
// The invisible material is serialized, so it survives the prototype's clone, and EntityInstance keeps it as
// this renderer's visible material; forceRenderingOff would not survive Instantiate.
var hardpoint = AddOrGet<ThrusterHardpoint>(Node(id).gameObject);
hardpoint.Emitter = Renderer(id);
Hide(hardpoint.Emitter, template.Invisible);
return hardpoint;
}).ToArray();
var radiators = plan.Radiators.Select(id =>
{
var hardpoint = AddOrGet<RadiatorHardpoint>(Node(id).gameObject);
hardpoint.Mesh = Renderer(id);
return hardpoint;
}).ToArray();
var weapons = plan.Weapons.Select(weapon =>
{
var hardpoint = AddOrGet<WeaponHardpoint>(Node(weapon.Mount).gameObject);
hardpoint.FiringPoint = weapon.Muzzles.Select(Node).ToArray();
return hardpoint;
}).ToArray();
var lines = visual.Root.transform.Find("Schematic Lines");
if (lines != null) lines.gameObject.SetActive(false);
var instance = AddOrGet<ShipInstance>(visual.Root);
instance.MapIcon = mapIcon;
instance.InfluencePrefab = null;
instance.PingPrefab = template.Ping.transform;
instance.InvisibleMaterial = template.Invisible;
instance.Shield = shield;
instance.HullColliders = new[] { surface };
instance.ThrusterHardpoints = thrusters;
instance.WeaponHardpoints = weapons;
instance.RadiatorHardpoints = radiators;
instance.ArticulationPoints = Array.Empty<ArticulationPoint>();
instance.DestroyEffect = template.DestroyEffect;
instance.TractorBeam = tractor;
return instance;
}
// Every material slot takes the invisible material, so the renderer draws nothing on the prototype and on every clone.
public static void Hide(Renderer renderer, Material invisible) =>
renderer.sharedMaterials = Enumerable.Repeat(invisible, renderer.sharedMaterials.Length).ToArray();
private static void Reset(Transform transform)
{
transform.localPosition = Vector3.zero;
transform.localRotation = Quaternion.identity;
}
private static T AddOrGet<T>(GameObject gameObject) where T : Component =>
gameObject.TryGetComponent<T>(out var found) ? found : gameObject.AddComponent<T>();
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 3b2c0124382433447b5a5679e8b91b57

View file

@ -0,0 +1,17 @@
using UnityEngine;
// The shared effect prototypes every mod ship is assembled with: the same assets ShipPrefabAuthoring wires into a
// prefab ship. It lives on one Addressable prefab, so a built player finds it by key without the Editor.
public class ShipModTemplate : MonoBehaviour
{
// The template prefab's .meta GUID, its Addressables key (Assets/Content is an addressable folder).
public const string Key = "5d1f3a8c7e2b4f60a9c4b7e1d3f2a860";
// Prefab roots; the assembler takes the component it needs from each.
public GameObject Shield;
public GameObject TractorBeam;
public GameObject Ping;
public GameObject DestroyEffect;
public Material Invisible;
public Material MapIcon;
}

View file

@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 3969283304824fe4a8eca1eb522fd3a7
guid: 7c3e9a52d8b14f0e8a6d2b1f4c95e703
MonoImporter:
externalObjects: {}
serializedVersion: 2

View file

@ -0,0 +1,113 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GLTFast;
using UnityEngine;
using Object = UnityEngine.Object;
// A mod package's visual assembly. It does not decide hull cells or hardpoint roles.
public static class ShipModVisual
{
public sealed class Instance
{
public GameObject Root;
public IReadOnlyDictionary<string, Transform> Anchors;
public Mesh LineMesh;
public Material LineMaterial;
public void Destroy()
{
DestroyObject(Root);
DestroyObject(LineMesh);
DestroyObject(LineMaterial);
}
}
private sealed class Nodes : GameObjectInstantiator
{
public Nodes(IGltfReadable gltf, Transform parent) : base(gltf, parent) { }
public Transform Get(uint index) => m_Nodes.TryGetValue(index, out var node) ? node.transform : null;
}
public static async Task<Instance> LoadAsync(ShipModCatalog.Package package, Transform parent)
{
var ship = package.Visual;
var root = new GameObject("mod-ship:" + ship.Id);
root.SetActive(false);
root.transform.SetParent(parent, false);
var result = new Instance { Root = root };
try
{
// glTFast's default defer agent creates a DontDestroyOnLoad object, which is
// unavailable in edit-mode previews. Play mode keeps its frame-budgeted agent.
var gltf = new GltfImport(deferAgent: Application.isPlaying ? null : new UninterruptedDeferAgent());
if (!await gltf.LoadFile(package.ModelPath))
throw new InvalidOperationException($"{ship.Id}: GLB import failed.");
var nodes = new Nodes(gltf, root.transform);
if (!await gltf.InstantiateMainSceneAsync(nodes))
throw new InvalidOperationException($"{ship.Id}: GLB scene instantiation failed.");
result.Anchors = ship.Anchors.ToDictionary(anchor => anchor.Id, anchor =>
nodes.Get(package.NodeIndices[anchor.ModelNodeId]) ??
throw new InvalidOperationException($"{ship.Id}: GLB scene omitted node {anchor.ModelNodeId}."),
StringComparer.Ordinal);
result.LineMesh = BuildLineMesh(ship.SchematicLines);
if (result.LineMesh != null)
{
var lines = new GameObject("Schematic Lines");
lines.transform.SetParent(root.transform, false);
lines.AddComponent<MeshFilter>().sharedMesh = result.LineMesh;
var shader = Shader.Find("Sprites/Default") ??
throw new InvalidOperationException("Sprites/Default shader is unavailable for ship lines.");
result.LineMaterial = new Material(shader) { name = "Ship Lines" };
lines.AddComponent<MeshRenderer>().sharedMaterial = result.LineMaterial;
}
root.SetActive(true);
return result;
}
catch
{
result.Destroy();
throw;
}
}
private static void DestroyObject(Object target)
{
if (target == null) return;
if (Application.isPlaying) Object.Destroy(target);
else Object.DestroyImmediate(target);
}
// Blender Z-up to Unity Y-up through Blender's glTF export and glTFast's handedness conversion.
// Segment topology preserves every authored point; display width is currently one screen pixel.
public static Mesh BuildLineMesh(IReadOnlyList<ShipPolyline> lines)
{
if (lines == null || lines.Count == 0) return null;
var vertices = new List<Vector3>();
var colors = new List<Color>();
var segments = new List<int>();
foreach (var line in lines)
{
var count = line.Points.Length / 3;
var start = vertices.Count;
for (var i = 0; i < count; i++)
{
var offset = i * 3;
vertices.Add(new Vector3(-line.Points[offset], line.Points[offset + 2], -line.Points[offset + 1]));
var rgba = line.Color;
colors.Add(new Color(rgba?[0] ?? 1, rgba?[1] ?? 1, rgba?[2] ?? 1,
(rgba?[3] ?? 1) * (line.Opacities?[i] ?? 1)));
if (i > 0) { segments.Add(start + i - 1); segments.Add(start + i); }
}
if (line.Cyclic && count > 2) { segments.Add(start + count - 1); segments.Add(start); }
}
var mesh = new Mesh { name = "Captured Ship Lines", indexFormat = UnityEngine.Rendering.IndexFormat.UInt32 };
mesh.SetVertices(vertices);
mesh.SetColors(colors);
mesh.SetIndices(segments, MeshTopology.Lines, 0);
mesh.RecalculateBounds();
return mesh;
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a8a4f72a22b44819a71e43e21c7db894

View file

@ -1,8 +1,16 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine;
public class ThrusterHardpoint : MonoBehaviour
{
public MeshRenderer Emitter;
// Points an exhaust's shape at a hardpoint's emitter, or at nothing when the ship has no such hardpoint. The emitter
// carries the invisible material (alpha 0), so the particles never take their colour from its mesh: with Use Mesh
// Colors on, Unity's default, they would all be born transparent.
public static void WireExhaust(ParticleSystem exhaust, ThrusterHardpoint hardpoint)
{
var shape = exhaust.shape;
shape.useMeshColors = false;
shape.meshRenderer = hardpoint != null ? hardpoint.Emitter : null;
}
}

View file

@ -11,7 +11,7 @@ public class ChargeEffectManager : MonoBehaviour
public void StartCharging(ChargedWeapon weapon, EquippedItem item, EntityInstance source)
{
var effect = EffectPrototype.Instantiate<WeaponChargeEffect>();
var hp = source.Entity.Hardpoints[item.Position.x, item.Position.y];
var hp = item.Hardpoint;
var barrel = source.GetBarrel(hp);
var t = effect.transform;
t.SetParent(barrel);

View file

@ -12,7 +12,7 @@ public class ConstantLaserManager : ConstantWeaponEffectManager
{
var p = LaserPrototype.Instantiate<ConstantLaser>();
p.SourceEntity = source.Entity;
var hp = source.Entity.Hardpoints[item.Position.x, item.Position.y];
var hp = item.Hardpoint;
var barrel = source.GetBarrel(hp);
p.Range = item.Evaluate(data.Range);
var t = p.transform;

View file

@ -13,7 +13,7 @@ public class ConstantLightningManager : ConstantWeaponEffectManager
{
var p = LightningPrototype.Instantiate<ConstantLightning>();
p.Source = source;
var hp = source.Entity.Hardpoints[item.Position.x, item.Position.y];
var hp = item.Hardpoint;
var barrel = source.GetBarrel(hp);
p.Barrel = barrel;
p.Range = item.Evaluate(data.Range);

View file

@ -13,7 +13,7 @@ public class ConstantParticleWeaponManager : ConstantWeaponEffectManager
var p = WeaponPrototype.Instantiate<ConstantParticleWeapon>();
p.Source = source;
p.Target = target;
var hp = source.Entity.Hardpoints[item.Position.x, item.Position.y];
var hp = item.Hardpoint;
var barrel = source.GetBarrel(hp);
var t = p.transform;
t.SetParent(barrel);

View file

@ -45,7 +45,7 @@ public class GuidedProjectileManager : InstantWeaponEffectManager
if (target != null) p.Target = target.transform;
else p.TargetPosition = () => burst;
p.Frequency = launcher.DodgeFrequency;
var hp = source.Entity.Hardpoints[item.Position.x, item.Position.y];
var hp = item.Hardpoint;
var barrel = source.GetBarrel(hp);
p.StartPosition = (p.transform.position = barrel.position).ToCultMath();
p.Range = weapon.Range;
@ -66,7 +66,7 @@ public class GuidedProjectileManager : InstantWeaponEffectManager
p.Source = source.transform;
p.SourceEntity = source.Entity;
p.Frequency = guidance.DodgeFrequency;
var hp = source.Entity.Hardpoints[item.Position.x, item.Position.y];
var hp = item.Hardpoint;
var barrel = source.GetBarrel(hp);
p.StartPosition = (p.transform.position = barrel.position).ToCultMath();
p.Range = weapon.Range;

View file

@ -7,7 +7,7 @@ public class HitscanManager : InstantWeaponEffectManager
{
var p = Prototype.Instantiate<HitscanEffect>();
p.SourceEntity = source.Entity;
var hp = source.Entity.Hardpoints[item.Position.x, item.Position.y];
var hp = item.Hardpoint;
var barrel = source.GetBarrel(hp);
var t = p.transform;
t.SetParent(barrel, false);

View file

@ -9,7 +9,7 @@ public class LaserManager : InstantWeaponEffectManager
public override void Fire(InstantWeapon weapon, EquippedItem item, EntityInstance source, EntityInstance target, int shotId)
{
var p = ProjectilePrototype.Instantiate<Laser>();
var hp = source.Entity.Hardpoints[item.Position.x, item.Position.y];
var hp = item.Hardpoint;
var barrel = source.GetBarrel(hp);
var t = p.transform;
t.SetParent(barrel);

View file

@ -9,7 +9,7 @@ public class LightningGunManager : InstantWeaponEffectManager
public override void Fire(InstantWeapon weapon, EquippedItem item, EntityInstance source, EntityInstance target, int shotId)
{
var p = Prototype.Instantiate<Lightning>();
var hp = source.Entity.Hardpoints[item.Position.x, item.Position.y];
var hp = item.Hardpoint;
var barrel = source.GetBarrel(hp);
p.ShotId = shotId;
p.Barrel = barrel;

View file

@ -13,7 +13,7 @@ public class MineManager : InstantWeaponEffectManager
public override void Fire(InstantWeapon weapon, EquippedItem item, EntityInstance source, EntityInstance target, int shotId)
{
var p = ProjectilePrototype.Instantiate<Mine>();
var hp = source.Entity.Hardpoints[item.Position.x, item.Position.y];
var hp = item.Hardpoint;
var barrel = source.GetBarrel(hp);
var angle = weapon.Spread / 2;
p.Source = source;

View file

@ -11,7 +11,7 @@ public class ProjectileManager : InstantWeaponEffectManager
public override void Fire(InstantWeapon weapon, EquippedItem item, EntityInstance source, EntityInstance target, int shotId)
{
var p = ProjectilePrototype.Instantiate<Projectile>();
var hp = source.Entity.Hardpoints[item.Position.x, item.Position.y];
var hp = item.Hardpoint;
var barrel = source.GetBarrel(hp);
var angle = weapon.Spread / 2;
p.ShotId = shotId;

View file

@ -6,7 +6,7 @@ using GameCult.Caching.MessagePack;
// Aetheria's stores: one home store per type, composed here and nowhere else.
public static class AetheriaStores
{
public static readonly Type[] CatalogTypes = { typeof(ItemData), typeof(Faction), typeof(FactionProductData), typeof(PersonalityAttribute), typeof(NameFile), typeof(InputLayout), typeof(Loadout), typeof(FieldKindData) };
public static readonly Type[] CatalogTypes = { typeof(ItemData), typeof(ShipAuthoring), typeof(Faction), typeof(FactionProductData), typeof(PersonalityAttribute), typeof(NameFile), typeof(InputLayout), typeof(Loadout), typeof(FieldKindData) };
public static readonly Type[] RunTypes = { typeof(OrbitData), typeof(BodyData), typeof(SavedZone), typeof(SavedGame), typeof(ProvenanceLedger) };
public static readonly Type[] PlayerTypes = { typeof(PlayerSettings) };

View file

@ -12,45 +12,40 @@ public class BaseState
_agent = agent;
}
private static List<BaseState> _lastVisitedStates = new List<BaseState>();
private static List<BaseState> _leafStates = new List<BaseState>();
private static List<BaseState> _visitedStates = new List<BaseState>();
private static HashSet<BaseState> _ignoreStates = new HashSet<BaseState>();
// The walk's state is the call's own: zones (and so their Minions) are built on more than one thread.
public void AddTransition(BaseState targetState, Func<bool> condition, Action onTransition = null, bool includeChildren = false, params BaseState[] ignoreStates)
{
Transitions.Add(new StateTransition(targetState, condition, onTransition));
// Traverse the state graph, adding every state that is reachable from this state without traversing over ignored nodes
if (includeChildren)
{
_visitedStates.Clear();
_ignoreStates.Clear();
var visitedStates = new List<BaseState>();
var ignored = new HashSet<BaseState>();
if(ignoreStates!=null)
foreach (var ignoreState in ignoreStates)
_ignoreStates.Add(ignoreState);
_leafStates.Clear();
_leafStates.Add(this);
_ignoreStates.Add(this);
_ignoreStates.Add(targetState);
while (_leafStates.Count > 0)
ignored.Add(ignoreState);
var leafStates = new List<BaseState> { this };
ignored.Add(this);
ignored.Add(targetState);
while (leafStates.Count > 0)
{
_lastVisitedStates.Clear();
_lastVisitedStates.AddRange(_leafStates);
_leafStates.Clear();
foreach (var state in _lastVisitedStates)
var lastVisitedStates = leafStates;
leafStates = new List<BaseState>();
foreach (var state in lastVisitedStates)
{
foreach (var transition in state.Transitions)
{
if(!_ignoreStates.Contains(transition.TargetState))
if(!ignored.Contains(transition.TargetState))
{
_visitedStates.Add(transition.TargetState);
_ignoreStates.Add(transition.TargetState);
_leafStates.Add(transition.TargetState);
visitedStates.Add(transition.TargetState);
ignored.Add(transition.TargetState);
leafStates.Add(transition.TargetState);
}
}
}
}
foreach (var state in _visitedStates)
foreach (var state in visitedStates)
{
state.AddTransition(targetState, condition, onTransition);
}

View file

@ -47,8 +47,8 @@ public class Thermotoggle : Behavior
TargetTemperature = data.TargetTemperature;
}
public override bool Execute(float dt)
{
return Temperature < TargetTemperature ^ _data.HighPass;
}
// Whether the rest of this behaviour's group runs this tick: below the target, or above it for a high-pass one.
public bool Open => Temperature < TargetTemperature ^ _data.HighPass;
public override bool Execute(float dt) => Open;
}

View file

@ -0,0 +1,97 @@
using System;
using System.Collections.Generic;
using CultMath;
// The Delaunay triangulation of a galaxy's zone positions, as the edges Galaxy links zones along. Bowyer-Watson
// (Bowyer 1981, Watson 1981) in double precision: each point is inserted by removing every triangle whose
// circumcircle holds it and fanning the cavity's boundary to it. Every point lands in the triangulation, so for two or
// more distinct points the edge graph is connected.
public static class Delaunay
{
// Each edge once, as (lower index, higher index), in ascending order.
public static List<(int a, int b)> Edges(IReadOnlyList<float2> points)
{
var n = points.Count;
var x = new double[n + 3];
var y = new double[n + 3];
double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue;
for (var i = 0; i < n; i++)
{
x[i] = points[i].x;
y[i] = points[i].y;
minX = Math.Min(minX, x[i]);
minY = Math.Min(minY, y[i]);
maxX = Math.Max(maxX, x[i]);
maxY = Math.Max(maxY, y[i]);
}
// A super-triangle far outside the points, so its vertices bend no edge between them; its triangles are
// dropped at the end.
var size = Math.Max(Math.Max(maxX - minX, maxY - minY), 1e-6) * 1000;
double midX = (minX + maxX) / 2, midY = (minY + maxY) / 2;
x[n] = midX - size; y[n] = midY - size;
x[n + 1] = midX + size; y[n + 1] = midY - size;
x[n + 2] = midX; y[n + 2] = midY + size;
var triangles = new List<Triangle> { new Triangle(n, n + 1, n + 2, x, y) };
var cavity = new Dictionary<(int, int), int>();
for (var p = 0; p < n; p++)
{
cavity.Clear();
for (var t = triangles.Count - 1; t >= 0; t--)
{
var triangle = triangles[t];
var dx = x[p] - triangle.CenterX;
var dy = y[p] - triangle.CenterY;
if (dx * dx + dy * dy >= triangle.RadiusSquared) continue;
Count(cavity, triangle.A, triangle.B);
Count(cavity, triangle.B, triangle.C);
Count(cavity, triangle.C, triangle.A);
triangles[t] = triangles[triangles.Count - 1];
triangles.RemoveAt(triangles.Count - 1);
}
// The cavity's boundary is every edge only one removed triangle had.
foreach (var edge in cavity)
if (edge.Value == 1)
triangles.Add(new Triangle(edge.Key.Item1, edge.Key.Item2, p, x, y));
}
var edges = new SortedSet<(int a, int b)>();
foreach (var triangle in triangles)
{
if (triangle.A >= n || triangle.B >= n || triangle.C >= n) continue;
edges.Add(Ordered(triangle.A, triangle.B));
edges.Add(Ordered(triangle.B, triangle.C));
edges.Add(Ordered(triangle.C, triangle.A));
}
return new List<(int a, int b)>(edges);
}
private static void Count(Dictionary<(int, int), int> cavity, int a, int b)
{
var key = Ordered(a, b);
cavity[key] = cavity.TryGetValue(key, out var seen) ? seen + 1 : 1;
}
private static (int a, int b) Ordered(int a, int b) => a < b ? (a, b) : (b, a);
private readonly struct Triangle
{
public readonly int A, B, C;
public readonly double CenterX, CenterY, RadiusSquared;
public Triangle(int a, int b, int c, double[] x, double[] y)
{
A = a;
B = b;
C = c;
double ax = x[a], ay = y[a], bx = x[b], by = y[b], cx = x[c], cy = y[c];
var d = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by));
double a2 = ax * ax + ay * ay, b2 = bx * bx + by * by, c2 = cx * cx + cy * cy;
CenterX = (a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by)) / d;
CenterY = (a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax)) / d;
RadiusSquared = (ax - CenterX) * (ax - CenterX) + (ay - CenterY) * (ay - CenterY);
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a05b77dab9114e19b222b79a8403fc21

View file

@ -207,7 +207,9 @@ public abstract class Entity
VisibleEntities.Remove(remove.Value);
VisibleEnemies.Remove(remove.Value);
VisibleFriendlies.Remove(remove.Value);
_iffOverrides.Remove(remove.Value);
// A stance lasts the sitting: it goes with an entity gone for good (destroyed, warped away, unloaded), not
// with a ship docking, which leaves the zone parented to its dock (TryDock) and rejoins it on undock.
if (remove.Value.Parent == null) _iffOverrides.Remove(remove.Value);
if (_grudgeSubscriptions.TryGetValue(remove.Value, out var grudgeSubs))
{
foreach (var s in grudgeSubs) s.Dispose();
@ -866,8 +868,10 @@ public abstract class Entity
private void MapEntity()
{
var hullData = ItemManager.GetData(Hull) as HullData;
EquippedHull = new EquippedItem(ItemManager, Hull, int2.zero, this);
EquippedHull = new EquippedItem(ItemManager, Hull, int2.zero, this, null);
Equipment.Add(EquippedHull);
// A bare hull, one TryEquip never ran on, still updates: its ordered equipment is the hull alone.
_orderedEquipment = Equipment.ToArray();
Mass = hullData.Mass;
Temperature = new float[hullData.Shape.Width, hullData.Shape.Height];
NewTemperature = new float[hullData.Shape.Width, hullData.Shape.Height];
@ -1050,12 +1054,11 @@ public abstract class Entity
return item.EquippableItem;
}
// Check whether the given item will fit when its origin is placed at the given coordinate
private bool ItemFits(EquippableItemData itemData, HullData hullData, EquippableItem item, int2 hullCoord)
// Check whether the given item will fit when its origin is placed at the given coordinate. For hardpoint gear,
// hardpoint is the one hardpoint the item would occupy there (HardpointAt); Tool gear occupies none.
private bool ItemFits(EquippableItemData itemData, HullData hullData, EquippableItem item, int2 hullCoord, out HardpointData hardpoint)
{
// If the given coordinate isn't even in the ship it obviously won't fit
if (!hullData.Shape[hullCoord]) return false;
hardpoint = null;
// Items without specific hardpoints on the ship can be freely rotated and placed anywhere
if (itemData.HardpointType == HardpointType.Tool)
{
@ -1072,40 +1075,34 @@ public abstract class Entity
}
else
{
var hardpoint = Hardpoints[hullCoord.x, hullCoord.y];
// If there's no hardpoint there, it won't fit
hardpoint = HardpointAt(itemData, hullData, hullCoord);
if (hardpoint == null) return false;
// If the hardpoint type doesn't match the item, it won't fit
if (hardpoint.Type != itemData.HardpointType) return false;
// Items placed in hardpoints are automatically aligned to hardpoint rotation
item.Rotation = hardpoint.Rotation;
// Inset the shapes of both item and hardpoint
var itemShapeInset = hullData.Shape.Inset(itemData.Shape, hullCoord, item.Rotation);
var hardpointShapeInset = hullData.Shape.Inset(hardpoint.Shape, hardpoint.Position);
// Check every cell of the hardpoint shape for existing items
foreach(var v in hardpointShapeInset.Coordinates)
if (GearOccupancy[v.x, v.y] != null)
return false;
// Check every cell of the item's shape
foreach (var i in itemShapeInset.Coordinates)
{
// If the hardpoint does not have a matching cell, it wont fit
if (!hardpointShapeInset[i]) return false;
// If there is any gear already occupying that space, it won't fit
if (GearOccupancy[i.x, i.y] != null) return false;
}
}
return true;
}
// The one placement rule for hardpoint gear. At this origin the item lies within a hardpoint of its type, turned to
// that hardpoint's rotation (HardpointData.TakesAt, the fit rule); its own cells are free, since a hardpoint's
// leftover cells may hold general gear (operator, 2026-09-30: "saving slots in a hardpoint can be a valid tradeoff
// for crowded ships"); and that hardpoint holds no other hardpoint item, since it holds one at most.
private HardpointData HardpointAt(EquippableItemData itemData, HullData hullData, int2 hullCoord)
{
foreach (var hardpoint in hullData.Hardpoints)
{
if (!hardpoint.TakesAt(itemData, hullCoord - hardpoint.Position)) continue;
var ownCellsFree = itemData.Shape.Coordinates
.Select(v => hullCoord + itemData.Shape.Rotate(v, hardpoint.Rotation))
.All(c => GearOccupancy[c.x, c.y] == null);
var holdsAnother = hardpoint.Shape.Coordinates
.Select(v => GearOccupancy[hardpoint.Position.x + v.x, hardpoint.Position.y + v.y])
.Any(occupant => occupant != null && occupant.Data.HardpointType != HardpointType.Tool);
if (ownCellsFree && !holdsAnother) return hardpoint;
}
return null;
}
// Check whether the given item will fit when its origin is placed at the given coordinate on the hull
public bool ItemFits(EquippableItem item, int2 hullCoord)
{
@ -1114,7 +1111,7 @@ public abstract class Entity
var itemData = ItemManager.GetData(item);
var hullData = ItemManager.GetData(Hull) as HullData;
return ItemFits(itemData, hullData, item, hullCoord);
return ItemFits(itemData, hullData, item, hullCoord, out _);
}
public bool TryFindSpace(EquippableItem item, out int2 hullCoord)
@ -1134,7 +1131,7 @@ public abstract class Entity
{
foreach (var hullCoord2 in hullData.InteriorCells.Coordinates)
{
if (ItemFits(itemData, hullData, item, hullCoord2))
if (ItemFits(itemData, hullData, item, hullCoord2, out _))
{
hullCoord = hullCoord2;
return true;
@ -1146,14 +1143,21 @@ public abstract class Entity
// Search the ship for an empty hardpoint that matches the type and shape of the item
else
{
// Every origin the fit rule (HardpointData.TakesAt) can accept: the item, turned to the hardpoint's rotation,
// may sit as far up and left as its own extent allows, so a design whose shape lacks its origin cell is
// found wherever it fits, not only where its origin lies inside the hardpoint.
foreach (var hardpoint in hullData.Hardpoints)
{
if(hardpoint.Type == itemData.HardpointType)
{
foreach (var hardpointCoord in hardpoint.Shape.Coordinates)
var turned = hardpoint.Rotation == ItemRotation.Clockwise || hardpoint.Rotation == ItemRotation.CounterClockwise
? int2(itemData.Shape.Height, itemData.Shape.Width)
: int2(itemData.Shape.Width, itemData.Shape.Height);
for (var x = 1 - turned.x; x < hardpoint.Shape.Width; x++)
for (var y = 1 - turned.y; y < hardpoint.Shape.Height; y++)
{
var hullCoord2 = hardpoint.Position + hardpointCoord;
if (ItemFits(itemData, hullData, item, hullCoord2))
var hullCoord2 = hardpoint.Position + int2(x, y);
if (ItemFits(itemData, hullData, item, hullCoord2, out _))
{
hullCoord = hullCoord2;
return true;
@ -1179,7 +1183,7 @@ public abstract class Entity
var itemData = ItemManager.GetData(item);
var hullData = ItemManager.GetData(Hull) as HullData;
if (!ItemFits(itemData, hullData, item, hullCoord)) return false;
if (!ItemFits(itemData, hullData, item, hullCoord, out var hardpoint)) return false;
EquippedItem equippedItem;
if (itemData.HardpointType == HardpointType.Tool)
@ -1199,13 +1203,13 @@ public abstract class Entity
}
else
{
equippedItem = new EquippedItem(ItemManager, item, hullCoord, this);
equippedItem = new EquippedItem(ItemManager, item, hullCoord, this, null);
Equipment.Add(equippedItem);
}
}
else
{
equippedItem = new EquippedItem(ItemManager, item, hullCoord, this);
equippedItem = new EquippedItem(ItemManager, item, hullCoord, this, hardpoint);
Equipment.Add(equippedItem);
}
@ -1270,8 +1274,7 @@ public abstract class Entity
bay.DockedShip = null;
ship.RemoveParent();
Zone.Entities.Add(ship);
ship.Activate();
Zone.Admit(ship, piloted: false);
return true;
}
@ -1634,6 +1637,10 @@ public class EquippedItem : IStatContext
public float Wear { get; private set; }
public Shape InsetShape { get; }
public Entity Entity { get; }
// The one hardpoint this item occupies, decided once at equip by the placement rule (Entity.HardpointAt);
// null for Tool gear and the hull. The item's origin cell need not lie in it: Entity.Hardpoints[,] is a
// per-cell map for armour and display, never an item lookup.
public HardpointData Hardpoint { get; }
public EquippableItemData Data { get; }
public Lot Lot { get; }
@ -1730,11 +1737,12 @@ public class EquippedItem : IStatContext
SetAudioParameter(metaObject.Id, v, true);
}
public EquippedItem(ItemManager itemManager, EquippableItem item, int2 position, Entity entity)
public EquippedItem(ItemManager itemManager, EquippableItem item, int2 position, Entity entity, HardpointData hardpoint)
{
ItemManager = itemManager;
Data = ItemManager.GetData(item);
Entity = entity;
Hardpoint = hardpoint;
EquippableItem = item;
Lot = ItemManager.GetLot(item);
Position = position;
@ -1983,7 +1991,7 @@ public class EquippedCargoBay : EquippedItem
}
}
public EquippedCargoBay(ItemManager itemManager, EquippableItem item, int2 position, Entity entity, string name) : base(itemManager, item, position, entity)
public EquippedCargoBay(ItemManager itemManager, EquippableItem item, int2 position, Entity entity, string name) : base(itemManager, item, position, entity, null)
{
Data = ItemManager.GetData(EquippableItem) as CargoBayData;
Name = name;

View file

@ -128,6 +128,7 @@ public static class EntitySerializer
// docking bay units, and their stored contents. The provenance ledger's GC root walk.
public static IEnumerable<ItemInstance> Items(EntityPack pack)
{
if (pack == null) throw new InvalidOperationException("This run's save is malformed: an entity is null. Start a new game.");
yield return pack.Hull;
foreach (var (_, item) in pack.Equipment) yield return item;
foreach (var (_, item) in pack.CargoBays) yield return item;

View file

@ -35,7 +35,7 @@ public static class FireControl
// GameplaySettings.FiringArc. Zero on the hardpoint means "use the default," not "no arc."
public static float ArcFor(EquippedItem item)
{
var hardpoint = item.Entity.Hardpoints[item.Position.x, item.Position.y];
var hardpoint = item.Hardpoint;
var arc = hardpoint?.FiringArc ?? 0f;
return arc > 0 ? arc : item.ItemManager.GameplaySettings.FiringArc;
}

View file

@ -7,7 +7,6 @@ using System.Threading;
using System.Threading.Tasks;
using DataStructures.ViliWonka.Heap;
using Ink.Runtime;
using MIConvexHull;
using JM.LinqFaster;
using UniRx;
using CultMath;
@ -29,6 +28,10 @@ public class Galaxy
public Dictionary<Faction, FactionRelationship> FactionRelationships { get; } = new Dictionary<Faction, FactionRelationship>();
private Action<string> Log { get; }
public bool IsPrelude { get; }
// The seed this galaxy was generated at, which also seeds its run's item draws (RunStart); zero for a galaxy
// restored from a save.
public uint Seed { get; }
private HashSet<CultRecordKey> _containedFactions;
private GalaxyZone[] _exitPath;
@ -105,7 +108,8 @@ public class Galaxy
Background = background;
Log = log;
var factions = cache.GetAll<Faction>();
var random = new Random(seed == 0 ? (uint) (DateTime.Now.Ticks % uint.MaxValue) : seed);
Seed = seed == 0 ? (uint) (DateTime.Now.Ticks % uint.MaxValue) : seed;
var random = new Random(Seed);
Factions = factions.OrderBy(x => random.NextFloat()).Take(settings.MegaCount).ToArray();
foreach (var f in Factions) FactionRelationships[f] = FactionRelationship.Neutral;
@ -139,6 +143,11 @@ public class Galaxy
return _cache.GetAll<Faction>().FirstOrDefault(f => f.Name.StartsWith(name, StringComparison.InvariantCultureIgnoreCase));
}
// How many jumps a faction's influence reaches in this galaxy: its authored distance, halved (rounding up) in a
// prelude. Derived, never written back to the catalog's Faction, so one galaxy's generation cannot change the next.
public int InfluenceOf(Faction faction) =>
IsPrelude ? (faction.InfluenceDistance + 1) / 2 : faction.InfluenceDistance;
public Galaxy(
TutorialGenerationSettings settings,
SectorBackgroundSettings background,
@ -155,7 +164,8 @@ public class Galaxy
Background = background;
Log = log;
var random = new Random(seed == 0 ? (uint) (DateTime.Now.Ticks % uint.MaxValue) : seed);
Seed = seed == 0 ? (uint) (DateTime.Now.Ticks % uint.MaxValue) : seed;
var random = new Random(Seed);
var factions = new List<Faction>();
@ -177,11 +187,7 @@ public class Galaxy
factions.AddRange(neutralFactions);
Factions = factions.ToArray();
foreach (var faction in Factions)
{
FactionRelationships[faction] = FactionRelationship.Neutral;
faction.InfluenceDistance = (faction.InfluenceDistance + 1) / 2;
}
foreach (var faction in Factions) FactionRelationships[faction] = FactionRelationship.Neutral;
Zones = GenerateZones(settings.ZoneCount, ref random, progressCallback);
@ -190,13 +196,13 @@ public class Galaxy
CalculateDistanceMatrix(progressCallback);
HomeZones[protagonistFaction] = Zones
.MaxBy(z => ConnectedRegion(z, protagonistFaction.InfluenceDistance).Count);
.MaxBy(z => ConnectedRegion(z, InfluenceOf(protagonistFaction)).Count);
HomeZones[antagonistFaction] = Zones
.MaxBy(z => ConnectedRegion(z, antagonistFaction.InfluenceDistance).Count * z.Distance[HomeZones[protagonistFaction]]);
.MaxBy(z => ConnectedRegion(z, InfluenceOf(antagonistFaction)).Count * z.Distance[HomeZones[protagonistFaction]]);
HomeZones[protagonistFaction] = Zones
.MaxBy(z => ConnectedRegion(z, protagonistFaction.InfluenceDistance).Count * sqrt(z.Distance[HomeZones[antagonistFaction]]));
.MaxBy(z => ConnectedRegion(z, InfluenceOf(protagonistFaction)).Count * sqrt(z.Distance[HomeZones[antagonistFaction]]));
// var antagonistRegion = ConnectedRegion(HomeZones[antagonistFaction], antagonistFaction.InfluenceDistance);
// var protagonistRegion = ConnectedRegion(HomeZones[protagonistFaction], protagonistFaction.InfluenceDistance);
@ -205,13 +211,13 @@ public class Galaxy
var bufferDistance = Zones.Min(z => abs(z.Distance[HomeZones[antagonistFaction]] - z.Distance[HomeZones[protagonistFaction]]));
var potentialBufferZones = Zones
.Where(z => abs(z.Distance[HomeZones[antagonistFaction]] - z.Distance[HomeZones[protagonistFaction]]) == bufferDistance);
HomeZones[bufferFaction] = potentialBufferZones.MaxBy(z => ConnectedRegion(z, bufferFaction.InfluenceDistance).Count);
HomeZones[bufferFaction] = potentialBufferZones.MaxBy(z => ConnectedRegion(z, InfluenceOf(bufferFaction)).Count);
// Place neutral headquarters away from existing factions while also maximizing territory
foreach (var faction in neutralFactions)
{
HomeZones[faction] = Zones.MaxBy(z =>
ConnectedRegion(z, faction.InfluenceDistance).Count *
ConnectedRegion(z, InfluenceOf(faction)).Count *
HomeZones.Values.Aggregate(1f, (i, os) => i * sqrt(os.Distance[z])));
}
@ -221,7 +227,7 @@ public class Galaxy
.Where(z => z.Factions.Contains(antagonistFaction) && z.Factions.Contains(bufferFaction));
if (potentialQuestZones.Any())
HomeZones[questFaction] = potentialQuestZones
.MaxBy(z => z.Distance[HomeZones[antagonistFaction]] * ConnectedRegion(z, questFaction.InfluenceDistance).Count);
.MaxBy(z => z.Distance[HomeZones[antagonistFaction]] * ConnectedRegion(z, InfluenceOf(questFaction)).Count);
else
HomeZones[questFaction] = Zones
.Where(z => z.Factions.Contains(antagonistFaction))
@ -287,9 +293,9 @@ public class Galaxy
// While occupying as much territory as possible
foreach (var mega in bossMegas)
{
HomeZones[mega] = ConnectedRegion(BossZones[mega], mega.InfluenceDistance)
HomeZones[mega] = ConnectedRegion(BossZones[mega], InfluenceOf(mega))
.MaxBy(z =>
ConnectedRegion(z, mega.InfluenceDistance).Count *
ConnectedRegion(z, InfluenceOf(mega)).Count *
HomeZones.Values.Aggregate(1f, (i, os) => i * sqrt(os.Distance[z])));
}
@ -297,7 +303,7 @@ public class Galaxy
foreach (var mega in Factions.Where(m => !bossMegas.Contains(m)))
{
HomeZones[mega] = Zones.MaxBy(z =>
pow(ConnectedRegion(z, mega.InfluenceDistance).Count, HomeZones.Count) *
pow(ConnectedRegion(z, InfluenceOf(mega)).Count, HomeZones.Count) *
Exit.Distance[z] * Entrance.Distance[z] *
HomeZones.Values.Aggregate(1f, (i, os) => i * sqrt(os.Distance[z])) *
BossZones.Values.Aggregate(1f, (i, os) => i * sqrt(os.Distance[z])));
@ -315,14 +321,14 @@ public class Galaxy
// Factions are present in all zones within their sphere of influence
zone.Factions = Factions
.Where(f => HomeZones.ContainsKey(f))
.Where(f => zone.Distance[HomeZones[f]] <= f.InfluenceDistance)
.Where(f => zone.Distance[HomeZones[f]] <= InfluenceOf(f))
.ToArray();
// Owner of a zone is the faction with the nearest headquarters
var nearestFaction = Factions
.Where(f => HomeZones.ContainsKey(f))
.MinBy(f => (float)zone.Distance[HomeZones[f]]);
if (zone.Distance[HomeZones[nearestFaction]] <= nearestFaction.InfluenceDistance)
if (zone.Distance[HomeZones[nearestFaction]] <= InfluenceOf(nearestFaction))
zone.Owner = nearestFaction;
}
}
@ -332,12 +338,13 @@ public class Galaxy
ref Random random,
Action<string> progressCallback = null)
{
var used = new HashSet<string>();
for (var i = 0; i < Factions.Length; i++)
{
progressCallback?.Invoke($"Feeding Markov Chains: {i + 1} / {Factions.Length}");
//if(progressCallback!=null) Thread.Sleep(250); // Inserting Delay to make it seem like it's doing more work lmao
var faction = Factions[i];
_nameGenerators[faction] = new MarkovNameGenerator(ref random, cache.Get(faction.GeonameFile).Names, nameGeneratorSettings);
_nameGenerators[faction] = new MarkovNameGenerator(ref random, cache.Get(faction.GeonameFile).Names, nameGeneratorSettings, used);
}
// Generate zone name using the owner's name generator, otherwise assign catalogue ID
@ -359,22 +366,10 @@ public class Galaxy
progressCallback?.Invoke("Triangulating Zone Positions");
if (progressCallback != null) Thread.Sleep(500); // Inserting Delay to make it seem like it's doing more work lmao
// Create a delaunay triangulation to connect adjacent sectors
var triangulation = DelaunayTriangulation<Vertex2<GalaxyZone>, Cell2<GalaxyZone>>
.Create(Zones.Select(z => new Vertex2<GalaxyZone>(z.Position, z)).ToList(), 1e-7f);
var links = new HashSet<(GalaxyZone, GalaxyZone)>();
foreach (var cell in triangulation.Cells)
{
if (!links.Contains((cell.Vertices[0].StoredObject, cell.Vertices[1].StoredObject)) &&
!links.Contains((cell.Vertices[1].StoredObject, cell.Vertices[0].StoredObject)))
links.Add((cell.Vertices[0].StoredObject, cell.Vertices[1].StoredObject));
if (!links.Contains((cell.Vertices[1].StoredObject, cell.Vertices[2].StoredObject)) &&
!links.Contains((cell.Vertices[2].StoredObject, cell.Vertices[1].StoredObject)))
links.Add((cell.Vertices[1].StoredObject, cell.Vertices[2].StoredObject));
if (!links.Contains((cell.Vertices[0].StoredObject, cell.Vertices[2].StoredObject)) &&
!links.Contains((cell.Vertices[2].StoredObject, cell.Vertices[0].StoredObject)))
links.Add((cell.Vertices[0].StoredObject, cell.Vertices[2].StoredObject));
}
// The Delaunay triangulation connects adjacent sectors, every zone among them
var links = Delaunay.Edges(Zones.Select(z => z.Position).ToArray())
.Select(edge => (Zones[edge.a], Zones[edge.b]))
.ToList();
progressCallback?.Invoke("Eliminating Zone Links");
if (progressCallback != null) Thread.Sleep(500); // Inserting Delay to make it seem like it's doing more work lmao

View file

@ -0,0 +1,86 @@
using System;
using System.IO;
using GameCult.Caching;
using MessagePack;
using static CultMath.math;
using Random = CultMath.Random;
// The galaxy half of a scenario's vocabulary (docs/scenarios-cut.md, R.4): the two kinds of galaxy the game generates,
// at the scenario's seed. The menu hands it the generation inputs; RunStart.Generate sets the seed and hands it to
// Scenario.Generate. The background's noise position derives from the same seed, so a fixed seed fixes the whole
// galaxy, and a clock seed makes every launch a new one.
public sealed class GalaxyStage
{
private readonly SectorGenerationSettings _sector;
private readonly SectorBackgroundSettings _sectorBackground;
private readonly TutorialGenerationSettings _prelude;
private readonly SectorBackgroundSettings _preludeBackground;
private readonly NameGeneratorSettings _names;
private readonly CultCache _cache;
private readonly PlayerSettings _playerSettings;
private readonly DirectoryInfo _narrativeDirectory;
private readonly Action<string> _log;
private readonly Action<string> _progress;
private readonly Func<uint> _clock;
public GalaxyStage(
SectorGenerationSettings sector,
SectorBackgroundSettings sectorBackground,
TutorialGenerationSettings prelude,
SectorBackgroundSettings preludeBackground,
NameGeneratorSettings names,
CultCache cache,
PlayerSettings playerSettings,
DirectoryInfo narrativeDirectory,
Action<string> log,
Action<string> progress = null,
Func<uint> clock = null)
{
_sector = sector;
_sectorBackground = sectorBackground;
_prelude = prelude;
_preludeBackground = preludeBackground;
_names = names;
_cache = cache;
_playerSettings = playerSettings;
_narrativeDirectory = narrativeDirectory;
_log = log;
_progress = progress;
_clock = clock ?? (() => (uint) (DateTime.Now.Ticks % uint.MaxValue));
}
// The seed this generation runs at, never zero: the scenario's, or the clock's when the scenario's is zero.
public uint Seed { get; private set; }
internal void SeedFrom(Scenario scenario)
{
var clock = _clock();
Seed = scenario.Seed != 0 ? scenario.Seed : clock != 0 ? clock : 1;
}
// A main galaxy: the sector settings, factions drawn from the catalog, an exit to reach.
public Galaxy Main()
{
var background = Copy(_sectorBackground);
var random = new Random(Seed);
background.NoisePosition = random.NextFloat() * 1000;
return new Galaxy(_sector, background, _names, _cache, _log, _progress, Seed);
}
// A prelude galaxy: the tutorial settings and their fixed factions, centred in dense cloud.
public Galaxy Prelude()
{
var background = Copy(_preludeBackground);
var random = new Random(Seed);
var iteration = 1;
do
{
background.NoisePosition = random.NextFloat() * 1000;
_progress?.Invoke($"Finding Galaxy Position: iteration {iteration++}");
} while (background.CloudDensity(float2(.5f)) < .5f);
return new Galaxy(_prelude, background, _names, _cache, _playerSettings, _narrativeDirectory, _log, _progress, Seed);
}
private static SectorBackgroundSettings Copy(SectorBackgroundSettings settings) =>
MessagePackSerializer.Deserialize<SectorBackgroundSettings>(MessagePackSerializer.Serialize(settings));
}

View file

@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: ee065f025d2f5374db2ceaa973b822d4
guid: f5cf458f47074786bf11e72b5d93c545
MonoImporter:
externalObjects: {}
serializedVersion: 2

View file

@ -204,14 +204,7 @@ public class Shape
for (int y = 0; y < other.Height - height + 1; y++)
{
position = int2(x, y);
var fits = true;
foreach (var v in Coordinates)
{
fits = fits && other[Rotate(v, rotation) + position];
if (!fits) break;
}
if (fits) return true;
if (FitsAt(other, rotation, position)) return true;
}
}
@ -219,6 +212,14 @@ public class Shape
return false;
}
// Whether this shape, turned to a rotation and placed at a position, lies wholly within another shape's cells
public bool FitsAt(Shape other, ItemRotation rotation, int2 position)
{
foreach (var v in Coordinates)
if (!other[Rotate(v, rotation) + position]) return false;
return true;
}
// Set every cell on the line from a to b to true according to Bresenham's Line Algorithm
public void SetLine(float2 a, float2 b)
{
@ -530,6 +531,11 @@ public class HullData : EquippableItemData
[Inspectable, JsonProperty("canTow"), Key(29)]
public bool CanTow;
// The hull's visual: a ShipAuthoring record holding its model package, or unset for a Unity-prefab hull. A hull
// names exactly one of Prefab and Visual. Keys 30 and 31 are EquippableItemData's, so 32 is the next free key.
[Inspectable, JsonProperty("visual"), Key(32)]
public CultRecordRef<ShipAuthoring> Visual;
[IgnoreMember]
public Shape InteriorCells
{
@ -567,6 +573,20 @@ public class HardpointData
return $"{Enum.GetName(typeof(HardpointType), Type)} Hardpoint {Rotation.Arrow()}";
}
// The one fit rule for hardpoint gear (operator, 2026-09-30: "Hardpoint fit is loose: nobody's gonna stop you
// from putting a small reactor in a large reactor's hardpoint"): gear of this hardpoint's type fits when its shape,
// laid in at the hardpoint's rotation, lies within the hardpoint's cells. TakesAt is the same rule at one offset
// from the hardpoint's origin, which is where equipping places it.
public bool Takes(EquippableItemData design) =>
design.HardpointType == Type && design.Shape.FitsWithin(Shape, Rotation, out _);
public bool TakesAt(EquippableItemData design, int2 offset) =>
design.HardpointType == Type && design.Shape.FitsAt(Shape, Rotation, offset);
// Generation's placement preference, not a fit rule: gear that fits and fills every cell of the hardpoint.
public bool IsFilledBy(EquippableItemData design) =>
Takes(design) && design.Shape.Coordinates.Length == Shape.Coordinates.Length;
[IgnoreMember]
public float3 TintColor
{

View file

@ -27,7 +27,7 @@ public class LoadoutSlot
[Key(2)] public CultRecordRef<EquippableItemData> Design;
}
// The owner of loadouts: capture from a live ship, the only writer, and the only builder of a ship from a loadout.
// The owner of loadouts: capture from a live ship, the only writer, and the only builder of an entity from a loadout.
public static class Loadouts
{
// Records the hull design and one slot per equipped item (gear, then cargo bays, then docking bays) with its cell,
@ -64,11 +64,14 @@ public static class Loadouts
// The only writer of presets. It opens its own short-lived cache over the catalog file, writable, and disposes it
// after the one commit. No other cache is touched, so no catalog instance play holds (or has mutated) can reach the
// file; a cache that already has the catalog open sees the preset only once it reloads.
// Throws and writes nothing when the file is missing (capture never creates a catalog), when a preset of this name
// Throws and writes nothing when the loadout names a mod design (hull or slot), when the file is missing (capture never creates a catalog), when a preset of this name
// exists under another key, or when one exists under KeyOf(Name) and replace is not set. The commit is conditional
// on the record at KeyOf(Name), so a preset changed on disk since this open is not clobbered: returns false then.
public static bool Commit(string catalogPath, Loadout loadout, bool replace)
{
var modDesigns = new[] { loadout.Hull.Key }.Concat(loadout.Slots.Select(slot => slot.Design.Key)).Where(ShipModCatalog.IsModKey).Select(key => key.Value).Distinct().ToArray();
if (modDesigns.Length > 0)
throw new InvalidOperationException($"Preset '{loadout.Name}' names mod designs ({string.Join(", ", modDesigns)}); the shipped catalog never references a mod, so a mod ship cannot be captured as a preset.");
if (!File.Exists(catalogPath))
throw new InvalidOperationException($"Catalog {catalogPath} does not exist; a preset capture never creates one.");
using var cache = AetheriaStores.Open(catalogPath, catalogWritable: true);
@ -86,36 +89,30 @@ public static class Loadouts
});
}
// All-or-nothing: returns a ship only when every design resolved, had an available product and fitted, the loadout
// has at most WeaponGroupCount weapon groups, and every group index names a weapon slot. Every failure is listed; on
// any failure nothing is returned and the zone and cache are unchanged, but a failed fit has already drawn from
// itemManager.Random. A design is built by its first available product in record-key order. A game spawner is to
// pass LoadoutGenerator.IsAvailable as isAvailable, with no fallback to any manufacturer. The ship always gets
// exactly WeaponGroupCount groups; a loadout with fewer is padded with empty groups. A failed materialization
// leaves any minted lots in the live ledger; they are not roots, so the next commit drops them.
public static Ship Materialize(ItemManager itemManager, Zone liveZone, Loadout loadout,
// The quality a design no manufacturer makes is built at: the console give's.
public const float UnbrandedQuality = .95f;
// All-or-nothing: returns an entity only when every design resolved and fitted, the loadout has at most
// WeaponGroupCount weapon groups, and every group index names a weapon slot. Every failure is listed; on any failure
// nothing is returned and the zone and cache are unchanged, but a failed fit has already drawn from
// itemManager.Random. How each design is built is Resolve's rule. A game spawner is to pass
// LoadoutGenerator.IsAvailable as isAvailable, with no fallback to any manufacturer; RunStart does. The hull's type
// picks the entity: a ship hull builds a Ship, a turret hull an OrbitalEntity with no orbit, which stays where it is
// put; a station hull is refused. The entity always gets exactly WeaponGroupCount groups; a loadout with fewer is
// padded with empty groups. A failed materialization leaves any minted lots in the live ledger; they are not roots,
// so the next commit drops them.
public static Entity Materialize(ItemManager itemManager, Zone liveZone, Loadout loadout,
Predicate<FactionProductData> isAvailable, List<string> failures)
{
var cache = itemManager.ItemData;
var products = cache.GetAll<FactionProductData>().OrderBy(p => cache.RefOf(p).Key.Value, StringComparer.Ordinal).ToArray();
var products = ProductsInKeyOrder(cache);
var reported = failures.Count;
FactionProductData Resolve<T>(CultRecordRef<T> design, string where) where T : EquippableItemData
{
var data = cache.Get(design);
if (data == null)
{
failures.Add($"{where}: design {design.Key} is not in the catalog");
return null;
}
var product = products.FirstOrDefault(p => p.Design.Key.Equals(design.Key) && isAvailable(p));
if (product == null) failures.Add($"{where}: no available product of {data.Name}");
return product;
}
var hullProduct = Resolve(loadout.Hull, "hull");
var slotProducts = loadout.Slots.Select(slot => Resolve(slot.Design, Cell(slot))).ToArray();
var hullBuild = Resolve(itemManager, products, loadout.Hull, isAvailable, "hull", failures);
var hullData = cache.Get(loadout.Hull);
if (hullData is { HullType: HullType.Station })
failures.Add($"hull: {hullData.Name} is a station hull; a preset builds a ship or a turret");
var slotBuilds = loadout.Slots.Select(slot => Resolve(itemManager, products, slot.Design, isAvailable, Cell(slot), failures)).ToArray();
var groups = loadout.WeaponGroups ?? new int[0][];
var groupCount = itemManager.GameplaySettings.WeaponGroupCount;
if (groups.Length > groupCount) failures.Add($"weapon groups: {groups.Length} groups, at most {groupCount}");
@ -127,23 +124,26 @@ public static class Loadouts
}
if (failures.Count > reported) return null;
var hull = (EquippableItem) itemManager.CreateInstance(hullProduct);
var ship = new Ship(itemManager, liveZone, hull, itemManager.GameplaySettings.DefaultEntitySettings);
var hull = hullBuild();
var settings = itemManager.GameplaySettings.DefaultEntitySettings;
Entity entity = hullData.HullType == HullType.Turret
? new OrbitalEntity(itemManager, liveZone, hull, default, settings)
: new Ship(itemManager, liveZone, hull, settings);
var equipped = new EquippedItem[loadout.Slots.Count];
for (var i = 0; i < loadout.Slots.Count; i++)
{
var slot = loadout.Slots[i];
var unit = (EquippableItem) itemManager.CreateInstance(slotProducts[i]);
var unit = slotBuilds[i]();
unit.Rotation = slot.Rotation;
if (!ship.TryEquip(unit, slot.Position))
if (!entity.TryEquip(unit, slot.Position))
{
failures.Add($"{Cell(slot)}: {cache.Get(slot.Design).Name} does not fit");
continue;
}
equipped[i] = ship.Equipment
.Concat<EquippedItem>(ship.CargoBays)
.Concat(ship.DockingBays)
equipped[i] = entity.Equipment
.Concat<EquippedItem>(entity.CargoBays)
.Concat(entity.DockingBays)
.First(item => item.EquippableItem == unit);
}
if (failures.Count > reported) return null;
@ -154,9 +154,44 @@ public static class Loadouts
var items = g < groups.Length ? groups[g].Select(i => equipped[i]).ToList() : new List<EquippedItem>();
built[g] = (items.Select(item => item.GetBehavior<Weapon>()).ToList(), items);
}
ship.WeaponGroups = built;
return ship;
entity.WeaponGroups = built;
return entity;
}
// How one design is built, or null with the failure listed; nothing is minted until the returned builder runs. A
// design is built by its first available product in record-key order. A design with no product at all is outside
// the economy (docs/scenarios-cut.md, Q3: generation, stock and sale all go through products) and is built
// unbranded, with no maker, at UnbrandedQuality. A design whose products are all unavailable is not built.
public static Func<EquippableItem> Resolve<T>(ItemManager itemManager, CultRecordRef<T> design,
Predicate<FactionProductData> isAvailable, string where, List<string> failures) where T : EquippableItemData =>
Resolve(itemManager, ProductsInKeyOrder(itemManager.ItemData), design, isAvailable, where, failures);
private static Func<EquippableItem> Resolve<T>(ItemManager itemManager, FactionProductData[] products,
CultRecordRef<T> design, Predicate<FactionProductData> isAvailable, string where, List<string> failures)
where T : EquippableItemData
{
var data = itemManager.ItemData.Get(design);
if (data == null)
{
failures.Add($"{where}: design {design.Key} is not in the catalog");
return null;
}
var made = products.Where(p => p.Design.Key.Equals(design.Key)).ToArray();
if (made.Length == 0)
return () => (EquippableItem) itemManager.CreateInstance(itemManager.CreateLot(data, default, UnbrandedQuality));
var product = made.FirstOrDefault(p => isAvailable(p));
if (product == null)
{
failures.Add($"{where}: no available product of {data.Name}");
return null;
}
return () => (EquippableItem) itemManager.CreateInstance(product);
}
private static FactionProductData[] ProductsInKeyOrder(CultCache cache) =>
cache.GetAll<FactionProductData>().OrderBy(p => cache.RefOf(p).Key.Value, StringComparer.Ordinal).ToArray();
private static string Cell(LoadoutSlot slot) => $"slot {slot.Position.x},{slot.Position.y}";
}

View file

@ -92,6 +92,19 @@ public class LoadoutGenerator
throw new InvalidLoadoutException("Failed to equip selected docking bay!");
}
// Every station carries a heater (operator, 2026-09-30): an idle station has no other heat source and cools
// toward freezing and invisibility. A heater is general gear whose thermostat runs its heat only below a
// target, the composition a cockpit uses: a low-pass Thermotoggle, then Heat, in its behaviours.
emptyShape = entity.UnoccupiedSpace;
var (heaterProduct, heaterData) = RandomProduct<GearData>(2, item => IsHeater(item) && item.Shape.FitsWithin(emptyShape, out _, out _), required: true);
if (heaterData == null) throw new InvalidLoadoutException("No compatible heater found for station!");
heaterData.Shape.FitsWithin(emptyShape, out var heaterRotation, out var heaterPosition);
var heater = ItemManager.CreateInstance(heaterProduct) as EquippableItem;
heater.Rotation = heaterRotation;
if (!entity.TryEquip(heater, heaterPosition))
throw new InvalidLoadoutException("Failed to equip selected heater!");
FillInterior(entity);
var cargo = entity.CargoBays.First();
@ -109,6 +122,11 @@ public class LoadoutGenerator
return EntitySerializer.Pack(entity) as OrbitalEntityPack;
}
private static bool IsHeater(GearData item) =>
item.HardpointType == HardpointType.Tool &&
item.Behaviors.Any(b => b is ThermotoggleData { HighPass: false }) &&
item.Behaviors.Any(b => b is HeatData);
// Every entity needs a hull, so hulls are always required
public (FactionProductData product, HullData design) RandomHull(HullType type, Predicate<HullData> hullFilter = null)
{
@ -123,12 +141,14 @@ public class LoadoutGenerator
// lacks variety, so it is logged rather than hidden.
public (FactionProductData product, T design)[] RandomProducts<T>(int count, float sizeExponent, Predicate<T> filter = null, bool required = false) where T : EquippableItemData
{
var hulls = ItemManager.ItemData.GetAll<HullData>().ToArray();
var candidates = ItemManager.ItemData.GetAll<FactionProductData>()
.Select(product => (product, design: ItemManager.ItemData.Get(product.Design) as T))
.Where(entry =>
entry.design != null &&
entry.design.Price > 0 &&
entry.product.Manufacturer.IsSet() &&
HasHome(entry.design, hulls) &&
(filter?.Invoke(entry.design) ?? true))
.ToArray();
var available = candidates.Where(entry => IsAvailable(entry.product)).ToArray();
@ -147,12 +167,22 @@ public class LoadoutGenerator
count);
}
// Hardpoint gear that no hull in the catalog can mount has no home (operator, 2026-09-30: "we'll need to author a
// bunch more hulls before all the gear variety in the game has a home"): generation never offers it, so no station
// stocks it. It gains one the moment a hull with a hardpoint that takes it exists. Tool gear goes in any interior.
private static bool HasHome(EquippableItemData design, HullData[] hulls) =>
design.HardpointType == HardpointType.Tool || design.HardpointType == HardpointType.Hull ||
hulls.Any(hull => hull.Hardpoints.Any(hardpoint => hardpoint.Takes(design)));
// No galaxy means no availability to filter by: every product is on offer. A fixture generates loadouts that
// way, so a test can exercise placement and products without standing up a whole galaxy; no game path does.
// Loadouts.Materialize takes availability as a predicate; a game spawner materializing presets is to pass this, so
// presets and generation share one availability rule. No game path materializes a preset yet.
// Loadouts.Materialize takes availability as a predicate; RunStart, the game's one preset spawner, passes this, so
// presets and generation share one availability rule. In a galaxy, a faction always reaches its own manufacturer's
// gear, and otherwise gear made by a manufacturer in that galaxy that its allegiance names (operator, 2026-09-30:
// allegiance lists only other factions).
public bool IsAvailable(FactionProductData product) =>
Galaxy == null || Galaxy.IsPrelude ||
Faction != null && ItemManager.ItemData.Get(product.Manufacturer) == Faction ||
Galaxy.ContainsFaction(product.Manufacturer) && (Faction == null || Faction.Allegiance.ContainsKey(product.Manufacturer));
// Prioritize products from the zone faction and its allies, penalizing distance to the manufacturer's headquarters
@ -174,10 +204,11 @@ public class LoadoutGenerator
public (FactionProductData product, T design) RandomProduct<T>(HardpointData hardpoint, float sizeExponent, Predicate<T> filter = null, bool required = false) where T : EquippableItemData
{
return RandomProduct<T>(sizeExponent, item => item.HardpointType == hardpoint.Type &&
(filter?.Invoke(item) ?? true) &&
item.Shape.FitsWithin(hardpoint.Shape, hardpoint.Rotation, out _) &&
item.Shape.Coordinates.Length==hardpoint.Shape.Coordinates.Length, required);
// Every candidate passes the one fit rule, HardpointData.Takes. Generation prefers gear that fills the hardpoint
// and falls back to anything that fits only when nothing that fills it is on offer.
var filling = RandomProduct<T>(sizeExponent, item => hardpoint.IsFilledBy(item) && (filter?.Invoke(item) ?? true));
if (filling.design != null) return filling;
return RandomProduct<T>(sizeExponent, item => hardpoint.Takes(item) && (filter?.Invoke(item) ?? true), required);
}
private void OutfitEntity(Entity entity)
@ -209,7 +240,7 @@ public class LoadoutGenerator
{
// If a previously selected product fits, use that one (this is why we must process larger hardpoints first)
var entry = previousProducts
.FirstOrDefault(e => e.design.HardpointType == hardpoint.Type && e.design.Shape.FitsWithin(hardpoint.Shape, hardpoint.Rotation, out _));
.FirstOrDefault(e => hardpoint.Takes(e.design));
var previousItem = entity.Equipment.FirstOrDefault(item => item.Data == entry.design);
if (entry.design == null) entry = RandomProduct<GearData>(hardpoint, 2);
if (entry.design == null) ItemManager.Log($"No compatible item found for entity {Enum.GetName(typeof(HardpointType), hardpoint.Type)} hardpoint!");

View file

@ -14,14 +14,17 @@ public class MarkovNameGenerator
{
private Dictionary<string, List<char>> _chains = new Dictionary<string, List<char>>();
private List<string> _samples = new List<string>();
private static List<string> _used = new List<string>();
// The names already given, shared by every generator that must not repeat another's: a galaxy passes one set to
// all its factions' generators. Never process-wide, so one galaxy's names cannot change the next galaxy's.
private readonly HashSet<string> _used;
private int _order;
private int _minLength;
private int _maxLength;
private Random _random;
public MarkovNameGenerator(ref Random random, IEnumerable<string> sampleNames, NameGeneratorSettings settings)
public MarkovNameGenerator(ref Random random, IEnumerable<string> sampleNames, NameGeneratorSettings settings, HashSet<string> used)
{
_used = used;
var names = new HashSet<string>();
foreach (var line in sampleNames)
{
@ -41,6 +44,7 @@ public class MarkovNameGenerator
public MarkovNameGenerator(ref Random random, IEnumerable<string> sampleNames, int order, int minLength, int maxLength)
{
_used = new HashSet<string>();
_random = random;
_order = max(1, order);
@ -113,12 +117,6 @@ public class MarkovNameGenerator
}
}
//Reset the used names
public void Reset()
{
_used.Clear();
}
//Get a random letter from the chain
private char GetLetter(string token)
{

View file

@ -1,114 +0,0 @@
using System.Collections;
using System.Linq;
using MIConvexHull;
using CultMath;
using static CultMath.math;
/// <summary>
/// A vertex is a simple class that stores the postion of a point, node or vertex.
/// </summary>
public class Cell2 : TriangulationCell<Vertex2, Cell2>
{
float2? circumCenter, centroid;
public float2 Circumcenter {
get {
circumCenter = circumCenter ?? GetCircumcenter();
return circumCenter.Value;
}
}
public float2 Centroid {
get {
centroid = centroid ?? GetCentroid();
return centroid.Value;
}
}
public Cell2 ()
{
}
double LengthSquared (float[] v)
{
float norm = 0;
for (int i = 0; i < v.Length; i++) {
var t = v [i];
norm += t * t;
}
return norm;
}
float Determinant(float[,] m)
{
float fCofactor00 = m[1,1] * m[2,2] - m[1,2] * m[2,1];
float fCofactor10 = m[1,2] * m[2,0] - m[1,0] * m[2,2];
float fCofactor20 = m[1,0] * m[2,1] - m[1,1] * m[2,0];
float fDet = m[0,0] * fCofactor00 + m[0,1] * fCofactor10 + m[0,2] * fCofactor20;
return fDet;
}
float2 GetCircumcenter ()
{
// From MathWorld: http://mathworld.wolfram.com/Circumcircle.html
var points = Vertices;
float[,] m = new float[3, 3];
// x, y, 1
for (int i = 0; i < 3; i++) {
m[i, 0] = points[i].x;
m[i, 1] = points[i].y;
m[i, 2] = 1;
}
var a = Determinant(m);
// size, y, 1
for (int i = 0; i < 3; i++) {
m[i, 0] = lengthsq(points[i].StoredPosition);
}
var dx = -Determinant(m);
// size, x, 1
for (int i = 0; i < 3; i++) {
m[i, 1] = points[i].x;
}
var dy = Determinant(m);
// size, x, y
//for (int i = 0; i < 3; i++) {
// m[i, 2] = points[i].y;
//}
//var c = -Det(m);
var s = -1.0f / (2.0f * a);
//var r = System.Math.Abs(s) * System.Math.Sqrt(dx * dx + dy * dy - 4 * a * c);
return new float2(s * dx, s * dy);
}
float2 GetCentroid ()
{
return new float2(Vertices.Select(v => v.Position[0]).Average(), Vertices.Select(v => v.Position[1]).Average());
}
}

View file

@ -1,114 +0,0 @@
using System.Collections;
using System.Linq;
using MIConvexHull;
using CultMath;
using static CultMath.math;
/// <summary>
/// A vertex is a simple class that stores the postion of a point, node or vertex.
/// </summary>
public class Cell2<T> : TriangulationCell<Vertex2<T>, Cell2<T>>
{
float2? circumCenter, centroid;
public float2 Circumcenter {
get {
circumCenter = circumCenter ?? GetCircumcenter();
return circumCenter.Value;
}
}
public float2 Centroid {
get {
centroid = centroid ?? GetCentroid();
return centroid.Value;
}
}
public Cell2 ()
{
}
double LengthSquared (float[] v)
{
float norm = 0;
for (int i = 0; i < v.Length; i++) {
var t = v [i];
norm += t * t;
}
return norm;
}
float Determinant(float[,] m)
{
float fCofactor00 = m[1,1] * m[2,2] - m[1,2] * m[2,1];
float fCofactor10 = m[1,2] * m[2,0] - m[1,0] * m[2,2];
float fCofactor20 = m[1,0] * m[2,1] - m[1,1] * m[2,0];
float fDet = m[0,0] * fCofactor00 + m[0,1] * fCofactor10 + m[0,2] * fCofactor20;
return fDet;
}
float2 GetCircumcenter ()
{
// From MathWorld: http://mathworld.wolfram.com/Circumcircle.html
var points = Vertices;
float[,] m = new float[3, 3];
// x, y, 1
for (int i = 0; i < 3; i++) {
m[i, 0] = points[i].x;
m[i, 1] = points[i].y;
m[i, 2] = 1;
}
var a = Determinant(m);
// size, y, 1
for (int i = 0; i < 3; i++) {
m[i, 0] = lengthsq(points[i].StoredPosition);
}
var dx = -Determinant(m);
// size, x, 1
for (int i = 0; i < 3; i++) {
m[i, 1] = points[i].x;
}
var dy = Determinant(m);
// size, x, y
//for (int i = 0; i < 3; i++) {
// m[i, 2] = points[i].y;
//}
//var c = -Det(m);
var s = -1.0f / (2.0f * a);
//var r = System.Math.Abs(s) * System.Math.Sqrt(dx * dx + dy * dy - 4 * a * c);
return new float2(s * dx, s * dy);
}
float2 GetCentroid ()
{
return new float2(Vertices.Select(v => v.Position[0]).Average(), Vertices.Select(v => v.Position[1]).Average());
}
}

View file

@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: ea854ab9e5204f92828e92ffb1244964
timeCreated: 1615420193

View file

@ -1,46 +0,0 @@
/******************************************************************************
*
* The MIT License (MIT)
*
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*****************************************************************************/
using System;
namespace MIConvexHull
{
internal static class Constants
{
/// <summary>
/// The default plane distance tolerance
/// </summary>
internal const float DefaultPlaneDistanceTolerance = 1e-10f;
/// <summary>
/// The starting delta dot product in simplex
/// </summary>
internal const float StartingDeltaDotProductInSimplex = 0.5f;
/// <summary>
/// The connector table size
/// </summary>
internal const int ConnectorTableSize = 2017;
}
}

View file

@ -1,135 +0,0 @@
/******************************************************************************
*
* The MIT License (MIT)
*
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*****************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
namespace MIConvexHull
{
/// <summary>
/// Factory class for computing convex hulls.
/// </summary>
public static class ConvexHull
{
/// <summary>
/// Creates a convex hull of the input data.
/// </summary>
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
/// <typeparam name="TFace">The type of the t face.</typeparam>
/// <param name="data">The data.</param>
/// <param name="PlaneDistanceTolerance">The plane distance tolerance (default is 1e-10). If too high, points
/// will be missed. If too low, the algorithm may break. Only adjust if you notice problems.</param>
/// <returns>
/// ConvexHull&lt;TVertex, TFace&gt;.
/// </returns>
public static ConvexHull<TVertex, TFace> Create<TVertex, TFace>(IList<TVertex> data,
float PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
where TVertex : IVertex
where TFace : ConvexFace<TVertex, TFace>, new()
{
return ConvexHull<TVertex, TFace>.Create(data, PlaneDistanceTolerance);
}
/// <summary>
/// Creates a convex hull of the input data.
/// </summary>
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
/// <param name="data">The data.</param>
/// <param name="PlaneDistanceTolerance">The plane distance tolerance (default is 1e-10). If too high, points
/// will be missed. If too low, the algorithm may break. Only adjust if you notice problems.</param>
/// <returns>
/// ConvexHull&lt;TVertex, DefaultConvexFace&lt;TVertex&gt;&gt;.
/// </returns>
public static ConvexHull<TVertex, DefaultConvexFace<TVertex>> Create<TVertex>(IList<TVertex> data,
float PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
where TVertex : IVertex
{
return ConvexHull<TVertex, DefaultConvexFace<TVertex>>.Create(data, PlaneDistanceTolerance);
}
/// <summary>
/// Creates a convex hull of the input data.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="PlaneDistanceTolerance">The plane distance tolerance (default is 1e-10). If too high, points
/// will be missed. If too low, the algorithm may break. Only adjust if you notice problems.</param>
/// <returns>
/// ConvexHull&lt;DefaultVertex, DefaultConvexFace&lt;DefaultVertex&gt;&gt;.
/// </returns>
public static ConvexHull<DefaultVertex, DefaultConvexFace<DefaultVertex>> Create(IList<float[]> data,
float PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
{
var points = data.Select(p => new DefaultVertex { Position = p }).ToList();
return ConvexHull<DefaultVertex, DefaultConvexFace<DefaultVertex>>.Create(points, PlaneDistanceTolerance);
}
}
/// <summary>
/// Representation of a convex hull.
/// </summary>
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
/// <typeparam name="TFace">The type of the t face.</typeparam>
public class ConvexHull<TVertex, TFace>
where TVertex : IVertex
where TFace : ConvexFace<TVertex, TFace>, new()
{
/// <summary>
/// Can only be created using a factory method.
/// </summary>
internal ConvexHull()
{
}
/// <summary>
/// Points of the convex hull.
/// </summary>
/// <value>The points.</value>
public IEnumerable<TVertex> Points { get; internal set; }
/// <summary>
/// Faces of the convex hull.
/// </summary>
/// <value>The faces.</value>
public IEnumerable<TFace> Faces { get; internal set; }
/// <summary>
/// Creates the convex hull.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="PlaneDistanceTolerance">The plane distance tolerance.</param>
/// <returns>
/// ConvexHull&lt;TVertex, TFace&gt;.
/// </returns>
/// <exception cref="System.ArgumentNullException">The supplied data is null.</exception>
/// <exception cref="ArgumentNullException">data</exception>
public static ConvexHull<TVertex, TFace> Create(IList<TVertex> data, float PlaneDistanceTolerance)
{
if (data == null) throw new ArgumentNullException("The supplied data is null.");
return ConvexHullAlgorithm.GetConvexHull<TVertex, TFace>(data, PlaneDistanceTolerance);
}
}
}

View file

@ -1,304 +0,0 @@
/******************************************************************************
*
* The MIT License (MIT)
*
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*****************************************************************************/
using System;
namespace MIConvexHull
{
/// <summary>
/// A more lightweight alternative to List of T.
/// On clear, only resets the count and does not clear the references
/// =&gt; this works because of the ObjectManager.
/// Includes a stack functionality.
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SimpleList<T>
{
/// <summary>
/// The capacity
/// </summary>
private int capacity;
/// <summary>
/// The count
/// </summary>
public int Count;
/// <summary>
/// The items
/// </summary>
private T[] items;
/// <summary>
/// Get the i-th element.
/// </summary>
/// <param name="i">The i.</param>
/// <returns>T.</returns>
public T this[int i]
{
get { return items[i]; }
set { items[i] = value; }
}
/// <summary>
/// Size matters.
/// </summary>
private void EnsureCapacity()
{
if (capacity == 0)
{
capacity = 32;
items = new T[32];
}
else
{
var newItems = new T[capacity*2];
Array.Copy(items, newItems, capacity);
capacity = 2*capacity;
items = newItems;
}
}
/// <summary>
/// Adds a vertex to the buffer.
/// </summary>
/// <param name="item">The item.</param>
public void Add(T item)
{
if (Count + 1 > capacity) EnsureCapacity();
items[Count++] = item;
}
/// <summary>
/// Pushes the value to the back of the list.
/// </summary>
/// <param name="item">The item.</param>
public void Push(T item)
{
if (Count + 1 > capacity) EnsureCapacity();
items[Count++] = item;
}
/// <summary>
/// Pops the last value from the list.
/// </summary>
/// <returns>T.</returns>
public T Pop()
{
return items[--Count];
}
/// <summary>
/// Sets the Count to 0, otherwise does nothing.
/// </summary>
public void Clear()
{
Count = 0;
}
}
/// <summary>
/// Class IndexBuffer.
/// A fancy name for a list of integers.
/// </summary>
internal class IndexBuffer : SimpleList<int>
{
}
/// <summary>
/// A priority based linked list.
/// </summary>
internal sealed class FaceList
{
/// <summary>
/// The last
/// </summary>
private ConvexFaceInternal last;
/// <summary>
/// Get the first element.
/// </summary>
/// <value>The first.</value>
public ConvexFaceInternal First { get; private set; }
/// <summary>
/// Adds the element to the beginning.
/// </summary>
/// <param name="face">The face.</param>
private void AddFirst(ConvexFaceInternal face)
{
face.InList = true;
First.Previous = face;
face.Next = First;
First = face;
}
/// <summary>
/// Adds a face to the list.
/// </summary>
/// <param name="face">The face.</param>
public void Add(ConvexFaceInternal face)
{
if (face.InList)
{
if (First.VerticesBeyond.Count < face.VerticesBeyond.Count)
{
Remove(face);
AddFirst(face);
}
return;
}
face.InList = true;
if (First != null && First.VerticesBeyond.Count < face.VerticesBeyond.Count)
{
First.Previous = face;
face.Next = First;
First = face;
}
else
{
if (last != null)
{
last.Next = face;
}
face.Previous = last;
last = face;
if (First == null)
{
First = face;
}
}
}
/// <summary>
/// Removes the element from the list.
/// </summary>
/// <param name="face">The face.</param>
public void Remove(ConvexFaceInternal face)
{
if (!face.InList) return;
face.InList = false;
if (face.Previous != null)
{
face.Previous.Next = face.Next;
}
else if ( /*first == face*/ face.Previous == null)
{
First = face.Next;
}
if (face.Next != null)
{
face.Next.Previous = face.Previous;
}
else if ( /*last == face*/ face.Next == null)
{
last = face.Previous;
}
face.Next = null;
face.Previous = null;
}
}
/// <summary>
/// Connector list.
/// </summary>
internal sealed class ConnectorList
{
/// <summary>
/// The last
/// </summary>
private FaceConnector last;
/// <summary>
/// Get the first element.
/// </summary>
/// <value>The first.</value>
public FaceConnector First { get; private set; }
/// <summary>
/// Adds the element to the beginning.
/// </summary>
/// <param name="connector">The connector.</param>
private void AddFirst(FaceConnector connector)
{
First.Previous = connector;
connector.Next = First;
First = connector;
}
/// <summary>
/// Adds a face to the list.
/// </summary>
/// <param name="element">The element.</param>
public void Add(FaceConnector element)
{
if (last != null)
{
last.Next = element;
}
element.Previous = last;
last = element;
if (First == null)
{
First = element;
}
}
/// <summary>
/// Removes the element from the list.
/// </summary>
/// <param name="connector">The connector.</param>
public void Remove(FaceConnector connector)
{
if (connector.Previous != null)
{
connector.Previous.Next = connector.Next;
}
else if ( /*first == face*/ connector.Previous == null)
{
First = connector.Next;
}
if (connector.Next != null)
{
connector.Next.Previous = connector.Previous;
}
else if ( /*last == face*/ connector.Next == null)
{
last = connector.Previous;
}
connector.Next = null;
connector.Previous = null;
}
}
}

View file

@ -1,69 +0,0 @@
/******************************************************************************
*
* The MIT License (MIT)
*
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*****************************************************************************/
namespace MIConvexHull
{
/// <summary>
/// A convex face representation containing adjacency information.
/// </summary>
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
/// <typeparam name="TFace">The type of the t face.</typeparam>
public abstract class ConvexFace<TVertex, TFace>
where TVertex : IVertex
where TFace : ConvexFace<TVertex, TFace>
{
/// <summary>
/// Adjacency. Array of length "dimension".
/// If F = Adjacency[i] then the vertices shared with F are Vertices[j] where j != i.
/// In the context of triangulation, can be null (indicates the cell is at boundary).
/// </summary>
/// <value>The adjacency.</value>
public TFace[] Adjacency { get; set; }
/// <summary>
/// The vertices stored in clockwise order for dimensions 2 - 4, in higher dimensions the order is arbitrary.
/// Unless I accidentally switch some index somewhere in which case the order is CCW. Either way, it is consistent.
/// 3D Normal = (V[1] - V[0]) x (V[2] - V[1]).
/// </summary>
/// <value>The vertices.</value>
public TVertex[] Vertices { get; set; }
/// <summary>
/// The normal vector of the face. Null if used in triangulation.
/// </summary>
/// <value>The normal.</value>
public float[] Normal { get; set; }
}
/// <summary>
/// A default convex face representation.
/// </summary>
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
public class DefaultConvexFace<TVertex> : ConvexFace<TVertex, DefaultConvexFace<TVertex>>
where TVertex : IVertex
{
}
}

View file

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 5db1a96860ec6d949930695ae9bedcc0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,721 +0,0 @@
/******************************************************************************
*
* The MIT License (MIT)
*
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*****************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
namespace MIConvexHull
{
/*
* This part of the implementation handles initialization of the convex hull algorithm:
* - Constructor & Process initiation
* - Determine the dimension by looking at length of Position vector of 10 random data points from the input.
* - Identify bounding box points in each direction.
* - Pick (Dimension + 1) points from the extremes and construct the initial simplex.
*/
/// <summary>
/// Class ConvexHullAlgorithm.
/// </summary>
internal partial class ConvexHullAlgorithm
{
#region Starting functions and constructor
/// <summary>
/// The main function for the Convex Hull algorithm. It is static, but it creates
/// an instantiation of this class in order to allow for parallel execution.
/// Following this simple function, the constructor and the main function "FindConvexHull" is listed.
/// </summary>
/// <typeparam name="TVertex">The type of the vertices in the data.</typeparam>
/// <typeparam name="TFace">The desired type of the faces.</typeparam>
/// <param name="data">The data is the vertices as a collection of IVertices.</param>
/// <param name="PlaneDistanceTolerance">The plane distance tolerance.</param>
/// <returns>
/// MIConvexHull.ConvexHull&lt;TVertex, TFace&gt;.
/// </returns>
internal static ConvexHull<TVertex, TFace> GetConvexHull<TVertex, TFace>(IList<TVertex> data,
float PlaneDistanceTolerance)
where TFace : ConvexFace<TVertex, TFace>, new()
where TVertex : IVertex
{
var ch = new ConvexHullAlgorithm(data.Cast<IVertex>().ToArray(), false, PlaneDistanceTolerance);
ch.GetConvexHull();
if (ch.NumOfDimensions == 2) return ch.Return2DResultInOrder<TVertex, TFace>(data);
return new ConvexHull<TVertex, TFace>
{
Points = ch.GetHullVertices(data),
Faces = ch.GetConvexFaces<TVertex, TFace>()
};
}
/// <summary>
/// Initializes a new instance of the <see cref="ConvexHullAlgorithm" /> class.
/// </summary>
/// <param name="vertices">The vertices.</param>
/// <param name="lift">if set to <c>true</c> [lift].</param>
/// <param name="PlaneDistanceTolerance">The plane distance tolerance.</param>
/// <exception cref="System.InvalidOperationException">Dimension of the input must be 2 or greater.</exception>
/// <exception cref="System.ArgumentException">There are too few vertices (m) for the n-dimensional space. (m must be greater +
/// than the n, but m is + NumberOfVertices + and n is + NumOfDimensions</exception>
/// <exception cref="InvalidOperationException">PointTranslationGenerator cannot be null if PointTranslationType is enabled.
/// or
/// Dimension of the input must be 2 or greater.</exception>
/// <exception cref="ArgumentException">There are too few vertices (m) for the n-dimensional space. (m must be greater " +
/// "than the n, but m is " + NumberOfVertices + " and n is " + Dimension</exception>
private ConvexHullAlgorithm(IVertex[] vertices, bool lift, float PlaneDistanceTolerance)
{
IsLifted = lift;
Vertices = vertices;
NumberOfVertices = vertices.Length;
NumOfDimensions = DetermineDimension();
if (IsLifted) NumOfDimensions++;
if (NumOfDimensions < 2) throw new InvalidOperationException("Dimension of the input must be 2 or greater.");
if (NumberOfVertices <= NumOfDimensions)
throw new ArgumentException(
"There are too few vertices (m) for the n-dimensional space. (m must be greater " +
"than the n, but m is " + NumberOfVertices + " and n is " + NumOfDimensions);
this.PlaneDistanceTolerance = PlaneDistanceTolerance;
UnprocessedFaces = new FaceList();
ConvexFaces = new IndexBuffer();
FacePool = new ConvexFaceInternal[(NumOfDimensions + 1) * 10]; // must be initialized before object manager
AffectedFaceFlags = new bool[(NumOfDimensions + 1) * 10];
ObjectManager = new ObjectManager(this);
Center = new float[NumOfDimensions];
TraverseStack = new IndexBuffer();
UpdateBuffer = new int[NumOfDimensions];
UpdateIndices = new int[NumOfDimensions];
EmptyBuffer = new IndexBuffer();
AffectedFaceBuffer = new IndexBuffer();
ConeFaceBuffer = new SimpleList<DeferredFace>();
SingularVertices = new HashSet<int>();
BeyondBuffer = new IndexBuffer();
ConnectorTable = new ConnectorList[Constants.ConnectorTableSize];
for (var i = 0; i < Constants.ConnectorTableSize; i++) ConnectorTable[i] = new ConnectorList();
VertexVisited = new bool[NumberOfVertices];
Positions = new float[NumberOfVertices * NumOfDimensions];
boundingBoxPoints = new List<int>[NumOfDimensions];
minima = new float[NumOfDimensions];
maxima = new float[NumOfDimensions];
mathHelper = new MathHelper(NumOfDimensions, Positions);
}
/// <summary>
/// Check the dimensionality of the input data.
/// </summary>
/// <returns>System.Int32.</returns>
/// <exception cref="ArgumentException">Invalid input data (non-uniform dimension).</exception>
private int DetermineDimension()
{
var r = new Random();
var dimensions = new List<int>();
for (var i = 0; i < 10; i++)
dimensions.Add(Vertices[r.Next(NumberOfVertices)].Position.Length);
var dimension = dimensions.Min();
if (dimension != dimensions.Max())
throw new ArgumentException("Invalid input data (non-uniform dimension).");
return dimension;
}
/// <summary>
/// Gets/calculates the convex hull. This is
/// </summary>
private void GetConvexHull()
{
// accessing a 1D array is quicker than a jagged array, so the first step is to make this array
SerializeVerticesToPositions();
// next the bounding box extremes are found. This is used to shift, scale and find the starting simplex.
FindBoundingBoxPoints();
// the positions are shifted to avoid divide by zero problems
// and if Delaunay or Voronoi, then the parabola terms are scaled back to match the size of the other coords
ShiftAndScalePositions();
// Find the (dimension+1) initial points and create the simplexes.
CreateInitialSimplex();
// Now, the main loop. These initial faces of a simplex are replaced and expanded
// outwards to make the convex hull and faces.
while (UnprocessedFaces.First != null)
{
var currentFace = UnprocessedFaces.First;
CurrentVertex = currentFace.FurthestVertex;
UpdateCenter();
// The affected faces get tagged
TagAffectedFaces(currentFace);
// Create the cone from the currentVertex and the affected faces horizon.
if (!SingularVertices.Contains(CurrentVertex) && CreateCone()) CommitCone();
else HandleSingular();
// Need to reset the tags
var count = AffectedFaceBuffer.Count;
for (var i = 0; i < count; i++) AffectedFaceFlags[AffectedFaceBuffer[i]] = false;
}
}
#endregion
/// <summary>
/// Serializes the vertices into the 1D array, Positions. The 1D array has much quicker access in C#.
/// </summary>
private void SerializeVerticesToPositions()
{
var index = 0;
if (IsLifted) // "Lifted" means that the last dimension is the sum of the squares of the others.
{
foreach (var v in Vertices)
{
var parabolaTerm = 0.0f; // the lifted term is a sum of squares.
var origNumDim = NumOfDimensions - 1;
for (var i = 0; i < origNumDim; i++)
{
var coordinate = v.Position[i];
Positions[index++] = coordinate;
parabolaTerm += coordinate * coordinate;
}
Positions[index++] = parabolaTerm;
}
}
else
foreach (var v in Vertices)
{
for (var i = 0; i < NumOfDimensions; i++)
Positions[index++] = v.Position[i];
}
}
/// <summary>
/// Finds the bounding box points.
/// </summary>
private void FindBoundingBoxPoints()
{
indexOfDimensionWithLeastExtremes = -1;
var minNumExtremes = int.MaxValue;
for (var i = 0; i < NumOfDimensions; i++)
{
var minIndices = new List<int>();
var maxIndices = new List<int>();
float min = float.PositiveInfinity, max = float.NegativeInfinity;
for (var j = 0; j < NumberOfVertices; j++)
{
var v = GetCoordinate(j, i);
var difference = min - v;
if (difference >= PlaneDistanceTolerance)
{
// you found a better solution than before, clear out the list and store new value
min = v;
minIndices.Clear();
minIndices.Add(j);
}
else if (difference > 0)
{
// you found a solution slightly better than before, clear out those that are no longer on the list and store new value
min = v;
minIndices.RemoveAll(index => min - GetCoordinate(index, i) > PlaneDistanceTolerance);
minIndices.Add(j);
}
else if (difference > -PlaneDistanceTolerance)
{
//same or almost as good as current limit, so store it
minIndices.Add(j);
}
difference = v - max;
if (difference >= PlaneDistanceTolerance)
{
// you found a better solution than before, clear out the list and store new value
max = v;
maxIndices.Clear();
maxIndices.Add(j);
}
else if (difference > 0)
{
// you found a solution slightly better than before, clear out those that are no longer on the list and store new value
max = v;
maxIndices.RemoveAll(index => min - GetCoordinate(index, i) > PlaneDistanceTolerance);
maxIndices.Add(j);
}
else if (difference > -PlaneDistanceTolerance)
{
//same or almost as good as current limit, so store it
maxIndices.Add(j);
}
}
minima[i] = min;
maxima[i] = max;
minIndices.AddRange(maxIndices);
if (minIndices.Count < minNumExtremes)
{
minNumExtremes = minIndices.Count;
indexOfDimensionWithLeastExtremes = i;
}
boundingBoxPoints[i] = minIndices;
}
}
/// <summary>
/// Shifts and scales the Positions to avoid future errors. This does not alter the original data.
/// </summary>
private void ShiftAndScalePositions()
{
var positionsLength = Positions.Length;
if (IsLifted)
{
var origNumDim = NumOfDimensions - 1;
var parabolaScale = 2 / (minima.Sum(x => Math.Abs(x)) + maxima.Sum(x => Math.Abs(x))
- Math.Abs(maxima[origNumDim]) - Math.Abs(minima[origNumDim]));
// the parabola scale is 1 / average of the sum of the other dimensions.
// multiplying this by the parabola will scale it back to be on near similar size to the
// other dimensions. Without this, the term is much larger than the others, which causes
// problems for roundoff error and finding the normal of faces.
minima[origNumDim] *= parabolaScale; // change the extreme values as well
maxima[origNumDim] *= parabolaScale;
// it is done here because
for (int i = origNumDim; i < positionsLength; i += NumOfDimensions)
Positions[i] *= parabolaScale;
}
var shiftAmount = new float[NumOfDimensions];
for (int i = 0; i < NumOfDimensions; i++)
// now the entire model is shifted to all positive numbers...plus some more.
// why?
// 1) to avoid dealing with a point at the origin {0,0,...,0} which causes problems
// for future normal finding
// 2) note that weird shift that is used (max - min - min). This is to avoid scaling
// issues. this shift means that the minima in a dimension will always be a positive
// number (no points at zero), and the minima [in a given dimension] will always be
// half of the maxima. 'Half' is much preferred to 'thousands of times'
// Think of the first term as the range (max - min), then the second term avoids cases
// where there are both positive and negative numbers.
if (maxima[i] == minima[i]) shiftAmount[i] = 0.0f;
else shiftAmount[i] = (maxima[i] - minima[i]) - minima[i];
for (int i = 0; i < positionsLength; i++)
Positions[i] += shiftAmount[i % NumOfDimensions];
}
/// <summary>
/// Find the (dimension+1) initial points and create the simplexes.
/// Creates the initial simplex of n+1 vertices by using points from the bounding box.
/// Special care is taken to ensure that the vertices chosen do not result in a degenerate shape
/// where vertices are collinear (co-planar, etc). This would technically be resolved when additional
/// vertices are checked in the main loop, but: 1) a degenerate simplex would not eliminate any other
/// vertices (thus no savings there), 2) the creation of the face normal is prone to error.
/// </summary>
private void CreateInitialSimplex()
{
var initialPoints = FindInitialPoints();
#region Create the first faces from (dimension + 1) vertices.
var faces = new int[NumOfDimensions + 1];
for (var i = 0; i < NumOfDimensions + 1; i++)
{
var vertices = new int[NumOfDimensions];
for (int j = 0, k = 0; j <= NumOfDimensions; j++)
{
if (i != j) vertices[k++] = initialPoints[j];
}
var newFace = FacePool[ObjectManager.GetFace()];
newFace.Vertices = vertices;
Array.Sort(vertices);
mathHelper.CalculateFacePlane(newFace, Center);
faces[i] = newFace.Index;
}
// update the adjacency (check all pairs of faces)
for (var i = 0; i < NumOfDimensions; i++)
for (var j = i + 1; j < NumOfDimensions + 1; j++) UpdateAdjacency(FacePool[faces[i]], FacePool[faces[j]]);
#endregion
#region Init the vertex beyond buffers.
foreach (var faceIndex in faces)
{
var face = FacePool[faceIndex];
FindBeyondVertices(face);
if (face.VerticesBeyond.Count == 0) ConvexFaces.Add(face.Index); // The face is on the hull
else UnprocessedFaces.Add(face);
}
#endregion
// Set all vertices to false (unvisited).
foreach (var vertex in initialPoints) VertexVisited[vertex] = false;
}
/// <summary>
/// Finds (dimension + 1) initial points.
/// </summary>
/// <returns>List&lt;System.Int32&gt;.</returns>
/// <exception cref="System.ArgumentException">The input data is degenerate. It appears to exist in " + NumOfDimensions +
/// " dimensions, but it is a " + (NumOfDimensions - 1) + " dimensional set (i.e. the point of collinear,"
/// + " coplanar, or co-hyperplanar.)</exception>
private List<int> FindInitialPoints()
{
var bigNumber = maxima.Sum() * NumOfDimensions * NumberOfVertices;
// the first two points are taken from the dimension that had the fewest extremes
// well, in most cases there will only be 2 in all dimensions: one min and one max
// but a lot of engineering part shapes are nice and square and can have hundreds of
// parallel vertices at the extremes
var vertex1 = boundingBoxPoints[indexOfDimensionWithLeastExtremes].First(); // these are min and max vertices along
var vertex2 = boundingBoxPoints[indexOfDimensionWithLeastExtremes].Last(); // the dimension that had the fewest points
boundingBoxPoints[indexOfDimensionWithLeastExtremes].RemoveAt(0);
boundingBoxPoints[indexOfDimensionWithLeastExtremes].RemoveAt(boundingBoxPoints[indexOfDimensionWithLeastExtremes].Count - 1);
var initialPoints = new List<int> { vertex1, vertex2 };
VertexVisited[vertex1] = VertexVisited[vertex2] = true;
CurrentVertex = vertex1; UpdateCenter();
CurrentVertex = vertex2; UpdateCenter();
var edgeVectors = new float[NumOfDimensions][];
edgeVectors[0] = mathHelper.VectorBetweenVertices(vertex2, vertex1);
// now the remaining vertices are just combined in one big list
var extremes = boundingBoxPoints.SelectMany(x => x).ToList();
// otherwise find the remaining points by maximizing the initial simplex volume
var index = 1;
while (index < NumOfDimensions && extremes.Any())
{
var bestVertex = -1;
var bestEdgeVector = new float[] { };
var maxVolume = Constants.DefaultPlaneDistanceTolerance;
for (var i = extremes.Count - 1; i >= 0; i--)
{
// count backwards in order to remove potential duplicates
var vIndex = extremes[i];
if (initialPoints.Contains(vIndex)) extremes.RemoveAt(i);
else
{
edgeVectors[index] = mathHelper.VectorBetweenVertices(vIndex, vertex1);
var volume = mathHelper.GetSimplexVolume(edgeVectors, index, bigNumber);
if (maxVolume < volume)
{
maxVolume = volume;
bestVertex = vIndex;
bestEdgeVector = edgeVectors[index];
}
}
}
extremes.Remove(bestVertex);
if (bestVertex == -1) break;
initialPoints.Add(bestVertex);
edgeVectors[index++] = bestEdgeVector;
CurrentVertex = bestVertex; UpdateCenter();
}
// hmm, there are not enough points on the bounding box to make a simplex. It is rare but entirely possibly.
// As an extreme, the bounding box can be made in n dimensions from only 2 unique points. When we can't find
// enough unique points, we start again with ALL the vertices. The following is a near replica of the code
// above, but instead of extremes, we consider "allVertices".
if (initialPoints.Count <= NumOfDimensions && !IsLifted)
{
var allVertices = Enumerable.Range(0, NumberOfVertices).ToList();
while (index < NumOfDimensions && allVertices.Any())
{
var bestVertex = -1;
var bestEdgeVector = new float[] { };
var maxVolume = 0.0;
for (var i = allVertices.Count - 1; i >= 0; i--)
{
// count backwards in order to remove potential duplicates
var vIndex = allVertices[i];
if (initialPoints.Contains(vIndex)) allVertices.RemoveAt(i);
else
{
edgeVectors[index] = mathHelper.VectorBetweenVertices(vIndex, vertex1);
var volume = mathHelper.GetSimplexVolume(edgeVectors, index, bigNumber);
if (maxVolume < volume)
{
maxVolume = volume;
bestVertex = vIndex;
bestEdgeVector = edgeVectors[index];
}
}
}
allVertices.Remove(bestVertex);
if (bestVertex == -1) break;
initialPoints.Add(bestVertex);
edgeVectors[index++] = bestEdgeVector;
CurrentVertex = bestVertex; UpdateCenter();
}
}
if (initialPoints.Count <= NumOfDimensions && IsLifted)
{
var allVertices = Enumerable.Range(0, NumberOfVertices).ToList();
while (index < NumOfDimensions && allVertices.Any())
{
var bestVertex = -1;
var bestEdgeVector = new float[] { };
var maxVolume = 0.0;
for (var i = allVertices.Count - 1; i >= 0; i--)
{
// count backwards in order to remove potential duplicates
var vIndex = allVertices[i];
if (initialPoints.Contains(vIndex)) allVertices.RemoveAt(i);
else
{
mathHelper.RandomOffsetToLift(vIndex, maxima.Last()-minima.Last());
edgeVectors[index] = mathHelper.VectorBetweenVertices(vIndex, vertex1);
var volume = mathHelper.GetSimplexVolume(edgeVectors, index, bigNumber);
if (maxVolume < volume)
{
maxVolume = volume;
bestVertex = vIndex;
bestEdgeVector = edgeVectors[index];
}
}
}
allVertices.Remove(bestVertex);
if (bestVertex == -1) break;
initialPoints.Add(bestVertex);
edgeVectors[index++] = bestEdgeVector;
CurrentVertex = bestVertex; UpdateCenter();
}
}
if (initialPoints.Count <= NumOfDimensions && IsLifted)
throw new ArgumentException("The input data is degenerate. It appears to exist in " + NumOfDimensions +
" dimensions, but it is a " + (NumOfDimensions - 1) + " dimensional set (i.e. the point of collinear,"
+ " coplanar, or co-hyperplanar.)");
return initialPoints;
}
/// <summary>
/// Check if 2 faces are adjacent and if so, update their AdjacentFaces array.
/// </summary>
/// <param name="l">The l.</param>
/// <param name="r">The r.</param>
private void UpdateAdjacency(ConvexFaceInternal l, ConvexFaceInternal r)
{
var lv = l.Vertices;
var rv = r.Vertices;
int i;
// reset marks on the 1st face
for (i = 0; i < lv.Length; i++) VertexVisited[lv[i]] = false;
// mark all vertices on the 2nd face
for (i = 0; i < rv.Length; i++) VertexVisited[rv[i]] = true;
// find the 1st false index
for (i = 0; i < lv.Length; i++) if (!VertexVisited[lv[i]]) break;
// no vertex was marked
if (i == NumOfDimensions) return;
// check if only 1 vertex wasn't marked
for (var j = i + 1; j < lv.Length; j++) if (!VertexVisited[lv[j]]) return;
// if we are here, the two faces share an edge
l.AdjacentFaces[i] = r.Index;
// update the adj. face on the other face - find the vertex that remains marked
for (i = 0; i < lv.Length; i++) VertexVisited[lv[i]] = false;
for (i = 0; i < rv.Length; i++)
{
if (VertexVisited[rv[i]]) break;
}
r.AdjacentFaces[i] = l.Index;
}
/// <summary>
/// Used in the "initialization" code.
/// </summary>
/// <param name="face">The face.</param>
private void FindBeyondVertices(ConvexFaceInternal face)
{
var beyondVertices = face.VerticesBeyond;
MaxDistance = float.NegativeInfinity;
FurthestVertex = 0;
for (var i = 0; i < NumberOfVertices; i++)
{
if (VertexVisited[i]) continue;
IsBeyond(face, beyondVertices, i);
}
face.FurthestVertex = FurthestVertex;
}
#region Fields
/// <summary>
/// Corresponds to the dimension of the data.
/// When the "lifted" hull is computed, Dimension is automatically incremented by one.
/// </summary>
internal readonly int NumOfDimensions;
/// <summary>
/// Are we on a paraboloid?
/// </summary>
private readonly bool IsLifted;
/// <summary>
/// Explained in ConvexHullComputationConfig.
/// </summary>
private readonly float PlaneDistanceTolerance;
/*
* Representation of the input vertices.
*
* - In the algorithm, a vertex is represented by its index in the Vertices array.
* This makes the algorithm a lot faster (up to 30%) than using object reference everywhere.
* - Positions are stored as a single array of values. Coordinates for vertex with index i
* are stored at indices <i * Dimension, (i + 1) * Dimension)
* - VertexMarks are used by the algorithm to help identify a set of vertices that is "above" (or "beyond")
* a specific face.
*/
/// <summary>
/// The vertices
/// </summary>
private readonly IVertex[] Vertices;
/// <summary>
/// The positions
/// </summary>
private float[] Positions;
/// <summary>
/// The vertex marks
/// </summary>
private readonly bool[] VertexVisited;
private readonly int NumberOfVertices;
/*
* The triangulation faces are represented in a single pool for objects that are being reused.
* This allows for represent the faces as integers and significantly speeds up many computations.
* - AffectedFaceFlags are used to mark affected faces/
*/
/// <summary>
/// The face pool
/// </summary>
internal ConvexFaceInternal[] FacePool;
/// <summary>
/// The affected face flags
/// </summary>
internal bool[] AffectedFaceFlags;
/// <summary>
/// Used to track the size of the current hull in the Update/RollbackCenter functions.
/// </summary>
private int ConvexHullSize;
/// <summary>
/// A list of faces that that are not a part of the final convex hull and still need to be processed.
/// </summary>
private readonly FaceList UnprocessedFaces;
/// <summary>
/// A list of faces that form the convex hull.
/// </summary>
private readonly IndexBuffer ConvexFaces;
/// <summary>
/// The vertex that is currently being processed.
/// </summary>
private int CurrentVertex;
/// <summary>
/// A helper variable to determine the furthest vertex for a particular convex face.
/// </summary>
private double MaxDistance;
/// <summary>
/// A helper variable to help determine the index of the vertex that is furthest from the face that is currently being
/// processed.
/// </summary>
private int FurthestVertex;
/// <summary>
/// The centroid of the currently computed hull.
/// </summary>
private readonly float[] Center;
/*
* Helper arrays to store faces for adjacency update.
* This is just to prevent unnecessary allocations.
*/
/// <summary>
/// The update buffer
/// </summary>
private readonly int[] UpdateBuffer;
/// <summary>
/// The update indices
/// </summary>
private readonly int[] UpdateIndices;
/// <summary>
/// Used to determine which faces need to be updated at each step of the algorithm.
/// </summary>
private readonly IndexBuffer TraverseStack;
/// <summary>
/// Used for VerticesBeyond for faces that are on the convex hull.
/// </summary>
private readonly IndexBuffer EmptyBuffer;
/// <summary>
/// Used to determine which vertices are "above" (or "beyond") a face
/// </summary>
private IndexBuffer BeyondBuffer;
/// <summary>
/// Stores faces that are visible from the current vertex.
/// </summary>
private readonly IndexBuffer AffectedFaceBuffer;
/// <summary>
/// Stores faces that form a "cone" created by adding new vertex.
/// </summary>
private readonly SimpleList<DeferredFace> ConeFaceBuffer;
/// <summary>
/// Stores a list of "singular" (or "generate", "planar", etc.) vertices that cannot be part of the hull.
/// </summary>
private readonly HashSet<int> SingularVertices;
/// <summary>
/// The connector table helps to determine the adjacency of convex faces.
/// Hashing is used instead of pairwise comparison. This significantly speeds up the computations,
/// especially for higher dimensions.
/// </summary>
private readonly ConnectorList[] ConnectorTable;
/// <summary>
/// Manages the memory allocations and storage of unused objects.
/// Saves the garbage collector a lot of work.
/// </summary>
private readonly ObjectManager ObjectManager;
/// <summary>
/// Helper class for handling math related stuff.
/// </summary>
private readonly MathHelper mathHelper;
private readonly List<int>[] boundingBoxPoints;
private int indexOfDimensionWithLeastExtremes;
private readonly float[] minima;
private readonly float[] maxima;
#endregion
}
}

View file

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 48bd00cb6ec8d244f90e1c1608f39074
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,635 +0,0 @@
/******************************************************************************
*
* The MIT License (MIT)
*
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*****************************************************************************/
using System.Collections.Generic;
namespace MIConvexHull
{
/*
* Main part of the algorithm
* Basic idea:
* - Create the initial hull (done in Initialize.cs)
*
* For each face there are "vertices beyond" which are "visible" from it.
* If there are no such vertices, the face is on the hull.
*
* - While there is at least one face with at least one "vertex beyond":
* * Pick the furthest beyond vertex
* * For this vertex:
* > find all faces that are visible from it (TagAffectedFaces)
* > remove them and replace them with a "cone" created by the vertex and the boundary
* of the affected faces, and for each new face, compute "beyond vertices"
* (CreateCone + CommitCone)
*
* + Implement it in way that is fast, but hard to understand and maintain.
*/
/// <summary>
/// Class ConvexHullAlgorithm.
/// </summary>
internal partial class ConvexHullAlgorithm
{
/// <summary>
/// Tags all faces seen from the current vertex with 1.
/// </summary>
/// <param name="currentFace">The current face.</param>
private void TagAffectedFaces(ConvexFaceInternal currentFace)
{
AffectedFaceBuffer.Clear();
AffectedFaceBuffer.Add(currentFace.Index);
TraverseAffectedFaces(currentFace.Index);
}
/// <summary>
/// Recursively traverse all the relevant faces.
/// </summary>
/// <param name="currentFace">The current face.</param>
private void TraverseAffectedFaces(int currentFace)
{
TraverseStack.Clear();
TraverseStack.Push(currentFace);
AffectedFaceFlags[currentFace] = true;
while (TraverseStack.Count > 0)
{
var top = FacePool[TraverseStack.Pop()];
for (var i = 0; i < NumOfDimensions; i++)
{
var adjFace = top.AdjacentFaces[i];
if (!AffectedFaceFlags[adjFace] &&
mathHelper.GetVertexDistance(CurrentVertex, FacePool[adjFace]) >= PlaneDistanceTolerance)
{
AffectedFaceBuffer.Add(adjFace);
AffectedFaceFlags[adjFace] = true;
TraverseStack.Push(adjFace);
}
}
}
}
/// <summary>
/// Creates a new deferred face.
/// </summary>
/// <param name="face">The face.</param>
/// <param name="faceIndex">Index of the face.</param>
/// <param name="pivot">The pivot.</param>
/// <param name="pivotIndex">Index of the pivot.</param>
/// <param name="oldFace">The old face.</param>
/// <returns>DeferredFace.</returns>
private DeferredFace MakeDeferredFace(ConvexFaceInternal face, int faceIndex, ConvexFaceInternal pivot,
int pivotIndex, ConvexFaceInternal oldFace)
{
var ret = ObjectManager.GetDeferredFace();
ret.Face = face;
ret.FaceIndex = faceIndex;
ret.Pivot = pivot;
ret.PivotIndex = pivotIndex;
ret.OldFace = oldFace;
return ret;
}
/// <summary>
/// Connect faces using a connector.
/// </summary>
/// <param name="connector">The connector.</param>
private void ConnectFace(FaceConnector connector)
{
var index = connector.HashCode % Constants.ConnectorTableSize;
var list = ConnectorTable[index];
for (var current = list.First; current != null; current = current.Next)
{
if (FaceConnector.AreConnectable(connector, current, NumOfDimensions))
{
list.Remove(current);
FaceConnector.Connect(current, connector);
current.Face = null;
connector.Face = null;
ObjectManager.DepositConnector(current);
ObjectManager.DepositConnector(connector);
return;
}
}
list.Add(connector);
}
/// <summary>
/// Removes the faces "covered" by the current vertex and adds the newly created ones.
/// </summary>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
private bool CreateCone()
{
var currentVertexIndex = CurrentVertex;
ConeFaceBuffer.Clear();
for (var fIndex = 0; fIndex < AffectedFaceBuffer.Count; fIndex++)
{
var oldFaceIndex = AffectedFaceBuffer[fIndex];
var oldFace = FacePool[oldFaceIndex];
// Find the faces that need to be updated
var updateCount = 0;
for (var i = 0; i < NumOfDimensions; i++)
{
var af = oldFace.AdjacentFaces[i];
if (!AffectedFaceFlags[af]) // Tag == false when oldFaces does not contain af
{
UpdateBuffer[updateCount] = af;
UpdateIndices[updateCount] = i;
++updateCount;
}
}
for (var i = 0; i < updateCount; i++)
{
var adjacentFace = FacePool[UpdateBuffer[i]];
var oldFaceAdjacentIndex = 0;
var adjFaceAdjacency = adjacentFace.AdjacentFaces;
for (var j = 0; j < adjFaceAdjacency.Length; j++)
{
if (oldFaceIndex == adjFaceAdjacency[j])
{
oldFaceAdjacentIndex = j;
break;
}
}
var forbidden = UpdateIndices[i]; // Index of the face that corresponds to this adjacent face
int oldVertexIndex;
int[] vertices;
var newFaceIndex = ObjectManager.GetFace();
var newFace = FacePool[newFaceIndex];
vertices = newFace.Vertices;
for (var j = 0; j < NumOfDimensions; j++) vertices[j] = oldFace.Vertices[j];
oldVertexIndex = vertices[forbidden];
int orderedPivotIndex;
// correct the ordering
if (currentVertexIndex < oldVertexIndex)
{
orderedPivotIndex = 0;
for (var j = forbidden - 1; j >= 0; j--)
{
if (vertices[j] > currentVertexIndex) vertices[j + 1] = vertices[j];
else
{
orderedPivotIndex = j + 1;
break;
}
}
}
else
{
orderedPivotIndex = NumOfDimensions - 1;
for (var j = forbidden + 1; j < NumOfDimensions; j++)
{
if (vertices[j] < currentVertexIndex) vertices[j - 1] = vertices[j];
else
{
orderedPivotIndex = j - 1;
break;
}
}
}
vertices[orderedPivotIndex] = CurrentVertex;
if (!mathHelper.CalculateFacePlane(newFace, Center))
{
return false;
}
ConeFaceBuffer.Add(MakeDeferredFace(newFace, orderedPivotIndex, adjacentFace, oldFaceAdjacentIndex,
oldFace));
}
}
return true;
}
/// <summary>
/// Commits a cone and adds a vertex to the convex hull.
/// </summary>
private void CommitCone()
{
// Fill the adjacency.
for (var i = 0; i < ConeFaceBuffer.Count; i++)
{
var face = ConeFaceBuffer[i];
var newFace = face.Face;
var adjacentFace = face.Pivot;
var oldFace = face.OldFace;
var orderedPivotIndex = face.FaceIndex;
newFace.AdjacentFaces[orderedPivotIndex] = adjacentFace.Index;
adjacentFace.AdjacentFaces[face.PivotIndex] = newFace.Index;
// let there be a connection.
for (var j = 0; j < NumOfDimensions; j++)
{
if (j == orderedPivotIndex) continue;
var connector = ObjectManager.GetConnector();
connector.Update(newFace, j, NumOfDimensions);
ConnectFace(connector);
}
// the id adjacent face on the hull? If so, we can use simple method to find beyond vertices.
if (adjacentFace.VerticesBeyond.Count == 0)
FindBeyondVertices(newFace, oldFace.VerticesBeyond);
// it is slightly more effective if the face with the lower number of beyond vertices comes first.
else if (adjacentFace.VerticesBeyond.Count < oldFace.VerticesBeyond.Count)
FindBeyondVertices(newFace, adjacentFace.VerticesBeyond, oldFace.VerticesBeyond);
else
FindBeyondVertices(newFace, oldFace.VerticesBeyond, adjacentFace.VerticesBeyond);
// This face will definitely lie on the hull
if (newFace.VerticesBeyond.Count == 0)
{
ConvexFaces.Add(newFace.Index);
UnprocessedFaces.Remove(newFace);
ObjectManager.DepositVertexBuffer(newFace.VerticesBeyond);
newFace.VerticesBeyond = EmptyBuffer;
}
else // Add the face to the list
{
UnprocessedFaces.Add(newFace);
}
// recycle the object.
ObjectManager.DepositDeferredFace(face);
}
// Recycle the affected faces.
for (var fIndex = 0; fIndex < AffectedFaceBuffer.Count; fIndex++)
{
var face = AffectedFaceBuffer[fIndex];
UnprocessedFaces.Remove(FacePool[face]);
ObjectManager.DepositFace(face);
}
}
/// <summary>
/// Check whether the vertex v is beyond the given face. If so, add it to beyondVertices.
/// </summary>
/// <param name="face">The face.</param>
/// <param name="beyondVertices">The beyond vertices.</param>
/// <param name="v">The v.</param>
private void IsBeyond(ConvexFaceInternal face, IndexBuffer beyondVertices, int v)
{
var distance = mathHelper.GetVertexDistance(v, face);
if (distance >= PlaneDistanceTolerance)
{
if (distance > MaxDistance)
{
// If it's within the tolerance distance, use the lex. larger point
if (distance - MaxDistance < PlaneDistanceTolerance)
{ // todo: why is this LexCompare necessary. Would seem to favor x over y over z (etc.)?
if (LexCompare(v, FurthestVertex) > 0)
{
MaxDistance = distance;
FurthestVertex = v;
}
}
else
{
MaxDistance = distance;
FurthestVertex = v;
}
}
beyondVertices.Add(v);
}
}
/// <summary>
/// Compares the values of two vertices. The return value (-1, 0 or +1) are found
/// by first checking the first coordinate and then progressing through the rest.
/// In this way {2, 8} will be a "-1" (less than) {3, 1}.
/// </summary>
/// <param name="u">The base vertex index, u.</param>
/// <param name="v">The compared vertex index, v.</param>
/// <returns>System.Int32.</returns>
private int LexCompare(int u, int v)
{
int uOffset = u * NumOfDimensions, vOffset = v * NumOfDimensions;
for (var i = 0; i < NumOfDimensions; i++)
{
double x = Positions[uOffset + i], y = Positions[vOffset + i];
var comp = x.CompareTo(y);
if (comp != 0) return comp;
}
return 0;
}
/// <summary>
/// Used by update faces.
/// </summary>
/// <param name="face">The face.</param>
/// <param name="beyond">The beyond.</param>
/// <param name="beyond1">The beyond1.</param>
private void FindBeyondVertices(ConvexFaceInternal face, IndexBuffer beyond, IndexBuffer beyond1)
{
var beyondVertices = BeyondBuffer;
MaxDistance = double.NegativeInfinity;
FurthestVertex = 0;
int v;
for (var i = 0; i < beyond1.Count; i++) VertexVisited[beyond1[i]] = true;
VertexVisited[CurrentVertex] = false;
for (var i = 0; i < beyond.Count; i++)
{
v = beyond[i];
if (v == CurrentVertex) continue;
VertexVisited[v] = false;
IsBeyond(face, beyondVertices, v);
}
for (var i = 0; i < beyond1.Count; i++)
{
v = beyond1[i];
if (VertexVisited[v]) IsBeyond(face, beyondVertices, v);
}
face.FurthestVertex = FurthestVertex;
// Pull the old switch a roo (switch the face beyond buffers)
var temp = face.VerticesBeyond;
face.VerticesBeyond = beyondVertices;
if (temp.Count > 0) temp.Clear();
BeyondBuffer = temp;
}
/// <summary>
/// Finds the beyond vertices.
/// </summary>
/// <param name="face">The face.</param>
/// <param name="beyond">The beyond.</param>
private void FindBeyondVertices(ConvexFaceInternal face, IndexBuffer beyond)
{
var beyondVertices = BeyondBuffer;
MaxDistance = double.NegativeInfinity;
FurthestVertex = 0;
int v;
for (var i = 0; i < beyond.Count; i++)
{
v = beyond[i];
if (v == CurrentVertex) continue;
IsBeyond(face, beyondVertices, v);
}
face.FurthestVertex = FurthestVertex;
// Pull the old switch a roo (switch the face beyond buffers)
var temp = face.VerticesBeyond;
face.VerticesBeyond = beyondVertices;
if (temp.Count > 0) temp.Clear();
BeyondBuffer = temp;
}
/// <summary>
/// Recalculates the centroid of the current hull.
/// </summary>
private void UpdateCenter()
{
for (var i = 0; i < NumOfDimensions; i++) Center[i] *= ConvexHullSize;
ConvexHullSize += 1;
var f = 1.0f / ConvexHullSize;
var co = CurrentVertex * NumOfDimensions;
for (var i = 0; i < NumOfDimensions; i++) Center[i] = f * (Center[i] + Positions[co + i]);
}
/// <summary>
/// Removes the last vertex from the center.
/// </summary>
private void RollbackCenter()
{
for (var i = 0; i < NumOfDimensions; i++) Center[i] *= ConvexHullSize;
ConvexHullSize -= 1;
var f = ConvexHullSize > 0 ? 1.0f / ConvexHullSize : 0.0f;
var co = CurrentVertex * NumOfDimensions;
for (var i = 0; i < NumOfDimensions; i++) Center[i] = f * (Center[i] - Positions[co + i]);
}
/// <summary>
/// Handles singular vertex.
/// </summary>
private void HandleSingular()
{
RollbackCenter();
SingularVertices.Add(CurrentVertex);
// This means that all the affected faces must be on the hull and that all their "vertices beyond" are singular.
for (var fIndex = 0; fIndex < AffectedFaceBuffer.Count; fIndex++)
{
var face = FacePool[AffectedFaceBuffer[fIndex]];
var vb = face.VerticesBeyond;
for (var i = 0; i < vb.Count; i++)
{
SingularVertices.Add(vb[i]);
}
ConvexFaces.Add(face.Index);
UnprocessedFaces.Remove(face);
ObjectManager.DepositVertexBuffer(face.VerticesBeyond);
face.VerticesBeyond = EmptyBuffer;
}
}
/// <summary>
/// Get a vertex coordinate. In order to reduce speed, all vertex coordinates
/// have been placed in a single array.
/// </summary>
/// <param name="vIndex">The vertex index.</param>
/// <param name="dimension">The index of the dimension.</param>
/// <returns>System.Double.</returns>
private float GetCoordinate(int vIndex, int dimension)
{
return Positions[vIndex * NumOfDimensions + dimension];
}
#region Returning the Results in the proper format
/// <summary>
/// Gets the hull vertices.
/// </summary>
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
/// <param name="data">The data.</param>
/// <returns>TVertex[].</returns>
private TVertex[] GetHullVertices<TVertex>(IList<TVertex> data)
{
var cellCount = ConvexFaces.Count;
var hullVertexCount = 0;
for (var i = 0; i < NumberOfVertices; i++) VertexVisited[i] = false;
for (var i = 0; i < cellCount; i++)
{
var vs = FacePool[ConvexFaces[i]].Vertices;
for (var j = 0; j < vs.Length; j++)
{
var v = vs[j];
if (!VertexVisited[v])
{
VertexVisited[v] = true;
hullVertexCount++;
}
}
}
var result = new TVertex[hullVertexCount];
for (var i = 0; i < NumberOfVertices; i++)
{
if (VertexVisited[i]) result[--hullVertexCount] = data[i];
}
return result;
}
/// <summary>
/// Finds the convex hull and creates the TFace objects.
/// </summary>
/// <typeparam name="TFace">The type of the t face.</typeparam>
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
/// <returns>TFace[].</returns>
private TFace[] GetConvexFaces<TVertex, TFace>()
where TFace : ConvexFace<TVertex, TFace>, new()
where TVertex : IVertex
{
var faces = ConvexFaces;
var cellCount = faces.Count;
var cells = new TFace[cellCount];
for (var i = 0; i < cellCount; i++)
{
var face = FacePool[faces[i]];
var vertices = new TVertex[NumOfDimensions];
for (var j = 0; j < NumOfDimensions; j++)
{
vertices[j] = (TVertex)Vertices[face.Vertices[j]];
}
cells[i] = new TFace
{
Vertices = vertices,
Adjacency = new TFace[NumOfDimensions],
Normal = IsLifted ? null : face.Normal
};
face.Tag = i;
}
for (var i = 0; i < cellCount; i++)
{
var face = FacePool[faces[i]];
var cell = cells[i];
for (var j = 0; j < NumOfDimensions; j++)
{
if (face.AdjacentFaces[j] < 0) continue;
cell.Adjacency[j] = cells[FacePool[face.AdjacentFaces[j]].Tag];
}
// Fix the vertex orientation.
if (face.IsNormalFlipped)
{
var tempVert = cell.Vertices[0];
cell.Vertices[0] = cell.Vertices[NumOfDimensions - 1];
cell.Vertices[NumOfDimensions - 1] = tempVert;
var tempAdj = cell.Adjacency[0];
cell.Adjacency[0] = cell.Adjacency[NumOfDimensions - 1];
cell.Adjacency[NumOfDimensions - 1] = tempAdj;
}
}
return cells;
}
/// <summary>
/// For 2D only: Returns the result in counter-clockwise order starting with the element with the lowest X value.
/// If there are multiple vertices with the same minimum X, then the one with the lowest Y is chosen.
/// </summary>
/// <typeparam name="TVertex">The type of the vertex.</typeparam>
/// <typeparam name="TFace">The type of the face.</typeparam>
/// <param name="data">The data.</param>
/// <returns></returns>
private ConvexHull<TVertex, TFace> Return2DResultInOrder<TVertex, TFace>(IList<TVertex> data)
where TVertex : IVertex
where TFace : ConvexFace<TVertex, TFace>, new()
{
TFace[] faces = GetConvexFaces<TVertex, TFace>();
var numPoints = faces.Length;
var orderDictionary = new Dictionary<TVertex, TFace>();
foreach (var face in faces)
orderDictionary.Add(face.Vertices[1], face);
var firstPoint = faces[0].Vertices[1];
var nextPoint = faces[0].Vertices[0];
var orderedPointList = new List<TVertex>();
orderedPointList.Add(firstPoint);
var orderedFaceList = new List<TFace>();
orderedFaceList.Add(faces[1]);
var lowestXMinIndex = 0;
var k = 0;
while (!nextPoint.Equals(firstPoint))
{
orderedPointList.Add(nextPoint);
var nextFace = orderDictionary[nextPoint];
orderedFaceList.Add(nextFace);
if (nextPoint.Position[0] < orderedPointList[lowestXMinIndex].Position[0]
|| (nextPoint.Position[0] == orderedPointList[lowestXMinIndex].Position[0]
&& nextPoint.Position[1] <= orderedPointList[lowestXMinIndex].Position[1]))
lowestXMinIndex = k;
k++;
nextPoint = nextFace.Vertices[0];
}
TVertex[] points = new TVertex[numPoints];
for (int i = 0; i < numPoints; i++)
{
var j = (i + lowestXMinIndex) % numPoints;
points[i] = orderedPointList[j];
faces[i] = orderedFaceList[j];
}
return new ConvexHull<TVertex, TFace>
{
Points = points,
Faces = faces
};
}
#endregion
}
}

View file

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: f7f265217d00ea340b87645242a45181
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,237 +0,0 @@
/******************************************************************************
*
* The MIT License (MIT)
*
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*****************************************************************************/
namespace MIConvexHull
{
/// <summary>
/// For deferred face addition.
/// </summary>
internal sealed class DeferredFace
{
/// <summary>
/// The faces.
/// </summary>
public ConvexFaceInternal Face, Pivot, OldFace;
/// <summary>
/// The indices.
/// </summary>
public int FaceIndex, PivotIndex;
}
/// <summary>
/// A helper class used to connect faces.
/// </summary>
internal sealed class FaceConnector
{
/// <summary>
/// The edge to be connected.
/// </summary>
public int EdgeIndex;
/// <summary>
/// The face.
/// </summary>
public ConvexFaceInternal Face;
/// <summary>
/// The hash code computed from indices.
/// </summary>
public uint HashCode;
/// <summary>
/// Next node in the list.
/// </summary>
public FaceConnector Next;
/// <summary>
/// Prev node in the list.
/// </summary>
public FaceConnector Previous;
/// <summary>
/// The vertex indices.
/// </summary>
public int[] Vertices;
/// <summary>
/// Ctor.
/// </summary>
/// <param name="dimension">The dimension.</param>
public FaceConnector(int dimension)
{
Vertices = new int[dimension - 1];
}
/// <summary>
/// Updates the connector.
/// </summary>
/// <param name="face">The face.</param>
/// <param name="edgeIndex">Index of the edge.</param>
/// <param name="dim">The dim.</param>
public void Update(ConvexFaceInternal face, int edgeIndex, int dim)
{
Face = face;
EdgeIndex = edgeIndex;
uint hashCode = 23;
unchecked
{
var vs = face.Vertices;
int i, c = 0;
for (i = 0; i < edgeIndex; i++)
{
Vertices[c++] = vs[i];
hashCode += 31*hashCode + (uint) vs[i];
}
for (i = edgeIndex + 1; i < vs.Length; i++)
{
Vertices[c++] = vs[i];
hashCode += 31*hashCode + (uint) vs[i];
}
}
HashCode = hashCode;
}
/// <summary>
/// Can two faces be connected.
/// </summary>
/// <param name="a">a.</param>
/// <param name="b">The b.</param>
/// <param name="dim">The dim.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
public static bool AreConnectable(FaceConnector a, FaceConnector b, int dim)
{
if (a.HashCode != b.HashCode) return false;
var av = a.Vertices;
var bv = b.Vertices;
for (var i = 0; i < av.Length; i++)
{
if (av[i] != bv[i]) return false;
}
return true;
}
/// <summary>
/// Connect two faces.
/// </summary>
/// <param name="a">a.</param>
/// <param name="b">The b.</param>
public static void Connect(FaceConnector a, FaceConnector b)
{
a.Face.AdjacentFaces[a.EdgeIndex] = b.Face.Index;
b.Face.AdjacentFaces[b.EdgeIndex] = a.Face.Index;
}
}
/// <summary>
/// This internal class manages the faces of the convex hull. It is a
/// separate class from the desired user class.
/// </summary>
internal sealed class ConvexFaceInternal
{
/// <summary>
/// Gets or sets the adjacent face data.
/// </summary>
public int[] AdjacentFaces;
/// <summary>
/// The furthest vertex.
/// </summary>
public int FurthestVertex;
/// <summary>
/// Index of the face inside the pool.
/// </summary>
public int Index;
/// <summary>
/// Is it present in the list.
/// </summary>
public bool InList;
/// <summary>
/// Is the normal flipped?
/// </summary>
public bool IsNormalFlipped;
/// <summary>
/// Next node in the list.
/// </summary>
public ConvexFaceInternal Next;
/// <summary>
/// Gets or sets the normal vector.
/// </summary>
public float[] Normal;
/// <summary>
/// Face plane constant element.
/// </summary>
public float Offset;
//public int UnprocessedIndex;
/// <summary>
/// Prev node in the list.
/// </summary>
public ConvexFaceInternal Previous;
/// <summary>
/// Used to traverse affected faces and create the Delaunay representation.
/// </summary>
public int Tag;
/// <summary>
/// Gets or sets the vertices.
/// </summary>
public int[] Vertices;
/// <summary>
/// Gets or sets the vertices beyond.
/// </summary>
public IndexBuffer VerticesBeyond;
/// <summary>
/// Initializes a new instance of the <see cref="ConvexFaceInternal" /> class.
/// </summary>
/// <param name="dimension">The dimension.</param>
/// <param name="index">The index.</param>
/// <param name="beyondList">The beyond list.</param>
public ConvexFaceInternal(int dimension, int index, IndexBuffer beyondList)
{
Index = index;
AdjacentFaces = new int[dimension];
VerticesBeyond = beyondList;
Normal = new float[dimension];
Vertices = new int[dimension];
}
}
}

View file

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 58c58e163f4c86e48a6df3ee6c5056c0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,480 +0,0 @@
/******************************************************************************
*
* The MIT License (MIT)
*
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*****************************************************************************/
using System;
using System.Collections.Generic;
using CultMath;
using static CultMath.math;
using Random = CultMath.Random;
namespace MIConvexHull
{
/// <summary>
/// A helper class mostly for normal computation. If convex hulls are computed
/// in higher dimensions, it might be a good idea to add a specific
/// FindNormalVectorND function.
/// </summary>
internal class MathHelper
{
/// <summary>
/// The dimension
/// </summary>
private readonly int Dimension;
/// <summary>
/// The matrix pivots
/// </summary>
private readonly int[] matrixPivots;
/// <summary>
/// The n d matrix
/// </summary>
private readonly float[] nDMatrix;
/// <summary>
/// The n d normal helper vector
/// </summary>
private readonly float[] nDNormalHelperVector;
/// <summary>
/// The nt x
/// </summary>
private readonly float[] ntX;
/// <summary>
/// The nt y
/// </summary>
private readonly float[] ntY;
/// <summary>
/// The nt z
/// </summary>
private readonly float[] ntZ;
/// <summary>
/// The position data
/// </summary>
private readonly float[] PositionData;
private static Random _random = new Random((uint) (DateTime.Now.Ticks % uint.MaxValue));
/// <summary>
/// Initializes a new instance of the <see cref="MathHelper"/> class.
/// </summary>
/// <param name="dimension">The dimension.</param>
/// <param name="positions">The positions.</param>
internal MathHelper(int dimension, float[] positions)
{
PositionData = positions;
Dimension = dimension;
ntX = new float[Dimension];
ntY = new float[Dimension];
ntZ = new float[Dimension];
nDNormalHelperVector = new float[Dimension];
nDMatrix = new float[Dimension * Dimension];
matrixPivots = new int[Dimension];
}
/// <summary>
/// Calculates the normal and offset of the hyper-plane given by the face's vertices.
/// </summary>
/// <param name="face">The face.</param>
/// <param name="center">The center.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
internal bool CalculateFacePlane(ConvexFaceInternal face, float[] center)
{
var vertices = face.Vertices;
var normal = face.Normal;
FindNormalVector(vertices, normal);
if (float.IsNaN(normal[0]))
{
return false;
}
var offset = 0.0f;
var centerDistance = 0.0f;
var fi = vertices[0] * Dimension;
for (var i = 0; i < Dimension; i++)
{
var n = normal[i];
offset += n * PositionData[fi + i];
centerDistance += n * center[i];
}
face.Offset = -offset;
centerDistance -= offset;
if (centerDistance > 0)
{
for (var i = 0; i < Dimension; i++) normal[i] = -normal[i];
face.Offset = offset;
face.IsNormalFlipped = true;
}
else face.IsNormalFlipped = false;
return true;
}
/// <summary>
/// Check if the vertex is "visible" from the face.
/// The vertex is "over face" if the return value is &gt; Constants.PlaneDistanceTolerance.
/// </summary>
/// <param name="v">The v.</param>
/// <param name="f">The f.</param>
/// <returns>The vertex is "over face" if the result is positive.</returns>
internal double GetVertexDistance(int v, ConvexFaceInternal f)
{
var normal = f.Normal;
var x = v * Dimension;
var distance = f.Offset;
for (var i = 0; i < normal.Length; i++) distance += normal[i] * PositionData[x + i];
return distance;
}
/// <summary>
/// Returns the vector the between vertices.
/// </summary>
/// <param name="toIndex">To index.</param>
/// <param name="fromIndex">From index.</param>
/// <returns>System.Double[].</returns>
internal float[] VectorBetweenVertices(int toIndex, int fromIndex)
{
var target = new float[Dimension];
VectorBetweenVertices(toIndex, fromIndex, target);
return target;
}
/// <summary>
/// Returns the vector the between vertices.
/// </summary>
/// <param name="fromIndex">From index.</param>
/// <param name="toIndex">To index.</param>
/// <param name="target">The target.</param>
/// <returns></returns>
private void VectorBetweenVertices(int toIndex, int fromIndex, float[] target)
{
int u = toIndex * Dimension, v = fromIndex * Dimension;
for (var i = 0; i < Dimension; i++)
{
target[i] = PositionData[u + i] - PositionData[v + i];
}
}
internal void RandomOffsetToLift(int index, float maxHeight)
{
var liftIndex = (index * Dimension) + Dimension - 1;
PositionData[liftIndex] += 0.0001f * maxHeight * (_random.NextFloat() - 0.5f);
}
#region Find the normal vector of the face
/// <summary>
/// Finds normal vector of a hyper-plane given by vertices.
/// Stores the results to normalData.
/// </summary>
/// <param name="vertices">The vertices.</param>
/// <param name="normalData">The normal data.</param>
private void FindNormalVector(int[] vertices, float[] normalData)
{
switch (Dimension)
{
case 2:
FindNormalVector2D(vertices, normalData);
break;
case 3:
FindNormalVector3D(vertices, normalData);
break;
case 4:
FindNormalVector4D(vertices, normalData);
break;
default:
FindNormalVectorND(vertices, normalData);
break;
}
}
/// <summary>
/// Finds 2D normal vector.
/// </summary>
/// <param name="vertices">The vertices.</param>
/// <param name="normal">The normal.</param>
private void FindNormalVector2D(int[] vertices, float[] normal)
{
VectorBetweenVertices(vertices[1], vertices[0], ntX);
var nx = -ntX[1];
var ny = ntX[0];
var norm = sqrt(nx * nx + ny * ny);
var f = 1.0f / norm;
normal[0] = f * nx;
normal[1] = f * ny;
}
/// <summary>
/// Finds 3D normal vector.
/// </summary>
/// <param name="vertices">The vertices.</param>
/// <param name="normal">The normal.</param>
private void FindNormalVector3D(int[] vertices, float[] normal)
{
VectorBetweenVertices(vertices[1], vertices[0], ntX);
VectorBetweenVertices(vertices[2], vertices[1], ntY);
var nx = ntX[1] * ntY[2] - ntX[2] * ntY[1];
var ny = ntX[2] * ntY[0] - ntX[0] * ntY[2];
var nz = ntX[0] * ntY[1] - ntX[1] * ntY[0];
var norm = sqrt(nx * nx + ny * ny + nz * nz);
var f = 1.0f / norm;
normal[0] = f * nx;
normal[1] = f * ny;
normal[2] = f * nz;
}
/// <summary>
/// Finds 4D normal vector.
/// </summary>
/// <param name="vertices">The vertices.</param>
/// <param name="normal">The normal.</param>
private void FindNormalVector4D(int[] vertices, float[] normal)
{
VectorBetweenVertices(vertices[1], vertices[0], ntX);
VectorBetweenVertices(vertices[2], vertices[1], ntY);
VectorBetweenVertices(vertices[3], vertices[2], ntZ);
var x = ntX;
var y = ntY;
var z = ntZ;
// This was generated using Mathematica
var nx = x[3] * (y[2] * z[1] - y[1] * z[2])
+ x[2] * (y[1] * z[3] - y[3] * z[1])
+ x[1] * (y[3] * z[2] - y[2] * z[3]);
var ny = x[3] * (y[0] * z[2] - y[2] * z[0])
+ x[2] * (y[3] * z[0] - y[0] * z[3])
+ x[0] * (y[2] * z[3] - y[3] * z[2]);
var nz = x[3] * (y[1] * z[0] - y[0] * z[1])
+ x[1] * (y[0] * z[3] - y[3] * z[0])
+ x[0] * (y[3] * z[1] - y[1] * z[3]);
var nw = x[2] * (y[0] * z[1] - y[1] * z[0])
+ x[1] * (y[2] * z[0] - y[0] * z[2])
+ x[0] * (y[1] * z[2] - y[2] * z[1]);
var norm = sqrt(nx * nx + ny * ny + nz * nz + nw * nw);
var f = 1.0f / norm;
normal[0] = f * nx;
normal[1] = f * ny;
normal[2] = f * nz;
normal[3] = f * nw;
}
/// <summary>
/// Finds the normal vector nd.
/// </summary>
/// <param name="vertices">The vertices.</param>
/// <param name="normal">The normal.</param>
private void FindNormalVectorND(int[] vertices, float[] normal)
{
/* We need to solve the matrix A n = B where
* - A contains coordinates of vertices as columns
* - B is vector with all 1's. Really, it should be the distance of
* the plane from the origin, but - since we're not worried about that
* here and we will normalize the normal anyway - all 1's suffices.
*/
var iPiv = matrixPivots;
var data = nDMatrix;
var norm = 0.0f;
// Solve determinants by replacing x-th column by all 1.
for (var x = 0; x < Dimension; x++)
{
for (var i = 0; i < Dimension; i++)
{
var offset = vertices[i] * Dimension;
for (var j = 0; j < Dimension; j++)
{
// maybe I got the i/j mixed up here regarding the representation Math.net uses...
// ...but it does not matter since Det(A) = Det(Transpose(A)).
data[Dimension * i + j] = j == x ? 1.0f : PositionData[offset + j];
}
}
LUFactor(data, Dimension, iPiv, nDNormalHelperVector);
var coord = 1.0f;
for (var i = 0; i < Dimension; i++)
{
if (iPiv[i] != i) coord *= -data[Dimension * i + i]; // the determinant sign changes on row swap.
else coord *= data[Dimension * i + i];
}
normal[x] = coord;
norm += coord * coord;
}
// Normalize the result
var f = 1.0f / sqrt(norm);
for (var i = 0; i < normal.Length; i++) normal[i] *= f;
}
#endregion
#region Simplex Volume
/// <summary>
/// Gets the simplex volume. Prior to having enough edge vectors, the method pads the remaining with all
/// "other numbers". So, yes, this method is not really finding the volume. But a relative volume-like measure. It
/// uses the magnitude of the determinant as the volume stand-in following the Cayley-Menger theorem.
/// </summary>
/// <param name="edgeVectors">The edge vectors.</param>
/// <param name="lastIndex">The last index.</param>
/// <param name="bigNumber">The big number.</param>
/// <returns>System.Double.</returns>
internal float GetSimplexVolume(float[][] edgeVectors, int lastIndex, float bigNumber)
{
var A = new float[Dimension * Dimension];
var index = 0;
for (int i = 0; i < Dimension; i++)
for (int j = 0; j < Dimension; j++)
if (i <= lastIndex)
A[index++] = edgeVectors[i][j];
else A[index] = (pow(-1, index) * index++) / bigNumber;
// this last term is used for all the vertices in the comparison for the yet determined vertices
// the idea is to come up with sets of numbers that are orthogonal so that an non-zero value will result
// and to choose smallish numbers since the choice of vectors will affect what the end volume is.
// A better way (todo?) is to solve a smaller matrix. However, cases were found in which the obvious smaller vector
// (the upper left) had too many zeros. So, one would need to find the right subset. Indeed choosing a subset
// biases the first dimensions of the others. Perhaps a larger volume would be created from a different vertex
// if another subset of dimensions were used.
return abs(DeterminantDestructive(A));
}
/// <summary>
/// Determinants the destructive.
/// </summary>
/// <param name="A">a.</param>
/// <returns>System.Double.</returns>
private float DeterminantDestructive(float[] A)
{
switch (Dimension)
{
case 0:
return 0.0f;
case 1:
return A[0];
case 2:
return A[0] * A[3] - A[1] * A[2];
case 3:
return A[0] * A[4] * A[8] + A[1] * A[5] * A[6] + A[2] * A[3] * A[7]
- A[0] * A[5] * A[7] - A[1] * A[3] * A[8] - A[2] * A[4] * A[6];
default:
{
var iPiv = new int[Dimension];
var helper = new float[Dimension];
LUFactor(A, Dimension, iPiv, helper);
var det = 1.0f;
for (var i = 0; i < iPiv.Length; i++)
{
det *= A[Dimension * i + i];
if (iPiv[i] != i) det *= -1; // the determinant sign changes on row swap.
}
return det;
}
}
}
#endregion
// Modified from Math.NET
// Copyright (c) 2009-2013 Math.NET
/// <summary>
/// Lus the factor.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="order">The order.</param>
/// <param name="ipiv">The ipiv.</param>
/// <param name="vecLUcolj">The vec l ucolj.</param>
private static void LUFactor(float[] data, int order, int[] ipiv, float[] vecLUcolj)
{
// Initialize the pivot matrix to the identity permutation.
for (var i = 0; i < order; i++)
{
ipiv[i] = i;
}
// Outer loop.
for (var j = 0; j < order; j++)
{
var indexj = j * order;
var indexjj = indexj + j;
// Make a copy of the j-th column to localize references.
for (var i = 0; i < order; i++)
{
vecLUcolj[i] = data[indexj + i];
}
// Apply previous transformations.
for (var i = 0; i < order; i++)
{
// Most of the time is spent in the following dot product.
var kmax = Math.Min(i, j);
var s = 0.0f;
for (var k = 0; k < kmax; k++)
{
s += data[k * order + i] * vecLUcolj[k];
}
data[indexj + i] = vecLUcolj[i] -= s;
}
// Find pivot and exchange if necessary.
var p = j;
for (var i = j + 1; i < order; i++)
{
if (abs(vecLUcolj[i]) > abs(vecLUcolj[p]))
{
p = i;
}
}
if (p != j)
{
for (var k = 0; k < order; k++)
{
var indexk = k * order;
var indexkp = indexk + p;
var indexkj = indexk + j;
var temp = data[indexkp];
data[indexkp] = data[indexkj];
data[indexkj] = temp;
}
ipiv[j] = p;
}
// Compute multipliers.
if (j < order & data[indexjj] != 0.0f)
{
for (var i = j + 1; i < order; i++)
{
data[indexj + i] /= data[indexjj];
}
}
}
}
}
}

View file

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 8bb3327041efa18479319ec117493f8c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,218 +0,0 @@
/******************************************************************************
*
* The MIT License (MIT)
*
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*****************************************************************************/
using System;
namespace MIConvexHull
{
/// <summary>
/// A helper class for object allocation/storage.
/// This helps the GC a lot as it prevents the creation of about 75% of
/// new face objects (in the case of ConvexFaceInternal). In the case of
/// FaceConnectors and DefferedFaces, the difference is even higher (in most
/// cases O(1) vs O(number of created faces)).
/// </summary>
internal class ObjectManager
{
/// <summary>
/// The dimension
/// </summary>
private readonly int Dimension;
/// <summary>
/// The connector stack
/// </summary>
private FaceConnector ConnectorStack;
/// <summary>
/// The deferred face stack
/// </summary>
private readonly SimpleList<DeferredFace> DeferredFaceStack;
/// <summary>
/// The empty buffer stack
/// </summary>
private readonly SimpleList<IndexBuffer> EmptyBufferStack;
/// <summary>
/// The face pool
/// </summary>
private ConvexFaceInternal[] FacePool;
/// <summary>
/// The face pool size
/// </summary>
private int FacePoolSize;
/// <summary>
/// The face pool capacity
/// </summary>
private int FacePoolCapacity;
/// <summary>
/// The free face indices
/// </summary>
private readonly IndexBuffer FreeFaceIndices;
/// <summary>
/// The hull
/// </summary>
private readonly ConvexHullAlgorithm Hull;
/// <summary>
/// Create the manager.
/// </summary>
/// <param name="hull">The hull.</param>
public ObjectManager(ConvexHullAlgorithm hull)
{
Dimension = hull.NumOfDimensions;
Hull = hull;
FacePool = hull.FacePool;
FacePoolSize = 0;
FacePoolCapacity = hull.FacePool.Length;
FreeFaceIndices = new IndexBuffer();
EmptyBufferStack = new SimpleList<IndexBuffer>();
DeferredFaceStack = new SimpleList<DeferredFace>();
}
/// <summary>
/// Return the face to the pool for later use.
/// </summary>
/// <param name="faceIndex">Index of the face.</param>
public void DepositFace(int faceIndex)
{
var face = FacePool[faceIndex];
var af = face.AdjacentFaces;
for (var i = 0; i < af.Length; i++)
{
af[i] = -1;
}
FreeFaceIndices.Push(faceIndex);
}
/// <summary>
/// Reallocate the face pool, including the AffectedFaceFlags
/// </summary>
private void ReallocateFacePool()
{
var newPool = new ConvexFaceInternal[2*FacePoolCapacity];
var newTags = new bool[2*FacePoolCapacity];
Array.Copy(FacePool, newPool, FacePoolCapacity);
Buffer.BlockCopy(Hull.AffectedFaceFlags, 0, newTags, 0, FacePoolCapacity*sizeof (bool));
FacePoolCapacity = 2*FacePoolCapacity;
Hull.FacePool = newPool;
FacePool = newPool;
Hull.AffectedFaceFlags = newTags;
}
/// <summary>
/// Create a new face and put it in the pool.
/// </summary>
/// <returns>System.Int32.</returns>
private int CreateFace()
{
var index = FacePoolSize;
var face = new ConvexFaceInternal(Dimension, index, GetVertexBuffer());
FacePoolSize++;
if (FacePoolSize > FacePoolCapacity) ReallocateFacePool();
FacePool[index] = face;
return index;
}
/// <summary>
/// Return index of an unused face or creates a new one.
/// </summary>
/// <returns>System.Int32.</returns>
public int GetFace()
{
if (FreeFaceIndices.Count > 0) return FreeFaceIndices.Pop();
return CreateFace();
}
/// <summary>
/// Store a face connector in the "embedded" linked list.
/// </summary>
/// <param name="connector">The connector.</param>
public void DepositConnector(FaceConnector connector)
{
if (ConnectorStack == null)
{
connector.Next = null;
ConnectorStack = connector;
}
else
{
connector.Next = ConnectorStack;
ConnectorStack = connector;
}
}
/// <summary>
/// Get an unused face connector. If none is available, create it.
/// </summary>
/// <returns>FaceConnector.</returns>
public FaceConnector GetConnector()
{
if (ConnectorStack == null) return new FaceConnector(Dimension);
var ret = ConnectorStack;
ConnectorStack = ConnectorStack.Next;
ret.Next = null;
return ret;
}
/// <summary>
/// Deposit the index buffer.
/// </summary>
/// <param name="buffer">The buffer.</param>
public void DepositVertexBuffer(IndexBuffer buffer)
{
buffer.Clear();
EmptyBufferStack.Push(buffer);
}
/// <summary>
/// Get a store index buffer or create a new instance.
/// </summary>
/// <returns>IndexBuffer.</returns>
public IndexBuffer GetVertexBuffer()
{
return EmptyBufferStack.Count != 0 ? EmptyBufferStack.Pop() : new IndexBuffer();
}
/// <summary>
/// Deposit the deferred face.
/// </summary>
/// <param name="face">The face.</param>
public void DepositDeferredFace(DeferredFace face)
{
DeferredFaceStack.Push(face);
}
/// <summary>
/// Get the deferred face.
/// </summary>
/// <returns>DeferredFace.</returns>
public DeferredFace GetDeferredFace()
{
return DeferredFaceStack.Count != 0 ? DeferredFaceStack.Pop() : new DeferredFace();
}
}
}

View file

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: e8d582e97c6824740ba9e1a41641b372
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,8 +0,0 @@
using System.Collections;
using MIConvexHull;
public class Face3 : ConvexFace<Vertex3, Face3>
{
}

View file

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 30a2635ffe51545499499ce392b234c8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,53 +0,0 @@
/******************************************************************************
*
* The MIT License (MIT)
*
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*****************************************************************************/
namespace MIConvexHull
{
/// <summary>
/// An interface for a structure with nD position.
/// </summary>
public interface IVertex
{
/// <summary>
/// Position of the vertex.
/// </summary>
/// <value>The position.</value>
float[] Position { get; }
}
/// <summary>
/// "Default" vertex.
/// </summary>
/// <seealso cref="MIConvexHull.IVertex" />
public class DefaultVertex : IVertex
{
/// <summary>
/// Position of the vertex.
/// </summary>
/// <value>The position.</value>
public float[] Position { get; set; }
}
}

View file

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: a55f713690988bb48aef7cbd4f01ebc7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,181 +0,0 @@
/******************************************************************************
*
* The MIT License (MIT)
*
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*****************************************************************************/
using System.Collections.Generic;
using System.Linq;
namespace MIConvexHull
{
/// <summary>
/// Simple interface to unify different types of triangulations in the future.
/// </summary>
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
/// <typeparam name="TCell">The type of the t cell.</typeparam>
public interface ITriangulation<TVertex, TCell>
where TCell : TriangulationCell<TVertex, TCell>, new()
where TVertex : IVertex
{
/// <summary>
/// Triangulation simplexes. For 2D - triangles, 3D - tetrahedrons, etc ...
/// </summary>
/// <value>The cells.</value>
IEnumerable<TCell> Cells { get; }
}
/// <summary>
/// Factory class for creating triangulations.
/// </summary>
public static class Triangulation
{
/// <summary>
/// Creates the Delaunay triangulation of the input data.
/// </summary>
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
/// <param name="data">The data.</param>
/// <param name="PlaneDistanceTolerance">The plane distance tolerance (default is 1e-10). If too high, points
/// will be missed. If too low, the algorithm may break. Only adjust if you notice problems.</param>
/// <returns>ITriangulation&lt;TVertex, DefaultTriangulationCell&lt;TVertex&gt;&gt;.</returns>
public static ITriangulation<TVertex, DefaultTriangulationCell<TVertex>> CreateDelaunay<TVertex>(
IList<TVertex> data,
float PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
where TVertex : IVertex
{
return DelaunayTriangulation<TVertex, DefaultTriangulationCell<TVertex>>.Create(data, PlaneDistanceTolerance);
}
/// <summary>
/// Creates the Delaunay triangulation of the input data.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="PlaneDistanceTolerance">The plane distance tolerance (default is 1e-10). If too high, points
/// will be missed. If too low, the algorithm may break. Only adjust if you notice problems.</param>
/// <returns>ITriangulation&lt;DefaultVertex, DefaultTriangulationCell&lt;DefaultVertex&gt;&gt;.</returns>
public static ITriangulation<DefaultVertex, DefaultTriangulationCell<DefaultVertex>> CreateDelaunay(
IList<float[]> data,
float PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
{
var points = data.Select(p => new DefaultVertex { Position = p }).ToList();
return DelaunayTriangulation<DefaultVertex, DefaultTriangulationCell<DefaultVertex>>.Create(points, PlaneDistanceTolerance);
}
/// <summary>
/// Creates the Delaunay triangulation of the input data.
/// </summary>
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
/// <typeparam name="TFace">The type of the t face.</typeparam>
/// <param name="data">The data.</param>
/// <param name="PlaneDistanceTolerance">The plane distance tolerance (default is 1e-10). If too high, points
/// will be missed. If too low, the algorithm may break. Only adjust if you notice problems.</param>
/// <returns>ITriangulation&lt;TVertex, TFace&gt;.</returns>
public static ITriangulation<TVertex, TFace> CreateDelaunay<TVertex, TFace>(IList<TVertex> data,
float PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
where TVertex : IVertex
where TFace : TriangulationCell<TVertex, TFace>, new()
{
return DelaunayTriangulation<TVertex, TFace>.Create(data, PlaneDistanceTolerance);
}
/// <summary>
/// Create the voronoi mesh.
/// </summary>
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
/// <typeparam name="TCell">The type of the t cell.</typeparam>
/// <typeparam name="TEdge">The type of the t edge.</typeparam>
/// <param name="data">The data.</param>
/// <param name="PlaneDistanceTolerance">The plane distance tolerance (default is 1e-10). If too high, points
/// will be missed. If too low, the algorithm may break. Only adjust if you notice problems.</param>
/// <returns>VoronoiMesh&lt;TVertex, TCell, TEdge&gt;.</returns>
public static VoronoiMesh<TVertex, TCell, TEdge> CreateVoronoi<TVertex, TCell, TEdge>(IList<TVertex> data,
float PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
where TCell : TriangulationCell<TVertex, TCell>, new()
where TVertex : IVertex
where TEdge : VoronoiEdge<TVertex, TCell>, new()
{
return VoronoiMesh<TVertex, TCell, TEdge>.Create(data, PlaneDistanceTolerance);
}
/// <summary>
/// Create the voronoi mesh.
/// </summary>
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
/// <param name="data">The data.</param>
/// <param name="PlaneDistanceTolerance">The plane distance tolerance (default is 1e-10). If too high, points
/// will be missed. If too low, the algorithm may break. Only adjust if you notice problems.</param>
/// <returns>VoronoiMesh&lt;TVertex, DefaultTriangulationCell&lt;TVertex&gt;, VoronoiEdge&lt;TVertex, DefaultTriangulationCell&lt;TVertex&gt;&gt;&gt;.</returns>
public static
VoronoiMesh
<TVertex, DefaultTriangulationCell<TVertex>, VoronoiEdge<TVertex, DefaultTriangulationCell<TVertex>>>
CreateVoronoi<TVertex>(IList<TVertex> data,
float PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
where TVertex : IVertex
{
return
VoronoiMesh
<TVertex, DefaultTriangulationCell<TVertex>, VoronoiEdge<TVertex, DefaultTriangulationCell<TVertex>>
>.Create(data, PlaneDistanceTolerance);
}
/// <summary>
/// Create the voronoi mesh.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="PlaneDistanceTolerance">The plane distance tolerance (default is 1e-10). If too high, points
/// will be missed. If too low, the algorithm may break. Only adjust if you notice problems.</param>
/// <returns>VoronoiMesh&lt;DefaultVertex, DefaultTriangulationCell&lt;DefaultVertex&gt;, VoronoiEdge&lt;DefaultVertex, DefaultTriangulationCell&lt;DefaultVertex&gt;&gt;&gt;.</returns>
public static
VoronoiMesh
<DefaultVertex, DefaultTriangulationCell<DefaultVertex>,
VoronoiEdge<DefaultVertex, DefaultTriangulationCell<DefaultVertex>>>
CreateVoronoi(IList<float[]> data,
float PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
{
var points = data.Select(p => new DefaultVertex { Position = p.ToArray() }).ToList();
return
VoronoiMesh
<DefaultVertex, DefaultTriangulationCell<DefaultVertex>,
VoronoiEdge<DefaultVertex, DefaultTriangulationCell<DefaultVertex>>>.Create(points, PlaneDistanceTolerance);
}
/// <summary>
/// Create the voronoi mesh.
/// </summary>
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
/// <typeparam name="TCell">The type of the t cell.</typeparam>
/// <param name="data">The data.</param>
/// <param name="PlaneDistanceTolerance">The plane distance tolerance (default is 1e-10). If too high, points
/// will be missed. If too low, the algorithm may break. Only adjust if you notice problems.</param>
/// <returns>VoronoiMesh&lt;TVertex, TCell, VoronoiEdge&lt;TVertex, TCell&gt;&gt;.</returns>
public static VoronoiMesh<TVertex, TCell, VoronoiEdge<TVertex, TCell>> CreateVoronoi<TVertex, TCell>(
IList<TVertex> data,
float PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
where TVertex : IVertex
where TCell : TriangulationCell<TVertex, TCell>, new()
{
return VoronoiMesh<TVertex, TCell, VoronoiEdge<TVertex, TCell>>.Create(data, PlaneDistanceTolerance);
}
}
}

View file

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 0762bfe861ed97749a222fb1c217788a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 5bf99a94223c6e1458c243cb68091852
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,96 +0,0 @@
/******************************************************************************
*
* The MIT License (MIT)
*
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*****************************************************************************/
using System.Collections.Generic;
using System.Linq;
namespace MIConvexHull
{
/*
* Code here handles triangulation related stuff.
*/
/// <summary>
/// Class ConvexHullAlgorithm.
/// </summary>
internal partial class ConvexHullAlgorithm
{
/// <summary>
/// Computes the Delaunay triangulation.
/// </summary>
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
/// <typeparam name="TCell">The type of the t cell.</typeparam>
/// <param name="data">The data.</param>
/// <param name="PlaneDistanceTolerance">The plane distance tolerance.</param>
/// <returns>TCell[].</returns>
internal static TCell[] GetDelaunayTriangulation<TVertex, TCell>(IList<TVertex> data,
float PlaneDistanceTolerance )
where TCell : TriangulationCell<TVertex, TCell>, new()
where TVertex : IVertex
{
var ch = new ConvexHullAlgorithm(data.Cast<IVertex>().ToArray(), true, PlaneDistanceTolerance);
ch.GetConvexHull();
ch.RemoveUpperFaces();
return ch.GetConvexFaces<TVertex, TCell>();
}
/// <summary>
/// Removes up facing Tetrahedrons from the triangulation.
/// </summary>
private void RemoveUpperFaces()
{
var delaunayFaces = ConvexFaces;
var dimension = NumOfDimensions - 1;
// Remove the "upper" faces
for (var i = delaunayFaces.Count - 1; i >= 0; i--)
{
var candidateIndex = delaunayFaces[i];
var candidate = FacePool[candidateIndex];
if (candidate.Normal[dimension] >= 0.0)
{
for (var fi = 0; fi < candidate.AdjacentFaces.Length; fi++)
{
var af = candidate.AdjacentFaces[fi];
if (af >= 0)
{
var face = FacePool[af];
for (var j = 0; j < face.AdjacentFaces.Length; j++)
{
if (face.AdjacentFaces[j] == candidateIndex)
{
face.AdjacentFaces[j] = -1;
}
}
}
}
delaunayFaces[i] = delaunayFaces[delaunayFaces.Count - 1];
delaunayFaces.Pop();
}
}
}
}
}

View file

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: de8661d86f2667647b9dca59c1c97e9a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,75 +0,0 @@
/******************************************************************************
*
* The MIT License (MIT)
*
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*****************************************************************************/
using System;
using System.Collections.Generic;
namespace MIConvexHull
{
/// <summary>
/// Calculation and representation of Delaunay triangulation.
/// </summary>
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
/// <typeparam name="TCell">The type of the t cell.</typeparam>
/// <seealso cref="MIConvexHull.ITriangulation{TVertex, TCell}" />
public class DelaunayTriangulation<TVertex, TCell> : ITriangulation<TVertex, TCell>
where TCell : TriangulationCell<TVertex, TCell>, new()
where TVertex : IVertex
{
/// <summary>
/// Can only be created using a factory method.
/// </summary>
private DelaunayTriangulation()
{
}
/// <summary>
/// Cells of the triangulation.
/// </summary>
/// <value>The cells.</value>
public IEnumerable<TCell> Cells { get; private set; }
/// <summary>
/// Creates the Delaunay triangulation of the input data.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="PlaneDistanceTolerance">The plane distance tolerance (default is 1e-10). If too high, points
/// will be missed. If too low, the algorithm may break. Only adjust if you notice problems.</param>
/// <returns>DelaunayTriangulation&lt;TVertex, TCell&gt;.</returns>
/// <exception cref="System.ArgumentNullException">data</exception>
/// <exception cref="ArgumentNullException">data</exception>
public static DelaunayTriangulation<TVertex, TCell> Create(IList<TVertex> data,
float PlaneDistanceTolerance)// = Constants.DefaultPlaneDistanceTolerance)
{
if (data == null) throw new ArgumentNullException("data");
if (data.Count == 0) return new DelaunayTriangulation<TVertex, TCell> { Cells = new TCell[0] };
var cells = ConvexHullAlgorithm.GetDelaunayTriangulation<TVertex, TCell>(data, PlaneDistanceTolerance);
return new DelaunayTriangulation<TVertex, TCell> { Cells = cells };
}
}
}

View file

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 4b0e872e78d2ab8428b446cfa5c06580
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,51 +0,0 @@
/******************************************************************************
*
* The MIT License (MIT)
*
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*****************************************************************************/
namespace MIConvexHull
{
/// <summary>
/// Representation of the triangulation cell. Pretty much the same as ConvexFace,
/// just wanted to distinguish the two.
/// To declare your own face type, use class Face : DelaunayFace(of Vertex, of Face)
/// </summary>
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
/// <typeparam name="TCell">The type of the t cell.</typeparam>
/// <seealso cref="MIConvexHull.ConvexFace{TVertex, TCell}" />
public abstract class TriangulationCell<TVertex, TCell> : ConvexFace<TVertex, TCell>
where TVertex : IVertex
where TCell : ConvexFace<TVertex, TCell>
{
}
/// <summary>
/// Default triangulation cell.
/// </summary>
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
public class DefaultTriangulationCell<TVertex> : TriangulationCell<TVertex, DefaultTriangulationCell<TVertex>>
where TVertex : IVertex
{
}
}

View file

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 808182249e0e66143b65945d9aeb37fe
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,93 +0,0 @@
/******************************************************************************
*
* The MIT License (MIT)
*
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*****************************************************************************/
namespace MIConvexHull
{
/// <summary>
/// A class representing an (undirected) edge of the Voronoi graph.
/// </summary>
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
/// <typeparam name="TCell">The type of the t cell.</typeparam>
public class VoronoiEdge<TVertex, TCell>
where TVertex : IVertex
where TCell : TriangulationCell<TVertex, TCell>
{
/// <summary>
/// Create an instance of the edge.
/// </summary>
public VoronoiEdge()
{
}
/// <summary>
/// Create an instance of the edge.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="target">The target.</param>
public VoronoiEdge(TCell source, TCell target)
{
Source = source;
Target = target;
}
/// <summary>
/// Source of the edge.
/// </summary>
/// <value>The source.</value>
public TCell Source { get; internal set; }
/// <summary>
/// Target of the edge.
/// </summary>
/// <value>The target.</value>
public TCell Target { get; internal set; }
/// <summary>
/// ...
/// </summary>
/// <param name="obj">The object to compare with the current object.</param>
/// <returns><c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
var other = obj as VoronoiEdge<TVertex, TCell>;
if (other == null) return false;
if (ReferenceEquals(this, other)) return true;
return (Source == other.Source && Target == other.Target)
|| (Source == other.Target && Target == other.Source);
}
/// <summary>
/// ...
/// </summary>
/// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
public override int GetHashCode()
{
var hash = 23;
hash = hash*31 + Source.GetHashCode();
return hash*31 + Target.GetHashCode();
}
}
}

View file

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 2f5c388c78c121a47b14c2f4ed26af38
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,203 +0,0 @@
/******************************************************************************
*
* The MIT License (MIT)
*
* MIConvexHull, Copyright (c) 2015 David Sehnal, Matthew Campbell
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*****************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
namespace MIConvexHull
{
/// <summary>
/// A factory class for creating a Voronoi mesh.
/// </summary>
public static class VoronoiMesh
{
/// <summary>
/// Create the voronoi mesh.
/// </summary>
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
/// <typeparam name="TCell">The type of the t cell.</typeparam>
/// <typeparam name="TEdge">The type of the t edge.</typeparam>
/// <param name="data">The data.</param>
/// <returns>VoronoiMesh&lt;TVertex, TCell, TEdge&gt;.</returns>
public static VoronoiMesh<TVertex, TCell, TEdge> Create<TVertex, TCell, TEdge>(IList<TVertex> data,
float PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
where TCell : TriangulationCell<TVertex, TCell>, new()
where TVertex : IVertex
where TEdge : VoronoiEdge<TVertex, TCell>, new()
{
return VoronoiMesh<TVertex, TCell, TEdge>.Create(data, PlaneDistanceTolerance);
}
/// <summary>
/// Create the voronoi mesh.
/// </summary>
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
/// <param name="data">The data.</param>
/// <returns>VoronoiMesh&lt;TVertex, DefaultTriangulationCell&lt;TVertex&gt;, VoronoiEdge&lt;TVertex, DefaultTriangulationCell&lt;TVertex&gt;&gt;&gt;.</returns>
public static
VoronoiMesh
<TVertex, DefaultTriangulationCell<TVertex>, VoronoiEdge<TVertex, DefaultTriangulationCell<TVertex>>>
Create<TVertex>(IList<TVertex> data,
float PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
where TVertex : IVertex
{
return
VoronoiMesh
<TVertex, DefaultTriangulationCell<TVertex>, VoronoiEdge<TVertex, DefaultTriangulationCell<TVertex>>
>.Create(data, PlaneDistanceTolerance);
}
/// <summary>
/// Create the voronoi mesh.
/// </summary>
/// <param name="data">The data.</param>
/// <returns>VoronoiMesh&lt;DefaultVertex, DefaultTriangulationCell&lt;DefaultVertex&gt;, VoronoiEdge&lt;DefaultVertex, DefaultTriangulationCell&lt;DefaultVertex&gt;&gt;&gt;.</returns>
public static
VoronoiMesh
<DefaultVertex, DefaultTriangulationCell<DefaultVertex>,
VoronoiEdge<DefaultVertex, DefaultTriangulationCell<DefaultVertex>>>
Create(IList<float[]> data,
float PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
{
var points = data.Select(p => new DefaultVertex { Position = p.ToArray() }).ToList();
return
VoronoiMesh
<DefaultVertex, DefaultTriangulationCell<DefaultVertex>,
VoronoiEdge<DefaultVertex, DefaultTriangulationCell<DefaultVertex>>>.Create(points, PlaneDistanceTolerance);
}
/// <summary>
/// Create the voronoi mesh.
/// </summary>
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
/// <typeparam name="TCell">The type of the t cell.</typeparam>
/// <param name="data">The data.</param>
/// <returns>VoronoiMesh&lt;TVertex, TCell, VoronoiEdge&lt;TVertex, TCell&gt;&gt;.</returns>
public static VoronoiMesh<TVertex, TCell, VoronoiEdge<TVertex, TCell>> Create<TVertex, TCell>(
IList<TVertex> data,
float PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
where TVertex : IVertex
where TCell : TriangulationCell<TVertex, TCell>, new()
{
return VoronoiMesh<TVertex, TCell, VoronoiEdge<TVertex, TCell>>.Create(data, PlaneDistanceTolerance);
}
}
/// <summary>
/// A representation of a voronoi mesh.
/// </summary>
/// <typeparam name="TEdge">The type of the t edge.</typeparam>
/// <typeparam name="TVertex">The type of the t vertex.</typeparam>
/// <typeparam name="TCell">The type of the t cell.</typeparam>
public class VoronoiMesh<TVertex, TCell, TEdge>
where TCell : TriangulationCell<TVertex, TCell>, new()
where TVertex : IVertex
where TEdge : VoronoiEdge<TVertex, TCell>, new()
{
/// <summary>
/// Can only be created using a factory method.
/// </summary>
private VoronoiMesh()
{
}
/// <summary>
/// Vertices of the diagram.
/// </summary>
/// <value>The vertices.</value>
public IEnumerable<TCell> Vertices { get; private set; }
/// <summary>
/// Edges connecting the cells.
/// The same information can be retrieved Cells' Adjacency.
/// </summary>
/// <value>The edges.</value>
public IEnumerable<TEdge> Edges { get; private set; }
/// <summary>
/// Create a Voronoi diagram of the input data.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="PlaneDistanceTolerance">The plane distance tolerance (default is 1e-10). If too high, points
/// will be missed. If too low, the algorithm may break. Only adjust if you notice problems.</param>
/// <returns>VoronoiMesh&lt;TVertex, TCell, TEdge&gt;.</returns>
/// <exception cref="System.ArgumentNullException">data</exception>
/// <exception cref="ArgumentNullException">data</exception>
public static VoronoiMesh<TVertex, TCell, TEdge> Create(IList<TVertex> data,
float PlaneDistanceTolerance = Constants.DefaultPlaneDistanceTolerance)
{
if (data == null) throw new ArgumentNullException("data");
var t = DelaunayTriangulation<TVertex, TCell>.Create(data, PlaneDistanceTolerance);
var vertices = t.Cells.ToList();
var edges = new HashSet<TEdge>(new EdgeComparer());
foreach (var f in vertices)
{
for (var i = 0; i < f.Adjacency.Length; i++)
{
var af = f.Adjacency[i];
if (af != null) edges.Add(new TEdge { Source = f, Target = af });
}
}
return new VoronoiMesh<TVertex, TCell, TEdge>
{
Vertices = vertices,
Edges = edges.ToList()
};
}
/// <summary>
/// This is probably not needed, but might make things a tiny bit faster.
/// </summary>
/// <seealso cref="System.Collections.Generic.IEqualityComparer{TEdge}" />
private class EdgeComparer : IEqualityComparer<TEdge>
{
/// <summary>
/// Equals the specified x.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <returns>System.Boolean.</returns>
public bool Equals(TEdge x, TEdge y)
{
return (x.Source == y.Source && x.Target == y.Target) || (x.Source == y.Target && x.Target == y.Source);
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <param name="obj">The <see cref="T:System.Object" /> for which a hash code is to be returned.</param>
/// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
public int GetHashCode(TEdge obj)
{
return obj.Source.GetHashCode() ^ obj.Target.GetHashCode();
}
}
}
}

View file

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: fbb5750f20479844eb4e504302755db9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,34 +0,0 @@
using System;
using System.Collections;
using MIConvexHull;
using CultMath;
using static CultMath.math;
public class Vertex2 : IVertex
{
public float[] Position => new[] {StoredPosition.x, StoredPosition.y};
public float2 StoredPosition;
public float x { get { return StoredPosition.x; } }
public float y { get { return StoredPosition.y; } }
public Vertex2(float x, float y)
{
StoredPosition = float2(x, y);
}
public Vertex2(float2 pos)
{
StoredPosition = pos;
}
public float2 ToFloat2() {
return StoredPosition;
}
public float Distance(Vertex2 v)
{
return length(StoredPosition-v.StoredPosition);
}
}

View file

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 67d3ec22ea52a2642a14ff864e3017b0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,16 +0,0 @@
using CultMath;
public class Vertex2<T> : Vertex2
{
public T StoredObject { get; }
public Vertex2(float x, float y, T obj) : base(x, y)
{
StoredObject = obj;
}
public Vertex2(float2 pos, T obj) : base(pos)
{
StoredObject = obj;
}
}

View file

@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: e42612a273ec490380eaa67bed216a6d
timeCreated: 1615418804

View file

@ -1,30 +0,0 @@
using System.Collections;
using MIConvexHull;
using CultMath;
using static CultMath.math;
public class Vertex3 : IVertex
{
public float[] Position => new[] {StoredPosition.x, StoredPosition.y};
public float3 StoredPosition;
public Vertex3(float x, float y, float z)
{
StoredPosition = float3(x, y, z);
}
public Vertex3(float3 pos)
{
StoredPosition = pos;
}
public float3 ToFloat3() {
return StoredPosition;
}
public float Distance(Vertex3 v)
{
return length(StoredPosition-v.StoredPosition);
}
}

View file

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 3553f231414f28347996a803a79425fa
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -10,7 +10,7 @@ using static CultMath.math;
public class PlayerSettings
{
[Key(0)] public string Name = "Anonymous";
[Key(2)] public bool TutorialPassed;
// Keys 1 and 2 are retired; an older player.cc that still carries them loads, and they are dropped.
[Key(3)] public Dictionary<string, string> HashedStoryFiles = new Dictionary<string, string>();
[Key(4)] public PlayerGameplaySettings GameplaySettings = new PlayerGameplaySettings();
[Key(5)] public PlayerInputSettings InputSettings = new PlayerInputSettings();

View file

@ -92,6 +92,16 @@ public class PowerBus
public Draw(EquippedItem item, int tier, float request) { Item = item; Tier = tier; Request = request; }
}
private static bool ClosedByThermostat(EquippedItem item, Behavior consumer)
{
foreach (var behavior in item.BehaviorGroups[consumer.Data.Group].Behaviors)
{
if (behavior == consumer) return false;
if (behavior is Thermotoggle { Open: false }) return true;
}
return false;
}
public void Step(float dt)
{
var reactors = new List<Reactor>();
@ -119,7 +129,9 @@ public class PowerBus
// The other direction of the same rule: a consumer switched off or shut down (Active.Value false)
// never runs its Execute, so it must never be billed either -- otherwise a disabled item's demand
// starves every live consumer and drains the capacitors for energy nobody spends.
if (behavior is IPowerConsumer consumer && item.Active.Value)
// And a consumer whose group a thermostat has closed ahead of it does not run this tick either, so it is
// not billed: a heater above its target draws nothing.
if (behavior is IPowerConsumer consumer && item.Active.Value && !ClosedByThermostat(item, behavior))
{
// Cut 5 (docs/stats-and-power-cut.md §1.3): the item's own stored choice wins once it has one;
// PowerTiers.Unassigned only survives past EquippedItem's constructor for a consumer added to

View file

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Random = CultMath.Random;
// The owner of a new run (docs/scenarios-cut.md, R.4). Every new run is a scenario: RunStart generates its galaxy,
// generates its arena (the galaxy's entrance zone) under the scenario's Ambient rule, and admits what the scenario
// stages through Zone.Admit, all of it or none of it. A scenario only declares; nothing else generates a new run's
// galaxy, generates or admits its player, or chooses its hull or faction. It holds no Unity type.
public static class RunStart
{
public sealed class Staged
{
public Ship Player;
public List<Entity> Entities; // what the scenario placed besides the player, in its order
}
// The scenario's galaxy, at the scenario's seed or, when that is zero, the clock's.
public static Galaxy Generate(Scenario scenario, GalaxyStage stage)
{
stage.SeedFrom(scenario);
return scenario.Generate(stage) ?? throw new InvalidOperationException($"Scenario {scenario.Name} generated no galaxy.");
}
public static ZonePack GenerateArena(ItemManager itemManager, ZoneGenerationSettings zoneSettings, Galaxy galaxy, Scenario scenario)
{
SeedItems(itemManager, galaxy, 1);
return galaxy.Entrance.PackedContents = ZoneGenerator.GenerateZone(
itemManager, zoneSettings, galaxy, galaxy.Entrance, galaxy.IsPrelude, scenario.Ambient);
}
// Runs the scenario's Stage, then admits its player and everything it placed: each entity's stance set both ways
// with the player, a pilot for each piloted one. Returns null, with every failure listed and the arena unchanged,
// unless the whole scenario staged.
public static Staged Stage(ItemManager itemManager, Zone arena, Scenario scenario, string startingHull,
TutorialGenerationSettings tutorialGenerationSettings, List<string> failures)
{
SeedItems(itemManager, arena.Galaxy, 2);
var stage = new ScenarioStage(itemManager, arena, startingHull, tutorialGenerationSettings);
scenario.Stage(stage);
var reported = failures.Count;
failures.AddRange(stage.Failures);
if (!stage.PlayerPlaced)
failures.Add("player: the scenario places no player");
if (failures.Count > reported) return null;
var player = stage.PlayerShip;
player.IsPlayerShip = true;
arena.Admit(player, piloted: false);
foreach (var placed in stage.Placed)
{
var hostile = placed.Stance == ScenarioStance.Hostile;
placed.Entity.SetIff(player, hostile);
player.SetIff(placed.Entity, hostile);
arena.Admit(placed.Entity, placed.Piloted);
}
return new Staged { Player = player, Entities = stage.Placed.Select(placed => placed.Entity).ToList() };
}
// A new run's item draws (each lot's quality, each generated fit) come from its galaxy's seed, not the process clock,
// so a fixed seed fixes the arena's gear and the player's fit. Each step draws its own stream, so whatever runs
// between them (populating the level) cannot shift it.
private static void SeedItems(ItemManager itemManager, Galaxy galaxy, uint step) =>
itemManager.Random = new Random(galaxy.Seed * 0x9E3779B1u + step);
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 28412ed9a0fc4f95b157846b0b132c27

View file

@ -55,7 +55,7 @@ public static class RunSave
{
// The live run as plain documents. Writes nothing.
public static (SavedGame Game, SavedZone[] Zones) Capture(CultCache cache, Galaxy galaxy, Zone currentZone,
Entity currentEntity, bool isTutorial, SavedActionBarBinding[] actionBar)
Entity currentEntity, SavedActionBarBinding[] actionBar)
{
var factions = galaxy.HomeZones.Keys.ToArray();
var game = new SavedGame
@ -74,7 +74,7 @@ public static class RunSave
CurrentZoneEntity = currentZone.Entities.IndexOf(currentEntity),
Entrance = Array.IndexOf(galaxy.Zones, galaxy.Entrance),
Exit = Array.IndexOf(galaxy.Zones, galaxy.Exit),
IsTutorial = isTutorial,
IsTutorial = galaxy.IsPrelude,
ActionBarBindings = actionBar
};
@ -91,6 +91,39 @@ public static class RunSave
return (game, zones);
}
// Continue's gate: every design a saved run names (each zone's items and each minted lot) must be one this catalog
// holds. A run made with a mod that is no longer installed is refused, naming the mod ships, before any scene is
// built; the save is never edited to fit.
public static void RequireDesigns(CultCache cache, SavedGame game)
{
var designs = new List<CultRecordKey>();
foreach (var zoneRef in game.Zones ?? Array.Empty<CultRecordRef<SavedZone>>())
{
var where = zoneRef.Key.Value;
var zone = cache.Get(zoneRef) ?? throw MalformedSave($"zone {where} has no record");
// A zone never visited has no contents: legitimately null.
foreach (var pack in zone.Contents?.Entities ?? new List<EntityPack>())
foreach (var item in EntitySerializer.Items(pack))
designs.Add((item ?? throw MalformedSave($"an item in {where} is null")).Data.Key);
}
foreach (var (number, lot) in Lots(cache).Lots ?? throw MalformedSave("the lot ledger has no lots"))
designs.Add((lot ?? throw MalformedSave($"lot {number} is null")).Design.Key);
var named = designs.Where(key => key.IsSet()).Distinct()
.Where(key => cache.Get<ItemData>(key) == null)
.Select(key => key.Value).OrderBy(key => key, StringComparer.Ordinal).ToArray();
if (named.Length == 0) return;
const string modHull = "mod-hull:";
var mods = named.Where(key => key.StartsWith(modHull, StringComparison.Ordinal)).Select(key => key.Substring(modHull.Length)).ToArray();
var others = named.Where(key => !key.StartsWith(modHull, StringComparison.Ordinal)).ToArray();
throw new InvalidOperationException("This run names designs the catalog no longer holds" +
(mods.Length > 0 ? $"; missing mod ships: {string.Join(", ", mods)}" : "") +
(others.Length > 0 ? $"; missing other designs: {string.Join(", ", others)}" : "") +
". Reinstall them, or start a new game.");
}
private static InvalidOperationException MalformedSave(string where) =>
new InvalidOperationException($"This run's save is malformed: {where}. Start a new game.");
// The stored ledger, or a fresh empty one when the run has minted nothing yet.
public static ProvenanceLedger Lots(CultCache cache) => cache.GetGlobal<ProvenanceLedger>() ?? new ProvenanceLedger();
@ -122,17 +155,37 @@ public static class RunSave
}
// Removes every run record (SavedGame, SavedZone, OrbitData, BodyData, ProvenanceLedger) in one Commit.
public static void Clear(CultCache cache)
public static void Clear(CultCache cache) => Remove(cache, Records(cache));
// A new run replaces the saved one only once it has started: start runs with the saved run still in the store.
// When it returns a value, the saved run's records go. When it returns null or throws, the records it wrote go and
// the saved run stays as it was.
public static T Replace<T>(CultCache cache, Func<T> start) where T : class
{
var run = cache.AllStoredDocuments
var saved = Records(cache);
T started = null;
try
{
started = start();
}
finally
{
Remove(cache, started != null ? saved : Records(cache).Except(saved).ToArray());
}
return started;
}
private static CultRecordKey[] Records(CultCache cache) =>
cache.AllStoredDocuments
.Where(stored => IsRunRecord(stored.Descriptor.DocumentType))
.Select(stored => stored.Key)
.ToArray();
private static void Remove(CultCache cache, CultRecordKey[] records) =>
cache.Commit(batch =>
{
foreach (var key in run) batch.Remove(key);
foreach (var key in records) batch.Remove(key);
});
}
public static bool IsRunRecord(Type documentType) =>
AetheriaStores.RunTypes.Any(home => home.IsAssignableFrom(documentType));

View file

@ -0,0 +1,32 @@
// A scenario is one way to set up a new run (docs/scenarios-cut.md, R): a script, compiled with the game, that says
// which galaxy to generate and what the run starts with. New Game lists them (Scenarios). RunStart runs one: it
// generates the galaxy through GalaxyStage, the arena under Ambient, and admits what Stage placed through a
// ScenarioStage. A scenario only declares; once staged, everything it placed is ordinary run state.
public abstract class Scenario
{
public abstract string Name { get; }
// The conditions and what to verify in them, shown under the scenario's button.
public abstract string Brief { get; }
// Zero draws the seed from the clock, so each launch is a new galaxy. Anything else fixes the galaxy, its
// background, its arena and every fit, each item's maker and workmanship included, so every launch has the same
// layout.
public virtual uint Seed => 0;
// False: the arena keeps its planets, orbits and stations but generates no ship or turret, so nothing wanders into
// the scenario's conditions.
public virtual bool Ambient => true;
// Which galaxy the run is in: stage.Main() or stage.Prelude().
public abstract Galaxy Generate(GalaxyStage stage);
// What the run starts with: exactly one stage.Player, and anything else the scenario places.
public abstract void Stage(ScenarioStage stage);
}
public enum ScenarioStance
{
Neutral,
Hostile
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: da26f6b6c5f34deaa1057177e2dd3262

View file

@ -0,0 +1,168 @@
using System;
using System.Collections.Generic;
using System.Linq;
using CultMath;
using static CultMath.math;
using float2 = CultMath.float2;
using float3 = CultMath.float3;
// The run half of a scenario's vocabulary (docs/scenarios-cut.md, R.4). A scenario's Stage builds its fits and places
// them here; nothing joins the arena until Stage returns with no failure, and then RunStart admits it all at once.
// Every verb names what it could not do instead of throwing, so one bad name in a script lists every bad name.
// Designs and hulls are named as the catalog names them. Only RunStart builds a stage.
public sealed class ScenarioStage
{
private readonly ItemManager _items;
private readonly Predicate<FactionProductData> _available;
private readonly List<string> _failures = new List<string>();
private readonly List<Placement> _placed = new List<Placement>();
private int _placements;
internal ScenarioStage(ItemManager items, Zone arena, string startingHull, TutorialGenerationSettings tutorialGenerationSettings)
{
_items = items;
Arena = arena;
StartingHull = startingHull;
TutorialGenerationSettings = tutorialGenerationSettings;
// A fit names designs, not manufacturers, so what the galaxy offers decides which product builds each one.
_available = new LoadoutGenerator(ref items.Random, items, arena.Galaxy, arena.GalaxyZone, null, 2).IsAvailable;
}
public Galaxy Galaxy => Arena.Galaxy;
public Zone Arena { get; }
public string StartingHull { get; }
public TutorialGenerationSettings TutorialGenerationSettings { get; }
internal IReadOnlyList<string> Failures => _failures;
internal bool PlayerPlaced { get; private set; }
internal Ship PlayerShip { get; private set; }
internal IReadOnlyList<Placement> Placed => _placed;
internal sealed class Placement
{
public Entity Entity;
public ScenarioStance Stance;
public bool Piloted;
}
// A hull fitted slot by slot: each slot a design, the hull cell it goes in, and its rotation.
public ScenarioFit Fit(string hull, params (string design, int2 cell, ItemRotation rotation)[] slots)
{
var where = $"fit {hull}";
var hullData = Named<HullData>(hull, where);
var loadout = new Loadout { Name = hull, WeaponGroups = new int[0][] };
if (hullData != null) loadout.Hull = _items.ItemData.RefOf(hullData);
foreach (var (design, cell, rotation) in slots)
{
var data = Named<EquippableItemData>(design, where);
if (data == null) continue;
loadout.Slots.Add(new LoadoutSlot { Design = _items.ItemData.RefOf(data), Position = cell, Rotation = rotation });
}
return hullData != null && loadout.Slots.Count == slots.Length ? new ScenarioFit(loadout) : null;
}
// A hull with nothing fitted.
public ScenarioFit Bare(string hull) => Fit(hull);
// A fit generated as the game generates its ships, for the faction when one is given, from the run's item draws,
// which RunStart seeds from the galaxy's seed. An empty hull means any ship hull.
public ScenarioFit Generated(string hull, Faction faction = null)
{
var generator = new LoadoutGenerator(ref _items.Random, _items, Galaxy, Arena.GalaxyZone, faction, 2);
var pack = generator.GenerateShipLoadout(data => string.IsNullOrEmpty(hull) || data.Name == hull);
if (pack != null) return new ScenarioFit(pack);
_failures.Add($"generated: no ship hull named {hull}");
return null;
}
// A loadout preset from the catalog, as capturepreset or Studio wrote it.
public ScenarioFit Preset(string name)
{
var preset = _items.ItemData.GetAll<Loadout>().FirstOrDefault(loadout => loadout.Name == name);
if (preset != null) return new ScenarioFit(preset);
_failures.Add($"preset {name}: no such preset");
return null;
}
// The player's ship. A run has exactly one, and it is a ship hull.
public Ship Player(ScenarioFit fit, float2 at, float2 facing = default)
{
if (PlayerPlaced)
{
_failures.Add("player: the scenario places a second player");
return null;
}
PlayerPlaced = true;
var entity = Build(fit, "player", at, facing);
if (entity == null) return null;
if (entity is Ship ship) return PlayerShip = ship;
_failures.Add($"player: {entity.Name} is not a ship hull");
return null;
}
// Anything else in the arena. A stance holds both ways between it and the player. A piloted ship gets the zone's
// pilot; an unpiloted entity has none and goes nowhere on its own. A turret hull stays where it is put.
public Entity Place(ScenarioFit fit, float2 at, float2 facing = default, ScenarioStance stance = ScenarioStance.Neutral, bool piloted = false)
{
var where = $"entity {_placements++}";
var entity = Build(fit, where, at, facing);
if (entity == null) return null;
if (piloted && !(entity is Ship)) _failures.Add($"{where}: {entity.Name} is not a ship hull, so it cannot be piloted");
_placed.Add(new Placement { Entity = entity, Stance = stance, Piloted = piloted });
return entity;
}
// Items in the entity's first cargo bay, one per design named.
public void Cargo(Entity entity, params string[] designs)
{
if (entity == null) return;
var where = $"cargo of {entity.Name}";
var bay = entity.CargoBays.FirstOrDefault();
foreach (var design in designs)
{
var data = Named<EquippableItemData>(design, where);
if (data == null) continue;
var build = Loadouts.Resolve(_items, _items.ItemData.RefOf(data), _available, where, _failures);
if (build != null && (bay == null || !bay.TryStore(build())))
_failures.Add($"{where}: no room for {design}");
}
}
private Entity Build(ScenarioFit fit, string where, float2 at, float2 facing)
{
if (fit == null) return null; // the verb that made it named why
Entity entity;
if (fit.Pack != null) entity = EntitySerializer.Unpack(_items, Arena, fit.Pack);
else
{
var failures = new List<string>();
entity = Loadouts.Materialize(_items, Arena, fit.Loadout, _available, failures);
_failures.AddRange(failures.Select(failure => $"{where} ({fit.Loadout.Name}): {failure}"));
if (entity == null) return null;
}
entity.Position = float3(at.x, 0, at.y);
if (lengthsq(facing) > 0) entity.Direction = normalize(facing);
return entity;
}
private T Named<T>(string name, string where) where T : EquippableItemData
{
var named = _items.ItemData.GetAll<T>().Where(data => data.Name == name).Take(2).ToArray();
if (named.Length == 1) return named[0];
_failures.Add(named.Length == 0 ? $"{where}: no design named {name}" : $"{where}: more than one design is named {name}");
return null;
}
}
// What a scenario places: a fit built from named designs or a preset, or a ship generated as the game generates them.
// Only ScenarioStage makes one.
public sealed class ScenarioFit
{
internal readonly Loadout Loadout;
internal readonly EntityPack Pack;
internal ScenarioFit(Loadout loadout) => Loadout = loadout;
internal ScenarioFit(EntityPack pack) => Pack = pack;
}

View file

@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: adf902e96e0c51049b65bc002d6ef4ca
guid: d8cd00dc23604dfb91e128e1a9a4a3d5
MonoImporter:
externalObjects: {}
serializedVersion: 2

View file

@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 4a109a0b0bb6e8f40935ca2ec55e5bd7
guid: 35866d82219241ae9fdb0030039afbed
folderAsset: yes
DefaultImporter:
externalObjects: {}

View file

@ -0,0 +1,46 @@
using static CultMath.math;
using static ItemRotation;
public sealed class Arcs : Scenario
{
public override string Name => "Arcs";
public override string Brief => "Forward mounts, a bare hull off the bow, one off the stern, a hostile turret. Verify: the bow " +
"hull can be hit, nothing fires at the stern one through the ship, the turret tracks you all the way round.";
public override uint Seed => 103;
public override bool Ambient => false;
// Where the targets sit: the player is at the origin facing +z, and every mount fires forward.
public static readonly CultMath.float2 Bow = float2(0, 400), Stern = float2(0, -400), Turret = float2(600, 0);
public override Galaxy Generate(GalaxyStage stage) => stage.Prelude();
public override void Stage(ScenarioStage stage)
{
var fighter = stage.Fit("LonginusX",
("Cockpit 2x2", int2(2, 6), None),
("Traction", int2(2, 3), None),
("Core Power", int2(2, 1), None),
("GT 3K", int2(0, 5), None),
("GT 3K", int2(5, 5), None),
("FastBlast+-", int2(1, 8), None),
("FastBlast+-", int2(4, 8), None),
("Iapyx", int2(1, 2), CounterClockwise),
("Iapyx", int2(4, 2), Clockwise),
("not if i see you first", int2(3, 10), None),
("Fire Control Array", int2(2, 5), None));
var turret = stage.Fit("Turret",
("ClearPath", int2(1, 2), None),
("ClearPath", int2(5, 2), None),
("Skiron", int2(0, 2), CounterClockwise),
("Skiron", int2(7, 2), Clockwise),
("Core Power", int2(3, 3), None),
("Turret Control Module", int2(3, 5), None),
("not if i see you first", int2(4, 5), None),
("Fire Control Array", int2(3, 6), None));
stage.Player(fighter, float2(0, 0), facing: float2(0, 1));
stage.Place(stage.Bare("LonginusX"), Bow);
stage.Place(stage.Bare("LonginusX"), Stern);
stage.Place(turret, Turret, stance: ScenarioStance.Hostile);
}
}

View file

@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 447289e858e19c14abbe91dfbd0e3089
guid: 724a07b881f34e8c9b32b3f2f338ac78
MonoImporter:
externalObjects: {}
serializedVersion: 2

View file

@ -0,0 +1,15 @@
using float2 = CultMath.float2;
public sealed class DjinniShakedown : Scenario
{
public override string Name => "Djinni Shakedown";
public override string Brief => "A fitted Djinni in empty space. Verify: its thrusters move and turn it; with the hull " +
"offline and thrusters firing, its speed does not run away.";
public override uint Seed => 101;
public override bool Ambient => false;
public override Galaxy Generate(GalaxyStage stage) => stage.Prelude();
public override void Stage(ScenarioStage stage) =>
stage.Player(stage.Generated("Djinni"), float2.zero);
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1afb559630c241ed813ddd3c444c618b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

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