Importing WebGL-only or WebGPU-only

Background

As recent development babylon.js is making dual-version shaders, one for WebGL, and one for WebGPU. But the shaders are imported via side effect and can not be tree-shaked by bundlers, that makes final packaged size grow in recent versions.

Here is a graph from webpack-bundle-analyzer that shows both Shaders and ShadersWGSL are kept in the final package, and takes considerable size.

Proposal

Add WebGL-only and WebGPU-only variants for each index.ts file, taking Meshes/index.ts for example:

A Meshes/index-webgl.ts contains only import/exports from Shaders, and a Meshes/index-webgpu.ts contains only import/exports from ShadersWGSL.
Also, when importing from other index file, like export * from "./fluidRenderer/index"; would be export * from "./fluidRenderer/index-webgl"; or export * from "./fluidRenderer/index-webgpu";

Alternative

  • Do not import from any index file, and manually import only files needed, which could be a major overhead to downstream devs.
  • Compile shaders to space-efficient compressed bytecode format and recover at runtime, which could make loading slower.
  • Configure bundlers to ignore shader imports globally

This is the current recommendation and @ryantrem / @RaananW have a plan for easier management.

3 Likes

If anyone interested, here is a webpack-based config that excludes part of the shaders with externals

webpack.config.js


const excludeBabylonjs = [
  /node_modules[\\/]@babylonjs[\\/]core[\\/]ShadersWGSL/, // Exclude WebGPU Shaders
  // /node_modules[\\/]@babylonjs[\\/]core[\\/]Shaders/, // Exclude WebGL Shaders
  // Add more here
];
module.exports = {
    externals: function (context, request, callback) {
      const absPath = path.join(context, request);
      const relPath = path.relative(__dirname, absPath);
      for (let i = 0, length = excludeBabylonjs.length; i < length; i++) {
        if (excludeBabylonjs[i].test(relPath)) {
          callback(null, {
            root: 'Object', // It should be safe since shader imports are side-effects only
          });
          return;
        }
      }
      callback();
    }
};
2 Likes