Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: lod texture enforcer #75

Merged
merged 3 commits into from
Apr 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,9 @@ Unity_lic.*
# This gets changed all the time, we ignore it to have a cleaner checkout
asset-bundle-converter/Assets/git-submodules/unity-shared-dependencies/Runtime/Shaders/URP/Lit.shader.meta

.idea/
.idea/

# LODs

asset-bundle-converter/Assets/AssetBundleConverter/LODsConverter/ExportLODToAssetBundle/
asset-bundle-converter/Assets/AssetBundleConverter/LODsConverter/ExportLODToAssetBundle.meta
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;

public class CustomLODFBXPostProcessor : AssetPostprocessor
{
private void GenerateColliders(GameObject model)
{
var meshFilters = model.GetComponentsInChildren<MeshFilter>();

foreach (var filter in meshFilters)
{
if (filter.name.Contains("_collider", StringComparison.OrdinalIgnoreCase))
ConfigureColliders(filter.transform, filter);
}

var renderers = model.GetComponentsInChildren<Renderer>();

foreach (var r in renderers)
{
if (r.name.Contains("_collider", StringComparison.OrdinalIgnoreCase))
Object.DestroyImmediate(r);
}
}

private void ConfigureColliders(Transform transform, MeshFilter filter)
{
if (filter != null)
{
Physics.BakeMesh(filter.sharedMesh.GetInstanceID(), false);
filter.gameObject.AddComponent<MeshCollider>();
Object.DestroyImmediate(filter.GetComponent<MeshRenderer>());
}

foreach (Transform child in transform)
{
var f = child.gameObject.GetComponent<MeshFilter>();
ConfigureColliders(child, f);
}
}

private void OnPostprocessModel(GameObject model)
{
if (context.assetPath.EndsWith(".fbx") && model.name.EndsWith("_0"))
GenerateColliders(model);
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;
using AssetBundleConverter.LODsConverter.Utils;
using AssetBundleConverter.Wrappers.Interfaces;
using UnityEngine.Rendering;
Expand All @@ -12,9 +13,8 @@ namespace DCL.ABConverter
{
public class LODClient : MonoBehaviour
{

[MenuItem("Assets/Export URL LODs")]
public static void ExportURLLODsToAssetBundles()
[MenuItem("Decentraland/LOD/Export URL LODs")]
public static async void ExportURLLODsToAssetBundles()
{
string[] commandLineArgs = Environment.GetCommandLineArgs();

Expand All @@ -30,15 +30,18 @@ public static void ExportURLLODsToAssetBundles()
customOutputDirectory = outputDirectoryArg[0] + "/";

var lodConversion = new LODConversion(customOutputDirectory, lodsURL.Split(";"));
lodConversion.ConvertLODs();
await lodConversion.ConvertLODs();
}

[MenuItem("Assets/Export FBX Folder To Asset Bundles")]
private static void ExportFBXToAssetBundles()
[MenuItem("Decentraland/LOD/Export FBX Folder To Asset Bundles")]
private static async void ExportFBXToAssetBundles()
{
string[] fileEntries = Directory.GetFiles(Path.Combine(Application.dataPath, "ExportToAssetBundle"), "*.fbx", SearchOption.AllDirectories);
var lodConversion = new LODConversion(LODConstants.DEFAULT_OUTPUT_PATH, fileEntries);
lodConversion.ConvertLODs();
string[] fileEntries = Directory.GetFiles(Path.Combine(Application.dataPath, "AssetBundleConverter/LODsConverter/ExportLODToAssetBundle"), "*.fbx", SearchOption.AllDirectories);
if (fileEntries.Length > 0)
{
var lodConversion = new LODConversion(LODConstants.DEFAULT_OUTPUT_PATH, fileEntries);
await lodConversion.ConvertLODs();
}
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ public class LODConversion
{
private readonly LODPathHandler lodPathHandler;
private readonly string[] urlsToConvert;
private readonly Shader usedLODShader;
private readonly Shader usedLOD0Shader;


//TODO: CLEAN THIS UP HERE AND IN THE ASSET BUNDLE BUILDER. THIS IS NOT USED IN ALPHA
private const string VERSION = "7.0";
Expand All @@ -26,9 +29,11 @@ public LODConversion(string customOutputPath, string[] urlsToConvert)
{
this.urlsToConvert = urlsToConvert;
lodPathHandler = new LODPathHandler(customOutputPath);
usedLOD0Shader = Shader.Find("DCL/Scene");
usedLODShader = Shader.Find("DCL/Scene_TexArray");
}

public async void ConvertLODs()
public async Task ConvertLODs()
{
PlatformUtils.currentTarget = EditorUserBuildSettings.activeBuildTarget;
//TODO (Juani) Temporal hack. Clean with the regular asset bundle process
Expand All @@ -53,16 +58,14 @@ public async void ConvertLODs()
foreach (string downloadedFilePath in downloadedFilePaths)
{
lodPathHandler.SetCurrentFile(downloadedFilePath);
if (File.Exists(lodPathHandler.assetBundlePath))
continue;
dictionaryStringForMetadata.Add(lodPathHandler.fileNameWithoutExtension, lodPathHandler.fileNameWithoutExtension);
lodPathHandler.MoveFileToMatchingFolder();
BuildPrefab(lodPathHandler);
}

AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
assetDatabase.AssignAssetBundle(Shader.Find("DCL/Scene"), false);
assetDatabase.AssignAssetBundle(usedLOD0Shader, false);
assetDatabase.AssignAssetBundle(usedLODShader, false);
BuildAssetBundles(EditorUserBuildSettings.activeBuildTarget, dictionaryStringForMetadata);
}
catch (Exception e)
Expand All @@ -72,11 +75,12 @@ public async void ConvertLODs()
return;
}

//Temporal hack
lodPathHandler.RelocateOutputFolder();

Directory.Delete(lodPathHandler.tempPath, true);
Debug.Log("Conversion done");
foreach (string downloadedFilePath in downloadedFilePaths)
{
Debug.Log($"LOD conversion done for {Path.GetFileName(downloadedFilePath)}");
}
Utils.Exit();
}

Expand All @@ -102,63 +106,50 @@ private void BuildPrefab(LODPathHandler lodPathHandler)
AssetDatabase.WriteImportSettingsIfDirty(lodPathHandler.filePathRelativeToDataPath);
AssetDatabase.ImportAsset(lodPathHandler.filePathRelativeToDataPath, ImportAssetOptions.ForceUpdate);

var instantiated = Object.Instantiate(AssetDatabase.LoadAssetAtPath<GameObject>(lodPathHandler.filePathRelativeToDataPath));
var asset = AssetDatabase.LoadAssetAtPath<GameObject>(lodPathHandler.filePathRelativeToDataPath);

if (lodPathHandler.filePath.Contains("_0"))
{
SetDCLShaderMaterial(lodPathHandler, instantiated, false);
GenerateColliders(instantiated);
SetDCLShaderMaterial(lodPathHandler, asset, false, usedLOD0Shader);
}
else
SetDCLShaderMaterial(lodPathHandler, instantiated, true);
{
EnsureTextureFormat();
SetDCLShaderMaterial(lodPathHandler, asset, true, usedLODShader);
}

importer.SearchAndRemapMaterials(ModelImporterMaterialName.BasedOnMaterialName, ModelImporterMaterialSearch.Local);
AssetDatabase.WriteImportSettingsIfDirty(lodPathHandler.filePathRelativeToDataPath);
AssetDatabase.ImportAsset(lodPathHandler.filePath, ImportAssetOptions.ForceUpdate);

PrefabUtility.SaveAsPrefabAsset(instantiated, lodPathHandler.prefabPathRelativeToDataPath);
Object.DestroyImmediate(instantiated);

var prefabImporter = AssetImporter.GetAtPath(lodPathHandler.fileDirectoryRelativeToDataPath);
prefabImporter.SetAssetBundleNameAndVariant(lodPathHandler.assetBundleFileName, "");
}

private void GenerateColliders(GameObject instantiated)
private void EnsureTextureFormat()
{
var meshFilters = instantiated.GetComponentsInChildren<MeshFilter>();

foreach (var filter in meshFilters)
string[] texturePaths = Directory.GetFiles(lodPathHandler.fileDirectory, "*.png", SearchOption.AllDirectories);
foreach (string texturePath in texturePaths)
{
if (filter.name.Contains("_collider", StringComparison.OrdinalIgnoreCase))
ConfigureColliders(filter.transform, filter);
}

var renderers = instantiated.GetComponentsInChildren<Renderer>();
string assetPath = PathUtils.GetRelativePathTo(Application.dataPath, texturePath);
var importer = AssetImporter.GetAtPath(assetPath) as TextureImporter;
var texture = AssetDatabase.LoadAssetAtPath<Texture2D>(assetPath);

foreach (var r in renderers)
{
if (r.name.Contains("_collider", StringComparison.OrdinalIgnoreCase))
Object.DestroyImmediate(r);
}
}

private void ConfigureColliders(Transform transform, MeshFilter filter)
{
if (filter != null)
{
Physics.BakeMesh(filter.sharedMesh.GetInstanceID(), false);
filter.gameObject.AddComponent<MeshCollider>();
Object.DestroyImmediate(filter.GetComponent<MeshRenderer>());
}

foreach (Transform child in transform)
{
var f = child.gameObject.GetComponent<MeshFilter>();
ConfigureColliders(child, f);
if (importer != null)
{
importer.textureType = TextureImporterType.Default;
importer.isReadable = true;
importer.SetPlatformTextureSettings(new TextureImporterPlatformSettings
{
overridden = true, maxTextureSize = texture.width, name = "Standalone", format = TextureImporterFormat.BC7,
textureCompression = TextureImporterCompression.Compressed
});
AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);
}
}
}

private void SetDCLShaderMaterial(LODPathHandler lodPathHandler, GameObject transform, bool setDefaultTransparency)
private void SetDCLShaderMaterial(LODPathHandler lodPathHandler, GameObject transform, bool setDefaultTransparency, Shader shader)
{
var childrenRenderers = transform.GetComponentsInChildren<Renderer>();
var materialsDictionary = new Dictionary<string, Material>();
Expand All @@ -169,7 +160,8 @@ private void SetDCLShaderMaterial(LODPathHandler lodPathHandler, GameObject tran
{
var material = componentsInChild.sharedMaterials[i];
var duplicatedMaterial = new Material(material);
duplicatedMaterial.shader = Shader.Find("DCL/Scene");
duplicatedMaterial.shader = shader;

if (duplicatedMaterial.name.Contains("FORCED_TRANSPARENT"))
ApplyTransparency(duplicatedMaterial, setDefaultTransparency);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public class LODPathHandler
public string filePathRelativeToDataPath;

public string filePath;
public string fileDirectory;
public string fileName;
public string fileNameWithoutExtension;

Expand All @@ -39,23 +40,23 @@ public void SetCurrentFile(string downloadedFilePath)
{
filePath = downloadedFilePath;
fileName = Path.GetFileName(filePath);
fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);
fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath).ToLower();
assetBundleFileName = fileNameWithoutExtension + PlatformUtils.GetPlatform();
assetBundlePath = Path.Combine(outputPath, assetBundleFileName);
}

public void MoveFileToMatchingFolder()
{
string fileDirectory = Path.GetDirectoryName(filePath);
string newFileDirectory = Path.GetDirectoryName(filePath);

if (fileDirectory.EndsWith(fileNameWithoutExtension))
if (newFileDirectory.EndsWith(fileNameWithoutExtension))
{
Console.WriteLine("The file is already in the correct folder.");
UpdatePaths(filePath);
return;
}

string targetFolderPath = Path.Combine(fileDirectory, fileNameWithoutExtension);
string targetFolderPath = Path.Combine(newFileDirectory, fileNameWithoutExtension.ToLower());
Directory.CreateDirectory(targetFolderPath);
string newFilePath = Path.Combine(targetFolderPath, fileName);
File.Move(filePath, newFilePath);
Expand All @@ -66,13 +67,14 @@ public void MoveFileToMatchingFolder()
private void UpdatePaths(string newFilePath)
{
filePath = newFilePath;
string fileDirectory = Path.GetDirectoryName(filePath);
fileDirectory = Path.GetDirectoryName(filePath);
filePathRelativeToDataPath = PathUtils.GetRelativePathTo(Application.dataPath, filePath);
fileDirectoryRelativeToDataPath = PathUtils.GetRelativePathTo(Application.dataPath, fileDirectory);

string materialsPath = Path.Combine(fileDirectory, "Materials");
Directory.CreateDirectory(materialsPath);
materialsPathRelativeToDataPath = PathUtils.GetRelativePathTo(Application.dataPath, materialsPath);


prefabPathRelativeToDataPath = PathUtils.GetRelativePathTo(Application.dataPath, fileDirectory + "/" + fileNameWithoutExtension + " (gameobject).prefab");
// Save assets and refresh the AssetDatabase
Expand Down
Submodule unity-shared-dependencies updated 20 files
+8 −0 Runtime/Shaders/SceneRendering/TexArray.meta
+8 −0 Runtime/Shaders/SceneRendering/TexArray/LightCookie.meta
+117 −0 Runtime/Shaders/SceneRendering/TexArray/LightCookie/Scene_LightCookie.hlsl
+7 −0 Runtime/Shaders/SceneRendering/TexArray/LightCookie/Scene_LightCookie.hlsl.meta
+126 −0 Runtime/Shaders/SceneRendering/TexArray/LightCookie/Scene_LightCookieInput.hlsl
+7 −0 Runtime/Shaders/SceneRendering/TexArray/LightCookie/Scene_LightCookieInput.hlsl.meta
+13 −0 Runtime/Shaders/SceneRendering/TexArray/LightCookie/Scene_LightCookieTypes.hlsl
+7 −0 Runtime/Shaders/SceneRendering/TexArray/LightCookie/Scene_LightCookieTypes.hlsl.meta
+137 −0 Runtime/Shaders/SceneRendering/TexArray/Scene_DepthNormalsPass_TexArray.hlsl
+7 −0 Runtime/Shaders/SceneRendering/TexArray/Scene_DepthNormalsPass_TexArray.hlsl.meta
+52 −0 Runtime/Shaders/SceneRendering/TexArray/Scene_DepthOnlyPass_TexArray.hlsl
+7 −0 Runtime/Shaders/SceneRendering/TexArray/Scene_DepthOnlyPass_TexArray.hlsl.meta
+110 −0 Runtime/Shaders/SceneRendering/TexArray/Scene_Input_TexArray.hlsl
+7 −0 Runtime/Shaders/SceneRendering/TexArray/Scene_Input_TexArray.hlsl.meta
+78 −0 Runtime/Shaders/SceneRendering/TexArray/Scene_ShadowCasterPass_TexArray.hlsl
+7 −0 Runtime/Shaders/SceneRendering/TexArray/Scene_ShadowCasterPass_TexArray.hlsl.meta
+55 −0 Runtime/Shaders/SceneRendering/TexArray/Scene_SurfaceInput_TexArray.hlsl
+7 −0 Runtime/Shaders/SceneRendering/TexArray/Scene_SurfaceInput_TexArray.hlsl.meta
+315 −0 Runtime/Shaders/SceneRendering/TexArray/Scene_TexArray.shader
+9 −0 Runtime/Shaders/SceneRendering/TexArray/Scene_TexArray.shader.meta
Loading