• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
jeff8j

OpenGL
Really Big Textures?

17 posts in this topic

I have some advanced models one in particular has a 14mb png texture which opengl does not like but being the only thing showing can handle the model just fine and I think can handle it with textures just not 1 big one.

I am far from a 3d modeler so have no clue about the best way to do this but I would assume there is a way to break the giant texture into smaller gpu friendly textures how can I do this? I use blender for tinkering although im up for anything.

Also is there a library that can do this on the fly?
0

Share this post


Link to post
Share on other sites
simple downsampling is not suitable? breaking texture into multiple pieces can be hard depending on how UV are mapped to the model. If you have only a terrain that's fine and simple, more complex models will make things harder if not impossible. You can split the texture into 4 textures and remap UV to 1 to 4 different sets of UVs. That will need a shader and 4 textures used at the same time. So input of the vertex is always a UV set (you don't need to change UV). But instead of using 1 texture unit you use 4 textures units (each one with 1/4 of the original image)

-------->U
0......0.5....1
. ...............
0.5...0.5....1
................
1......1.......1
V

When UV is in the first quad you scale it by 2 and use first texture newU= 2*U; newV=V*2;
when UV is in the second quad newU = U*2 -1; newV = V*2;
When UV is in the third quad newU=U*2; newV = V*2-1;
When UV is in the fourth quad newU=U*2-1; newV = V*2-1;

quads assumed in this order

1 2
3 4
1

Share this post


Link to post
Share on other sites
Hi DemonRad

Downsampling will work but im looking to get really good detail out of the object and downsampling to something like 1024x1024 will quickly deteriorate quality as its a big model. I do think that I will give it a try though just too see.

Hmm I dont think breaking it down manually is an option as its a mesh/model not something easier like terrain and its lots triangles so far out of my knowledge.

Theres no way something like blender or 3d studio max can take a max texture size and then break it up accordingly? It makes no difference how its broken up to me I just want to show it and fly through the model I dont need animation or anything.
0

Share this post


Link to post
Share on other sites
[quote]I have some advanced models one in particular has a 14mb png texture which opengl does not like but being the only thing showing can handle the model just fine and I think can handle it with textures just not 1 big one.[/quote]
What is the texture size? What does opengl does not like it mean? Are you using DXT compression?
0

Share this post


Link to post
Share on other sites
Hi jeff8j, do try to be as specific as possible about errors. The nature of the error affects what solutions people will offer. Is there a code error? The object appears black? The texture looks distorted? If there is a visual artefact, a screenshot of how it looks in your game vs in the modelling program may help.
0

Share this post


Link to post
Share on other sites
The texture is 12,000 by 12,000 right now and not using dxt just a raw rgba texture.

At the moment I broke everything I was trying to change from the old fixed pipeline to using shaders and made a horrible mess.

Does anyone have a drop in class for assimp with devil and opengl?
0

Share this post


Link to post
Share on other sites
Lol I would be surprised if my card could even do 8192x8192.

Ill post a pic as soon as I get it going again.

Its only used for specific scenes that will pan across the outside of the ship where the game itself takes place inside so no performance concern because at max were talking the ship and a few other smaller things in the scene at once. Im for the sections was hoping for an easy way to achieve them with software rather than me messing with the model.
0

Share this post


Link to post
Share on other sites
Chop your image up into square sections that are 2048x2048 with the end sections only carrying whatever is left.
Take the uv coords 0 to 1, and mutliply them by 12,000. Then convert them to 0 to 1 for each section. Do some math and convert pixel coordinate x = 2048, y = 2048 = 1,1 for tile 0,0. x= (2048 + 1024), y = (2048 + 512) = .5,.25 for the texture tile 1,1
0

Share this post


Link to post
Share on other sites
8192x8192 is REALLY large. Even modern games don't typically exceed 2048x2048, and most get by on MUCH less (shadowmaps, for instance, are often 512x512). I have seen demos (e.g. NVIDIA's human head) that produce very [i]very[/i] high quality results with 4096x4096, and that had a [i]lot[/i] of sampling.

The only excuse I can think of for a texture that large is raw medical or scientific survey measurements. And even that should be reduced before going on a screen. You don't have 12000x12000 pixels on a monitor, so it's just plain pointless to have that much data.

-G
0

Share this post


Link to post
Share on other sites
dpadam450 I am going to take my little knowledge and work with that, in my mind thats exactly what needs to be done and wouldnt be much processing either, although im not confident about my ability to pull it off lol.

Geometrain 12000x12000 is really large for a single image but not when it occupies 10 seconds or so of maneuvering from multiple points to and from multiple angles it can actually quite easily be alot more. Thanks for the concern but theres alot of data that we would like to have a 1to1 scale.
0

Share this post


Link to post
Share on other sites
jeff8j, the only way you can get 1:1 scale is if a single piece of geometry is 12000x12000 in area, otherwise, it'll be down sampled by the hardware anyway.

but, let's say you absolutely have to(although i'm doubtful you can provide an actual valid reason that each pixel absolutely must be seen(and again, the hardware will downsample via nearest/linear mapping based on MAG and MIN filters to screen space for your texture anyway),

what you need to do is what dpadman said:

upon loading the texture, split it into several tiles, let's say 4096x4096, this means a total of 9 tiles in a row major format, where the mapping between each tile is 0-4096/12000=0.3413.

so, in the pixel shader, you take the input uv, from the original modeal and do something like:

[code]
sampler2D TexTiles[9];
vec2 inputUV;
vec2 UVMap; //0.3413 for both u/v.

void main(void){
int xtile = floor(inputUV.x/UVMap.x);
int yTile = floor(inputUV.y/UVMap.y);
sampler2D MappedTile = TexTiles[xTile+yTile*3];
vec2 mappedUV = vec2((inputUV.x-xtile*UVMap.x)/UVMap.x, (inputUV.y-ytile*UVMap.y)/UVMap.y); //get the inputUV into the tile range, then divide by the maximum size to map between 0-1.
vec4 Texel = texture2D(MappedTile, MappedUV);
}
[/code]

anywho, that's what my pixel shader would probably look like, but i doubt i'd ever build a game that absolutely relied on such ridiculously sized textures. Edited by slicer4ever
0

Share this post


Link to post
Share on other sites
Well it should be 1:1 it just wont be all visible so not all 12000x12000 but 1920x1280 give or take would be visible and be 1:1 although still probably not exactly the same.

I havent yet started on the code to break the texture apart but that looks like it will help out alot thank you.

If you had a big structure that played a major role how would you go about building it then besides using such a huge texture? Would you break it down into levels or something arbitrary of that nature? For us that would make it harder to edit because its not like a building made of squares that can be equally separated. Thats why I was wondering if something could break it down in software not necessarily at run time.
0

Share this post


Link to post
Share on other sites
[quote name='jeff8j' timestamp='1343713146' post='4964722']
Well it should be 1:1 it just wont be all visible so not all 12000x12000 but 1920x1280 give or take would be visible and be 1:1 although still probably not exactly the same.

I havent yet started on the code to break the texture apart but that looks like it will help out alot thank you.

If you had a big structure that played a major role how would you go about building it then besides using such a huge texture? Would you break it down into levels or something arbitrary of that nature? For us that would make it harder to edit because its not like a building made of squares that can be equally separated. Thats why I was wondering if something could break it down in software not necessarily at run time.
[/quote]

it sounds like your doing a perspective projection setup for your camera, so again, how the texture is filtered before it reach's the screen means that you won't ever have a 1:1 projection:screen space, the only way is via ortho projection, and it doesn't sound like this is an ortho simulation.

for your question, you say this is a game, I wouldn't build my editor to be bound to loading a single huge model/texture, this is absolutely horrible in terms of performance, you would have practically no method of culling large piece's of offscreen geometry, because all of the geometry/level sounds like it's one huge model(although i could be wrong, but this is what i understand from what i've read). I would never build a game in such a way, instead, the level would be broken up into chunks, and managed in such a way that i can create a nice bsp tree. as such, i could then have my modeler break the 12000x12000 texture into several pieces, to be mapped over several objects.

either way, without more information about what you are doing, we can't suggest a better approach/method, all you have told us is that it's a large model and texture, it's still a game, and it's viewed from several viewpoints. what is it?, why is it so difficult to be broken down manually? what are you trying to accomplish? Edited by slicer4ever
0

Share this post


Link to post
Share on other sites
[quote name='Geometrian' timestamp='1343707161' post='4964696']
The only excuse I can think of for a texture that large is raw medical or scientific survey measurements. And even that should be reduced before going on a screen. You don't have 12000x12000 pixels on a monitor, so it's just plain pointless to have that much data.

-G
[/quote]

It is not pointless to have a lot of data. I regularly work with data that is dozens or hundreds of Gigabyte in size and all of it is needed. The important point is: not at the same time. The same goes for the OPs problem. If he just needs a wide shot from the distance of his ship, then, yes, he could just downsample his data. A lot. But if he needs detail images of his ship he will need the full resolution texture (or more accurately: small subsets of the full resolution image at any one time). That is what LoD concepts are about after all.
0

Share this post


Link to post
Share on other sites
[quote name='jeff8j' timestamp='1343713146' post='4964722']
If you had a big structure that played a major role how would you go about building it then besides using such a huge texture? Would you break it down into levels or something arbitrary of that nature? For us that would make it harder to edit because its not like a building made of squares that can be equally separated. Thats why I was wondering if something could break it down in software not necessarily at run time.
[/quote]

If an object is so big that it needs a texture of that resolution then the object will be too big to be seen on screen at once in all that detail.
Therefore your object is the problem because the object is too big.

Large structres in games are made up of smaller substructures so that we can cull the chunks which aren't visable at any given moment and only process those which are.

For example, lets say you had a huge castle in the world. This would not be made as a single model instead various walls, ramparts and turrets would be made seperately and then placed together to form the final world object.

If you built the model as one solid object then you can only visibility test against that one huge object. Lets say the castle is 3 million verts in size. Now lets say you can only see the tip of the top of a tower - in the 'huge model' method you now have to submit and run the vertex shader for all 3 million verts (give or take depending on reuse) where as with a broken up model you'll end up submitting only the tower segement which might only be a few thousand verts at most.

The long and the short of it is you are not going to need a single model of such a size that it will need a single texture map of that size; if you have a model of that size then you'll want to break it up.

Doing otherwise is going to cost you performance AND, as you've discovered, is physically impossible to do in many cases.
0

Share this post


Link to post
Share on other sites
I might sound a bit simple, but the way you described those specific scenes makes me guess that those are cutscenes. If it's so, and you really need a texture this size, you could consider prerendering the scene. With the right settings, you could even make it look similar to an engine render. It would add the hassle of using a video decoder and displaying it, but this might be still easier than getting a 12k*12k texture working properly on the desired range of machines.
Also, as written above, breaking the model itself can be a nice idea too. This could work best if you had reusable parts of your object. This way you could get over redundant mesh data ( only store each element once ). The texture issue would be realigned - you would have to texture the individual parts. You would have small individual textures that would easily fit into the GPU. Also, the clipping issue would be conveniently solved.

Edit.: Forgot to mention that rendering takes some time, depending on your cutscene's length, complexity and your rig. Expect it to be somewhere from a few hours ( for 10-30 sec ), to a few days ( for 10-20 minutes ). However, these were just guesses based on my experiences. I own a not too competent machine. Edited by TheUnnamable
0

Share this post


Link to post
Share on other sites
[quote name='BitMaster' timestamp='1343717965' post='4964740']
[quote name='Geometrian' timestamp='1343707161' post='4964696']
The only excuse I can think of for a texture that large is raw medical or scientific survey measurements. And even that should be reduced before going on a screen. You don't have 12000x12000 pixels on a monitor, so it's just plain pointless to have that much data.

-G
[/quote]

It is not pointless to have a lot of data. I regularly work with data that is dozens or hundreds of Gigabyte in size and all of it is needed. The important point is: not at the same time. The same goes for the OPs problem. If he just needs a wide shot from the distance of his ship, then, yes, he could just downsample his data. A lot. But if he needs detail images of his ship he will need the full resolution texture (or more accurately: small subsets of the full resolution image at any one time). That is what LoD concepts are about after all.[/quote]I should clarify, that's what I meant when I said "that should be reduced before going on a screen." If your data is too large to even fit on your graphics card, that's an excellent indication that you need to do CPU processing to transfer the relevant bits only. However, I maintain that, while over time a large amount of different data might be loaded and displayed, a large amount of data in a short time is almost always unnecessary.[quote name='jeff8j' timestamp='1343707765' post='4964701']Geometrain 12000x12000 is really large for a single image but not when it occupies 10 seconds or so of maneuvering from multiple points to and from multiple angles it can actually quite easily be alot more.[/quote]I think the absolute worst case scenario for something like this is a REALLY up-close fly-through of a REALLY detailed model. You can imagine a quad with your texture mapped onto it, and then looking along one of the diagonals. Nearly all the data is visible, but most of it is minified. The problem is that there's not really a hard distinction between levels of detail--you blend mipmap levels for this. Another worst case is looking at that quad from above as a scale of about 1:1, then rapidly panning around the texture area. Breaking up the model into pieces will help, but you can still get worst cases like these.

If you really need every part of a fully, 100% contiguous texture that doesn't fit in texture memory, by definition, you're out of luck. You can get "all" of that detail at once by paging mipmap level texels in as necessary. This makes things more complicated, and again makes filtering (e.g. mipmap blending, anisotropic filtering) hard if not impossible.

I still feel like we're asking the wrong questions, though. Seriously--you need a 12K texture for an object? The largest unpaged texture I have [i]ever[/i] seen in a game is 8K (the hardware limit), and that was a hack to demonstrate how ridiculously useless it was. It's OK to have smaller textures. Will a 2x or 3x reduction [i]really[/i] hurt that much? There ARE situations where that kind of resolution is warranted (offline rendering, maybe), but unless you need cinematic-quality rendering, you're barking up the wrong tree.

Maybe you DO need that much resolution. But do you really need [i]information[/i], or just [i]detail[/i]? Procedural texturing uses next to no memory, and because texture samples are into smaller images (for lookup tables), it's cache-coherent and faster than sampling the actual data. If the state is small enough, you don't even need (texture) lookup tables at all! You can make a hybrid approach where you sample a more reasonably-sized texture, and then add as much detail as you want with some noise. This works [i]so well[/i] that offline renderers often do [i]that[/i] instead of making huge textures (memory efficiency pays off on the CPU too!). [i]Every[/i] major renderer has procedural texture support for [i]this exact reason[/i]. Don't forget, Perlin noise was [i]invented[/i] to solve this problem!

Maybe you DO need that much resolution because your texture is broadband noise, doesn't have a nice Fourier decomposition, and so recreating it with noise is out, or maybe you just can't add noise instead because every single subpixel-sized texel must be exactly right for some reason. Maybe you just need to view five orders of magnitude of texture all at once. In these cases, even if you [i]can[/i] figure out a way to robustly figure out which texels are necessary, page them in from RAM and render them, you're still talking about processing and transferring up to hundreds of megabytes of texels every few frames--a gigabyte or so per second if you really have a bad case. It's possible, but that will start eating up a lot of your CPU and GPU time just on data transfer. Many applications fail--I have seen games where clumsily-paged textures lead to LOD jumps (not in geometry but in texture). This is [i]disconcerting[/i] and [i]distracting[/i]. Setting the texture resolution smaller fixes the problem. There are no jumps, and the game plays smoothly. Even if a pixel here or there [i]could[/i] be more detailed, it is [i]immensely better[/i] not to have the little pops all over the place.

So maybe you DO need all that resolution, and you can't recreate it with noise--now you've figured out a way to rapidly page texels in and out of CPU and GPU memory--maybe with PBOs so it's somewhat asynchronous and doesn't hurt too much, and it works robustly and is miraculously realtime. What have you gained? You can display so much information that it's silly--humans can't differentiate small changes in data changing at more than about two times per second. Your model is rendered with much more detail than is needed. If you paused the moving camera and looked closely, admittedly you could see a pixel or two that are different--the higher resolution one looks better, yes. Maybe you're zoomed in and huge sections of texture space are magnified. That would point to a LOD problem (which is beside the point)--but hey, the texture is maybe [i]twice[/i] as detailed in each direction, so you win, right?

In sum:
-I am almost certain that you don't need a 12000x12000 texel texture, even without knowing exactly what your application is.
-Even for the most demanding applications, you still almost certainly don't need that much--you can recreate it MUCH more efficiently (and often, better) using procedural/hybrid techniques.
-This problem occurs frequently in industry, because people want "higher resolution" everything. It's a natural desire, but it is almost always an insignificant one. In nearly all cases, there is [i]minimal perceptual difference[/i] in even large resolution improvements, simply because the display technology and the human eye can't keep up. [i]Even if you succeed[/i] in making most of your scene's textures more detailed, it usually doesn't even matter because you kill your framerate and you get LOD pops--which is just not an improvement.
-On modern graphics hardware, it is (usually) possible to page texels in and out of memory fast enough to keep up with non-pathological cases where textures don't fit into memory, assuming minimal other work is being done on both the CPU and GPU. If doing it is still somehow absolutely critical, you might be better off looking into realtime CPU raytracing.
-A texture about half the resolution in both dimensions (4096x4096) avoids all the above problems. For magnified pixels, of which there are usually none, it looks maybe half as good--but in return you get portability, high framerate, robustness, elegance, and simplicity--and it's still ultimately high-quality. I [i]strongly recommend[/i] using 4096x4096 as a [i]maximum[/i], and (for only the [i]most extreme[/i] of circumstances), add procedural noise. Edited by Geometrian
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0

  • Similar Content

    • By Solid_Spy
      Hello, I have been working on SH Irradiance map rendering, and I have been using a GLSL pixel shader to render SH irradiance to 2D irradiance maps for my static objects. I already have it working with 9 3D textures so far for the first 9 SH functions.
      In my GLSL shader, I have to send in 9 SH Coefficient 3D Texures that use RGBA8 as a pixel format. RGB being used for the coefficients for red, green, and blue, and the A for checking if the voxel is in use (for the 3D texture solidification shader to prevent bleeding).
      My problem is, I want to knock this number of textures down to something like 4 or 5. Getting even lower would be a godsend. This is because I eventually plan on adding more SH Coefficient 3D Textures for other parts of the game map (such as inside rooms, as opposed to the outside), to circumvent irradiance probe bleeding between rooms separated by walls. I don't want to reach the 32 texture limit too soon. Also, I figure that it would be a LOT faster.
      Is there a way I could, say, store 2 sets of SH Coefficients for 2 SH functions inside a texture with RGBA16 pixels? If so, how would I extract them from inside GLSL? Let me know if you have any suggestions ^^.
    • By DaniDesu
      #include "MyEngine.h" int main() { MyEngine myEngine; myEngine.run(); return 0; } MyEngine.h
      #pragma once #include "MyWindow.h" #include "MyShaders.h" #include "MyShapes.h" class MyEngine { private: GLFWwindow * myWindowHandle; MyWindow * myWindow; public: MyEngine(); ~MyEngine(); void run(); }; MyEngine.cpp
      #include "MyEngine.h" MyEngine::MyEngine() { MyWindow myWindow(800, 600, "My Game Engine"); this->myWindow = &myWindow; myWindow.createWindow(); this->myWindowHandle = myWindow.getWindowHandle(); // Load all OpenGL function pointers for use gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); } MyEngine::~MyEngine() { this->myWindow->destroyWindow(); } void MyEngine::run() { MyShaders myShaders("VertexShader.glsl", "FragmentShader.glsl"); MyShapes myShapes; GLuint vertexArrayObjectHandle; float coordinates[] = { 0.5f, 0.5f, 0.0f, 0.5f, -0.5f, 0.0f, -0.5f, 0.5f, 0.0f }; vertexArrayObjectHandle = myShapes.drawTriangle(coordinates); while (!glfwWindowShouldClose(this->myWindowHandle)) { glClearColor(0.5f, 0.5f, 0.5f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw something glUseProgram(myShaders.getShaderProgram()); glBindVertexArray(vertexArrayObjectHandle); glDrawArrays(GL_TRIANGLES, 0, 3); glfwSwapBuffers(this->myWindowHandle); glfwPollEvents(); } } MyShaders.h
      #pragma once #include <glad\glad.h> #include <GLFW\glfw3.h> #include "MyFileHandler.h" class MyShaders { private: const char * vertexShaderFileName; const char * fragmentShaderFileName; const char * vertexShaderCode; const char * fragmentShaderCode; GLuint vertexShaderHandle; GLuint fragmentShaderHandle; GLuint shaderProgram; void compileShaders(); public: MyShaders(const char * vertexShaderFileName, const char * fragmentShaderFileName); ~MyShaders(); GLuint getShaderProgram(); const char * getVertexShaderCode(); const char * getFragmentShaderCode(); }; MyShaders.cpp
      #include "MyShaders.h" MyShaders::MyShaders(const char * vertexShaderFileName, const char * fragmentShaderFileName) { this->vertexShaderFileName = vertexShaderFileName; this->fragmentShaderFileName = fragmentShaderFileName; // Load shaders from files MyFileHandler myVertexShaderFileHandler(this->vertexShaderFileName); this->vertexShaderCode = myVertexShaderFileHandler.readFile(); MyFileHandler myFragmentShaderFileHandler(this->fragmentShaderFileName); this->fragmentShaderCode = myFragmentShaderFileHandler.readFile(); // Compile shaders this->compileShaders(); } MyShaders::~MyShaders() { } void MyShaders::compileShaders() { this->vertexShaderHandle = glCreateShader(GL_VERTEX_SHADER); this->fragmentShaderHandle = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(this->vertexShaderHandle, 1, &(this->vertexShaderCode), NULL); glShaderSource(this->fragmentShaderHandle, 1, &(this->fragmentShaderCode), NULL); glCompileShader(this->vertexShaderHandle); glCompileShader(this->fragmentShaderHandle); this->shaderProgram = glCreateProgram(); glAttachShader(this->shaderProgram, this->vertexShaderHandle); glAttachShader(this->shaderProgram, this->fragmentShaderHandle); glLinkProgram(this->shaderProgram); return; } GLuint MyShaders::getShaderProgram() { return this->shaderProgram; } const char * MyShaders::getVertexShaderCode() { return this->vertexShaderCode; } const char * MyShaders::getFragmentShaderCode() { return this->fragmentShaderCode; } MyWindow.h
      #pragma once #include <glad\glad.h> #include <GLFW\glfw3.h> class MyWindow { private: GLFWwindow * windowHandle; int windowWidth; int windowHeight; const char * windowTitle; public: MyWindow(int windowWidth, int windowHeight, const char * windowTitle); ~MyWindow(); GLFWwindow * getWindowHandle(); void createWindow(); void MyWindow::destroyWindow(); }; MyWindow.cpp
      #include "MyWindow.h" MyWindow::MyWindow(int windowWidth, int windowHeight, const char * windowTitle) { this->windowHandle = NULL; this->windowWidth = windowWidth; this->windowWidth = windowWidth; this->windowHeight = windowHeight; this->windowTitle = windowTitle; glfwInit(); } MyWindow::~MyWindow() { } GLFWwindow * MyWindow::getWindowHandle() { return this->windowHandle; } void MyWindow::createWindow() { // Use OpenGL 3.3 and GLSL 3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // Limit backwards compatibility glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Prevent resizing window glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Create window this->windowHandle = glfwCreateWindow(this->windowWidth, this->windowHeight, this->windowTitle, NULL, NULL); glfwMakeContextCurrent(this->windowHandle); } void MyWindow::destroyWindow() { glfwTerminate(); } MyShapes.h
      #pragma once #include <glad\glad.h> #include <GLFW\glfw3.h> class MyShapes { public: MyShapes(); ~MyShapes(); GLuint & drawTriangle(float coordinates[]); }; MyShapes.cpp
      #include "MyShapes.h" MyShapes::MyShapes() { } MyShapes::~MyShapes() { } GLuint & MyShapes::drawTriangle(float coordinates[]) { GLuint vertexBufferObject{}; GLuint vertexArrayObject{}; // Create a VAO glGenVertexArrays(1, &vertexArrayObject); glBindVertexArray(vertexArrayObject); // Send vertices to the GPU glGenBuffers(1, &vertexBufferObject); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject); glBufferData(GL_ARRAY_BUFFER, sizeof(coordinates), coordinates, GL_STATIC_DRAW); // Dertermine the interpretation of the array buffer glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), (void *)0); glEnableVertexAttribArray(0); // Unbind the buffers glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); return vertexArrayObject; } MyFileHandler.h
      #pragma once #include <cstdio> #include <cstdlib> class MyFileHandler { private: const char * fileName; unsigned long fileSize; void setFileSize(); public: MyFileHandler(const char * fileName); ~MyFileHandler(); unsigned long getFileSize(); const char * readFile(); }; MyFileHandler.cpp
      #include "MyFileHandler.h" MyFileHandler::MyFileHandler(const char * fileName) { this->fileName = fileName; this->setFileSize(); } MyFileHandler::~MyFileHandler() { } void MyFileHandler::setFileSize() { FILE * fileHandle = NULL; fopen_s(&fileHandle, this->fileName, "rb"); fseek(fileHandle, 0L, SEEK_END); this->fileSize = ftell(fileHandle); rewind(fileHandle); fclose(fileHandle); return; } unsigned long MyFileHandler::getFileSize() { return (this->fileSize); } const char * MyFileHandler::readFile() { char * buffer = (char *)malloc((this->fileSize)+1); FILE * fileHandle = NULL; fopen_s(&fileHandle, this->fileName, "rb"); fread(buffer, this->fileSize, sizeof(char), fileHandle); fclose(fileHandle); buffer[this->fileSize] = '\0'; return buffer; } VertexShader.glsl
      #version 330 core layout (location = 0) vec3 VertexPositions; void main() { gl_Position = vec4(VertexPositions, 1.0f); } FragmentShader.glsl
      #version 330 core out vec4 FragmentColor; void main() { FragmentColor = vec4(1.0f, 0.0f, 0.0f, 1.0f); } I am attempting to create a simple engine/graphics utility using some object-oriented paradigms. My first goal is to get some output from my engine, namely, a simple red triangle.
      For this goal, the MyShapes class will be responsible for defining shapes such as triangles, polygons etc. Currently, there is only a drawTriangle() method implemented, because I first wanted to see whether it works or not before attempting to code other shape drawing methods.
      The constructor of the MyEngine class creates a GLFW window (GLAD is also initialized here to load all OpenGL functionality), and the myEngine.run() method in Main.cpp is responsible for firing up the engine. In this run() method, the shaders get loaded from files via the help of my FileHandler class. The vertices for the triangle are processed by the myShapes.drawTriangle() method where a vertex array object, a vertex buffer object and vertrex attributes are set for this purpose.
      The while loop in the run() method should be outputting me the desired red triangle, but all I get is a grey window area. Why?
      Note: The shaders are compiling and linking without any errors.
      (Note: I am aware that this code is not using any good software engineering practices (e.g. exceptions, error handling). I am planning to implement them later, once I get the hang of OpenGL.)

       
    • By KarimIO
      EDIT: I thought this was restricted to Attribute-Created GL contexts, but it isn't, so I rewrote the post.
      Hey guys, whenever I call SwapBuffers(hDC), I get a crash, and I get a "Too many posts were made to a semaphore." from Windows as I call SwapBuffers. What could be the cause of this?
      Update: No crash occurs if I don't draw, just clear and swap.
      static PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be { sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format 32, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 0, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 24, // 24Bit Z-Buffer (Depth Buffer) 0, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; if (!(hDC = GetDC(windowHandle))) return false; unsigned int PixelFormat; if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) return false; if (!SetPixelFormat(hDC, PixelFormat, &pfd)) return false; hRC = wglCreateContext(hDC); if (!hRC) { std::cout << "wglCreateContext Failed!\n"; return false; } if (wglMakeCurrent(hDC, hRC) == NULL) { std::cout << "Make Context Current Second Failed!\n"; return false; } ... // OGL Buffer Initialization glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glBindVertexArray(vao); glUseProgram(myprogram); glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, (void *)indexStart); SwapBuffers(GetDC(window_handle));  
    • By Tchom
      Hey devs!
       
      I've been working on a OpenGL ES 2.0 android engine and I have begun implementing some simple (point) lighting. I had something fairly simple working, so I tried to get fancy and added color-tinting light. And it works great... with only one or two lights. Any more than that, the application drops about 15 frames per light added (my ideal is at least 4 or 5). I know implementing lighting is expensive, I just didn't think it was that expensive. I'm fairly new to the world of OpenGL and GLSL, so there is a good chance I've written some crappy shader code. If anyone had any feedback or tips on how I can optimize this code, please let me know.
       
      Vertex Shader
      uniform mat4 u_MVPMatrix; uniform mat4 u_MVMatrix; attribute vec4 a_Position; attribute vec3 a_Normal; attribute vec2 a_TexCoordinate; varying vec3 v_Position; varying vec3 v_Normal; varying vec2 v_TexCoordinate; void main() { v_Position = vec3(u_MVMatrix * a_Position); v_TexCoordinate = a_TexCoordinate; v_Normal = vec3(u_MVMatrix * vec4(a_Normal, 0.0)); gl_Position = u_MVPMatrix * a_Position; } Fragment Shader
      precision mediump float; uniform vec4 u_LightPos["+numLights+"]; uniform vec4 u_LightColours["+numLights+"]; uniform float u_LightPower["+numLights+"]; uniform sampler2D u_Texture; varying vec3 v_Position; varying vec3 v_Normal; varying vec2 v_TexCoordinate; void main() { gl_FragColor = (texture2D(u_Texture, v_TexCoordinate)); float diffuse = 0.0; vec4 colourSum = vec4(1.0); for (int i = 0; i < "+numLights+"; i++) { vec3 toPointLight = vec3(u_LightPos[i]); float distance = length(toPointLight - v_Position); vec3 lightVector = normalize(toPointLight - v_Position); float diffuseDiff = 0.0; // The diffuse difference contributed from current light diffuseDiff = max(dot(v_Normal, lightVector), 0.0); diffuseDiff = diffuseDiff * (1.0 / (1.0 + ((1.0-u_LightPower[i])* distance * distance))); //Determine attenuatio diffuse += diffuseDiff; gl_FragColor.rgb *= vec3(1.0) / ((vec3(1.0) + ((vec3(1.0) - vec3(u_LightColours[i]))*diffuseDiff))); //The expensive part } diffuse += 0.1; //Add ambient light gl_FragColor.rgb *= diffuse; } Am I making any rookie mistakes? Or am I just being unrealistic about what I can do? Thanks in advance
    • By yahiko00
      Hi,
      Not sure to post at the right place, if not, please forgive me...
      For a game project I am working on, I would like to implement a 2D starfield as a background.
      I do not want to deal with static tiles, since I plan to slowly animate the starfield. So, I am trying to figure out how to generate a random starfield for the entire map.
      I feel that using a uniform distribution for the stars will not do the trick. Instead I would like something similar to the screenshot below, taken from the game Star Wars: Empire At War (all credits to Lucasfilm, Disney, and so on...).

      Is there someone who could have an idea of a distribution which could result in such a starfield?
      Any insight would be appreciated
  • Popular Now