【问题标题】:Setting the values of a struct array from JS to GLSL将结构数组的值从 JS 设置为 GLSL
【发布时间】:2011-11-26 18:51:40
【问题描述】:

我一直在尝试创建一个包含我的 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

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

是否有正确执行此操作的标准或推荐方法?任何人都可以启发我吗?

【问题讨论】:

    标签: javascript glsl webgl


    【解决方案1】:

    你做得对。你可以试着把它收紧一点

    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;
    }
    

    【讨论】:

    • 现在我正在使用“eval”函数来实现它,但我会尝试这两种实现并查看最快的一种。我必须说你的看起来很干净!谢谢!
    猜你喜欢
    • 2013-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    相关资源
    最近更新 更多