floooh / sokol

minimal cross-platform standalone C headers
https://floooh.github.io/sokol-html5
zlib License
6.53k stars 468 forks source link

A simple Initialization texture binding function would be nice to have #1050

Closed trace-andreason closed 1 month ago

trace-andreason commented 1 month ago

When I'm using sokol fetch to get a texture, I need to initialize the texture first with a placeholder texture. If you don't initialize the texture, because fetch won't finish on the first frame, your program crashes. It would be nice to have a function like this so everyone doesn't have to roll their own temporary texture binding function: https://github.com/zeromake/learnopengl-examples/blob/master/libs/sokol/sokol_helper.h

I'm working in zig, so I just wrote this:

fn dummyImage(textureSlot: u8) void {
    const data: [4]u8 = .{ 0, 0, 0, 0 };
    var img_desc: sg.ImageDesc = .{ .width = 1, .height = 1, .pixel_format = .RGBA8 };
    img_desc.data.subimage[0][0] = .{
        .ptr = &data,
        .size = 4,
    };
    state.bind.fs.images[textureSlot] = sg.makeImage(img_desc);
}

So its definitely not hard to work around, but I think that if everyone is going to need to do this when using fetch for textures, it might be good to have a more canonical solution to this problem.

floooh commented 1 month ago

Ah I see. You don't actually need to do that.

You can create the texture in two steps like I do here in the loadpng-sapp sample:

...next time the frame callback is called, the image handle will be valid and rendering works as expected.

The vanilla sg.makeImage() function is basically alloc + init in the same call.

You can also explicitly skip rendering by testing if the image is valid, smth like:

if (sg.queryImageState(img) == .VALID) {
    // image has been initialized and it's valid to render
} else {
    // image still loading, or failed to load
}

...theoretically the same works for all resource types, but is mainly intended for images and buffers.

Also see this documentation blurb: https://github.com/floooh/sokol/blob/c2d01bc25c58be460787d5f027eed73d1c036e6f/sokol_gfx.h#L1276-L1437

trace-andreason commented 1 month ago

Ah ok, makes sense. Interesting in the openGL examples I'm working from they actually have the same comment copied from that example presumably. Wonder why they felt the need to define a header 🤔

floooh commented 1 month ago

Tbf the two-step initialization and deinitialization of sokol-gfx resource objects isn't a prominent feature, and also had some inconsistencies until sometime last year.