changeset 1006:a96df6bc5545

did: refacotor for easier user of sRGB-conversion functions
author sam <sam@basx.dev>
date Mon, 15 Apr 2024 20:22:16 +0700
parents 3845b9f1d27d
children 6261baf55963
files semicongine/core/color.nim semicongine/core/imagetypes.nim
diffstat 2 files changed, 38 insertions(+), 22 deletions(-) [+]
line wrap: on
line diff
--- a/semicongine/core/color.nim	Mon Apr 15 14:36:19 2024 +0700
+++ b/semicongine/core/color.nim	Mon Apr 15 20:22:16 2024 +0700
@@ -1,3 +1,4 @@
+import std/math
 import std/parseutils
 import std/strformat
 
@@ -36,8 +37,40 @@
   discard parseHex(hex[6 .. 7], a)
   return Vec4f([float32(r), float32(g), float32(b), float32(a)]) / 255'f
 
-func gamma*[T: Vec3f|Vec4f](color: T, gamma: float32): T =
-  return pow(color, gamma)
+
+func linear2srgb*(value: SomeFloat): SomeFloat =
+  clamp(
+    if (value < 0.0031308): value * 12.92
+    else: pow(value, 1.0 / 2.4) * 1.055 - 0.055,
+    0,
+    1,
+  )
+func srgb2linear*(value: SomeFloat): SomeFloat =
+  clamp(
+    if (value < 0.04045): value / 12.92
+    else: pow((value + 0.055) / 1.055, 2.4),
+    0,
+    1,
+  )
+func linear2srgb*(value: uint8): uint8 = # also covers GrayPixel
+  uint8(round(linear2srgb(float(value) / 255.0) * 255))
+func srgb2linear*(value: uint8): uint8 = # also covers GrayPixel
+  uint8(round(srgb2linear(float(value) / 255.0) * 255))
+
+func toSRGB*(value: Vec4f): Vec4f =
+  newVec4f(
+    linear2srgb(value.r),
+    linear2srgb(value.g),
+    linear2srgb(value.b),
+    value.a,
+  )
+func fromSRGB*(value: Vec4f): Vec4f =
+  newVec4f(
+    srgb2linear(value.r),
+    srgb2linear(value.g),
+    srgb2linear(value.b),
+    value.a,
+  )
 
 const
   Black* = toRGBA "#000000FF"
--- a/semicongine/core/imagetypes.nim	Mon Apr 15 14:36:19 2024 +0700
+++ b/semicongine/core/imagetypes.nim	Mon Apr 15 20:22:16 2024 +0700
@@ -3,6 +3,7 @@
 
 import ./vulkanapi
 import ./vector
+import ./color
 
 type
   RGBAPixel* = array[4, uint8]
@@ -41,27 +42,9 @@
 
 # colorspace conversion functions
 
-func linear2srgb(value: float): float =
-  clamp(
-    if (value < 0.0031308): value * 12.92
-    else: pow(value, 1.0 / 2.4) * 1.055 - 0.055,
-    0,
-    1,
-  )
-func srgb2linear(value: float): float =
-  clamp(
-    if (value < 0.04045): value / 12.92
-    else: pow((value + 0.055) / 1.055, 2.4),
-    0,
-    1,
-  )
-func linear2srgb(value: uint8): uint8 = # also covers GrayPixel
-  uint8(round(linear2srgb(float(value) / 255.0) * 255))
-func linear2srgb(value: RGBAPixel): RGBAPixel =
+func linear2srgb*(value: RGBAPixel): RGBAPixel =
   [linear2srgb(value[0]), linear2srgb(value[1]), linear2srgb(value[2]), value[3]]
-func srgb2linear(value: uint8): uint8 = # also covers GrayPixel
-  uint8(round(srgb2linear(float(value) / 255.0) * 255))
-func srgb2linear(value: RGBAPixel): RGBAPixel =
+func srgb2linear*(value: RGBAPixel): RGBAPixel =
   [srgb2linear(value[0]), srgb2linear(value[1]), srgb2linear(value[2]), value[3]]
 
 proc asSRGB*[T](image: Image[T]): Image[T] =