Skip to content

Instantly share code, notes, and snippets.

@JettMonstersGoBoom
Last active October 28, 2023 14:31
Show Gist options
  • Save JettMonstersGoBoom/29d0ea17f77bc3bbd69950d5ae5b5b85 to your computer and use it in GitHub Desktop.
Save JettMonstersGoBoom/29d0ea17f77bc3bbd69950d5ae5b5b85 to your computer and use it in GitHub Desktop.
Experiment with Generic and converting some Raylib Types to and from strings.
#include "raylib.h"
// printf("%s\n",toString((Vector3}(1,2,3));
// {1.0000,2.000,3.000} is printed
// toString can be used with any of the variable types below
#define toString(X) _Generic((X), \
Vector2 : TextFormat("{%f,%f}",X.x,X.y), \
Vector3 : TextFormat("{%f,%f,%f}",X.x,X.y,X.z), \
Vector4 : TextFormat("{%f,%f,%f,%f}",X.x,X.y,X.z,X.w), \
Rectangle : TextFormat("{%f,%f,%f,%f}",X.x,X.y,X.width,X.height), \
Color : TextFormat("{0x%02X,0x%02X,0x%02X,0x%02X}",X.r,X.g,X.b,X.a), \
Matrix : TextFormat("{\n\t%f,%f,%f,%f,\n\t%f,%f,%f,%f,\n\t%f,%f,%f,%f,\n\t%f,%f,%f,%f\n}",X.m0,X.m1,X.m2,X.m3,X.m4,X.m5,X.m6,X.m7,X.m8,X.m9,X.m10,X.m11,X.m12,X.m13,X.m14,X.m15))
// Rect rectangle;
// fromString(rectangle,"{0,0,320,400}");
// rectangle is now 0,0,320,400
#define fromString(X,S) _Generic((X), \
Vector2 : sscanf(S,"{%f,%f}",&X.x,&X.y),\
Vector3 : sscanf(S,"{%f,%f,%f}",&X.x,&X.y,&X.z),\
Vector4 : sscanf(S,"{%f,%f,%f,%f}",&X.x,&X.y,&X.z,&X.w),\
Rectangle : sscanf(S,"{%f,%f,%f,%f}",&X.x,&X.y,&X.width,&X.height),\
Color : sscanf(S,"{0x%02X,0x%02X,0x%02X,0x%02X}",&X.r,&X.g,&X.b,&X.a), \
Matrix : sscanf(S,"{\n\t%f,%f,%f,%f,\n\t%f,%f,%f,%f,\n\t%f,%f,%f,%f,\n\t%f,%f,%f,%f\n}",&X.m0,&X.m1,&X.m2,&X.m3,&X.m4,&X.m5,&X.m6,&X.m7,&X.m8,&X.m9,&X.m10,&X.m11,&X.m12,&X.m13,&X.m14,&X.m15))
// Vector4 someV4;
// printf("%s\n",toStringLabeled(someV4));
// someV4={.. , .. , .. , .. } is printed
#define toStringLabeled(X) TextFormat("%s=%s",#X,toString(X))
/*
printf("%s\n",toString(v2));
printf("%s\n",toString(v3));
printf("%s\n",toString(v4));
printf("%s\n",toString(color));
printf("%s\n",toString(rect));
printf("%s\n",toString(m0));
// labeled
printf("%s\n",toStringLabeled(v2));
printf("%s\n",toStringLabeled(v3));
printf("%s\n",toStringLabeled(v4));
printf("%s\n",toStringLabeled(color));
printf("%s\n",toStringLabeled(rect));
printf("%s\n",toStringLabeled(m0));
// conver v2 to a string
char *str = toString(v2);
// purposefully change it
v2.x = 0;
v2.y = 0;
fromString(v2,str);
// print it now e grabbed it from a string
printf("%s\n",toString(v2));
// same with a matrix
m0.m14=12;
m0.m15=32;
str = toString(m0);
fromString(m0,str);
printf("%s\n",toString(m0));
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment