Editor/Core/UnityModel.cs

A parser and data model for Unity 3D model assets (OBJ and FBX). Reads mesh, material, LOD, transform and metadata from asset files and Unity YAML metadata, reconstructs renderer bindings and computes import-related info like scales and LOD thresholds.

File Access
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ImportUnityPackage;

public sealed class UnityModel
{
	public sealed record RendererBinding( string Mesh, string[] Slots )
	{
		// Without material objects the model compiler names the implicit slot after the mesh.
		public IEnumerable<string> EffectiveSlots => Slots.Length == 0 ? new[] { Mesh } : Slots;
	}
	/// <summary>One prefab material reference and how its renderer/slot was identified, for the import report.</summary>
	public sealed record PrefabSlotEvidence( string Prefab, string Slot, long Id, string Mesh, int Index, string Material, string IdSource, string Problem )
	{
		public bool Applied { get; init; }
	}
	public Dictionary<long, RendererBinding> RendererSlots { get; } = new();
	readonly Dictionary<long, RendererBinding> metadataMeshes = new();
	readonly HashSet<long> metadataRenderers = new();
	/// <summary>Every sub-object ID listed in the model's metadata tables, whether or not it was matched.</summary>
	internal readonly HashSet<long> MetadataObjectIds = new();
	internal readonly Dictionary<long, RendererBinding> ReconstructedMeshes = new();
	/// <summary>Each uniquely named mesh node's transform relative to the model root, in file units and axes (as ModelDoc bakes it).</summary>
	internal readonly Dictionary<string, UnityTransform> MeshNodes = new( StringComparer.Ordinal );
	/// <summary>Each uniquely named mesh's bounds relative to the model root, in file units and axes.</summary>
	internal readonly Dictionary<string, (double[] Min, double[] Max)> MeshBounds = new( StringComparer.Ordinal );
	/// <summary>The file's axis system as a basis change into FBX's default Y-up axes.</summary>
	internal UnityTransform FileAxes { get; set; } = UnityTransform.Identity;
	/// <summary>The transform (file units and axes) of the file's only top node, which Unity makes the prefab root; null otherwise.</summary>
	internal UnityTransform CollapsedRoot { get; set; }
	/// <summary>Reconstructed IDs of interchangeable same-path objects, numbered in assumed traversal order.</summary>
	internal readonly HashSet<long> DuplicateIds = new();
	/// <summary>True when every mesh node received reconstructed renderer IDs (no malformed or ambiguous nodes).</summary>
	internal bool RendererIdsComplete { get; set; }
	// IDs read from model metadata tables are distinguished from IDs reconstructed from the FBX hierarchy.
	internal string RendererIdSource( long id ) => metadataRenderers.Contains( id ) ? "metadata" : DuplicateIds.Contains( id ) ? "reconstructed-duplicate" : "reconstructed";
	internal string MeshIdSource( long id ) => metadataMeshes.ContainsKey( id ) ? "metadata" : DuplicateIds.Contains( id ) ? "reconstructed-duplicate" : "reconstructed";
	readonly Dictionary<long, string> metadataMaterials = new();
	/// <summary>The FBX material whose embedded Unity material has this sub-asset ID, or null.</summary>
	internal string EmbeddedMaterialName( long id ) => metadataMaterials.GetValueOrDefault( id ) ?? Materials.FirstOrDefault( name => UnityFileId.Material( name ) == id );
	/// <summary>Slots whose prefab assignment is the model's own embedded material, generated by Unity from the FBX.</summary>
	public HashSet<string> EmbeddedSlots { get; } = new( StringComparer.OrdinalIgnoreCase );
	internal RendererBinding ResolveMesh( long id ) => metadataMeshes.GetValueOrDefault( id ) ?? ReconstructedMeshes.GetValueOrDefault( id );

	/// <summary>Sub-object IDs recorded in model metadata, as (Unity class ID, file ID, object name).</summary>
	internal static IEnumerable<(int Class, long Id, string Name)> MetadataIds( YamlNode metadata )
	{
		// Before Unity 2019.3: "fileID: name". Legacy IDs encode the class in their leading digits (2300000 = MeshRenderer).
		foreach ( var (key, value) in metadata?.Find( "fileIDToRecycleName" )?.Pairs ?? Array.Empty<KeyValuePair<string, YamlNode>>() )
			if ( long.TryParse( key, out var id ) && value.Value is string name ) yield return ((int)(id / 100000), id, name);
		// Unity 2019.3+: "- first: {classID: fileID}, second: name", keeping IDs from earlier imports.
		foreach ( var entry in metadata?.Find( "internalIDToNameTable" )?.Items ?? Array.Empty<YamlNode>() )
			if ( entry["first"]?.Pairs is [var (type, value)] && int.TryParse( type, out var classId ) && value.Integer is long id && entry["second"]?.Value is string name )
				yield return (classId, id, name);
	}

	void ApplyMetadataIds( YamlNode metadata, RendererBinding[] bindings = null )
	{
		bindings ??= RendererSlots.Values.Distinct().ToArray();
		foreach ( var (classId, id, name) in MetadataIds( metadata ) )
		{
			MetadataObjectIds.Add( id );
			if ( classId == 21 ) metadataMaterials.TryAdd( id, name ); // Material sub-asset generated inside the model
			var matches = name == "//RootNode" ? bindings : bindings.Where( b => b.Mesh == name ).ToArray();
			// Older Unity names repeated objects "Name 1", "Name 2"; only interchangeable duplicates share one binding.
			if ( matches.Length == 0 && Regex.Match( name, @"^(.+) [0-9]+$" ) is { Success: true } numbered )
				matches = bindings.Where( b => b.Mesh == numbered.Groups[1].Value ).ToArray();
			if ( matches.Length != 1 ) continue;
			if ( classId is 23 or 137 && RendererSlots.TryAdd( id, matches[0] ) ) metadataRenderers.Add( id ); // MeshRenderer or SkinnedMeshRenderer
			if ( classId == 43 ) metadataMeshes.TryAdd( id, matches[0] ); // Mesh
		}
	}
	/// <summary>A slot material chosen by the model's own import settings (externalObjects or Unity's legacy material search).</summary>
	public sealed record ImporterMaterial( string Guid, string Rule );
	public Dictionary<string, ImporterMaterial> ImporterMaterials { get; } = new( StringComparer.OrdinalIgnoreCase );
	/// <summary>How Unity imports this model's materials: none, embedded, or external with its naming/search settings.</summary>
	public string MaterialImport { get; internal set; }
	public Dictionary<string, string> PrefabSlotMaterials { get; } = new( StringComparer.OrdinalIgnoreCase );
	public HashSet<string> UnresolvedPrefabSlots { get; } = new( StringComparer.OrdinalIgnoreCase );
	public List<string> AssignmentWarnings { get; } = new();
	/// <summary>Assignment decisions that are not problems, such as which prefab variant became the default.</summary>
	public List<string> AssignmentNotes { get; } = new();
	/// <summary>One distinct set of slot materials used by Unity prefab placements, and the prefabs that use it.</summary>
	public sealed record PrefabVariant( string[] Prefabs, IReadOnlyDictionary<string, string> Slots );
	public List<PrefabVariant> PrefabVariants { get; } = new();
	/// <summary>Slots whose default is the most common of several conflicting prefab assignments.</summary>
	public HashSet<string> MostCommonSlots { get; } = new( StringComparer.OrdinalIgnoreCase );
	public List<PrefabSlotEvidence> PrefabEvidence { get; } = new();
	public bool CollisionOnly { get; internal set; }
	/// <summary>The model has no faces (an empty OBJ), so the model compiler cannot load it.</summary>
	public bool Empty { get; internal set; }
	/// <summary>Why the model file could not be read (it is then <see cref="Empty"/>), or null.</summary>
	public string ReadError { get; internal set; }
	/// <summary>Unity's "Generate Colliders" import setting: every mesh of the model gets an exact MeshCollider.</summary>
	public bool GenerateColliders { get; internal set; }
	public List<string> Materials { get; } = new();
	public List<string> Meshes { get; } = new();
	public List<string> PrefabMaterials { get; } = new();
	public Dictionary<string, string> MaterialAlbedoFiles { get; } = new( StringComparer.OrdinalIgnoreCase );
	public double? UnitScaleCentimeters { get; private set; }
	public double ImportScale( string metadata ) => ImportScale( metadata == null ? null : UnityYaml.Document( metadata ) );
	internal double ImportScale( YamlNode metadata )
	{
		double Setting( string key, double fallback ) => metadata?.Find( key )?.Number ?? fallback;
		var globalScale = Setting( "globalScale", 1 );
		var meters = Setting( "useFileScale", 1 ) == 0 ? 1 : (UnitScaleCentimeters ?? 2.54) / 100;
		var scale = globalScale * meters / 0.0254;
		if ( !double.IsFinite( scale ) || scale <= 0 ) throw new InvalidDataException( "Model import scale must be finite and positive." );
		return scale;
	}
	public string[] HighestDetailMeshes => Meshes.Where( n => Regex.IsMatch( n, @"(?i)(?:^|[_ .-])LOD0(?:$|[_ .-])" ) ).ToArray();
	/// <summary>Meshes Unity never shows: every prefab or scene placement names its meshes explicitly and none names these.</summary>
	public HashSet<string> HiddenMeshes { get; } = new( StringComparer.Ordinal );
	/// <summary>Meshes the VMDL imports: the highest LOD when LODs exist, without hidden meshes.</summary>
	/// <summary>
	/// The meshes a whole-model VMDL shows: with LOD-named meshes, LOD0 and every mesh without a LOD suffix (Unity renders
	/// those at every level); the lower levels come in as LOD levels instead.
	/// </summary>
	public string[] ImportedMeshes => (HighestDetailMeshes.Length > 0 ? Meshes.Where( m => !LowerLod.IsMatch( m ) ).ToArray() : Meshes.ToArray()).Where( m => !HiddenMeshes.Contains( m ) ).ToArray();
	static readonly Regex LowerLod = new( @"(?i)(?:^|[_ .-])LOD0*[1-9][0-9]*(?:$|[_ .-])" );
	/// <summary>Whether the mesh is a lower LOD level (LOD1 and up) of a model that has LOD0 meshes.</summary>
	public bool IsLowerLod( string mesh ) => HighestDetailMeshes.Length > 0 && LowerLod.IsMatch( mesh );
	/// <summary>
	/// Meshes grouped by LOD level, from names ending in LOD0, LOD1 and so on (Unity builds a LOD group from them), when the
	/// file has a LOD0 and at least one lower level; otherwise empty.
	/// </summary>
	public IReadOnlyList<string[]> LodLevels
	{
		get
		{
			var levels = Meshes.Where( m => !HiddenMeshes.Contains( m ) ).Select( m => (Mesh: m, Match: Regex.Match( m, @"(?i)(?:^|[_ .-])LOD([0-9])(?:$|[_ .-])" )) )
				.Where( x => x.Match.Success ).GroupBy( x => int.Parse( x.Match.Groups[1].Value, CultureInfo.InvariantCulture ) ).OrderBy( g => g.Key ).ToList();
			return levels.Count < 2 || levels[0].Key != 0 ? Array.Empty<string[]>() : levels.Select( g => g.Select( x => x.Mesh ).ToArray() ).ToArray();
		}
	}
	/// <summary>
	/// Switch thresholds for <see cref="LodLevels"/>: the model's LOD screen percentages, or Unity's defaults (60%, 30%,
	/// 10%, then halving), as s&amp;box switch distances for the LOD group Unity builds: its size is the largest axis of
	/// all levels' bounds, scaled to inches by the model's import scale.
	/// </summary>
	public double[] LodThresholds( YamlNode metadata, double scale )
	{
		var levels = LodLevels.Count;
		var size = LodSize( scale ) ?? UnityImport.DefaultLodSize;
		// Unity serializes m_LODScreenPercentages as "lODScreenPercentages" (the older spelling is read too).
		var percentages = ((metadata?.Find( "lODScreenPercentages" ) ?? metadata?.Find( "lodScreenPercentages" ))?.Items ?? Array.Empty<YamlNode>()).Select( i => i.Number ?? 0 ).Where( v => v > 0 ).ToList();
		var defaults = new List<double> { 0.6, 0.3, 0.1 };
		while ( defaults.Count < levels ) defaults.Add( defaults[^1] / 2 );
		return Enumerable.Range( 0, Math.Max( 0, levels - 1 ) ).Select( i => UnityImport.LodThreshold( i < percentages.Count ? percentages[i] : defaults[i], size ) ).ToArray();
	}
	/// <summary>The largest axis of the LOD levels' combined bounds in inches, or null when a level's bounds are unknown.</summary>
	internal double? LodSize( double scale )
	{
		var meshes = LodLevels.SelectMany( l => l ).ToArray();
		if ( meshes.Length == 0 || meshes.Any( m => !MeshBounds.ContainsKey( m ) ) ) return null;
		var size = Enumerable.Range( 0, 3 ).Max( a => meshes.Max( m => MeshBounds[m].Max[a] ) - meshes.Min( m => MeshBounds[m].Min[a] ) ) * scale;
		return size > 0 && double.IsFinite( size ) ? size : null;
	}
	/// <summary>The import filter's included meshes, or empty when every mesh is imported.</summary>
	public string[] FilteredMeshes => HighestDetailMeshes.Length > 0 || HiddenMeshes.Count > 0 ? ImportedMeshes : Array.Empty<string>();
	public string[] RenderedMaterials
	{
		get
		{
			var meshes = FilteredMeshes;
			var bindings = RendererSlots.Values.Where( b => meshes.Length == 0 || meshes.Contains( b.Mesh ) ).ToArray();
			return bindings.Length > 0 ? bindings.SelectMany( b => b.EffectiveSlots ).Distinct( StringComparer.OrdinalIgnoreCase ).ToArray() : Materials.ToArray();
		}
	}
	public static string Normalize( string name ) => Regex.Replace( name.ToLowerInvariant(), "[^a-z]", "" );

	/// <summary>OBJ meshes and slots: one mesh per object (or per group when the file has no objects), a slot per material used.</summary>
	static UnityModel ReadObj( UnityAsset asset )
	{
		var result = new UnityModel();
		var objects = new List<(string Name, List<string> Slots, bool Faces)>();
		var groups = new List<(string Name, List<string> Slots, bool Faces)>();
		int Open( List<(string Name, List<string> Slots, bool Faces)> list, string name )
		{
			var index = list.FindIndex( e => e.Name == name );
			if ( index < 0 ) { list.Add( (name, new List<string>(), false) ); index = list.Count - 1; }
			return index;
		}
		int currentObject = -1, currentGroup = -1;
		string material = null;
		var faces = false;
		// Vertex bounds per object and per group; OBJ vertices belong to the object or group they follow.
		var bounds = new Dictionary<string, (double[] Min, double[] Max)>();
		void Extend( string key, double[] v )
		{
			if ( key == null ) return;
			if ( !bounds.TryGetValue( key, out var b ) ) bounds[key] = b = (v.ToArray(), v.ToArray());
			for ( var a = 0; a < 3; a++ ) { b.Min[a] = Math.Min( b.Min[a], v[a] ); b.Max[a] = Math.Max( b.Max[a], v[a] ); }
		}
		void Use( List<(string Name, List<string> Slots, bool Faces)> list, int index )
		{
			if ( index < 0 ) return;
			var entry = list[index];
			if ( material != null && !entry.Slots.Contains( material ) ) entry.Slots.Add( material );
			list[index] = entry with { Faces = true };
		}
		using ( var reader = new StreamReader( asset.Source ) )
		{
			string line;
			while ( (line = reader.ReadLine()) != null )
			{
				var parts = line.Trim().Split( (char[])null, 2, StringSplitOptions.RemoveEmptyEntries );
				if ( parts.Length == 0 ) continue;
				var value = parts.Length > 1 ? parts[1].Trim() : "";
				if ( parts[0] == "o" ) currentObject = Open( objects, value );
				else if ( parts[0] == "g" ) currentGroup = Open( groups, value );
				else if ( parts[0] == "usemtl" && value.Length > 0 )
				{
					material = value;
					if ( !result.Materials.Contains( value ) ) result.Materials.Add( value );
				}
				else if ( parts[0] == "f" ) { Use( objects, currentObject ); Use( groups, currentGroup ); faces = true; }
				else if ( parts[0] == "v" && value.Split( (char[])null, StringSplitOptions.RemoveEmptyEntries ) is { Length: >= 3 } xyz &&
					xyz.Take( 3 ).Select( t => double.TryParse( t, NumberStyles.Float, CultureInfo.InvariantCulture, out var n ) ? n : double.NaN ).ToArray() is var v && v.All( double.IsFinite ) )
				{
					Extend( currentObject >= 0 ? "o:" + objects[currentObject].Name : null, v );
					Extend( currentGroup >= 0 ? "g:" + groups[currentGroup].Name : null, v );
					Extend( "file", v );
				}
			}
		}
		var meshes = (objects.Count > 0 ? objects : groups).Where( e => e.Faces && e.Name.Length > 0 ).ToList();
		// Without named objects or groups the whole file is one mesh, named by Unity after the file.
		result.Empty = !faces;
		if ( meshes.Count == 0 ) meshes.Add( (Path.GetFileNameWithoutExtension( asset.Path ), result.Materials, true) );
		result.Meshes.AddRange( meshes.Select( m => m.Name ) );
		var prefix = objects.Count > 0 ? "o:" : "g:";
		foreach ( var mesh in result.Meshes )
			if ( bounds.TryGetValue( result.Meshes.Count == 1 && !bounds.ContainsKey( prefix + mesh ) ? "file" : prefix + mesh, out var box ) ) result.MeshBounds[mesh] = box;
		result.ApplyMetadataIds( asset.MetadataDocument, meshes.Select( m => new RendererBinding( m.Name, m.Slots.ToArray() ) ).ToArray() );
		return result;
	}

	public static UnityModel Read( UnityAsset asset )
	{
		var result = new UnityModel();
		if ( asset.Path.EndsWith( ".obj", StringComparison.OrdinalIgnoreCase ) ) return ReadObj( asset );
		if ( !asset.Path.EndsWith( ".fbx", StringComparison.OrdinalIgnoreCase ) ) return result;
		using var stream = File.OpenRead( asset.Source );
		using var reader = new BinaryReader( stream, Encoding.UTF8 );
		var header = Encoding.ASCII.GetString( reader.ReadBytes( 23 ) );
		if ( !header.StartsWith( "Kaydara FBX Binary", StringComparison.Ordinal ) )
		{
			stream.Position = 0;
			using var textReader = new StreamReader( stream );
			var links = new UnityAsciiFbxLinks();
			var asciiBindings = new UnityFbxBindings();
			string line;
			while ( (line = textReader.ReadLine()) != null )
			{
				links.Observe( line );
				asciiBindings.ObserveAscii( line );
				var unit = Regex.Match( line, "^\\s*(?:P|Property):\\s*\"UnitScaleFactor\".*?,\\s*([-+0-9.eE]+)\\s*$" );
				if ( unit.Success && double.TryParse( unit.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var centimeters ) && centimeters > 0 && double.IsFinite( centimeters ) ) result.UnitScaleCentimeters = centimeters;
				var material = Regex.Match( line, "^\\s*Material:\\s*(?:[-0-9]+,\\s*)?\"Material::([^\"]+)\"" );
				if ( material.Success && !result.Materials.Contains( material.Groups[1].Value ) ) result.Materials.Add( material.Groups[1].Value );
				var mesh = Regex.Match( line, "^\\s*Model:\\s*(?:[-0-9]+,\\s*)?\"Model::([^\"]+)\",\\s*\"Mesh\"" );
				if ( mesh.Success && !result.Meshes.Contains( mesh.Groups[1].Value ) ) result.Meshes.Add( mesh.Groups[1].Value );
			}
			foreach ( var link in links.Resolve() ) result.MaterialAlbedoFiles[link.Key] = link.Value;
			asciiBindings.FinishAscii();
			asciiBindings.Apply( result, asset.MetadataDocument?.Find( "preserveHierarchy" )?.Value == "1" );
			result.ApplyMetadataIds( asset.MetadataDocument );
			return result;
		}
		var wide = reader.ReadUInt32() >= 7500;
		var materialNames = new Dictionary<long, string>();
		var textureFiles = new Dictionary<long, string>();
		var diffuseLinks = new List<(long Texture, long Material)>();
		var bindings = new UnityFbxBindings();
		int nodes = 0;
		// Polygon material indices, read only for their first-use order (Unity's submesh order).
		List<int> MaterialIndices( long end )
		{
			var type = (char)reader.ReadByte();
			if ( type != 'i' ) return null;
			var count = reader.ReadUInt32();
			var encoding = reader.ReadUInt32();
			var length = reader.ReadUInt32();
			if ( count > 64 * 1024 * 1024 || stream.Position + length > end ) throw new InvalidDataException( "Invalid FBX material array." );
			var bytes = reader.ReadBytes( (int)length );
			using var data = encoding == 1 ? (Stream)new ZLibStream( new MemoryStream( bytes ), CompressionMode.Decompress ) : new MemoryStream( bytes );
			using var values = new BinaryReader( data );
			var order = new List<int>();
			for ( var i = 0; i < count; i++ )
			{
				var index = values.ReadInt32();
				if ( !order.Contains( index ) ) order.Add( index );
			}
			return order;
		}
		// Control points, read only for their bounds.
		void VertexBounds( long owner, long end )
		{
			var type = (char)reader.ReadByte();
			if ( type is not ('d' or 'f') ) return;
			var count = reader.ReadUInt32();
			var encoding = reader.ReadUInt32();
			var length = reader.ReadUInt32();
			if ( count > 256 * 1024 * 1024 || stream.Position + length > end ) throw new InvalidDataException( "Invalid FBX vertex array." );
			var bytes = reader.ReadBytes( (int)length );
			using var data = encoding == 1 ? (Stream)new ZLibStream( new MemoryStream( bytes ), CompressionMode.Decompress ) : new MemoryStream( bytes );
			using var values = new BinaryReader( data );
			var bounds = new UnityFbxBindings.BoundsBuilder( owner );
			for ( var i = 0; i < count; i++ ) bounds.Add( type == 'd' ? values.ReadDouble() : values.ReadSingle() );
			bounds.Finish( bindings );
		}
		void ReadNodes( long limit, bool objects = false, bool connections = false, long textureId = 0, bool settings = false, long owner = 0, bool layer = false, long node = 0 )
		{
			while ( stream.Position + (wide ? 25 : 13) <= limit )
			{
				if ( ++nodes > 2000000 ) throw new InvalidDataException( "Too many FBX nodes." );
				var end = wide ? (long)reader.ReadUInt64() : reader.ReadUInt32();
				var properties = wide ? (long)reader.ReadUInt64() : reader.ReadUInt32();
				var propertyBytes = wide ? (long)reader.ReadUInt64() : reader.ReadUInt32();
				var nameBytes = reader.ReadByte();
				if ( end == 0 ) return;
				if ( end <= stream.Position || end > stream.Length ) throw new InvalidDataException( "Invalid FBX node offset." );
				var name = Encoding.UTF8.GetString( reader.ReadBytes( nameBytes ) );
				var children = stream.Position + propertyBytes;
				if ( children > end ) throw new InvalidDataException( "Invalid FBX property size." );
				object Property()
				{
						var type = (char)reader.ReadByte();
						if ( type == 'L' ) return reader.ReadInt64();
						if ( type == 'I' ) return reader.ReadInt32();
						if ( type == 'D' ) return reader.ReadDouble();
						if ( type == 'F' ) return reader.ReadSingle();
						if ( type == 'S' )
						{
							var length = reader.ReadInt32();
							if ( length < 0 || length > 1024 * 1024 || stream.Position + length > children ) throw new InvalidDataException( "Invalid FBX string." );
							return Encoding.UTF8.GetString( reader.ReadBytes( length ) );
						}
						if ( type == 'C' ) return reader.ReadByte() != 0;
						if ( type == 'Y' ) return reader.ReadInt16();
						if ( type is 'f' or 'd' or 'l' or 'i' or 'b' )
						{
							reader.ReadUInt32(); reader.ReadUInt32();
							var bytes = reader.ReadUInt32();
							if ( stream.Position + bytes > children ) throw new InvalidDataException( "Invalid FBX array." );
							stream.Position += bytes;
							return null;
						}
						throw new InvalidDataException( "Unsupported FBX object property." );
				}
				if ( objects && name is "Material" or "Model" or "Texture" or "Geometry" && properties >= 3 )
				{
					var id = Convert.ToInt64( Property() );
					var objectName = (Property() as string ?? "").Split( '\0' )[0];
					var typeName = Property() as string;
					if ( name == "Material" ) { result.Materials.Add( objectName ); materialNames[id] = objectName; bindings.Materials[id] = objectName; }
					if ( name == "Model" )
					{
						bindings.Nodes[id] = (objectName, typeName == "Mesh");
						if ( typeName == "Mesh" ) result.Meshes.Add( objectName );
					}
					if ( name == "Texture" ) { stream.Position = children; ReadNodes( end, textureId: id ); }
					// FBX 7 keeps polygon materials on Geometry objects; FBX 6 keeps them on the mesh model.
					// Every model node also carries its transform properties.
					if ( name == "Model" || name == "Geometry" ) { stream.Position = children; ReadNodes( end, owner: id ); }
				}
				else if ( owner != 0 && !layer && name == "LayerElementMaterial" && !bindings.MaterialOrder.ContainsKey( owner ) ) { stream.Position = children; ReadNodes( end, owner: owner, layer: true ); }
				else if ( layer && name == "Materials" && properties >= 1 && MaterialIndices( end ) is { } order ) bindings.MaterialOrder[owner] = order;
				else if ( owner != 0 && !layer && name == "Vertices" && properties >= 1 && !bindings.VertexBounds.ContainsKey( owner ) )
				{
					// Bounds only size LOD groups: an unreadable vertex array leaves the mesh without bounds, not the model unread.
					try { VertexBounds( owner, end ); }
					catch ( Exception ex ) when ( ex is InvalidDataException or EndOfStreamException ) { }
				}
				else if ( owner != 0 && !layer && name is "Properties70" or "Properties60" && bindings.Nodes.ContainsKey( owner ) ) { stream.Position = children; ReadNodes( end, node: owner ); }
				else if ( node != 0 && name is "P" or "Property" && properties >= 2 && properties <= 16 )
				{
					var propertyName = Property() as string;
					var values = new List<double>();
					for ( var index = 1; index < properties; index++ ) if ( Property() is var value && value is double or float or int or long or short ) values.Add( Convert.ToDouble( value, CultureInfo.InvariantCulture ) );
					if ( propertyName != null ) bindings.Property( node, propertyName, values.ToArray() );
				}
				else if ( textureId != 0 && name is "FileName" or "RelativeFilename" && properties > 0 ) textureFiles[textureId] = Property() as string;
				else if ( settings && name is "P" or "Property" && properties >= 4 && properties <= 8 )
				{
					var propertyName = Property() as string;
					object value = null;
					for ( var index = 1; index < properties; index++ ) value = Property();
					if ( value is double or float or int or long or short )
					{
						var number = Convert.ToDouble( value, CultureInfo.InvariantCulture );
						if ( propertyName == "UnitScaleFactor" && number > 0 && double.IsFinite( number ) ) result.UnitScaleCentimeters = number;
						else if ( propertyName != null ) bindings.Property( 0, propertyName, new[] { number } );
					}
				}
				else if ( connections && name == "C" && properties >= 3 )
				{
					var kind = Property() as string;
					var child = Convert.ToInt64( Property() );
					var parent = Convert.ToInt64( Property() );
					var channel = properties >= 4 ? Property() as string ?? "" : "";
					if ( kind == "OO" ) bindings.Connections.Add( (child, parent) );
					if ( kind == "OP" && (channel == "DiffuseColor" || channel.EndsWith( "|base_color_map", StringComparison.Ordinal )) ) diffuseLinks.Add( (child, parent) );
				}
				if ( name == "Objects" ) { stream.Position = children; ReadNodes( end, true ); }
				if ( name == "Connections" ) { stream.Position = children; ReadNodes( end, connections: true ); }
				if ( name == "GlobalSettings" || settings && name is "Properties70" or "Properties60" ) { stream.Position = children; ReadNodes( end, settings: true ); }
				stream.Position = end;
			}
		}
		ReadNodes( stream.Length, false );
		bindings.Apply( result, asset.MetadataDocument?.Find( "preserveHierarchy" )?.Value == "1" );
		result.ApplyMetadataIds( asset.MetadataDocument );
		foreach ( var link in diffuseLinks )
			if ( materialNames.TryGetValue( link.Material, out var material ) && textureFiles.TryGetValue( link.Texture, out var file ) && !string.IsNullOrEmpty( file ) )
				result.MaterialAlbedoFiles[material] = file.Replace( '\\', '/' ).Split( '/' ).Last();
		return result;
	}

	public static void AssignPrefabMaterials( UnityArchive archive )
	{
		// Model import settings first: prefab conflicts fall back to them.
		UnityModelMaterials.Apply( archive );
		UnityPrefabBindings.Apply( archive );
	}
}