three.js,glsl,webgl , Atmosphere Scattering for Earth from space and on the ground


Atmosphere Scattering for Earth from space and on the ground

Question:

Tag: three.js,glsl,webgl

Please provide prompt how to make the atmosphere of the Earth so that it is visible from space and from the ground (as shown in the image)

a model of the earth:

Earth = new THREE.Mesh(new THREE.SphereGeometry(6700,32,32),ShaderMaterialEarth);

model of the cosmos:

 cosmos= new THREE.Mesh(new THREE.SphereGeometry(50000,32,32),ShaderMaterialCosmos);

and a light source:

sun = new THREE.DirectionalLight();

where to start, just I do not know. Perhaps this should do ShaderMaterialCosmos, where to pass position of the camera, and calculate how should be painted pixel. But how?

I tried using the following but get zero vectors at the entrance of the fragment shader http://http.developer.nvidia.com/GPUGems2/gpugems2_chapter16.html

vertexShader:

        #define M_PI 3.1415926535897932384626433832795 
        const float ESun=1.0; 
        const float Kr = 0.0025; 
        const float Km = 0.0015; 
        const int nSamples = 2; 
        const float fSamples = 1.0; 

        const float fScaleDepth = 0.25; 

        varying vec2 vUv; 
        varying vec3 wPosition; 
        varying vec4 c0; 
        varying vec4 c1; 
        varying vec3 t0; 

         uniform vec3 v3CameraPos; ,    // The camera's current position
         uniform vec3 v3LightDir;       // Direction vector to the light source
         uniform vec3 v3InvWavelength;  // 1 / pow(wavelength, 4) for RGB
         uniform float fCameraHeight;    // The camera's current height

         const float fOuterRadius=6500.0;     // The outer (atmosphere) radius
         const float fInnerRadius=6371.0;      // The inner (planetary) radius

         const float fKrESun=Kr*ESun;           // Kr * ESun
         const float fKmESun=Km*ESun;           // Km * ESun
         const float fKr4PI=Kr*4.0*M_PI;            // Kr * 4 * PI
         const float fKm4PI=Km*4.0*M_PI;           // Km * 4 * PI

         const float fScale=1.0/(fOuterRadius-fInnerRadius);            // 1 / (fOuterRadius - fInnerRadius)
         const float fScaleOverScaleDepth= fScale / fScaleDepth;  // fScale / fScaleDepth

    const float fInvScaleDepth=1.0/0.25; 

    float getNearIntersection(vec3 v3Pos, vec3 v3Ray, float fDistance2, float fRadius2) 
{ 
   float B = 2.0 * dot(v3Pos, v3Ray); 
   float C = fDistance2 - fRadius2; 
   float fDet = max(0.0, B*B - 4.0 * C); 
   return 0.5 * (-B - sqrt(fDet)); 
} 

    float scale(float fCos) 
{ 
    float x = 1.0 - fCos; 
    return fScaleDepth * exp(-0.00287 + x*(0.459 + x*(3.83 + x*(-6.80 + x*5.25)))); 
} 


void main() { 


// Get the ray from the camera to the vertex and its length (which

  // is the far point of the ray passing through the atmosphere)

  vec3 v3Pos = position.xyz; 
  vec3 v3Ray = v3Pos - v3CameraPos; 
  float fFar = length(v3Ray); 

  v3Ray /= fFar; 



  // Calculate the closest intersection of the ray with

  // the outer atmosphere (point A in Figure 16-3)


  float fNear = getNearIntersection(v3CameraPos, v3Ray, fCameraHeight*fCameraHeight, fOuterRadius*fOuterRadius); 

  // Calculate the ray's start and end positions in the atmosphere,

  // then calculate its scattering offset

  vec3 v3Start = v3CameraPos + v3Ray * fNear; 

  fFar -= fNear; 
  float fStartAngle = dot(v3Ray, v3Start) / fOuterRadius; 
  float fStartDepth = exp(-fInvScaleDepth); 
  float fStartOffset = fStartDepth * scale(fStartAngle); 


  // Initialize the scattering loop variables


  float fSampleLength = fFar / fSamples; 
  float fScaledLength = fSampleLength * fScale; 
  vec3 v3SampleRay = v3Ray * fSampleLength; 
  vec3 v3SamplePoint = v3Start + v3SampleRay * 0.5; 



  // Now loop through the sample points

  vec3 v3FrontColor = vec3(0.0, 0.0, 0.0); 
  for(int i=0; i<nSamples; i++) { 

    float fHeight = length(v3SamplePoint); 
    float fDepth = exp(fScaleOverScaleDepth * (fInnerRadius - fHeight)); 
    float fLightAngle = dot(v3LightDir, v3SamplePoint) / fHeight; 
    float fCameraAngle = dot(v3Ray, v3SamplePoint) / fHeight; 
    float fScatter = (fStartOffset + fDepth * (scale(fLightAngle) * scale(fCameraAngle))); 
    vec3 v3Attenuate = exp(-fScatter *  (v3InvWavelength * fKr4PI + fKm4PI)); 
    v3FrontColor += v3Attenuate * (fDepth * fScaledLength); 
    v3SamplePoint += v3SampleRay; 

  } 


 wPosition = (modelMatrix * vec4(position,1.0)).xyz; 

  c0.rgb = v3FrontColor * (v3InvWavelength * fKrESun); 
  c1.rgb = v3FrontColor * fKmESun; 
  t0 = v3CameraPos - v3Pos; 

  vUv = uv; 

        }

fragmentShader: 

    float getMiePhase(float fCos, float fCos2, float g, float g2){ 

   return 1.5 * ((1.0 - g2) / (2.0 + g2)) * (1.0 + fCos2) / pow(1.0 + g2 - 2.0*g*fCos, 1.5);    
} 

// Rayleigh phase function
float getRayleighPhase(float fCos2){ 

   //return 0.75 + 0.75 * fCos2;
   return 0.75 * (2.0 + 0.5 * fCos2); 

} 


    varying vec2 vUv; 
    varying vec3 wPosition; 
    varying vec4 c0; 
    varying vec4 c1; 
    varying vec3 t0; 

      uniform vec3 v3LightDir; 
      uniform float g; 
      uniform float g2; 

    void main() { 

      float fCos = dot(v3LightDir, t0) / length(t0); 

    float fCos2 = fCos * fCos; 
    gl_FragColor = getRayleighPhase(fCos2) * c0 +  getMiePhase(fCos, fCos2, g, g2) * c1; 
    gl_FragColor = c1; 
    }

enter image description here


Answer:

Chapter 16 of GPU Gem 2 has nice explanation and illustration for achieving your goal in real time.

Basically you need to perform ray casting through the atmosphere layer and evaluate the light scattering.


Related:


Three.js set face color


javascript,three.js
I want to set the color of a face but failed. If I use wireframe, the result seems to be correct. But if not, the face seems not to be rendered. var geo = new THREE.Geometry(); geo.vertices.push(new THREE.Vector3(1, 1, 0)); geo.vertices.push(new THREE.Vector3(1, 0, 0)); geo.vertices.push(new THREE.Vector3(0, 0, 0)); geo.faces.push(new THREE.Face3(0,...

Create a 2D texture from existing textures


three.js,textures,webgl,texture-atlas
I have an application where I load a series of medical images (jpg), create a texture object for each image and display those textures on 3D planes. The amount of images depends in the CT scanner's resolution but my prototype should work with up to 512. As an additional task,...

3D Lines disappear sometimes


javascript,d3.js,3d,three.js
I am building 3d line chart from data here is the code Demo the part of code that generate line is parentTransform = new THREE.Object3D(); var _color = d3.scale.category10(); for (var i = 5; i > 0; i--) { var material = new THREE.LineBasicMaterial({ // color: 0x0000ff,linewidth: 30 color: _color(i),...

How to create latitudinal (horizontal) contour lines in GLSL?


opengl,glsl,webgl
I'm aiming for this effect: (horizontal-only contour lines): I did find this example, however it creates horizontal and vertical contour lines. I can't quite wrap my head around how the call to fwidth() is generating the lines. uniform float gsize;//size of the grid uniform float gwidth;//grid lines'width in pixels varying...

Should Meshes with and without Skeleton use different Shaders?


c++,opengl,glsl,shader,vertex-shader
Should Meshes with and without Skeleton use different Shaders? Background: Right now my shader is constructed to handle meshes with skeletons. Each vertex takes 3 bone IDs, with respective bone weight. This works well for models with skeletons that I wish to animate, but I feel that it is a...

Javascript Three.js point camera at fixed coordinate


javascript,three.js
In Javascript THREE.js, given the coordinates of the camera and the coordinates of a point (x, y, z), how would I rotate the camera to look directly at the point?

ThreeJS LOD clone()


three.js
In threejs, LOD objects created with clone() method show all levels of details at once. If i have two LODs, named LOD1 & LOD2, if LOD2 is a clone of the first and that both are updated in the render loop, then LOD1 will behave as expected. But LOD2 will...

Javascript three.js smooth camera motion


javascript,three.js
In javascript, I can use the document.addEventListener('keydown', function(event){...}); to add a key listener. However, when using three.js and moving the camera with the key, the camera moves once, delays, and then continues moving. This is because the computer delays key holding for a fixed amount of time. How would I...

OpenGL GLSL: How to implement the concept of gradient map in photoshop using fragment shader?


image-processing,glsl,photoshop
This may be not the perfect question for stackoverflow but I have asked this in graphicdesign network of stackexchange but did not get any answer so posting it here. I am trying to implement gradient map of Photoshop programmatically using glsl fragment shader. Consider below shown gradient map where all...

How to make a skyBox with THREE.Js


javascript,three.js,skybox
I have looked a a number of different examples of skyboxes in three.js, however I can't get any of them to work in my three.js project. Here is what I have so far, with a skybox (which doesn't work). Can someone help me make a skybox or help fix my...

How can I render an infinite 2D grid in GLSL?


opengl,glsl
Ideally, what I'd like to do is draw a single quad and have GLSL handle the creation of the actual gridlines. In my attempt so far the vertex shader: #version 400 layout (location = 0) in vec4 in_position; layout (location = 2) in vec3 in_UV; uniform mat4 model; uniform mat4...

OpenGL: Defining variables in shaders


opengl,glsl
My OpenGL program, using GLSL for shaders, has a simple vertex and fragment shader (given by a tutorial). The vertex shader is: #version 330 layout (location = 0) in vec3 Position; void main() { gl_Position = vec4(0.5 * Position.x, 0.5 * Position.y, Position.z, 1.0); } And the fragment shader is:...

EdgesHelper loses its mesh when scene is rotated


three.js
I've drawn a mesh with a edgeshelper. When I rotate the scene using the mouse, the edges seems to react twice as fast the mesh. The result is that the edges don't "fit" around the mesh anymore when the scene is rotated. What am I doing wrong ? <html> <body...

Understand Vectors use


three.js
From my physics studies a vector is similar to an arrow, it has, in 3-dimensional space, 3 coordinates (x,y,z), a magnitude, a direction (cosines). In three.js you can define Vector3 just by 3 coordinates. Is in three.js a Vector3 object like a point in space?

Ambient and Specular lighting not working correctly in GLSL


opengl,glsl,lighting,phong
In my lighting scene, for some reason the ambient lighting isn't working at all. The whole model is the same brightness, no matter which way it is facing. I tried getting rid of the attenuation but it still has the same results. Along with that, the specular lighting is always...

three.js merge geometry and octree selection


merge,three.js,geometry,selection,octree
I am using Three.js to show a number of custom geometry's in various positions and rotations. They are static and rarely change, but the user can add, delete or change the shape of each individual object. This has worked well using the code snippet below: var Mat=new THREE.MeshBasicMaterial( { color:...

GLSL - program link error: Slot 0 unavailable from layout location request


c++,opengl,glsl
I'm trying to draw a textured quad copying some code from a tutorial but I'm afraid there is a problem with the shaders. Both the vertex shader and the fragment shader compilation works, but when linking the program I get the error: ERROR: Active attribute aliasing. Slot 0 unavailable for...

Error setting Color


javascript,three.js
I'm new with three.js. Basically I want to make something like a chessboard. I got this: for( x=-30; x<=50;x=x+10){ for( y=-30; y<=20;y=y+10 ){ var TileGeometry = new THREE.PlaneGeometry(5,5); var TileMaterial = new THREE.MeshBasicMaterial(); var Tile = new THREE.Mesh(TileGeometry,TileMaterial); //tile.receiveShadow = true Tile.rotation.x=-0.5*Math.PI; Tile.position.x = x; Tile.position.y = 0; Tile.position.z =...

How to get shader version from QOpenGLShader?


qt,opengl,glsl
I am using QT to load, compile and link OpenGL shaders. I need to perform specific operations depending on the GLSLversion used in the shader code Is it possible to recover the version from the QOpenGLShader interface without actually getting the shader source code and parsing it to detect the...

how to draw Highcharts in Three.js


javascript,three.js,html5-canvas
I am new to js, I want to draw 2d Highchart in Three.js on a face of the cube. I am able to draw a cube and post a image on that but however I am confused with highcharts.

Three.js: Switching between Cameras and Controls


javascript,three.js
I have a Three.js v72dev scene composed of objects imported through THREE.ObjectLoader. This works well. I am now importing cameras that are translated to Three.js cameras from my CAD package. I start to get issues when I move the camera with OrbitControls. With one camera, one does not notice the...

Updating a material's texture map with images rapidly (every 50ms or so) causes huge stuttering


javascript,three.js
Question: How should I update a sphere's material texture map with images (stored in a HTML5 canvas) very rapidly (50ms ~ 200ms interval) without the browser choking? I have a series of panoramic images to map onto a sphere. These images are updated every 50ms ~ 200ms. The code seems...

How much data does texImage2D in WebGL need?


javascript,three.js,webgl
I created a DataTexture in ThreeJS, which in turn will call texImage2D. var twidth = 50; var theight = 50; var tsize = twidth * theight; var tileData = new Uint8Array( tsize * 3); //fill it with some data tileDataTexture = new THREE.DataTexture(this.tileData, twidth, theight, THREE.RGBFormat); As you can see,...

How to draw a line on the diameter of a sphere in ThreeJs?


javascript,three.js
Suppose I've got a sphere like this: var geometry = new THREE.SphereGeometry( 1, 32, 32 ); window.sphere = new THREE.Mesh( geometry, material ); scene.add( window.sphere ); How would I then draw a line around the diameter of a sphere? Preferably parallel to the x axis. The end goal here is...

jQuery Dialog not working in three.js


javascript,jquery,three.js
jQuery dialog is not working while using in three.js. I'm trying to implement a click event on a Circle(using Circle Geometry) using jQuery. But it not supporting. Here is my code: function onDocumentMouseDown(event) { event.preventDefault(); var vector = new THREE.Vector3((event.clientX / window.innerWidth) * 2 - 1, -(event.clientY / window.innerHeight) *...

Load multiple OBJ-files together with multple textures


ajax,three.js,textures
Using the many examples on ThreeJS, I'm able to load multiple OBJ files into my scene. I'm also able to load multiple images as textures. However, the textures get assigned to the objects in 'order of appearance' and therefore, sometimes the wrong image gets assigned to the OBJ files. I...

Water rendering in opengl [duplicate]


opengl,glsl,shader
This question already has an answer here: How to render ocean wave using opengl in 3D? [closed] 2 answers I have absolutely no idea how to render water sources (ocean, lake, etc). It's like every tutorial I come across assumes I have the basic knowledge in this subject, and...

Passing grayscale OpenCV image to an OpenGL texture


c++,opencv,opengl,glsl
I want to use a grayscale image generated in OpenCV in a GLSL shader. Based on the question on OpenCV image loading for OpenGL Texture, I've managed to come up with the code that passes RGB image to the shader: cv::Mat image; // ...acquire and process image somehow... //create and...

Export ThreeJS Geometry to JSON


three.js,xml3d
I need to export Three Geometry to JSON so I can used with xml3D. I am trying to find the THREE.GeometryExporter() but I can't. Has it been completely deprecated? It is mentioned here Once I have the Three JSON I should be able to use this converter to obtain the...

Stripped shadows on collada objects


javascript,three.js,shadow,stripes,directional-light
I have a scene with two collada objects and a directional light. The first collada is pretty much a plane, and the second one is made of multiple boxes. It appears that when the scene is rendered, some "side" shadows are really stripped, although the shadows casted on ground are...

three.js transparent sphere glitch


three.js
I have a transparent sphere and a spot light and that's about it. My sphere displays visual glitches, like striations. see: http://jsfiddle.net/blwoodley/tvcogqkg/3/ (Note the grid is not necessary to manifest the bug. I just put it in there to show that transparency is working otherwise fine). Any thoughts on how...

How apply different materials to either sides of a plane in three.js?


three.js
I have created the simple triangle plane using materials = []; material1 = new THREE.MeshPhongMaterial( { color: 0xff00ff, specular: 0xff00ff, shininess: -3, shading: THREE.FlatShading, side: THREE.FrontSide } ); material2 = new THREE.MeshPhongMaterial( { color: 0xf0f0ff, specular: 0xf0f0ff, shininess: -3, shading: THREE.FlatShading, side: THREE.BackSide } ); materials.push(material1); materials.push(material2); mat = new...

Three js, block textures are blured


javascript,web,three.js
I'm trying to make a 3D block with the three.js library. I've done it. Now i wan't to put a texture on it. I did that and it's working : var textureHerbe = [ new THREE.MeshBasicMaterial({map:THREE.ImageUtils.loadTexture('img/texture/herbe/border.gif')}), new THREE.MeshBasicMaterial({map:THREE.ImageUtils.loadTexture('img/texture/herbe/border.gif')}), new THREE.MeshBasicMaterial({map:THREE.ImageUtils.loadTexture('img/texture/herbe/top.gif')}), new...

Artificial intelligence functionality in three.js


three.js
Does Three.JS have a function or capability of AI( Artificial intelligence )? Specifically let's say a FPS game. I want enemies to look for me and try to kill me, is it possible in three.js? Do they have a functionality or a system of such?

TypeError: this.mesh.geometry.area is not a function


javascript,three.js,leap-motion
I've working lately with JavaScript and Three.js with Leapmotion, and I started using the leap widgets (http://blog.leapmotion.com/leapjs-widgets-new-library-3d-web-design/here!) library to add some cool buttons to my program. After many hours, I got this type error from one of the libraries. Is it something mine? I just can't figure it out... TypeError:...

how to move an Object to other object position in THREE.JS?


javascript,three.js
What i want is to move an object to the position of another object. what i get from the internet is use TWEEN library but the problem is that i am not being able to add tween in my code help would be appreciated :) <script src="js/three.min.js"></script> <script src="js/OrbitControls.js"></script> <script...

Orbit camera lookAt change


javascript,camera,three.js
Is there any possibility to change the lookAt target of Orbit camera? I have it set for my 'static' camera, but when activating the orbit camera it always looks at (0,0,0)....

How to make the arc corners go out not in with a Three.js Shape


javascript,three.js,shapes
How to make all three corners ( created using shape.absarc) of the Three.js Shape go out and not in? See http://jsfiddle.net/theo/v7v4fu2v/ // Shape var radius = 10; var material = new THREE.MeshNormalMaterial(); pt1 = new THREE.Vector3(40, 50, 0); pt2 = new THREE.Vector3(-40, 0, 0); pt3 = new THREE.Vector3(30, -20, 0);...

Rotate the mergeometry object at its center in Three.js


javascript,three.js
I am struggling to find the way to rotate the object at its center. At the moment i am able to rotate the scene, but when i do the rotation, the object goes away from the user. I look into the some the already asked questions in the same line...

Centering three.js renderer.domElement (canvas) inside a parent div


css,three.js
I'm having difficulty understanding how to 'style' the output of a threejs renderer within an html div. For instance here is a simple scene: jsFiddle html: <div id="myPlanet"></div> css: body { background : #000; padding : 50px; margin : 0; } #myPlanet { width : 400px; min-height: 400px; margin :...

My .obj model is white even though I attached an .mtl file to it


three.js,.obj,dds-format
I'm working on three.js and I'm trying to import a .obj file with its corresponding mtl file. The textures the mtl file was referencing were .bmp so I tweaked the mtl file to point to all .dds files and converted all my assests to dds. Problem is that its just...

What does three.js's Matrix4.multiply() method do?


javascript,matrix,three.js,linear-algebra,matrix-multiplication
I'm learning three.js and am trying to multiply two translation matrices together to get a single matrix that describes both translations: | 1 0 0 -2 | | 1 0 0 3 | | 0 1 0 7 | * | 0 1 0 4 | | 0 0 1...

How to access all vertexes within the same patch in Tessellation Control Shader


opengl,glsl,tessellation
I want to do LOD in Tessenllation Control Shader. And my method is to calculate the area each patch occupyed on screen coordinate, and set different tessellation level for them. So I need to access all vertices within a patch and I do so like: for(int i = 0; i...

Convert autodesk .dwg and .dwf files to three.js json format


json,three.js,autodesk,dwg
I want to render 3D graphics files of autodesk (.dwg and .dwf) using three.js but three.js requires 3D data to be in json format. So, I need to convert these files to three.js readable json format. I tried searching on the internet but couldn't find any solution. Can anyone tell...

How can I render .mtl for object on iPhone 5 using ThreeJS?


javascript,ios,three.js,webgl,.obj
I am trying to load .obj files through ThreeJS and have it be cross compatible. I am using the OBJMTLLoader method. The object loads and renders fine for Firefox, Chrome, and IE on Windows; see falloutfan.com/eyebot for reference. On iPhone 5, I am able to see the object, but it...

Overlaying a transparent color over a Texture with GLSL


glsl,lwjgl,slick2d,vertex-shader,blending
I have an image that I am loading using the Slick library, and the image renders fine without my shader active. When I use my shader to overlay a transparent color over the image the entire image is replaced by the transparent color. without the shader With the shader Vertex...

Interactive Meshes in Three.js


javascript,three.js,mesh,interactive
I new to javascript and three.js so this is probably a noob question. BTW, I'm working on the example interactive/cubes/tween and I'm trying to modify it to test something else. At the moment the MouseDown event gives the tween effect to the intersected geometry, here's the function: function onDocumentMouseDown( event...

Modern GLSL ( opengl 3+ ) : Implementing phong effect correctly;


glsl,opengl-3
I am implementing a basic phong lighting GLSL shader; I have looked up some things on the internet, and found that the phong effect was created by adding an ambient, diffuse, and specular layer on the object (see image below, from tom dalling's site); problem is I have seen a...

Want to `return` more than once


javascript,three.js,return
I want to return multiple lines (one line each time the for-loop goes around), but it only returns the first line. I tried to write a function just to return the line, but I got errors with it because I don't know where to put it. What's a good way...

combining several iterations of same object in different location using .add() or .merge()


merge,three.js,geometry,rendering,mesh
I am trying to make a coil with several small loops. I have a custom function to create a single helix for each loop, and at first I was calling that within a for loop several hundred times, but it was taking too long to render and slowed down the...