Files
chameleon/Assets/Scripts/Editor/WebAssets/ModelImportUtil.cs
T
adminandClaude Fable 5 eab5081354 Add model import support to Poly Haven importer
Browser gets Textures/Models tabs (per-type catalog cache). Model file
JSON is parsed into per-set texture maps (generic set-prefix matching),
FBX is downloaded with resolution fallback, one URP/Lit material is
built per set via the shared PbrMaterialBuilder (which now returns the
created Material), and new ModelImportUtil remaps FBX material slots to
the built materials by set-name matching.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-16 16:43:24 +02:00

64 lines
2.5 KiB
C#

using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Chameleon.Editor.WebAssets
{
/// <summary>Shared helpers for imported 3D models (FBX etc.).</summary>
public static class ModelImportUtil
{
/// <summary>
/// Remaps every source material of an imported model to the given built materials.
/// With a single set, all slots get that material; with multiple sets, the source
/// material name is matched against the set names (substring, case-insensitive).
/// </summary>
public static void RemapMaterials(string modelAssetPath, List<(string setName, Material mat)> sets)
{
if (sets == null || sets.Count == 0)
return;
var importer = AssetImporter.GetAtPath(modelAssetPath) as ModelImporter;
if (!importer)
{
Debug.LogWarning($"[PBR Import] No model importer at {modelAssetPath} — skipping material remap.");
return;
}
// Source material names = the embedded materials Unity generated on import.
var srcNames = new List<string>();
foreach (var obj in AssetDatabase.LoadAllAssetsAtPath(modelAssetPath))
if (obj is Material m)
srcNames.Add(m.name);
if (srcNames.Count == 0)
{
Debug.LogWarning($"[PBR Import] {modelAssetPath} exposes no materials to remap.");
return;
}
foreach (var name in srcNames)
{
var target = Pick(name, sets);
if (!target)
continue;
importer.AddRemap(new AssetImporter.SourceAssetIdentifier(typeof(Material), name), target);
}
importer.SaveAndReimport();
Debug.Log($"[PBR Import] Remapped {srcNames.Count} material slot(s) on {modelAssetPath}.");
}
private static Material Pick(string srcName, List<(string setName, Material mat)> sets)
{
if (sets.Count == 1)
return sets[0].mat;
string s = srcName.ToLowerInvariant();
foreach (var (setName, mat) in sets)
if (!string.IsNullOrEmpty(setName) && s.Contains(setName.ToLowerInvariant()))
return mat;
Debug.LogWarning($"[PBR Import] Material '{srcName}' matched no texture set — using '{sets[0].setName}'.");
return sets[0].mat;
}
}
}