javascript - 如何在 WebGl 中使用漫射照明进行 Gouraud 着色?

标签 javascript opengl glsl webgl shading

我坚持实现 Gouraud 平滑着色。我遗漏了一些东西,我需要帮助。

首先是漫射照明。为了获得漫射光,我使用了这个公式:

Id * Kd * max( dot(N,L), 0.0)

我应该得到我的漫反射颜色,我会将它添加到我的环境颜色中。

下一个阴影。 Gouraud 着色是逐顶点着色。 我在这个 lectures 中找到了 Gouraud 着色算法

据我了解这个算法:

  1. 确定每个多边形顶点的法线
vec3 N = mat3(normalMatrix) * normals;
  1. 对每个顶点应用光照模型 计算顶点强度
float labertian = max(dot(N, L), 0.0);
vec4 color = vec4(intensityAmbientColor * ambientColor
                 + intensityDiffuseColor * diffuseColor * labertian, 1.0);
  1. 对顶点强度进行线性插值 表面多边形
v_color = color;

这是输出图像

output image

我在这里错过了什么? 顶点着色器:

attribute vec3 coordinates;
attribute vec3 normals;

/** MVP */
uniform mat4 modelMatrix;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 normalMatrix;
// uniform mat4 viewModelMatrixl

/** LIGHT */
uniform vec3 ambientColor;
uniform float intensityAmbientColor;

uniform vec3 diffuseColor;
uniform float intensityDiffuseColor;

uniform vec3 cameraCoordinates;
uniform vec3 lightCoordinates;

varying vec4 v_color;

void main() {

  gl_Position = projectionMatrix *
    viewMatrix *
    modelMatrix *
    vec4(coordinates, 1.0);

  vec3 surfaceWorldPosition = (
    viewMatrix
    * modelMatrix
    * vec4(coordinates, 1.0)
  ).xyz;

  vec3 L = lightCoordinates - surfaceWorldPosition;
  vec3 V = cameraCoordinates - surfaceWorldPosition;
  vec3 N = mat3(normalMatrix) * normals;

  float labertian = max(dot(N, L), 0.0);
  v_color = vec4(intensityAmbientColor * ambientColor
                 + intensityDiffuseColor * diffuseColor * labertian, 1.0);
}

片段着色器:

precision mediump float;

varying vec4 v_color;

void main() {
  gl_FragColor = v_color;
}

最佳答案

Gouraud 着色只不过是平均你的顶点法线,通常这是网格导入器/导出器/转换器的一部分,你可以手动完成,但是如果你的网格没有索引,你需要先重新索引它才能找到共享顶点,然后对它们之间的法线进行平均。现在您似乎渲染了一个未索引的网格,其中每个顶点相对于一个面都是唯一的。

An estimate to the surface normal of each vertex in a polygonal 3D model is either specified for each vertex or found by averaging the surface normals of the polygons that meet at each vertex.

https://en.wikipedia.org/wiki/Gouraud_shading

关于javascript - 如何在 WebGl 中使用漫射照明进行 Gouraud 着色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55634273/

相关文章:

glsl - Vulkan GLSL 中 block 名称有什么用?

javascript - 检查 JSON 中是否存在值

javascript - 光标未使用 HTML Canvas 对齐

opengl - 构建后如何运行 Android 模拟器?

c++ - 当提供轴和四元数时,如何使用 GLM 获得角度?

c - OpenGL 着色器编译代码位于何处?

c++ - 如何使用 OpenGL 渲染到多个纹理?

opengl - 如何获得自动唯一的原子计数器绑定(bind)点(无硬编码绑定(bind)=)?

javascript - 等待 Javascript 函数在 foreach cshtml 中完成?

java - 从 Java 调用网页上的 Javascript