从JS到GLSL设置结构数组的值 [英] Setting the values of a struct array from JS to GLSL

查看:141
本文介绍了从JS到GLSL设置结构数组的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试构建一个包含我的WebGL应用程序所有功能的结构,并且在从JS设置它的值时遇到了麻烦.结构如下:

I've been trying to make a structure that will contain all the lights of my WebGL app, and I'm having troubles setting up it's values from JS. The structure is as follows:

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

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

After testing LOTS of things I made it work but I'm not happy with the code I wrote:

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

很抱歉让您看这段代码,我知道这很可怕,但是我找不到更好的方法.

I'm sorry for making you look at this code, I know it's horrible but I can't find a better way.

是否有标准或推荐的方法可以正确地做到这一点?谁能启发我?

Is there a standard or recommended way of doing this properly? Can anyone enlighten me?

推荐答案

您做对了.您可以尝试像在

You're doing it right. You could try to tighten it up a bit as in

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

这篇关于从JS到GLSL设置结构数组的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆