Skip to content

Directly activate a WebGL context from JS #27776

Description

@matzf

Using an already existing WebGL context requires a somewhat confusing dance with preinitializedWebGLContext.

To activate a GL context (as in https://github.com/emscripten-core/emscripten/blob/25c255b66fe553a4bff3761cbeb7add8f1583d25/test/browser/test_preinitialized_webgl_context.c):

  1. set preinitalizedWebGLContext on module creation
  2. call emscripten_webgl_context_create(), necessarily passing a valid canvas element reference and context attributes. These arguments will not really be used, this function returns (a handle to) the preinitializedWebGLContext.
  3. call emscripten_webgl_make_context_current(handle)

This appears more confusing than necessary. Also, this process does not seem to allow using the module with more than one WebGL context. This is something that we'd like to, to reuse our module to render into multiple (dynamically created) canvases.

To work around this, we've extended the Module with this --pre-js file.

// Activates the given WebGL context for rendering. Does _not_ register a context handle for the context and thus it cannot be referenced from WASM.
Module.makeWebGL2ContextCurrent = (ctx) => {
    GL.currentContext = {
        handle: -1, // unused?
        attributes: {}, // unused?
        version: 2,
        GLctx: ctx
    };
    Module['ctx'] = GLctx = GL.currentContext?.GLctx;
}

With this, we don't need any of the steps 1. - 3. above; we only call module.makeWebGL2ContextCurrent(gl) for our canvas and proceed to call into the WASM to render.


Questions:

  • Is there a pre-existing functionality that already achieves what our --pre-js extension does?
  • If not, would it be useful to add this to emscripten directly?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions