Left-Hand-Side Of Assignment Must Not Be Read-Only Os

 

This tutorial is based on the directional lights tutorial as most of the code comes from there. The tutorial is based on the difference between a directional light and a point light. A directional light is assumed to be infinitely far away, so that the light rays are parallel when they reach the object. In contrast, a point light has a position, and sends rays in all directions. Furthermore, in a point light, the intensity decays with the distance to the vertex.

From an OpenGL application point of view there are two differences between the two:

  • the w component of the light position field: in a directional light it is zero to indicate that the position is in fact a direction (or vector), where as in a point light the w component of the light position field is 1.
  • The attenuation is specified based on three coefficients: a constant term, a linear term, and a quadratic term

From a computational point of view these differences must be taken care of. For a directional light, the direction of the light rays is constant for every vertex, whereas for a point light it is the vector from the vertex to the lights position. Hence, all that needs to change in the vertex shader is the computation of the lights direction.

The attenuation is computed based on the following formula in OpenGL:

where k0 is the constant attenuation, k1 is the linear attenuation, k2 is the quadratic attenuation and d is the distance from the light’s position to the vertex.

Note that the attenuation does not vary linearly with distance, hence we can’t compute the attenuation per vertex and use the interpolated value in the fragment shader. We can however compute the distance in the vertex shader and use the interpolated distance in the fragment shader to compute the attenuation.

The equation for the color using a point light is:


As shown in the above equation, the ambient term must be spitted in two: one global ambient term using the lighting model ambient setting and a light specific ambient term. The vertex shader must separate the computation of the ambient term accordingly. The new vertex shader is:

varying vec4 diffuse,ambientGlobal,ambient, ecPos; varying vec3 normal,halfVector; void main() { vec3 aux; /* first transform the normal into eye space and normalize the result */ normal = normalize(gl_NormalMatrix * gl_Normal); /* compute the vertex position in camera space. */ ecPos = gl_ModelViewMatrix * gl_Vertex; /* Normalize the halfVector to pass it to the fragment shader */ halfVector = gl_LightSource[0].halfVector.xyz; /* Compute the diffuse, ambient and globalAmbient terms */ diffuse = gl_FrontMaterial.diffuse * gl_LightSource[0].diffuse; ambient = gl_FrontMaterial.ambient * gl_LightSource[0].ambient; ambientGlobal = gl_LightModel.ambient * gl_FrontMaterial.ambient; gl_Position = ftransform(); }

The fragment shader needs to compute the attenuation.

varying vec4 diffuse,ambientGlobal, ambient, ecPos; varying vec3 normal,halfVector; void main() { vec3 n,halfV,viewV,lightDir; float NdotL,NdotHV; vec4 color = ambientGlobal; float att, dist; /* a fragment shader can't write a verying variable, hence we need a new variable to store the normalized interpolated normal */ n = normalize(normal); // Compute the ligt direction lightDir = vec3(gl_LightSource[0].position-ecPos); /* compute the distance to the light source to a varying variable*/ dist = length(lightDir); /* compute the dot product between normal and ldir */ NdotL = max(dot(n,normalize(lightDir)),0.0); if (NdotL > 0.0) { att = 1.0 / (gl_LightSource[0].constantAttenuation + gl_LightSource[0].linearAttenuation * dist + gl_LightSource[0].quadraticAttenuation * dist * dist); color += att * (diffuse * NdotL + ambient); halfV = normalize(halfVector); NdotHV = max(dot(n,halfV),0.0); color += att * gl_FrontMaterial.specular * gl_LightSource[0].specular * pow(NdotHV,gl_FrontMaterial.shininess); } gl_FragColor = color; }

The following images show the difference between a point light as computed by the fixed functionality, i.e. per vertex, and using the shader in this tutorial, i.e. per pixel.

Fixed FunctionalityPer Pixel

 

 

JavaScript Errors and How to Fix Them

JavaScript can be a nightmare to debug: Some errors it gives can be very difficult to understand at first, and the line numbers given aren’t always helpful either. Wouldn’t it be useful to have a list where you could look to find out what they mean and how to fix them? Here you go!

Below is a list of the strange errors in JavaScript. Different browsers can give you different messages for the same error, so there are several different examples where applicable.

How to read errors?

Before the list, let’s quickly look at the structure of an error message. Understanding the structure helps understand the errors, and you’ll have less trouble if you run into any errors not listed here.

A typical error from Chrome looks like this:

Uncaught TypeError: undefined is not a function

The structure of the error is as follows:

  1. Uncaught TypeError: This part of the message is usually not very useful. Uncaught means the error was not caught in a statement, and is the error’s name.
  2. undefined is not a function: This is the message part. With error messages, you have to read them very literally. For example in this case it literally means that the code attempted to use like it was a function.

Other webkit-based browsers, like Safari, give errors in a similar format to Chrome. Errors from Firefox are similar, but do not always include the first part, and recent versions of Internet Explorer also give simpler errors than Chrome – but in this case, simpler does not always mean better.

Now onto the actual errors.

Uncaught TypeError: undefined is not a function

Related errors: number is not a function, object is not a function, string is not a function, Unhandled Error: ‘foo’ is not a function, Function Expected

Occurs when attempting to call a value like a function, where the value is not a function. For example:

var foo = undefined; foo();

This error typically occurs if you are trying to call a function in an object, but you typed the name wrong.

var x = document.getElementByID('foo');

Since object properties that don’t exist are by default, the above would result in this error.

The other variations such as “number is not a function” occur when attempting to call a number like it was a function.

How to fix this error: Ensure the function name is correct. With this error, the line number will usually point at the correct location.

Uncaught ReferenceError: Invalid left-hand side in assignment

Related errors: Uncaught exception: ReferenceError: Cannot assign to ‘functionCall()’, Uncaught exception: ReferenceError: Cannot assign to ‘this’

Caused by attempting to assign a value to something that cannot be assigned to.

The most common example of this error is with if-clauses:

if(doSomething() = 'somevalue')

In this example, the programmer accidentally used a single equals instead of two. The message “left-hand side in assignment” is referring to the part on the left side of the equals sign, so like you can see in the above example, the left-hand side contains something you can’t assign to, leading to the error.

How to fix this error: Make sure you’re not attempting to assign values to function results or to the keyword.

Uncaught TypeError: Converting circular structure to JSON

Related errors: Uncaught exception: TypeError: JSON.stringify: Not an acyclic Object, TypeError: cyclic object value, Circular reference in value argument not supported

Always caused by a circular reference in an object, which is then passed into .

var a = { }; var b = { a: a }; a.b = b; JSON.stringify(a);

Because both and in the above example have a reference to each other, the resulting object cannot be converted into JSON.

How to fix this error: Remove circular references like in the example from any objects you want to convert into JSON.

Unexpected token ;

Related errors: Expected ), missing ) after argument list

The JavaScript interpreter expected something, but it wasn’t there. Typically caused by mismatched parentheses or brackets.

The token in this error can vary – it might say “Unexpected token ]” or “Expected {” etc.

How to fix this error: Sometimes the line number with this error doesn’t point to the correct place, making it difficult to fix.

  • An error with [ ] { } ( ) is usually caused by a mismatching pair. Check that all your parentheses and brackets have a matching pair. In this case, line number will often point to something else than the problem character
  • Unexpected / is related to regular expressions. The line number for this will usually be correct.
  • Unexpected ; is usually caused by having a ; inside an object or array literal, or within the argument list of a function call. The line number will usually be correct for this case as well

Uncaught SyntaxError: Unexpected token ILLEGAL

Related errors: Unterminated String Literal, Invalid Line Terminator

A string literal is missing the closing quote.

How to fix this error: Ensure all strings have the correct closing quote.

Uncaught TypeError: Cannot read property ‘foo’ of null, Uncaught TypeError: Cannot read property ‘foo’ of undefined

Related errors: TypeError: someVal is null, Unable to get property ‘foo’ of undefined or null reference

Attempting to read or as if it was an object. For example:

var someVal = null; console.log(someVal.foo);

How to fix this error: Usually caused by typos. Check that the variables used near the line number pointed by the error are correctly named.

Uncaught TypeError: Cannot set property ‘foo’ of null, Uncaught TypeError: Cannot set property ‘foo’ of undefined

Related errors: TypeError: someVal is undefined, Unable to set property ‘foo’ of undefined or null reference

Attempting to write or as if it was an object. For example:

var someVal = null; someVal.foo = 1;

How to fix this error: This too is usually caused by typos. Check the variable names near the line the error points to.

Uncaught RangeError: Maximum call stack size exceeded

Related errors: Uncaught exception: RangeError: Maximum recursion depth exceeded, too much recursion, Stack overflow

Usually caused by a bug in program logic, causing infinite recursive function calls.

How to fix this error: Check recursive functions for bugs that could cause them to keep recursing forever.

Uncaught URIError: URI malformed

Related errors: URIError: malformed URI sequence

Caused by an invalid decodeURIComponent call.

How to fix this error: Check that the call at the error’s line number gets correct input.

XMLHttpRequest cannot load http://some/url/. No ‘Access-Control-Allow-Origin’ header is present on the requested resource

Related errors: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://some/url/

This error is always caused by the usage of XMLHttpRequest.

How to fix this error: Ensure the request URL is correct and it respects the same-origin policy. A good way to find the offending code is to look at the URL in the error message and find it from your code.

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

Related errors: InvalidStateError, DOMException code 11

Means the code called a function that you should not call at the current state. Occurs usually with , when attempting to call functions on it before it’s ready.

var xhr = new XMLHttpRequest(); xhr.setRequestHeader('Some-Header', 'val');

In this case, you would get the error because the function can only be called after calling .

How to fix this error: Look at the code on the line pointed by the error and make sure it runs at the correct time, or add any necessary calls before it (such as )

Conclusion

JavaScript has some of the most unhelpful errors I’ve seen, with the exception of the notorious in PHP. With more familiarity the errors start to make more sense. Modern browsers also help, as they no longer give the completely useless errors they used to.

What’s the most confusing error you’ve seen? Share the frustration in the comments!

Want to learn more about these errors and how to prevent them? Detect Problems in JavaScript Automatically with ESLint.

About Jani Hartikainen

Jani Hartikainen has spent over 10 years building web applications. His clients include companies like Nokia and hot super secret startups. When not programming or playing games, Jani writes about JavaScript and high quality code on his site.

codeutopia.netjhartikainenPosts

Categories: 1

0 Replies to “Left-Hand-Side Of Assignment Must Not Be Read-Only Os”

Leave a comment

L'indirizzo email non verrĂ  pubblicato. I campi obbligatori sono contrassegnati *