封装一个初始化engine和scene的方法
async function initScene(cvs: HTMLCanvasElement): Promise<{
engine: WebGPUEngine | Engine
scene: Scene
}> {
const options = {
antialias: true,
adaptToDeviceRatio: false,
}
let engine: WebGPUEngine | Engine
let scene: Scene
Tools.ScriptBaseUrl = new URL('./config', import.meta.url).href
const webgpuSupported = await WebGPUEngine.IsSupportedAsync
if (webgpuSupported) {
engine = new WebGPUEngine(cvs, {
...options,
glslangOptions: {
jsPath: new URL('./config/glslang/glslang.js', import.meta.url).href,
wasmPath: new URL('./config/glslang/glslang.wasm', import.meta.url).href,
},
twgslOptions: {
jsPath: new URL('./config/twgsl/twgsl.js', import.meta.url).href,
wasmPath: new URL('./config/twgsl/twgsl.wasm', import.meta.url).href,
},
})
await engine.initAsync()
}
else {
engine = new Engine(cvs, true, options)
}
scene = new Scene(engine)
return {
engine,
scene,
}
}
上面这段代码已经没有警告和报错,可以正常使用
过程中遇到问题
1. Failed to execute 'compile' on 'WebAssembly': Incorrect response MIME type.
一开始没有选择本地引入glslangOptions和twgslOptions,Babylon默认本地没有配置的话是从他官网的cdn服务器拿的(这里我觉得是Babylon的cdn服务器有点问题),一直报上面的警告。
2. 换本地glslangOptions和twgslOptions
相关js和wasm文件下载地址。下载
然后按照上面的方法配置即可
主要在vite中必须使用 new URL来引入静态的资源,Tools.ScriptBaseUrl也必须用new URL来设置 或者可以把下载的文件放到
public目录下(我觉得也可以,没尝试)
下载下来的压缩包很大,按照他的目录结构把需要的文件拿出来就行了。
我的目录结构:
部署后服务器需要添加MIME类型来支持wasm(如果本来就有则不需要)
nginx
在 Nginx 中,编辑你的 Nginx 配置文件通常位于 /etc/nginx/nginx.conf 或者是站点特定的配置文件,并添加如下行到 http 或者 server 或者 location 块中:
types {
application/wasm wasm;
}
node
如果你使用的是 Node.js 并且通过 Express 进行服务,可以使用 express.static.mime 来定义 MIME 类型:
const express = require('express');
const app = express();
express.static.mime.define({'application/wasm': ['wasm']});
app.use('/', express.static('public'));
app.listen(3000, () => console.log('App listening on port 3000!'));