NoiseGenerator.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using Sirenix.OdinInspector;
  5. namespace KairoEngine.NoiseUtilities
  6. {
  7. public enum NoiseBlendingModes
  8. {
  9. Blend,
  10. Addictive,
  11. Subtractive
  12. }
  13. [System.Serializable]
  14. public class NoiseGenerator
  15. {
  16. [HorizontalGroup("Slpit", 80, MarginRight = 15), VerticalGroup("Slpit/Preview"), PreviewField(80, ObjectFieldAlignment.Left), HideLabel]
  17. public Texture2D texture;
  18. [HorizontalGroup("Slpit"), VerticalGroup("Slpit/Config"), LabelWidth(80), OnValueChanged("OnChange")] public float scale = 1f;
  19. [HorizontalGroup("Slpit"), VerticalGroup("Slpit/Config"), LabelWidth(80), OnValueChanged("OnChange")] public Vector2 offset = new Vector2();
  20. [HorizontalGroup("Slpit"), VerticalGroup("Slpit/Config"), LabelWidth(80), Range(0, 1f), OnValueChanged("OnChange")] public float opacity = 1f;
  21. [HorizontalGroup("Slpit"), VerticalGroup("Slpit/Config"), LabelWidth(80), OnValueChanged("OnChange")] public NoiseBlendingModes blending = NoiseBlendingModes.Blend;
  22. [HorizontalGroup("Slpit"), VerticalGroup("Slpit/Config"), LabelWidth(80), HideInInspector] public Vector2Int size = new Vector2Int(128, 128);
  23. [HideInInspector] public System.Action OnChangeDelegate;
  24. public NoiseGenerator()
  25. {
  26. this.size = new Vector2Int(128, 128);;
  27. this.scale = 1f;
  28. this.offset = new Vector2();
  29. this.opacity = 1f;
  30. //GenerateTexture(); // Disabled to fix weird bug when unity starts
  31. }
  32. public float SamplePoint(float x, float y)
  33. {
  34. float xCoord = (x * scale) + offset.x;
  35. float yCoord = (y * scale) + offset.y;
  36. return Mathf.PerlinNoise(xCoord, yCoord);
  37. }
  38. public float SamplePixel(int x, int y)
  39. {
  40. float xCoord = (((float)x / size.x) * scale) + offset.x;
  41. float yCoord = (((float)y / size.y) * scale) + offset.y;
  42. return Mathf.PerlinNoise(xCoord, yCoord);
  43. }
  44. //[HorizontalGroup("Slpit"), VerticalGroup("Slpit/Preview"), Button("Preview")]
  45. public void GenerateTexture()
  46. {
  47. texture = new Texture2D(size.x, size.y);
  48. for (int x = 0; x < size.x; x++)
  49. {
  50. for (int y = 0; y < size.y; y++)
  51. {
  52. float sample = SamplePixel(x, y);
  53. Color color = new Color(sample, sample, sample);
  54. texture.SetPixel(x, y, color);
  55. }
  56. }
  57. texture.Apply();
  58. }
  59. private void OnChange()
  60. {
  61. GenerateTexture();
  62. if(OnChangeDelegate != null) OnChangeDelegate();
  63. }
  64. }
  65. }