简体   繁体   中英

C++ type on GPU(Metal), how to save the type of another variable into a class, and make sure all the class instance have the same size?

Pseudocode on CPU side:

class Sphere {
//some property 
}

class Square {
//some property
}

class BVH {
    Type type; // save the type of Sphere or Square, or other types.
    // But the instance of this class should maintain the same size.
}

It's possible using enum as type, then checking type and branching on GPU. I already got it working on GPU. But if I can save the type directly into this class, maybe I can do type cast and use template on GPU. In my understanding, it will reduce all the ugly branching.

All the logic happens on GPU side, CPU side is only preparing data. GPU(Metal) doesn't super class and virtual function, but template is supported. It's better to avoid any std stuff unless I can get the same type on GPU.

Since you talk about parsing to a GPU, I assume that what you need can be an ugly solution, and your focus is on it being efficient rather than readable and nice.This would look something like this:

union Figure
{
    Square square;
    Sphere sphere;
};

class BVH {

public:

    enum class FigureType { Square, Sphere };
    BVH(Square square) // or const Square& square, or move...
    {
        type = FigureType::Square;
        figure.square = square;
    }
    BVH(Sphere sphere) { ... }
    // Or instead of the two signatures above,
    // BVH(Figure figure, FigureType type);
    // although that would allow the two parameters to not match.
    // One might even consider to make the enum private.

    void process()
    {
        // or switch
        if(type == FigureType::Square) process_square();
        ...
    }

private:

    FigureType type;
    Figure figure;

    void process_square()
    {
        figure.square.do_something();
    }
}

For more about union s, see https://en.cppreference.com/w/cpp/language/union

But again, union s are ugly, and I only mention those as possibility when you really have to do it, ugly very low level programming. If you can go by making BVH a template, or if you can introduce some super class Figure from which Square and Sphere inherit and have BVH store a pointer to Figure , maybe even with Figure providing an interface for the sub classes to overwrite, that would be preferable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM