NoiseCombinator.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using Sirenix.OdinInspector;
  5. namespace KairoEngine.NoiseUtilities
  6. {
  7. [System.Serializable]
  8. public class NoiseCombinator
  9. {
  10. [PreviewField(256, ObjectFieldAlignment.Center), HideLabel, PropertyOrder(0)]
  11. public Texture2D texture;
  12. [PropertyOrder(2), OnCollectionChanged("Before", "After"), OnInspectorInit("After")] public List<NoiseGenerator> generators = new List<NoiseGenerator>();
  13. [PropertyOrder(3), HideInInspector] public Vector2Int size = new Vector2Int(128, 128);
  14. public float SamplePoint(float x, float y)
  15. {
  16. float value = 0;
  17. for (int i = 0; i < generators.Count; i++)
  18. {
  19. switch (generators[i].blending)
  20. {
  21. case NoiseBlendingModes.Blend:
  22. value = BlendSubpixel(value, generators[i].SamplePoint(x, y), 1, 1f - generators[i].opacity);
  23. break;
  24. case NoiseBlendingModes.Addictive:
  25. value += generators[i].SamplePoint(x, y) * generators[i].opacity;
  26. break;
  27. case NoiseBlendingModes.Subtractive:
  28. value -= generators[i].SamplePoint(x, y) * generators[i].opacity;
  29. break;
  30. }
  31. value = Mathf.Clamp(value, 0, 1f);
  32. }
  33. return value;
  34. }
  35. //[Button("Preview"), PropertyOrder(1)]
  36. public void GenerateTexture()
  37. {
  38. texture = new Texture2D(size.x, size.y);
  39. for (int x = 0; x < size.x; x++)
  40. {
  41. for (int y = 0; y < size.y; y++)
  42. {
  43. float xCoord = (((float)x / size.x));
  44. float yCoord = (((float)y / size.y));
  45. float sample = SamplePoint(xCoord, yCoord);
  46. Color color = new Color(sample, sample, sample);
  47. texture.SetPixel(x, y, color);
  48. }
  49. }
  50. texture.Apply();
  51. }
  52. static float BlendSubpixel(float top, float bottom, float alphaTop, float alphaBottom){
  53. return (top * alphaTop) + ( (bottom-1f) * (alphaBottom-alphaTop) );
  54. }
  55. public void Before() { }
  56. public void After()
  57. {
  58. for (int i = 0; i < generators.Count; i++) generators[i].OnChangeDelegate = GenerateTexture;
  59. GenerateTexture();
  60. }
  61. }
  62. }