Can fog be applied from a fixed location within a three.js scene without being tied to the camera's position?

Is it feasible to render fog in such a way that an avatar on a terrain remains clear while the surrounding area gradually fades into the mist, especially when the camera is positioned overhead at a distance?

Answer №1

Yes, it seems that creating your own shader is necessary instead of using the ones provided with three.js. While there might be a way to customize them for this purpose, I am not personally familiar with that method.

If you are interested in implementing fog based on the distance from the camera, you can refer to this answer. The approach involves passing the camera position to the shader as a uniform, calculating the distance from the camera to each vertex in the vertex shader, and then using that distance to determine the fog effect in the fragment shader. An example of this technique can be found in this sample code from the OpenGL ES 2.0 Programming guide.

To modify the shader to be based on the distance from a character instead of the camera, you simply need to replace the camera position uniform with the character position uniform in the calculation. Additionally, you may need to adjust variable names accordingly in the shader code.

Here is an example snippet of a vertex shader for achieving this effect:

uniform mat4 matViewProjection;
uniform mat4 matView;
uniform vec4 u_characterPos;

attribute vec4 rm_Vertex;
attribute vec2 rm_TexCoord0;

varying vec2 v_texCoord;
varying float v_characterDist;

void main() {
  vec4 vViewPos = matView * rm_Vertex;

  v_characterDist = length(vViewPos - u_characterPos);

  gl_Position = matViewProjection * rm_Vertex;
  v_texCoord = rm_TexCoord0.xy;
}

And here is a fragment shader snippet for incorporating linear fog based on the character distance:

precision mediump float;

uniform vec4 u_fogColor;
uniform float u_fogMaxDist;
uniform float u_fogMinDist;
uniform sampler2D baseMap;

varying vec2 v_texCoord;
varying float v_characterDist;

float computeLinearFogFactor() {
  float factor;

  factor = (u_fogMaxDist - v_characterDist) / (u_fogMaxDist - u_fogMinDist);

  factor = clamp(factor, 0.0, 1.0);

  return factor;
}

void main() {
  float fogFactor = computeLinearFogFactor();
  vec4 fogColor = fogFactor * u_fogColor;
  vec4 baseColor = texture2D(baseMap, v_texCoord);

  gl_FragColor = baseColor * fogFactor + fogColor * (1.0 - fogFactor);
}

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

Struggling with JavaScript's getElementById function

If anyone has any suggestions or alternative methods, please kindly assist me. I currently have: 1 Textbox 1 Label 1 LinkButton Upon clicking the lnk_NameEdit button, the txtUserName textbox should become visible while the lblusername label should becom ...

Retrieve pairs of items from a given variable

Containing values in my 'getDuplicates' variable look like this: getDuplicates = 100,120,450,490,600,650, ... These represent pairs and ranges: Abegin,Aend,Bbegin,Bend My task is to loop through them in order to apply these ranges. var ge ...

Can someone please explain how to use the prevState in REACT?

Can you explain the difference between how to define the counterHandler function in these two examples? counterHandler = () => { this.setState(() => { return { times: this.state.times + 1 } }); } versus counterHandle ...

There seems to be a connection issue between my Jquery and HTML, as they

I've hit a roadblock because my jQuery isn't connecting and I can't seem to figure out why. It's been stumping me for hours. Here is the HTML code snippet from exercise6.html: <!DOCTYPE html> <html lang="en> <h ...

Limit the velocity of an object in Box2D using JavaScript

In my Box2D simulation, a collection of dynamic objects is experiencing various random forces. Is there a way to set a maximum speed for each object (both translational and rotational)? I considered implementing a workaround, but I'm curious if the e ...

Conceal the title attribute when hovering over a link using javascript/jquery

I have implemented the title attribute for all my links, but I want it to be hidden during mouse hover while still accessible to screen readers. var linkElements = document.getElementsByTagName('a'); for (var index = 0; index < linkElements. ...

A guide to retrieving the timezone based on a specific address using the Google API

I need to utilize the Google API time zones, which requires geocoding the address to obtain the latitude and longitude for the time zone. How can I achieve this using a value from a textarea? Here are the 2 steps: Convert the textarea value into a geoc ...

Finding the number of parameters in an anonymous function while using strict mode can be achieved through which method?

Is it possible to determine the arity of a function, such as the methods.myfunc function, when using apply() to define the scope of this and applying arguments? Following the jQuery plugin pattern, how can this be achieved? (function($, window, document ){ ...

Struggling with dynamically updating fields based on user input in real time

I have a goal to update a field based on the inputs of two other fields. Currently, all the fields are manual input. Below is the code I'm using to try and make the "passThru" field update in real-time as data is entered into the other fields. The ma ...

Tips for showcasing elements individually in JavaScript when a button is clicked and halting on a random element

I have some names stored in h3 tags. I want to highlight one name at a time when I click a button, stopping at a random name. <div class="all-names"> <h3 class="name-one"><span class="line">Name ...

Struggling to implement .indexOf() in conjunction with .filter()

Hello, I'm new to JavaScript and ES6. Currently, I am working on a react-native app that utilizes Firebase and Redux. One of my action creators acts as a search bar function to fetch data from Firebase. Here's the code I have so far: export cons ...

Optimizing Angular for requireJS deletion

We recently developed an Angular directive that utilizes blueimp-fileupload. Everything seems to be working fine until we decided to optimize our code using requireJs. After running the optimizer, we encountered the following error: Error: cannot call m ...

React Native app experiences a start-up crash caused by SoLoader problem

I'm encountering a problem with my Android app (iOS is working fine). Every time I build it, the application closes before launching. I've tried various solutions found on Github and here, but haven't been able to resolve it yet. The instal ...

Utilizing React-Router-Redux alongside the powerful features of React-Bootstrap

I've been struggling with this issue for some time now! My goal is to create a 'main app container' that consistently displays the logo, navigation... I plan on using react-bootstrap to enhance its appearance. Currently, I'm encounter ...

Retrieving information from an API and transferring it to the state in a React component

I am currently working on a random quote generator project, and I'm facing some difficulties in passing the API data to my state and also accessing it in the QuoteComponent through props. Despite following all the correct procedures, whenever I try to ...

Are XHR2 credential requests truly secure or easily faked?

I am working to determine the level of security provided by credentialed XHR2 requests. More precisely, can I verify that the request originated from a browser runtime environment, and not from a bot (such as a server-side program) that might be able to m ...

Purchasing a Checkbox alongside its corresponding label

I have been working with the Oracle CPQ tool and am faced with the challenge of creating a checkbox attribute within it. Upon inspecting the UI, I came across the following: https://i.sstatic.net/xE5aH.png Upon examining the browser source code (generat ...

StyledTab element unable to receive To or component attributes

Is there a way to use tabs as links within a styled tab component? I've tried using the Tab component syntax with links, but it doesn't seem to work in this scenario: <Tab value="..." component={Link} to="/"> If I have ...

Is there an issue with loading Vue list rendering due to Axios not returning the data?

Utilize the axios request api interface to fetch data and populate a list, but encounter a problem when trying to iterate through the properties of an object using v-for. Take a look at the javascript snippet below: var vm = new Vue({ el: '# ...

Unable to access the property 'vertexNormals' of an undefined object

I am currently facing an issue while attempting to load a .obj file with a .mtl using the example code provided on the three.js documentation page. The error message I keep encountering is 'cannot read property 'vertexNormals' of undefined.& ...