66 lines
2.2 KiB
C#
66 lines
2.2 KiB
C#
using UnityEngine;
|
|
|
|
[ExecuteAlways]
|
|
public class FogNoiseGenerator : MonoBehaviour
|
|
{
|
|
public Material targetMaterial;
|
|
public string propertyName = "_FogNoise";
|
|
public int size = 64;
|
|
public float scale = 0.05f;
|
|
public int seed = 1337;
|
|
|
|
void Start() { if (Application.isPlaying) Generate(); }
|
|
|
|
[ContextMenu("Generate Noise")]
|
|
public void Generate()
|
|
{
|
|
if (targetMaterial == null) { Debug.LogWarning("No target material set"); return; }
|
|
var tex = CreatePerlin3D(size, scale, seed);
|
|
tex.wrapMode = TextureWrapMode.Repeat;
|
|
tex.filterMode = FilterMode.Trilinear;
|
|
tex.Apply();
|
|
targetMaterial.SetTexture(propertyName, tex);
|
|
Debug.Log("Generated Texture3D and assigned to material");
|
|
}
|
|
|
|
static Texture3D CreatePerlin3D(int size, float scale, int seed)
|
|
{
|
|
var tex = new Texture3D(size, size, size, TextureFormat.RGBA32, false);
|
|
var cols = new Color[size * size * size];
|
|
var rng = new System.Random(seed);
|
|
float ox = (float)rng.NextDouble() * 10000f, oy = (float)rng.NextDouble() * 10000f, oz = (float)rng.NextDouble() * 10000f;
|
|
int idx = 0;
|
|
for (int z = 0; z < size; z++)
|
|
{
|
|
float wz = (z + oz) * scale;
|
|
for (int y = 0; y < size; y++)
|
|
{
|
|
float wy = (y + oy) * scale;
|
|
for (int x = 0; x < size; x++)
|
|
{
|
|
float wx = (x + ox) * scale;
|
|
float n = FractalPerlin(wx, wy, wz, 3);
|
|
cols[idx++] = new Color(n, n, n, n);
|
|
}
|
|
}
|
|
}
|
|
tex.SetPixels(cols);
|
|
return tex;
|
|
}
|
|
|
|
static float FractalPerlin(float x, float y, float z, int octaves)
|
|
{
|
|
float amp = 1f, freq = 1f, sum = 0f, max = 0f;
|
|
for (int i = 0; i < octaves; i++)
|
|
{
|
|
sum += amp * Mathf.PerlinNoise(x * freq, y * freq);
|
|
sum += amp * Mathf.PerlinNoise(y * freq, z * freq);
|
|
sum += amp * Mathf.PerlinNoise(z * freq, x * freq);
|
|
max += 3f * amp;
|
|
amp *= 0.5f;
|
|
freq *= 2f;
|
|
}
|
|
return Mathf.Clamp01(sum / max);
|
|
}
|
|
}
|