TiledTerrain/Assets/Tile Terrain/Runtime/RuntimeGlobals.cs

63 lines
1.8 KiB
C#
Raw Normal View History

2024-08-28 11:22:57 +03:00
using UnityEngine;
namespace BitGames.Terrain
{
internal static class RuntimeGlobals
{
public const float TILE_SIZE = 2.5f;
public static readonly SizeOption[] SizeOptions = { new(32), new(64), new(128), new(256) };
private static Material _instancedMaterial;
private static int _materialDependencies;
private static TerrainAsset _currentAsset;
private static readonly int ControlMapId = Shader.PropertyToID("ControlMap");
private static readonly int ShadowMapId = Shader.PropertyToID("ShadowMap");
private static readonly int ShadowColorId = Shader.PropertyToID("ShadowColor");
private static readonly int TileSizeId = Shader.PropertyToID("TileSize");
public static Material RegisterMaterialUser(ITerrainMaterialUser user)
{
if (_materialDependencies == 0 || _instancedMaterial == null)
{
_instancedMaterial = new Material(Shader.Find("Terrain/Tile Terrain")) { name = "Terrain (instance)" };
}
_materialDependencies++;
return _instancedMaterial;
}
public static void RemoveMaterialUser(ITerrainMaterialUser user)
{
_materialDependencies--;
if (_materialDependencies == 0)
{
SafeDestroy(_instancedMaterial);
}
}
private static void SafeDestroy(Object obj)
{
#if UNITY_EDITOR
if(UnityEditor.EditorApplication.isPlaying)
Object.Destroy(obj);
else
Object.DestroyImmediate(obj);
#else
Object.Destroy(obj);
#endif
}
public static void ActivateAsset(TerrainAsset asset)
{
_currentAsset = asset;
Shader.SetGlobalTexture(ControlMapId, asset.ControlTexture);
Shader.SetGlobalTexture(ShadowMapId, asset.ShadowTexture);
Shader.SetGlobalColor(ShadowColorId, asset.ShadowColor);
Shader.SetGlobalFloat(TileSizeId, TILE_SIZE);
}
}
}