NoiseGenerator.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 Vector2 randomOffset = new Vector2();
  24. [HideInInspector] public System.Action OnChangeDelegate;
  25. public NoiseGenerator()
  26. {
  27. this.size = new Vector2Int(128, 128);;
  28. this.scale = 1f;
  29. this.offset = new Vector2();
  30. this.opacity = 1f;
  31. //GenerateTexture(); // Disabled to fix weird bug when unity starts
  32. }
  33. public float SamplePoint(float x, float y)
  34. {
  35. float xCoord = (x * scale) + offset.x + randomOffset.x;
  36. float yCoord = (y * scale) + offset.y + randomOffset.y;
  37. return Mathf.PerlinNoise(xCoord, yCoord);
  38. }
  39. public float SamplePixel(int x, int y)
  40. {
  41. float xCoord = (((float)x / size.x) * scale) + offset.x + randomOffset.x;
  42. float yCoord = (((float)y / size.y) * scale) + offset.y + randomOffset.y;
  43. return Mathf.PerlinNoise(xCoord, yCoord);
  44. }
  45. //[HorizontalGroup("Slpit"), VerticalGroup("Slpit/Preview"), Button("Preview")]
  46. public void GenerateTexture()
  47. {
  48. var newTexture = new Texture2D(size.x, size.y);
  49. for (int x = 0; x < size.x; x++)
  50. {
  51. for (int y = 0; y < size.y; y++)
  52. {
  53. float sample = SamplePixel(x, y);
  54. Color color = new Color(sample, sample, sample);
  55. newTexture.SetPixel(x, y, color);
  56. }
  57. }
  58. newTexture.Apply();
  59. texture = newTexture;
  60. }
  61. private void OnChange()
  62. {
  63. GenerateTexture();
  64. if(OnChangeDelegate != null) OnChangeDelegate();
  65. }
  66. }
  67. }