Transferring data from a JavaScript struct array to GLSL

Struggling to configure the values of a structure containing all the lights in my WebGL app using JavaScript. The layout of 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];

Despite numerous attempts, I managed to make it work but I'm not pleased with the code quality:

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 apologize for making you review this messy code; I acknowledge its shortcomings but am struggling to find a cleaner solution.

Is there an industry standard or best practice for handling this situation more effectively? Could someone provide guidance on this matter?

Answer №1

Great job! You may want to consider optimizing it further by:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it an error to pass arguments using square brackets when requiring a node module?

Recently, I came across this piece of nodeJS code on a GitHub repository: var env = process.env.NODE_ENV || 'development' , config = require('./config/config')[env] , auth = require('./config/middlewares/authorization') , mon ...

Navigating the Angular Element: A Guide to Clicking Buttons within Modal-Dialogs Using Protractor

I am currently creating an automation test for an angular application using the protractor framework. Test scenario: Click on the "Create PDF Report" button A modal-dialog window will appear Click on the "Run Report Now" button within the modal-d ...

Is there a Facebook application embedded in the user's wall?

Is it feasible to create a website similar to YouTube, where users can share it on Facebook and run the app (in this case, the video player) directly on their wall without having to visit the YouTube page? If it is possible, is this functionality limited ...

Avoid triggering the parent modal to close when a child element is clicked in VueJS

In my Vue application, there is a situation where I have a button called "detach button" with a @click function inside an element that is clickable. When clicking on this parent element, it triggers another @click function and toggles a Bootstrap modal eve ...

Pedaling back and forth along a sequence

Is there a way to implement forward and backward buttons for a clickable list without using arrays, as the list will be expanding over time? I have already achieved changing color of the listed items to red, but need a solution to navigate through the list ...

The rendering of HTML DOM is being obstructed on iPhone devices running iOS 13

Currently, I'm developing a web-based URL stream music player using JavaScript. The player functions smoothly on Android devices, but I'm encountering an issue with DOM rendering being blocked on iPhone devices. Despite rearranging the JavaScript ...

Text aligned at the center of the Y and X axis

I am looking to center my content along the Y axis instead of only on the X axis. To prevent the page from expanding beyond its current size, I have applied the following CSS: html { overflow-y: hidden; overflow-x: hidden } What I want to achieve is havi ...

Navigating Sockets with Navigator in React Native

Every time I encounter the error message undefined is not an object (evaluating this.props.socket.on). In my code, I define the socket in the index.ios.js file as shown below: class Main extends Component { constructor(props) { super(props); ...

Ways to determine the specific content type within req.body?

Based on the information found at https://developer.mozilla.org/en-US/docs/Web/API/Request/Request, it is stated that the body of a request can be one of the following types: ArrayBuffer Blob formData JSON text I am wondering if there is a way ...

Error in Laravel Mix Vuejs component: Syntax problem detected in <template />

My development environment involves Windows 10 OS and I have created a Laravel 8 project integrated with VueJs. However, when I try to access the file ./components/app.vue, it returns a SyntaxError: Unexpected token (1:0) The content of the app.vue file i ...

Syntax for the expression used in the ng-click directive

I have two variables named wkidx and dyidx. My goal is to create multiple collapsible elements on the same page using the angular ui bootstrap directive. I am currently facing an issue with the following code snippet: <a href="" class="" ...

execute a rigorous compilation during the ng build angular process

I am currently working on a project using angular-cli and I have configured my package.json with the following scripts: "scripts": { "ng": "ng", "build": "ng build --base-href /test/", "prod": "ng build --prod --base-href /test/" } According to the ...

How to style the first dropdown value in AngularJS to appear bold?

Is there a way to style only the first value in a dropdown list as bold without using jQuery? Here is the code for the dropdown: <div class="col-xs-3"> <select-box id="ad-version-select" options="curItem.stats.version" model="state.version" i ...

Guide on Retrieving the Current URL in NodeJS

Currently, I am utilizing express in conjunction with node.js. In my setup, the following code is present: app.get('/callback', async function (req, res) { Whenever a user reaches the callback section of my website, I expect to receive the req ...

A React component created in a class cannot effectively update its state when using a functional component to pass

I'm currently working on a React project that involves both a Class component and a Functional Component. In my Class component, I have a function that updates the name in its state. The issue arises when I try to pass this function as a property to t ...

Storing the information filled out in the form and utilizing it to navigate to the correct destination URL

With the generous assistance and insightful advice from members of Stack Overflow, I am nearing completion of my quiz project. However, I do have a few lingering questions regarding some final touches needed for the project. Before delving into those quest ...

How can I identify the nearest ancestor based on a specific class in Angular 8?

In order to achieve a specific goal, let's imagine this scenario: Object A Object B Object C Object D Object D represents my angular component. It is important for me to adjust its height based on the heights of Object A and Object B. Regardle ...

Capture a screenshot of an embedded object and include it in an email using the mailto function

Is there a way to capture a screenshot of a flash object on a webpage and then send it via email using a mailto: form submission to a designated address? I have attempted to use different JavaScript techniques, but none seem to be successful. Appreciate a ...

Creating a modal window when a link is clicked in an MVC application

I am looking to open a Crystal Report in a pop-up window when a menu item is clicked. <%= Html.ActionLink("Display Name", "Action","Controller", new { target="blank"})%> The code above successfully opens the report, but it currently opens in a new ...

Exploring the functionality of JSON within the jQuery each method

I'm currently struggling with my JavaScript skills and attempting to piece this project together using various tutorials. However, I can't seem to identify why it's not functioning properly. Could someone guide me on how to properly pass an ...