RynthSuite as of 2026-09-05 (internal a5ff5c2)

A snapshot of the working tree for aelrynth.com/git/: the code, build files
and public docs. Internal review notes and agent instructions are left out.
MIT licensed; see LICENSE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tom Bohar 2026-09-25 21:23:05 -04:00
commit 0a4b611a90
166 changed files with 186537 additions and 0 deletions

View file

@ -0,0 +1,199 @@
namespace RynthCore.Loot;
/// <summary>
/// AC object classes. Values match VTank / Decal ObjectClass enum exactly
/// so that meta expressions, loot profiles, and wobjectgetobjectclass[]
/// return the same numbers players expect from UB/VTank.
/// </summary>
public enum AcObjectClass
{
Unknown = 0,
MeleeWeapon = 1,
Armor = 2,
Clothing = 3,
Jewelry = 4,
Monster = 5,
Food = 6,
Money = 7,
Misc = 8,
MissileWeapon = 9,
Container = 10,
Gem = 11,
SpellComponent = 12,
Key = 13,
Portal = 14,
TradeNote = 15,
ManaStone = 16,
Plant = 17,
BaseCooking = 18,
BaseAlchemy = 19,
BaseFletching = 20,
CraftedCooking = 21,
CraftedAlchemy = 22,
CraftedFletching = 23,
Player = 24,
Vendor = 25,
Door = 26,
Corpse = 27,
Lifestone = 28,
HealingKit = 29,
Lockpick = 30,
WandStaffOrb = 31,
Bundle = 32,
Book = 33,
Journal = 34,
Sign = 35,
Housing = 36,
Npc = 37,
Foci = 38,
Salvage = 39,
Ust = 40,
Services = 41,
Scroll = 42,
CombatPet = 43,
}
/// <summary>
/// Loot-relevant integer item properties. Values match Chorizite STypeInt sequential enum
/// (UNDEF=0, ITEM_TYPE=1, …). Cast to int when calling item.Values(key, 0).
/// </summary>
public enum AcIntProperty
{
ArmorLevel = 28, // ARMOR_LEVEL
Burden = 5, // ENCUMB_VAL — encumbrance units
CombatUse = 51, // COMBAT_USE — melee/missile/magic/shield
CurrentMana = 107, // ITEM_CUR_MANA
Damage = 44, // DAMAGE — base weapon damage
DamageType = 45, // DAMAGE_TYPE — slash/pierce/blunt/…
EquipSlots = 9, // LOCATIONS — equippable slot bits
ImbuedEffect = 179, // IMBUED_EFFECT — imbue type bitfield
ItemType = 1, // ITEM_TYPE — item category enum
LootTier = 263, // RESISTANCE_MODIFIER_TYPE — loot tier 1–7
MaterialType = 131, // MATERIAL_TYPE
MaxMana = 108, // ITEM_MAX_MANA
MaxStructure = 91, // MAX_STRUCTURE — item max charges (pet-device essence)
NumSockets = 177, // GEM_COUNT
NumTimesTinkered = 171, // NUM_TIMES_TINKERED
Spellcraft = 106, // ITEM_SPELLCRAFT
Structure = 92, // STRUCTURE — item remaining charges (pet-device essence)
Value = 19, // VALUE — pyreal sell value
WeaponSkill = 48, // WEAPON_SKILL — skill enum used to wield
WieldDifficulty = 160, // WIELD_DIFFICULTY — skill level required
WieldedSlot = 10, // CURRENT_WIELDED_LOCATION
WieldRequirements = 158, // WIELD_REQUIREMENTS — req type enum
WieldSkillType = 159, // WIELD_SKILLTYPE — skill type required
Workmanship = 105, // ITEM_WORKMANSHIP
}
/// <summary>
/// Loot-relevant float item properties. Values match Chorizite STypeFloat sequential enum
/// (UNDEF=0, HEARTBEAT_INTERVAL=1, …). Cast to int when calling item.Values(key, 0.0).
/// </summary>
public enum AcFloatProperty
{
AcidProtMod = 18, // ARMOR_MOD_VS_ACID
AttackBonus = 61, // WEAPON_OFFENSE — attack bonus %
BluntProtMod = 15, // ARMOR_MOD_VS_BLUDGEON
ColdProtMod = 16, // ARMOR_MOD_VS_COLD
DamageMod = 62, // DAMAGE_MOD — damage bonus %
DamageVariance = 22, // DAMAGE_VARIANCE
DefenseBonus = 29, // WEAPON_DEFENSE — melee defense bonus %
ElectricProtMod = 19, // ARMOR_MOD_VS_ELECTRIC
ElementalDamageMod = 152, // ELEMENTAL_DAMAGE_MOD
FireProtMod = 17, // ARMOR_MOD_VS_FIRE
MagicDefBonus = 150, // WEAPON_MAGIC_DEFENSE
ManaConvMod = 143, // MANA_CONVERSION_MOD
MissileDefBonus = 149, // WEAPON_MISSILE_DEFENSE
NetherProtMod = 165, // ARMOR_MOD_VS_NETHER
PierceProtMod = 14, // ARMOR_MOD_VS_PIERCE
SlashProtMod = 13, // ARMOR_MOD_VS_SLASH
SlayerDamageBonus = 137, // SLAYER_DAMAGE_BONUS
}
/// <summary>AC material types. Integer values match the live acclient.exe property table.</summary>
public enum AcMaterialType
{
Agate = 10,
Alabaster = 66,
Amber = 11,
Amethyst = 12,
Aquamarine = 13,
ArmoredilloHide = 53,
Azurite = 14,
Brass = 57,
Bronze = 58,
Carnelian = 18,
Ceramic = 1,
Citrine = 19,
Copper = 59,
Diamond = 20,
Ebony = 73,
Emerald = 21,
FireOpal = 22,
Gold = 60,
Granite = 67,
GreenGarnet = 23,
GreenJade = 24,
GromnieHide = 54,
Hematite = 25,
ImperialTopaz = 26,
Iron = 61,
Ivory = 51,
Jet = 27,
LapisLazuli = 28,
LavenderJade = 29,
Leather = 52,
Linen = 4,
Mahogany = 74,
Malachite = 30,
Marble = 68,
Moonstone = 31,
Oak = 75,
Obsidian = 69,
Onyx = 32,
Opal = 33,
Peridot = 34,
Pine = 76,
Porcelain = 2,
Pyreal = 62,
RedGarnet = 35,
RedJade = 36,
ReedSharkHide = 55,
RoseQuartz = 37,
Ruby = 38,
Sandstone = 70,
Sapphire = 39,
Satin = 5,
Serpentine = 71,
Silk = 6,
Silver = 63,
SmokeyQuartz = 40,
Steel = 64,
Sunstone = 41,
Teak = 77,
TigerEye = 42,
Tourmaline = 43,
Turquoise = 44,
Velvet = 7,
WhiteJade = 45,
WhiteQuartz = 46,
WhiteSapphire = 47,
Wool = 8,
YellowGarnet = 48,
YellowTopaz = 49,
Zircon = 50,
}
/// <summary>AC skill types. Matches Chorizite STypeSkill sequential enum.</summary>
public enum AcSkillType
{
Unknown = 0,
MeleeDefense, MissileDefense, MagicDefense,
ItemEnchantment, LifeMagic, CreatureEnchantment, WarMagic, VoidMagic,
HeavyWeapons, LightWeapons, FinesseWeapons, TwoHandedCombat,
Shield, DualWield, Recklessness, SneakAttack, DirtyFighting,
ArcaneLore, ArmorTinkering, ItemTinkering, MagicItemTinkering, WeaponTinkering,
Salvaging, Run, Jump, Loyalty, Leadership, Deception,
Healing, Lockpick, Cooking, Fletching, Alchemy, ManaConversion,
AssessCreature, AssessPerson, Summoning,
}

View file

@ -0,0 +1,157 @@
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace RynthCore.Loot;
// ── Actions ───────────────────────────────────────────────────────────────────
public enum LootAction
{
Keep,
Sell,
Salvage,
Read,
KeepUpTo, // "Keep #" — keep at most LootRule.KeepCount in inventory
}
// ── Condition base ────────────────────────────────────────────────────────────
[JsonPolymorphic(TypeDiscriminatorPropertyName = "$t")]
[JsonDerivedType(typeof(ObjectClassCondition), "ObjectClass")]
[JsonDerivedType(typeof(LongValKeyGECondition), "LongGE")]
[JsonDerivedType(typeof(LongValKeyLECondition), "LongLE")]
[JsonDerivedType(typeof(LongValKeyECondition), "LongE")]
[JsonDerivedType(typeof(LongValKeyNECondition), "LongNE")]
[JsonDerivedType(typeof(LongValKeyFlagCondition), "LongFlag")]
[JsonDerivedType(typeof(DoubleValKeyGECondition), "DoubleGE")]
[JsonDerivedType(typeof(DoubleValKeyLECondition), "DoubleLE")]
[JsonDerivedType(typeof(StringValueCondition), "String")]
[JsonDerivedType(typeof(TotalRatingsGECondition), "TotalRatingsGE")]
[JsonDerivedType(typeof(MinDamageGECondition), "MinDamageGE")]
[JsonDerivedType(typeof(DamagePercentGECondition), "DmgPctGE")]
[JsonDerivedType(typeof(CharacterSkillGECondition), "SkillGE")]
public abstract class LootCondition { }
// ── ObjectClass ───────────────────────────────────────────────────────────────
public sealed class ObjectClassCondition : LootCondition
{
public AcObjectClass ObjectClass { get; set; }
public override string ToString() => $"ObjectClass == {ObjectClass}";
}
// ── LongValKey ────────────────────────────────────────────────────────────────
public sealed class LongValKeyGECondition : LootCondition { public int Key { get; set; } public int Value { get; set; } public override string ToString() => $"LongKey[{Key}] >= {Value}"; }
public sealed class LongValKeyLECondition : LootCondition { public int Key { get; set; } public int Value { get; set; } public override string ToString() => $"LongKey[{Key}] <= {Value}"; }
public sealed class LongValKeyECondition : LootCondition { public int Key { get; set; } public int Value { get; set; } public override string ToString() => $"LongKey[{Key}] == {Value}"; }
public sealed class LongValKeyNECondition : LootCondition { public int Key { get; set; } public int Value { get; set; } public override string ToString() => $"LongKey[{Key}] != {Value}"; }
public sealed class LongValKeyFlagCondition : LootCondition { public int Key { get; set; } public int FlagValue { get; set; } public override string ToString() => $"LongKey[{Key}] has flag {FlagValue}"; }
// ── DoubleValKey ──────────────────────────────────────────────────────────────
public sealed class DoubleValKeyGECondition : LootCondition { public int Key { get; set; } public double Value { get; set; } public override string ToString() => $"DoubleKey[{Key}] >= {Value}"; }
public sealed class DoubleValKeyLECondition : LootCondition { public int Key { get; set; } public double Value { get; set; } public override string ToString() => $"DoubleKey[{Key}] <= {Value}"; }
// ── StringValue ───────────────────────────────────────────────────────────────
public sealed class StringValueCondition : LootCondition
{
public int Key { get; set; }
public string Pattern { get; set; } = "";
public override string ToString() => $"StringKey[{Key}] matches \"{Pattern}\"";
}
// ── Computed ──────────────────────────────────────────────────────────────────
public sealed class TotalRatingsGECondition : LootCondition { public int Value { get; set; } public override string ToString() => $"TotalRatings >= {Value}"; }
public sealed class MinDamageGECondition : LootCondition { public double Value { get; set; } public override string ToString() => $"MinDamage >= {Value}"; }
public sealed class DamagePercentGECondition : LootCondition { public double Value { get; set; } public override string ToString() => $"DamagePercent >= {Value}"; }
// ── Character ─────────────────────────────────────────────────────────────────
public sealed class CharacterSkillGECondition : LootCondition
{
public AcSkillType Skill { get; set; }
public int Value { get; set; }
public override string ToString() => $"Skill {Skill} >= {Value}";
}
// ── Rule ──────────────────────────────────────────────────────────────────────
public sealed class LootRule : System.ComponentModel.INotifyPropertyChanged
{
public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged;
private string _name = "";
public string Name
{
get => _name;
set { _name = value; PropertyChanged?.Invoke(this, new(nameof(Name))); }
}
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.Never)]
public bool Enabled { get; set; } = true;
public LootAction Action { get; set; } = LootAction.Keep;
public int KeepCount { get; set; } = 1;
public List<LootCondition> Conditions { get; set; } = new();
}
// ── Profile ───────────────────────────────────────────────────────────────────
public sealed class LootProfile
{
public string Name { get; set; } = "";
/// <summary>Rules evaluated top-to-bottom. First match wins.</summary>
public List<LootRule> Rules { get; set; } = new();
/// <summary>
/// Optional per-material salvage combine rules — see SalvageCombineSettings.
/// When null or Enabled=false, salvage combine falls back to material-only
/// grouping (combine any same-material under-full bags regardless of WM).
/// </summary>
public SalvageCombineSettings? SalvageCombine { get; set; }
// ── Persistence ──────────────────────────────────────────────────────────
public void Save(string path)
{
string json = JsonSerializer.Serialize(this, LootJsonContext.Default.LootProfile);
File.WriteAllText(path, json);
}
public static LootProfile Load(string path)
{
string json = File.ReadAllText(path);
return JsonSerializer.Deserialize(json, LootJsonContext.Default.LootProfile)
?? new LootProfile();
}
public static LootProfile? TryLoad(string path)
{
if (!File.Exists(path)) return null;
try
{
string json = File.ReadAllText(path);
return JsonSerializer.Deserialize(json, LootJsonContext.Default.LootProfile);
}
catch
{
return null;
}
}
}
// ── JSON source-gen context ───────────────────────────────────────────────────
[JsonSourceGenerationOptions(
WriteIndented = true,
UseStringEnumConverter = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault)]
[JsonSerializable(typeof(LootProfile))]
[JsonSerializable(typeof(SalvageCombineSettings))]
public sealed partial class LootJsonContext : JsonSerializerContext { }

View file

@ -0,0 +1,45 @@
using System.Collections.Generic;
namespace RynthCore.Loot;
/// <summary>
/// AC MaterialType id → human name. Used by the loot editor to populate the
/// per-material combine grid. IDs are the same values returned by AC's
/// MATERIAL_TYPE int property (STypeInt 131).
/// </summary>
public static class MaterialTypes
{
public static readonly IReadOnlyDictionary<int, string> ByName = BuildMap();
private static Dictionary<int, string> BuildMap() => new()
{
{ 1, "Ceramic" }, { 2, "Porcelain" },
{ 3, "Cloth" }, { 4, "Linen" }, { 5, "Satin" },
{ 6, "Silk" }, { 7, "Velvet" }, { 8, "Wool" },
{ 9, "Gem" }, { 10, "Agate" }, { 11, "Amber" },
{ 12, "Amethyst" }, { 13, "Aquamarine" }, { 14, "Azurite" },
{ 15, "Black Garnet" }, { 16, "Black Opal" }, { 17, "Bloodstone" },
{ 18, "Carnelian" }, { 19, "Citrine" }, { 20, "Diamond" },
{ 21, "Emerald" }, { 22, "Fire Opal" }, { 23, "Green Garnet" },
{ 24, "Green Jade" }, { 25, "Hematite" }, { 26, "Imperial Topaz" },
{ 27, "Jet" }, { 28, "Lapis Lazuli" }, { 29, "Lavender Jade" },
{ 30, "Malachite" }, { 31, "Moonstone" }, { 32, "Onyx" },
{ 33, "Opal" }, { 34, "Peridot" }, { 35, "Red Garnet" },
{ 36, "Red Jade" }, { 37, "Rose Quartz" }, { 38, "Ruby" },
{ 39, "Sapphire" }, { 40, "Smoky Quartz" }, { 41, "Sunstone" },
{ 42, "Tiger Eye" }, { 43, "Tourmaline" }, { 44, "Turquoise" },
{ 45, "White Jade" }, { 46, "White Quartz" }, { 47, "White Sapphire" },
{ 48, "Yellow Garnet" }, { 49, "Yellow Topaz" }, { 50, "Zircon" },
{ 51, "Ivory" }, { 52, "Leather" }, { 53, "Armoredillo Hide" },
{ 54, "Gromnie Hide" }, { 55, "Reedshark Hide" },{ 56, "Metal" },
{ 57, "Brass" }, { 58, "Bronze" }, { 59, "Copper" },
{ 60, "Gold" }, { 61, "Iron" }, { 62, "Pyreal" },
{ 63, "Silver" }, { 64, "Steel" }, { 65, "Stone" },
{ 66, "Alabaster" }, { 67, "Granite" }, { 68, "Marble" },
{ 69, "Obsidian" }, { 70, "Sandstone" }, { 71, "Serpentine" },
{ 72, "Wood" }, { 73, "Ebony" }, { 74, "Mahogany" },
{ 75, "Oak" }, { 76, "Pine" }, { 77, "Teak" },
};
public static string Name(int id) => ByName.TryGetValue(id, out string? n) ? n : $"Material#{id}";
}

View file

@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<RootNamespace>RynthCore.Loot</RootNamespace>
<AssemblyName>RynthCore.LootSdk</AssemblyName>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,70 @@
using System.Collections.Generic;
using System.Globalization;
namespace RynthCore.Loot;
/// <summary>
/// Per-material salvage combine bands, modeled after LootSnob/VTank's
/// SalvageCombine block. Bands describe which workmanship values may merge —
/// salvage bags only combine when they share both MaterialType and the same
/// band. Stored as raw strings (e.g. "1-6, 7-8, 9, 10") so the JSON file is
/// human-editable.
/// </summary>
public sealed class SalvageCombineSettings
{
public bool Enabled { get; set; } = true;
/// <summary>Default bands applied to materials with no per-material override.</summary>
public string DefaultBands { get; set; } = "1-6, 7-8, 9, 10";
/// <summary>Per-material override (key = MaterialType id, value = bands string).</summary>
public Dictionary<int, string> PerMaterial { get; set; } = new();
/// <summary>
/// First numeric line of VTank's SalvageCombine block — appears to be a
/// version or checksum value the client writes but the parser ignores.
/// Preserved verbatim so round-tripping a .utl file produces identical
/// bytes. New configs default to "0".
/// </summary>
public string RawVersion { get; set; } = "0";
/// <summary>
/// Returns the band key (e.g. "1-6") that contains the given workmanship
/// for the given material, or null if the workmanship falls outside every
/// configured band — which the caller should treat as do-not-combine.
/// </summary>
public string? GetBandKey(int materialId, int workmanship)
{
string raw = PerMaterial.TryGetValue(materialId, out string? perMat) ? perMat : DefaultBands;
foreach (var (min, max) in ParseBands(raw))
{
if (workmanship >= min && workmanship <= max)
return $"{min}-{max}";
}
return null;
}
/// <summary>Parses "1-6, 7-8, 9, 10" → [(1,6), (7,8), (9,9), (10,10)].</summary>
public static List<(int Min, int Max)> ParseBands(string? raw)
{
var result = new List<(int, int)>();
if (string.IsNullOrWhiteSpace(raw)) return result;
foreach (string part in raw.Split(','))
{
string p = part.Trim();
if (p.Length == 0) continue;
int dash = p.IndexOf('-');
if (dash > 0 && dash < p.Length - 1)
{
if (int.TryParse(p.Substring(0, dash).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int lo)
&& int.TryParse(p.Substring(dash + 1).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int hi))
result.Add((lo, hi));
}
else if (int.TryParse(p, NumberStyles.Integer, CultureInfo.InvariantCulture, out int v))
{
result.Add((v, v));
}
}
return result;
}
}

View file

@ -0,0 +1,184 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
namespace RynthCore.Loot.VTank;
/// <summary>
/// Reads a VTank/LootSnob ".utl" file into a VTankLootProfile. Pairs with
/// VTankLootWriter for full round-trip — parse + write of an unmodified file
/// produces identical bytes (modulo line endings, which are normalised to LF).
/// </summary>
public static class VTankLootParser
{
public static VTankLootProfile Load(string filePath)
{
if (!File.Exists(filePath)) return new VTankLootProfile();
return LoadFromText(File.ReadAllText(filePath));
}
public static VTankLootProfile LoadFromText(string text)
{
var profile = new VTankLootProfile();
// Split preserving every line as-is (no automatic newline conversion);
// we trim trailing CR so this works on both LF and CRLF source.
string[] lines = text.Split('\n');
for (int i = 0; i < lines.Length; i++)
if (lines[i].EndsWith("\r", StringComparison.Ordinal))
lines[i] = lines[i].Substring(0, lines[i].Length - 1);
if (lines.Length < 3)
throw new InvalidOperationException("Invalid UTL file: too short.");
int fileVersion;
int ruleCount;
int idx;
if (string.Equals(lines[0].Trim(), "UTL", StringComparison.Ordinal))
{
if (!int.TryParse(lines[1].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out fileVersion))
throw new InvalidOperationException("Invalid UTL file: bad version.");
if (!int.TryParse(lines[2].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out ruleCount))
throw new InvalidOperationException("Invalid UTL file: bad rule count.");
idx = 3;
}
else
{
if (!int.TryParse(lines[0].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out ruleCount))
throw new InvalidOperationException("Invalid UTL file: bad rule count.");
fileVersion = 0;
idx = 1;
}
profile.FileVersion = fileVersion;
bool v1Plus = fileVersion >= 1;
while (idx < lines.Length && profile.Rules.Count < ruleCount)
{
var rule = new VTankLootRule
{
Name = lines[idx++],
};
// v1+: custom expression line is ALWAYS present (may be blank).
if (v1Plus && idx < lines.Length)
rule.CustomExpression = lines[idx++];
if (idx >= lines.Length) break;
string infoLine = lines[idx++].Trim();
string[] parts = infoLine.Split(';');
if (parts.Length >= 1
&& int.TryParse(parts[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out int prio))
rule.Priority = prio;
if (parts.Length >= 2
&& int.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out int actionInt))
rule.Action = (VTankLootAction)actionInt;
// KeepUpTo carries its count on the next line.
if (rule.Action == VTankLootAction.KeepUpTo && idx < lines.Length)
{
if (int.TryParse(lines[idx].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int kc))
rule.KeepCount = kc;
idx++;
}
// Read each condition's data block.
for (int i = 2; i < parts.Length; i++)
{
if (!int.TryParse(parts[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out int nodeType))
continue;
string lengthCode = "0";
if (v1Plus && idx < lines.Length)
lengthCode = lines[idx++];
int dataLineCount = VTankNodeTypes.GetDataLineCount(nodeType);
var data = new List<string>();
if (dataLineCount < 0)
{
// Unknown type — slurp lines until we look like the start
// of the next rule. This mirrors the plugin's previous
// heuristic and at least keeps the bytes preserved.
while (idx < lines.Length && !IsStartOfNextRule(lines, idx, fileVersion))
data.Add(lines[idx++]);
}
else
{
for (int d = 0; d < dataLineCount && idx < lines.Length; d++)
data.Add(lines[idx++]);
}
rule.Conditions.Add(new VTankLootCondition(nodeType, lengthCode, data));
}
profile.Rules.Add(rule);
}
// Optional SalvageCombine block at the end.
while (idx < lines.Length)
{
if (string.Equals(lines[idx].Trim(), "SalvageCombine", StringComparison.OrdinalIgnoreCase))
{
idx++;
profile.SalvageCombine = ParseSalvageCombineBlock(lines, ref idx);
break;
}
idx++;
}
return profile;
}
private static SalvageCombineSettings ParseSalvageCombineBlock(string[] lines, ref int idx)
{
var cfg = new SalvageCombineSettings { DefaultBands = string.Empty };
if (idx >= lines.Length) return cfg;
cfg.RawVersion = lines[idx].Trim();
idx++;
if (idx < lines.Length
&& int.TryParse(lines[idx].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int en))
{ cfg.Enabled = en != 0; idx++; }
if (idx < lines.Length)
{ cfg.DefaultBands = lines[idx].Trim(); idx++; }
if (idx < lines.Length
&& int.TryParse(lines[idx].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n))
{
idx++;
for (int i = 0; i < n && idx + 1 < lines.Length; i++)
{
if (!int.TryParse(lines[idx].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int matId))
break;
idx++;
cfg.PerMaterial[matId] = lines[idx].Trim();
idx++;
}
}
return cfg;
}
/// <summary>
/// Heuristic boundary detection for unknown node types — true if the lines
/// starting at `index` could plausibly be a new rule (name + custom-expr +
/// info-line-with-semicolon).
/// </summary>
private static bool IsStartOfNextRule(string[] lines, int index, int fileVersion)
{
int infoOffset = fileVersion >= 1 ? 2 : 1;
if (index + infoOffset >= lines.Length) return false;
string infoLine = lines[index + infoOffset].Trim();
if (!infoLine.Contains(';')) return false;
string[] parts = infoLine.Split(';');
if (parts.Length < 2) return false;
return int.TryParse(parts[0].Trim(), out _)
&& int.TryParse(parts[1].Trim(), out _);
}
}

View file

@ -0,0 +1,118 @@
using System.Collections.Generic;
namespace RynthCore.Loot.VTank;
/// <summary>VTank loot rule action codes — the integer in the info line's second slot.</summary>
public enum VTankLootAction
{
Keep = 1,
Salvage = 2,
Sell = 3,
Read = 4,
KeepUpTo = 10,
}
/// <summary>One condition node attached to a VTank loot rule.</summary>
public sealed class VTankLootCondition
{
/// <summary>Node type id from VTank — see VTankNodeTypes for known values.</summary>
public int NodeType { get; set; }
/// <summary>
/// Raw v1+ length-code line preserved verbatim from the source file. The parser
/// doesn't actually use this value for anything, but it must be round-tripped
/// so the file is byte-stable. Empty string for v0 files.
/// </summary>
public string LengthCode { get; set; } = "0";
/// <summary>
/// Data lines for this condition, in VTank's documented order. Length
/// matches VTankNodeTypes.GetDataLineCount(NodeType) for known types; for
/// unknown types the parser collects raw lines until the next rule and
/// stuffs them all in here so save still emits identical bytes.
/// </summary>
public List<string> DataLines { get; set; } = new();
public VTankLootCondition() { }
public VTankLootCondition(int nodeType, string lengthCode, IEnumerable<string> dataLines)
{
NodeType = nodeType;
LengthCode = lengthCode;
DataLines = new List<string>(dataLines);
}
}
/// <summary>
/// Single VTank loot rule. Conditions are evaluated in order; ALL must match
/// for the rule's Action to fire (the standard "9999 DisabledRule" condition
/// returns false to disable a rule entirely).
/// </summary>
public sealed class VTankLootRule
{
/// <summary>Rule display name as shown in VTank's rule list.</summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// v1+ custom-expression line, always present in v1 files but typically
/// blank. Null for v0 files (the field doesn't exist there). Treated as a
/// pure passthrough — VTank evaluates it server-side via something like
/// CustomKeyExpression but our evaluator ignores it.
/// </summary>
public string? CustomExpression { get; set; }
/// <summary>
/// Priority — first slot of the info line. VTank uses priority for
/// rule ordering ties; we just preserve it.
/// </summary>
public int Priority { get; set; }
/// <summary>Loot action — second slot of the info line.</summary>
public VTankLootAction Action { get; set; } = VTankLootAction.Keep;
/// <summary>
/// Keep-count for the KeepUpTo action — null for every other action. Stored
/// on the line immediately after the info line in the source file.
/// </summary>
public int? KeepCount { get; set; }
/// <summary>Condition nodes; same order as the type list in the info line.</summary>
public List<VTankLootCondition> Conditions { get; set; } = new();
/// <summary>
/// Convenience — true when the rule has no DisabledRule (9999) condition or
/// that condition's payload is "false". Editors can flip this to add/remove
/// the DisabledRule node; the writer only emits the node when it's present.
/// </summary>
public bool Enabled
{
get
{
foreach (var c in Conditions)
if (c.NodeType == 9999 && c.DataLines.Count > 0
&& string.Equals(c.DataLines[0].Trim(), "true", System.StringComparison.OrdinalIgnoreCase))
return false;
return true;
}
set
{
// Ensure exactly one DisabledRule node when disabled, none when enabled.
for (int i = Conditions.Count - 1; i >= 0; i--)
if (Conditions[i].NodeType == 9999) Conditions.RemoveAt(i);
if (!value)
Conditions.Add(new VTankLootCondition(9999, "0", new[] { "true" }));
}
}
}
/// <summary>Top-level VTank loot profile.</summary>
public sealed class VTankLootProfile
{
/// <summary>0 for the legacy headerless format, 1+ for files prefixed with "UTL".</summary>
public int FileVersion { get; set; } = 1;
public List<VTankLootRule> Rules { get; set; } = new();
/// <summary>Optional SalvageCombine block at the end of the file.</summary>
public SalvageCombineSettings? SalvageCombine { get; set; }
}

View file

@ -0,0 +1,84 @@
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace RynthCore.Loot.VTank;
/// <summary>
/// Serializes a VTankLootProfile back to ".utl" text in VTank's exact format.
/// Pairs with VTankLootParser — round-tripping a parsed profile produces the
/// same logical content (line endings normalised to LF).
/// </summary>
public static class VTankLootWriter
{
public static void Save(VTankLootProfile profile, string filePath)
{
File.WriteAllText(filePath, Serialize(profile));
}
public static string Serialize(VTankLootProfile profile)
{
var sb = new StringBuilder();
bool v1Plus = profile.FileVersion >= 1;
if (v1Plus)
{
sb.Append("UTL\n");
sb.Append(profile.FileVersion.ToString(CultureInfo.InvariantCulture)).Append('\n');
}
sb.Append(profile.Rules.Count.ToString(CultureInfo.InvariantCulture)).Append('\n');
foreach (var rule in profile.Rules)
{
sb.Append(rule.Name).Append('\n');
if (v1Plus)
sb.Append(rule.CustomExpression ?? string.Empty).Append('\n');
sb.Append(BuildInfoLine(rule)).Append('\n');
if (rule.Action == VTankLootAction.KeepUpTo)
sb.Append((rule.KeepCount ?? 0).ToString(CultureInfo.InvariantCulture)).Append('\n');
foreach (var cond in rule.Conditions)
{
if (v1Plus)
sb.Append(cond.LengthCode ?? "0").Append('\n');
foreach (var line in cond.DataLines)
sb.Append(line ?? string.Empty).Append('\n');
}
}
if (profile.SalvageCombine != null)
{
sb.Append("SalvageCombine\n");
sb.Append(profile.SalvageCombine.RawVersion ?? "0").Append('\n'); // VTank version/checksum
sb.Append(profile.SalvageCombine.Enabled ? "1\n" : "0\n"); // enabled flag
sb.Append(profile.SalvageCombine.DefaultBands ?? string.Empty).Append('\n');
sb.Append(profile.SalvageCombine.PerMaterial.Count.ToString(CultureInfo.InvariantCulture)).Append('\n');
foreach (var kv in profile.SalvageCombine.PerMaterial)
{
sb.Append(kv.Key.ToString(CultureInfo.InvariantCulture)).Append('\n');
sb.Append(kv.Value ?? string.Empty).Append('\n');
}
sb.Append("0\n"); // terminator
}
return sb.ToString();
}
private static string BuildInfoLine(VTankLootRule rule)
{
var sb = new StringBuilder();
sb.Append(rule.Priority.ToString(CultureInfo.InvariantCulture));
sb.Append(';');
sb.Append(((int)rule.Action).ToString(CultureInfo.InvariantCulture));
foreach (var cond in rule.Conditions)
{
sb.Append(';');
sb.Append(cond.NodeType.ToString(CultureInfo.InvariantCulture));
}
return sb.ToString();
}
}

View file

@ -0,0 +1,132 @@
namespace RynthCore.Loot.VTank;
/// <summary>
/// Static metadata about VTank loot rule node (condition) types: id ↔ display
/// name, data-line arity, value semantics. Single source of truth for both the
/// parser/writer and the editor's typed UIs.
/// </summary>
public static class VTankNodeTypes
{
public const int SpellNameMatch = 0;
public const int StringValueMatch = 1;
public const int LongValKeyLE = 2;
public const int LongValKeyGE = 3;
public const int DoubleValKeyLE = 4;
public const int DoubleValKeyGE = 5;
public const int DamagePercentGE = 6;
public const int ObjectClass = 7;
public const int SpellCountGE = 8;
public const int SpellMatch = 9;
public const int MinDamageGE = 10;
public const int LongValKeyFlagExists = 11;
public const int LongValKeyE = 12;
public const int LongValKeyNE = 13;
public const int AnySimilarColor = 14;
public const int SimilarColorArmorType = 15;
public const int SlotSimilarColor = 16;
public const int SlotExactPalette = 17;
public const int CharacterSkillGE = 1000;
public const int CharacterMainPackEmptySlotsGE = 1001;
public const int CharacterLevelGE = 1002;
public const int CharacterLevelLE = 1003;
public const int CharacterBaseSkill = 1004;
public const int BuffedMedianDamageGE = 2000;
public const int BuffedMissileDamageGE = 2001;
public const int BuffedLongValKeyGE = 2003;
public const int BuffedDoubleValKeyGE = 2005;
public const int CalcdBuffedTinkedDamageGE = 2006;
public const int TotalRatingsGE = 2007;
public const int CalcedBuffedTinkedTargetMeleeGE = 2008;
public const int DisabledRule = 9999;
/// <summary>Number of data lines a given node type consumes; -1 for unknown.</summary>
public static int GetDataLineCount(int type) => type switch
{
SpellNameMatch => 1, // pattern
StringValueMatch => 2, // pattern, key
LongValKeyLE => 2, // value, key
LongValKeyGE => 2, // value, key
DoubleValKeyLE => 2, // value, key
DoubleValKeyGE => 2, // value, key
DamagePercentGE => 1, // value
ObjectClass => 1, // class id
SpellCountGE => 1, // count
SpellMatch => 3, // match_rx, no_match_rx, count
MinDamageGE => 1, // value
LongValKeyFlagExists => 2, // flag, key
LongValKeyE => 2, // value, key
LongValKeyNE => 2, // value, key
AnySimilarColor => 5, // r, g, b, maxDiffH, maxDiffSV
SimilarColorArmorType => 6, // r, g, b, maxDiffH, maxDiffSV, armorGroup
SlotSimilarColor => 6, // r, g, b, maxDiffH, maxDiffSV, slot
SlotExactPalette => 2, // slot, palette
CharacterSkillGE => 2, // value, skillId
CharacterMainPackEmptySlotsGE => 1, // count
CharacterLevelGE => 1, // value
CharacterLevelLE => 1, // value
CharacterBaseSkill => 3, // skillId, min, max
BuffedMedianDamageGE => 1, // value
BuffedMissileDamageGE => 1, // value
BuffedLongValKeyGE => 2, // value, key
BuffedDoubleValKeyGE => 2, // value, key
CalcdBuffedTinkedDamageGE => 1, // value
TotalRatingsGE => 1, // value
CalcedBuffedTinkedTargetMeleeGE => 3, // dot, def, atk
DisabledRule => 1, // "true"/"false"
_ => -1,
};
/// <summary>Human-readable name for a node type, suitable for UI labels.</summary>
public static string DisplayName(int type) => type switch
{
SpellNameMatch => "Spell Name Match",
StringValueMatch => "String Value Match",
LongValKeyLE => "Long Key ≤",
LongValKeyGE => "Long Key ≥",
DoubleValKeyLE => "Double Key ≤",
DoubleValKeyGE => "Double Key ≥",
DamagePercentGE => "Damage % ≥",
ObjectClass => "Object Class",
SpellCountGE => "Spell Count ≥",
SpellMatch => "Spell Match",
MinDamageGE => "Min Damage ≥",
LongValKeyFlagExists => "Long Key Has Flag",
LongValKeyE => "Long Key =",
LongValKeyNE => "Long Key ≠",
AnySimilarColor => "Any Similar Color",
SimilarColorArmorType => "Similar Color (Armor Type)",
SlotSimilarColor => "Slot Similar Color",
SlotExactPalette => "Slot Exact Palette",
CharacterSkillGE => "Char Skill ≥ (buffed)",
CharacterMainPackEmptySlotsGE => "Char Pack Slots ≥",
CharacterLevelGE => "Char Level ≥",
CharacterLevelLE => "Char Level ≤",
CharacterBaseSkill => "Char Base Skill in [min,max]",
BuffedMedianDamageGE => "Buffed Median Damage ≥",
BuffedMissileDamageGE => "Buffed Missile Damage ≥",
BuffedLongValKeyGE => "Buffed Long Key ≥",
BuffedDoubleValKeyGE => "Buffed Double Key ≥",
CalcdBuffedTinkedDamageGE => "Buffed Tinked Damage ≥",
TotalRatingsGE => "Total Ratings ≥",
CalcedBuffedTinkedTargetMeleeGE => "Tinked Target Melee ≥",
DisabledRule => "Disabled Rule",
_ => $"Unknown ({type})",
};
/// <summary>Every known node type id, in canonical UI order.</summary>
public static readonly int[] All =
{
ObjectClass,
StringValueMatch,
LongValKeyE, LongValKeyNE, LongValKeyGE, LongValKeyLE, LongValKeyFlagExists,
DoubleValKeyGE, DoubleValKeyLE,
MinDamageGE, DamagePercentGE,
SpellNameMatch, SpellCountGE, SpellMatch,
AnySimilarColor, SimilarColorArmorType, SlotSimilarColor, SlotExactPalette,
CharacterSkillGE, CharacterBaseSkill, CharacterLevelGE, CharacterLevelLE,
CharacterMainPackEmptySlotsGE,
BuffedMedianDamageGE, BuffedMissileDamageGE, BuffedLongValKeyGE, BuffedDoubleValKeyGE,
CalcdBuffedTinkedDamageGE, TotalRatingsGE, CalcedBuffedTinkedTargetMeleeGE,
DisabledRule,
};
}

View file

@ -0,0 +1,357 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace RynthCore.Plugin.RynthAi.Raycasting
{
/// <summary>
/// AC .dat file reader — ported directly from ACEmulator's DatLoader.
///
/// Key format details (from ACE source):
/// - Header at file offset 0x140
/// - Block chain: FIRST 4 bytes of each block = next block address (byte offset)
/// Remaining (BlockSize - 4) bytes = data
/// - B-tree node (DatDirectoryHeader): 62 branches, entry count, 61 entries × 24 bytes = 1716 total
/// - All pointers (BTree root, chain pointers, file offsets) are byte offsets
/// </summary>
public class DatDatabase : IDisposable
{
private FileStream _stream;
private readonly object _lock = new object();
private const uint DAT_HEADER_OFFSET = 0x140;
// B-tree geometry (from ACE DatDirectoryHeader.cs):
// 0x3E (62) branches, 0x3D (61) max entries, each entry = 6 × uint32 = 24 bytes
// ObjectSize = (4 * 62) + 4 + (24 * 61) = 248 + 4 + 1464 = 1716
private const int BTREE_BRANCH_COUNT = 0x3E; // 62
private const int BTREE_MAX_ENTRIES = 0x3D; // 61
private const int BTREE_ENTRY_SIZE = 24; // 6 × uint32
private const int BTREE_NODE_SIZE = (4 * BTREE_BRANCH_COUNT) + 4 + (BTREE_ENTRY_SIZE * BTREE_MAX_ENTRIES); // 1716
// Header fields
public uint FileType { get; private set; }
public uint BlockSize { get; private set; }
public uint FileSize { get; private set; }
public uint DataSet { get; private set; }
public uint BTreeRoot { get; private set; } // Byte offset
public bool IsLoaded { get; private set; }
public string FilePath { get; private set; }
public int RecordCount { get; private set; }
// All files indexed by ObjectId (populated during Open)
private readonly Dictionary<uint, DatBTreeEntry> _allFiles = new Dictionary<uint, DatBTreeEntry>();
public List<string> DiagLog { get; } = new List<string>();
public bool Open(string path)
{
try
{
if (!File.Exists(path))
{
Log($"File not found: {path}");
return false;
}
FilePath = path;
// Plugin init runs *before* acclient.exe opens its own DAT files,
// so our handle is the first one Windows sees on the file. Our
// share-mode dictates what AC's subsequent open can request — if
// we omit FileShare.Delete, AC's open (which needs delete-rename
// semantics for DDD/patcher) fails with a sharing violation and
// the AC client errors out with "cannot access the data files."
//
// FileShare.ReadWrite | FileShare.Delete = permit other openers
// to read, write, and delete-mark the file. RandomAccess hint +
// 4 KB buffer keeps the .dat B-tree reads efficient.
_stream = new FileStream(
path,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite | FileShare.Delete,
bufferSize: 4096,
options: FileOptions.RandomAccess);
Log($"File: {Path.GetFileName(path)}, Size: {_stream.Length:N0} bytes");
if (!ReadHeader())
{
Close();
return false;
}
// Read the entire B-tree directory and index all files
ReadDirectory(BTreeRoot);
RecordCount = _allFiles.Count;
IsLoaded = true;
Log($"SUCCESS: {RecordCount} files indexed, BlockSize={BlockSize}, Root=0x{BTreeRoot:X8}");
return true;
}
catch (Exception ex)
{
Log($"Error: {ex.Message}");
Close();
return false;
}
}
/// <summary>
/// Reads the dat header from offset 0x140.
/// Format matches ACE's DatDatabaseHeader.Unpack().
/// </summary>
private bool ReadHeader()
{
if (_stream.Length < DAT_HEADER_OFFSET + 64)
{
Log("File too small");
return false;
}
_stream.Seek(DAT_HEADER_OFFSET, SeekOrigin.Begin);
using (var reader = new BinaryReader(_stream, System.Text.Encoding.Default, true))
{
FileType = reader.ReadUInt32();
BlockSize = reader.ReadUInt32();
FileSize = reader.ReadUInt32();
DataSet = reader.ReadUInt32();
uint dataSubset = reader.ReadUInt32();
uint freeHead = reader.ReadUInt32();
uint freeTail = reader.ReadUInt32();
uint freeCount = reader.ReadUInt32();
BTreeRoot = reader.ReadUInt32();
}
Log($"FileType=0x{FileType:X8}, BlockSize={BlockSize}, DataSet={DataSet}, BTree=0x{BTreeRoot:X8}");
if (BlockSize == 0 || BTreeRoot == 0 || BTreeRoot >= (uint)_stream.Length)
{
Log("Invalid header values");
return false;
}
return true;
}
/// <summary>
/// Reads data from the dat file following the block chain.
/// Matches ACE's DatReader.ReadDat() exactly.
///
/// Block format:
/// [4 bytes: next block address] [BlockSize - 4 bytes: data]
///
/// The FIRST 4 bytes of each block are the chain pointer (next block address).
/// If 0, this is the last block.
/// </summary>
private byte[] ReadDatData(uint offset, int size)
{
if (offset + BlockSize > (uint)_stream.Length || size <= 0)
return null;
byte[] buffer = new byte[size];
_stream.Seek(offset, SeekOrigin.Begin);
// Read first 4 bytes = next block address
byte[] addrBuf = new byte[4];
_stream.Read(addrBuf, 0, 4);
uint nextAddress = BitConverter.ToUInt32(addrBuf, 0);
int bufferOffset = 0;
int remaining = size;
while (remaining > 0)
{
if (nextAddress == 0)
{
// Last block — read remaining data directly
int toRead = Math.Min(remaining, (int)(_stream.Length - _stream.Position));
if (toRead <= 0) break;
_stream.Read(buffer, bufferOffset, toRead);
remaining = 0;
}
else
{
// Read data portion of this block (BlockSize - 4 bytes)
int dataInBlock = (int)BlockSize - 4;
int toRead = Math.Min(dataInBlock, remaining);
_stream.Read(buffer, bufferOffset, toRead);
bufferOffset += toRead;
remaining -= toRead;
if (remaining > 0)
{
// Follow chain to next block
if (nextAddress >= (uint)_stream.Length) break;
_stream.Seek(nextAddress, SeekOrigin.Begin);
// Read next block's chain pointer
_stream.Read(addrBuf, 0, 4);
nextAddress = BitConverter.ToUInt32(addrBuf, 0);
}
}
}
return buffer;
}
/// <summary>
/// Recursively reads the B-tree directory and indexes all files.
/// Matches ACE's DatDirectory.Read() + AddFilesToList().
/// </summary>
private void ReadDirectory(uint sectorOffset)
{
if (sectorOffset == 0 || sectorOffset >= (uint)_stream.Length)
return;
// Read the directory header (B-tree node)
byte[] nodeData;
lock (_lock)
{
nodeData = ReadDatData(sectorOffset, BTREE_NODE_SIZE);
}
if (nodeData == null || nodeData.Length < BTREE_NODE_SIZE)
return;
// Parse branches (62 × uint32)
uint[] branches = new uint[BTREE_BRANCH_COUNT];
for (int i = 0; i < BTREE_BRANCH_COUNT; i++)
branches[i] = BitConverter.ToUInt32(nodeData, i * 4);
// Parse entry count
int countOffset = BTREE_BRANCH_COUNT * 4; // 248
uint entryCount = BitConverter.ToUInt32(nodeData, countOffset);
if (entryCount > BTREE_MAX_ENTRIES)
return; // Invalid node
// Parse entries
int entriesOffset = countOffset + 4; // 252
var entries = new DatBTreeEntry[entryCount];
for (int i = 0; i < entryCount; i++)
{
int eOff = entriesOffset + i * BTREE_ENTRY_SIZE;
entries[i] = new DatBTreeEntry
{
BitFlags = BitConverter.ToUInt32(nodeData, eOff),
ObjectId = BitConverter.ToUInt32(nodeData, eOff + 4),
FileOffset = BitConverter.ToUInt32(nodeData, eOff + 8),
FileSize = BitConverter.ToUInt32(nodeData, eOff + 12)
};
}
// Recurse into child directories (if branches[0] != 0, node has children)
if (branches[0] != 0)
{
for (int i = 0; i < entryCount + 1 && i < BTREE_BRANCH_COUNT; i++)
{
if (branches[i] != 0)
ReadDirectory(branches[i]);
}
}
// Add entries to the file index
for (int i = 0; i < entryCount; i++)
{
if (entries[i].ObjectId != 0)
_allFiles[entries[i].ObjectId] = entries[i];
}
}
/// <summary>
/// Finds a file by ID. O(1) lookup from the pre-built index.
/// </summary>
public DatBTreeEntry FindFile(uint fileId)
{
if (!IsLoaded) return null;
_allFiles.TryGetValue(fileId, out var entry);
return entry;
}
/// <summary>
/// Reads file data for a given entry.
/// </summary>
public byte[] ReadFileData(DatBTreeEntry entry)
{
if (!IsLoaded || entry == null || entry.FileSize == 0 || _stream == null)
return null;
lock (_lock)
{
return ReadDatData(entry.FileOffset, (int)entry.FileSize);
}
}
public byte[] GetFileData(uint fileId)
{
var entry = FindFile(fileId);
return entry != null ? ReadFileData(entry) : null;
}
/// <summary>
/// Returns all interior cell IDs (0x0100–0xFFFD) for a given landblock from the dat index.
/// This avoids the sequential scan gap cutoff that misses cells in large dungeons.
/// </summary>
public List<uint> GetLandblockCellIds(uint landblockKey)
{
var cellIds = new List<uint>();
if (!IsLoaded) return cellIds;
uint prefix = landblockKey << 16;
foreach (var id in _allFiles.Keys)
{
if ((id & 0xFFFF0000) != prefix) continue;
uint cell = id & 0xFFFF;
if (cell >= 0x0100 && cell <= 0xFFFD)
cellIds.Add(id);
}
return cellIds;
}
/// <summary>
/// Returns sample file IDs from the index for diagnostics.
/// </summary>
public List<uint> GetSampleIds(int maxCount = 20)
{
var ids = new List<uint>();
foreach (var kvp in _allFiles)
{
ids.Add(kvp.Key);
if (ids.Count >= maxCount) break;
}
return ids;
}
public void Close()
{
_stream?.Dispose();
_stream = null;
IsLoaded = false;
_allFiles.Clear();
}
public void Dispose() { Close(); }
private void Log(string msg)
{
string line = $"[DatDB] {msg}";
System.Diagnostics.Debug.WriteLine(line);
if (DiagLog.Count < 100) DiagLog.Add(line);
}
}
public class DatBTreeEntry
{
public uint BitFlags;
public uint ObjectId;
public uint FileOffset; // Byte offset into file
public uint FileSize;
}
}

View file

@ -0,0 +1,336 @@
using System;
using System.IO;
namespace RynthCore.Plugin.RynthAi.Raycasting
{
/// <summary>
/// Parsed CellLandblock (0xXXYYFFFF) — terrain heightmap and terrain-type words for one 192×192 m landblock.
///
/// File layout (cell.dat 0xXXYYFFFF):
/// uint Id (0xXXYYFFFF)
/// uint HasObjects (nonzero if matching 0xXXYYFFFE LandblockInfo exists)
/// ushort Terrain[81] 9×9 grid, (terrainType &lt;&lt; 2 | roadMask) | (sceneType &lt;&lt; 11)
/// byte Height[81] 9×9 grid, indices into RegionDesc.LandHeightTable
///
/// Vertex indexing: idx = ix * 9 + iy, where ix = 0..8 (west→east) and iy = 0..8 (south→north).
/// </summary>
public class LandblockData
{
public const int VertexDim = 9;
public const int BlockSide = 8;
public const float CellLength = 24.0f;
public const float BlockLength = 192.0f;
public uint LandblockKey { get; private set; }
public bool HasObjects { get; private set; }
/// <summary>81 terrain words, row-major (ix, iy) via idx = ix*9 + iy.</summary>
public ushort[] TerrainWords { get; private set; }
/// <summary>81 raw height indices (into LandHeightTable).</summary>
public byte[] HeightIndices { get; private set; }
/// <summary>Decoded world-space Z for every vertex. Indexed as HeightsZ[ix, iy].</summary>
public float[,] HeightsZ { get; private set; }
/// <summary>World-space X of vertex (0, 0) — the SW corner of the landblock.</summary>
public float WorldOriginX { get; private set; }
/// <summary>World-space Y of vertex (0, 0) — the SW corner of the landblock.</summary>
public float WorldOriginY { get; private set; }
/// <summary>
/// Loads and parses the 0xXXYYFFFF CellLandblock for the given landblock key.
/// Returns null if the file is missing, too short, or the height table hasn't been loaded yet.
/// </summary>
public static LandblockData Load(DatDatabase cellDat, uint landblockKey, float[] landHeightTable)
{
if (cellDat == null || landHeightTable == null) return null;
uint cellId = (landblockKey << 16) | 0xFFFF;
byte[] data = cellDat.GetFileData(cellId);
// 4 (Id) + 4 (HasObjects) + 81*2 (terrain) + 81 (heights) = 251
if (data == null || data.Length < 251) return null;
var terrain = new ushort[81];
var heights = new byte[81];
bool hasObjects;
try
{
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
reader.ReadUInt32(); // Id
hasObjects = reader.ReadUInt32() != 0; // HasObjects
for (int i = 0; i < 81; i++)
terrain[i] = reader.ReadUInt16();
for (int i = 0; i < 81; i++)
heights[i] = reader.ReadByte();
}
}
catch
{
return null;
}
var heightsZ = new float[VertexDim, VertexDim];
for (int ix = 0; ix < VertexDim; ix++)
{
for (int iy = 0; iy < VertexDim; iy++)
{
byte h = heights[ix * VertexDim + iy];
heightsZ[ix, iy] = h < landHeightTable.Length ? landHeightTable[h] : 0f;
}
}
float originX = ((landblockKey >> 8) & 0xFF) * BlockLength;
float originY = (landblockKey & 0xFF) * BlockLength;
return new LandblockData
{
LandblockKey = landblockKey,
HasObjects = hasObjects,
TerrainWords = terrain,
HeightIndices = heights,
HeightsZ = heightsZ,
WorldOriginX = originX,
WorldOriginY = originY,
};
}
/// <summary>
/// Z of the nearest grid vertex for a local position in [0, 192) on each axis.
/// Coords outside the landblock are clamped to the edge.
/// </summary>
public float GetNearestVertexHeightLocal(float lx, float ly)
{
int ix = (int)Math.Round(lx / CellLength);
int iy = (int)Math.Round(ly / CellLength);
if (ix < 0) ix = 0; else if (ix > BlockSide) ix = BlockSide;
if (iy < 0) iy = 0; else if (iy > BlockSide) iy = BlockSide;
return HeightsZ[ix, iy];
}
/// <summary>
/// Z of the nearest grid vertex at a world-space (X, Y). Returns NaN if (X, Y) is not inside this landblock.
/// </summary>
public float GetNearestVertexHeightWorld(float worldX, float worldY)
{
float lx = worldX - WorldOriginX;
float ly = worldY - WorldOriginY;
if (lx < 0f || ly < 0f || lx >= BlockLength || ly >= BlockLength)
return float.NaN;
return GetNearestVertexHeightLocal(lx, ly);
}
/// <summary>Min and max decoded vertex Z across the whole landblock.</summary>
public void GetHeightRange(out float min, out float max)
{
min = float.PositiveInfinity;
max = float.NegativeInfinity;
for (int ix = 0; ix < VertexDim; ix++)
{
for (int iy = 0; iy < VertexDim; iy++)
{
float z = HeightsZ[ix, iy];
if (z < min) min = z;
if (z > max) max = z;
}
}
}
/// <summary>Convenience: vertex Z at integer grid coords (0..8, 0..8).</summary>
public float GetVertexZ(int ix, int iy)
{
if ((uint)ix > BlockSide || (uint)iy > BlockSide) return 0f;
return HeightsZ[ix, iy];
}
// ===================================================================
// Triangle-exact terrain Z
//
// Each 24 m cell is split by the SW→NE diagonal into two triangles
// (matching the fixed split ScatterSystem uses for passability checks):
// SE triangle (below diagonal, fy ≤ fx): SW, SE, NE
// NW triangle (above diagonal, fy > fx): SW, NE, NW
// AC's client uses a per-cell PRNG to pick between SE/NW and NE/SW diagonals;
// we don't hash yet, so expect a few cm of divergence from the client's exact Z
// in cells where the PRNG would have picked NE/SW.
// ===================================================================
/// <summary>
/// Plane-interpolated Z at a landblock-local (lx, ly) ∈ [0, 192]². Clamps to the interior.
/// </summary>
public float GetTerrainZLocal(float lx, float ly)
{
if (lx < 0f) lx = 0f; else if (lx > BlockLength) lx = BlockLength;
if (ly < 0f) ly = 0f; else if (ly > BlockLength) ly = BlockLength;
int cx = (int)(lx / CellLength);
int cy = (int)(ly / CellLength);
if (cx >= BlockSide) cx = BlockSide - 1;
if (cy >= BlockSide) cy = BlockSide - 1;
float fx = lx - cx * CellLength;
float fy = ly - cy * CellLength;
float u = fx / CellLength;
float v = fy / CellLength;
float hSW = HeightsZ[cx, cy];
float hSE = HeightsZ[cx + 1, cy];
float hNW = HeightsZ[cx, cy + 1];
float hNE = HeightsZ[cx + 1, cy + 1];
if (fy <= fx)
return hSW + u * (hSE - hSW) + v * (hNE - hSE);
return hSW + v * (hNW - hSW) - u * (hNW - hNE);
}
/// <summary>
/// Plane-interpolated Z at a world (X, Y). NaN if (X, Y) is not in this landblock.
/// </summary>
public float GetTerrainZWorld(float worldX, float worldY)
{
float lx = worldX - WorldOriginX;
float ly = worldY - WorldOriginY;
if (lx < 0f || ly < 0f || lx >= BlockLength || ly >= BlockLength)
return float.NaN;
return GetTerrainZLocal(lx, ly);
}
// ===================================================================
// Landscape raycast (per landblock)
// ===================================================================
/// <summary>
/// Ray vs. terrain-mesh test inside this landblock. <paramref name="localOrigin"/> is in
/// landblock-local XY (world – <see cref="WorldOriginX"/>/<see cref="WorldOriginY"/>; Z unchanged).
/// Walks the 8×8 cell grid via 2D DDA, tests both triangles per cell with Möller-Trumbore.
/// Returns the nearest hit within <paramref name="maxDist"/>; <paramref name="hitNormal"/>
/// is the unit upward-facing normal of the triangle hit.
/// </summary>
public bool RaycastTerrainLocal(Vector3 localOrigin, Vector3 dir, float maxDist,
out float hitDist, out Vector3 hitNormal)
{
hitDist = 0f;
hitNormal = Vector3.Zero;
float px = localOrigin.X;
float py = localOrigin.Y;
float vx = dir.X;
float vy = dir.Y;
int cx = (int)Math.Floor(px / CellLength);
int cy = (int)Math.Floor(py / CellLength);
if (cx < 0) cx = 0; else if (cx > BlockSide - 1) cx = BlockSide - 1;
if (cy < 0) cy = 0; else if (cy > BlockSide - 1) cy = BlockSide - 1;
int stepX = vx > 0 ? 1 : (vx < 0 ? -1 : 0);
int stepY = vy > 0 ? 1 : (vy < 0 ? -1 : 0);
float tMaxX = float.PositiveInfinity, tDeltaX = float.PositiveInfinity;
float tMaxY = float.PositiveInfinity, tDeltaY = float.PositiveInfinity;
if (stepX != 0)
{
float nextX = (stepX > 0 ? (cx + 1) : cx) * CellLength;
tMaxX = (nextX - px) / vx;
tDeltaX = CellLength / Math.Abs(vx);
}
if (stepY != 0)
{
float nextY = (stepY > 0 ? (cy + 1) : cy) * CellLength;
tMaxY = (nextY - py) / vy;
tDeltaY = CellLength / Math.Abs(vy);
}
float bestT = maxDist;
Vector3 bestNormal = Vector3.Zero;
bool found = false;
// Enough steps to traverse the block diagonally plus a small safety margin.
int iterLimit = BlockSide * 2 + 4;
while (iterLimit-- > 0)
{
if (cx < 0 || cy < 0 || cx >= BlockSide || cy >= BlockSide)
break;
float x0 = cx * CellLength, x1 = x0 + CellLength;
float y0 = cy * CellLength, y1 = y0 + CellLength;
Vector3 vSW = new Vector3(x0, y0, HeightsZ[cx, cy]);
Vector3 vSE = new Vector3(x1, y0, HeightsZ[cx + 1, cy]);
Vector3 vNE = new Vector3(x1, y1, HeightsZ[cx + 1, cy + 1]);
Vector3 vNW = new Vector3(x0, y1, HeightsZ[cx, cy + 1]);
if (RayTriangle(localOrigin, dir, vSW, vSE, vNE, out float tSE) && tSE < bestT)
{
bestT = tSE;
bestNormal = TriangleUpNormal(vSW, vSE, vNE);
found = true;
}
if (RayTriangle(localOrigin, dir, vSW, vNE, vNW, out float tNW) && tNW < bestT)
{
bestT = tNW;
bestNormal = TriangleUpNormal(vSW, vNE, vNW);
found = true;
}
float tNext = Math.Min(tMaxX, tMaxY);
// If we already have a closer hit than the nearest cell boundary, we're done.
if (found && tNext >= bestT) break;
if (tNext > maxDist) break;
if (stepX == 0 && stepY == 0) break; // vertical ray: single-cell only
if (tMaxX < tMaxY)
{
tMaxX += tDeltaX;
cx += stepX;
}
else
{
tMaxY += tDeltaY;
cy += stepY;
}
}
if (found)
{
hitDist = bestT;
hitNormal = bestNormal;
return true;
}
return false;
}
// Möller-Trumbore. Local copy to keep LandblockData self-contained
// (BoundingVolume has the same routine privately).
private static bool RayTriangle(Vector3 origin, Vector3 dir,
Vector3 v0, Vector3 v1, Vector3 v2, out float t)
{
t = 0f;
const float EPSILON = 1e-7f;
Vector3 edge1 = v1 - v0;
Vector3 edge2 = v2 - v0;
Vector3 h = Vector3.Cross(dir, edge2);
float a = Vector3.Dot(edge1, h);
if (a > -EPSILON && a < EPSILON) return false;
float f = 1f / a;
Vector3 s = origin - v0;
float u = f * Vector3.Dot(s, h);
if (u < 0f || u > 1f) return false;
Vector3 q = Vector3.Cross(s, edge1);
float v = f * Vector3.Dot(dir, q);
if (v < 0f || u + v > 1f) return false;
t = f * Vector3.Dot(edge2, q);
return t >= 0f;
}
private static Vector3 TriangleUpNormal(Vector3 a, Vector3 b, Vector3 c)
{
// Winding is chosen so this points up (+Z) — see LandblockData docs.
Vector3 n = Vector3.Cross(b - a, c - a);
return n.Normalize();
}
}
}

View file

@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<RootNamespace>RynthCore.TerrainData</RootNamespace>
<AssemblyName>RynthCore.TerrainData</AssemblyName>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,273 @@
using System;
using System.Collections.Generic;
using System.IO;
using RynthCore.Plugin.RynthAi.Raycasting;
namespace RynthCore.TerrainData;
/// <summary>
/// Self-contained terrain-data provider for AC landblocks: opens the client's
/// portal/cell .dat files, parses the 256-entry land-height table from RegionDesc,
/// and exposes per-landblock heights, slope passability, and terrain-type/water
/// lookups. Reuses the shared DatDatabase/LandblockData parsers; the slope math
/// and height-table prefix parse are reimplemented here so this carries no
/// dependency on RynthAi's raycasting engine.
/// </summary>
public sealed class TerrainSampler : IDisposable
{
// AC's actual walkable threshold from ACE PhysicsGlobals.FloorZ — anything
// with normal.Z below this value is blocked by is_valid_walkable. The visual
// overlay must match the game's blocker, not a tuned-for-scatter looser
// value, or moderate slopes the game blocks render as walkable.
// (RynthAi's ScatterSystem.FloorZ is intentionally looser to suppress
// gentle-slope false positives on vegetation placement and is unrelated.)
public const float FloorZ = 0.66417414618662751f;
private const float CellLength = 24.0f;
private readonly DatDatabase _portalDat = new();
private readonly DatDatabase _cellDat = new();
private float[]? _landHeightTable;
private bool _ready;
// Deep-audit finding #6 (2026-06-18): RynthVision's /rv watertypes ->
// InspectTerrain runs synchronously on the Avalonia UI thread and calls
// LoadLandblock, while the same call hits from the AC tick thread hundreds
// of times per Submit via the slope/water overlays. Two threads mutating
// one plain Dictionary (with a periodic Clear() at MaxCache=30) is classic
// bucket-array corruption on whichever thread lands on it — frequently
// AC's own main thread. Guard every access with this gate.
private readonly object _cacheGate = new();
private readonly Dictionary<uint, LandblockData?> _cache = new();
private const int MaxCache = 30;
public bool IsReady => _ready;
public string Status { get; private set; } = "uninitialized";
/// <summary>
/// Opens the AC .dat files and loads the land-height table. Idempotent. When
/// acFolderPath is null, uses the running process's directory — inside an
/// injected plugin that's acclient.exe's folder, where the active client's
/// .dat files live.
/// </summary>
public bool Initialize(string? acFolderPath = null)
{
if (_ready) return true;
try
{
string? folder = acFolderPath;
if (string.IsNullOrEmpty(folder))
{
string? exe = Environment.ProcessPath;
folder = string.IsNullOrEmpty(exe) ? null : Path.GetDirectoryName(exe);
}
if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder))
{
Status = $"AC folder not found ({folder ?? "null"})";
return false;
}
string? portalPath = FindDat(folder, "client_portal.dat", "portal.dat");
string? cellPath = FindDat(folder, "client_cell_1.dat", "cell.dat");
if (portalPath == null || cellPath == null)
{
Status = $"portal/cell .dat not found in {folder}";
return false;
}
if (!_portalDat.Open(portalPath) || !_cellDat.Open(cellPath))
{
Status = "failed to open .dat files";
return false;
}
if (!LoadLandHeightTable())
{
Status = "RegionDesc land-height table parse failed";
return false;
}
_ready = true;
Status = "ready";
return true;
}
catch (Exception ex)
{
Status = ex.Message;
return false;
}
}
/// <summary>Parsed landblock (heights + terrain words), cached. Null if unavailable.</summary>
public LandblockData? LoadLandblock(uint landblockKey)
{
if (!_ready || _landHeightTable == null) return null;
lock (_cacheGate)
{
if (_cache.TryGetValue(landblockKey, out var cached)) return cached;
}
LandblockData? data = LandblockData.Load(_cellDat, landblockKey, _landHeightTable);
lock (_cacheGate)
{
if (_cache.Count >= MaxCache) _cache.Clear();
_cache[landblockKey] = data;
}
return data;
}
/// <summary>
/// AC's per-cell diagonal-split PRNG (ACE LandblockStruct.ConstructPolygons /
/// FSplitNESW). When true the cell is cut SW→NE (triangles SW-SE-NE and
/// SW-NE-NW); when false it's cut SE→NW (triangles SW-SE-NW and SE-NE-NW).
/// Roughly 50/50 across cells. Slope and Z-interpolation queries must agree
/// with this or they describe the wrong triangle pair.
///
/// The PRNG inputs are the cell's *vertex-grid* coordinates (landblock
/// index × 8 + cell index within landblock), NOT raw landblock indices —
/// this matches ACE's <c>blockid_to_lcoord</c>, which shifts the byte
/// landblock index left by <c>LandblockShift</c> (= 3, i.e. ×8) before
/// feeding it to the seed multiplications. Getting this wrong gives the
/// wrong diagonal on most cells and paints the wrong triangle half.
/// </summary>
public static bool SwToNeCut(uint landblockKey, int cellX, int cellY)
{
int lbX = (int)((landblockKey >> 8) & 0xFF);
int lbY = (int)(landblockKey & 0xFF);
int vertexX = (lbX << 3) + cellX; // lbX * 8 + cellX (ACE LandblockShift = 3)
int vertexY = (lbY << 3) + cellY;
unchecked
{
uint seedA = (uint)vertexX * 214614067u;
uint seedB = (uint)vertexX * 1109124029u;
uint magicA = seedA + 1813693831u;
uint magicB = seedB;
uint splitDir = (uint)vertexY * magicA - magicB - 1369149221u;
return (splitDir & 0x80000000u) != 0;
}
}
/// <summary>
/// Per-triangle walkability for cell (cx,cy) in landblock <paramref name="lb"/>.
/// The tri1/tri2 identity depends on <paramref name="swToNeCut"/>:
/// swToNeCut=true → tri1 = SE half (SW,SE,NE); tri2 = NW half (SW,NE,NW)
/// swToNeCut=false → tri1 = SW half (SW,SE,NW); tri2 = NE half (SE,NE,NW)
/// <paramref name="floorZ"/> overrides the default walkable-normal threshold
/// (defaults to <see cref="FloorZ"/>); the visual overlay exposes it as a
/// slider so the user can match what AC actually blocks in their environment.
/// </summary>
public static void GetTrianglePassability(LandblockData lb, int cx, int cy, bool swToNeCut,
out bool tri1Passable, out bool tri2Passable, float floorZ = FloorZ)
{
float h00 = lb.GetVertexZ(cx, cy);
float h10 = lb.GetVertexZ(cx + 1, cy);
float h01 = lb.GetVertexZ(cx, cy + 1);
float h11 = lb.GetVertexZ(cx + 1, cy + 1);
float nzSquare = CellLength * CellLength;
float n1x, n1y, n2x, n2y;
if (swToNeCut)
{
// tri1 (SE): SW(0,0,h00), SE(24,0,h10), NE(24,24,h11)
n1x = -CellLength * (h10 - h00);
n1y = -CellLength * (h11 - h10);
// tri2 (NW): SW(0,0,h00), NE(24,24,h11), NW(0,24,h01)
n2x = -CellLength * (h11 - h01);
n2y = -CellLength * (h01 - h00);
}
else
{
// tri1 (SW): SW(0,0,h00), SE(24,0,h10), NW(0,24,h01)
n1x = -CellLength * (h10 - h00);
n1y = -CellLength * (h01 - h00);
// tri2 (NE): SE(24,0,h10), NE(24,24,h11), NW(0,24,h01)
n2x = -CellLength * (h11 - h01);
n2y = -CellLength * (h11 - h10);
}
float z1 = nzSquare / (float)Math.Sqrt(n1x * n1x + n1y * n1y + nzSquare * nzSquare);
float z2 = nzSquare / (float)Math.Sqrt(n2x * n2x + n2y * n2y + nzSquare * nzSquare);
tri1Passable = z1 >= floorZ;
tri2Passable = z2 >= floorZ;
}
/// <summary>
/// Convenience overload that looks up the cell's split direction itself.
/// </summary>
public static void GetTrianglePassability(LandblockData lb, int cx, int cy,
out bool tri1Passable, out bool tri2Passable)
=> GetTrianglePassability(lb, cx, cy, SwToNeCut(lb.LandblockKey, cx, cy),
out tri1Passable, out tri2Passable);
/// <summary>
/// AC terrain-type index (0–31) at vertex (ix,iy), 0–8. Decoded from the
/// CellLandblock terrain word: bits 0–1 road, 2–10 terrain type, 11+ scene.
/// Returns -1 if unavailable.
/// </summary>
public static int GetTerrainType(LandblockData lb, int ix, int iy)
{
var words = lb.TerrainWords;
if (words == null) return -1;
int idx = ix * 9 + iy;
if ((uint)idx >= 81) return -1;
return (words[idx] >> 2) & 0x1F;
}
private static string? FindDat(string folder, params string[] names)
{
foreach (var n in names)
{
string p = Path.Combine(folder, n);
if (File.Exists(p)) return p;
}
return null;
}
private bool LoadLandHeightTable()
{
byte[]? data = _portalDat.GetFileData(0x13000000);
// 12 (header) + >=2 (PString) + 32 (LandDefs prefix) + 256*4 (table)
if (data == null || data.Length < 12 + 2 + 32 + 256 * 4) return false;
using var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32(); // id 0x13000000
r.ReadUInt32(); // regionNumber
r.ReadUInt32(); // version
SkipPString(r, ms); // RegionName
// LandDefs prefix (8 scalar fields) precedes the height table.
r.ReadInt32(); // NumBlockLength
r.ReadInt32(); // NumBlockWidth
r.ReadSingle(); // SquareLength
r.ReadInt32(); // LBlockLength
r.ReadInt32(); // VertexPerCell
r.ReadSingle(); // MaxObjHeight
r.ReadSingle(); // SkyHeight
r.ReadSingle(); // RoadWidth
var table = new float[256];
for (int i = 0; i < 256; i++) table[i] = r.ReadSingle();
_landHeightTable = table;
return true;
}
// PString: ushort length, that many bytes, padded to a 4-byte boundary.
private static void SkipPString(BinaryReader reader, MemoryStream ms)
{
ushort len = reader.ReadUInt16();
if (len > 0 && ms.Position + len <= ms.Length)
ms.Seek(len, SeekOrigin.Current);
long aligned = (ms.Position + 3) & ~3L;
if (aligned <= ms.Length) ms.Position = aligned;
}
public void Dispose()
{
_portalDat.Dispose();
_cellDat.Dispose();
_ready = false;
}
}

View file

@ -0,0 +1,143 @@
using System;
namespace RynthCore.Plugin.RynthAi.Raycasting
{
/// <summary>
/// Custom Vector3 for the raycasting system.
///
/// IMPORTANT: This replaces System.Numerics.Vector3 in the Raycasting namespace.
/// All Raycasting/*.cs files must NOT import System.Numerics to avoid type conflicts.
/// </summary>
public struct Vector3
{
public float X { get; set; }
public float Y { get; set; }
public float Z { get; set; }
public static readonly Vector3 Zero = new Vector3(0, 0, 0);
public static readonly Vector3 One = new Vector3(1, 1, 1);
public static readonly Vector3 Up = new Vector3(0, 0, 1);
public Vector3(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
}
// --- Conversion ---
public static Vector3 FromNumerics(System.Numerics.Vector3 v)
=> new Vector3(v.X, v.Y, v.Z);
public System.Numerics.Vector3 ToNumerics()
=> new System.Numerics.Vector3(X, Y, Z);
public float[] ToArray()
=> new float[] { X, Y, Z };
public static Vector3 FromArray(float[] arr)
{
if (arr == null || arr.Length < 3) return Zero;
return new Vector3(arr[0], arr[1], arr[2]);
}
// --- Arithmetic operators ---
public static Vector3 operator +(Vector3 a, Vector3 b)
=> new Vector3(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
public static Vector3 operator -(Vector3 a, Vector3 b)
=> new Vector3(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
public static Vector3 operator -(Vector3 v)
=> new Vector3(-v.X, -v.Y, -v.Z);
public static Vector3 operator *(Vector3 v, float s)
=> new Vector3(v.X * s, v.Y * s, v.Z * s);
public static Vector3 operator *(float s, Vector3 v)
=> new Vector3(v.X * s, v.Y * s, v.Z * s);
public static Vector3 operator /(Vector3 v, float s)
{
float inv = 1.0f / s;
return new Vector3(v.X * inv, v.Y * inv, v.Z * inv);
}
// --- Vector math ---
public static float Dot(Vector3 a, Vector3 b)
=> a.X * b.X + a.Y * b.Y + a.Z * b.Z;
public static Vector3 Cross(Vector3 a, Vector3 b)
=> new Vector3(
a.Y * b.Z - a.Z * b.Y,
a.Z * b.X - a.X * b.Z,
a.X * b.Y - a.Y * b.X
);
public float Length()
=> (float)Math.Sqrt(X * X + Y * Y + Z * Z);
public float LengthSquared()
=> X * X + Y * Y + Z * Z;
public Vector3 Normalize()
{
float len = Length();
if (len < 1e-8f) return Zero;
return this * (1.0f / len);
}
public float Distance(Vector3 other)
=> (this - other).Length();
public static Vector3 Min(Vector3 a, Vector3 b)
=> new Vector3(Math.Min(a.X, b.X), Math.Min(a.Y, b.Y), Math.Min(a.Z, b.Z));
public static Vector3 Max(Vector3 a, Vector3 b)
=> new Vector3(Math.Max(a.X, b.X), Math.Max(a.Y, b.Y), Math.Max(a.Z, b.Z));
public static Vector3 Lerp(Vector3 a, Vector3 b, float t)
=> a + (b - a) * t;
public float Length2D()
=> (float)Math.Sqrt(X * X + Y * Y);
// --- Equality ---
public override bool Equals(object obj)
{
if (obj is Vector3 other)
return X == other.X && Y == other.Y && Z == other.Z;
return false;
}
public override int GetHashCode()
=> X.GetHashCode() ^ (Y.GetHashCode() << 8) ^ (Z.GetHashCode() << 16);
public static bool operator ==(Vector3 a, Vector3 b)
=> a.X == b.X && a.Y == b.Y && a.Z == b.Z;
public static bool operator !=(Vector3 a, Vector3 b)
=> !(a == b);
public override string ToString()
=> $"({X:F3}, {Y:F3}, {Z:F3})";
public float this[int i]
{
get
{
switch (i)
{
case 0: return X;
case 1: return Y;
case 2: return Z;
default: throw new IndexOutOfRangeException();
}
}
}
}
}