javascript - 将结构数组的值从 JS 设置为 GLSL

标签 javascript glsl webgl

我一直在尝试创建一个结构来包含我的 WebGL 应用程序的所有灯光,但我在从 JS 设置它的值时遇到了麻烦。结构如下:

struct Light {
    vec4 position;
    vec4 ambient;
    vec4 diffuse;
    vec4 specular;
    vec3 spotDirection;
    float spotCutOff;
    float constantAttenuation;
    float linearAttenuation;
    float quadraticAttenuation;
    float spotExponent;
    float spotLightCosCutOff;
};
uniform Light lights[numLights];

在测试了很多东西之后我让它工作了但是我对我写的代码不满意:

program.uniform.lights = []; 
    program.uniform.lights.push({
        position: "",
        diffuse: "",
        specular: "",
        ambient: "",
        spotDirection: "",
        spotCutOff: "",
        constantAttenuation: "",
        linearAttenuation: "",
        quadraticAttenuation: "",
        spotExponent: "",
        spotLightCosCutOff: ""         
    });


            program.uniform.lights[0].position = gl.getUniformLocation(program, "lights[0].position");
            program.uniform.lights[0].diffuse = gl.getUniformLocation(program, "lights[0].diffuse");
            program.uniform.lights[0].specular = gl.getUniformLocation(program, "lights[0].specular");
            program.uniform.lights[0].ambient = gl.getUniformLocation(program, "lights[0].ambient");

    ... and so on

很抱歉让您看到这段代码,我知道这很糟糕,但我找不到更好的方法。

是否有正确执行此操作的标准或推荐方法?谁能启发我?

最佳答案

你做得对。你可以试着把它收紧一点,就像在

lightLocations = [
  "position",
  "diffuse",
  "specular",
  "ambient",
  "spotDirection",
  "spotCutOff",
  "constantAttenuation",
  "linearAttenuation",
  "quadraticAttenuation",
  "spotExponent",
  "spotLightCosCutOff",
];

var program = {
  uniform: {
    lights: [];
  }
};

for (var ll = 0; ll < numLights; ++ll) {
  var locations = { };
  for (var jj = 0; jj < lightLocations.length; ++jj) {
    var name = lightLocaitons[jj];
    locations = gl.getUniformLocation(program, "lights[" + ll + "]." + name);
  }
  program.uniform.lights[ll] = locations;
}

关于javascript - 将结构数组的值从 JS 设置为 GLSL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8202173/

相关文章:

javascript - 如何在 GWT/Javascript 中解析/规范化 URL?

javascript - 使函数根据 AJAX 响应返回 false

java - Android 版 OpenGL ES 2.0 中的纹理

glsl - WebGL - 有没有在 HTML 中嵌入着色器的替代方法?

javascript - 在html中使用for时函数调用两次

Javascript : Get the HTMLAudioElement currently playing

c++ - GLSL 计算着色器不适用于大输入

c++ - 为什么 glDrawElements 给我 GL_OUT_OF_MEMORY?

webgl - 使用 puppeteer 截取运行 WebGL 的页面的屏幕截图

rendering - Three.js - 使用延迟渲染向区域光添加阴影