简体   繁体   中英

How can I make this spherical gradient in an OpenGL fragment shader?

I'm new to OpenGL. I'd like my background to look as if the player is inside the sphere pictured below. White as the player looks up, black as the player looks down, and a gradient along the way.

I tried enclosing the camera in a diamond shaped prism and assigning white to the top vertex, gray to middles, and black to the bottom. But the seams of the triangles are very apparent, which I don't totally understand why. It seems overkill to make more vertices to better approximate a sphere. I feel like I should be able to do this all in the fragment shader, but don't know enough to implement it. I can pass the camera's y direction [-1,1] as a uniform to the shader.

How can I implement this?

球体渐变

Solution A: Add more triangles. This way they will be less noticeable. Modern GPUs can render 3 or 3000 triangles just as easily in your case.

Solution B: Apply a texture with a gradient to your "diamond shaped prism"

Solution C: Write a custom fragment shader which will assign pixel color depending on vertical location

why not use y coordinate as color intensity instead of texture...

  • in Players coordinate system it looks like this:
  • 概观
  • so let (0,0,0) be the players position (center of sphere)
  • let r be the radius of sphere
  • So in Fragment shader compute the color like this:

     float i=0.5f+(0.5f*y/r); if (i>1.0f) i=1.0f; // white for out of sphere fragments if (i<0.0f) i=1.0f; // here you could have 0.0 if triangles are outer not inner vec3 col; col=vec3(i,i,i); 
  • do not forget that tis works only localy in Players coordinate system

Now how to get rid of the triangulation artifacts?

  • normalize the fragment coordinates before applying the above
  • so let vec3 p be the rendered fragment position in player coordinate system
  • you are rendering surface of the sphere so the distance from (0,0,0) should be r
  • so normalize the p to it
  • p.xyz*=r/length(p);
  • and now use py

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM