add simple color data types

Mon, 30 Oct 2023 18:42:09 +0100

author
Mike Becker <universe@uap-core.de>
date
Mon, 30 Oct 2023 18:42:09 +0100
changeset 4
b7acda6a4476
parent 3
1efd6da2ad53
child 5
7e1196d551ff

add simple color data types

src/ascension/datatypes.h file | annotate | diff | comparison | revisions
--- a/src/ascension/datatypes.h	Mon Oct 30 18:09:27 2023 +0100
+++ b/src/ascension/datatypes.h	Mon Oct 30 18:42:09 2023 +0100
@@ -28,16 +28,66 @@
 #ifndef ASCENSION_DATATYPES_H
 #define ASCENSION_DATATYPES_H
 
+#include <SDL2/SDL_endian.h>
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
+typedef unsigned char asc_ubyte;
+typedef signed char asc_sbyte;
+
 typedef union {
     int data[2];
     struct { int x, y; };
     struct { int width, height; };
 } asc_vec2i;
 
+typedef union {
+    asc_ubyte data[4];
+#if SDL_BYTEORDER == SDL_BIG_ENDIAN
+    struct { asc_ubyte red, green, blue, alpha; };
+#else
+    struct { asc_ubyte alpha, blue, green, red; };
+#endif
+} asc_col4i;
+
+typedef union {
+    float data[4];
+#if SDL_BYTEORDER == SDL_BIG_ENDIAN
+    struct { float red, green, blue, alpha; };
+#else
+    struct { float alpha, blue, green, red; };
+#endif
+} asc_col4f;
+
+static inline int asc_clamp_i(int v, int min, int max) {
+    if (v < min) return min;
+    if (v > max) return max;
+    return v;
+}
+
+/**
+ * Converts a float color (0.0f to 1.0f) to an int color (0 to 255).
+ *
+ * This operation is quite expensive. When you need to use it often, it's
+ * quite obvious that you should change the data type.
+ *
+ * @param c the color using floats
+ * @return the same color using ints
+ */
+static inline asc_col4i asc_col_ftoi(asc_col4f c) {
+    int red = (int)(255*c.red);
+    int green = (int)(255*c.green);
+    int blue = (int)(255*c.blue);
+    int alpha = (int)(255*c.alpha);
+    asc_col4i r;
+    r.red = (asc_ubyte)asc_clamp_i(red, 0, 255);
+    r.green = (asc_ubyte)asc_clamp_i(green, 0, 255);
+    r.blue = (asc_ubyte)asc_clamp_i(blue, 0, 255);
+    r.alpha = (asc_ubyte)asc_clamp_i(alpha, 0, 255);
+    return r;
+}
 
 #ifdef __cplusplus
 } // extern "C"

mercurial