OpenGL mesa3d buffer uncompatible with jpg & my Baseimage buffer..help!

Recommended Posts

wwinthan    122
i use opengl and mesa3d.org to render the 2d drawing offscreen and get the buffer. again i can successfully save buffer to iSaveJpegdirect by using jpglib but i need to convert the mesa3d offscreen rendered buffer to our own cImage object. and there is uncompatible with mesa3d buffer and our own cImage class(object) buffer. help! please cImage image; image.Create(buffer8,4000,4000,24); iSaveJpeg(image,"C:\\jpgimage.jpg"); << //this one give me blank page (help!) iSaveJpegdirect(buffer8,"C:\\jpgimagedirect.jpg"); << this one is working and get the image i want cImage class can be found in the following link. Download BaseImage.h from Uploading.com Download BaseImage.cpp from Uploading.com ///////////////////// iSaveJpeg & iSaveJpegdirect are here //////////////////////

template <class T>
bool iSaveJpegdirect(cBaseImage<T>& image,unsigned char* buffersimage,char * filename)
{
JSAMPLE* image_buffer;	/* Points to large array of R,G,B-order data */
int image_height;	/* Number of rows in image */
int image_width;
image_height = 4000;
image_width = 4000;
//image_height = 454;
//image_width = 367;
image_buffer = buffersimage;

struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
FILE * outfile;		/* target file */
JSAMPROW row_pointer[1];	/* pointer to JSAMPLE row[s] */
int row_stride;		/* physical row width in image buffer */
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);

if ((outfile = fopen(filename, "wb")) == NULL) {
fprintf(stderr, "can't open %s\n", filename);
exit(1);
}
jpeg_stdio_dest(&cinfo, outfile);
cinfo.image_width = image_width; 	/* image width and height, in pixels */
cinfo.image_height = image_height;
cinfo.input_components = 3;		/* # of color components per pixel */
cinfo.in_color_space = JCS_RGB; 	/* colorspace of input image */
jpeg_set_defaults(&cinfo);
int quality=200;
jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
jpeg_start_compress(&cinfo, TRUE);
row_stride = image_width * 3;	/* JSAMPLEs per row in image_buffer */
while (cinfo.next_scanline < cinfo.image_height) {
row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
(void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
jpeg_finish_compress(&cinfo);
fclose(outfile);
jpeg_destroy_compress(&cinfo);
return true;
}
// It returns true, so that it can be used in ASSERT(Save()) for debugging
template <class T>
bool iSaveJpeg(cBaseImage<T>& image, const string& imageFile)
{
//	if (imageFile.find(".tif")!=string::npos) return iSaveTiff(image, imageFile);
//	ofstream s(imageFile.c_str(),ios::out|ios::binary);
//	s << image;
//	s.close();
//	return true;
/* This struct contains the JPEG compression parameters and pointers to
* working space (which is allocated as needed by the JPEG library).
* It is possible to have several such structures, representing multiple
* compression/decompression processes, in existence at once.  We refer
* to any one struct (and its associated working data) as a "JPEG object".
*/
struct jpeg_compress_struct cinfo;
/* This struct represents a JPEG error handler.  It is declared separately
* because applications often want to supply a specialized error handler
* (see the second half of this file for an example).  But here we just
* take the easy way out and use the standard error handler, which will
* print a message on stderr and call exit() if compression fails.
* Note that this struct must live as long as the main JPEG parameter
* struct, to avoid dangling-pointer problems.
*/
struct jpeg_error_mgr jerr;
/* More stuff */
FILE * outfile;		/* target file */
JSAMPROW row_pointer[1];	/* pointer to JSAMPLE row[s] */
int row_stride;		/* physical row width in image buffer */

/* Step 1: allocate and initialize JPEG compression object */

/* We have to set up the error handler first, in case the initialization
* step fails.  (Unlikely, but it could happen if you are out of memory.)
* This routine fills in the contents of struct jerr, and returns jerr's
*/
cinfo.err = jpeg_std_error(&jerr);
/* Now we can initialize the JPEG compression object. */
jpeg_create_compress(&cinfo);

/* Step 2: specify data destination (eg, a file) */
/* Note: steps 2 and 3 can be done in either order. */

/* Here we use the library-supplied code to send compressed data to a
* stdio stream.  You can also write your own code to do something else.
* VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
* requires it in order to write binary files.
*/
if ((outfile = fopen(imageFile.c_str(), "wb")) == NULL) {
//    fprintf(stderr, "can't open %s\n", filename);
//    exit(1);
assert(0);
}
jpeg_stdio_dest(&cinfo, outfile);

/* Step 3: set parameters for compression */

/* First we supply a description of the input image.
* Four fields of the cinfo struct must be filled in:
*/
int ncomp = (image.GetBitCount()==24)?3:1;
cinfo.image_width = image.Width(); 	/* image width and height, in pixels */
cinfo.image_height = image.Height();
cinfo.input_components = ncomp;		/* # of color components per pixel */
cinfo.in_color_space = (ncomp==1)?JCS_GRAYSCALE:JCS_RGB; 	/* colorspace of input image */
/* Now use the library's routine to set default compression parameters.
* (You must set at least cinfo.in_color_space before calling this,
* since the defaults depend on the source color space.)
*/
jpeg_set_defaults(&cinfo);
/* Now you can set any non-default parameters you wish to.
* Here we just illustrate the use of quality (quantization table) scaling:
*/
jpeg_set_quality(&cinfo, 100, TRUE /* limit to baseline-JPEG values */);

/* Step 4: Start compressor */

/* TRUE ensures that we will write a complete interchange-JPEG file.
* Pass TRUE unless you are very sure of what you're doing.
*/
jpeg_start_compress(&cinfo, TRUE);

/* Step 5: while (scan lines remain to be written) */
/*           jpeg_write_scanlines(...); */

/* Here we use the library's state variable cinfo.next_scanline as the
* loop counter, so that we don't have to keep track ourselves.
* To keep things simple, we pass one scanline per call; you can pass
* more if you wish, though.
*/
row_stride = image.Width() * ncomp;	/* JSAMPLEs per row in image_buffer */
ubyte* line_buffer = new ubyte[row_stride];

while (cinfo.next_scanline < cinfo.image_height) {
/* jpeg_write_scanlines expects an array of pointers to scanlines.
* Here the array is only one element long, but you could pass
* more than one scanline at a time if that's more convenient.
*/
ubyte* line = image[cinfo.image_height-1-cinfo.next_scanline].GetBufferPointer();;
ubyte* ptr = line_buffer;
for (int x=0; x<ncomp*image.Width(); x+=ncomp, ptr+=ncomp)
{
for (int c=0; c<ncomp; c++)
*(ptr+ncomp-1-c) = line[x+c];
//			*ptr = 255-line[x];
//	image.GetRGB(line[x], *ptr, *(ptr+1), *(ptr+2));
}
row_pointer[0] = line_buffer;
(void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
delete [] line_buffer;
/* Step 6: Finish compression */

jpeg_finish_compress(&cinfo);
/* After finish_compress, we can close the output file. */
fclose(outfile);

/* Step 7: release JPEG compression object */

/* This is an important step since it will release a good deal of memory. */
jpeg_destroy_compress(&cinfo);

return true;
}



wwinthan    122
hi Graz,

Share on other sites
Ravyne    14300
What makes you think your custom buffer is compatible with the mesa buffer? Some things to check: pixel format, byte ordering and padding/alignment constraints.

Most likely, you will not be able to do a straight-across copy like you seem to be relying on.

Share on other sites
wwinthan    122
since i'm new to image processing, what you mean by padding and alignment stuff? could you please explain more for me. besides, what does it mean by 32 bit alignment? help!

Share on other sites
Ravyne    14300
Alignment refers to a constraint on the memory location at which the data begins, for example, it might require that the data begin on a WORD or DWORD boundary.

Sometimes this alignment constraint is per line of the image, which means that the data in line N must be padded (usually with 0 by convention, but the bytes are nearly always ignored in practice) such that line N+1 begins at a memory location which also satisfies the alignment constraint. This can be seen in the bitmap file format and Win32 DIBs, IIRC. Sometimes, images are padded out to the next higher power of two, which would be 4096x4096 in your case if true.

Specifically, 32bit alignment means that data must begin at an address that is aligned on a 32bit boundary, or, in layman's terms, the address should end in only 0, 4, 8 or C (hex), any other alignment would produce incorrect results.

Now, 24bit color presents some interesting possibilities -- It does not align naturally with the any single data type, ie it doesn't fill a 32bit int like 32bit ARGB color format would. But it does align on a multiple of of the fundamental data type, byte. The long and the short of all that is that the Mesa color buffers for 24 bit mode might be a triplet of bytes per color, or a 32bit word which leaves 1 byte's worth unused. You'll have to find out what mesa does and compare that to what your own image class expects.

Share on other sites
wwinthan    122
cBaseImage.h & cpp can be found below
http://pastebin.com/m53eaed68

Share on other sites
wwinthan    122
mesa allocated and code here

Share on other sites
Ravyne    14300
Line 28 in the mesa code you posted seems to be allocating 4 channels, which means it is including an alpha channel in addition to the R, G and B channels. the 'bits' variable there also seems to be not the bits per pixel, but the pits per channel -- in other words, as best as I can tell, setting it to 32 like you have at the top means its allocating 1 float per channel per pixel, or 16 bytes per pixel -- you commented out setting it to 8, but 8 seems to have been correct, although you still have the additional alpha channel to deal with. You don't seem to be doing any alignment or padding, so that appears unnecessary if this code works on its own.

cBaseImage seems to allocate only 3 bytes per pixel, assuming that WidthBytes() simply divides by 8. It doesn't seem to allocate an alpha channel.

The bottom line is that you can't do a simple bitwise copy of one buffer into the other and expect it to work. As it stands, they are extremely different formats and have a different number of channels. You'll have to loop over each pixel and do the conversion or make cBaseImage's internal format such that it matches Mesa's internal format.

Share on other sites
wwinthan    122
i changed the format of mesa3d buffer to be compatible with buffer that cBaseImage accepts. but still it doesnt seem to be working out.
My last question is what is the use of SetPalette() and GetPalette for? they also accepts ubyte*(unsigned char)..thx

Share on other sites
wwinthan    122
GLint bits=8;
const char *filename ="C:\\image81.ppm";
// const GLint z = 32;
const GLint z = 8;
const GLint stencil = 0;
const GLint accum = 0;
OSMesaContext ctx;
void *buffer;
GLint cBits;
assert(bits == 8 ||
bits == 16 ||
bits == 32);
assert(type == GL_UNSIGNED_BYTE ||
type == GL_UNSIGNED_SHORT ||
type == GL_FLOAT);
ctx = OSMesaCreateContextExt(OSMESA_RGB, z, stencil, accum, NULL );
buffer = malloc(WIDTH*HEIGHT*3*bits/8);
if (!OSMesaMakeCurrent( ctx, buffer, type, WIDTH, HEIGHT )) {

}
rendering comes here

GLubyte *buffer8 = (GLubyte *) buffer;

image1.Create(4000,4000,8);
image1.CreatePalette(256);
//image1.InitGrayPalette(256);
image1.SetPalette(buffer8,4000*4000*8);
//image1.InitGrayPalette();
//image1.Init8BitColorPalette();
iSaveJpeg(image1,"C:\\testing.jpg");
i tried above code and can't successfully save to jpg.
the internal format of mesa3d and cBaseImage is now compatible i suppose.

wwinthan    122
plz help!

wwinthan    122
solved!

Share on other sites
Ravyne    14300
Good work, what did you ultimately find to be the cause of the problem?

Create an account

Register a new account

• Similar Content

• By Zaphyk
I am developing my engine using the OpenGL 3.3 compatibility profile. It runs as expected on my NVIDIA card and on my Intel Card however when I tried it on an AMD setup it ran 3 times worse than on the other setups. Could this be a AMD driver thing or is this probably a problem with my OGL code? Could a different code standard create such bad performance?

• I'm trying to get some legacy OpenGL code to run with a shader pipeline,
The legacy code uses glVertexPointer(), glColorPointer(), glNormalPointer() and glTexCoordPointer() to supply the vertex information.
I know that it should be using setVertexAttribPointer() etc to clearly define the layout but that is not an option right now since the legacy code can't be modified to that extent.
I've got a version 330 vertex shader to somewhat work:
#version 330 uniform mat4 osg_ModelViewProjectionMatrix; uniform mat4 osg_ModelViewMatrix; layout(location = 0) in vec4 Vertex; layout(location = 2) in vec4 Normal; // Velocity layout(location = 3) in vec3 TexCoord; // TODO: is this the right layout location? out VertexData { vec4 color; vec3 velocity; float size; } VertexOut; void main(void) { vec4 p0 = Vertex; vec4 p1 = Vertex + vec4(Normal.x, Normal.y, Normal.z, 0.0f); vec3 velocity = (osg_ModelViewProjectionMatrix * p1 - osg_ModelViewProjectionMatrix * p0).xyz; VertexOut.velocity = velocity; VertexOut.size = TexCoord.y; gl_Position = osg_ModelViewMatrix * Vertex; } What works is the Vertex and Normal information that the legacy C++ OpenGL code seem to provide in layout location 0 and 2. This is fine.
What I'm not getting to work is the TexCoord information that is supplied by a glTexCoordPointer() call in C++.
Question:
What layout location is the old standard pipeline using for glTexCoordPointer()? Or is this undefined?

Side note: I'm trying to get an OpenSceneGraph 3.4.0 particle system to use custom vertex, geometry and fragment shaders for rendering the particles.

• Hi i am new to this forum  i wanted to ask for help from all of you i want to generate real time terrain using a 32 bit heightmap i am good at c++ and have started learning Opengl as i am very interested in making landscapes in opengl i have looked around the internet for help about this topic but i am not getting the hang of the concepts and what they are doing can some here suggests me some good resources for making terrain engine please for example like tutorials,books etc so that i can understand the whole concept of terrain generation.

• By KarimIO
Hey guys. I'm trying to get my application to work on my Nvidia GTX 970 desktop. It currently works on my Intel HD 3000 laptop, but on the desktop, every bind textures specifically from framebuffers, I get half a second of lag. This is done 4 times as I have three RGBA textures and one depth 32F buffer. I tried to use debugging software for the first time - RenderDoc only shows SwapBuffers() and no OGL calls, while Nvidia Nsight crashes upon execution, so neither are helpful. Without binding it runs regularly. This does not happen with non-framebuffer binds.
GLFramebuffer::GLFramebuffer(FramebufferCreateInfo createInfo) { glGenFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER, fbo); textures = new GLuint[createInfo.numColorTargets]; glGenTextures(createInfo.numColorTargets, textures); GLenum *DrawBuffers = new GLenum[createInfo.numColorTargets]; for (uint32_t i = 0; i < createInfo.numColorTargets; i++) { glBindTexture(GL_TEXTURE_2D, textures[i]); GLint internalFormat; GLenum format; TranslateFormats(createInfo.colorFormats[i], format, internalFormat); // returns GL_RGBA and GL_RGBA glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, createInfo.width, createInfo.height, 0, format, GL_FLOAT, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); DrawBuffers[i] = GL_COLOR_ATTACHMENT0 + i; glBindTexture(GL_TEXTURE_2D, 0); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, textures[i], 0); } if (createInfo.depthFormat != FORMAT_DEPTH_NONE) { GLenum depthFormat; switch (createInfo.depthFormat) { case FORMAT_DEPTH_16: depthFormat = GL_DEPTH_COMPONENT16; break; case FORMAT_DEPTH_24: depthFormat = GL_DEPTH_COMPONENT24; break; case FORMAT_DEPTH_32: depthFormat = GL_DEPTH_COMPONENT32; break; case FORMAT_DEPTH_24_STENCIL_8: depthFormat = GL_DEPTH24_STENCIL8; break; case FORMAT_DEPTH_32_STENCIL_8: depthFormat = GL_DEPTH32F_STENCIL8; break; } glGenTextures(1, &depthrenderbuffer); glBindTexture(GL_TEXTURE_2D, depthrenderbuffer); glTexImage2D(GL_TEXTURE_2D, 0, depthFormat, createInfo.width, createInfo.height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glBindTexture(GL_TEXTURE_2D, 0); glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthrenderbuffer, 0); } if (createInfo.numColorTargets > 0) glDrawBuffers(createInfo.numColorTargets, DrawBuffers); else glDrawBuffer(GL_NONE); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) std::cout << "Framebuffer Incomplete\n"; glBindFramebuffer(GL_FRAMEBUFFER, 0); width = createInfo.width; height = createInfo.height; } // ... // FBO Creation FramebufferCreateInfo gbufferCI; gbufferCI.colorFormats = gbufferCFs.data(); gbufferCI.depthFormat = FORMAT_DEPTH_32; gbufferCI.numColorTargets = gbufferCFs.size(); gbufferCI.width = engine.settings.resolutionX; gbufferCI.height = engine.settings.resolutionY; gbufferCI.renderPass = nullptr; gbuffer = graphicsWrapper->CreateFramebuffer(gbufferCI); // Bind glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo); // Draw here... // Bind to textures glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textures[0]); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, textures[1]); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, textures[2]); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, depthrenderbuffer); Here is an extract of my code. I can't think of anything else to include. I've really been butting my head into a wall trying to think of a reason but I can think of none and all my research yields nothing. Thanks in advance!

• Hi everyone, I've shared my 2D Game Engine source code. It's the result of 4 years working on it (and I still continue improving features ) and I want to share with the community. You can see some videos on youtube and some demo gifs on my twitter account.
This Engine has been developed as End-of-Degree Project and it is coded in Javascript, WebGL and GLSL. The engine is written from scratch.
This is not a professional engine but it's for learning purposes, so anyone can review the code an learn basis about graphics, physics or game engine architecture. Source code on this GitHub repository.
I'm available for a good conversation about Game Engine / Graphics Programming

• 15
• 10
• 18
• 9
• 10