Skip to content
Snippets Groups Projects
Octave.cs 2.15 KiB
Newer Older
using System;
using System.Collections.Generic;
using Unity.Mathematics;
using UnityEngine;

[Serializable]
public enum NoiseType
{
    MathfPerlin,
    MathematicsPerlin,
    Simplex,
    Celluar
}

[Serializable]
public struct Octave
{
    public float amplitude;
    public float frequency;
    public NoiseType type;
    public Vector2 offset;

    public float Calculate(float2 position)
    {
        float addition;

        position += new float2(offset);

        switch (type)
        {
            default:
            case NoiseType.MathfPerlin:
                addition = Mathf.PerlinNoise(position.x, position.y);
                break;
            case NoiseType.MathematicsPerlin:
                addition = noise.cnoise(position) / 2.3f + 0.5f;
                break;
            case NoiseType.Simplex:
                addition = noise.snoise(position) / 4.6f + 0.5f;
                break;
            case NoiseType.Celluar:
                addition = noise.cellular(position).x / 2.3f + 0.5f;
                break;
        }

        return addition * amplitude;
    }
Ryan Chang's avatar
Ryan Chang committed

    /// <summary>
    /// Copies an octave.
    /// </summary>
    /// <param name="copy"></param>
    public Octave(Octave copy)
    {
        amplitude = copy.amplitude;
        frequency = copy.frequency;
        type = copy.type;
        offset = copy.offset;
    }

    /// <summary>
    /// Copies an octave, but changes the offset.
    /// </summary>
    /// <param name="copy"></param>
    /// <param name="offset"></param>
    public Octave(Octave copy, Vector2 offset)
    {
        amplitude = copy.amplitude;
        frequency = copy.frequency;
        type = copy.type;
        this.offset = offset;
    }
Ryan Chang's avatar
Ryan Chang committed
}

public static class OctaveExtensions
{
    private static float MAX_OCTAVE_OFFSET = 256;

    public static List<Octave> ReseedOctave(this List<Octave> octaves)
    {
        List<Octave> output = new(octaves.Count);

        foreach (var o in octaves)
        {
            Octave newOctave = new(o, RandomOffset());
            output.Add(newOctave);
        }

        return output;
    }

    private static Vector2 RandomOffset() => RNG.GetRandomVector2(MAX_OCTAVE_OFFSET);