第九章:环境光照

原文链接:


Tutorial 9: Ambient Lighting
第九章:环境光照

This tutorial will be an introduction to using ambient lighting in OpenGL 4.0 using GLSL.
本章将介绍使用OpenGL 4.0 GLSL实现环境光照。

I will explain ambient lighting using an example. Imagine you are in a room and the only light source is sunlight which is coming in from a window. The sunlight doesn't directly point at all the surfaces in the room but everything in the room is illuminated to a certain extent due to bouncing light particles. This lighting effect on the surfaces that the sun isn't directly pointing at is called ambient lighting.
我将用一个例子解释环境光照。想象在一个房间里,只有太阳光从窗户照进来。阳光并不直接照射所有的墙面,但房间里所有的物体都被不同程度的照亮了。这种没有被直接照明的光照效果叫做环境光。

Now to simulate ambient lighting we use a very simple equation. We just set each pixel to be the value of the ambient light at the start of the pixel shader. From that point forward all other operations just add their value to the ambient color. This way we ensure everything is at a minimum using the ambient color value.
我们使用一个非常简单的公式来模拟环境光照。我们在像素着色器开始位置设置每个像素的值为环境光颜色。剩下的操作都在环境光的基础上再加其他的值。这种方式可以保证物体至少有环境光的颜色。

Ambient lighting also adds far more realism to a 3D scene. Take for example the following picture that has only diffuse lighting pointing down the positive X axis at a cube:
环境光增加了3D场景的现实感。例如下面这个只有X轴上漫反射光照的盒子:

The image produced doesn't look realistic because ambient light is almost always everywhere giving everything their proper shape even if it is only slightly illuminated. Now if we just add 15% ambient white light to the same scene we get the following image instead:
图像看上去不够真实,因为环境光到处都存在,哪怕是很暗的地方。下面我们添加15%环境白光到相同的物体上得到下面的图像:

This now gives us a more realistic lighting effect that we as humans are used to.
这个图像得到了更加真实的光照效果。

We will now look at the changes to the code to implement ambient lighting. This tutorial is built on the previous tutorials that used diffuse lighting. We will now add the ambient component with just a few changes.
下面我们来修改代码实现环境光照。本章在漫反射光照的教程基础上进行修改。下面来添加漫反射部分。

Light.vs

The vertex shader has stayed the same for this tutorial.
顶点着色器不做任何改动。
////////////////////////////////////////////////////////////////////////////////
// Filename: light.vs
////////////////////////////////////////////////////////////////////////////////
#version 400

/////////////////////
// INPUT VARIABLES //
/////////////////////
in vec3 inputPosition;
in vec2 inputTexCoord;
in vec3 inputNormal;

//////////////////////
// OUTPUT VARIABLES //
//////////////////////
out vec2 texCoord;
out vec3 normal;

///////////////////////
// UNIFORM VARIABLES //
///////////////////////
uniform mat4 worldMatrix;
uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;

////////////////////////////////////////////////////////////////////////////////
// Vertex Shader
////////////////////////////////////////////////////////////////////////////////
void main(void)
{
 // Calculate the position of the vertex against the world, view, and projection matrices.
 gl_Position = worldMatrix * vec4(inputPosition, 1.0f);
 gl_Position = viewMatrix * gl_Position;
 gl_Position = projectionMatrix * gl_Position;

 // Store the texture coordinates for the pixel shader.
 texCoord = inputTexCoord;

 // Calculate the normal vector against the world matrix only.
 normal = mat3(worldMatrix) * inputNormal;

 // Normalize the normal vector.
 normal = normalize(normal);
}

Light.ps

////////////////////////////////////////////////////////////////////////////////
// Filename: light.ps
////////////////////////////////////////////////////////////////////////////////
#version 400

/////////////////////
// INPUT VARIABLES //
/////////////////////
in vec2 texCoord;
in vec3 normal;

//////////////////////
// OUTPUT VARIABLES //
//////////////////////
out vec4 outputColor;

First we add a 4 float ambient light uniform variable so that the ambient light color can be set in this shader by outside classes.
首先添加4个浮点数格式的环境光照一致变了,这样环境光的颜色可以被外部设置。
///////////////////////
// UNIFORM VARIABLES //
///////////////////////
uniform sampler2D shaderTexture;
uniform vec3 lightDirection;
uniform vec4 diffuseLightColor;
uniform vec4 ambientLight;

////////////////////////////////////////////////////////////////////////////////
// Pixel Shader
////////////////////////////////////////////////////////////////////////////////
void main(void)
{
 vec4 textureColor;
 vec4 color;
 vec3 lightDir;
 float lightIntensity;

 // Sample the pixel color from the texture using the sampler at this texture coordinate location.
 textureColor = texture(shaderTexture, texCoord);
We set the output color value to the base ambient color. All pixels will now be illuminated by a minimum of the ambient color value.
先设置输出颜色的值为环境光。所有像素至少都显示为环境光值。
 // Set the default output color to the ambient light value for all pixels.
 color = ambientLight;

 // Invert the light direction for calculations.
 lightDir = -lightDirection;

 // Calculate the amount of light on this pixel.
 lightIntensity = clamp(dot(normal, lightDir), 0.0f, 1.0f);
Check if the N dot L is greater than zero. If it is then add the diffuse color to the ambient color. If not then you need to be careful to not add the diffuse color. The reason being is that the diffuse color could be negative and it will subtract away some of the ambient color in the addition which is not correct.
检查N点乘L的值是否大于0。如果大于0,将漫反射光和环境光叠加。否则就不加漫反射光。如果漫反射光为负值,那么加上环境光后计算出来的结果就会不正确。
 if(lightIntensity > 0.0f)
 {
  // Determine the final diffuse color based on the diffuse color and the amount of light intensity.
  color += (diffuseLightColor * lightIntensity);
 }
Make sure to clamp the final output light color since the combination of ambient and diffuse could have been greater than 1.
确保最后输出的光照颜色在0.0f和1.0f范围内。
 // Clamp the final light color.
 color = clamp(color, 0.0f, 1.0f);
Finally combine the ambient/diffuse light to the texture pixel to produce the final result.
最后融合将环境/漫反射光照和纹理像素融合。
 // Multiply the texture pixel and the final diffuse color to get the final pixel color result.
 outputColor = color * textureColor;
}
Lightshaderclass.h
////////////////////////////////////////////////////////////////////////////////
// Filename: lightshaderclass.h
////////////////////////////////////////////////////////////////////////////////
#ifndef _LIGHTSHADERCLASS_H_
#define _LIGHTSHADERCLASS_H_

//////////////
// INCLUDES //
//////////////
#include <fstream>
using namespace std;

///////////////////////
// MY CLASS INCLUDES //
///////////////////////
#include "openglclass.h"

////////////////////////////////////////////////////////////////////////////////
// Class name: LightShaderClass
////////////////////////////////////////////////////////////////////////////////
class LightShaderClass
{
public:
 LightShaderClass();
 LightShaderClass(const LightShaderClass&);
 ~LightShaderClass();

 bool Initialize(OpenGLClass*, HWND);
 void Shutdown(OpenGLClass*);
 void SetShader(OpenGLClass*);
The SetShaderParameters now takes an extra float array as input for the ambient light value.
SetShaderParameters增加了环境光作为输入参数。
bool SetShaderParameters(OpenGLClass*, float*, float*, float*, int, float*, float*, float*);

private:
 bool InitializeShader(char*, char*, OpenGLClass*, HWND);
 char* LoadShaderSourceFile(char*);
 void OutputShaderErrorMessage(OpenGLClass*, HWND, unsigned int, char*);
 void OutputLinkerErrorMessage(OpenGLClass*, HWND, unsigned int);
 void ShutdownShader(OpenGLClass*);

private:
 unsigned int m_vertexShader;
 unsigned int m_fragmentShader;
 unsigned int m_shaderProgram;
};

#endif
Lightshaderclass.cpp
////////////////////////////////////////////////////////////////////////////////
// Filename: lightshaderclass.cpp
////////////////////////////////////////////////////////////////////////////////
#include "lightshaderclass.h"

LightShaderClass::LightShaderClass()
{
}

LightShaderClass::LightShaderClass(const LightShaderClass& other)
{
}

LightShaderClass::~LightShaderClass()
{
}

bool LightShaderClass::Initialize(OpenGLClass* OpenGL, HWND hwnd)
{
 bool result;

 // Initialize the vertex and pixel shaders.
 result = InitializeShader("../Engine/light.vs", "../Engine/light.ps", OpenGL, hwnd);
 if(!result)
 {
  return false;
 }

 return true;
}

void LightShaderClass::Shutdown(OpenGLClass* OpenGL)
{
 // Shutdown the vertex and pixel shaders as well as the related objects.
 ShutdownShader(OpenGL);

 return;
}

void LightShaderClass::SetShader(OpenGLClass* OpenGL)
{
 // Install the shader program as part of the current rendering state.
 OpenGL->glUseProgram(m_shaderProgram);
 
 return;
}

bool LightShaderClass::InitializeShader(char* vsFilename, char* fsFilename, OpenGLClass* OpenGL, HWND hwnd)
{
 const char* vertexShaderBuffer;
 const char* fragmentShaderBuffer;
 int status;

 // Load the vertex shader source file into a text buffer.
 vertexShaderBuffer = LoadShaderSourceFile(vsFilename);
 if(!vertexShaderBuffer)
 {
  return false;
 }

 // Load the fragment shader source file into a text buffer.
 fragmentShaderBuffer = LoadShaderSourceFile(fsFilename);
 if(!fragmentShaderBuffer)
 {
  return false;
 }

 // Create a vertex and fragment shader object.
 m_vertexShader = OpenGL->glCreateShader(GL_VERTEX_SHADER);
 m_fragmentShader = OpenGL->glCreateShader(GL_FRAGMENT_SHADER);

 // Copy the shader source code strings into the vertex and fragment shader objects.
 OpenGL->glShaderSource(m_vertexShader, 1, &vertexShaderBuffer, NULL);
 OpenGL->glShaderSource(m_fragmentShader, 1, &fragmentShaderBuffer, NULL);

 // Release the vertex and fragment shader buffers.
 delete [] vertexShaderBuffer;
 vertexShaderBuffer = 0;
 
 delete [] fragmentShaderBuffer;
 fragmentShaderBuffer = 0;

 // Compile the shaders.
 OpenGL->glCompileShader(m_vertexShader);
 OpenGL->glCompileShader(m_fragmentShader);

 // Check to see if the vertex shader compiled successfully.
 OpenGL->glGetShaderiv(m_vertexShader, GL_COMPILE_STATUS, &status);
 if(status != 1)
 {
  // If it did not compile then write the syntax error message out to a text file for review.
  OutputShaderErrorMessage(OpenGL, hwnd, m_vertexShader, vsFilename);
  return false;
 }

 // Check to see if the fragment shader compiled successfully.
 OpenGL->glGetShaderiv(m_fragmentShader, GL_COMPILE_STATUS, &status);
 if(status != 1)
 {
  // If it did not compile then write the syntax error message out to a text file for review.
  OutputShaderErrorMessage(OpenGL, hwnd, m_fragmentShader, fsFilename);
  return false;
 }

 // Create a shader program object.
 m_shaderProgram = OpenGL->glCreateProgram();

 // Attach the vertex and fragment shader to the program object.
 OpenGL->glAttachShader(m_shaderProgram, m_vertexShader);
 OpenGL->glAttachShader(m_shaderProgram, m_fragmentShader);

 // Bind the shader input variables.
 OpenGL->glBindAttribLocation(m_shaderProgram, 0, "inputPosition");
 OpenGL->glBindAttribLocation(m_shaderProgram, 1, "inputTexCoord");
 OpenGL->glBindAttribLocation(m_shaderProgram, 2, "inputNormal");

 // Link the shader program.
 OpenGL->glLinkProgram(m_shaderProgram);

 // Check the status of the link.
 OpenGL->glGetProgramiv(m_shaderProgram, GL_LINK_STATUS, &status);
 if(status != 1)
 {
  // If it did not link then write the syntax error message out to a text file for review.
  OutputLinkerErrorMessage(OpenGL, hwnd, m_shaderProgram);
  return false;
 }

 return true;
}

char* LightShaderClass::LoadShaderSourceFile(char* filename)
{
 ifstream fin;
 int fileSize;
 char input;
 char* buffer;

 // Open the shader source file.
 fin.open(filename);

 // If it could not open the file then exit.
 if(fin.fail())
 {
  return 0;
 }

 // Initialize the size of the file.
 fileSize = 0;

 // Read the first element of the file.
 fin.get(input);

 // Count the number of elements in the text file.
 while(!fin.eof())
 {
  fileSize++;
  fin.get(input);
 }

 // Close the file for now.
 fin.close();

 // Initialize the buffer to read the shader source file into.
 buffer = new char[fileSize+1];
 if(!buffer)
 {
  return 0;
 }

 // Open the shader source file again.
 fin.open(filename);

 // Read the shader text file into the buffer as a block.
 fin.read(buffer, fileSize);

 // Close the file.
 fin.close();

 // Null terminate the buffer.
 buffer[fileSize] = '\0';

 return buffer;
}

void LightShaderClass::OutputShaderErrorMessage(OpenGLClass* OpenGL, HWND hwnd, unsigned int shaderId, char* shaderFilename)
{
 int logSize, i;
 char* infoLog;
 ofstream fout;
 wchar_t newString[128];
 unsigned int error, convertedChars;

 // Get the size of the string containing the information log for the failed shader compilation message.
 OpenGL->glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &logSize);

 // Increment the size by one to handle also the null terminator.
 logSize++;

 // Create a char buffer to hold the info log.
 infoLog = new char[logSize];
 if(!infoLog)
 {
  return;
 }

 // Now retrieve the info log.
 OpenGL->glGetShaderInfoLog(shaderId, logSize, NULL, infoLog);

 // Open a file to write the error message to.
 fout.open("shader-error.txt");

 // Write out the error message.
 for(i=0; i<logSize; i++)
 {
  fout << infoLog[i];
 }

 // Close the file.
 fout.close();

 // Convert the shader filename to a wide character string.
 error = mbstowcs_s(&convertedChars, newString, 128, shaderFilename, 128);
 if(error != 0)
 {
  return;
 }

 // Pop a message up on the screen to notify the user to check the text file for compile errors.
 MessageBox(hwnd, L"Error compiling shader.  Check shader-error.txt for message.", newString, MB_OK);

 return;
}

void LightShaderClass::OutputLinkerErrorMessage(OpenGLClass* OpenGL, HWND hwnd, unsigned int programId)
{
 int logSize, i;
 char* infoLog;
 ofstream fout;

 // Get the size of the string containing the information log for the failed shader compilation message.
 OpenGL->glGetProgramiv(programId, GL_INFO_LOG_LENGTH, &logSize);

 // Increment the size by one to handle also the null terminator.
 logSize++;

 // Create a char buffer to hold the info log.
 infoLog = new char[logSize];
 if(!infoLog)
 {
  return;
 }

 // Now retrieve the info log.
 OpenGL->glGetProgramInfoLog(programId, logSize, NULL, infoLog);

 // Open a file to write the error message to.
 fout.open("linker-error.txt");

 // Write out the error message.
 for(i=0; i<logSize; i++)
 {
  fout << infoLog[i];
 }

 // Close the file.
 fout.close();

 // Pop a message up on the screen to notify the user to check the text file for linker errors.
 MessageBox(hwnd, L"Error compiling linker.  Check linker-error.txt for message.", L"Linker Error", MB_OK);

 return;
}

void LightShaderClass::ShutdownShader(OpenGLClass* OpenGL)
{
 // Detach the vertex and fragment shaders from the program.
 OpenGL->glDetachShader(m_shaderProgram, m_vertexShader);
 OpenGL->glDetachShader(m_shaderProgram, m_fragmentShader);

 // Delete the vertex and fragment shaders.
 OpenGL->glDeleteShader(m_vertexShader);
 OpenGL->glDeleteShader(m_fragmentShader);

 // Delete the shader program.
 OpenGL->glDeleteProgram(m_shaderProgram);

 return;
}
The SetShaderParameters function now takes in an ambient light color value and then sets the ambientLight uniform variable in the pixel shader.
SetShaderParameters方法增加了环境光作为参数,并设置像素着色器的环境光的一直变量。
bool LightShaderClass::SetShaderParameters(OpenGLClass* OpenGL, float* worldMatrix, float* viewMatrix, float* projectionMatrix, int textureUnit,
        float* lightDirection, float* diffuseLightColor, float* ambientLight)
{
 unsigned int location;

 // Set the world matrix in the vertex shader.
 location = OpenGL->glGetUniformLocation(m_shaderProgram, "worldMatrix");
 if(location == -1)
 {
  return false;
 }
 OpenGL->glUniformMatrix4fv(location, 1, false, worldMatrix);

 // Set the view matrix in the vertex shader.
 location = OpenGL->glGetUniformLocation(m_shaderProgram, "viewMatrix");
 if(location == -1)
 {
  return false;
 }
 OpenGL->glUniformMatrix4fv(location, 1, false, viewMatrix);

 // Set the projection matrix in the vertex shader.
 location = OpenGL->glGetUniformLocation(m_shaderProgram, "projectionMatrix");
 if(location == -1)
 {
  return false;
 }
 OpenGL->glUniformMatrix4fv(location, 1, false, projectionMatrix);

 // Set the texture in the pixel shader to use the data from the first texture unit.
 location = OpenGL->glGetUniformLocation(m_shaderProgram, "shaderTexture");
 if(location == -1)
 {
  return false;
 }
 OpenGL->glUniform1i(location, textureUnit);

 // Set the light direction in the pixel shader.
 location = OpenGL->glGetUniformLocation(m_shaderProgram, "lightDirection");
 if(location == -1)
 {
  return false;
 }
 OpenGL->glUniform3fv(location, 1, lightDirection);

 // Set the light direction in the pixel shader.
 location = OpenGL->glGetUniformLocation(m_shaderProgram, "diffuseLightColor");
 if(location == -1)
 {
  return false;
 }
 OpenGL->glUniform4fv(location, 1, diffuseLightColor);
The ambient value in the pixel shader is set here.
这里设置像素着色器的环境光的值。
 // Set the ambient light in the pixel shader.
 location = OpenGL->glGetUniformLocation(m_shaderProgram, "ambientLight");
 if(location == -1)
 {
  return false;
 }
 OpenGL->glUniform4fv(location, 1, ambientLight);

 return true;
}
Lightclass.h

The LightClass was updated for this tutorial to have an ambient component and related helper functions.
本章更新了LightClass,增加了环境光照部分。
////////////////////////////////////////////////////////////////////////////////
// Filename: lightclass.h
////////////////////////////////////////////////////////////////////////////////
#ifndef _LIGHTCLASS_H_
#define _LIGHTCLASS_H_

////////////////////////////////////////////////////////////////////////////////
// Class name: LightClass
////////////////////////////////////////////////////////////////////////////////
class LightClass
{
public:
 LightClass();
 LightClass(const LightClass&);
 ~LightClass();

 void SetDiffuseColor(float, float, float, float);
 void SetDirection(float, float, float);
 void SetAmbientLight(float, float, float, float);

 void GetDiffuseColor(float*);
 void GetDirection(float*);
 void GetAmbientLight(float*);

private:
 float m_diffuseColor[4];
 float m_direction[3];
 float m_ambientLight[4];
};

#endif
Lightclass.cpp
////////////////////////////////////////////////////////////////////////////////
// Filename: lightclass.cpp
////////////////////////////////////////////////////////////////////////////////
#include "lightclass.h"

LightClass::LightClass()
{
}

LightClass::LightClass(const LightClass& other)
{
}

LightClass::~LightClass()
{
}

void LightClass::SetDiffuseColor(float red, float green, float blue, float alpha)
{
 m_diffuseColor[0] = red;
 m_diffuseColor[1] = green;
 m_diffuseColor[2] = blue;
 m_diffuseColor[3] = alpha;
 return;
}

void LightClass::SetDirection(float x, float y, float z)
{
 m_direction[0] = x;
 m_direction[1] = y;
 m_direction[2] = z;
 return;
}

void LightClass::SetAmbientLight(float red, float green, float blue, float alpha)
{
 m_ambientLight[0] = red;
 m_ambientLight[1] = green;
 m_ambientLight[2] = blue;
 m_ambientLight[3] = alpha;
 return;
}

void LightClass::GetDiffuseColor(float* color)
{
 color[0] = m_diffuseColor[0];
 color[1] = m_diffuseColor[1];
 color[2] = m_diffuseColor[2];
 color[3] = m_diffuseColor[3];
 return;
}

void LightClass::GetDirection(float* direction)
{
 direction[0] = m_direction[0];
 direction[1] = m_direction[1];
 direction[2] = m_direction[2];
 return;
}

void LightClass::GetAmbientLight(float* ambient)
{
 ambient[0] = m_ambientLight[0];
 ambient[1] = m_ambientLight[1];
 ambient[2] = m_ambientLight[2];
 ambient[3] = m_ambientLight[3];
 return;
}
Graphicsclass.h

The header for the GraphicsClass hasn't changed for this tutorial.
////////////////////////////////////////////////////////////////////////////////
// Filename: graphicsclass.h
////////////////////////////////////////////////////////////////////////////////
#ifndef _GRAPHICSCLASS_H_
#define _GRAPHICSCLASS_H_

///////////////////////
// MY CLASS INCLUDES //
///////////////////////
#include "openglclass.h"
#include "cameraclass.h"
#include "modelclass.h"
#include "lightshaderclass.h"
#include "lightclass.h"

/////////////
// GLOBALS //
/////////////
const bool FULL_SCREEN = true;
const bool VSYNC_ENABLED = true;
const float SCREEN_DEPTH = 1000.0f;
const float SCREEN_NEAR = 0.1f;

////////////////////////////////////////////////////////////////////////////////
// Class name: GraphicsClass
////////////////////////////////////////////////////////////////////////////////
class GraphicsClass
{
public:
 GraphicsClass();
 GraphicsClass(const GraphicsClass&);
 ~GraphicsClass();

 bool Initialize(OpenGLClass*, HWND);
 void Shutdown();
 bool Frame();

private:
 bool Render(float);

private:
 OpenGLClass* m_OpenGL;
 CameraClass* m_Camera;
 ModelClass* m_Model;
 LightShaderClass* m_LightShader;
 LightClass* m_Light;
};

#endif
Graphicsclass.cpp
////////////////////////////////////////////////////////////////////////////////
// Filename: graphicsclass.cpp
////////////////////////////////////////////////////////////////////////////////
#include "graphicsclass.h"

GraphicsClass::GraphicsClass()
{
 m_OpenGL = 0;
 m_Camera = 0;
 m_Model = 0;
 m_LightShader = 0;
 m_Light = 0;
}

GraphicsClass::GraphicsClass(const GraphicsClass& other)
{
}

GraphicsClass::~GraphicsClass()
{
}

bool GraphicsClass::Initialize(OpenGLClass* OpenGL, HWND hwnd)
{
 bool result;

 // Store a pointer to the OpenGL class object.
 m_OpenGL = OpenGL;

 // Create the camera object.
 m_Camera = new CameraClass;
 if(!m_Camera)
 {
  return false;
 }

 // Set the initial position of the camera.
 m_Camera->SetPosition(0.0f, 0.0f, -10.0f);

 // Create the model object.
 m_Model = new ModelClass;
 if(!m_Model)
 {
  return false;
 }

 // Initialize the model object.
 result = m_Model->Initialize(m_OpenGL,  "../Engine/data/cube.txt", "../Engine/data/opengl.tga", 0, true);
 if(!result)
 {
  MessageBox(hwnd, L"Could not initialize the model object.", L"Error", MB_OK);
  return false;
 }
 
 // Create the light shader object.
 m_LightShader = new LightShaderClass;
 if(!m_LightShader)
 {
  return false;
 }

 // Initialize the light shader object.
 result = m_LightShader->Initialize(m_OpenGL, hwnd);
 if(!result)
 {
  MessageBox(hwnd, L"Could not initialize the light shader object.", L"Error", MB_OK);
  return false;
 }

 // Create the light object.
 m_Light = new LightClass;
 if(!m_Light)
 {
  return false;
 }
Set the intensity of the ambient light to 15% white color. Also set the direction of the light to point down the positive X axis so we can directly see the effect of ambient lighting on the cube.
设置环境光强度为15%白色。设置光照方向为X轴正方向,这样我们就可以看到盒子上环境光照的效果。
 // Initialize the light object.
 m_Light->SetDiffuseColor(1.0f, 1.0f, 1.0f, 1.0f);
 m_Light->SetDirection(1.0f, 0.0f, 0.0f);
 m_Light->SetAmbientLight(0.15f, 0.15f, 0.15f, 1.0f);

 return true;
}

void GraphicsClass::Shutdown()
{
 // Release the light object.
 if(m_Light)
 {
  delete m_Light;
  m_Light = 0;
 }

 // Release the light shader object.
 if(m_LightShader)
 {
  m_LightShader->Shutdown(m_OpenGL);
  delete m_LightShader;
  m_LightShader = 0;
 }

 // Release the model object.
 if(m_Model)
 {
  m_Model->Shutdown(m_OpenGL);
  delete m_Model;
  m_Model = 0;
 }

 // Release the camera object.
 if(m_Camera)
 {
  delete m_Camera;
  m_Camera = 0;
 }

 // Release the pointer to the OpenGL class object.
 m_OpenGL = 0;

 return;
}

bool GraphicsClass::Frame()
{
 bool result;
 static float rotation = 0.0f;
I have slowed down the rotation by half so the effect is easier to see.
我将旋转速度减半,这样效果很明显。
// Update the rotation variable each frame.
 rotation += 0.0174532925f * 1.0f;
 if(rotation > 360.0f)
 {
  rotation -= 360.0f;
 }

 // Render the graphics scene.
 result = Render(rotation);
 if(!result)
 {
  return false;
 }

 return true;
}
In the render function we have added getting the ambient light value from the light object and then setting it in the shader during rendering.
Render方法增加了从光照对象获取环境光值的代码,并在渲染时设置到着色器中。
bool GraphicsClass::Render(float rotation)
{
 float worldMatrix[16];
 float viewMatrix[16];
 float projectionMatrix[16];
 float lightDirection[3];
 float diffuseLightColor[4];
 float ambientLight[4];

 // Clear the buffers to begin the scene.
 m_OpenGL->BeginScene(0.0f, 0.0f, 0.0f, 1.0f);

 // Generate the view matrix based on the camera's position.
 m_Camera->Render();

 // Get the world, view, and projection matrices from the opengl and camera objects.
 m_OpenGL->GetWorldMatrix(worldMatrix);
 m_Camera->GetViewMatrix(viewMatrix);
 m_OpenGL->GetProjectionMatrix(projectionMatrix);

 // Get the light properties.
 m_Light->GetDirection(lightDirection);
 m_Light->GetDiffuseColor(diffuseLightColor);
 m_Light->GetAmbientLight(ambientLight);

 // Rotate the world matrix by the rotation value so that the triangle will spin.
 m_OpenGL->MatrixRotationY(worldMatrix, rotation);

 // Set the light shader as the current shader program and set the matrices that it will use for rendering.
 m_LightShader->SetShader(m_OpenGL);
 m_LightShader->SetShaderParameters(m_OpenGL, worldMatrix, viewMatrix, projectionMatrix, 0, lightDirection, diffuseLightColor, ambientLight);

 // Render the model using the light shader.
 m_Model->Render(m_OpenGL);
 
 // Present the rendered scene to the screen.
 m_OpenGL->EndScene();

 return true;
}
Summary
总结

With the addition of ambient lighting all surfaces now illuminate to a minimum degree to produce a more realistic lighting effect.
增加环境光照后,我们得到了更加真实的光照效果。

To Do Exercises
练习

1. Recompile the code and ensure you get a spinning cube that is illuminated on the dark side now.
1. 重新编译并运行代码,确保得到一个阴暗面可见的旋转盒子。

2. Change the ambient light value to (0.0f, 0.0f, 0.0f, 1.0f) to see just the diffuse component again.
2. 将环境光的值改为(0.0f, 0.0f, 0.0f, 1.0f),再看光照效果。

Source Code
源代码

http://www.rastertek.com/gl40src09.zip

内容概要:本文详细介绍了一种基于Simulink的表贴式永磁同步电机(SPMSM)有限控制集模型预测电流控制(FCS-MPCC)仿真系统。通过构建PMSM数学模型、坐标变换、MPC控制器、SVPWM调制等模块,实现了对电机定子电流的高精度跟踪控制,具备快速动态响应和低稳态误差的特点。文中提供了完整的仿真建模步骤、关键参数设置、核心MATLAB函数代码及仿真结果分析,涵盖转速、电流、转矩和三相电流波形,验证了MPC控制策略在动态性能、稳态精度和抗负载扰动方面的优越性,并提出了参数自整定、加权代价函数、模型预测转矩控制和弱磁扩速等优化方向。; 适合人群:自动化、电气工程及其相关专业本科生、研究生,以及从事电机控制算法研究与仿真的工程技术人员;具备一定的电机原理、自动控制理论和Simulink仿真基础者更佳; 使用场景及目标:①用于永磁同步电机模型预测控制的教学演示、课程设计或毕业设计项目;②作为电机先进控制算法(如MPC、MPTC)的仿真验证平台;③支撑科研中对控制性能优化(如动态响应、抗干扰能力)的研究需求; 阅读建议:建议读者结合Simulink环境动手搭建模型,深入理解各模块间的信号流向与控制逻辑,重点掌握预测模型构建、代价函数设计与开关状态选择机制,并可通过修改电机参数或控制策略进行拓展实验,以增强实践与创新能力。
根据原作 https://pan.quark.cn/s/23d6270309e5 的源码改编 湖北省黄石市2021年中考数学试卷所包含的知识点广泛涉及了中学数学的基础领域,涵盖了实数、科学记数法、分式方程、几何体的三视图、立体几何、概率统计以及代数方程等多个方面。 接下来将对每道试题所关联的知识点进行深入剖析:1. 实数与倒数的定义:该题目旨在检验学生对倒数概念的掌握程度,即一个数a的倒数表达为1/a,因此-7的倒数可表示为-1/7。 2. 科学记数法的运用:科学记数法是一种表示极大或极小数字的方法,其形式为a×10^n,其中1≤|a|<10,n为整数。 此题要求学生运用科学记数法表示一个天文单位的距离,将1.4960亿千米转换为1.4960×10^8千米。 3. 分式方程的求解方法:考察学生解决包含分母的方程的能力,题目要求找出满足方程3/(2x-1)=1的x值,需通过消除分母的方式转化为整式方程进行解答。 4. 三视图的辨认:该题目测试学生对于几何体三视图(主视图、左视图、俯视图)的认识,需要识别出具有两个相同视图而另一个不同的几何体。 5. 立体几何与表面积的计算:题目要求学生计算由直角三角形旋转形成的圆锥的表面积,要求学生对圆锥的底面积和侧面积公式有所了解并加以运用。 6. 统计学的基础概念:题目涉及众数、平均数、极差和中位数的定义,要求学生根据提供的数据信息选择恰当的统计量。 7. 方程的整数解求解:考察学生在实际问题中进行数学建模的能力,通过建立方程来计算在特定条件下帐篷的搭建方案数量。 8. 三角学的实际应用:题目通过在直角三角形中运用三角函数来求解特定线段的长度。 利用正弦定理求解AD的长度是解答该问题的关键。 9. 几何变换的应用:题目要求学生运用三角板的旋转来求解特定点的...
Python基于改进粒子群IPSO与LSTM的短期电力负荷预测研究内容概要:本文围绕“Python基于改进粒子群IPSO与LSTM的短期电力负荷预测研究”展开,提出了一种结合改进粒子群优化算法(IPSO)与长短期记忆网络(LSTM)的混合预测模型。通过IPSO算法优化LSTM网络的关键参数(如学习率、隐层节点数等),有效提升了模型在短期电力负荷预测中的精度与收敛速度。文中详细阐述了IPSO算法的改进策略(如引入自适应惯性权重、变异机制等),增强了全局搜索能力与避免早熟收敛,并利用实际电力负荷数据进行实验验证,结果表明该IPSO-LSTM模型相较于传统LSTM、PSO-LSTM等方法在预测准确性(如MAE、RMSE指标)方面表现更优。研究为电力系统调度、能源管理提供了高精度的负荷预测技术支持。; 适合人群:具备一定Python编程基础、熟悉基本机器学习算法的高校研究生、科研人员及电力系统相关领域的技术人员,尤其适合从事负荷预测、智能优化算法应用研究的专业人士。; 使用场景及目标:①应用于短期电力负荷预测,提升电网调度的精确性与稳定性;②为优化算法(如粒子群算法)与深度学习模型(如LSTM)的融合应用提供实践案例;③可用于学术研究、毕业论文复现或电力企业智能化改造的技术参考。; 阅读建议:建议读者结合文中提到的IPSO与LSTM原理进行理论学习,重点关注参数优化机制的设计思路,并动手复现实验部分,通过对比不同模型的预测结果加深理解。同时可拓展尝试将该方法应用于其他时序预测场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值