Editor/VmdlObjExporter.cs

Editor utility that loads a .vmdl Model asset and exports it to OBJ/MTL plus copies/writes texture maps. It reads model vertex and index data, builds face groups per mesh/draw-call, collects materials, writes OBJ/MTL and opens the output folder.

File Access
namespace Sandbox;

/// <summary>
/// Loads a VMDL and exports OBJ + MTL + texture sources.
/// </summary>
public static class VmdlObjExporter
{
	public static bool TryExportFromAsset( Asset asset )
	{
		if ( asset is null || string.IsNullOrWhiteSpace( asset.Path ) )
		{
			ShowDialog( "No asset selected." );
			return false;
		}

		if ( !asset.Path.EndsWith( ".vmdl", StringComparison.OrdinalIgnoreCase ) )
		{
			ShowDialog( "Select a .vmdl asset." );
			return false;
		}

		var modelName = string.IsNullOrWhiteSpace( asset.Name )
			? Path.GetFileNameWithoutExtension( asset.Path )
			: asset.Name;

		var parentDir = Path.GetDirectoryName( asset.AbsolutePath );
		if ( string.IsNullOrWhiteSpace( parentDir ) )
			parentDir = Environment.CurrentDirectory;

		var defaultObj = Path.Combine( parentDir, $"{modelName}_obj", $"{modelName}.obj" );
		Directory.CreateDirectory( Path.GetDirectoryName( defaultObj )! );

		var chosen = EditorUtility.SaveFileDialog( "Export OBJ", "obj", defaultObj );
		if ( string.IsNullOrWhiteSpace( chosen ) )
			return false;

		return TryExport( asset.Path, chosen );
	}

	public static bool TryExport( string modelPath, string objPath )
	{
		try
		{
			var model = Model.Load( modelPath );
			if ( model is null || !model.IsValid() || model.IsError )
			{
				ShowDialog( $"Could not load model:\n{modelPath}" );
				return false;
			}

			if ( !model.HasRenderMeshes() )
			{
				ShowDialog( "This model has no render meshes." );
				return false;
			}

			if ( !TryBuildGeometry( model, out var vertices, out var groups, out var materials ) )
			{
				ShowDialog( "Could not read mesh geometry from this model." );
				return false;
			}

			if ( groups.Count == 0 || vertices.Length == 0 )
			{
				ShowDialog( "No triangle data to export." );
				return false;
			}

			var outputDir = Path.GetDirectoryName( objPath ) ?? ".";
			Directory.CreateDirectory( outputDir );

			var mtlFileName = Path.GetFileNameWithoutExtension( objPath ) + ".mtl";

			ObjWriter.Write(
				objPath,
				mtlFileName,
				vertices,
				groups,
				materials,
				slot => MaterialTextureExporter.WriteMapsAndCopyTextures( slot, outputDir ) );

			Log.Info( $"[ModelExporter] Exported '{modelPath}' → '{objPath}' ({vertices.Length} verts, {materials.Count} materials)" );
			ShowDialog( $"Exported OBJ to:\n{outputDir}" );
			EditorUtility.OpenFolder( outputDir );
			return true;
		}
		catch ( Exception e )
		{
			Log.Warning( $"[ModelExporter] Export failed for '{modelPath}': {e}" );
			ShowDialog( $"Export failed:\n{e.Message}" );
			return false;
		}
	}

	static bool TryBuildGeometry(
		Model model,
		out Vertex[] vertices,
		out List<ObjWriter.FaceGroup> groups,
		out List<ObjWriter.MaterialSlot> materials )
	{
		vertices = Array.Empty<Vertex>();
		groups = new List<ObjWriter.FaceGroup>();
		materials = new List<ObjWriter.MaterialSlot>();

		var materialList = materials;
		var materialKeys = new Dictionary<Material, string>();

		string AddMaterial( Material material, string fallbackName )
		{
			if ( material is not null && materialKeys.TryGetValue( material, out var existing ) )
				return existing;

			var rawName = material is not null
				? (string.IsNullOrWhiteSpace( material.Name ) ? fallbackName : material.Name)
				: fallbackName;

			var unique = MakeUniqueName( ObjWriter.SanitizeMtlName( Path.GetFileNameWithoutExtension( rawName ) ), materialList );
			materialList.Add( new ObjWriter.MaterialSlot( unique, material ) );

			if ( material is not null )
				materialKeys[material] = unique;

			return unique;
		}

		var allVerts = model.GetVertices();
		var allIndices = model.GetIndices() ?? Array.Empty<uint>();
		if ( allVerts is null || allVerts.Length == 0 )
			return false;

		vertices = allVerts;

		if ( TryBuildFromMeshInfo( model, vertices, allIndices, groups, AddMaterial ) )
		{
			EnsureAllMaterials( model, AddMaterial, materialKeys );
			return groups.Count > 0;
		}

		groups.Clear();
		materialList.Clear();
		materialKeys.Clear();

		var matList = model.Materials;
		var matName = matList.Length > 0 && matList[0] is not null
			? AddMaterial( matList[0], "material_0" )
			: AddMaterial( null, "material_0" );

		var tri = BuildFlatTriangleList( allIndices, vertices.Length );
		if ( tri.Count >= 3 )
			groups.Add( new ObjWriter.FaceGroup( "mesh", matName, tri ) );

		EnsureAllMaterials( model, AddMaterial, materialKeys );
		return groups.Count > 0;
	}

	static bool TryBuildFromMeshInfo(
		Model model,
		Vertex[] vertices,
		uint[] globalIndices,
		List<ObjWriter.FaceGroup> groups,
		Func<Material, string, string> addMaterial )
	{
		groups.Clear();

		Model.ModelMeshInfo meshInfo;
		try
		{
			meshInfo = model.MeshInfo;
		}
		catch
		{
			return false;
		}

		if ( meshInfo is null || meshInfo.Meshes is null || meshInfo.Meshes.Length == 0 )
			return false;

		var drawCallIndex = 0;
		var any = false;

		foreach ( var mesh in meshInfo.Meshes )
		{
			try
			{
				if ( mesh.LodMask != 0 && (mesh.LodMask & 1) == 0 )
					continue;
			}
			catch
			{
				// keep mesh if LodMask is unavailable
			}

			if ( mesh.DrawCalls is null || mesh.DrawCalls.Length == 0 )
				continue;

			var meshName = string.IsNullOrWhiteSpace( mesh.Name ) ? $"mesh_{drawCallIndex}" : mesh.Name;

			foreach ( var draw in mesh.DrawCalls )
			{
				var matName = addMaterial( draw.Material, $"{meshName}_{drawCallIndex}" );
				var tri = ExtractTriangleIndices( model, draw, drawCallIndex, globalIndices, vertices.Length );

				if ( tri.Count >= 3 )
				{
					groups.Add( new ObjWriter.FaceGroup( $"{meshName}_{drawCallIndex}", matName, tri ) );
					any = true;
				}

				drawCallIndex++;
			}
		}

		return any;
	}

	static List<int> ExtractTriangleIndices(
		Model model,
		Model.ModelMeshInfo.DrawCallData draw,
		int drawCallIndex,
		uint[] globalIndices,
		int vertexCount )
	{
		var result = new List<int>();

		var start = draw.StartIndex;
		var count = draw.Indices;
		var baseVertex = draw.BaseVertex;

		// Prefer public draw-call helpers when the MeshInfo counts look empty.
		if ( count <= 0 )
		{
			try
			{
				start = model.GetIndexStart( drawCallIndex );
				count = model.GetIndexCount( drawCallIndex );
				baseVertex = model.GetBaseVertex( drawCallIndex );
			}
			catch
			{
				return result;
			}
		}

		if ( count <= 0 || globalIndices.Length == 0 )
			return result;

		if ( start < 0 || start + count > globalIndices.Length )
			return result;

		for ( var i = 0; i < count; i++ )
		{
			var idx = (int)globalIndices[start + i] + baseVertex;
			if ( idx >= 0 && idx < vertexCount )
				result.Add( idx );
		}

		return result;
	}

	static List<int> BuildFlatTriangleList( uint[] indices, int vertexCount )
	{
		var tri = new List<int>( indices.Length );
		for ( var i = 0; i < indices.Length; i++ )
		{
			var idx = (int)indices[i];
			if ( idx >= 0 && idx < vertexCount )
				tri.Add( idx );
		}

		if ( tri.Count < 3 && vertexCount >= 3 )
		{
			tri.Clear();
			for ( var i = 0; i + 2 < vertexCount; i += 3 )
			{
				tri.Add( i );
				tri.Add( i + 1 );
				tri.Add( i + 2 );
			}
		}

		return tri;
	}

	static void EnsureAllMaterials(
		Model model,
		Func<Material, string, string> addMaterial,
		Dictionary<Material, string> materialKeys )
	{
		foreach ( var mat in model.Materials )
		{
			if ( mat is null )
				continue;
			if ( materialKeys.ContainsKey( mat ) )
				continue;
			addMaterial( mat, Path.GetFileNameWithoutExtension( mat.Name ) ?? "material" );
		}
	}

	static string MakeUniqueName( string baseName, List<ObjWriter.MaterialSlot> existing )
	{
		if ( existing.All( m => !string.Equals( m.Name, baseName, StringComparison.OrdinalIgnoreCase ) ) )
			return baseName;

		for ( var i = 2; i < 10000; i++ )
		{
			var candidate = $"{baseName}_{i}";
			if ( existing.All( m => !string.Equals( m.Name, candidate, StringComparison.OrdinalIgnoreCase ) ) )
				return candidate;
		}

		return $"{baseName}_{Guid.NewGuid():N}";
	}

	static void ShowDialog( string message )
	{
		EditorUtility.DisplayDialog( "Model Exporter", message, "OK", "", null );
	}
}