• Advertisement
  • Popular Tags

  • Popular Now

  • Advertisement
  • Similar Content

    • By tj8146
      I am using immediate mode for OpenGL and I am creating a 2D top down car game. I am trying to configure my game loop in order to get my car-like physics working on a square shape. I have working code but it is not doing as I want it to. I am not sure as to whether it is my game loop that is incorrect or my code for the square is incorrect, or maybe both! Could someone help because I have been trying to work this out for over a day now
      I have attached my .cpp file if you wish to run it for yourself.. 
      WinMain code:
      /******************* WIN32 FUNCTIONS ***************************/ int WINAPI WinMain( HINSTANCE hInstance, // Instance HINSTANCE hPrevInstance, // Previous Instance LPSTR lpCmdLine, // Command Line Parameters int nCmdShow) // Window Show State { MSG msg; // Windows Message Structure bool done=false; // Bool Variable To Exit Loop Car car; car.x = 220; car.y = 140; car.dx = 0; car.dy = 0; car.ang = 0; AllocConsole(); FILE *stream; freopen_s(&stream, "CONOUT$", "w", stdout); // Create Our OpenGL Window if (!CreateGLWindow("OpenGL Win32 Example",screenWidth,screenHeight)) { return 0; // Quit If Window Was Not Created } while(!done) // Loop That Runs While done=FALSE { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is There A Message Waiting? { if (msg.message==WM_QUIT) // Have We Received A Quit Message? { done=true; // If So done=TRUE break; } else // If Not, Deal With Window Messages { TranslateMessage(&msg); // Translate The Message DispatchMessage(&msg); // Dispatch The Message } } else // If There Are No Messages { if(keys[VK_ESCAPE]) done = true; void processKeys(Car& car); //process keyboard while (game_is_running) { loops = 0; while (GetTickCount() > next_game_tick && loops < MAX_FRAMESKIP) { update(car); // update variables next_game_tick += SKIP_TICKS; loops++; } display(car); // Draw The Scene SwapBuffers(hDC); // Swap Buffers (Double Buffering) } } } // Shutdown KillGLWindow(); // Kill The Window return (int)(msg.wParam); // Exit The Program } //WIN32 Processes function - useful for responding to user inputs or other events. LRESULT CALLBACK WndProc( HWND hWnd, // Handle For This Window UINT uMsg, // Message For This Window WPARAM wParam, // Additional Message Information LPARAM lParam) // Additional Message Information { switch (uMsg) // Check For Windows Messages { case WM_CLOSE: // Did We Receive A Close Message? { PostQuitMessage(0); // Send A Quit Message return 0; // Jump Back } break; case WM_SIZE: // Resize The OpenGL Window { reshape(LOWORD(lParam),HIWORD(lParam)); // LoWord=Width, HiWord=Height return 0; // Jump Back } break; case WM_LBUTTONDOWN: { mouse_x = LOWORD(lParam); mouse_y = screenHeight - HIWORD(lParam); LeftPressed = true; } break; case WM_LBUTTONUP: { LeftPressed = false; } break; case WM_MOUSEMOVE: { mouse_x = LOWORD(lParam); mouse_y = screenHeight - HIWORD(lParam); } break; case WM_KEYDOWN: // Is A Key Being Held Down? { keys[wParam] = true; // If So, Mark It As TRUE return 0; // Jump Back } break; case WM_KEYUP: // Has A Key Been Released? { keys[wParam] = false; // If So, Mark It As FALSE return 0; // Jump Back } break; } // Pass All Unhandled Messages To DefWindowProc return DefWindowProc(hWnd,uMsg,wParam,lParam); }  
      C++ and OpenGL code:
      int mouse_x=0, mouse_y=0; bool LeftPressed = false; int screenWidth=1080, screenHeight=960; bool keys[256]; float radiansFromDegrees(float deg) { return deg * (M_PI / 180.0f); } float degreesFromRadians(float rad) { return rad / (M_PI / 180.0f); } bool game_is_running = true; const int TICKS_PER_SECOND = 50; const int SKIP_TICKS = 1000 / TICKS_PER_SECOND; const int MAX_FRAMESKIP = 10; DWORD next_game_tick = GetTickCount(); int loops; typedef struct { float x, y; float dx, dy; float ang; }Car; //OPENGL FUNCTION PROTOTYPES void display(const Car& car); //called in winmain to draw everything to the screen void reshape(int width, int height); //called when the window is resized void init(); //called in winmain when the program starts. void processKeys(Car& car); //called in winmain to process keyboard input void update(Car& car); //called in winmain to update variables /************* START OF OPENGL FUNCTIONS ****************/ void display(const Car& car) { const float w = 50.0f; const float h = 50.0f; glClear(GL_COLOR_BUFFER_BIT); glLoadIdentity(); glTranslatef(100, 100, 0); glBegin(GL_POLYGON); glVertex2f(car.x, car.y); glVertex2f(car.x + w, car.y); glVertex2f(car.x + w, car.y + h); glVertex2f(car.x, car.y + h); glEnd(); glFlush(); } void reshape(int width, int height) // Resize the OpenGL window { screenWidth = width; screenHeight = height; // to ensure the mouse coordinates match // we will use these values to set the coordinate system glViewport(0, 0, width, height); // Reset the current viewport glMatrixMode(GL_PROJECTION); // select the projection matrix stack glLoadIdentity(); // reset the top of the projection matrix to an identity matrix gluOrtho2D(0, screenWidth, 0, screenHeight); // set the coordinate system for the window glMatrixMode(GL_MODELVIEW); // Select the modelview matrix stack glLoadIdentity(); // Reset the top of the modelview matrix to an identity matrix } void init() { glClearColor(1.0, 1.0, 0.0, 0.0); //sets the clear colour to yellow //glClear(GL_COLOR_BUFFER_BIT) in the display function //will clear the buffer to this colour. } void processKeys(Car& car) { if (keys[VK_UP]) { float cdx = sinf(radiansFromDegrees(car.ang)); float cdy = -cosf(radiansFromDegrees(car.ang)); car.dx += cdx; car.dy += cdy; } if (keys[VK_DOWN]) { float cdx = sinf(radiansFromDegrees(car.ang)); float cdy = -cosf(radiansFromDegrees(car.ang)); car.dx += -cdx; car.dy += -cdy; } if (keys[VK_LEFT]) { car.ang -= 2; } if (keys[VK_RIGHT]) { car.ang += 2; } } void update(Car& car) { car.x += car.dx*next_game_tick; }  
      game.cpp
    • By tj8146
      I am using immediate mode for OpenGL and I am creating a 2D top down car game. I am trying to configure my game loop in order to get my car-like physics working on a square shape. I have working code but it is not doing as I want it to. I am not sure as to whether it is my game loop that is incorrect or my code for the square is incorrect, or maybe both! Could someone help because I have been trying to work this out for over a day now
      I have attached my .cpp file if you wish to run it for yourself.. 
       
      This is my C++ and OpenGL code:
      int mouse_x=0, mouse_y=0; bool LeftPressed = false; int screenWidth=1080, screenHeight=960; bool keys[256]; float radiansFromDegrees(float deg) { return deg * (M_PI / 180.0f); } float degreesFromRadians(float rad) { return rad / (M_PI / 180.0f); } bool game_is_running = true; const int TICKS_PER_SECOND = 50; const int SKIP_TICKS = 1000 / TICKS_PER_SECOND; const int MAX_FRAMESKIP = 10; DWORD next_game_tick = GetTickCount(); int loops; typedef struct { float x, y; float dx, dy; float ang; }Car; //OPENGL FUNCTION PROTOTYPES void display(const Car& car); //called in winmain to draw everything to the screen void reshape(int width, int height); //called when the window is resized void init(); //called in winmain when the program starts. void processKeys(Car& car); //called in winmain to process keyboard input void update(Car& car); //called in winmain to update variables /************* START OF OPENGL FUNCTIONS ****************/ void display(const Car& car) { const float w = 50.0f; const float h = 50.0f; glClear(GL_COLOR_BUFFER_BIT); glLoadIdentity(); glTranslatef(100, 100, 0); glBegin(GL_POLYGON); glVertex2f(car.x, car.y); glVertex2f(car.x + w, car.y); glVertex2f(car.x + w, car.y + h); glVertex2f(car.x, car.y + h); glEnd(); glFlush(); } void reshape(int width, int height) // Resize the OpenGL window { screenWidth = width; screenHeight = height; // to ensure the mouse coordinates match // we will use these values to set the coordinate system glViewport(0, 0, width, height); // Reset the current viewport glMatrixMode(GL_PROJECTION); // select the projection matrix stack glLoadIdentity(); // reset the top of the projection matrix to an identity matrix gluOrtho2D(0, screenWidth, 0, screenHeight); // set the coordinate system for the window glMatrixMode(GL_MODELVIEW); // Select the modelview matrix stack glLoadIdentity(); // Reset the top of the modelview matrix to an identity matrix } void init() { glClearColor(1.0, 1.0, 0.0, 0.0); //sets the clear colour to yellow //glClear(GL_COLOR_BUFFER_BIT) in the display function //will clear the buffer to this colour. } void processKeys(Car& car) { if (keys[VK_UP]) { float cdx = sinf(radiansFromDegrees(car.ang)); float cdy = -cosf(radiansFromDegrees(car.ang)); car.dx += cdx; car.dy += cdy; } if (keys[VK_DOWN]) { float cdx = sinf(radiansFromDegrees(car.ang)); float cdy = -cosf(radiansFromDegrees(car.ang)); car.dx += -cdx; car.dy += -cdy; } if (keys[VK_LEFT]) { car.ang -= 2; } if (keys[VK_RIGHT]) { car.ang += 2; } } void update(Car& car) { car.x += car.dx*next_game_tick; } My WinMain code:
      /******************* WIN32 FUNCTIONS ***************************/ int WINAPI WinMain( HINSTANCE hInstance, // Instance HINSTANCE hPrevInstance, // Previous Instance LPSTR lpCmdLine, // Command Line Parameters int nCmdShow) // Window Show State { MSG msg; // Windows Message Structure bool done=false; // Bool Variable To Exit Loop Car car; car.x = 220; car.y = 140; car.dx = 0; car.dy = 0; car.ang = 0; AllocConsole(); FILE *stream; freopen_s(&stream, "CONOUT$", "w", stdout); // Create Our OpenGL Window if (!CreateGLWindow("OpenGL Win32 Example",screenWidth,screenHeight)) { return 0; // Quit If Window Was Not Created } while(!done) // Loop That Runs While done=FALSE { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is There A Message Waiting? { if (msg.message==WM_QUIT) // Have We Received A Quit Message? { done=true; // If So done=TRUE break; } else // If Not, Deal With Window Messages { TranslateMessage(&msg); // Translate The Message DispatchMessage(&msg); // Dispatch The Message } } else // If There Are No Messages { if(keys[VK_ESCAPE]) done = true; void processKeys(Car& car); //process keyboard while (game_is_running) { loops = 0; while (GetTickCount() > next_game_tick && loops < MAX_FRAMESKIP) { update(car); // update variables next_game_tick += SKIP_TICKS; loops++; } display(car); // Draw The Scene SwapBuffers(hDC); // Swap Buffers (Double Buffering) } } } // Shutdown KillGLWindow(); // Kill The Window return (int)(msg.wParam); // Exit The Program } //WIN32 Processes function - useful for responding to user inputs or other events. LRESULT CALLBACK WndProc( HWND hWnd, // Handle For This Window UINT uMsg, // Message For This Window WPARAM wParam, // Additional Message Information LPARAM lParam) // Additional Message Information { switch (uMsg) // Check For Windows Messages { case WM_CLOSE: // Did We Receive A Close Message? { PostQuitMessage(0); // Send A Quit Message return 0; // Jump Back } break; case WM_SIZE: // Resize The OpenGL Window { reshape(LOWORD(lParam),HIWORD(lParam)); // LoWord=Width, HiWord=Height return 0; // Jump Back } break; case WM_LBUTTONDOWN: { mouse_x = LOWORD(lParam); mouse_y = screenHeight - HIWORD(lParam); LeftPressed = true; } break; case WM_LBUTTONUP: { LeftPressed = false; } break; case WM_MOUSEMOVE: { mouse_x = LOWORD(lParam); mouse_y = screenHeight - HIWORD(lParam); } break; case WM_KEYDOWN: // Is A Key Being Held Down? { keys[wParam] = true; // If So, Mark It As TRUE return 0; // Jump Back } break; case WM_KEYUP: // Has A Key Been Released? { keys[wParam] = false; // If So, Mark It As FALSE return 0; // Jump Back } break; } // Pass All Unhandled Messages To DefWindowProc return DefWindowProc(hWnd,uMsg,wParam,lParam); }  
      game.cpp
    • By lxjk
      Hi guys,
      There are many ways to do light culling in tile-based shading. I've been playing with this idea for a while, and just want to throw it out there.
      Because tile frustums are general small compared to light radius, I tried using cone test to reduce false positives introduced by commonly used sphere-frustum test.
      On top of that, I use distance to camera rather than depth for near/far test (aka. sliced by spheres).
      This method can be naturally extended to clustered light culling as well.
      The following image shows the general ideas

       
      Performance-wise I get around 15% improvement over sphere-frustum test. You can also see how a single light performs as the following: from left to right (1) standard rendering of a point light; then tiles passed the test of (2) sphere-frustum test; (3) cone test; (4) spherical-sliced cone test
       

       
      I put the details in my blog post (https://lxjk.github.io/2018/03/25/Improve-Tile-based-Light-Culling-with-Spherical-sliced-Cone.html), GLSL source code included!
       
      Eric
    • By Fadey Duh
      Good evening everyone!

      I was wondering if there is something equivalent of  GL_NV_blend_equation_advanced for AMD?
      Basically I'm trying to find more compatible version of it.

      Thank you!
    • By Jens Eckervogt
      Hello guys, 
       
      Please tell me! 
      How do I know? Why does wavefront not show for me?
      I already checked I have non errors yet.
      using OpenTK; using System.Collections.Generic; using System.IO; using System.Text; namespace Tutorial_08.net.sourceskyboxer { public class WaveFrontLoader { private static List<Vector3> inPositions; private static List<Vector2> inTexcoords; private static List<Vector3> inNormals; private static List<float> positions; private static List<float> texcoords; private static List<int> indices; public static RawModel LoadObjModel(string filename, Loader loader) { inPositions = new List<Vector3>(); inTexcoords = new List<Vector2>(); inNormals = new List<Vector3>(); positions = new List<float>(); texcoords = new List<float>(); indices = new List<int>(); int nextIdx = 0; using (var reader = new StreamReader(File.Open("Contents/" + filename + ".obj", FileMode.Open), Encoding.UTF8)) { string line = reader.ReadLine(); int i = reader.Read(); while (true) { string[] currentLine = line.Split(); if (currentLine[0] == "v") { Vector3 pos = new Vector3(float.Parse(currentLine[1]), float.Parse(currentLine[2]), float.Parse(currentLine[3])); inPositions.Add(pos); if (currentLine[1] == "t") { Vector2 tex = new Vector2(float.Parse(currentLine[1]), float.Parse(currentLine[2])); inTexcoords.Add(tex); } if (currentLine[1] == "n") { Vector3 nom = new Vector3(float.Parse(currentLine[1]), float.Parse(currentLine[2]), float.Parse(currentLine[3])); inNormals.Add(nom); } } if (currentLine[0] == "f") { Vector3 pos = inPositions[0]; positions.Add(pos.X); positions.Add(pos.Y); positions.Add(pos.Z); Vector2 tc = inTexcoords[0]; texcoords.Add(tc.X); texcoords.Add(tc.Y); indices.Add(nextIdx); ++nextIdx; } reader.Close(); return loader.loadToVAO(positions.ToArray(), texcoords.ToArray(), indices.ToArray()); } } } } } And It have tried other method but it can't show for me.  I am mad now. Because any OpenTK developers won't help me.
      Please help me how do I fix.

      And my download (mega.nz) should it is original but I tried no success...
      - Add blend source and png file here I have tried tried,.....  
       
      PS: Why is our community not active? I wait very longer. Stop to lie me!
      Thanks !
  • Advertisement
  • Advertisement
Sign in to follow this  

OpenGL "no Shaders Attached To Current Program" Only In Release Build

This topic is 645 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi,

 

I'm working on an OpenGL project and I get an error that says "No shaders attached to current program" only in the release build. If I build it in debug mode I don't get this error. I know this is a link error, but I don't understand why I'm only getting it in release mode?

 

I'm building this project as a dll file that then gets called from a normal exe file.

 

here i my code

#pragma once
#include <GLEW/GL/glew.h>
#include <vector>
#include "../../../IO/FileReader.h"
#include "../../../Math/Math.h"

#ifdef COMPILE_BLUE_FLAME_ENGINE   
	#define DLLEXPORT __declspec(dllexport) 
#else   
	#define DLLEXPORT __declspec(dllimport) 
#endif

namespace BFE
{
	namespace Graphics
	{
		class DLLEXPORT GLShader
		{
			private:
				GLint result = GL_FALSE;
				int errorLength;
				GLuint programID;

			private:
				void LoadAndSpliteShader(const char* shaderFile, std::string *vertexShader, std::string *fragmentShader);
				GLuint &CompileShader(std::string shaderCode, GLenum shaderType);

			public:
				GLShader();
				~GLShader();

				void Load(const char* fileName);

				void SetUniformFloat(const char* varibleName, const float &value) const;

				void SetUniformVector2(const char* varibleName, const Math::Vector2 &vector) const;
				void SetUniformVector3(const char* varibleName, const Math::Vector3 &vector) const;
				void SetUniformVector4(const char* varibleName, const Math::Vector4 &vector) const;

				//void SetUniformMatrix4(const char* VaribleName, const Math::Matrix4 &Matrix) const;

				void Bind();
				void Unbind();
		};
	}
}

---

---

---

---

		void GLShader::LoadAndSpliteShader(const char* shaderFile, std::string *vertexShader, std::string *fragmentShader)
		{
			std::string strShaderCode = IO::FileReader::ReadFile(shaderFile);

			int vertexPosition = strShaderCode.find("#Vertex Shader");;
			int fragmentPosition = strShaderCode.find("#Fragment Shader");;

			int vertexLength = 15;
			int fragmentLength = 17;

			//Splite vertex shader
			std::string tempVertexShader = strShaderCode.substr(vertexPosition + vertexLength);
			*vertexShader = tempVertexShader.substr(vertexPosition, fragmentPosition - fragmentLength);

			//Splite fragment shader
			*fragmentShader = strShaderCode.substr(fragmentPosition + fragmentLength);
		}

		GLuint &GLShader::CompileShader(std::string shaderCode, GLenum shaderType)
		{
			GLuint shaderID = glCreateShader(shaderType);

			const char* cShaderCode = shaderCode.c_str();

			glShaderSource(shaderID, 1, &cShaderCode, 0);
			glCompileShader(shaderID);

			glGetShaderiv(shaderID, GL_COMPILE_STATUS, &result);
			glGetShaderiv(shaderID, GL_INFO_LOG_LENGTH, &errorLength);
			if (errorLength > 0)
			{
				std::vector<char> shaderErrorMessage(errorLength + 1);
				glGetShaderInfoLog(shaderID, errorLength, NULL, &shaderErrorMessage[0]);
				printf("Compile Error: %s\n", &shaderErrorMessage[0]);
			}

			return shaderID;
		}

		void GLShader::Load(const char* fileName)
		{
			std::string vertexShaderCode, fragmentShaderCode;
			LoadAndSpliteShader(fileName, &vertexShaderCode, &fragmentShaderCode);

			GLuint vertexShader = CompileShader(vertexShaderCode, GL_VERTEX_SHADER);
			GLuint fragmentShader = CompileShader(fragmentShaderCode, GL_FRAGMENT_SHADER);
			
			programID = glCreateProgram();
			glAttachShader(programID, vertexShader);
			glAttachShader(programID, fragmentShader);
			glLinkProgram(programID);

			glGetProgramiv(programID, GL_LINK_STATUS, &result);
			glGetProgramiv(programID, GL_INFO_LOG_LENGTH, &errorLength);
			if (errorLength > 0)
			{
				std::vector<char> ProgramErrorMessage(errorLength + 1);
				glGetProgramInfoLog(programID, errorLength, NULL, &ProgramErrorMessage[0]);
				printf("Link Error: %s\n", &ProgramErrorMessage[0]);
			}

			glDetachShader(programID, vertexShader);
			glDetachShader(programID, fragmentShader);
			glDeleteShader(vertexShader);
			glDeleteShader(fragmentShader);
		}

Share this post


Link to post
Share on other sites
Advertisement

Differences between release and debug builds are commonly due to uninitialized stack variables: the debug memory allocator will typically initialize these to something well-known, the release allocator will not and you'll just get stack garbage.

Share this post


Link to post
Share on other sites

Differences between release and debug builds are commonly due to uninitialized stack variables: the debug memory allocator will typically initialize these to something well-known, the release allocator will not and you'll just get stack garbage.

 

I just went through my entire code base and made sure that everything is Initialized as a member list. I also made sure that every variable in a function is initialized, but i'm still having the same problem. I'm out of ideas. :(

Share this post


Link to post
Share on other sites

Alright, I did some more investigating and for some reason glAttachShader is return an error code of 1281. I have no idea why. In debug mode it returns 0.

Share this post


Link to post
Share on other sites

Alright, I did some more investigating and for some reason glAttachShader is return an error code of 1281. I have no idea why. In debug mode it returns 0.

 

In that case which of these values are not as expected?

            glAttachShader(programID, vertexShader);
            glAttachShader(programID, fragmentShader);

If programID ok, is vertexShader ok, is fragmentShader ok?

 

I just noticed this:

GLuint &GLShader::CompileShader(std::string shaderCode, GLenum shaderType)

You are returning a reference to a local variable that is a bad idea. Surprisingly I did a quick test and (in my test at least) it did return the value I would expect in both debug and release build but you really shouldn't be doing that. I am surprised it works but I am no expert. I wouldn't be surprised if that is your issue.

 

You should really check these return values when before you use them too. Don't just print an error then carry on as if there was no error. Could you paste the full log you get when you fail to compile the shader? It might be an idea to post the shader code too. Also, is it the vertex or the fragment shader that isn't compiling?

 

Print the actual code you pass to the shader, ({after doing your split function). Is everything null terminated correctly? I remember having issues at some point where I wasn't doing that step correctly and I had junk on the end of my shader which prevented it from compiling. This isn't an issue in debug because the whole length of memory is usually initialised to 0 so the string ends up being null-terminated but in release this isn't the case. Make sure your code stops where it should stop.

Edited by Nanoha

Share this post


Link to post
Share on other sites

 

Alright, I did some more investigating and for some reason glAttachShader is return an error code of 1281. I have no idea why. In debug mode it returns 0.

 

In that case which of these values are not as expected?

            glAttachShader(programID, vertexShader);
            glAttachShader(programID, fragmentShader);

If programID ok, is vertexShader ok, is fragmentShader ok?

 

I just noticed this:

GLuint &GLShader::CompileShader(std::string shaderCode, GLenum shaderType)

You are returning a reference to a local variable that is a bad idea. Surprisingly I did a quick test and (in my test at least) it did return the value I would expect in both debug and release build but you really shouldn't be doing that. I am surprised it works but I am no expert.

 

 

 

Alright, removing the reference from CompileShader fixed the problem.

 

Can you explain to me why is this bad? What was actually happening when I was passing it by reference ?

I thought It is always a good idea to pass by reference so you wouldn't wast memory and cpu cycles copying from one variable to the other. This way both variables have the same memory address.

 

wait, wait, wait.....

 

I think I know why.

Ok, so i'm just guessing here but here is my theory.

When I return by reference to a local variable from a function, this variable will be removed from the stack because the function finished it's work and since both variables have the same memory address they will both be deleted and I will just point to an empty memory address.

 

How off am I?

 

 

[edit]

Quote from Stackoverflow

 

This code snippet:

int& func1()
{
int i;
i = 1;
return i;
}

will not work because you're returning an alias (a reference) to an object with a lifetime limited to the scope of the function call. That means once func1() returns, int i dies, making the reference returned from the function worthless because it now refers to an object that doesn't exist.

 

 

wow, I wasn't off at all. yay, I'm not stupid...

Well, I made this mistake so.... yeah.. :P

 

Thanks ! :)

 

 

[Edit 2]

 

 

You should really check these return values when before you use them too. Don't just print an error then carry on as if there was no error. Could you paste the full log you get when you fail to compile the shader? It might be an idea to post the shader code too. Also, is it the vertex or the fragment shader that isn't compiling?

 

Print the actual code you pass to the shader, ({after doing your split function). Is everything null terminated correctly? I remember having issues at some point where I wasn't doing that step correctly and I had junk on the end of my shader which prevented it from compiling. This isn't an issue in debug because the whole length of memory is usually initialised to 0 so the string ends up being null-terminated but in release this isn't the case. Make sure your code stops where it should stop.

 

 

Here is my shader code

#Vertex Shader
#version 450 core
layout(location = 0) in vec3 inPosition;
layout(location = 1) in vec3 inColor;

out vec3 fragmentColor;

void main()
{
	gl_Position = vec4(inPosition.xyz, 1.0f);
	fragmentColor = inColor;
}

#Fragment Shader
#version 450 core

in vec3 fragmentColor;
out vec3 color;

void main() 
{
	color = fragmentColor;
}

and here is the code after splitting

 

Vertex shader

#version 450 core
layout(location = 0) in vec3 inPosition;
layout(location = 1) in vec3 inColor;

out vec3 fragmentColor;

void main()
{
	gl_Position = vec4(inPosition.xyz, 1.0f);
	fragmentColor = inColor;
}

Fragment Shader

#version 450 core

in vec3 fragmentColor;
out vec3 color;

void main() 
{
	color = fragmentColor;
}

and here is the output of the compiled vertex and fragment shader.

GLuint vertexShader = CompileShader(vertexShaderCode, GL_VERTEX_SHADER);
GLuint fragmentShader = CompileShader(fragmentShaderCode, GL_FRAGMENT_SHADER);

std::cout << vertexShader << " " << fragmentShader << std::endl;

//Bad output
VertexShader output:- "2724212624"
FragmentShader output:- "2775447968"

//Correct output
VertexShader output:- "1"
FragmentShader output:- "2"

Again, thanks :)

Edited by FantasyVII

Share this post


Link to post
Share on other sites

I edited my post before I saw your reply. Check the last bit as I think that might be your issue.

 

 

 

I thought It is always a good idea to pass by reference so you wouldn't wast memory and cpu cycles copying from one variable to the other. This way both variables have the same memory address.

 

I'm no expert on this so take it with a grain of salt but you should be very very careful when using pass by reference, passing things into functions by reference is often a good idea particularly with very large objects (otherwise they have to be copied each time). You should try to pass in const references though unless you know the function will/must modify your object. It's often unnecessary to pass things like ints and floats by reference but passing something like a string by reference usually makes sense.

 

Where it all goes very bad is when you start returning references. This can have it's uses but don't use it as a rule  of thumb, it's more an exception rather than a norm and you need to be very careful that the thing you are returning the reference from is going to outlive the thing you are returning it to. Also you are just returning an int which will likely be the same size as an int& (depending on your system) so you don't gain any extra memory from doing it. The same goes for passing references into functions for types such as ints, it's likely the same size as a reference (again, depending on your system).

 

It is as you say, the reference is essentially just a pointer pointing to memory and you return a reference to something allocated on the stack, as soon as that function returns the local variable no longer exists but the memory still does and could contain anything. The way you are using it I guess there isn't a chance for that memory to get reused so it's lucky the 'value' stays the same but you shouldn't do that.

Edited by Nanoha

Share this post


Link to post
Share on other sites

I edited my post before I saw your reply. Check the last bit as I think that might be your issue.

 

 

 

I thought It is always a good idea to pass by reference so you wouldn't wast memory and cpu cycles copying from one variable to the other. This way both variables have the same memory address.

 

I'm no expert on this so take it with a grain of salt but you should be very very careful when using pass by reference, passing things into functions by reference is often a good idea particularly with very large objects (otherwise they have to be copied each time). You should try to pass in const references though unless you know the function will/must modify your object. It's often unnecessary to pass things like ints and floats by reference but passing something like a string by reference usually makes sense.

 

Where it all goes very bad is when you start returning references. This can have it's uses but don't use it as a rule  of thumb, it's more an exception rather than a norm and you need to be very careful that the thing you are returning the reference from is going to outlive the thing you are returning it to. Also you are just returning an int which will likely be the same size as an int& (depending on your system) so you don't gain any extra memory from doing it. The same goes for passing references into functions for types such as ints, it's likely the same size as a reference (again, depending on your system).

 

It is as you say, the reference is essentially just a pointer pointing to memory and you return a reference to something allocated on the stack, as soon as that function returns the local variable no longer exists but the memory still does and could contain anything. The way you are using it I guess there isn't a chance for that memory to get reused so it's lucky the 'value' stays the same but you shouldn't do that.

 

 

Alright, cool.

Thanks ! :D

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement