我决定学习 Dart,为此我的项目将是一个小型 webgl 游戏。
使用带有 aysnc 操作和 futures 的单线程对我来说是新的,虽然我理解这些概念,但我发现要知道如何使用它们有点困难。
在我的游戏中,我想加载一个 webgl GLSL 程序。要创建这个程序,我首先必须从文件中加载一个顶点着色器和一个片段着色器。所以我写了这个似乎可以正常加载和编译着色器。
我遇到的问题是我如何知道何时加载了两个着色器,以便我可以从两个加载的着色器创建“程序”对象。就像我以后可以使用 .then 从 HttpRequest.getString 返回一样,我需要以某种方式做同样的事情,并有一个 .then 在加载片段和顶点着色器时运行。
我确定我在这里遗漏了一些重要且简单的东西,但这对我来说是新的,我正在努力了解如何使用它。 (这很好,学习新东西很好!)
//
// Start the process of loading the shaders.
//
void initShaders()
{
Shader vs = gl.createShader(VERTEX_SHADER);
Shader fs = gl.createShader(FRAGMENT_SHADER);
var vsFuture = HttpRequest.getString('basic.vert');
var fsFuture = HttpRequest.getString('basic.frag');
//
// When we have the vertex shader source, compile it
//
vsFuture.then((src) {
gl.shaderSource(vs, src);
gl.compileShader(vs);
if (!gl.getShaderParameter(vs, COMPILE_STATUS)) {
throw new Exception(gl.getShaderInfoLog(vs));
}
print ('Vertex shader compiled');
});
//
// When we have the fragment shader source, compile it
//
fsFuture.then((src) {
gl.shaderSource(fs, src);
gl.compileShader(fs);
if (!gl.getShaderParameter(fs, COMPILE_STATUS)) {
throw new Exception(gl.getShaderInfoLog(fs));
}
print ('Fragment shader compiled');
});
//
// When both the fragment shader and the vertex shader are
// compiled, we need to link them. But how do we know??
//
***something... to make this be called when both the vertex and
fragment shaders are compiled...***
{
program = gl.createProgram();
gl.attachShader(program, fs);
gl.attachShader(program, ps);
gl.linkProgram(program);
}
最佳答案
所有对 then
的调用都会返回一个 Future
,它会在执行 then 回调后触发。所以你在编译步骤中有两个 future 。之后你可以使用 Future.wait
等待一份 future list 。 wait
函数返回一个 Future
,在所有输入 futures 完成后触发。
像这样的(不完整,但了解它是如何工作的):
var vsCompiledFuture = vsFuture.then((src) {
// Compile
});
var fsCompiledFuture = fsFuture.then((src) {
// Compile
});
Future.wait([vsCompiledFuture, fsCompiledFuture]).then((_) {
// Link here...
});
如果您从 future 的回调中返回已编译的着色器,Future.wait
回调会收到一个列表,其中包含来自所有 future 的所有结果。
关于webgl - 使用 future 进行异步加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20813354/