Editor/Core/UnityImport.cs

Editor helper that imports Unity package assets into the project. It reads a UnityArchive and ImportPlan, converts textures, materials, models, terrains, sounds, prefabs and scenes into engine/editor formats, stages files, generates reports and handles many conversion heuristics.

File AccessExternal Download
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;

namespace ImportUnityPackage;

/// <summary>Meshes from one file, filtered to the named nodes (all when empty), at an import scale.</summary>
internal sealed record MeshPart( string File, string[] Meshes, double Scale );
public record ImportOptions( bool Materials, bool Models, bool Vmat, bool Tmat, bool Vmdl )
{
	public bool Automatic { get; init; }
	public bool TerrainDefinitions { get; init; } = true;
	public bool Vtex { get; init; } = true;
	public bool Sound { get; init; } = true;
	public bool Prefabs { get; init; } = true;
	public bool Scenes { get; init; } = true;
	public bool Terrains { get; init; } = true;
	// Keep programmatic callers compatible; the editor window chooses its destination explicitly.
	public bool ImportToAssets { get; init; } = true;
	public static ImportOptions Auto( bool additionalTerrainMaterials = false ) => new( true, true, true, additionalTerrainMaterials, true ) { Automatic = true };
}
public record ImportIssue( string Asset, string Code, string Message )
{
	// Compatibility fallbacks are warnings; failing to produce a selected resource is an error.
	public string Severity => Code is "conversion-skipped" or "unreadable-model" or "texture-processing-failed" ? "Error" : "Warning";
}
public record ImportResult( string Directory, int AssetCount, int ConvertedCount, string[] Files, string[] Warnings )
{
	public bool RequiresResourcePreparation { get; init; } = true;
	public ImportIssue[] Unresolved { get; init; } = Array.Empty<ImportIssue>();
	public string ReportJson { get; init; }
	public void ExportReport( string path ) => File.WriteAllText( path, ReportJson );
	public string[] ChangedFiles { get; init; } = Array.Empty<string>();
	/// <summary>Written files that replaced an existing file (the only ones whose dependants may need rebuilding).</summary>
	public string[] ReplacedFiles { get; init; } = Array.Empty<string>();
	public string[] Information { get; init; } = Array.Empty<string>();
}
/// <summary>
/// One derived image from Source: a channel (Channel 0-3, scaled and optionally inverted), the whole image (-1), the
/// image with its green channel flipped (-3), or a normal map from the image as height (-4: Scale is Unity's bumpiness,
/// Invert selects the Sobel filter); resized first when Width and Height are set. With Faces, a sky panorama composed
/// from six cube faces (Width 0 picks the size).
/// </summary>
public record TextureChannelRequest( string Source, string Destination, int Channel, double Scale, bool Invert, int Width = 0, int Height = 0, SkyFace[] Faces = null );
public delegate void ExtractTextureChannels( IReadOnlyList<TextureChannelRequest> requests, CancellationToken cancel );

/// <summary>
/// Thrown by a texture batch after every request was processed, listing the requests whose source could not be read or
/// converted; each of those destinations holds a neutral placeholder.
/// </summary>
public sealed class TextureBatchException : Exception
{
	public sealed record Failure( string Source, string Destination, string Message );
	public IReadOnlyList<Failure> Failures { get; }
	public TextureBatchException( IReadOnlyList<Failure> failures ) : base( $"{failures.Count} texture outputs could not be generated." ) { Failures = failures; }
}

public static class UnityImport
{
	public static bool NeedsTextureResource( string path ) => Path.GetExtension( path ).ToLowerInvariant() is ".exr" or ".psd" or ".tif" or ".tiff";
	public static bool IsEnabled( UnityAsset asset, ImportOptions options ) => asset.Kind switch
	{
		UnityAssetKind.Material or UnityAssetKind.Texture => options.Materials,
		UnityAssetKind.Model or UnityAssetKind.ModelSupport => options.Models,
		UnityAssetKind.Sound => true,
		UnityAssetKind.Prefab => options.Models && options.Prefabs,
		UnityAssetKind.Scene => options.Models && options.Scenes,
		UnityAssetKind.Terrain => options.Terrains,
		_ => false
	};

	public static HashSet<UnityAsset> Selection( UnityArchive archive, ImportOptions options ) =>
		ImportCatalog.Read( archive ).CreatePlan( options ).Assets.Select( a => a.Asset ).ToHashSet();

	internal static string ReadText( string path )
	{
		if ( new FileInfo( path ).Length > 16 * 1024 * 1024 ) throw new InvalidDataException( "Material or metadata exceeds the 16 MiB text limit." );
		return File.ReadAllText( path );
	}

	public static ImportResult Run( UnityArchive archive, string assetsDirectory, ImportOptions options,
		IProgress<ImportProgress> progress, CancellationToken cancel, ExtractTextureChannels extractChannels = null )
		=> Run( ImportCatalog.Read( archive, cancel ).CreatePlan( options ), assetsDirectory, progress, cancel, extractChannels );

	public static ImportResult Run( ImportPlan plan, string assetsDirectory,
		IProgress<ImportProgress> progress, CancellationToken cancel, ExtractTextureChannels extractChannels = null )
	{
		using var merge = ImportMergePlan.Create( plan, assetsDirectory, cancel );
		merge.Prepare( progress, cancel, extractChannels );
		var result = merge.Commit( progress, cancel );
		merge.Dispose();
		return result with { Warnings = result.Warnings.Concat( merge.CleanupWarnings ).Distinct().ToArray() };
	}

	internal static ImportResult PrepareFiles( ImportPlan plan, string stageDirectory, string destination,
		IProgress<ImportProgress> progress, CancellationToken cancel, ExtractTextureChannels extractChannels )
	{
		cancel.ThrowIfCancellationRequested();
		var archive = plan.Archive;
		var options = plan.Options;
		var selected = plan.Assets.Select( a => a.Asset ).ToArray();
		if ( selected.Length == 0 ) throw new InvalidOperationException( "Select at least one supported asset." );
		var stage = Path.GetFullPath( stageDirectory );
		CheckDirectory( stage );
		const string prefix = "Imported/";
		var warnings = new List<string>( archive.Warnings );
		var information = new List<string>();
		if ( !options.ImportToAssets ) information.Add( "Stored outside Assets. Use Import to assets to make these files available in the editor and game." );
		var unresolved = new List<ImportIssue>( plan.Issues );
		warnings.AddRange( plan.Issues.Select( i => $"{i.Asset}: {i.Message}" ) );
		void Issue( string asset, string code, string message )
		{
			unresolved.Add( new( asset, code, message ) );
			warnings.Add( $"{asset}: {message}" );
		}
		var files = new List<string>();
		var outputs = new HashSet<string>( StringComparer.OrdinalIgnoreCase );
		var textures = selected.Where( a => a.Kind == UnityAssetKind.Texture ).ToDictionary( a => a.Guid, a => prefix + a.Path, StringComparer.OrdinalIgnoreCase );
		var textureSources = selected.Where( a => a.Kind == UnityAssetKind.Texture ).ToDictionary( a => a.Guid, StringComparer.OrdinalIgnoreCase );
		// Lookups by GUID and path instead of scans over every asset (large packages have tens of thousands).
		var selectedByGuid = selected.GroupBy( a => a.Guid, StringComparer.OrdinalIgnoreCase ).ToDictionary( g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase );
		var assetsByGuid = archive.Assets.GroupBy( a => a.Guid, StringComparer.OrdinalIgnoreCase ).ToDictionary( g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase );
		var assetPaths = archive.Assets.Select( a => a.Path ).ToHashSet( StringComparer.OrdinalIgnoreCase );
		// The selected material with this GUID when its VMAT is written by this import.
		UnityAsset SelectedVmat( string guid ) => guid != null && selectedByGuid.TryGetValue( guid, out var a ) && outputs.Contains( Path.ChangeExtension( a.Path, ".vmat" ) ) ? a : null;
		var generatedFiles = new GeneratedAssetFiles( plan, stage, destination );
		var documents = new List<(string File, string Text)>();
		var generatedChannels = new Dictionary<string, string>();
		var channelRequests = new List<TextureChannelRequest>();
		var channelTimer = new System.Diagnostics.Stopwatch();
		// Time per import stage, for the report: each mark records the time since the previous one.
		var stageTimer = System.Diagnostics.Stopwatch.StartNew();
		var stageTimes = new List<(string Stage, long Milliseconds)>();
		void Mark( string stage ) { stageTimes.Add( (stage, stageTimer.ElapsedMilliseconds) ); stageTimer.Restart(); }
		var shaders = archive.Assets.Where( a => a.Path.EndsWith( ".shader", StringComparison.OrdinalIgnoreCase ) || a.Path.EndsWith( ".shadergraph", StringComparison.OrdinalIgnoreCase ) ).ToDictionary( a => a.Guid, StringComparer.OrdinalIgnoreCase );
		var shaderText = new Dictionary<string, string>( StringComparer.OrdinalIgnoreCase );
		var convertedMaterials = new Dictionary<string, UnityMaterial>( StringComparer.OrdinalIgnoreCase );
		var skies = new Dictionary<string, ConvertedSky>( StringComparer.OrdinalIgnoreCase );
		var conversions = 0;
		var assignments = new List<object>();
		var ruleCounts = new SortedDictionary<string, int>();
		var idCounts = new SortedDictionary<string, int>();
		var materialGroups = 0;
		var hiddenMeshes = 0;
		// Imported models as prefabs and scenes place them, and the prefab/scene conversion results.
		var prefabModels = new Dictionary<string, PrefabModel>( StringComparer.OrdinalIgnoreCase );
		var placements = new List<UnityPrefabConverter.Summary>();
		var terrains = new List<object>();
		var materialPaths = archive.Assets.Where( a => a.Kind == UnityAssetKind.Material ).ToDictionary( a => a.Guid, a => a.Path, StringComparer.OrdinalIgnoreCase );
		object ReportEvidence( UnityModel.PrefabSlotEvidence e ) => new
		{
			e.Prefab, e.Applied, Renderer = e.Id, e.IdSource, e.Mesh, e.Index,
			Material = materialPaths.GetValueOrDefault( e.Material ?? "" ) ?? e.Material, e.Problem
		};
		// Audio files of one name in different formats compile to the same sound resource: one is kept (WAV, then OGG,
		// then MP3) and the others are skipped and reported, as is a sound whose name another format already uses.
		var soundResources = new HashSet<string>( StringComparer.OrdinalIgnoreCase );
		var skippedSounds = new HashSet<UnityAsset>();
		var formats = new[] { ".wav", ".ogg", ".mp3" };
		foreach ( var sound in selected.Where( a => a.Kind == UnityAssetKind.Sound ).OrderBy( a => Array.IndexOf( formats, Path.GetExtension( a.Path ).ToLowerInvariant() ) ) )
		{
			var existing = formats.FirstOrDefault( extension => !Path.GetExtension( sound.Path ).Equals( extension, StringComparison.OrdinalIgnoreCase ) &&
				File.Exists( Path.Combine( destination, Path.ChangeExtension( sound.Path, extension ) ) ) );
			if ( soundResources.Add( Path.ChangeExtension( sound.Path, ".vsnd" ) ) && existing == null ) continue;
			skippedSounds.Add( sound );
			Issue( sound.Path, "sound-name-conflict", existing != null
				? $"The project already has '{Path.ChangeExtension( sound.Path, existing )}', which compiles to the same sound resource; this file was not imported."
				: "Another selected audio file of the same name compiles to the same sound resource; this file was not imported." );
		}
		// Model files that would write the same VMDL (Rock.fbx and Rock.obj, or names that fold to the same ASCII name): one
		// keeps the VMDL (FBX first, then by path) and the others are reported; their source files are still imported.
		var skippedModels = new HashSet<UnityAsset>();
		foreach ( var clash in selected.Where( a => plan.Find( a ).Vmdl ).GroupBy( a => ModelOutput( a.Path ), StringComparer.OrdinalIgnoreCase ).Where( g => g.Count() > 1 ) )
		{
			var kept = clash.OrderBy( a => Path.GetExtension( a.Path ).Equals( ".fbx", StringComparison.OrdinalIgnoreCase ) ? 0 : 1 ).ThenBy( a => a.Path, StringComparer.Ordinal ).First();
			foreach ( var other in clash.Where( a => a != kept ) )
			{
				skippedModels.Add( other );
				Issue( other.Path, "output-name-conflict", $"'{kept.Path}' writes the same model resource ({clash.Key}); this model's source is imported without a VMDL." );
			}
		}
		var operation = "creating the staging folder";
		string currentAsset = null;
		Exception failure = null;
		var preserveStage = false;
		try
		{
			Directory.CreateDirectory( stage );
			string Output( string relative )
			{
				if ( !outputs.Add( relative ) ) throw new InvalidDataException( $"Two assets generate the same output: {relative}" );
				var full = Path.GetFullPath( Path.Combine( stage, relative + ".iup" ) );
				if ( !full.StartsWith( stage + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase ) ) throw new InvalidDataException( "Invalid output path." );
				Directory.CreateDirectory( Path.GetDirectoryName( full ) );
				files.Add( relative );
				return full;
			}
			// Model VMDLs that Unity colliders can put their physics shape in, as s&box models carry their own collision.
			// Their text is rendered again with the shape before files are written.
			var physicsModels = new Dictionary<string, PhysicsModel>( StringComparer.OrdinalIgnoreCase );
			void AddModel( string relative, Func<MeshPart, bool, string> text, MeshPart physics = null, bool convex = false )
			{
				var document = text( physics, convex ); documents.Add( (Output( relative ), document) );
				physicsModels[prefix + relative] = new PhysicsModel { Document = documents.Count - 1, Text = text, Physics = physics, Convex = convex };
			}
			// A collider's shape in the model it uses: accepted unless that model already holds a different shape.
			bool EmbedPhysics( string model, MeshPart shape, bool convex )
			{
				if ( !physicsModels.TryGetValue( model, out var target ) ) return false;
				if ( target.Physics == null ) { target.Physics = shape; target.Convex = convex; return true; }
				return target.Convex == convex && target.Physics.File == shape.File && target.Physics.Meshes.SequenceEqual( shape.Meshes );
			}
			for ( var i = 0; i < selected.Length; i++ )
			{
				cancel.ThrowIfCancellationRequested();
				var asset = selected[i];
				operation = "writing imported files";
				currentAsset = asset.Path;
				var planned = plan.Find( asset );
				if ( asset.Kind == UnityAssetKind.Model && asset.ModelInfo.CollisionOnly )
					information.Add( $"{asset.Path}: used only by Unity MeshColliders; kept as a collision source without a visible VMDL. Physics setup is not recreated." );
				progress?.Report( new( 0.8 * i / selected.Length, $"Preparing {asset.Path}", "Preparing assets" ) );
				// Prefabs and scenes are converted after every model; their Unity YAML sources are not copied.
				if ( planned.Prefab || planned.Scene || planned.Terrain || skippedSounds.Contains( asset ) ) continue;
				using ( var source = File.OpenRead( asset.Source ) )
				using ( var target = new FileStream( Output( asset.Path ), FileMode.CreateNew ) )
						UnityArchive.Copy( source, target, cancel );
				if ( planned.Sound )
				{
					// Sound events reference the native compiled sound resource, not an absolute source path.
					documents.Add( (Output( Path.ChangeExtension( asset.Path, ".sound" ) ), JsonSerializer.Serialize( new
					{
						__version = 1, UI = false, Volume = "1", Pitch = "1",
						Sounds = new[] { prefix + Path.ChangeExtension( asset.Path, ".vsnd" ) }
					}, new JsonSerializerOptions { WriteIndented = true } )) );
					conversions++;
				}
				if ( planned.Vtex )
				{
					// Keep source pixels/HDR data intact and give the editor a loadable texture resource.
					File.WriteAllText( Output( asset.Path + ".vtex" ), JsonSerializer.Serialize( new
					{
						Images = new[] { prefix + asset.Path }, InputColorSpace = "Linear", OutputColorSpace = "Linear",
						OutputFormat = asset.Path.EndsWith( ".exr", StringComparison.OrdinalIgnoreCase ) ? "RGBA16161616F" : "BC7",
						OutputMipAlgorithm = "Box", OutputTypeString = "2D"
					}, new JsonSerializerOptions { WriteIndented = true } ) );
					conversions++;
				}
				if ( planned.Vmat || planned.Tmat )
				{
					try
					{
						var material = UnityMaterial.Parse( ReadText( asset.Source ) );
						if ( material.ShaderGuid != null && shaders.TryGetValue( material.ShaderGuid, out var shader ) )
						{
							if ( !shaderText.TryGetValue( shader.Guid, out var source ) ) shaderText[shader.Guid] = source = ReadText( shader.Source );
							material.ConfigureShader( source, Path.GetFileNameWithoutExtension( shader.Path ) );
						}
						// Unity rounds non-power-of-two textures to the nearest power of two (nPOTScale) before use. s&box's mip
						// generators for alpha-weighted color and for roughness reject other sizes, so material textures are resized too.
						(int Width, int Height) PowerOfTwo( UnityAsset texture )
						{
							if ( extractChannels == null ||
								Path.GetExtension( texture.Path ).ToLowerInvariant() is not (".png" or ".jpg" or ".jpeg" or ".tga" or ".psd" or ".tif" or ".tiff") ||
								(texture.MetadataDocument?.Find( "nPOTScale" )?.Number ?? 1) == 0 || UnityImageSize.Read( texture.Source ) is not var (width, height) ||
								UnityImageSize.IsPowerOfTwo( width ) && UnityImageSize.IsPowerOfTwo( height ) ) return default;
							return (UnityImageSize.NearestPowerOfTwo( width ), UnityImageSize.NearestPowerOfTwo( height ));
						}
						string Derive( UnityAsset source, int channel, double scale, bool invert, string purpose )
						{
							var size = PowerOfTwo( source );
							var key = $"{source.Guid}_{channel}_{scale.ToString( System.Globalization.CultureInfo.InvariantCulture )}_{invert}_{size.Width}x{size.Height}";
							if ( !generatedChannels.TryGetValue( key, out var generated ) )
							{
								var derived = generatedFiles.Add( source.Path, purpose, ".png" );
								generated = derived.Reference;
								channelRequests.Add( new( source.Source, derived.File, channel, scale, invert, size.Width, size.Height ) );
								generatedChannels[key] = generated;
								if ( channel == -1 ) information.Add( $"{asset.Path}: resized '{source.Path}' to {size.Width}x{size.Height}, as Unity does for non-power-of-two textures." );
							}
							return generated;
						}
						if ( extractChannels != null )
						{
							material.PrepareChannels( (guid, channel, scale, invert) =>
							{
								if ( !textureSources.TryGetValue( guid, out var source ) )
								{
									Issue( asset.Path, "missing-texture", material.MissingTexture( guid ) );
									return null;
								}
								return Derive( source, channel, scale, invert, channel switch { 0 => "metallic", 1 => "ao", 2 => "height", _ => invert ? "roughness" : "opacity" } );
							} );
						}
						string Resolve( string guid )
						{
							if ( textures.TryGetValue( guid, out var texture ) ) return texture;
							Issue( asset.Path, "missing-texture", material.MissingTexture( guid ) );
							return null;
						}
						string ResolveVmat( string guid ) =>
							textureSources.TryGetValue( guid, out var source ) && PowerOfTwo( source ) != default ? Derive( source, -1, 1, false, "pot" ) : Resolve( guid );
						// Normal maps Unity prepares on import: Flip Green Channel turns a DirectX-style map into Unity's OpenGL style,
						// which s&box shares (measured in the engine), and Create from Grayscale makes a normal map from a height image.
						string ResolveNormal( string guid )
						{
							if ( extractChannels == null || !textureSources.TryGetValue( guid, out var source ) ) return ResolveVmat( guid );
							var settings = source.MetadataDocument;
							if ( (settings?.Find( "convertToNormalMap" )?.Number ?? 0) == 1 )
								return Derive( source, -4, settings.Find( "heightScale" )?.Number ?? 0.25, (settings.Find( "normalMapFilter" )?.Number ?? 0) == 1, "normal" );
							return (settings?.Find( "flipGreenChannel" )?.Number ?? 0) == 1 ? Derive( source, -3, 1, false, "normal" ) : ResolveVmat( guid );
						}
						if ( planned.Vmat && UnitySky.Detect( material ) is { } sky )
						{
							// Skybox materials become sky materials, which scenes' environments use.
							var problem = sky.Problem;
							string image = null;
							SkyFace[] faces = null;
							static bool Decodable( UnityAsset texture ) => Path.GetExtension( texture.Path ).ToLowerInvariant() is ".png" or ".jpg" or ".jpeg" or ".tga" or ".psd" or ".tif" or ".tiff";
							if ( problem == null && sky.Type == UnitySky.Kind.Faces )
							{
								var sources = sky.Faces.Select( g => textureSources.GetValueOrDefault( g ) ).ToArray();
								if ( sources.Any( t => t == null ) ) problem = material.MissingTexture( sky.Faces.First( g => !textureSources.ContainsKey( g ) ) );
								else if ( sources.FirstOrDefault( t => !Decodable( t ) ) is { } hdr ) problem = $"The sky face '{hdr.Path}' is not an image format the editor can compose.";
								else faces = sources.Select( t => new SkyFace( t.Source, 0, 0, 0, 0, false ) ).ToArray();
							}
							else if ( problem == null && sky.Type == UnitySky.Kind.Panorama )
							{
								if ( !textureSources.TryGetValue( sky.Texture, out var texture ) ) problem = material.MissingTexture( sky.Texture );
								else
								{
									var size = UnityImageSize.Read( texture.Source );
									var layout = sky.Panoramic && !sky.Frames ? UnitySky.Layout.LatLong : UnitySky.CubeLayout( size, (int)(texture.MetadataDocument?.Find( "generateCubemap" )?.Number ?? 6), sky.Frames );
									if ( layout == null ) problem = $"The sky texture '{texture.Path}' uses a cube layout that is not converted (sphere maps and unrecognized aspect ratios).";
									else if ( layout == UnitySky.Layout.LatLong ) image = Resolve( sky.Texture );
									else if ( !Decodable( texture ) ) problem = $"The sky texture '{texture.Path}' is a cube layout in an image format the editor cannot compose.";
									else faces = UnitySky.Regions( layout.Value, texture.Source, size.Value.Width );
								}
							}
							if ( problem == null && faces != null )
							{
								if ( extractChannels == null ) problem = "Composing a sky panorama from cube faces needs the editor.";
								else
								{
									var derived = generatedFiles.Add( asset.Path, "sky", ".png" );
									channelRequests.Add( new( faces[0].Source, derived.File, -2, 1, false, Faces: faces ) );
									image = derived.Reference;
									information.Add( $"{asset.Path}: composed a sky panorama from the skybox's cube faces." );
								}
							}
							if ( problem != null ) Issue( asset.Path, "sky-not-converted", $"Skybox not converted; scenes show s&box's default sky. {problem}" );
							else
							{
								if ( sky.Type == UnitySky.Kind.Procedural )
								{
									// A procedural sky has no image to convert; scenes use s&box's standard day sky, which lights them.
									skies[asset.Guid] = new( UnitySky.DefaultSky, null, 0 );
									information.Add( $"{asset.Path}: procedural skybox shown as s&box's standard day sky, which lights the scene; Unity's computed sky colors and sun-following sky are not reproduced." );
								}
								else
								{
									documents.Add( (Output( Path.ChangeExtension( asset.Path, ".vmat" ) ), UnitySky.Vmat( image )) );
									conversions++;
									skies[asset.Guid] = new( prefix + Path.ChangeExtension( asset.Path, ".vmat" ), sky.Tint, sky.Yaw );
									information.Add( $"{asset.Path}: skybox converted to an s&box sky material." );
								}
							}
						}
						else
						{
							if ( planned.Vmat ) { var vmatText = material.ToVmat( ResolveVmat, ResolveNormal ); documents.Add( (Output( Path.ChangeExtension( asset.Path, ".vmat" ) ), vmatText) ); conversions++; } // Converted before the output is reserved.
							convertedMaterials[asset.Guid] = material;
							if ( planned.Tmat ) { documents.Add( (Output( Path.ChangeExtension( asset.Path, ".tmat" ) ), material.ToTmat( Resolve )) ); conversions++; }
							warnings.AddRange( material.Warnings.Select( w => $"{asset.Path}: {w}" ) );
							information.AddRange( material.Information.Select( m => $"{asset.Path}: {m}" ) );
						}
					}
					catch ( Exception ex ) when ( Skippable( ex ) ) { Issue( asset.Path, "conversion-skipped", $"Conversion skipped. {Describe( ex )}" ); }
				}
				// The mesh file a VMDL reads: the source, or a repaired or ASCII-named copy of it.
				string MeshSource()
				{
					var meshPath = prefix + asset.Path;
					// The model compiler cannot open source paths with non-ASCII characters, so such models use an ASCII-named copy.
					var nonAscii = asset.Path.Any( c => c > 127 );
					var derivedName = nonAscii ? AsciiPath( asset.Path ) : asset.Path;
					if ( asset.Path.EndsWith( ".fbx", StringComparison.OrdinalIgnoreCase ) && UnityFbxCompatibility.Normalize( asset.Source, cancel ) is byte[] normalized )
					{
						var repaired = generatedFiles.Add( derivedName, "repaired", ".fbx" );
						File.WriteAllBytes( repaired.File, normalized );
						meshPath = repaired.Reference;
						warnings.Add( $"{asset.Path}: removed an exact duplicate vertex array after a closing brace in a derived FBX; original source preserved." );
					}
					else if ( nonAscii )
					{
						var copy = generatedFiles.Add( derivedName, "ascii", Path.GetExtension( asset.Path ).ToLowerInvariant() );
						File.Copy( asset.Source, copy.File, true );
						meshPath = copy.Reference;
						information.Add( $"{asset.Path}: the model compiler cannot open paths with non-ASCII characters, so the VMDL uses an ASCII-named copy of the model." );
					}
					return meshPath;
				}
				// The VMDL a Unity MeshCollider uses, per mesh node (null for the whole model) and shape kind. The shape goes in the
				// model that shows that mesh, as s&box models carry their collision: the model itself when it shows only that mesh
				// (or the collider uses the whole model), else the mesh's single-mesh VMDL. A model that already holds a different
				// shape keeps it, and so does a mesh with no visible model; those colliders get a physics-only VMDL.
				Func<string, bool, string> CollisionFactory( string meshPath, UnityModel info, double scale, string modelVmdl = null, Func<string, string> meshVmdl = null )
				{
					var made = new Dictionary<(string, bool), string>();
					var modelPath = AsciiPath( asset.Path );
					return ( node, convex ) =>
					{
						if ( made.TryGetValue( (node, convex), out var existing ) ) return existing;
						if ( modelVmdl != null )
						{
							var whole = node == null || info.ImportedMeshes.SequenceEqual( new[] { node } );
							var target = whole ? modelVmdl : meshVmdl( node );
							if ( EmbedPhysics( target, new MeshPart( meshPath, whole ? info.FilteredMeshes : new[] { node }, scale ), convex ) ) return made[(node, convex)] = target;
						}
						var part = (node == null ? "" : "_" + Regex.Replace( node.Trim(), "[^A-Za-z0-9_-]+", "_" ).Trim( '_' )) + (convex ? "_hull" : "");
						var relative = Path.ChangeExtension( modelPath, null ) + "_iup_collision" + part + ".vmdl";
						for ( var n = 2; outputs.Contains( relative ); n++ ) relative = Path.ChangeExtension( modelPath, null ) + "_iup_collision" + part + "_" + n + ".vmdl";
						var meshes = node != null ? new[] { node } : info.FilteredMeshes;
						documents.Add( (Output( relative ), CollisionDocument( meshPath, meshes, scale, convex )) );
						conversions++;
						return made[(node, convex)] = prefix + relative;
					};
				}
				if ( planned.Vmdl && !skippedModels.Contains( asset ) )
				{
					var meshPath = MeshSource();
					var info = asset.ModelInfo;
					var scale = ModelScale( asset, info );
					var remaps = files.Where( f => f.EndsWith( ".vmat", StringComparison.OrdinalIgnoreCase ) )
						.GroupBy( Path.GetFileNameWithoutExtension, StringComparer.OrdinalIgnoreCase )
						.Where( g => g.Count() == 1 ).ToDictionary( g => g.Key.ToLowerInvariant() + ".vmat", g => prefix + g.Single(), StringComparer.OrdinalIgnoreCase );
					// Which evidence produced each remap; reported per slot so inferred matches stay visible.
					var rules = remaps.Keys.ToDictionary( k => k, _ => "slot-filename", StringComparer.OrdinalIgnoreCase );
					void Remap( string slot, string material, string rule ) { remaps[slot.ToLowerInvariant() + ".vmat"] = material; rules[slot.ToLowerInvariant() + ".vmat"] = rule; }
					var meshName = Path.GetFileNameWithoutExtension( asset.Path ).ToLowerInvariant();
					if ( remaps.TryGetValue( meshName + ".vmat", out var matchingMaterial ) )
					{
						// Some exporters append an LOD suffix to slots that share the model's base material.
						for ( var lod = 0; lod <= 8; lod++ ) if ( remaps.TryAdd( $"{meshName}_lod{lod}.vmat", matchingMaterial ) ) rules[$"{meshName}_lod{lod}.vmat"] = "model-filename-lod";
					}
					var prefabMaterials = info.PrefabMaterials.Distinct( StringComparer.OrdinalIgnoreCase ).Select( SelectedVmat ).Where( a => a != null ).OrderBy( a => Array.IndexOf( selected, a ) ).ToArray();
					foreach ( var slot in info.Materials )
					{
						var semantic = prefabMaterials.Where( a => UnityModel.Normalize( Path.GetFileNameWithoutExtension( a.Path ) ) == UnityModel.Normalize( slot ) ).ToArray();
						if ( semantic.Length == 1 ) Remap( slot, prefix + Path.ChangeExtension( semantic[0].Path, ".vmat" ), "prefab-material-name" );
					}
					foreach ( var (slot, albedoFile) in info.MaterialAlbedoFiles )
					{
						if ( remaps.ContainsKey( slot.ToLowerInvariant() + ".vmat" ) ) continue;
						var candidates = (prefabMaterials.Length > 0 ? prefabMaterials : selected.Where( a => a.Kind == UnityAssetKind.Material ).ToArray())
							.Where( a => convertedMaterials.TryGetValue( a.Guid, out var material ) && material.ColorTextureGuids.Any( guid =>
								textureSources.TryGetValue( guid, out var texture ) && Path.GetFileNameWithoutExtension( texture.Path ).Equals(
									Path.GetFileNameWithoutExtension( albedoFile ), StringComparison.OrdinalIgnoreCase ) ) ).ToArray();
						// Unity often keeps the old diffuse filename as the material name
						// after repacking its texture. Require a unique prefab-assigned material.
						if ( candidates.Length == 0 ) candidates = prefabMaterials.Where( a =>
							Path.GetFileNameWithoutExtension( a.Path ).Equals( Path.GetFileNameWithoutExtension( albedoFile ), StringComparison.OrdinalIgnoreCase ) ).ToArray();
						if ( candidates.Length == 1 && outputs.Contains( Path.ChangeExtension( candidates[0].Path, ".vmat" ) ) )
							Remap( slot, prefix + Path.ChangeExtension( candidates[0].Path, ".vmat" ), "albedo-texture" );
					}
					// The model's own Unity import settings replace inferred matches; prefab slot evidence overrides them.
					foreach ( var (slot, source) in info.ImporterMaterials )
					{
						var assigned = SelectedVmat( source.Guid );
						if ( assigned != null ) Remap( slot, prefix + Path.ChangeExtension( assigned.Path, ".vmat" ), source.Rule );
					}
					foreach ( var (slot, guid) in info.PrefabSlotMaterials )
					{
						var assigned = SelectedVmat( guid );
						if ( assigned != null ) Remap( slot, prefix + Path.ChangeExtension( assigned.Path, ".vmat" ), info.MostCommonSlots.Contains( slot ) ? "prefab-slot-most-common" : "prefab-slot" );
					}
					foreach ( var slot in info.UnresolvedPrefabSlots ) remaps.Remove( slot.ToLowerInvariant() + ".vmat" );
					var lodLevels = info.LodLevels;
					string[] SlotsOf( string mesh ) => info.RendererSlots.Values.FirstOrDefault( b => b.Mesh == mesh )?.EffectiveSlots.ToArray() ?? Array.Empty<string>();
					static string LodKey( string mesh ) => Regex.Replace( mesh, "(?i)LOD[0-9]", "LOD" );
					var defaultMaterial = prefabMaterials.Length == 1 && info.PrefabSlotMaterials.Count == 0 && info.ImporterMaterials.Count == 0 && info.AssignmentWarnings.Count == 0 ? prefix + Path.ChangeExtension( prefabMaterials[0].Path, ".vmat" ) : null;
					var defaultRule = defaultMaterial == null ? null : "prefab-single-material";
					// Embedded materials (materialLocation 1, or a prefab choosing the model's own) are generated by Unity from
					// the FBX rather than stored as .mat files. A neutral material stands in, and the cause is reported as such.
					var embeddedSlots = info.RenderedMaterials.Where( s => !remaps.ContainsKey( s.ToLowerInvariant() + ".vmat" ) &&
						(info.MaterialImport == "embedded" || info.EmbeddedSlots.Contains( s )) ).ToArray();
					if ( options.Materials && options.Vmat && defaultMaterial == null && embeddedSlots.Length > 0 )
					{
						var embeddedPath = generatedFiles.Add( asset.Path, "embedded", ".vmat" );
						var standIn = new UnityMaterial();
						standIn.Colors["_Color"] = new[] { 0.5, 0.5, 0.5, 1.0 };
						File.WriteAllText( embeddedPath.File, standIn.ToVmat( _ => null ) );
						conversions++;
						foreach ( var slot in embeddedSlots ) Remap( slot, embeddedPath.Reference, "embedded-material" );
						var textured = embeddedSlots.Where( info.MaterialAlbedoFiles.ContainsKey ).ToArray();
						Issue( asset.Path, "embedded-material", $"Unity generates the material for {string.Join( ", ", embeddedSlots.Select( s => $"'{s}'" ) )} from the FBX; a neutral material stands in" +
							(textured.Length > 0 ? $" (the FBX names a texture for {string.Join( ", ", textured.Select( s => $"'{s}'" ) )}, which is not applied)." : "; the FBX provides no texture.") );
					}
					var missingSlots = info.RenderedMaterials.Where( s => !remaps.ContainsKey( s.ToLowerInvariant() + ".vmat" ) ).ToArray();
					// Slots without any material evidence get a neutral s&box standard material instead of a missing one.
					var noSlots = info.RendererSlots.Count == 0 && info.Materials.Count == 0;
					if ( options.Materials && options.Vmat && defaultMaterial == null && (noSlots || missingSlots.Length > 0) &&
						Path.GetExtension( asset.Path ).ToLowerInvariant() is ".fbx" or ".obj" )
					{
						var neutralPath = generatedFiles.Add( asset.Path, "unassigned", ".vmat" );
						var neutral = new UnityMaterial();
						neutral.Colors["_Color"] = new[] { 0.5, 0.5, 0.5, 1.0 };
						File.WriteAllText( neutralPath.File, neutral.ToVmat( _ => null ) );
						conversions++;
						if ( noSlots ) (defaultMaterial, defaultRule) = (neutralPath.Reference, "neutral-fallback");
						else foreach ( var slot in missingSlots ) Remap( slot, neutralPath.Reference, "neutral-fallback" );
						Issue( asset.Path, "unassigned-material", info.Materials.Count == 0
							? "The model contains no named material slots and no unambiguous prefab assignment was resolved; using a neutral material."
							: $"No material was found for {string.Join( ", ", missingSlots.Select( s => $"'{s}'" ) )}; a neutral standard material stands in" +
								(info.MaterialImport == "none" ? ", as Unity shows its default material for models that import no materials." : ".") );
					}
					if ( options.Materials && options.Vmat && defaultMaterial == null )
						foreach ( var slot in info.RenderedMaterials.Where( s => !remaps.ContainsKey( s.ToLowerInvariant() + ".vmat" ) ) )
							Issue( asset.Path, "unassigned-material", $"No converted material was resolved for slot '{slot}'." );
					// Lower LOD meshes repeat their LOD0 mesh's materials, as their Unity renderers almost always do: a slot without
					// its own assignment takes the material of the LOD0 counterpart's slot in the same position.
					foreach ( var mesh in lodLevels.Skip( 1 ).SelectMany( l => l ) )
					{
						var top = lodLevels[0].Length == 1 ? lodLevels[0][0] : lodLevels[0].FirstOrDefault( m => LodKey( m ).Equals( LodKey( mesh ), StringComparison.OrdinalIgnoreCase ) );
						if ( top == null ) continue;
						var (own, source) = (SlotsOf( mesh ), SlotsOf( top ));
						for ( var s = 0; s < own.Length && s < source.Length; s++ )
							if ( !remaps.ContainsKey( own[s].ToLowerInvariant() + ".vmat" ) && remaps.TryGetValue( source[s].ToLowerInvariant() + ".vmat", out var lodMaterial ) )
								Remap( own[s], lodMaterial, "lod0-slot" );
					}
					// Slots of lower LOD meshes that the model file does not name fall back to LOD0's material when it has only one.
					// The global default replaces every material, so it is not used when a lower level has a material of its own
					// (an impostor level's atlas).
					if ( defaultMaterial == null && lodLevels.Count > 1 &&
						lodLevels[0].SelectMany( SlotsOf ).Select( s => remaps.GetValueOrDefault( s.ToLowerInvariant() + ".vmat" ) ).Distinct( StringComparer.OrdinalIgnoreCase ).ToArray() is [string lodDefault] &&
						lodLevels.Skip( 1 ).SelectMany( l => l ).SelectMany( SlotsOf ).All( s => !remaps.TryGetValue( s.ToLowerInvariant() + ".vmat", out var own ) || own.Equals( lodDefault, StringComparison.OrdinalIgnoreCase ) ) )
						(defaultMaterial, defaultRule) = (lodDefault, "lod0-material");
					// Each other Unity prefab variant becomes a ModelDoc material group. A group replaces the default group's
					// resolved materials, so slots that share one default material change together; such cases are noted.
					string VariantMaterial( string guid ) => SelectedVmat( guid ) is UnityAsset variantAsset ? prefix + Path.ChangeExtension( variantAsset.Path, ".vmat" ) : null;
					string DefaultOf( string slot ) => remaps.GetValueOrDefault( slot.ToLowerInvariant() + ".vmat" ) ?? defaultMaterial;
					var groups = new List<VariantGroup>();
					var groupNames = new HashSet<string>( StringComparer.OrdinalIgnoreCase ) { "default" };
					foreach ( var variant in info.PrefabVariants )
					{
						var groupRemaps = new Dictionary<string, string>( StringComparer.OrdinalIgnoreCase );
						var notes = new List<string>();
						foreach ( var (slot, guid) in variant.Slots )
						{
							var from = DefaultOf( slot );
							var to = VariantMaterial( guid );
							if ( from == null || to == null ) { notes.Add( $"Slot '{slot}' has no {(from == null ? "default" : "imported variant")} material." ); continue; }
							if ( from.Equals( to, StringComparison.OrdinalIgnoreCase ) ) continue;
							if ( groupRemaps.TryGetValue( from, out var kept ) && !kept.Equals( to, StringComparison.OrdinalIgnoreCase ) )
							{
								notes.Add( $"Slot '{slot}' shares its default material with another slot that this variant changes differently; kept {kept}." );
								continue;
							}
							groupRemaps[from] = to;
							foreach ( var other in info.RenderedMaterials.Where( s => !variant.Slots.ContainsKey( s ) && from.Equals( DefaultOf( s ), StringComparison.OrdinalIgnoreCase ) ) )
								notes.Add( $"Slot '{other}' shares the default material of '{slot}', so it also changes in this group." );
						}
						if ( groupRemaps.Count == 0 ) continue; // Same as the default group.
						var same = groups.FirstOrDefault( g => g.Remaps.Count == groupRemaps.Count && g.Remaps.All( r => groupRemaps.TryGetValue( r.Key, out var m ) && m.Equals( r.Value, StringComparison.OrdinalIgnoreCase ) ) );
						if ( same != null ) { same.Prefabs.AddRange( variant.Prefabs ); continue; }
						var baseName = Regex.Replace( Path.GetFileNameWithoutExtension( variant.Prefabs[0] ), "[^A-Za-z0-9_-]+", "_" );
						var name = baseName;
						for ( var n = 2; !groupNames.Add( name ); n++ ) name = $"{baseName}_{n}";
						groups.Add( new( name, variant.Prefabs.ToList(), groupRemaps, notes ) );
					}
					materialGroups += groups.Count;
					information.AddRange( info.AssignmentNotes.Select( n => $"{asset.Path}: {n}" ) );
					if ( info.HiddenMeshes.Count > 0 )
						information.Add( $"{asset.Path}: left out {info.HiddenMeshes.Count} mesh(es) that no Unity prefab or scene places: {string.Join( ", ", info.HiddenMeshes.Order( StringComparer.Ordinal ) )}." );
					hiddenMeshes += info.HiddenMeshes.Count;
					// Neutral fallbacks are reported without their generated placeholder path.
					string Reported( string material, string rule ) => rule == "neutral-fallback" || material?.StartsWith( "iup:generated:", StringComparison.Ordinal ) == true ? null : material;
					string Shown( string material ) => material.StartsWith( "iup:generated:", StringComparison.Ordinal ) ? "(neutral fallback)" : material;
					var slotRows = info.RenderedMaterials.Concat( info.PrefabSlotMaterials.Keys ).Concat( info.UnresolvedPrefabSlots ).Distinct( StringComparer.OrdinalIgnoreCase ).Select( slot =>
					{
						var key = slot.ToLowerInvariant() + ".vmat";
						var rule = remaps.ContainsKey( key ) ? rules.GetValueOrDefault( key, "slot-filename" ) : defaultRule ?? "unresolved";
						return new
						{
							Slot = slot, Rule = rule, Material = Reported( remaps.GetValueOrDefault( key ) ?? defaultMaterial, rule ),
							Evidence = info.PrefabEvidence.Where( e => string.Equals( e.Slot, slot, StringComparison.OrdinalIgnoreCase ) ).Select( ReportEvidence ).ToArray()
						};
					} ).ToArray();
					assignments.Add( new
					{
						Model = asset.Path,
						info.MaterialImport,
						Default = defaultRule == null ? null : new { Material = Reported( defaultMaterial, defaultRule ), Rule = defaultRule },
						Slots = slotRows,
						MaterialGroups = groups.Select( g => new { g.Name, g.Prefabs, Remaps = g.Remaps.Select( r => new { From = Shown( r.Key ), To = r.Value } ).ToArray(), g.Notes } ).ToArray(),
						Notes = info.AssignmentNotes.ToArray(),
						HiddenMeshes = info.HiddenMeshes.Order( StringComparer.Ordinal ).ToArray(),
						// Prefab references that could not be tied to an imported slot.
						Unmatched = info.PrefabEvidence.Where( e => e.Problem != null ).Select( ReportEvidence ).ToArray()
					} );
					foreach ( var rule in slotRows.Length > 0 ? slotRows.Select( r => r.Rule ) : new[] { defaultRule ?? "no-slot-information" } )
						ruleCounts[rule] = ruleCounts.GetValueOrDefault( rule ) + 1;
					foreach ( var evidence in info.PrefabEvidence.Where( e => e.Applied ) )
						idCounts[evidence.Problem ?? evidence.IdSource] = idCounts.GetValueOrDefault( evidence.Problem ?? evidence.IdSource ) + 1;
					// Unity's "Generate Colliders" gives every mesh an exact collider, so the VMDL gets the matching physics mesh.
					var lodThresholds = info.LodThresholds( asset.MetadataDocument, scale );
					// Only the model's own slots: its material names, renderer slots and mesh names (a slotless mesh's slot is its
					// name). Remaps of other slots would only bloat the VMDL (every material of the package).
					var ownSlots = info.Materials.Concat( info.Meshes ).Concat( info.RendererSlots.Values.SelectMany( b => b.Slots ) ).Concat( info.PrefabSlotMaterials.Keys )
						.Select( n => n.ToLowerInvariant() + ".vmat" ).ToHashSet( StringComparer.OrdinalIgnoreCase );
					foreach ( var other in remaps.Keys.Where( k => !ownSlots.Contains( k ) ).ToArray() ) remaps.Remove( other );
					AddModel( ModelOutput( asset.Path ), ( shape, convex ) => ModelDocument( meshPath, remaps, defaultMaterial, groups, info.FilteredMeshes, scale, shape, convex, info.LodLevels, lodThresholds ),
						info.GenerateColliders ? new MeshPart( meshPath, info.FilteredMeshes, scale ) : null );
					if ( info.LodLevels.Count > 1 ) information.Add( $"{asset.Path}: {info.LodLevels.Count} LOD levels from the mesh names go into the VMDL's LOD group" +
						(info.LodSize( scale ) == null ? "; the levels' bounds could not be read, so the switch distances assume a 1 m model." : ".") );
					if ( info.GenerateColliders ) information.Add( $"{asset.Path}: Unity generates colliders for this model, so its VMDL has a physics mesh." );
					// Renderers that show one mesh of a multi-mesh model get a VMDL holding only that mesh.
					var meshModels = new Dictionary<string, string>( StringComparer.Ordinal );
					var (modelPath, modelMesh, modelRemaps, modelDefault, modelScale) = (AsciiPath( asset.Path ), meshPath, remaps, defaultMaterial, scale);
					var modelGroups = groups;
					string MeshVmdl( string node )
					{
						if ( meshModels.TryGetValue( node, out var existing ) ) return existing;
						var relative = Path.ChangeExtension( modelPath, null ) + "_iup_mesh_" + Regex.Replace( node.Trim(), "[^A-Za-z0-9_-]+", "_" ).Trim( '_' ) + ".vmdl";
						for ( var n = 2; outputs.Contains( relative ); n++ ) relative = Path.ChangeExtension( modelPath, null ) + "_iup_mesh_" + Regex.Replace( node.Trim(), "[^A-Za-z0-9_-]+", "_" ).Trim( '_' ) + "_" + n + ".vmdl";
						AddModel( relative, ( shape, convex ) => ModelDocument( modelMesh, modelRemaps, modelDefault, modelGroups, new[] { node }, modelScale, shape, convex ) );
						conversions++;
						return meshModels[node] = prefix + relative;
					}
					prefabModels[asset.Guid] = new PrefabModel
					{
						Vmdl = prefix + ModelOutput( asset.Path ), Info = info, Scale = scale, Name = Path.GetFileNameWithoutExtension( asset.Path ), MeshFile = meshPath,
						MeshVmdl = MeshVmdl,
						Group = slots => ChooseGroup( slots, DefaultOf, VariantMaterial, modelGroups ),
						CollisionVmdl = CollisionFactory( meshPath, info, scale, prefix + ModelOutput( asset.Path ), MeshVmdl )
					};
					conversions++;
					information.Add( $"{asset.Path}: review scale, orientation, material assignments, collision and animations in ModelDoc." );
				}
				else if ( asset.Kind == UnityAssetKind.Model && asset.ModelInfo.CollisionOnly && selected.Any( a => plan.Find( a ) is { Prefab: true } or { Scene: true } ) )
				{
					// A mesh used only by Unity MeshColliders has no visible VMDL; prefabs and scenes get collision VMDLs from it.
					var info = asset.ModelInfo;
					var scale = ModelScale( asset, info );
					prefabModels[asset.Guid] = new PrefabModel
					{
						Info = info, Scale = scale, Name = Path.GetFileNameWithoutExtension( asset.Path ), Group = _ => ("", true),
						CollisionVmdl = CollisionFactory( MeshSource(), info, scale )
					};
				}
			}
			Mark( "Assets (copies, sounds, materials, models)" );
			// Unity blends terrain layers by height only when the placing terrain's material enables it.
			bool HeightBlend( UnityAsset terrain )
			{
				foreach ( var placement in selected.Where( a => plan.Find( a ) is { Prefab: true } or { Scene: true } ) )
				{
					string text;
					try { text = ReadPlacement( placement.Source ); }
					catch ( InvalidDataException ) { continue; }
					if ( !text.Contains( terrain.Guid, StringComparison.OrdinalIgnoreCase ) ) continue;
					foreach ( var component in UnityYaml.Parse( text ).Where( o => o.ClassId == 218 && !o.Stripped ) )
					{
						if ( !string.Equals( component.Body["m_TerrainData"]?.Reference.Guid, terrain.Guid, StringComparison.OrdinalIgnoreCase ) ) continue;
						var template = component.Body["m_MaterialTemplate"]?.Reference ?? default;
						if ( template.HasGuid && assetsByGuid.GetValueOrDefault( template.Guid ) is { Kind: UnityAssetKind.Material } material )
						{
							try { return UnityMaterial.Parse( ReadText( material.Source ) ).Number( "_EnableHeightBlend", 0 ) != 0; }
							catch ( InvalidDataException ) { }
						}
						return false;
					}
				}
				return false;
			}
			// Terrains reference the terrain layers' TMATs; scenes and prefabs place them.
			var prefabTerrains = new Dictionary<string, PrefabTerrain>( StringComparer.OrdinalIgnoreCase );
			foreach ( var asset in selected.Where( a => plan.Find( a ).Terrain ) )
			{
				cancel.ThrowIfCancellationRequested();
				operation = "converting terrains";
				currentAsset = asset.Path;
				try
				{
					var data = UnityTerrainData.Read( asset.Source );
					var storage = data.ToStorage();
					// Layers keep Unity's order, so painted layer indices match; a layer without a TMAT paints nothing.
					var materials = data.Layers.Select( l => l.HasGuid && selectedByGuid.GetValueOrDefault( l.Guid ) is { } layer && plan.Find( layer ).Tmat
						? prefix + Path.ChangeExtension( layer.Path, ".tmat" ) : null ).ToList();
					if ( materials.Any( m => m == null ) ) warnings.Add( $"{asset.Path}: {materials.Count( m => m == null )} terrain layer(s) have no imported terrain material; those areas are unpainted." );
					var (json, blob) = UnityTerrainData.TerrainFile( storage, materials, HeightBlend( asset ) );
					var output = PlacementOutput( asset.Path, ".terrain" );
					documents.Add( (Output( output ), json) );
					File.WriteAllBytes( Output( output + "_d" ), blob );
					conversions++;
					data.ReleaseMaps();
					prefabTerrains[asset.Guid] = new PrefabTerrain { Path = prefix + output, Size = storage.Size, Height = storage.Height, Data = data };
					terrains.Add( new { Source = asset.Path, storage.Resolution, Size = Math.Round( storage.Size, 1 ), Height = Math.Round( storage.Height, 1 ), Layers = data.Layers.Count, Trees = data.Trees.Count, TreePrototypes = data.TreePrototypes.Count,
						DetailLayersNotConverted = data.DetailPrototypes, Notes = data.Notes.Distinct().ToArray() } );
					information.Add( $"{asset.Path}: {storage.Resolution}x{storage.Resolution} terrain with {data.Layers.Count} layers and {data.Trees.Count} trees" +
						(data.DetailPrototypes > 0 ? $"; its {data.DetailPrototypes} grass and detail layers are not converted." : ".") );
					warnings.AddRange( data.Notes.Distinct().Select( n => $"{asset.Path}: {n}" ) );
				}
				catch ( Exception ex ) when ( Skippable( ex ) ) { Issue( asset.Path, "conversion-skipped", $"Conversion skipped. {Describe( ex )}" ); }
			}
			Mark( "Terrains" );
			// Meshes the importer writes itself: Unity's built-in primitives and meshes stored in prefabs, scenes and .asset files.
			var meshObjs = new Dictionary<(string, long), GeneratedMesh>();
			var meshFiles = new Dictionary<string, IReadOnlyList<UnityYamlObject>>( StringComparer.OrdinalIgnoreCase );
			// Built-in meshes go in the package's own folder (the deepest folder holding all its prefabs and scenes, whatever is
			// selected), so a package's import stays under its folder. Every package's copy is identical.
			var primitivesFolder = PackageFolder( archive.Assets.Where( a => a.Kind is UnityAssetKind.Prefab or UnityAssetKind.Scene ).Select( a => a.Path ) ) + "Unity Primitives/";
			GeneratedMesh MeshObj( string guid, long fileId )
			{
				if ( meshObjs.TryGetValue( (guid, fileId), out var known ) ) return known;
				var owner = assetsByGuid.GetValueOrDefault( guid );
				GeneratedMesh result;
				try
				{
					UnityMesh mesh;
					string relative;
					if ( guid.Equals( UnityMesh.BuiltinGuid, StringComparison.OrdinalIgnoreCase ) )
					{
						if ( !UnityMesh.Primitives.TryGetValue( fileId, out var primitive ) ) throw new InvalidDataException( $"Unity's built-in mesh {fileId} is not one of its primitives." );
						mesh = UnityMesh.Primitive( primitive );
						relative = primitivesFolder + primitive + ".obj";
					}
					else
					{
						if ( owner == null ) throw new InvalidDataException( "its file is not in the package." );
						object body;
						if ( UnitySerializedFile.Is( owner.Source ) )
						{
							var file = UnitySerializedFile.Read( owner.Source );
							var info = file.Find( fileId );
							if ( info == null || info.ClassId != 43 ) throw new InvalidDataException( "the file holds no such mesh." );
							body = file.ReadObject( info );
						}
						else
						{
							if ( !meshFiles.TryGetValue( guid, out var objects ) ) meshFiles[guid] = objects = UnityYaml.Parse( ReadPlacement( owner.Source ) );
							body = objects.FirstOrDefault( o => o.FileId == fileId && o.ClassId == 43 && !o.Stripped )?.Body ?? throw new InvalidDataException( "the file holds no such mesh." );
						}
						mesh = UnityMesh.Read( body );
						var stem = Path.ChangeExtension( owner.Path, null );
						var meshName = Regex.Replace( mesh.Name ?? "Mesh", "[^A-Za-z0-9_-]+", "_" ).Trim( '_' );
						relative = owner.Path.EndsWith( ".asset", StringComparison.OrdinalIgnoreCase ) ? stem + "_iup_mesh.obj" : stem + "_iup_mesh_" + (meshName.Length > 0 ? meshName : "Mesh") + ".obj";
						if ( meshObjs.Values.Any( m => m.Relative != null && m.Relative.Equals( AsciiPath( relative ), StringComparison.OrdinalIgnoreCase ) ) )
							relative = Path.ChangeExtension( relative, null ) + "_" + (fileId < 0 ? "n" + (-fileId) : fileId.ToString( System.Globalization.CultureInfo.InvariantCulture )) + ".obj";
					}
					relative = AsciiPath( relative );
					if ( !outputs.Contains( relative ) ) { var obj = mesh.ToObj(); File.WriteAllText( Output( relative ), obj ); conversions++; }
					result = new( relative, prefix + relative, mesh.Submeshes.Count, null );
				}
				catch ( Exception ex ) when ( Skippable( ex ) ) { result = new( null, null, 0, $"A mesh in '{owner?.Path ?? guid}' could not be read: {Describe( ex )}" ); }
				return meshObjs[(guid, fileId)] = result;
			}
			// Composed VMDLs (generated meshes, LOD groups, collision); identical documents are written once. They use no
			// global default material: ModelDoc's global default replaces every material, remapped or not (measured).
			var composedModels = new Dictionary<string, string>( StringComparer.Ordinal );
			string Compose( ComposedModel model )
			{
				var text = model.Lods.Count == 0 && model.Physics != null ? CollisionDocument( model.Physics.File, model.Physics.Meshes, model.Physics.Scale, model.Convex )
					: ComposedDocument( model.Remaps, null, null, model.Lods, model.Thresholds, model.Physics, model.Convex );
				if ( composedModels.TryGetValue( text, out var existing ) ) return existing;
				var name = AsciiPath( model.Name );
				var relative = name + ".vmdl";
				for ( var n = 2; outputs.Contains( relative ) || assetPaths.Contains( relative ); n++ ) relative = $"{name}_{n}.vmdl";
				// Render models can take a collider's shape later; physics-only models are complete.
				if ( model.Lods.Count > 0 )
					AddModel( relative, ( shape, convex ) => ComposedDocument( model.Remaps, null, null, model.Lods, model.Thresholds, shape, convex ), model.Physics, model.Convex );
				else documents.Add( (Output( relative ), text) );
				conversions++;
				return composedModels[text] = prefix + relative;
			}
			// Prefabs and scenes reference the models converted above.
			var converter = new UnityPrefabConverter( archive.Assets.ToDictionary( a => a.Guid, StringComparer.OrdinalIgnoreCase ), prefabModels,
				selected.Where( a => plan.Find( a ).Prefab ).ToDictionary( a => a.Guid, a => prefix + PlacementOutput( a.Path, ".prefab" ), StringComparer.OrdinalIgnoreCase ),
				guid => UnityYaml.Parse( ReadPlacement( archive.Assets.First( a => a.Guid.Equals( guid, StringComparison.OrdinalIgnoreCase ) ).Source ) ) )
			{
				Terrains = prefabTerrains,
				Materials = selected.Where( a => plan.Find( a ).Vmat ).ToDictionary( a => a.Guid, a => prefix + Path.ChangeExtension( a.Path, ".vmat" ), StringComparer.OrdinalIgnoreCase ),
				MeshObj = MeshObj, Compose = Compose, Skies = skies, EmbedPhysics = EmbedPhysics,
				Sounds = selected.Where( a => plan.Find( a ).Sound && !skippedSounds.Contains( a ) ).ToDictionary( a => a.Guid, a => prefix + Path.ChangeExtension( a.Path, ".sound" ), StringComparer.OrdinalIgnoreCase )
			};
			foreach ( var asset in selected.Where( a => plan.Find( a ) is { Prefab: true } or { Scene: true } ) )
			{
				cancel.ThrowIfCancellationRequested();
				operation = "converting prefabs and scenes";
				currentAsset = asset.Path;
				var summary = new UnityPrefabConverter.Summary { Source = asset.Path };
				try
				{
					// Convert before reserving the output, so a skipped conversion leaves no unwritten file behind.
					var prefabFile = plan.Find( asset ).Prefab;
					var text = prefabFile ? converter.ConvertPrefab( asset, summary ) : converter.ConvertScene( asset, summary, Path.GetFileNameWithoutExtension( asset.Path ) );
					documents.Add( (Output( PlacementOutput( asset.Path, prefabFile ? ".prefab" : ".scene" ) ), text) );
					conversions++;
					placements.Add( summary );
					warnings.AddRange( summary.Notes.Distinct().Select( n => $"{asset.Path}: {n}" ) );
				}
				catch ( Exception ex ) when ( Skippable( ex ) ) { Issue( asset.Path, "conversion-skipped", $"Conversion skipped. {Describe( ex )}" ); }
			}
			if ( placements.Count > 0 )
				information.Add( $"{placements.Count} prefab(s) and scene(s) converted: {placements.Sum( p => p.Renderers )} renderers, {placements.Sum( p => p.PrefabInstances )} nested prefab references, " +
					$"{placements.Sum( p => p.InlinedInstances )} inlined instances, {placements.Sum( p => p.Lights )} lights, {placements.Sum( p => p.Cameras )} cameras, {placements.Sum( p => p.Probes )} reflection probes, " +
					$"{placements.Sum( p => p.Sounds )} audio sources. Scripts, particle effects and animation are not converted." );
			Mark( "Prefabs and scenes" );
			operation = "extracting texture channels";
			currentAsset = null;
			progress?.Report( new( 0.8, $"Preparing {channelRequests.Count} texture channels", "Converting textures" ) );
			channelTimer.Start();
			try { if ( channelRequests.Count > 0 ) extractChannels( channelRequests, cancel ); }
			catch ( TextureBatchException failed )
			{
				// Paths in the destination are relative to the staging folder; the report names the package source.
				var sources = textureSources.Values.ToDictionary( t => Path.GetFullPath( t.Source ), t => t.Path, StringComparer.OrdinalIgnoreCase );
				foreach ( var bySource in failed.Failures.GroupBy( f => f.Source, StringComparer.OrdinalIgnoreCase ) )
					Issue( sources.GetValueOrDefault( Path.GetFullPath( bySource.Key ), Path.GetFileName( bySource.Key ) ), "texture-processing-failed",
						$"The image could not be processed ({bySource.First().Message}); {bySource.Count()} derived textures use a neutral placeholder." );
			}
			channelTimer.Stop();
			Mark( "Texture processing" );
			progress?.Report( new( 0.95, "Choosing generated filenames…", "Naming generated files" ) );
			generatedFiles.Complete( Output, cancel );
			foreach ( var model in physicsModels.Values.Where( m => m.Physics != null ) )
				documents[model.Document] = (documents[model.Document].File, model.Text( model.Physics, model.Convex ));
			foreach ( var document in documents )
			{
				cancel.ThrowIfCancellationRequested();
				File.WriteAllText( document.File, generatedFiles.ResolveDocument( document.Text ) );
			}
			Mark( "Writing files" );
			var unsupported = archive.Assets.Count( a => a.Kind == UnityAssetKind.Unsupported );
			if ( unsupported > 0 ) information.Add( $"{unsupported} unsupported files (such as scripts, shaders, animations and generic assets) were excluded." );
			if ( archive.Skipped.Count > 0 ) information.Add( $"{archive.Skipped.Count} package entries were left out while reading: {string.Join( "; ", archive.Skipped.Take( 10 ) )}{(archive.Skipped.Count > 10 ? "; …" : "")}" );
			var issues = unresolved.Distinct().ToArray();
			// Each package shader the conversion approximates: its materials and the effects their shader properties name.
			var shaderApproximations = selected.Where( a => convertedMaterials.TryGetValue( a.Guid, out var m ) && shaders.ContainsKey( m.ShaderGuid ?? "" ) )
				.GroupBy( a => convertedMaterials[a.Guid].ShaderName ?? convertedMaterials[a.Guid].ShaderGuid, StringComparer.Ordinal ).OrderBy( g => g.Key, StringComparer.Ordinal )
				.Select( g => new
				{
					Shader = g.Key, Materials = g.Count(),
					NotReproduced = g.SelectMany( a => convertedMaterials[a.Guid].Unreproduced ).GroupBy( f => f.Key ).OrderBy( f => f.Key, StringComparer.Ordinal )
						.Select( f => new { Feature = f.Key, Materials = f.Count(), Properties = f.SelectMany( p => p.Value ).Distinct().Order( StringComparer.Ordinal ).ToArray() } ).ToArray()
				} ).ToArray();
			if ( shaderApproximations.Length > 0 )
				information.Add( $"{shaderApproximations.Sum( s => s.Materials )} material(s) use {shaderApproximations.Length} package shader(s), approximated with s&box's complex shader" +
					(shaderApproximations.Any( s => s.NotReproduced.Length > 0 ) ? "; effects not reproduced: " + string.Join( ", ", shaderApproximations.SelectMany( s => s.NotReproduced )
						.GroupBy( f => f.Feature ).OrderByDescending( f => f.Sum( x => x.Materials ) ).Select( f => $"{f.Key} ({f.Sum( x => x.Materials )})" ) ) : "") +
					". See ShaderApproximations in the report." );
			var report = new
			{
				Package = Path.GetFileName( archive.FileName ), Assets = selected.Length, Converted = conversions,
				Files = files.ToArray(), Unresolved = issues,
				// Package reading happens before this preparation; committing and engine preparation are added later.
				Timings = new[] { new { Stage = "Reading the package", Milliseconds = archive.ReadMilliseconds }, new { Stage = "Cataloguing dependencies", Milliseconds = plan.CatalogMilliseconds } }.Concat( stageTimes.Select( t => new { t.Stage, t.Milliseconds } ) ).ToArray(),
				TextureProcessing = new { ChannelsGenerated = channelRequests.Count, SourceDecodes = channelRequests.Select( r => r.Source ).Distinct().Count(), ElapsedMilliseconds = channelTimer.ElapsedMilliseconds },
				Selection = plan.Assets.Select( a => new { Source = a.Asset.Path, a.Explicit, a.OutputLabel,
					RequiredBy = a.RequiredBy.Select( d => new { Source = d.Asset.Path, d.Reason } ).ToArray() } ).ToArray(),
				AssignmentSummary = new { Rules = ruleCounts, PrefabReferences = idCounts, MaterialGroups = materialGroups, HiddenMeshes = hiddenMeshes },
				Assignments = assignments.ToArray(),
				Placements = placements.Select( p => new { p.Source, p.Objects, p.Renderers, p.ModelInstances, p.PrefabInstances, p.InlinedInstances, p.Colliders, p.Terrains, p.Trees, p.Lights, p.Cameras, p.Probes, p.Sounds, p.Skies, p.GeneratedMeshes, p.LodGroups, NotConverted = p.Skipped, Notes = p.Notes.Distinct().ToArray() } ).ToArray(),
				Terrains = terrains,
				MaterialConversions = selected.Where( a => convertedMaterials.ContainsKey( a.Guid ) ).Select( a => new
				{
					Source = a.Path, convertedMaterials[a.Guid].ShaderName, convertedMaterials[a.Guid].ShaderGuid,
					Textures = convertedMaterials[a.Guid].Textures.Count,
					Values = convertedMaterials[a.Guid].Numbers.Count + convertedMaterials[a.Guid].Colors.Count,
					Conversion = "Common material properties; shader programs are not translated",
					NotReproduced = convertedMaterials[a.Guid].Unreproduced,
					Vmat = plan.Find( a ).Vmat, Tmat = plan.Find( a ).Tmat
				} ).ToArray(),
				ShaderApproximations = shaderApproximations,
				Information = information.ToArray(), Warnings = warnings.Distinct().ToArray()
			};
			operation = "preparing import details";
			currentAsset = null;
			var reportJson = JsonSerializer.Serialize( report, new JsonSerializerOptions { WriteIndented = true } );
			cancel.ThrowIfCancellationRequested();
			var prepared = new ImportResult( stage, selected.Length, conversions, files.Select( f => Path.Combine( stage, f + ".iup" ) ).ToArray(), warnings.Distinct().ToArray() ) { Unresolved = issues, Information = information.ToArray(), ReportJson = reportJson };
			preserveStage = true;

			return prepared;
		}
		catch ( Exception ex )
		{
			failure = ex;
			if ( ex is IOException or UnauthorizedAccessException )
			{
				failure = new IOException( $"Import failed while {operation}" + (currentAsset == null ? "" : $" for '{currentAsset}'") +
					$". Staging folder: '{stage}'. Windows error {ex.HResult & 0xffff}: {ex.Message}", ex );
				throw failure;
			}
			throw;
		}
		finally
		{
			if ( !preserveStage && Directory.Exists( stage ) )
			{
				try { ImportWorkspace.RemoveTree( stage ); }
				catch ( Exception cleanup ) when ( cleanup is IOException or UnauthorizedAccessException )
				{
					// Preserve the original conversion/cancellation error if cleanup also fails.
					if ( failure == null ) throw new IOException( $"Could not remove staging folder '{stage}'. {cleanup.Message}", cleanup );
					failure.Data["StagingCleanupError"] = $"Could not remove '{stage}': {cleanup}";
				}
			}
		}
	}

	/// <summary>The material group whose materials match a renderer's slot assignment ("" for the default group).</summary>
	static (string Group, bool Exact) ChooseGroup( IReadOnlyDictionary<string, string> slots, Func<string, string> defaultOf, Func<string, string> variantMaterial, IReadOnlyList<VariantGroup> groups )
	{
		var wanted = slots.Select( p => (Default: defaultOf( p.Key ), Want: variantMaterial( p.Value ) ?? defaultOf( p.Key )) ).Where( w => w.Default != null ).ToArray();
		int Score( IReadOnlyDictionary<string, string> remaps ) => wanted.Count( w => string.Equals( remaps?.GetValueOrDefault( w.Default ) ?? w.Default, w.Want, StringComparison.OrdinalIgnoreCase ) );
		var best = (Name: "", Score: Score( null ));
		if ( best.Score == wanted.Length ) return ("", true);
		foreach ( var group in groups )
		{
			var score = Score( group.Remaps );
			if ( score == wanted.Length ) return (group.Name, true);
			if ( score > best.Score ) best = (group.Name, score);
		}
		return (best.Name, false);
	}

	/// <summary>Where a model's VMDL is written: beside its source, with a name the engine can load (<see cref="AsciiPath"/>).</summary>
	/// <summary>
	/// A model's import scale into s&amp;box inches: FBX from its unit and Unity's scale settings; OBJ, which has no unit,
	/// as meters (Unity's OBJ import) times globalScale; other formats as they are.
	/// </summary>
	internal static double ModelScale( UnityAsset asset, UnityModel info ) => Path.GetExtension( asset.Path ).ToLowerInvariant() switch
	{
		".fbx" => info.ImportScale( asset.MetadataDocument ),
		".obj" => (asset.MetadataDocument?.Find( "globalScale" )?.Number is double global && global > 0 && double.IsFinite( global ) ? global : 1) * UnityTransform.InchesPerMeter,
		_ => 1,
	};

	public static string ModelOutput( string source ) => AsciiPath( Path.ChangeExtension( source, ".vmdl" ) );

	/// <summary>Where a converted prefab, scene or terrain is written: beside its source, with a name the engine can load (<see cref="AsciiPath"/>).</summary>
	public static string PlacementOutput( string source, string extension ) => AsciiPath( Path.ChangeExtension( source, extension ) );

	/// <summary>
	/// The path with each non-ASCII character replaced by an underscore, and spaces ending the file name (before its
	/// extension) too: the engine's compilers cannot open non-ASCII paths, and its resource lookup cannot find a name
	/// ending in a space ("Terrain .prefab").
	/// </summary>
	internal static string AsciiPath( string path )
	{
		var ascii = new string( path.Select( c => c > 127 ? '_' : c ).ToArray() );
		var extension = Path.GetExtension( ascii );
		var stem = ascii[..^extension.Length];
		var trimmed = stem.TrimEnd( ' ' );
		return trimmed.Length == stem.Length || trimmed.EndsWith( '/' ) ? ascii : trimmed + new string( '_', stem.Length - trimmed.Length ) + extension;
	}

	static string ReadPlacement( string path )
	{
		if ( new FileInfo( path ).Length > 256L * 1024 * 1024 ) throw new InvalidDataException( "Prefab or scene exceeds the 256 MiB limit." );
		var text = File.ReadAllText( path );
		if ( !text.TrimStart().StartsWith( "%YAML", StringComparison.Ordinal ) && text.Contains( '\0' ) )
			throw new InvalidDataException( "The prefab or scene uses Unity's binary serialization; re-export it with Force Text serialization to convert it." );
		return text;
	}

	internal static void CheckDirectory( string path )
	{
		for ( var current = new DirectoryInfo( Path.GetFullPath( path ) ); current != null; current = current.Parent )
			if ( (Directory.Exists( current.FullName ) || File.Exists( current.FullName )) && File.GetAttributes( current.FullName ).HasFlag( FileAttributes.ReparsePoint ) )
				throw new IOException( $"Import destination cannot pass through a symbolic link: {current.FullName}" );
	}

	/// <summary>A named ModelDoc material group replacing default materials for one Unity prefab variant.</summary>
	sealed record VariantGroup( string Name, List<string> Prefabs, Dictionary<string, string> Remaps, List<string> Notes );

	/// <summary>A written VMDL that colliders can add a physics shape to: its document, how to render it and the shape.</summary>
	sealed class PhysicsModel
	{
		public int Document { get; init; }
		public Func<MeshPart, bool, string> Text { get; init; }
		public MeshPart Physics { get; set; }
		public bool Convex { get; set; }
	}

	static string Remaps( IEnumerable<KeyValuePair<string, string>> remaps ) => string.Join( ", ", remaps.Select( r => "{ from = " + UnityMaterial.Quote( r.Key ) + " to = " + UnityMaterial.Quote( r.Value ) + " }" ) );

	static string Scale( double scale ) => scale.ToString( "0.#########", System.Globalization.CultureInfo.InvariantCulture );

	/// <summary>A ModelDoc physics node: one convex hull (as Unity's convex MeshCollider builds) or the exact mesh.</summary>
	static string PhysicsNode( string mesh, string[] includedMeshes, double scale, bool convex ) =>
		"{ _class = \"" + (convex ? "PhysicsHullFile" : "PhysicsMeshFile") + "\" filename = " + UnityMaterial.Quote( mesh ) + " surface_prop = \"default\" collision_tags = \"solid\"" +
		(convex ? " import_mode = \"SingleHull\" maxHullVertices = 255" : "") + " import_scale = " + Scale( scale ) +
		" import_filter = { exclude_by_default = " + (includedMeshes.Length > 0 ? "true" : "false") + " exception_list = [ " + string.Join( ", ", includedMeshes.Select( UnityMaterial.Quote ) ) + " ] } }";

	/// <summary>A physics-only VMDL for a Unity MeshCollider.</summary>
	static string CollisionDocument( string mesh, string[] includedMeshes, double scale, bool convex ) => $$"""
		<!-- kv3 encoding:text:version{e21c7f3c-8a33-41c5-9977-a76d3a32aa0d} format:modeldoc29:version{3cec427c-1b0e-4d48-a90a-0436f33a6041} -->
		{
			rootNode =
			{
				_class = "RootNode"
				children =
				[
					{ _class = "PhysicsShapeList" children = [ {{PhysicsNode( mesh, includedMeshes, scale, convex )}} ] }
				]
				model_archetype = ""
			}
		}
		""";

	static string ModelDocument( string mesh, Dictionary<string, string> remaps, string defaultMaterial, IReadOnlyList<VariantGroup> groups, string[] includedMeshes, double scale, MeshPart physics = null, bool convex = false, IReadOnlyList<string[]> lods = null, IReadOnlyList<double> thresholds = null ) =>
		ComposedDocument( remaps, defaultMaterial, groups,
			lods is { Count: > 1 }
				// Meshes without a LOD suffix are not part of Unity's LOD group: they show at every level.
				? lods.Select( l => (IReadOnlyList<MeshPart>)new[] { new MeshPart( mesh, l.Concat( includedMeshes.Where( m => !lods.Any( level => level.Contains( m ) ) ) ).ToArray(), scale ) } ).ToList()
				: new List<IReadOnlyList<MeshPart>> { new[] { new MeshPart( mesh, includedMeshes, scale ) } },
			thresholds, physics, convex );

	/// <summary>
	/// A ModelDoc document: render meshes from one or more files, as LOD levels when there are several (each level's
	/// meshes switch in at its threshold), material remaps and groups, and an optional physics shape. Without render
	/// meshes (no LOD levels) it is a physics-only model.
	/// </summary>
	static string ComposedDocument( IEnumerable<KeyValuePair<string, string>> remaps, string defaultMaterial, IReadOnlyList<VariantGroup> groups,
		IReadOnlyList<IReadOnlyList<MeshPart>> lods, IReadOnlyList<double> thresholds, MeshPart physics, bool convex )
	{
		const string Tab = "\t";
		string Indent( int n ) => string.Concat( Enumerable.Repeat( Tab, n ) );
		static string Filter( string[] meshes ) => "{ exclude_by_default = " + (meshes.Length > 0 ? "true" : "false") + " exception_list = [ " + string.Join( ", ", meshes.Select( UnityMaterial.Quote ) ) + " ] }";
		var named = lods.Count > 1;
		var renderMeshes = new List<string>();
		var lodGroups = new List<string>();
		for ( var l = 0; l < lods.Count; l++ )
		{
			var names = new List<string>();
			for ( var p = 0; p < lods[l].Count; p++ )
			{
				var part = lods[l][p];
				var name = named ? $"LOD{l}" + (p > 0 ? $"_{p}" : "") : null;
				if ( name != null ) names.Add( name );
				renderMeshes.Add( Indent( 6 ) + "{ _class = \"RenderMeshFile\"" + (name != null ? " name = " + UnityMaterial.Quote( name ) : "") + " filename = " + UnityMaterial.Quote( part.File ) +
					" import_filter = " + Filter( part.Meshes ) + " import_scale = " + Scale( part.Scale ) + " import_translation = [ 0.0, 0.0, 0.0 ] import_rotation = [ 0.0, 0.0, 0.0 ] }" );
			}
			var threshold = l == 0 ? 0 : thresholds != null && l - 1 < thresholds.Count ? thresholds[l - 1] : 50.0 * l;
			if ( named ) lodGroups.Add( Indent( 6 ) + "{ _class = \"LODGroup\" switch_threshold = " + threshold.ToString( "0.0##", System.Globalization.CultureInfo.InvariantCulture ) + " meshes = [ " + string.Join( ", ", names.Select( UnityMaterial.Quote ) ) + " ] }" );
		}
		var text = new System.Text.StringBuilder();
		text.Append( "<!-- kv3 encoding:text:version{e21c7f3c-8a33-41c5-9977-a76d3a32aa0d} format:modeldoc29:version{3cec427c-1b0e-4d48-a90a-0436f33a6041} -->\n" );
		text.Append( "{\n" ).Append( Tab ).Append( "rootNode =\n" ).Append( Tab ).Append( "{\n" ).Append( Indent( 2 ) ).Append( "_class = \"RootNode\"\n" ).Append( Indent( 2 ) ).Append( "children =\n" ).Append( Indent( 2 ) ).Append( "[\n" );
		var children = new List<string>();
		var materials = new System.Text.StringBuilder();
		materials.Append( Indent( 3 ) ).Append( "{\n" ).Append( Indent( 4 ) ).Append( "_class = \"MaterialGroupList\"\n" ).Append( Indent( 4 ) ).Append( "children =\n" ).Append( Indent( 4 ) ).Append( "[\n" );
		materials.Append( Indent( 5 ) ).Append( "{\n" ).Append( Indent( 6 ) ).Append( "_class = \"DefaultMaterialGroup\"\n" );
		materials.Append( Indent( 6 ) ).Append( "remaps = [ " ).Append( Remaps( remaps ) ).Append( " ]\n" );
		materials.Append( Indent( 6 ) ).Append( "use_global_default = " ).Append( defaultMaterial != null ? "true" : "false" ).Append( '\n' );
		materials.Append( Indent( 6 ) ).Append( "global_default_material = " ).Append( UnityMaterial.Quote( defaultMaterial ?? "" ) ).Append( '\n' ).Append( Indent( 5 ) ).Append( '}' );
		foreach ( var g in groups ?? Array.Empty<VariantGroup>() )
			materials.Append( ",\n" ).Append( Indent( 5 ) ).Append( "{ _class = \"MaterialGroup\" name = " ).Append( UnityMaterial.Quote( g.Name ) ).Append( " remaps = [ " ).Append( Remaps( g.Remaps ) ).Append( " ] }" );
		materials.Append( '\n' ).Append( Indent( 4 ) ).Append( "]\n" ).Append( Indent( 3 ) ).Append( '}' );
		children.Add( materials.ToString() );
		if ( renderMeshes.Count > 0 )
			children.Add( Indent( 3 ) + "{\n" + Indent( 4 ) + "_class = \"RenderMeshList\"\n" + Indent( 4 ) + "children =\n" + Indent( 4 ) + "[\n" + string.Join( ",\n", renderMeshes ) + "\n" + Indent( 4 ) + "]\n" + Indent( 3 ) + "}" );
		if ( named )
			children.Add( Indent( 3 ) + "{\n" + Indent( 4 ) + "_class = \"LODGroupList\"\n" + Indent( 4 ) + "children =\n" + Indent( 4 ) + "[\n" + string.Join( ",\n", lodGroups ) + "\n" + Indent( 4 ) + "]\n" + Indent( 3 ) + "}" );
		if ( physics != null )
			children.Add( Indent( 3 ) + "{ _class = \"PhysicsShapeList\" children = [ " + PhysicsNode( physics.File, physics.Meshes, physics.Scale, convex ) + " ] }" );
		text.Append( string.Join( ",\n", children ) ).Append( '\n' ).Append( Indent( 2 ) ).Append( "]\n" ).Append( Indent( 2 ) ).Append( "model_archetype = \"\"\n" ).Append( Tab ).Append( "}\n}\n" );
		return text.ToString();
	}

	/// <summary>The deepest folder shared by the paths, with a trailing slash; empty when they share none.</summary>
	internal static string PackageFolder( IEnumerable<string> paths )
	{
		string[] shared = null;
		foreach ( var path in paths )
		{
			var folders = path.Replace( '\\', '/' ).Split( '/' )[..^1];
			shared = shared == null ? folders : shared.Zip( folders ).TakeWhile( p => p.First.Equals( p.Second, StringComparison.OrdinalIgnoreCase ) ).Select( p => p.First ).ToArray();
		}
		return shared is { Length: > 0 } ? string.Join( "/", shared ) + "/" : "";
	}

	/// <summary>
	/// Unity's LOD bias, which divides every LOD group's switch heights. Packages carry no quality settings; this is the
	/// bias of Unity's default desktop quality level (built-in Ultra, URP High Fidelity).
	/// </summary>
	internal const double UnityLodBias = 2;
	/// <summary>The LOD group size assumed when a model's bounds are unknown, in inches (one meter).</summary>
	internal const double DefaultLodSize = UnityTransform.InchesPerMeter;

	/// <summary>
	/// Errors that skip one asset instead of stopping the import: malformed or unexpected source data. Cancellation, file
	/// system and memory failures still stop it.
	/// </summary>
	static bool Skippable( Exception ex ) => ex is not (OperationCanceledException or IOException or UnauthorizedAccessException or OutOfMemoryException);
	static string Describe( Exception ex ) => ex is InvalidDataException ? ex.Message : $"{ex.GetType().Name}: {ex.Message}";

	/// <summary>
	/// Unity's screen-relative LOD height as an s&amp;box switch threshold, for a LOD group of the given size (Unity's
	/// largest bounds axis, in inches). Measured in the engine, a level switches in at a camera distance of 0.0201 ×
	/// threshold × the camera's focal length in pixels, whatever the model's size or shape (a 40 and a 400 inch cube switch
	/// at the same distance). Unity switches where the group's size covers that height ÷ LOD bias of the screen height, at a
	/// distance of size × bias × focal length ÷ (height × screen height). Equal on a 1080-pixel-high screen: threshold =
	/// size × bias ÷ (21.7 × height). s&amp;box switches move with resolution; Unity's do not.
	/// </summary>
	internal static double LodThreshold( double screenRelativeHeight, double size ) =>
		Math.Round( Math.Max( 1, size ) * UnityLodBias / (0.0201 * 1080 * Math.Max( 0.001, screenRelativeHeight )), 2 );
}