sirhcofe / minirt

2 stars 0 forks source link

Possible use of Union and Struct #28

Open nwhean opened 9 months ago

nwhean commented 9 months ago

https://github.com/sirhcofe/minirt/blob/458c8ce738501bb80e7e7264597ee9706dbf3a50/src/driver/draw.c#L15

One of the things I didn't do, but hoped I did, in my own project, was the use of union when it comes to colour manipulation. The colour could be defined as something like

typedef union colour { 
    unsigned int  colour;
    struct {
        char blue;
        char green;
        char red;
        char transparency;
    }
} t_colour;

So you'll be able have quick access to the individual components, rather than having to do bit shifting / mask, or hard-to-read code like the get_t, get_r, get_g and get-b as given in https://harm-smits.github.io/42docs/libs/minilibx/colors.html.

DeOtherJoT commented 9 months ago

Our code uses the struct t_rgb

typedef struct s_rgb
{
    double  red;
    double  green;
    double  blue;
}   t_rgb;

If I understand correctly, this provides us with the quick access you mentioned. I am not sure how we would avoid the bit manipulation done by create_colour, using the union you have prototyped above. Can you please elaborate further?

nwhean commented 9 months ago

I've edited out some errors in my previous comment. Here's a code snippet to show you the gist:

#include <stdio.h>

typedef union colour { 
    unsigned int  colour;
    struct {
        char blue;
        char green;
        char red;
        char transparency;
    }
} t_colour;

int main() {
    t_colour col;

    col.colour = 0;
    printf("colour: %x\n", col.colour);

    col.transparency = 0xab;
    col.red = 0xcd;
    col.green = 0xef;
    col.blue = 0x01;
    printf("colour: %x\n", col.colour);

    return 0;
}

and you'll get the output

colour: 0 colour: abcdef01

you may want to play with the union definition a bit to get it to work with the colour definition in minilibx.