• Advertisement
  • Popular Tags

  • Popular Now

  • Advertisement
  • Similar Content

    • By Achivai
      Hey, I am semi-new to 3d-programming and I've hit a snag. I have one object, let's call it Object A. This object has a long int array of 3d xyz-positions stored in it's vbo as an instanced attribute. I am using these numbers to instance object A a couple of thousand times. So far so good. 
      Now I've hit a point where I want to remove one of these instances of object A while the game is running, but I'm not quite sure how to go about it. At first my thought was to update the instanced attribute of Object A and change the positions to some dummy number that I could catch in the vertex shader and then decide there whether to draw the instance of Object A or not, but I think that would be expensive to do while the game is running, considering that it might have to be done several times every frame in some cases. 
      I'm not sure how to proceed, anyone have any tips?
    • By fleissi
      Hey guys!

      I'm new here and I recently started developing my own rendering engine. It's open source, based on OpenGL/DirectX and C++.
      The full source code is hosted on github:
      https://github.com/fleissna/flyEngine

      I would appreciate if people with experience in game development / engine desgin could take a look at my source code. I'm looking for honest, constructive criticism on how to improve the engine.
      I'm currently writing my master's thesis in computer science and in the recent year I've gone through all the basics about graphics programming, learned DirectX and OpenGL, read some articles on Nvidia GPU Gems, read books and integrated some of this stuff step by step into the engine.

      I know about the basics, but I feel like there is some missing link that I didn't get yet to merge all those little pieces together.

      Features I have so far:
      - Dynamic shader generation based on material properties
      - Dynamic sorting of meshes to be renderd based on shader and material
      - Rendering large amounts of static meshes
      - Hierarchical culling (detail + view frustum)
      - Limited support for dynamic (i.e. moving) meshes
      - Normal, Parallax and Relief Mapping implementations
      - Wind animations based on vertex displacement
      - A very basic integration of the Bullet physics engine
      - Procedural Grass generation
      - Some post processing effects (Depth of Field, Light Volumes, Screen Space Reflections, God Rays)
      - Caching mechanisms for textures, shaders, materials and meshes

      Features I would like to have:
      - Global illumination methods
      - Scalable physics
      - Occlusion culling
      - A nice procedural terrain generator
      - Scripting
      - Level Editing
      - Sound system
      - Optimization techniques

      Books I have so far:
      - Real-Time Rendering Third Edition
      - 3D Game Programming with DirectX 11
      - Vulkan Cookbook (not started yet)

      I hope you guys can take a look at my source code and if you're really motivated, feel free to contribute :-)
      There are some videos on youtube that demonstrate some of the features:
      Procedural grass on the GPU
      Procedural Terrain Engine
      Quadtree detail and view frustum culling

      The long term goal is to turn this into a commercial game engine. I'm aware that this is a very ambitious goal, but I'm sure it's possible if you work hard for it.

      Bye,

      Phil
    • By tj8146
      I have attached my project in a .zip file if you wish to run it for yourself.
      I am making a simple 2d top-down game and I am trying to run my code to see if my window creation is working and to see if my timer is also working with it. Every time I run it though I get errors. And when I fix those errors, more come, then the same errors keep appearing. I end up just going round in circles.  Is there anyone who could help with this? 
       
      Errors when I build my code:
      1>Renderer.cpp 1>c:\users\documents\opengl\game\game\renderer.h(15): error C2039: 'string': is not a member of 'std' 1>c:\program files (x86)\windows kits\10\include\10.0.16299.0\ucrt\stddef.h(18): note: see declaration of 'std' 1>c:\users\documents\opengl\game\game\renderer.h(15): error C2061: syntax error: identifier 'string' 1>c:\users\documents\opengl\game\game\renderer.cpp(28): error C2511: 'bool Game::Rendering::initialize(int,int,bool,std::string)': overloaded member function not found in 'Game::Rendering' 1>c:\users\documents\opengl\game\game\renderer.h(9): note: see declaration of 'Game::Rendering' 1>c:\users\documents\opengl\game\game\renderer.cpp(35): error C2597: illegal reference to non-static member 'Game::Rendering::window' 1>c:\users\documents\opengl\game\game\renderer.cpp(36): error C2597: illegal reference to non-static member 'Game::Rendering::window' 1>c:\users\documents\opengl\game\game\renderer.cpp(43): error C2597: illegal reference to non-static member 'Game::Rendering::window' 1>Done building project "Game.vcxproj" -- FAILED. ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========  
       
      Renderer.cpp
      #include <GL/glew.h> #include <GLFW/glfw3.h> #include "Renderer.h" #include "Timer.h" #include <iostream> namespace Game { GLFWwindow* window; /* Initialize the library */ Rendering::Rendering() { mClock = new Clock; } Rendering::~Rendering() { shutdown(); } bool Rendering::initialize(uint width, uint height, bool fullscreen, std::string window_title) { if (!glfwInit()) { return -1; } /* Create a windowed mode window and its OpenGL context */ window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL); if (!window) { glfwTerminate(); return -1; } /* Make the window's context current */ glfwMakeContextCurrent(window); glViewport(0, 0, (GLsizei)width, (GLsizei)height); glOrtho(0, (GLsizei)width, (GLsizei)height, 0, 1, -1); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glfwSwapInterval(1); glEnable(GL_SMOOTH); glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glDepthFunc(GL_LEQUAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glEnable(GL_TEXTURE_2D); glLoadIdentity(); return true; } bool Rendering::render() { /* Loop until the user closes the window */ if (!glfwWindowShouldClose(window)) return false; /* Render here */ mClock->reset(); glfwPollEvents(); if (mClock->step()) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glfwSwapBuffers(window); mClock->update(); } return true; } void Rendering::shutdown() { glfwDestroyWindow(window); glfwTerminate(); } GLFWwindow* Rendering::getCurrentWindow() { return window; } } Renderer.h
      #pragma once namespace Game { class Clock; class Rendering { public: Rendering(); ~Rendering(); bool initialize(uint width, uint height, bool fullscreen, std::string window_title = "Rendering window"); void shutdown(); bool render(); GLFWwindow* getCurrentWindow(); private: GLFWwindow * window; Clock* mClock; }; } Timer.cpp
      #include <GL/glew.h> #include <GLFW/glfw3.h> #include <time.h> #include "Timer.h" namespace Game { Clock::Clock() : mTicksPerSecond(50), mSkipTics(1000 / mTicksPerSecond), mMaxFrameSkip(10), mLoops(0) { mLastTick = tick(); } Clock::~Clock() { } bool Clock::step() { if (tick() > mLastTick && mLoops < mMaxFrameSkip) return true; return false; } void Clock::reset() { mLoops = 0; } void Clock::update() { mLastTick += mSkipTics; mLoops++; } clock_t Clock::tick() { return clock(); } } TImer.h
      #pragma once #include "Common.h" namespace Game { class Clock { public: Clock(); ~Clock(); void update(); bool step(); void reset(); clock_t tick(); private: uint mTicksPerSecond; ufloat mSkipTics; uint mMaxFrameSkip; uint mLoops; uint mLastTick; }; } Common.h
      #pragma once #include <cstdio> #include <cstdlib> #include <ctime> #include <cstring> #include <cmath> #include <iostream> namespace Game { typedef unsigned char uchar; typedef unsigned short ushort; typedef unsigned int uint; typedef unsigned long ulong; typedef float ufloat; }  
      Game.zip
    • 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!
  • Advertisement
  • Advertisement
Sign in to follow this  

OpenGL 2d images and OpenGL

This topic is 688 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

Hello everyone.

I've been researching 2d rendering with OpenGL for some time.

The only solution I've found is mimicking a 2D environment using rectangles,textures and flat ortho projection.

 

My request is for resources about 2d rendering.

Because I'm limited to my sources and most of them talk about 3D rendering. (Which i'm familiar with). 

What i'm looking for is in depth articles or books that cover topics like that. (Using OpenGL api and not libraries that are openGL based).

 

Thanks!

Share this post


Link to post
Share on other sites
Advertisement

What exactly are your doubts about drawing 2D?

 

As far as I know, the way you describe, is the way to do it (and I wouldn't call it "mimicking" a 2D environment. It IS a 2D environment).

 

You set up the ortho projection, and draw textured quads.

Preferably, you set the ortho projection to match the application's window resolution and draw the quad the exact size of the texture you want to draw. That results in essentialy the same as what other APIs call 'sprites' (like Flash/Java/etc).

 

And, again, that's pretty much all that's needed.

 

Sorry if I'm misunderstanding your question (apart from me not providing articles), but there's not really much else to it that I'm aware.

Edited by __SKYe

Share this post


Link to post
Share on other sites

Yes, what you describe is the way to do 2D rendering.

 

It's important to realise that OpenGL doesn't differentiate between 2D and 3D; it just defines a standard pipeline that everything goes through.  Whether or not something appears 2D or 3D depends on the type of projection you use, and that's just a matter of putting different numbers into what is otherwise the same mathematical equations.

 

In other words, learning 2D on OpenGL is the same as learning 3D, and if you know one you will also know the other.

 

Now, older versions of OpenGL did have a 2D pipeline, of sorts, and you could get something up and running using glDrawPixels, glBitmap, etc calls.  But: (1) this 2D pipeline is very limited, (2) it's deprecated in more recent OpenGL versions, (3) it was never likely to be hardware-accelerated on consumer hardware anyway, and (4) it doesn't exist in OpenGL ES so if you want to run on mobile devices or WebGL, you can't use it.

 

In other words, nobody ever used it, and any 2D OpenGL game you've ever seen will be using the standard pipeline with an ortho projection instead.

Share this post


Link to post
Share on other sites

this is an example of drawing 2d text as set of 2d textured images (that you load each texture for each character)


struct TFontChar
{
int id;
AnsiString txt;
AnsiString FontName;
TGLTexture texture;
};

struct TFontVertex
{
	t3dpoint<float> v;
	textpoint t;
};

struct TFont
{


	TFont()
	{
		initialized = false;
		font_color = vec3(0.0, 1.0, 0.0);
	}

	~TFont()
	{
if(initialized)
{
	glDeleteBuffers(1, &alphabet_vbuffer);

delete FONT_SHADER;
delete FONT_EVENT_SHADER;
}
	}

AnsiString chartable;
TFontChar * Alphabet;
TFontVertex * FONT_VERTEX_BUFFER;
TShaderObject * FONT_SHADER;
TShaderObject * FONT_EVENT_SHADER;
bool initialized;
vec3 font_color;
unsigned int alphabet_vbuffer;
float sw,sh;
 void initialize_char_table(AnsiString FONT_DIR, float asw, float ash, AnsiString appdir) //additionally load default font for debugging
	{
	 sw=asw;
	 sh=ash;
CAN_LOG = true;
		FONT_SHADER = new TShaderObject();

		FONT_SHADER->LoadShaderProgram(appdir+"shaders/fonts/base_font_vp.shader",appdir+"shaders/fonts/base_font_fp.shader");

		FONT_EVENT_SHADER = new TShaderObject();

		FONT_EVENT_SHADER->LoadShaderProgram(appdir+"shaders/fonts/event_font_vp.shader",appdir+"shaders/fonts/event_font_fp.shader");



		chartable = " ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-+.,=:{}()[]/*;!<>_?";
int x = chartable.length();
		Alphabet = new TFontChar[ x ];
//		ALOG("alphabet length: "+IntToStr(x));

		for (int i=0; i < chartable.length(); i++)
		{
//ALOG("FONT INDEX: "+IntToStr(i));
			Alphabet[i].texture.px_height = 32;
			Alphabet[i].texture.px_width  = 32;
		Alphabet[i].texture.LoadTGA(appdir+FONT_DIR+IntToStr(i)+".tga");
		Alphabet[i].txt = chartable[i];
		}

		FONT_VERTEX_BUFFER = new TFontVertex[ 256*4 ]; //max 256 chars...
for (int i=0; i < 256; i++)
{

	FONT_VERTEX_BUFFER[i*4+0].t = textpoint(0.0, 0.0);
	FONT_VERTEX_BUFFER[i*4+0].v = t3dpoint<float>(0.0+i*18.0, 0.0, 0.0);
	FONT_VERTEX_BUFFER[i*4+1].t = textpoint(1.0, 0.0);
	FONT_VERTEX_BUFFER[i*4+1].v = t3dpoint<float>(0.0+i*18.0+18.0, 0.0, 0.0);
	FONT_VERTEX_BUFFER[i*4+2].t = textpoint(1.0, 1.0);
	FONT_VERTEX_BUFFER[i*4+2].v = t3dpoint<float>(0.0+i*18.0+18.0, 0.0 + 18.0, 0.0);
	FONT_VERTEX_BUFFER[i*4+3].t = textpoint(0.0, 1.0);
	FONT_VERTEX_BUFFER[i*4+3].v = t3dpoint<float>(0.0, 0.0 + 18.0, 0.0);
}

		glGenBuffers(1, &alphabet_vbuffer);
		glBindBuffer(GL_ARRAY_BUFFER, alphabet_vbuffer);
		glBufferData(GL_ARRAY_BUFFER, sizeof(TFontVertex) * 256 * 4, FONT_VERTEX_BUFFER, GL_STATIC_DRAW);

		glBindBuffer(GL_ARRAY_BUFFER, 0);
		ALOG("DONE WITH LOADING FONT");
		initialized = true;
	}


	 int find_index(char txt)
	{
		for (int i=0; i < chartable.length(); i++)
		{
if (Alphabet[i].txt[0] == txt) return i;
		}

		return 1;
	}



void DrawEventText(float x, float y, float size, vec3 color, float alpha, AnsiString text);


void DrawText(float x, float y, float size, AnsiString atext, vec3 color)
{

	glActiveTexture(GL_TEXTURE0);

	glDisable(GL_DEPTH_TEST);
	glDepthMask(GL_FALSE);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	AnsiString text = UpperCase(atext);

	//lets assume we draw from left top corner of text
	for (int i=0; i < 256; i++)
	{
		FONT_VERTEX_BUFFER[i*4+0].t = textpoint(0.0, 0.0);
		FONT_VERTEX_BUFFER[i*4+0].v = t3dpoint<float>(x+i*size, y, 0.0);

		FONT_VERTEX_BUFFER[i*4+1].t = textpoint(1.0, 0.0);
		FONT_VERTEX_BUFFER[i*4+1].v = t3dpoint<float>(x+i*size+size, y, 0.0);

		FONT_VERTEX_BUFFER[i*4+2].t = textpoint(1.0, 1.0);
		FONT_VERTEX_BUFFER[i*4+2].v = t3dpoint<float>(x+i*size+size, y + size, 0.0);


		FONT_VERTEX_BUFFER[i*4+3].t = textpoint(0.0, 1.0);
		FONT_VERTEX_BUFFER[i*4+3].v = t3dpoint<float>(x+i*size, y + size, 0.0);
	}

	glBindBuffer(GL_ARRAY_BUFFER, alphabet_vbuffer);
	glBufferSubData(GL_ARRAY_BUFFER,0, sizeof(TFontVertex) * 256 * 4, FONT_VERTEX_BUFFER);


	FONT_SHADER->Enable();
	FONT_SHADER->Send1I(glGetUniformLocation(FONT_SHADER->gProgram, "font_tex"), 0 );
	FONT_SHADER->Send3F(glGetUniformLocation(FONT_SHADER->gProgram, "FONT_COLOR"), color );
	FONT_SHADER->Send1F(glGetUniformLocation(FONT_SHADER->gProgram, "sh"), sh );
	FONT_SHADER->Send1F(glGetUniformLocation(FONT_SHADER->gProgram, "sw"), sw );


	glVertexAttribPointer(FONT_SHADER->vertex_pos, 3, GL_FLOAT, GL_FALSE, sizeof(TFontVertex), (void*)(offsetof(struct TFontVertex, v)));
	glVertexAttribPointer(FONT_SHADER->texture_coord, 2, GL_FLOAT, GL_FALSE, sizeof(TFontVertex), (void*)(offsetof(struct TFontVertex, t)));

	glEnableVertexAttribArray(FONT_SHADER->vertex_pos);
	glEnableVertexAttribArray(FONT_SHADER->texture_coord);

		for (int i=0; i < text.length(); i++)
				{
			int index = find_index(text[i]);
				glBindTexture(GL_TEXTURE_2D, Alphabet[ index ].texture.texture);
				glDrawArrays(GL_TRIANGLE_FAN, i*4 , 4);
				}


		glDisableVertexAttribArray(FONT_SHADER->vertex_pos);
		glDisableVertexAttribArray(FONT_SHADER->texture_coord);
	FONT_SHADER->Disable();
		glBindBuffer(GL_ARRAY_BUFFER, 0);


	glDisable(GL_BLEND);
	glDepthMask(GL_TRUE);
	glEnable(GL_DEPTH_TEST);
}

void DrawText(float x, float y, float size, AnsiString atext)
{
	DrawText(x, y, size, atext, font_color);
}

};

fragment shader


uniform sampler2D font_tex;
    varying vec2 texcoord;
 
uniform vec3 FONT_COLOR;
    
void main()
{
vec3 color =    texture2D( font_tex, texcoord ).rgb;
 
float intensity = 0.0;
 
if (color.x > 0.5)
intensity = 0.0;
else
intensity = 1.0;
 
 
 
 
 
gl_FragColor = vec4(FONT_COLOR, intensity);
}
 

 

vertex shader


attribute vec3 Vpos;
attribute vec2 Vtexcoord;
varying vec2 texcoord;
uniform float sw;
uniform float sh;
 
void main()
{
float x = -1.0 + (Vpos.x / sw) * 2.0;
float y = -1.0 + (Vpos.y / sh) * 2.0;
texcoord = Vtexcoord;
gl_Position = vec4(vec2(x,y), 0.0, 1.0);
}
 

 

 

 

Important thing here is that you can define image left, top, width and height in lets say pixels (knowing opengl window size)

 

so you just draw a quad for (one image) that is lets say at top left corner of ogl window:

 

in fragment shader you calculate on screen coordinate (Vpos is vertex position, sw ogl window width, sh ogl window height)

 

float x = -1.0 + (Vpos.x / sw) * 2.0;
float y = -1.0 + (Vpos.y / sh) * 2.0;
 
 
since screen coordinate in ogl is from -1..1 you will put exactly sized image whereever you want

Share this post


Link to post
Share on other sites

this is an example of drawing 2d text as set of 2d textured images (that you load each texture for each character)


I have to downvote because the OP has to (1) pick apart your class structure, and (2) try to figure out what the classes you didn't give code for do.  That's worse than useless to somebody who by definition is unsure what code to use in the first place.

Share this post


Link to post
Share on other sites

What exactly are your doubts about drawing 2D?

 

As far as I know, the way you describe, is the way to do it (and I wouldn't call it "mimicking" a 2D environment. It IS a 2D environment).

 

You set up the ortho projection, and draw textured quads.

Preferably, you set the ortho projection to match the application's window resolution and draw the quad the exact size of the texture you want to draw. That results in essentialy the same as what other APIs call 'sprites' (like Flash/Java/etc).

 

And, again, that's pretty much all that's needed.

 

Sorry if I'm misunderstanding your question (apart from me not providing articles), but there's not really much else to it that I'm aware.

 

 

Yes, what you describe is the way to do 2D rendering.

 

It's important to realise that OpenGL doesn't differentiate between 2D and 3D; it just defines a standard pipeline that everything goes through.  Whether or not something appears 2D or 3D depends on the type of projection you use, and that's just a matter of putting different numbers into what is otherwise the same mathematical equations.

 

In other words, learning 2D on OpenGL is the same as learning 3D, and if you know one you will also know the other.

 

Now, older versions of OpenGL did have a 2D pipeline, of sorts, and you could get something up and running using glDrawPixels, glBitmap, etc calls.  But: (1) this 2D pipeline is very limited, (2) it's deprecated in more recent OpenGL versions, (3) it was never likely to be hardware-accelerated on consumer hardware anyway, and (4) it doesn't exist in OpenGL ES so if you want to run on mobile devices or WebGL, you can't use it.

 

In other words, nobody ever used it, and any 2D OpenGL game you've ever seen will be using the standard pipeline with an ortho projection instead.

 

That's what I meant, My initial progress was using OpenGL 2.1(~), so I'm old fashioned trying to evolve, so the concepts aren't sitting well in my head. From an 3d infrastructure perspective, I need to make a 2D pipeline so I could create 2d images, it does sound simple, but sounds too complex just to draw an image on the screen. Isn't there a way writing images to buffers (A quick way, unlike glDrawPixels, or the whole buffering transfering)? Or because there's no efficient way to do it, we have to using the pipeline for that?

 

 

this is an example of drawing 2d text as set of 2d textured images (that you load each texture for each character)


struct TFontChar
{
int id;
AnsiString txt;
AnsiString FontName;
TGLTexture texture;
};

struct TFontVertex
{
	t3dpoint<float> v;
	textpoint t;
};

struct TFont
{


	TFont()
	{
		initialized = false;
		font_color = vec3(0.0, 1.0, 0.0);
	}

	~TFont()
	{
if(initialized)
{
	glDeleteBuffers(1, &alphabet_vbuffer);

delete FONT_SHADER;
delete FONT_EVENT_SHADER;
}
	}

AnsiString chartable;
TFontChar * Alphabet;
TFontVertex * FONT_VERTEX_BUFFER;
TShaderObject * FONT_SHADER;
TShaderObject * FONT_EVENT_SHADER;
bool initialized;
vec3 font_color;
unsigned int alphabet_vbuffer;
float sw,sh;
 void initialize_char_table(AnsiString FONT_DIR, float asw, float ash, AnsiString appdir) //additionally load default font for debugging
	{
	 sw=asw;
	 sh=ash;
CAN_LOG = true;
		FONT_SHADER = new TShaderObject();

		FONT_SHADER->LoadShaderProgram(appdir+"shaders/fonts/base_font_vp.shader",appdir+"shaders/fonts/base_font_fp.shader");

		FONT_EVENT_SHADER = new TShaderObject();

		FONT_EVENT_SHADER->LoadShaderProgram(appdir+"shaders/fonts/event_font_vp.shader",appdir+"shaders/fonts/event_font_fp.shader");



		chartable = " ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-+.,=:{}()[]/*;!<>_?";
int x = chartable.length();
		Alphabet = new TFontChar[ x ];
//		ALOG("alphabet length: "+IntToStr(x));

		for (int i=0; i < chartable.length(); i++)
		{
//ALOG("FONT INDEX: "+IntToStr(i));
			Alphabet[i].texture.px_height = 32;
			Alphabet[i].texture.px_width  = 32;
		Alphabet[i].texture.LoadTGA(appdir+FONT_DIR+IntToStr(i)+".tga");
		Alphabet[i].txt = chartable[i];
		}

		FONT_VERTEX_BUFFER = new TFontVertex[ 256*4 ]; //max 256 chars...
for (int i=0; i < 256; i++)
{

	FONT_VERTEX_BUFFER[i*4+0].t = textpoint(0.0, 0.0);
	FONT_VERTEX_BUFFER[i*4+0].v = t3dpoint<float>(0.0+i*18.0, 0.0, 0.0);
	FONT_VERTEX_BUFFER[i*4+1].t = textpoint(1.0, 0.0);
	FONT_VERTEX_BUFFER[i*4+1].v = t3dpoint<float>(0.0+i*18.0+18.0, 0.0, 0.0);
	FONT_VERTEX_BUFFER[i*4+2].t = textpoint(1.0, 1.0);
	FONT_VERTEX_BUFFER[i*4+2].v = t3dpoint<float>(0.0+i*18.0+18.0, 0.0 + 18.0, 0.0);
	FONT_VERTEX_BUFFER[i*4+3].t = textpoint(0.0, 1.0);
	FONT_VERTEX_BUFFER[i*4+3].v = t3dpoint<float>(0.0, 0.0 + 18.0, 0.0);
}

		glGenBuffers(1, &alphabet_vbuffer);
		glBindBuffer(GL_ARRAY_BUFFER, alphabet_vbuffer);
		glBufferData(GL_ARRAY_BUFFER, sizeof(TFontVertex) * 256 * 4, FONT_VERTEX_BUFFER, GL_STATIC_DRAW);

		glBindBuffer(GL_ARRAY_BUFFER, 0);
		ALOG("DONE WITH LOADING FONT");
		initialized = true;
	}


	 int find_index(char txt)
	{
		for (int i=0; i < chartable.length(); i++)
		{
if (Alphabet[i].txt[0] == txt) return i;
		}

		return 1;
	}



void DrawEventText(float x, float y, float size, vec3 color, float alpha, AnsiString text);


void DrawText(float x, float y, float size, AnsiString atext, vec3 color)
{

	glActiveTexture(GL_TEXTURE0);

	glDisable(GL_DEPTH_TEST);
	glDepthMask(GL_FALSE);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	AnsiString text = UpperCase(atext);

	//lets assume we draw from left top corner of text
	for (int i=0; i < 256; i++)
	{
		FONT_VERTEX_BUFFER[i*4+0].t = textpoint(0.0, 0.0);
		FONT_VERTEX_BUFFER[i*4+0].v = t3dpoint<float>(x+i*size, y, 0.0);

		FONT_VERTEX_BUFFER[i*4+1].t = textpoint(1.0, 0.0);
		FONT_VERTEX_BUFFER[i*4+1].v = t3dpoint<float>(x+i*size+size, y, 0.0);

		FONT_VERTEX_BUFFER[i*4+2].t = textpoint(1.0, 1.0);
		FONT_VERTEX_BUFFER[i*4+2].v = t3dpoint<float>(x+i*size+size, y + size, 0.0);


		FONT_VERTEX_BUFFER[i*4+3].t = textpoint(0.0, 1.0);
		FONT_VERTEX_BUFFER[i*4+3].v = t3dpoint<float>(x+i*size, y + size, 0.0);
	}

	glBindBuffer(GL_ARRAY_BUFFER, alphabet_vbuffer);
	glBufferSubData(GL_ARRAY_BUFFER,0, sizeof(TFontVertex) * 256 * 4, FONT_VERTEX_BUFFER);


	FONT_SHADER->Enable();
	FONT_SHADER->Send1I(glGetUniformLocation(FONT_SHADER->gProgram, "font_tex"), 0 );
	FONT_SHADER->Send3F(glGetUniformLocation(FONT_SHADER->gProgram, "FONT_COLOR"), color );
	FONT_SHADER->Send1F(glGetUniformLocation(FONT_SHADER->gProgram, "sh"), sh );
	FONT_SHADER->Send1F(glGetUniformLocation(FONT_SHADER->gProgram, "sw"), sw );


	glVertexAttribPointer(FONT_SHADER->vertex_pos, 3, GL_FLOAT, GL_FALSE, sizeof(TFontVertex), (void*)(offsetof(struct TFontVertex, v)));
	glVertexAttribPointer(FONT_SHADER->texture_coord, 2, GL_FLOAT, GL_FALSE, sizeof(TFontVertex), (void*)(offsetof(struct TFontVertex, t)));

	glEnableVertexAttribArray(FONT_SHADER->vertex_pos);
	glEnableVertexAttribArray(FONT_SHADER->texture_coord);

		for (int i=0; i < text.length(); i++)
				{
			int index = find_index(text[i]);
				glBindTexture(GL_TEXTURE_2D, Alphabet[ index ].texture.texture);
				glDrawArrays(GL_TRIANGLE_FAN, i*4 , 4);
				}


		glDisableVertexAttribArray(FONT_SHADER->vertex_pos);
		glDisableVertexAttribArray(FONT_SHADER->texture_coord);
	FONT_SHADER->Disable();
		glBindBuffer(GL_ARRAY_BUFFER, 0);


	glDisable(GL_BLEND);
	glDepthMask(GL_TRUE);
	glEnable(GL_DEPTH_TEST);
}

void DrawText(float x, float y, float size, AnsiString atext)
{
	DrawText(x, y, size, atext, font_color);
}

};

fragment shader


uniform sampler2D font_tex;
    varying vec2 texcoord;
 
uniform vec3 FONT_COLOR;
    
void main()
{
vec3 color =    texture2D( font_tex, texcoord ).rgb;
 
float intensity = 0.0;
 
if (color.x > 0.5)
intensity = 0.0;
else
intensity = 1.0;
 
 
 
 
 
gl_FragColor = vec4(FONT_COLOR, intensity);
}
 

 

vertex shader


attribute vec3 Vpos;
attribute vec2 Vtexcoord;
varying vec2 texcoord;
uniform float sw;
uniform float sh;
 
void main()
{
float x = -1.0 + (Vpos.x / sw) * 2.0;
float y = -1.0 + (Vpos.y / sh) * 2.0;
texcoord = Vtexcoord;
gl_Position = vec4(vec2(x,y), 0.0, 1.0);
}
 

 

 

 

Important thing here is that you can define image left, top, width and height in lets say pixels (knowing opengl window size)

 

so you just draw a quad for (one image) that is lets say at top left corner of ogl window:

 

in fragment shader you calculate on screen coordinate (Vpos is vertex position, sw ogl window width, sh ogl window height)

 

float x = -1.0 + (Vpos.x / sw) * 2.0;
float y = -1.0 + (Vpos.y / sh) * 2.0;
 
 
since screen coordinate in ogl is from -1..1 you will put exactly sized image whereever you want

 

 

Hmm thanks for the example,but i'm already familiar with openGL api :) 

 

 

this is an example of drawing 2d text as set of 2d textured images (that you load each texture for each character)

I have to downvote because the OP has to (1) pick apart your class structure, and (2) try to figure out what the classes you didn't give code for do.  That's worse than useless to somebody who by definition is unsure what code to use in the first place.

 

 

There's no need to be negative, he gave a nice example of using 2D graphics.

 

Orthogonal 3D is the way to do 2D.

 

I see.

 

Also, if you are feeling brave, you can look at the SDL code for rendering 2D stuff with OpenGL.  It does use some 2.0 stuff, but it is still in use today.

I use the SDL renderer stuff for simple prototyping.

 

https://hg.libsdl.org/SDL/file/e12c38730512/src/render/opengl/SDL_render_gl.c

 

I'll give it a look , thanks! 

Share this post


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

  • Advertisement