How can I rotate triangle in OpenGL? - opengl

I want to rotate my triangle in OpenGL, and running program on Raspberry Pi.
I can draw triangle and move it.
But I have no idea to rotate it..
Nothing rotates.
#include <cstdio>
#include <ctime>
#include <cmath>
#include <string>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES2/gl2.h>
#include <GLES/gl.h>
#include <bcm_host.h>
EGLDisplay Disp;
EGLSurface Surface;
EGLContext Context;
int ScrWidth, ScrHeight;
float MVPMatrix[16];
float ProjectionMatrix[16];
float ViewMatrix[16];
using namespace std;
class Shader
{
private:
string VertexShaderFile;
string FragmentShaderFile;
GLuint Load(GLenum type, string FileName)
{
(Compile shader)
}
GLuint Program;
bool Linked;
public:
Shader(string FileNameV, string FileNameF)
{
Linked = false;
VertexShaderFile = FileNameV;
FragmentShaderFile = FileNameF;
}
bool Load()
{
(Link vertex/fragment shader)
}
void Use()
{
glUseProgram(Program);
}
int GetAttrLoc(const char *Name)
{
glGetAttribLocation(Program, Name);
}
int GetUniformLoc(const char *Name)
{
return glGetUniformLocation(Program, Name);
}
~Shader()
{
if(Linked)
{
Linked = false;
glDeleteProgram(Program);
}
}
};
class Triangle
{
private:
const int COORDS_PER_VERTEX = 3;
const int vertexCount = 9 / COORDS_PER_VERTEX; //9: Length of triangleCoords
const int vertexStride = COORDS_PER_VERTEX * 4; // 4 bytes per vertex
static float TriangleCoords [];
float Color[4];
float XOff;
float YOff;
float ZOff;
Shader *S;
public:
Triangle()
{
XOff = YOff = ZOff = 0;
S = new Shader("Shaders/test.vsh", "Shaders/test.fsh");
if (!S->Load())
{
delete S;
S = NULL;
}
}
void SetColor(int R, int G, int B, int A)
{
Color[0] = R / 255.0;
Color[1] = G / 255.0;
Color[2] = B / 255.0;
Color[3] = A / 255.0;
}
void SetXYZ(int X, int Y, int Z)
{
(Sets position)
}
bool Draw()
{
float TriangleCoords[] = { // in counterclockwise order:
-0.0 + XOff, 0.622008459 + YOff, 0.0 + ZOff, // top
-0.5 + XOff, -0.311004243 + YOff, 0.0 + ZOff, // bottom left
0.5 + XOff, -0.311004243 + YOff, 0.0 + ZOff // bottom right
};
printf("%f\n", TriangleCoords[1]);
//glMatrixMode(GL_PROJECTION);
if (S == NULL)
return false;
S->Use();
// Load the vertex data
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, TriangleCoords);
// get handle to shape's transformation matrix
// Pass the projection and view transformation to the shader
//UniformMatrix4fv(S->GetUniformLoc("uMVPMatrix"), 1, false, MVPMatrix);
glUniform4fv(S->GetUniformLoc("vColor"), 1, Color);
glEnableVertexAttribArray(0);
//glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
float X = LocalTime->tm_hour / 23.0;
float Y = LocalTime->tm_min / 59.0;
float Z = LocalTime->tm_sec / 59.0;
glTranslatef(0, 0, 1);
glRotatef(60, 1.f, 0.f, 0.f);
glRotatef(30, 0.f, 1.f, 0.f);
glRotatef(30, 0.f, 0.f, 1.f);
glDrawArrays(GL_TRIANGLES, 0, 3);
//glPopMatrix();
return true;
}
};
bool InitDisplay()
{
bcm_host_init();
Disp = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if(eglInitialize(Disp, NULL, NULL) != EGL_TRUE)
{
printf("Display initialize error.\n");
return false;
}
printf("Display initialized.\n");
static const EGLint AttrList[] =
{
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_NONE
};
EGLConfig Config;
int ConfigCount;
if(eglChooseConfig(Disp, AttrList, &Config, 1, &ConfigCount) != EGL_TRUE)
{
printf("Display choose config error.\n");
return false;
}
printf("Display config chosen. %d configs.\n", ConfigCount);
//if(eglBindAPI(EGL_OPENGL_ES_API) != EGL_TRUE)
//{
// printf("Bind API error.\n");
// return false;
//}
//printf("API bound.\n");
static const EGLint ContextAttr[] =
{
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
if((Context = eglCreateContext(Disp, Config, EGL_NO_CONTEXT, ContextAttr)) == EGL_NO_CONTEXT)
{
printf("Create context error.\n");
return false;
}
printf("Context created.\n");
if(graphics_get_display_size(0 /* LCD */, &ScrWidth, &ScrHeight) < 0)
{
printf("Get screen size error.\n");
return false;
}
printf("Got screen size. %dx%d\n", ScrWidth, ScrHeight);
DISPMANX_DISPLAY_HANDLE_T DispmanDisp;
DispmanDisp = vc_dispmanx_display_open(0 /* LCD */);
printf("Dispmanx - Display opened.\n");
DISPMANX_UPDATE_HANDLE_T DispmanUpdate;
DispmanUpdate = vc_dispmanx_update_start(0);
printf("Dispmanx - Update started.\n");
DISPMANX_ELEMENT_HANDLE_T DispmanElement;
VC_RECT_T DestRect;
VC_RECT_T SrcRect;
DestRect.x = 0;
DestRect.y = 0;
DestRect.width = ScrWidth;
DestRect.height = ScrHeight;
SrcRect.x = 0;
SrcRect.y = 0;
SrcRect.width = ScrWidth << 16;
SrcRect.height = ScrHeight << 16;
DispmanElement= vc_dispmanx_element_add(
DispmanUpdate,
DispmanDisp,
0/*layer*/,
&DestRect,
0/*src*/,
&SrcRect,
DISPMANX_PROTECTION_NONE,
0 /*alpha*/,
0/*clamp*/,
0/*transform*/
);
printf("Dispmanx - Element added.\n");
static EGL_DISPMANX_WINDOW_T NativeWindow;
NativeWindow.element = DispmanElement;
NativeWindow.width = ScrWidth;
NativeWindow.height = ScrHeight;
vc_dispmanx_update_submit_sync(DispmanUpdate);
printf("Dispmanx - Sync submited.\n");
if((Surface = eglCreateWindowSurface(Disp, Config, &NativeWindow, NULL)) == EGL_NO_SURFACE)
{
printf("Create surface error.\n");
return false;
}
printf("Surface created\n");
if(eglMakeCurrent(Disp, Surface, Surface, Context) != EGL_TRUE)
{
printf("Make onnection between context and surface error.\n");
return false;
}
printf("Connection made between context and surface.\n");
glEnable(GL_CULL_FACE);
glMatrixMode(GL_MODELVIEW);
printf("Graphics system ready.\n");
return true;
}
void makeFrustum(float fovY, float aspectRatio, float front, float back)
{
const float DEG2RAD = 3.14159265 / 180;
float tangent = tan(fovY / 2 * DEG2RAD); // tangent of half fovY
float height = front * tangent; // half height of near plane
float width = height * aspectRatio; // half width of near plane
// params: left, right, bottom, top, near, far
glFrustumf(-width, width, -height, height, front, back);
}
void DrawLoop()
{
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glViewport(0, 0, ScrWidth, ScrHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
makeFrustum(45.0, ScrWidth / (float)ScrHeight, 1, 500);
glEnableClientState(GL_VERTEX_ARRAY);
Triangle T1;
Triangle T2;
Triangle T3;
Triangle T4;
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.f, 0.f, -50.f);
while (1)
{
time_t Time;
time(&Time);
tm *LocalTime = localtime(&Time);
printf("%d:%d:%d\n", LocalTime->tm_hour, LocalTime->tm_min, LocalTime->tm_sec);
float R = LocalTime->tm_hour / 23.0;
float G = LocalTime->tm_min / 59.0;
float B = LocalTime->tm_sec / 59.0;
T1.SetColor(255, 0, 0, 255);
T1.SetXYZ(B * ScrWidth, B * ScrHeight, 0);
//glClearColor(0, 0, 0, 1.0);
//glClear(GL_COLOR_BUFFER_BIT);
if (!T1.Draw() || !T2.Draw() || !T3.Draw() || !T4.Draw())
{
return;
}
glFlush();
eglSwapBuffers(Disp, Surface);
}
}
int main()
{
if(!InitDisplay())
{
printf("Display initialize error.\n");
return false;
}
DrawLoop();
return 0;
}
What should I do to rotate triangle?
I referenced working code, but it still doesn't rotates.

You're trying to use OpenGL ES 1.1 functions (glLoadIdentity, glMatrixMode, glTranslatef, glRotatef, etc) in an OpenGL ES 2.0 context - this won't work. You can use either OpenGL ES 1.1 OR OpenGL ES 2.0, but you can't use both at the same time from the same context.
I would suggest sticking with OpenGL ES 2.0 using shaders, and learning the OpenGL ES 2.0 way of doing things, as this is how all of the newer APIs work.
To do translation and rotation you need to encode it into an MVP matrix and pass this as a uniform to the vertex shader which you use when calculating gl_Position. Some examples here:
https://open.gl/transformations

Related

How to implement interactive rotation operations in a decent way

Recently, I want to achieve interactive rotation operations as can be done in meshlab:
Basically, it achieves rotation of three degrees of freedom. I visualize these operations as following codes with the help of GLFW:
static void mouse_move_callback(GLFWwindow* window, double xpos, double ypos){
...
do{
//perform rotation operations only if keeping the right mouse key pressed
if(glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_RELEASE) {
g_clr_right_mouse = true;
break;
}
/*clear mouse state once transferred from release state
to pressed state to prevent from a instant flicker*/
if(g_clr_right_mouse){
g_lastX = xpos;
g_lastY = ypos;
g_clr_right_mouse = false;
}
float xoffset = xpos - g_lastX; //let movement from down to top positive
float yoffset = g_lastY - ypos;
g_lastX = xpos;
g_lastY = ypos;
//do counterclockwise rotation around x-asis with movement in y direction
glm::mat4 r1 = glm::rotate(glm::mat4(), glm::radians(-yoffset * 0.5f), glm::vec3(1.0f,0.0f,0.0f));
//do counterclockwise rotation around y-asis with movement in x direction
glm::mat4 r2 = glm::rotate(glm::mat4(), glm::radians( xoffset * 0.5f), glm::vec3(0.0f,1.0f,0.0f));
glm::mat4 tmp = r2 * r1 * g_model;
for(int i=0; i<3; i++)
g_model[i] = tmp[i];
return ;
}while(false);
}
These codes are located here, and the whole project can be found here which can be downloaded and built. Finally, it performs as follows:
However, my implementation can only achieve rotation operations of 2 DOF, I add a keyboard callback to achieve rotation around the z axis:
void keyboard_callback(GLFWwindow* window, int key, int scancode, int action, int mod){
if(glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS){
glm::mat4 r3 = glm::rotate(glm::mat4(), glm::radians(3.0f), glm::vec3(0,0,1.0f));
glm::mat4 tmp = r3 * g_model;
for(int i=0; i<3; i++)
g_model[i] = tmp[i];
}else if(glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS){
glm::mat4 r3 = glm::rotate(glm::mat4(), glm::radians(-3.0f), glm::vec3(0,0,1.0f));
glm::mat4 tmp = r3 * g_model;
for(int i=0; i<3; i++)
g_model[i] = tmp[i];
}
}
So my question is how to decently achieve interactive rotation operations of 3 DOF only with mouse movement?
When dragging the mouse, the object must be rotated around an axis that is perpendicular to the direction of movement of the mouse. The pivot is the origin of the model.
Rotate the mouse movement vector by 90 ° in the XY plane of the view. Since this is a vector in view space, the vector must be transformed from view space into world space. The matrix that transforms a vector from view space to world space is the inverse matrix of the upper left 3x3 of the view matrix:
vec2 drag_start;
vec2 drag_end;
glm::mat3 to_world = glm::inverse(glm::mat3(view_matrix));
glm::vec2 drag_vec = glm::vec2(drag_end.x - drag_start.x, drag_start.y - drag_end.y);
glm::vec3 axis_vec = glm::normalize(to_world * glm::vec3(-drag_vec.y, drag_vec.x, 0));
Create a rotation matrix around the axis. The angle depends on the length of the vector (height is the height of the viewport in pixels):
GLfloat angle = glm::length(drag_vec) / height / 2 * M_PI;
drag_rotation = glm::rotate(glm::mat4(1.0f), angle, axis_vec);
Compute a rotation matrix while dragging the mouse. Concatenate the rotation matrix and the model matrix after the drag ends:
glm::mat4 view_matrix(1.0f);
glm::mat4 model_rotation(1.0f);
glm::mat4 drag_rotation(1.0f);
glm::vec2 drag_start(0.0f);
bool drag = false;
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
if (button != GLFW_MOUSE_BUTTON_LEFT)
return;
if (action == GLFW_PRESS)
{
drag = true;
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
drag_start = glm::vec2(xpos, ypos);
}
else if (action == GLFW_RELEASE)
{
drag = false;
model_rotation = drag_rotation * model_rotation;
drag_rotation = glm::mat4(1.0f);
}
}
void cursor_position_callback(GLFWwindow* window, double xpos, double ypos)
{
if (!drag)
return;
glm::mat3 to_world = glm::inverse(glm::mat3(view_matrix));
glm::vec2 drag_vec = glm::vec2(xpos - drag_start.x, drag_start.y - ypos);
glm::vec3 axis_vec = glm::normalize(to_world * glm::vec3(-drag_vec.y, drag_vec.x, 0));
GLfloat angle = glm::length(drag_vec) / height / 2 * M_PI;
drag_rotation = glm::rotate(glm::mat4(1.0f), angle, axis_vec);
}
The model matrix is the concatenation of drag_rotation and model_rotation:
glm::mat4 model = drag_rotation * model_rotation;
See also Orbit
Complete example:
#include <GL/glew.h>
#include <GL/gl.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <GLFW/glfw3.h>
#include <vector>
#include <string>
#include <stdexcept>
#include <iostream>
#define _USE_MATH_DEFINES
#include <cmath>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
std::string sh_vert = R"(
#version 460 core
layout (location = 0) in vec4 a_position;
layout (location = 1) in vec3 a_uvw;
out vec3 v_uvw;
layout (location = 0) uniform mat4 u_projection;
layout (location = 1) uniform mat4 u_view;
layout (location = 2) uniform mat4 u_model;
void main()
{
v_uvw = a_uvw;
gl_Position = u_projection * u_view * u_model * a_position;
}
)";
std::string sh_frag = R"(
#version 460 core
out vec4 frag_color;
in vec3 v_uvw;
vec3 HUEtoRGB(in float H)
{
float R = abs(H * 6.0 - 3.0) - 1.0;
float G = 2.0 - abs(H * 6.0 - 2.0);
float B = 2.0 - abs(H * 6.0 - 4.0);
return clamp(vec3(R, G, B), 0.0, 1.0);
}
void main()
{
frag_color = vec4(HUEtoRGB(v_uvw.z), 1.0);
}
)";
class ShaderProgram
{
public:
GLuint programObject;
static ShaderProgram newProgram(const std::string& vsh, const std::string& fsh);
private:
GLuint compileShader(const std::string& sourceCode, GLenum shaderType);
void linkProgram(std::vector<GLuint> shObjs);
void compileStatus(GLuint shader);
void linkStatus();
};
class VertexArrayObject
{
public:
GLuint vaoObject = 0;
GLsizei noOfVertices = 0;
GLsizei noOfIndices = 0;
static VertexArrayObject newCube();
static VertexArrayObject newCircles();
static VertexArrayObject newVAO(const std::vector<GLfloat>& varray, const std::vector<GLuint>& iarray);
};
int width = 800, height = 600;
glm::mat4 view_matrix(1.0f);
glm::mat4 model_rotation(1.0f);
glm::mat4 drag_rotation(1.0f);
glm::vec2 drag_start(0.0f);
bool drag = false;
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
if (button != GLFW_MOUSE_BUTTON_LEFT)
return;
if (action == GLFW_PRESS)
{
drag = true;
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
drag_start = glm::vec2(xpos, ypos);
}
else if (action == GLFW_RELEASE)
{
drag = false;
model_rotation = drag_rotation * model_rotation;
drag_rotation = glm::mat4(1.0f);
}
}
void cursor_position_callback(GLFWwindow* window, double xpos, double ypos)
{
if (!drag)
return;
glm::mat3 to_world = glm::inverse(glm::mat3(view_matrix));
glm::vec2 drag_vec = glm::vec2(xpos - drag_start.x, drag_start.y - ypos);
glm::vec3 axis_vec = glm::normalize(to_world * glm::vec3(-drag_vec.y, drag_vec.x, 0));
GLfloat angle = glm::length(drag_vec) / height / 2 * M_PI;
drag_rotation = glm::rotate(glm::mat4(1.0f), angle, axis_vec);
}
int main(void)
{
if (glfwInit() == GLFW_FALSE)
throw std::runtime_error( "error initializing glfw" );
glfwWindowHint(GLFW_SAMPLES, 8);
GLFWwindow * window = glfwCreateWindow(width, height, "OGL window", nullptr, nullptr);
if (window == nullptr)
{
glfwTerminate();
throw std::runtime_error( "error initializing window" );
}
glfwSetMouseButtonCallback(window, mouse_button_callback);
glfwSetCursorPosCallback(window, cursor_position_callback);
glfwMakeContextCurrent(window);
if ( glewInit() != GLEW_OK )
throw std::runtime_error( "error initializing glew" );
auto progam = ShaderProgram::newProgram(sh_vert, sh_frag);
auto cube = VertexArrayObject::newCube();
auto circles = VertexArrayObject::newCircles();
glUseProgram(progam.programObject);
glEnable( GL_DEPTH_TEST );
glClearColor(0.1f, 0.3f, 0.2f, 0.0f);
view_matrix = glm::lookAt(glm::vec3(0.0f, 0.0f, 7.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
glUniformMatrix4fv(1, 1, GL_FALSE, glm::value_ptr(view_matrix));
while (!glfwWindowShouldClose(window))
{
glfwGetFramebufferSize(window, &width, &height);
float ascpect = (float)width / (float)height;
glm::mat4 project = glm::perspective(glm::radians(60.0f), ascpect, 0.1f, 20.0f);
glUniformMatrix4fv(0, 1, GL_FALSE, glm::value_ptr(project));
glm::mat4 model = drag_rotation * model_rotation;
glViewport(0, 0, width, height);
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glUniformMatrix4fv(2, 1, GL_FALSE, glm::value_ptr(model));
glBindVertexArray(cube.vaoObject);
glDrawElements(GL_TRIANGLES, cube.noOfIndices, GL_UNSIGNED_INT, nullptr);
glUniformMatrix4fv(2, 1, GL_FALSE, glm::value_ptr(glm::scale(model, glm::vec3(2.5f))));
glBindVertexArray(circles.vaoObject);
glDrawElements(GL_LINES, circles.noOfIndices, GL_UNSIGNED_INT, nullptr);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
ShaderProgram ShaderProgram::newProgram(const std::string& vsh, const std::string& fsh)
{
ShaderProgram program;
auto shObjs = std::vector<GLuint>
{
program.compileShader(vsh, GL_VERTEX_SHADER),
program.compileShader(fsh, GL_FRAGMENT_SHADER),
};
for (auto shObj : shObjs)
program.compileStatus(shObj);
program.linkProgram(shObjs);
for (auto shObj : shObjs)
glDeleteShader(shObj);
return program;
}
GLuint ShaderProgram::compileShader(const std::string& sourceCode, GLenum shaderType)
{
auto shaderObj = glCreateShader(shaderType);
const char* srcCodePtr = sourceCode.c_str();
glShaderSource(shaderObj, 1, &srcCodePtr, nullptr);
glCompileShader(shaderObj);
return shaderObj;
}
void ShaderProgram::linkProgram(std::vector<GLuint> shObjs)
{
programObject = glCreateProgram();
for (auto shObj : shObjs)
glAttachShader(programObject, shObj);
glLinkProgram(programObject);
linkStatus();
}
void ShaderProgram::compileStatus(GLuint shader)
{
GLint status = GL_TRUE;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE)
{
GLint logLen;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLen);
std::vector< char >log(logLen);
GLsizei written;
glGetShaderInfoLog(shader, logLen, &written, log.data());
std::cout << "compile error:" << std::endl << log.data() << std::endl;
}
}
void ShaderProgram::linkStatus()
{
GLint status = GL_TRUE;
glGetProgramiv(programObject, GL_LINK_STATUS, &status);
if (status == GL_FALSE)
{
GLint logLen;
glGetProgramiv(programObject, GL_INFO_LOG_LENGTH, &logLen);
std::vector< char >log(logLen);
GLsizei written;
glGetProgramInfoLog(programObject, logLen, &written, log.data());
std::cout << "link error:" << std::endl << log.data() << std::endl;
}
}
VertexArrayObject VertexArrayObject::newCube()
{
static const std::vector<GLfloat> vertices{ -1, -1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1 };
static const std::vector<GLfloat> uv{ 0, 0, 1, 0, 1, 1, 0, 1 };
static const std::vector<size_t> faces{ 0, 1, 2, 3, 1, 5, 6, 2, 5, 4, 7, 6, 4, 0, 3, 7, 3, 2, 6, 7, 1, 0, 4, 5 };
std::vector<GLfloat> varray;
std::vector<GLuint> iarray;
for (auto si = 0; si < faces.size() / 4; si++)
{
for (auto qi = 0; qi < 4; qi++)
{
varray.insert(varray.end(), vertices.begin() + faces[si * 4 + qi] * 3, vertices.begin() + faces[si * 4 + qi] * 3 + 3);
std::vector<GLfloat> uvw{ 0, 0, (GLfloat)si * 4.0f / (GLfloat)faces.size() };
varray.insert(varray.end(), uvw.begin(), uvw.end());
}
std::vector<GLuint> indices{ 4u * si, 4u * si + 1, 4u * si + 2, 4u * si, 4u * si + 2, 4u * si + 3 };
iarray.insert(iarray.end(), indices.begin(), indices.end());
}
return newVAO(varray, iarray);
}
VertexArrayObject VertexArrayObject::newCircles()
{
const GLuint noC = 360;
std::vector<GLfloat> varray;
std::vector<GLuint> iarray;
for (int i = 0; i <= noC; i++)
{
GLfloat angle = static_cast<GLfloat>(i * 2 * M_PI / noC);
GLfloat c = cos(angle), s = sin(angle);
std::vector<GLfloat> va{ 0, c, s, 0, 0, 0, s, 0, c, 0, 0, 1.0f / 3.0f, c, s, 0, 0, 0, 2.0f / 3.0f };
varray.insert(varray.end(), va.begin(), va.end());
}
for (GLuint ci = 0; ci < 3; ci++)
{
for (GLuint i = 0; i <= noC; i++)
{
std::vector<GLuint> ia{ i * 3 + ci, ((i + 1) % noC) * 3 + ci };
iarray.insert(iarray.end(), ia.begin(), ia.end());
}
}
return newVAO(varray, iarray);
}
VertexArrayObject VertexArrayObject::newVAO(const std::vector<GLfloat>& varray, const std::vector<GLuint>& iarray)
{
VertexArrayObject vao;
vao.noOfIndices = static_cast<GLsizei>(iarray.size());
vao.noOfVertices = static_cast<GLsizei>(varray.size() / 6);
GLuint bufferObjects[2];
glGenBuffers(2, bufferObjects);;
glGenVertexArrays(1, &vao.vaoObject);
glBindVertexArray(vao.vaoObject);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, bufferObjects[0]);
glBufferData(GL_ARRAY_BUFFER, varray.size() * sizeof(*varray.data()), varray.data(), GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(*varray.data()), 0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(*varray.data()), (void*)(3 * sizeof(*varray.data())));
if (vao.noOfIndices > 0)
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferObjects[1]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, iarray.size() * sizeof(*iarray.data()), iarray.data(), GL_STATIC_DRAW);
}
glBindVertexArray(0);
glDeleteBuffers(2, bufferObjects);
return vao;
}
You kinda need to draw the ball to make it intuitive.
On mouse down, you put an anchor on the ball directly under the mouse pointer. If the click is outside the ball, then you use the closest point on the ball.
As the mouse moves, you rotate the ball so that the anchor point follows the shortest path so that it remains directly under the mouse pointer. If the mouse pointer is off the ball, then the closest point on the ball is used.
Maybe this will help.

Arc with radius between 2 points [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I need to find out how to draw an arc with OpenGL between 2 points with a given radius.Is there any way to do this in OpenGL or to find the center point where I need to draw the arc so the both points get connected with the given radius ? :)
Attached screenshot: https://i.imgur.com/LLP78Ak.png
Here is a simple, but complete and tested opengl program that demonstrates what it sounds like you are looking for. Note that there is not a single answer to the question of what is the arc between two points at radius x, since the arc can bend in either of two directions.
Pay careful attention to the second createArc function overload as this represents the core of the answer, though it calls the first createArc function overload to finish the job.
EDIT: I've realized that I did not account for the ambiguity of "arc between two angles" in my earlier answer (arc from 0 to 90 could be direct or all the way around). I've updated the code to define whether you are interested in the smaller arc or the larger arc.
#define GLEW_STATIC
#define _USE_MATH_DEFINES
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <gl/gl.h>
#include <math.h>
#include <iostream>
const int ARC_VERTEX_COUNT = 100;
// Don't use global variables at home, kids!
GLFWwindow* window;
GLuint shader;
GLint shaderLoc_pos;
GLuint vbo_circle;
GLuint vbo_arc;
float normalizeAngleToSmallestPositive(float angle) {
while (angle < 0.0) { angle += M_PI*2; }
while (angle >= M_PI*2) { angle -= M_PI*2; }
return angle;
}
bool startApp() {
if (!glfwInit()) {
return false;
}
window = glfwCreateWindow(500, 500, "Hello World", NULL, NULL);
if (!window) {
glfwTerminate();
return false;
}
glfwMakeContextCurrent(window);
glewInit();
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glLineWidth(10.0);
return true;
}
void stopApp() {
glfwTerminate();
}
void createShader() {
const char* vsSrc =
"#version 330 core\n"
"in vec2 pos; void main() { gl_Position = vec4(pos, 0.0, 1.0); }";
const char* fsSrc =
"#version 330 core\n"
"out vec4 color; void main() { color = vec4(1.0,1.0,1.0,0.5); }";
GLuint vs = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vs, 1, &vsSrc, nullptr);
glCompileShader(vs);
GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fs, 1, &fsSrc, nullptr);
glCompileShader(fs);
shader = glCreateProgram();
glAttachShader(shader, vs);
glAttachShader(shader, fs);
glLinkProgram(shader);
shaderLoc_pos = glGetAttribLocation(shader, "pos");
}
// Create an arc between two given angles, based on the circle described by the given radius and
// center point
GLuint createArc(float angle1, float angle2, float radius, float x, float y, float useBiggerArc) {
// Prepare angles
angle1 = normalizeAngleToSmallestPositive(angle1);
angle2 = normalizeAngleToSmallestPositive(angle2);
if (angle1 > angle2) {
float buffer = angle1;
angle1 = angle2;
angle2 = buffer;
}
if (useBiggerArc != angle2-angle1 > M_PI) {
angle1 += M_PI*2;
}
// Create opengl geometry
GLfloat pos[ARC_VERTEX_COUNT * 2];
for (int i = 0; i < ARC_VERTEX_COUNT; i++) {
pos[i*2] = sin((float)i / (ARC_VERTEX_COUNT-1) * (angle2 - angle1) + angle1) * radius + x;
pos[i*2+1] = cos((float)i / (ARC_VERTEX_COUNT-1) * (angle2 - angle1) + angle1) * radius + y;
}
GLuint result;
glGenBuffers(1, &result);
glBindBuffer(GL_ARRAY_BUFFER, result);
glBufferData(GL_ARRAY_BUFFER, sizeof(pos), pos, GL_STATIC_DRAW);
return result;
}
GLuint createCircle(float radius, float x, float y) {
return createArc(M_PI*0, M_PI*2, radius, x, y, true);
}
// Create an arc between two given points that is based on a circle with the given radius.
GLuint createArc(
float x1, float y1, float x2, float y2, float radius, bool arcDirection, bool useBiggerArc)
{
// distance between points
float distance = sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
// halfway point
float xAverage = (x1+x2)/2.0;
float yAverage = (y1+y2)/2.0;
// circle center
float xCenter = sqrt(radius*radius - distance*distance/4.0) * (y1-y2) / distance;
float yCenter = sqrt(radius*radius - distance*distance/4.0) * (x2-x1) / distance;
xCenter = xAverage + (arcDirection ? xCenter : -xCenter);
yCenter = yAverage + (arcDirection ? yCenter : -yCenter);
// angles
float angle1 = atan2(x1-xCenter, y1-yCenter);
float angle2 = atan2(x2-xCenter, y2-yCenter);
// create the arc
return createArc(angle1, angle2, radius, xCenter, yCenter, useBiggerArc);
}
void runMainLoop() {
while (!glfwWindowShouldClose(window)) {
int width, height;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(shader);
glEnableVertexAttribArray(shaderLoc_pos);
glBindBuffer(GL_ARRAY_BUFFER, vbo_circle);
glVertexAttribPointer(shaderLoc_pos, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
glDrawArrays(GL_LINE_STRIP, 0, ARC_VERTEX_COUNT);
glBindBuffer(GL_ARRAY_BUFFER, vbo_arc);
glVertexAttribPointer(shaderLoc_pos, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
glDrawArrays(GL_LINE_STRIP, 0, ARC_VERTEX_COUNT);
glfwSwapBuffers(window);
glfwPollEvents();
}
}
int main(void) {
if (startApp())
{
createShader();
vbo_circle = createCircle(0.75, 0.0, 0.0);
vbo_arc = createArc(0.0, 0.75, 0.75, 0.0, 0.75, false, false);
runMainLoop();
stopApp();
return 0;
}
else
{
return -1;
}
}
This is more of a maths question, I feel.
If you have the coordinates of the two points suppose:
and the given radius is 'R'
then the coordinates of the centre, say can be calculated using
where
,
there shall be two centres, one for an upward arc and another for a downward arc.
the other centre can be found through
now, you can find the inverse cosine using the acos() function included in the <cmath> library.

Set line colors in OpenGL 3+

how can I set the color for the lines I draw using openGL3 ?
the rendering function I'm using is the following
void renderVertex(std::vector<doubleVertex> &Poly, int32_t iniBound, int32_t endBound, int32_t Type){
for (int32_t i = iniBound; i < endBound; i++) {
GLfloat *ptr_polygonVertices;
ptr_polygonVertices = createPolygonVertices(Poly[i]);
// render OpenGL here
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, ptr_polygonVertices);
glDrawArrays(Type, 0, Poly[i].x.size() - 1);
glDisableClientState(GL_VERTEX_ARRAY);
delete[] ptr_polygonVertices;
}
}
Inside this loop
while (!glfwWindowShouldClose(window)) {
glClear(GL_COLOR_BUFFER_BIT);
renderVertex(Poly, 0, nBound, GL_LINE_LOOP);
// Swap front and back buffers
glfwSwapBuffers(window);
// Poll for and process events
glfwPollEvents();
}
If necessary, the complete code is the listed here:
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <math.h>
#include <stdlib.h>
#include "Globals.h"
GLfloat* createPolygonVertices(doubleVertex &Poly);
doubleVertex createCircle(double x, double y, double radius, int numberOfSides);
void windowInit(GLFWwindow *window);
void renderVertex(std::vector<doubleVertex> &Poly, int32_t iniBound, int32_t endBound, int32_t Type);
int main(void)
{
GLFWwindow *window;
// Initialize the library
if (!glfwInit())
exit(0);
// Create a windowed mode window and its OpenGL context
window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "Polygon Linear Infill", NULL, NULL);
windowInit(window);
////////////////////////////////////// Polygon Example //////////////////////////////////////////
std::vector<doubleVertex> Poly{
{
{ 0, 23.37, 50.24, 31.26, 34.57, 1.46, 4.69, 0 },
{ 0, 11.91, 0, -21.39, -32.22, -26.31, -13.17, 0 }
},
{
{ 42.19, 35.69, 29.76, 34.46, 42.19 },
{ -4.26, 2.34, -5.2, -11.87, -4.26 }
},
{
{ 23.57, 26.29, 11.94, 23.57 },
{ -26.73, -17.39, -18.38, -26.73 }
}
};
double x = 14.97, y = -5.28, r = 7.33;
Poly.push_back(createCircle(x, y, r, 37));
uint32_t i, nBound = Poly.size();
while (!glfwWindowShouldClose(window)) {
glClear(GL_COLOR_BUFFER_BIT);
renderVertex(Poly, 0, nBound, GL_LINE_LOOP);
// Swap front and back buffers
glfwSwapBuffers(window);
// Poll for and process events
glfwPollEvents();
}
glfwTerminate();
return 0;
}
GLfloat* createPolygonVertices(doubleVertex &Poly){
int32_t j, n_Vertex, cnt_polygonVertices=0;
n_Vertex = Poly.x.size();
GLfloat *polygonVertices;
polygonVertices = new GLfloat[(n_Vertex-1) * 2];
for (j = 0; j < n_Vertex-1; j++) {
polygonVertices[cnt_polygonVertices] = Poly.x[j];
cnt_polygonVertices++;
polygonVertices[cnt_polygonVertices] = Poly.y[j];
cnt_polygonVertices++;
}
return polygonVertices;
}
doubleVertex createCircle(double x, double y, double radius, int numberOfSides){
int numberOfVertices = numberOfSides + 2;
double twicePi = 2.0f * M_PI;
doubleVertex Poly;
for (int i = 0; i < numberOfVertices; i++)
{
Poly.x.push_back(x + (radius * cos(i * twicePi / numberOfSides)));
Poly.y.push_back(y + (radius * sin(i * twicePi / numberOfSides)));
}
return Poly;
}
void windowInit(GLFWwindow *window){
if (!window) {
glfwTerminate();
exit(0);
}
// Make the window's context current
glfwMakeContextCurrent(window);
glViewport(0.0f, 0.0f, SCREEN_WIDTH, SCREEN_HEIGHT); // specifies the part of the window to which OpenGL will draw (in pixels), convert from normalised to pixels
glMatrixMode(GL_PROJECTION); // projection matrix defines the properties of the camera that views the objects in the world coordinate frame. Here you typically set the zoom factor, aspect ratio and the near and far clipping planes
glLoadIdentity(); // replace the current matrix with the identity matrix and starts us a fresh because matrix transforms such as glOrpho and glRotate cumulate, basically puts us at (0, 0, 0)
glOrtho(0, 51, -33, 12, 0, 1); // essentially set coordinate system
glMatrixMode(GL_MODELVIEW); // (default matrix mode) modelview matrix defines how your objects are transformed (meaning translation, rotation and scaling) in your world
glLoadIdentity(); // same as above comment
}
void renderVertex(std::vector<doubleVertex> &Poly, int32_t iniBound, int32_t endBound, int32_t Type){
for (int32_t i = iniBound; i < endBound; i++) {
GLfloat *ptr_polygonVertices;
ptr_polygonVertices = createPolygonVertices(Poly[i]);
// render OpenGL here
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, ptr_polygonVertices);
glDrawArrays(Type, 0, Poly[i].x.size() - 1);
glDisableClientState(GL_VERTEX_ARRAY);
delete[] ptr_polygonVertices;
}
}
Thanks in advance!

ID3DX11EffectPass GetDesc Access Violation

Hi I just got Introduction to 3D Game Programming with DirectX 11 and am trying to get the BoxDemo code working, however I am having troubles with the effect.
Basically the compiled shader part works, and even the creation of the effect works but when it comes to getting the description from the effect pass, I get a Access Violation error, I have tried, and researched online but can't find any help for this matter.
Please note I have the latest version of effects11.
Here is the fx:
//***************************************************************************** **********
// color.fx by Frank Luna (C) 2011 All Rights Reserved.
//
// Transforms and colors geometry.
//***************************************************************************************
cbuffer cbPerObject
{
float4x4 gWorldViewProj;
};
struct VertexIn
{
float3 PosL : POSITION;
float4 Color : COLOR;
};
struct VertexOut
{
float4 PosH : SV_POSITION;
float4 Color : COLOR;
};
VertexOut VS(VertexIn vin)
{
VertexOut vout;
// Transform to homogeneous clip space.
vout.PosH = mul(float4(vin.PosL, 1.0f), gWorldViewProj);
// Just pass vertex color into the pixel shader.
vout.Color = vin.Color;
return vout;
}
float4 PS(VertexOut pin) : SV_Target
{
return pin.Color;
}
technique11 ColorTech
{
pass P0
{
SetVertexShader(CompileShader(vs_5_0, VS()));
SetGeometryShader(NULL);
SetPixelShader(CompileShader(ps_5_0, PS()));
}
}
here is the cpp file:
#include "BoxApp.h"
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance,
PSTR cmdLine, int showCmd)
{
// Enable run-time memory check for debug builds.
#if defined(DEBUG) | defined(_DEBUG)
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
BoxApp theApp(hInstance);
if (!theApp.Init())
return 0;
return theApp.Run();
}
BoxApp::BoxApp(HINSTANCE hInstance)
: D3DApp(hInstance), mBoxVB(0), mBoxIB(0), mFX(0), mTech(0),
mfxWorldViewProj(0), mInputLayout(0),
mTheta(1.5f*MathHelper::Pi), mPhi(0.25f*MathHelper::Pi), mRadius(5.0f)
{
mMainWndCaption = L"Box Demo";
mLastMousePos.x = 0;
mLastMousePos.y = 0;
XMMATRIX I = XMMatrixIdentity();
XMStoreFloat4x4(&mWorld, I);
XMStoreFloat4x4(&mView, I);
XMStoreFloat4x4(&mProj, I);
}
BoxApp::~BoxApp()
{
ReleaseCOM(mBoxVB);
ReleaseCOM(mBoxIB);
ReleaseCOM(mFX);
ReleaseCOM(mInputLayout);
}
bool BoxApp::Init()
{
if (!D3DApp::Init())
return false;
BuildGeometryBuffers();
BuildFX();
BuildVertexLayout();
return true;
}
void BoxApp::OnResize()
{
D3DApp::OnResize();
// The window resized, so update the aspect ratio and recompute the projection matrix.
XMMATRIX P = XMMatrixPerspectiveFovLH(0.25f*MathHelper::Pi, AspectRatio(), 1.0f, 1000.0f);
XMStoreFloat4x4(&mProj, P);
}
void BoxApp::UpdateScene(float dt)
{
// Convert Spherical to Cartesian coordinates.
float x = mRadius*sinf(mPhi)*cosf(mTheta);
float z = mRadius*sinf(mPhi)*sinf(mTheta);
float y = mRadius*cosf(mPhi);
// Build the view matrix.
XMVECTOR pos = XMVectorSet(x, y, z, 1.0f);
XMVECTOR target = XMVectorZero();
XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
XMMATRIX V = XMMatrixLookAtLH(pos, target, up);
XMStoreFloat4x4(&mView, V);
}
void BoxApp::DrawScene()
{
md3dImmediateContext->ClearRenderTargetView(mRenderTargetView, reinterpret_cast<const float*>(&Colors::LightSteelBlue));
md3dImmediateContext->ClearDepthStencilView(mDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
md3dImmediateContext->IASetInputLayout(mInputLayout);
md3dImmediateContext- >IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
UINT stride = sizeof(Vertex);
UINT offset = 0;
md3dImmediateContext->IASetVertexBuffers(0, 1, &mBoxVB, &stride, &offset);
md3dImmediateContext->IASetIndexBuffer(mBoxIB, DXGI_FORMAT_R32_UINT, 0);
// Set constants
XMMATRIX world = XMLoadFloat4x4(&mWorld);
XMMATRIX view = XMLoadFloat4x4(&mView);
XMMATRIX proj = XMLoadFloat4x4(&mProj);
XMMATRIX worldViewProj = world*view*proj;
mfxWorldViewProj->SetMatrix(reinterpret_cast<float*>(&worldViewProj));
D3DX11_TECHNIQUE_DESC techDesc;
mTech->GetDesc(&techDesc);
for (UINT p = 0; p < techDesc.Passes; ++p)
{
mTech->GetPassByIndex(p)->Apply(0, md3dImmediateContext);
// 36 indices for the box.
md3dImmediateContext->DrawIndexed(36, 0, 0);
}
HRESULT hr = (mSwapChain->Present(0, 0));
}
void BoxApp::OnMouseDown(WPARAM btnState, int x, int y)
{
mLastMousePos.x = x;
mLastMousePos.y = y;
SetCapture(mhMainWnd);
}
void BoxApp::OnMouseUp(WPARAM btnState, int x, int y)
{
ReleaseCapture();
}
void BoxApp::OnMouseMove(WPARAM btnState, int x, int y)
{
if ((btnState & MK_LBUTTON) != 0)
{
// Make each pixel correspond to a quarter of a degree.
float dx = XMConvertToRadians(0.25f*static_cast<float>(x - mLastMousePos.x));
float dy = XMConvertToRadians(0.25f*static_cast<float>(y - mLastMousePos.y));
// Update angles based on input to orbit camera around box.
mTheta += dx;
mPhi += dy;
// Restrict the angle mPhi.
mPhi = MathHelper::Clamp(mPhi, 0.1f, MathHelper::Pi - 0.1f);
}
else if ((btnState & MK_RBUTTON) != 0)
{
// Make each pixel correspond to 0.005 unit in the scene.
float dx = 0.005f*static_cast<float>(x - mLastMousePos.x);
float dy = 0.005f*static_cast<float>(y - mLastMousePos.y);
// Update the camera radius based on input.
mRadius += dx - dy;
// Restrict the radius.
mRadius = MathHelper::Clamp(mRadius, 3.0f, 15.0f);
}
mLastMousePos.x = x;
mLastMousePos.y = y;
}
void BoxApp::BuildGeometryBuffers()
{
// Create vertex buffer
Vertex vertices[] =
{
{ XMFLOAT3(-1.0f, -1.0f, -1.0f), (const float*)&Colors::White },
{ XMFLOAT3(-1.0f, +1.0f, -1.0f), (const float*)&Colors::Black },
{ XMFLOAT3(+1.0f, +1.0f, -1.0f), (const float*)&Colors::Red },
{ XMFLOAT3(+1.0f, -1.0f, -1.0f), (const float*)&Colors::Green },
{ XMFLOAT3(-1.0f, -1.0f, +1.0f), (const float*)&Colors::Blue },
{ XMFLOAT3(-1.0f, +1.0f, +1.0f), (const float*)&Colors::Yellow },
{ XMFLOAT3(+1.0f, +1.0f, +1.0f), (const float*)&Colors::Cyan },
{ XMFLOAT3(+1.0f, -1.0f, +1.0f), (const float*)&Colors::Magenta }
};
D3D11_BUFFER_DESC vbd;
vbd.Usage = D3D11_USAGE_IMMUTABLE;
vbd.ByteWidth = sizeof(Vertex) * 8;
vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vbd.CPUAccessFlags = 0;
vbd.MiscFlags = 0;
vbd.StructureByteStride = 0;
D3D11_SUBRESOURCE_DATA vinitData;
vinitData.pSysMem = vertices;
HRESULT hr1 = (md3dDevice->CreateBuffer(&vbd, &vinitData, &mBoxVB));
// Create the index buffer
UINT indices[] = {
// front face
0, 1, 2,
0, 2, 3,
// back face
4, 6, 5,
4, 7, 6,
// left face
4, 5, 1,
4, 1, 0,
// right face
3, 2, 6,
3, 6, 7,
// top face
1, 5, 6,
1, 6, 2,
// bottom face
4, 0, 3,
4, 3, 7
};
D3D11_BUFFER_DESC ibd;
ibd.Usage = D3D11_USAGE_IMMUTABLE;
ibd.ByteWidth = sizeof(UINT) * 36;
ibd.BindFlags = D3D11_BIND_INDEX_BUFFER;
ibd.CPUAccessFlags = 0;
ibd.MiscFlags = 0;
ibd.StructureByteStride = 0;
D3D11_SUBRESOURCE_DATA iinitData;
iinitData.pSysMem = indices;
HRESULT hr2 = (md3dDevice->CreateBuffer(&ibd, &iinitData, &mBoxIB));
}
void BoxApp::BuildFX()
{
DWORD shaderFlags = 0;
//#if defined( DEBUG ) || defined( _DEBUG )
// shaderFlags |= D3D10_SHADER_DEBUG;
// shaderFlags |= D3D10_SHADER_SKIP_OPTIMIZATION;
//#endif
ID3D10Blob* compiledShader = 0;
ID3D10Blob* compilationMsgs = 0;
HRESULT hr;
hr = D3DX11CompileFromFile(L"color.fx", NULL, NULL, "ColorTech", "fx_5_0"
, shaderFlags, 0, 0, &compiledShader, &compilationMsgs, &hr);
// compilationMsgs can store errors or warnings.
if (compilationMsgs != 0)
{
MessageBoxA(0, (char*)compilationMsgs->GetBufferPointer(), 0, 0);
ReleaseCOM(compilationMsgs);
}
// Even if there are no compilationMsgs, check to make sure there were no other errors.
if (FAILED(hr))
{
//DXTrace(__FILE__, (DWORD)__LINE__, hr, L"D3DX11CompileFromFile", true);
}
ID3D10Blob* pErrorBlob = 0;
//ID3DInclude* include = D3D_COMPILE_STANDARD_FILE_INCLUDE;
HRESULT hr3 = (D3DX11CreateEffectFromMemory(compiledShader->GetBufferPointer(), compiledShader->GetBufferSize(),
0, md3dDevice, &mFX));
//HRESULT hr3 = (D3DX11CreateEffectFromFile(L"color.fx", shaderFlags, md3dDevice, &mFX));
// Done with compiled shader.
ReleaseCOM(compiledShader);
mTech = mFX->GetTechniqueByName("ColorTech");
mfxWorldViewProj = mFX->GetVariableByName("gWorldViewProj")->AsMatrix();
}
void BoxApp::BuildVertexLayout()
{
// Create the vertex input layout.
D3D11_INPUT_ELEMENT_DESC vertexDesc[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
// Create the input layout
D3DX11_PASS_DESC passDesc;
ID3DX11EffectPass* pass = mTech->GetPassByIndex(0);
if (pass != nullptr)
{
HRESULT hr5 = pass->GetDesc(&passDesc);
HRESULT hr4 = (md3dDevice->CreateInputLayout(vertexDesc, 2, passDesc.pIAInputSignature,
passDesc.IAInputSignatureSize, &mInputLayout));
}
}
You've commented out all the error checks, so it's probably that D3DX11CreateEffectFromMemory returned a failure. If a function returns an HRESULT, you must check it at runtime or you will miss potential errors. That means using the FAILED macro, the SUCCEEDED macro, or the ThrowIfFailed helper on every function that returns an HRESULT. See MSDN.
Since you are making use of the Effects for Direct3D 11 library, you should pick up the latest version from GitHub. If you are using VS 2013 or VS 2015 for a Windows desktop app, you can also get it from NuGet.
You should also read this post which has some additional notes about the Introduction to 3D Game Programming with DirectX 11 book. It's a good book, but unfortunately it was published just before the DirectX development story was changed rather radically with the deprecation of the DirectX SDK. See MSDN.
You should also take a look at the DirectX Tool Kit tutorials, particularly the material on ComPtr.
Ok finally here is the final code
BoxDemoApp.h:
#pragma once
//#pragma comment(lib, "Effects11.lib")
#pragma comment(lib, "d3d11.lib")
//#pragma comment(lib, "d3dx11.lib")
//#pragma comment(lib, "DxErr.lib")
//#pragma comment(lib, "D3DCompiler.lib")
//#pragma comment(lib, "dxguid.lib")
#include <windows.h>
#include <d3d11_1.h>
#include "d3dApp.h"
#include "d3dx11effect.h"
#include "MathHelper.h"
#include "StaticCamera.h"
#include "Conversion.h"
#include "DefinedModel.h"
#include <iostream>
using namespace std;
class BoxDemoApp : public D3DApp
{
public:
BoxDemoApp(HINSTANCE hInstance);
~BoxDemoApp();
bool Init();
bool InitScene();
void OnResize();
void UpdateScene(float dt);
void DrawScene();
private:
DefinedModel* m_Model;
bool m_bLoaded;
bool m_bInitModel;
};
BoxDemoApp.cpp:
#include "BoxDemoApp.h"
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance,
PSTR cmdLine, int showCmd)
{
// Enable run-time memory check for debug builds.
#if defined(DEBUG) | defined(_DEBUG)
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
BoxDemoApp theApp(hInstance);
if (!theApp.Init())
return 0;
return theApp.Run();
}
BoxDemoApp::BoxDemoApp(HINSTANCE hInstance)
: D3DApp(hInstance)
{
mMainWndCaption = L"Box Demo";
m_bLoaded = false;
m_bInitModel = false;
m_Model = NULL;
}
BoxDemoApp::~BoxDemoApp()
{
m_Model->Destroy();
SafeDelete(m_Model);
}
bool BoxDemoApp::Init()
{
if (!D3DApp::Init())
return false;
InitScene();
return true;
}
bool BoxDemoApp::InitScene()
{
//Camera information
m_Camera->setCamera(XMFLOAT4(0.0f, 3.0f, -8.0f, 0.0f),
XMFLOAT4(0.0f, 0.0f, 0.0f, 0.0f),
XMFLOAT4(0.0f, 1.0f, 0.0f, 0.0f));
//Set the Projection matrix
m_Camera->setFOV(0.4f*3.14f, (float)mClientWidth / mClientHeight, 1.0f, 1000.0f);
///////////////**************new**************////////////////////
return true;
}
void BoxDemoApp::OnResize()
{
D3DApp::OnResize();
//Create the Viewport
D3D11_VIEWPORT viewport;
ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));
viewport.TopLeftX = 0;
viewport.TopLeftY = 0;
viewport.Width = this->mClientWidth;
viewport.Height = this->mClientHeight;
//Set the Viewport
md3dImmediateContext->RSSetViewports(1, &viewport);
//Set the Projection matrix
m_Camera->setFOV(0.4f*3.14f, (float)mClientWidth / mClientHeight, 1.0f, 1000.0f);
///////////////**************new**************////////////////////
}
void BoxDemoApp::UpdateScene(float dt)
{
if (m_bLoaded && !m_bInitModel)
{
m_Model = new DefinedModel(this);
m_Model->create3DCube(4, 4, 4);
m_bInitModel = true;
}
}
void BoxDemoApp::DrawScene()
{
assert(md3dImmediateContext);
assert(mSwapChain);
md3dImmediateContext->ClearRenderTargetView(mRenderTargetView, reinterpret_cast<const float*>(&Colors::LightSteelBlue));
md3dImmediateContext->ClearDepthStencilView(mDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
if (m_bInitModel)
{
m_Model->Draw();
}
if (!m_bLoaded)
{
m_bLoaded = true;
}
HRESULT hr = (mSwapChain->Present(0, 0));
}
MathHelper.h:
//***************************************************************************************
// MathHelper.h by Frank Luna (C) 2011 All Rights Reserved.
//
// Helper math class.
//***************************************************************************************
#pragma once
#ifndef MATHHELPER_H
#define MATHHELPER_H
#include <Windows.h>
#include <xnamath.h>
class MathHelper
{
public:
// Returns random float in [0, 1).
static float RandF()
{
return (float)(rand()) / (float)RAND_MAX;
}
// Returns random float in [a, b).
static float RandF(float a, float b)
{
return a + RandF()*(b - a);
}
template<typename T>
static T Min(const T& a, const T& b)
{
return a < b ? a : b;
}
template<typename T>
static T Max(const T& a, const T& b)
{
return a > b ? a : b;
}
template<typename T>
static T Lerp(const T& a, const T& b, float t)
{
return a + (b - a)*t;
}
template<typename T>
static T Clamp(const T& x, const T& low, const T& high)
{
return x < low ? low : (x > high ? high : x);
}
// Returns the polar angle of the point (x,y) in [0, 2*PI).
static float AngleFromXY(float x, float y);
static XMMATRIX InverseTranspose(CXMMATRIX M)
{
// Inverse-transpose is just applied to normals. So zero out
// translation row so that it doesn't get into our inverse-transpose
// calculation--we don't want the inverse-transpose of the translation.
XMMATRIX A = M;
A.r[3] = XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f);
XMVECTOR det = XMMatrixDeterminant(A);
return XMMatrixTranspose(XMMatrixInverse(&det, A));
}
static XMVECTOR RandUnitVec3();
static XMVECTOR RandHemisphereUnitVec3(XMVECTOR n);
static const float Infinity;
static const float Pi;
};
#endif // MATHHELPER_H
MathHelper.cpp:
//***************************************************************************************
// MathHelper.cpp by Frank Luna (C) 2011 All Rights Reserved.
//***************************************************************************************
#include "MathHelper.h"
#include <float.h>
#include <cmath>
const float MathHelper::Infinity = FLT_MAX;
const float MathHelper::Pi = 3.1415926535f;
float MathHelper::AngleFromXY(float x, float y)
{
float theta = 0.0f;
// Quadrant I or IV
if (x >= 0.0f)
{
// If x = 0, then atanf(y/x) = +pi/2 if y > 0
// atanf(y/x) = -pi/2 if y < 0
theta = atanf(y / x); // in [-pi/2, +pi/2]
if (theta < 0.0f)
theta += 2.0f*Pi; // in [0, 2*pi).
}
// Quadrant II or III
else
theta = atanf(y / x) + Pi; // in [0, 2*pi).
return theta;
}
XMVECTOR MathHelper::RandUnitVec3()
{
XMVECTOR One = XMVectorSet(1.0f, 1.0f, 1.0f, 1.0f);
XMVECTOR Zero = XMVectorZero();
// Keep trying until we get a point on/in the hemisphere.
while (true)
{
// Generate random point in the cube [-1,1]^3.
XMVECTOR v = XMVectorSet(MathHelper::RandF(-1.0f, 1.0f), MathHelper::RandF(-1.0f, 1.0f), MathHelper::RandF(-1.0f, 1.0f), 0.0f);
// Ignore points outside the unit sphere in order to get an even distribution
// over the unit sphere. Otherwise points will clump more on the sphere near
// the corners of the cube.
if (XMVector3Greater(XMVector3LengthSq(v), One))
continue;
return XMVector3Normalize(v);
}
}
XMVECTOR MathHelper::RandHemisphereUnitVec3(XMVECTOR n)
{
XMVECTOR One = XMVectorSet(1.0f, 1.0f, 1.0f, 1.0f);
XMVECTOR Zero = XMVectorZero();
// Keep trying until we get a point on/in the hemisphere.
while (true)
{
// Generate random point in the cube [-1,1]^3.
XMVECTOR v = XMVectorSet(MathHelper::RandF(-1.0f, 1.0f), MathHelper::RandF(-1.0f, 1.0f), MathHelper::RandF(-1.0f, 1.0f), 0.0f);
// Ignore points outside the unit sphere in order to get an even distribution
// over the unit sphere. Otherwise points will clump more on the sphere near
// the corners of the cube.
if (XMVector3Greater(XMVector3LengthSq(v), One))
continue;
// Ignore points in the bottom hemisphere.
if (XMVector3Less(XMVector3Dot(n, v), Zero))
continue;
return XMVector3Normalize(v);
}
}
StaticCamera.h:
#pragma once
#include "MathHelper.h"
#include "Conversion.h"
class StaticCamera
{
public:
StaticCamera();
~StaticCamera();
XMMATRIX* WVP();
XMMATRIX* World();
XMMATRIX* camView();
XMMATRIX* camProjection();
XMVECTOR* camPosition();
XMVECTOR* camTarget();
XMVECTOR* camUp();
void WVP(XMMATRIX WVP);
void World(XMMATRIX World);
void setFOV(float FOV, float aspectRatio, float nearZ, float farZ);
void setCamera(XMFLOAT4 position, XMFLOAT4 Target, XMFLOAT4 Up);
void updateMatrix();
private:
///////////////**************new**************////////////////////
XMMATRIX m_WVP;
XMMATRIX m_World;
XMMATRIX m_camView;
XMMATRIX m_camProjection;
XMVECTOR m_camPosition;
XMVECTOR m_camTarget;
XMVECTOR m_camUp;
///////////////**************new**************////////////////////
};
StaticCamera.cpp:
#include "StaticCamera.h"
StaticCamera::StaticCamera()
{
}
StaticCamera::~StaticCamera()
{
}
XMMATRIX* StaticCamera::WVP()
{
return &m_WVP;
}
XMMATRIX* StaticCamera::World()
{
return &m_World;
}
XMMATRIX* StaticCamera::camView()
{
return &m_camView;
}
XMMATRIX* StaticCamera::camProjection()
{
return &m_camProjection;
}
XMVECTOR* StaticCamera::camPosition()
{
return &m_camPosition;
}
XMVECTOR* StaticCamera::camTarget()
{
return &m_camTarget;
}
XMVECTOR* StaticCamera::camUp()
{
return &m_camUp;
}
void StaticCamera::WVP(XMMATRIX WVP)
{
m_WVP = WVP;
}
void StaticCamera::World(XMMATRIX World)
{
m_World = World;
}
void StaticCamera::setFOV(float FOV, float aspectRatio, float nearZ, float farZ)
{
//Set the Projection matrix
m_camProjection = XMMatrixPerspectiveFovLH(FOV, aspectRatio, nearZ, farZ);
updateMatrix();
}
void StaticCamera::setCamera(XMFLOAT4 position, XMFLOAT4 Target, XMFLOAT4 Up)
{
//Camera information
m_camPosition = Conversion::XMFLOAT4TOXMVECTOR(position);
m_camTarget = Conversion::XMFLOAT4TOXMVECTOR(Target);
m_camUp = Conversion::XMFLOAT4TOXMVECTOR(Up);
//Set the View matrix
m_camView = XMMatrixLookAtLH(m_camPosition, m_camTarget, m_camUp);
///////////////**************new**************////////////////////
updateMatrix();
}
void StaticCamera::updateMatrix()
{
m_World = XMMatrixIdentity();
m_WVP = (m_World * m_camView * m_camProjection);
}
Conversion.h:
#pragma once
#include "MathHelper.h"
#include <vector>
using namespace std;
static class Conversion
{
public:
static XMFLOAT4 XMVECTORTOXMFLOAT4(XMVECTOR Xmvector);
static XMFLOAT3 XMVECTORTOXMFLOAT3(XMVECTOR Xmvector);
static XMVECTOR XMFLOAT4TOXMVECTOR(XMFLOAT4 Xmfloat);
static void INTVECTORTOARRAY(std::vector<int> vector, int *arr);
static LPCWSTR STRINGTOLPCWSTR(std::string stdstr);
};
Conversion.cpp:
#include "Conversion.h"
XMFLOAT4 Conversion::XMVECTORTOXMFLOAT4(XMVECTOR Xmvector)
{
XMFLOAT4 pos;
XMStoreFloat4(&pos, Xmvector);
return pos;
}
XMFLOAT3 Conversion::XMVECTORTOXMFLOAT3(XMVECTOR Xmvector)
{
XMFLOAT3 pos;
XMStoreFloat3(&pos, Xmvector);
return pos;
}
XMVECTOR Conversion::XMFLOAT4TOXMVECTOR(XMFLOAT4 Xmfloat)
{
return XMLoadFloat4(&Xmfloat);
}
void Conversion::INTVECTORTOARRAY(std::vector<int> vector, int *arr)
{
arr = &vector[0];
}
LPCWSTR Conversion::STRINGTOLPCWSTR(std::string stdstr)
{
std::wstring stemp = std::wstring(stdstr.begin(), stdstr.end());
LPCWSTR sw = stemp.c_str();
return sw;
}
DefinedModel.h:
#pragma once
#include <windows.h>
#include <d3d11_1.h>
#include "ShaderHelper.h"
#include "d3dx11effect.h"
#include "Conversion.h"
#include "Vector3.h"
#include "d3dApp.h"
class DefinedModel
{
public:
enum RastMode {
Solid,
Wireframe
};
public:
DefinedModel(D3DApp* parent);
~DefinedModel();
protected:
D3DApp* m_pParent;
//Vertex Structure and Vertex Layout (Input Layout)//
struct Vertex //Overloaded Vertex Structure
{
Vertex() {}
Vertex(float x, float y, float z,
float cr, float cg, float cb, float ca)
: pos(x, y, z), color(cr, cg, cb, ca) {}
XMFLOAT3 pos;
XMFLOAT4 color;
};
std::vector<Vertex> m_VertexArray;
std::vector<int> m_indices;
struct cbPerObject
{
XMMATRIX WVP;
};
cbPerObject cbPerObj;
ID3D11Buffer* cbPerObjectBuffer;
ID3D11Buffer* squareIndexBuffer;
ID3D11Buffer* squareVertBuffer;
ID3D11VertexShader* VS;
ID3D11PixelShader* PS;
ID3D10Blob* VS_Buffer;
ID3D10Blob* PS_Buffer;
ID3D11InputLayout* vertLayout;
///////////////**************new**************////////////////////
Vector3 m_Rotation;
Vector3 m_Scale;
Vector3 m_Offset;
XMMATRIX m_modelWorld;
///////////////**************new**************////////////////////
RastMode m_RastMode;
ID3D11RasterizerState* m_RastState;
public:
virtual void create3DCube(float Width, float Height, float Depth);
void Init();
void Draw();
void Rotation(float X, float Y, float Z);
void Scale(float X, float Y, float Z);
void Offset(float X, float Y, float Z);
void rastMode(RastMode rastmode);
Vector3 Rotation();
Vector3 Scale();
Vector3 Offset();
XMMATRIX worldMatrix();
void Destroy();
private:
virtual void InitBuffers();
virtual void InitFX();
virtual void InitInputLayout();
virtual void InitCBBuffer();
};
DefinedModel.cpp:
#include "DefinedModel.h"
DefinedModel::DefinedModel(D3DApp* parent): m_pParent(parent)
{
m_VertexArray = std::vector<Vertex>();
m_indices = std::vector<int>();
m_modelWorld = XMMatrixIdentity();
Offset(0, 0, 0);
Scale(1, 1, 1);
Rotation(0, 0, 0);
rastMode(RastMode::Solid);
}
DefinedModel::~DefinedModel()
{
}
void DefinedModel::create3DCube(float Width, float Height, float Depth)
{
///////////////**************new**************////////////////////
//Create the vertex buffer
m_VertexArray = {
Vertex(-Width / 2, -Height / 2, -Depth / 2, 1.0f, 0.0f, 0.0f, 1.0f),
Vertex(-Width / 2, +Height / 2, -Depth / 2, 0.0f, 1.0f, 0.0f, 1.0f),
Vertex(+Width / 2, +Height / 2, -Depth / 2, 0.0f, 0.0f, 1.0f, 1.0f),
Vertex(+Width / 2, -Height / 2, -Depth / 2, 1.0f, 1.0f, 0.0f, 1.0f),
Vertex(-Width / 2, -Height / 2, +Depth / 2, 0.0f, 1.0f, 1.0f, 1.0f),
Vertex(-Width / 2, +Height / 2, +Depth / 2, 1.0f, 1.0f, 1.0f, 1.0f),
Vertex(+Width / 2, +Height / 2, +Depth / 2, 1.0f, 0.0f, 1.0f, 1.0f),
Vertex(+Width / 2, -Height / 2, +Depth / 2, 1.0f, 0.0f, 0.0f, 1.0f),
};
///////////////**************new**************////////////////////
m_indices = {
// front face
0, 1, 2,
0, 2, 3,
// back face
4, 6, 5,
4, 7, 6,
// left face
4, 5, 1,
4, 1, 0,
// right face
3, 2, 6,
3, 6, 7,
// top face
1, 5, 6,
1, 6, 2,
// bottom face
4, 0, 3,
4, 3, 7
};
Init();
}
void DefinedModel::Init()
{
InitBuffers();
InitFX();
InitInputLayout();
InitCBBuffer();
}
void DefinedModel::InitBuffers()
{
HRESULT hr;
//index buffer creation
D3D11_BUFFER_DESC indexBufferDesc;
ZeroMemory(&indexBufferDesc, sizeof(indexBufferDesc));
indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = sizeof(DWORD) * 12 * 3;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
indexBufferDesc.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA iinitData;
iinitData.pSysMem = &m_indices[0];
hr = m_pParent->Device()->CreateBuffer(&indexBufferDesc, &iinitData, &squareIndexBuffer);
//vertex buffer creation
D3D11_BUFFER_DESC vertexBufferDesc;
ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));
vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
vertexBufferDesc.ByteWidth = sizeof(Vertex) * 8;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = 0;
vertexBufferDesc.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA vertexBufferData;
ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));
vertexBufferData.pSysMem = &m_VertexArray[0];
hr = m_pParent->Device()->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &squareVertBuffer);
}
void DefinedModel::InitFX()
{
HRESULT hr;
//Compile Shaders from shader file
hr = D3DX11CompileFromFile(L"Trans.fx", 0, 0, "VS", "vs_4_0", 0, 0, 0, &VS_Buffer, 0, 0);
hr = D3DX11CompileFromFile(L"Trans.fx", 0, 0, "PS", "ps_4_0", 0, 0, 0, &PS_Buffer, 0, 0);
//Create the Shader Objects
hr = m_pParent->Device()->CreateVertexShader(VS_Buffer->GetBufferPointer(), VS_Buffer->GetBufferSize(), NULL, &VS);
hr = m_pParent->Device()->CreatePixelShader(PS_Buffer->GetBufferPointer(), PS_Buffer->GetBufferSize(), NULL, &PS);
//Set Vertex and Pixel Shaders
m_pParent->DeviceContext()->VSSetShader(VS, 0, 0);
m_pParent->DeviceContext()->PSSetShader(PS, 0, 0);
}
void DefinedModel::InitInputLayout()
{
HRESULT hr;
D3D11_INPUT_ELEMENT_DESC layout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
UINT numElements = ARRAYSIZE(layout);
//Create the Input Layout
hr = m_pParent->Device()->CreateInputLayout(layout, numElements, VS_Buffer->GetBufferPointer(),
VS_Buffer->GetBufferSize(), &vertLayout);
}
void DefinedModel::InitCBBuffer()
{
HRESULT hr;
//Create the buffer to send to the cbuffer in effect file
D3D11_BUFFER_DESC cbbd;
ZeroMemory(&cbbd, sizeof(D3D11_BUFFER_DESC));
cbbd.Usage = D3D11_USAGE_DEFAULT;
cbbd.ByteWidth = sizeof(cbPerObject);
cbbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbbd.CPUAccessFlags = 0;
cbbd.MiscFlags = 0;
hr = m_pParent->Device()->CreateBuffer(&cbbd, NULL, &cbPerObjectBuffer);
}
void DefinedModel::Draw()
{
//set index buffer
m_pParent->DeviceContext()->IASetIndexBuffer(squareIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
//Set the vertex buffer
UINT stride = sizeof(Vertex);
UINT offset = 0;
m_pParent->DeviceContext()->IASetVertexBuffers(0, 1, &squareVertBuffer, &stride, &offset);
//Set the Input Layout
m_pParent->DeviceContext()->IASetInputLayout(vertLayout);
//Set Primitive Topology
m_pParent->DeviceContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
//set rasteriser state
m_pParent->DeviceContext()->RSSetState(m_RastState);
//Matrices
///////////////**************new**************////////////////////
//Set the WVP matrix and send it to the constant buffer in effect file
XMMATRIX WVP = (worldMatrix()) * (*m_pParent->Camera()->camView()) * (*m_pParent->Camera()->camProjection());
cbPerObj.WVP = XMMatrixTranspose(WVP);
m_pParent->DeviceContext()->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
m_pParent->DeviceContext()->VSSetConstantBuffers(0, 1, &cbPerObjectBuffer);
//draw shape
m_pParent->DeviceContext()->DrawIndexed(m_indices.size(), 0, 0);
}
void DefinedModel::Rotation(float X, float Y, float Z)
{
m_Rotation = Vector3(X, Y, Z);
//m_Rotation.X = X;
//m_Rotation.Y = Y;
//m_Rotation.Z = Z;
}
void DefinedModel::Scale(float X, float Y, float Z)
{
m_Scale = Vector3(X, Y, Z);
//m_Scale.X = X;
//m_Scale.Y = Y;
//m_Scale.Z = Z;
}
void DefinedModel::Offset(float X, float Y, float Z)
{
m_Offset = Vector3(X, Y, Z);
//m_Offset.X = X;
//m_Offset.Y = Y;
//m_Offset.Z = Z;
}
Vector3 DefinedModel::Rotation()
{
return m_Rotation;
}
Vector3 DefinedModel::Scale()
{
return m_Scale;
}
Vector3 DefinedModel::Offset()
{
return m_Offset;
}
XMMATRIX DefinedModel::worldMatrix()
{
XMMATRIX Scale = XMMatrixScaling(m_Scale.X(), m_Scale.Y(), m_Scale.Z());
XMMATRIX Rot = (XMMatrixRotationX(m_Rotation.X())) * (XMMatrixRotationY(m_Rotation.Y())) * (XMMatrixRotationZ(m_Rotation.Z()));
XMMATRIX Trans = XMMatrixTranslation(m_Offset.X(), m_Offset.Y(), m_Offset.Z());
// orbital
//m_modelWorld = Trans * Rot * Scale;
//on spot
m_modelWorld = Scale * Rot * Trans;
return m_modelWorld;
}
void DefinedModel::Destroy()
{
squareVertBuffer->Release();
squareIndexBuffer->Release();
VS->Release();
PS->Release();
VS_Buffer->Release();
PS_Buffer->Release();
vertLayout->Release();
cbPerObjectBuffer->Release();
m_VertexArray.clear();
m_indices.clear();
}
void DefinedModel::rastMode(RastMode rastmode)
{
HRESULT hr;
m_RastMode = rastmode;
switch (rastmode)
{
case RastMode::Solid:
{
///////////////**************new**************////////////////////
D3D11_RASTERIZER_DESC wfdesc;
ZeroMemory(&wfdesc, sizeof(D3D11_RASTERIZER_DESC));
wfdesc.FillMode = D3D11_FILL_SOLID;
wfdesc.CullMode = D3D11_CULL_BACK;
hr = m_pParent->Device()->CreateRasterizerState(&wfdesc, &m_RastState);
///////////////**************new**************////////////////////
break;
}
case RastMode::Wireframe:
{
///////////////**************new**************////////////////////
D3D11_RASTERIZER_DESC wfdesc;
ZeroMemory(&wfdesc, sizeof(D3D11_RASTERIZER_DESC));
wfdesc.FillMode = D3D11_FILL_WIREFRAME;
wfdesc.CullMode = D3D11_CULL_BACK;
hr = m_pParent->Device()->CreateRasterizerState(&wfdesc, &m_RastState);
///////////////**************new**************////////////////////
break;
}
}
}
Effect file (trans.fx):
cbuffer cbPerObject
{
float4x4 WVP;
};
struct VS_OUTPUT
{
float4 Pos : SV_POSITION;
float4 Color : COLOR;
};
VS_OUTPUT VS(float4 inPos : POSITION, float4 inColor : COLOR)
{
VS_OUTPUT output;
output.Pos = mul(inPos, WVP);
output.Color = inColor;
return output;
}
float4 PS(VS_OUTPUT input) : SV_TARGET
{
return input.Color;
}

Billboarding C++

I got a code from my teacher that currently shows a 3D globe and a 2D particle system. The camera moves around in circles. The particle system is supposed to face the camera.
According to my lecture notes, I have to multiply the billboard with the inverse of the camera's view matrix. I would love to try that but I have trouble using the variable for the view matrix.
#include "pch.h"
#include <Kore/Application.h>
#include <Kore/IO/FileReader.h>
#include <Kore/Math/Core.h>
#include <Kore/Math/Random.h>
#include <Kore/System.h>
#include <Kore/Input/Keyboard.h>
#include <Kore/Input/Mouse.h>
#include <Kore/Audio/Mixer.h>
#include <Kore/Graphics/Image.h>
#include <Kore/Graphics/Graphics.h>
#include <Kore/Log.h>
#include "ObjLoader.h"
#include "Collision.h"
#include "PhysicsWorld.h"
#include "PhysicsObject.h"
using namespace Kore;
// A simple particle implementation
class Particle {
public:
VertexBuffer* vb;
IndexBuffer* ib;
mat4 M;
// The current position
vec3 position;
// The current velocity
vec3 velocity;
// The remaining time to live
float timeToLive;
// The total time time to live
float totalTimeToLive;
// Is the particle dead (= ready to be re-spawned?)
bool dead;
void init(const VertexStructure& structure) {
vb = new VertexBuffer(4, structure,0);
float* vertices = vb->lock();
SetVertex(vertices, 0, -1, -1, 0, 0, 0);
SetVertex(vertices, 1, -1, 1, 0, 0, 1);
SetVertex(vertices, 2, 1, 1, 0, 1, 1);
SetVertex(vertices, 3, 1, -1, 0, 1, 0);
vb->unlock();
// Set index buffer
ib = new IndexBuffer(6);
int* indices = ib->lock();
indices[0] = 0;
indices[1] = 1;
indices[2] = 2;
indices[3] = 0;
indices[4] = 2;
indices[5] = 3;
ib->unlock();
dead = true;
}
void Emit(vec3 pos, vec3 velocity, float timeToLive) {
position = pos;
this->velocity = velocity;
dead = false;
this->timeToLive = timeToLive;
totalTimeToLive = timeToLive;
}
Particle() {
}
void SetVertex(float* vertices, int index, float x, float y, float z, float u, float v) {
vertices[index* 8 + 0] = x;
vertices[index*8 + 1] = y;
vertices[index*8 + 2] = z;
vertices[index*8 + 3] = u;
vertices[index*8 + 4] = v;
vertices[index*8 + 5] = 0.0f;
vertices[index*8 + 6] = 0.0f;
vertices[index*8 + 7] = -1.0f;
}
void render(TextureUnit tex, Texture* image) {
Graphics::setTexture(tex, image);
Graphics::setVertexBuffer(*vb);
Graphics::setIndexBuffer(*ib);
Graphics::drawIndexedVertices();
}
void Integrate(float deltaTime) {
timeToLive -= deltaTime;
if (timeToLive < 0.0f) {
dead = true;
}
// Note: We are using no forces or gravity at the moment.
position += velocity * deltaTime;
// Build the matrix
M = mat4::Translation(position.x(), position.y(), position.z()) * mat4::Scale(0.2f, 0.2f, 0.2f);
}
};
class ParticleSystem {
public:
// The center of the particle system
vec3 position;
// The minimum coordinates of the emitter box
vec3 emitMin;
// The maximal coordinates of the emitter box
vec3 emitMax;
// The list of particles
Particle* particles;
// The number of particles
int numParticles;
// The spawn rate
float spawnRate;
// When should the next particle be spawned?
float nextSpawn;
ParticleSystem(int maxParticles, const VertexStructure& structure ) {
particles = new Particle[maxParticles];
numParticles = maxParticles;
for (int i = 0; i < maxParticles; i++) {
particles[i].init(structure);
}
spawnRate = 0.05f;
nextSpawn = spawnRate;
position = vec3(0.5f, 1.3f, 0.5f);
float b = 0.1f;
emitMin = position + vec3(-b, -b, -b);
emitMax = position + vec3(b, b, b);
}
void update(float deltaTime) {
// Do we need to spawn a particle?
nextSpawn -= deltaTime;
bool spawnParticle = false;
if (nextSpawn < 0) {
spawnParticle = true;
nextSpawn = spawnRate;
}
for (int i = 0; i < numParticles; i++) {
if (particles[i].dead) {
if (spawnParticle) {
EmitParticle(i);
spawnParticle = false;
}
}
particles[i].Integrate(deltaTime);
}
}
void render(TextureUnit tex, Texture* image, ConstantLocation mLocation, mat4 V) {
Graphics::setBlendingMode(BlendingOperation::SourceAlpha, BlendingOperation::InverseSourceAlpha);
Graphics::setRenderState(RenderState::DepthWrite, false);
/************************************************************************/
/* Exercise 7 1.1 */
/************************************************************************/
/* Change the matrix V in such a way that the billboards are oriented towards the camera */
/************************************************************************/
/* Exercise 7 1.2 */
/************************************************************************/
/* Animate using at least one new control parameter */
for (int i = 0; i < numParticles; i++) {
// Skip dead particles
if (particles[i].dead) continue;
Graphics::setMatrix(mLocation, particles[i].M * V);
particles[i].render(tex, image);
}
Graphics::setRenderState(RenderState::DepthWrite, true);
}
float getRandom(float minValue, float maxValue) {
int randMax = 1000000;
int randInt = Random::get(0, randMax);
float r = (float) randInt / (float) randMax;
return minValue + r * (maxValue - minValue);
}
void EmitParticle(int index) {
// Calculate a random position inside the box
float x = getRandom(emitMin.x(), emitMax.x());
float y = getRandom(emitMin.y(), emitMax.y());
float z = getRandom(emitMin.z(), emitMax.z());
vec3 pos;
pos.set(x, y, z);
vec3 velocity(0, 0.3f, 0);
particles[index].Emit(pos, velocity, 3.0f);
}
};
namespace {
const int width = 1024;
const int height = 768;
double startTime;
Shader* vertexShader;
Shader* fragmentShader;
Program* program;
float angle = 0.0f;
// null terminated array of MeshObject pointers
MeshObject* objects[] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr };
// null terminated array of PhysicsObject pointers
PhysicsObject* physicsObjects[] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr };
// The view projection matrix aka the camera
mat4 P;
mat4 View;
mat4 PV;
vec3 cameraPosition;
MeshObject* sphere;
PhysicsObject* po;
PhysicsWorld physics;
// uniform locations - add more as you see fit
TextureUnit tex;
ConstantLocation pvLocation;
ConstantLocation mLocation;
ConstantLocation tintLocation;
Texture* particleImage;
ParticleSystem* particleSystem;
double lastTime;
void update() {
double t = System::time() - startTime;
double deltaT = t - lastTime;
//Kore::log(Info, "%f\n", deltaT);
lastTime = t;
Kore::Audio::update();
Graphics::begin();
Graphics::clear(Graphics::ClearColorFlag | Graphics::ClearDepthFlag, 0xff9999FF, 1000.0f);
Graphics::setFloat4(tintLocation, vec4(1, 1, 1, 1));
program->set();
angle += 0.3f * deltaT;
float x = 0 + 3 * Kore::cos(angle);
float z = 0 + 3 * Kore::sin(angle);
cameraPosition.set(x, 2, z);
//PV = mat4::Perspective(60, (float)width / (float)height, 0.1f, 100) * mat4::lookAt(vec3(0, 2, -3), vec3(0, 2, 0), vec3(0, 1, 0));
P = mat4::Perspective(60, (float)width / (float)height, 0.1f, 100);
View = mat4::lookAt(vec3(x, 2, z), vec3(0, 2, 0), vec3(0, 1, 0));
PV = P * View;
Graphics::setMatrix(pvLocation, PV);
// iterate the MeshObjects
MeshObject** current = &objects[0];
while (*current != nullptr) {
// set the model matrix
Graphics::setMatrix(mLocation, (*current)->M);
(*current)->render(tex);
++current;
}
// Update the physics
physics.Update(deltaT);
PhysicsObject** currentP = &physics.physicsObjects[0];
while (*currentP != nullptr) {
(*currentP)->UpdateMatrix();
Graphics::setMatrix(mLocation, (*currentP)->Mesh->M);
(*currentP)->Mesh->render(tex);
++currentP;
}
particleSystem->update(deltaT);
particleSystem->render(tex, particleImage, mLocation, View);
Graphics::end();
Graphics::swapBuffers();
}
void SpawnSphere(vec3 Position, vec3 Velocity) {
PhysicsObject* po = new PhysicsObject();
po->SetPosition(Position);
po->Velocity = Velocity;
po->Collider.radius = 0.2f;
po->Mass = 5;
po->Mesh = sphere;
// The impulse should carry the object forward
// Use the inverse of the view matrix
po->ApplyImpulse(Velocity);
physics.AddObject(po);
}
void keyDown(KeyCode code, wchar_t character) {
if (code == Key_Space) {
// The impulse should carry the object forward
// Use the inverse of the view matrix
vec4 impulse(0, 0.4, 2, 0);
mat4 viewI = View;
viewI.Invert();
impulse = viewI * impulse;
vec3 impulse3(impulse.x(), impulse.y(), impulse.z());
SpawnSphere(cameraPosition + impulse3 *0.2f, impulse3);
}
}
void keyUp(KeyCode code, wchar_t character) {
if (code == Key_Left) {
// ...
}
}
void mouseMove(int x, int y, int movementX, int movementY) {
}
void mousePress(int button, int x, int y) {
}
void mouseRelease(int button, int x, int y) {
}
void init() {
FileReader vs("shader.vert");
FileReader fs("shader.frag");
vertexShader = new Shader(vs.readAll(), vs.size(), VertexShader);
fragmentShader = new Shader(fs.readAll(), fs.size(), FragmentShader);
// This defines the structure of your Vertex Buffer
VertexStructure structure;
structure.add("pos", Float3VertexData);
structure.add("tex", Float2VertexData);
structure.add("nor", Float3VertexData);
program = new Program;
program->setVertexShader(vertexShader);
program->setFragmentShader(fragmentShader);
program->link(structure);
tex = program->getTextureUnit("tex");
pvLocation = program->getConstantLocation("PV");
mLocation = program->getConstantLocation("M");
tintLocation = program->getConstantLocation("tint");
objects[0] = new MeshObject("Base.obj", "Level/basicTiles6x6.png", structure);
objects[0]->M = mat4::Translation(0.0f, 1.0f, 0.0f);
sphere = new MeshObject("ball_at_origin.obj", "Level/unshaded.png", structure);
SpawnSphere(vec3(0, 2, 0), vec3(0, 0, 0));
Graphics::setRenderState(DepthTest, true);
Graphics::setRenderState(DepthTestCompare, ZCompareLess);
Graphics::setTextureAddressing(tex, U, Repeat);
Graphics::setTextureAddressing(tex, V, Repeat);
particleImage = new Texture("SuperParticle.png", true);
particleSystem = new ParticleSystem(100, structure);
}
}
int kore(int argc, char** argv) {
Application* app = new Application(argc, argv, width, height, 0, false, "Exercise7");
init();
app->setCallback(update);
startTime = System::time();
lastTime = 0.0f;
Kore::Mixer::init();
Kore::Audio::init();
Keyboard::the()->KeyDown = keyDown;
Keyboard::the()->KeyUp = keyUp;
Mouse::the()->Move = mouseMove;
Mouse::the()->Press = mousePress;
Mouse::the()->Release = mouseRelease;
app->start();
delete app;
return 0;
}
There's a comment where the teacher wants us to add the code.
The variable for the view matrix "View" is in "namespace". I've only ever used namespace as a library but this one doesn't have a name. So how do I use it?
The comment says that we should use matrix V. So I just add V = Inverse View Matrix * Model Matrix to the code and it removes the rotation?
I'm sorry for the stupid questions, it's supposed to be a class for beginners but it's really anything but. The lecture notes aren't very helpful when it comes to the programming part and I only found tutorials for OpenGL or Unity or Direct X and where not using any of it.
Please help me, I need to hand this in until Saturday morning and I've already spent the last two days trying out code and I've got nothing so far!
You can find the whole thing here: https://github.com/TUDGameTechnology/Exercise7
You don't have to do anything special to access an unnamed namespace. This thread explains more.
You are most probably trying to reference View within methods that cannot see your namespace because of the order in which they are defined in your file.
This line in your update method:
particleSystem->render(tex, particleImage, mLocation, View);
is already passing View into the render method.
void render(TextureUnit tex, Texture* image, ConstantLocation mLocation, mat4 V)
That means that in this case mat4 v is your camera view.