/* Exports the left and right eye view as images */ void exportImage(void) { unsigned char *image; image = (unsigned char*)malloc((3*Settings::pixelWidth*Settings::pixelHeight)*sizeof(char)); glPixelStorei(GL_PACK_ALIGNMENT,1); // Left Image glReadBuffer(GL_BACK_LEFT); glReadPixels(0, 0, (int)Settings::pixelWidth, (int)Settings::pixelHeight, GL_BGR,GL_UNSIGNED_BYTE, image); FIBITMAP* leftImage = FreeImage_ConvertFromRawBits(image, (int)Settings::pixelWidth, (int)Settings::pixelHeight, 3*Settings::pixelWidth, 24, 0xFF0000, 0x00FF00, 0x0000FF, false); FreeImage_Save(FIF_BMP, leftImage, "left.bmp", 0); // Right image glReadBuffer(GL_BACK_RIGHT); glReadPixels(0, 0, (int)Settings::pixelWidth, (int)Settings::pixelHeight, GL_BGR, GL_UNSIGNED_BYTE, image); FIBITMAP* rightImage = FreeImage_ConvertFromRawBits(image, (int)Settings::pixelWidth, (int)Settings::pixelHeight, 3*Settings::pixelWidth, 24, 0xFF0000, 0x00FF00, 0x0000FF, false); FreeImage_Save(FIF_BMP, rightImage, "right.bmp", 0); free(image); }
void FreeImage::loadFromDatas( unsigned char * datas, const Math::Vec2<Size> & size, Format format, bool datasInvertY ) { unload(); lock(); setLoading( true ); _updateFormat( format ); this -> size = size; this -> invertY = datasInvertY; this -> loadingType = LoadingType::EMPTY; this -> fileName.clear(); //we have no reason to keep a filepath now. #ifdef WIN32 this -> fileNameW.clear(); //we have no reason to keep a filepath now. #endif // WIN32 #ifdef WIN32 if ( format == Format::RGB || format == Format::RGBA ) { //because FreeImage do not care of MASK and use BGR on Windows size_t numPixels = this -> size.x * this -> size.y; size_t offsetPerPixel = ( this -> BPP / 8 ); unsigned char * newDatas = new unsigned char[offsetPerPixel * numPixels]; auto otherIt = datas; auto thisIt = newDatas; if ( format == Format::RGB ) { for ( size_t i = 0; i < numPixels; i++ ) { thisIt[0] = otherIt[2]; thisIt[1] = otherIt[1]; thisIt[2] = otherIt[0]; otherIt += offsetPerPixel; thisIt += offsetPerPixel; } } else if ( format == Format::RGBA ) { for ( size_t i = 0; i < numPixels; i++ ) { thisIt[0] = otherIt[2]; thisIt[1] = otherIt[1]; thisIt[2] = otherIt[0]; thisIt[3] = otherIt[3]; otherIt += offsetPerPixel; thisIt += offsetPerPixel; } } this -> freeImage = FreeImage_ConvertFromRawBits( newDatas, this -> size.x, this -> size.y, this -> size.x * ( this -> BPP / 8 ), this -> BPP, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK, this -> invertY ); delete[] newDatas; } else { this -> freeImage = FreeImage_ConvertFromRawBits( datas, this -> size.x, this -> size.y, this -> size.x * ( this -> BPP / 8 ), this -> BPP, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK, this -> invertY ); } #else this -> freeImage = FreeImage_ConvertFromRawBits( datas, this -> size.x, this -> size.y, this -> size.x * ( this -> BPP / 8 ), this -> BPP, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK, this -> invertY ); #endif this -> stride = FreeImage_GetPitch( this -> freeImage ); setLoading( false ); setLoaded( true ); unlock(); }
/// // Save an image using the FreeImage library // bool SaveImage(char *fileName, char *buffer, int width, int height) { FREE_IMAGE_FORMAT format = FreeImage_GetFIFFromFilename(fileName); FIBITMAP *image = FreeImage_ConvertFromRawBits((BYTE*)buffer, width, height, width * 4, 32, 0xFF000000, 0x00FF0000, 0x0000FF00); return (FreeImage_Save(format, image, fileName) == TRUE) ? true : false; }
int main(int argc, char** argv) { int winx = 1920; int winy = 1080; glfwInit(); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4); GLFWwindow* window = glfwCreateWindow(winx, winy, "IGS View GLFW", NULL, NULL); if (!window) { glfwTerminate(); return -1; } glfwSetKeyCallback(window, glfw_key); glfwSetMouseButtonCallback(window, glfw_mousebutton); glfwSetCursorPosCallback(window, glfw_motion); /* Make the window's context current */ glfwMakeContextCurrent(window); glewExperimental = true; glewInit(); the_app = std::make_shared<application>(argc, argv, winx, winy); bool result_feedback = false; /* Loop until the user closes the window */ while (!glfwWindowShouldClose(window)) { glut_display(); #if 1 if (!result_feedback) { std::vector<std::array<uint8_t, 3>> data(winx*winy); glReadPixels(0, 0, winx, winy, GL_RGB, GL_UNSIGNED_BYTE, &data[0]); FIBITMAP* image = FreeImage_ConvertFromRawBits((unsigned char*)&data[0], winx, winy, 3 * winx, 24, 0xFF0000, 0x00FF00, 0x0000FF, false); FreeImage_Save(FIF_BMP, image, "result.bmp", 0); FreeImage_Unload(image); result_feedback = true; } #endif glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); the_app.reset(); return 0; }
void WindowGL::screenshot(std::string filename) { unsigned char* buffer = new unsigned char[800 * 600 * 3]; //TODO: dodac sciaganie wymiarow okna z WindowGL glReadPixels(0, 0, SIZE_W, SIZE_H, GL_BGR, GL_UNSIGNED_BYTE, buffer); std::cout << "INFO: Saving screen to: " << filename << std::endl; FIBITMAP * bitmap = FreeImage_ConvertFromRawBits(buffer, SIZE_W, SIZE_H, 800 * 3, 24, 0xFF0000, 0x00FF00, 0x0000FF, false); FreeImage_Save(FREE_IMAGE_FORMAT::FIF_PNG, bitmap, filename.c_str()); FreeImage_Unload(bitmap); delete[] buffer; }
void saveScreenshot(string fname) { int pix = w * h; BYTE pixels[3*pix]; glReadBuffer(GL_FRONT); glReadPixels(0,0,w,h,GL_BGR,GL_UNSIGNED_BYTE, pixels); FIBITMAP *img = FreeImage_ConvertFromRawBits(pixels, w, h, w * 3, 24, 0xFF0000, 0x00FF00, 0x0000FF, false); std::cout << "Saving screenshot: " << fname << "\n"; FreeImage_Save(FIF_PNG, img, fname.c_str(), 0); }
bool Webcam::saveFrame(string sFilename, bool bMirror) { if(!use) return false; if(!m_curFrame) return false; #ifdef USE_VIDEOINPUT FIBITMAP* bmp = FreeImage_ConvertFromRawBits(m_curFrame, m_iWidth, m_iHeight, m_iWidth * 3, 24, 0x0000FF, 0x00FF00, 0xFF0000, true); #elif !defined(NO_WEBCAM) FIBITMAP* bmp = FreeImage_ConvertFromRawBits(m_curFrame->data, m_iWidth, m_iHeight, m_iWidth * 3, 24, 0x0000FF, 0x00FF00, 0xFF0000, true); #else FIBITMAP* bmp = NULL; #endif if(!bmp) return false; if(bMirror) FreeImage_FlipHorizontal(bmp); #ifdef USE_VIDEOINPUT FreeImage_FlipVertical(bmp); #endif bool bRet = FreeImage_Save(FIF_JPEG, bmp, sFilename.c_str()); FreeImage_Unload(bmp); return bRet; }
void saveScreenshot() { int pix = windowWidth * windowHeight; BYTE pixels[3*pix]; glReadBuffer(GL_FRONT); glReadPixels(0,0,windowWidth,windowHeight,GL_BGR,GL_UNSIGNED_BYTE,pixels); FIBITMAP *img = FreeImage_ConvertFromRawBits(pixels, windowWidth, windowHeight, windowWidth * 3, 24, 0xFF0000, 0x00FF00, 0x0000FF, false); std::cout << "Saving screenshot: screenshot.png\n"; FreeImage_Save(FIF_PNG, img, "screenshot.png", 0); }
void save_png(gli::texture2D const & Texture, char const * Filename) { FreeImageInit(); FIBITMAP* Bitmap = FreeImage_ConvertFromRawBits( const_cast<BYTE*>(Texture.data<BYTE>()), Texture.dimensions().x, Texture.dimensions().y, Texture.dimensions().x * gli::component_count(Texture.format()), 24, 0x0000FF, 0xFF0000, 0x00FF00, false); FreeImage_Save(FIF_PNG, Bitmap, Filename, 0); FreeImage_Unload(Bitmap); }
void ofxGifEncoder::doSave() { // create a multipage bitmap FIMULTIBITMAP *multi = FreeImage_OpenMultiBitmap(FIF_GIF, ofToDataPath(fileName).c_str(), TRUE, FALSE); FIBITMAP * bmp = NULL; for(int i = 0; i < frames.size(); i++ ) { // we need to swap the channels if we're on little endian (see ofImage::swapRgb); #ifdef TARGET_LITTLE_ENDIAN swapRgb(frames[i]); #endif // get the pixel data bmp = FreeImage_ConvertFromRawBits( frames[i]->pixels, frames[i]->width, frames[i]->height, frames[i]->width*(frames[i]->bitsPerPixel/8), frames[i]->bitsPerPixel, 0, 0, 0, true // in of006 this (topdown) had to be false. ); #ifdef TARGET_LITTLE_ENDIAN swapRgb(frames[i]); #endif DWORD frameDuration = (DWORD) (frames[i]->duration * 1000.f); bmp = FreeImage_ColorQuantizeEx(bmp, FIQ_NNQUANT, nColors); // dithering :) if(ditherMode > OFX_GIF_DITHER_NONE) bmp = FreeImage_Dither(bmp, (FREE_IMAGE_DITHER)ditherMode); // clear any animation metadata used by this dib as we’ll adding our own ones FreeImage_SetMetadata(FIMD_ANIMATION, bmp, NULL, NULL); // add animation tags to dib[i] FITAG *tag = FreeImage_CreateTag(); if(tag) { FreeImage_SetTagKey(tag, "FrameTime"); FreeImage_SetTagType(tag, FIDT_LONG); FreeImage_SetTagCount(tag, 1); FreeImage_SetTagLength(tag, 4); FreeImage_SetTagValue(tag, &frameDuration); FreeImage_SetMetadata(FIMD_ANIMATION, bmp, FreeImage_GetTagKey(tag), tag); FreeImage_DeleteTag(tag); } FreeImage_AppendPage(multi, bmp); } FreeImage_Unload(bmp); FreeImage_CloseMultiBitmap(multi); }
FREEIMAGE_BMP* FREEIMAGE_LoadImage(const UString& filePath, BYTE* raw_data, int len) { if (!raw_data) return NULL; FREEIMAGE_BMP* vix_bmp = new FREEIMAGE_BMP; vix_bmp->path = filePath; vix_bmp->name = getFileName(filePath); vix_bmp->format = FREEIMAGE_FormatFromExtension(getFileExtension(filePath, false)); vix_bmp->data = NULL; vix_bmp->bitmap = NULL; switch (vix_bmp->format) { case FIF_PNG: FREEIMAGE_LoadPNGHeader(&vix_bmp->header, raw_data); break; case FIF_TARGA: FREEIMAGE_LoadTGAHeader(&vix_bmp->header, vix_bmp->data); break; case FIF_JPEG: FREEIMAGE_LoadJPGHeader(&vix_bmp->header, vix_bmp->data); break; } //Check if FreeImage has reading capabilities if (FreeImage_FIFSupportsReading(vix_bmp->format)) { int pitch = ((vix_bmp->header.bitdepth * vix_bmp->header.width + 31) / 32) * 4; vix_bmp->bitmap = FreeImage_ConvertFromRawBits(raw_data, vix_bmp->header.width, vix_bmp->header.height, pitch, vix_bmp->header.bitdepth * 4, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK); } //If image failed to load, return NULL if (!vix_bmp->bitmap) return NULL; FreeImage_FlipVertical(vix_bmp->bitmap); //return bitmap return vix_bmp; }
void poImage::load(uint w, uint h, uint c, const ubyte *pix) { if(bitmap) { totalAllocatedImageMemorySize -= FreeImage_GetDIBSize(bitmap); FreeImage_Unload(bitmap); } if(pix != NULL) bitmap = FreeImage_ConvertFromRawBits(const_cast<ubyte*>(pix), w, h, w*c, c*8, 0,0,0); else { bitmap = FreeImage_Allocate(w, h, c*8); char black[] = {0,0,0,0}; FreeImage_FillBackground(bitmap, black); } totalAllocatedImageMemorySize += FreeImage_GetDIBSize(bitmap); }
void Scene::saveImage(int t){ FreeImage_Initialise(); BYTE* pixels = new BYTE[ 3 * WIDTH * HEIGHT]; glReadPixels(0, 0, WIDTH, HEIGHT, GL_BGR, GL_UNSIGNED_BYTE, pixels); FIBITMAP* image = FreeImage_ConvertFromRawBits(pixels, WIDTH, HEIGHT, 3 * WIDTH, 24, 0x0000FF, 0xFF0000, 0x00FF00, false); // get a string to concat with an int stringstream nameStream; nameStream << "test" << t << ".png"; string name = nameStream.str(); char *a = new char[name.size() + 1]; a[name.size()] = 0; memcpy(a, name.c_str(), name.size()); if(FreeImage_Save(FIF_BMP, image, a, 0)) cout << "Image " << t << " successfully saved! " << endl ; FreeImage_DeInitialise(); //Cleanup ! }
void Film::WriteImage(std::string fname){ /*Before you use FreeImage, call FreeImage_Initialise(). To record the colors for each pixel, use an array of one byte elements. Then convert this array to a FIBITMAP object as follows, assuming the bytes are in RGB order:*/ FreeImage_Initialise(); int pix = width * height; BYTE *pixels = new BYTE[3 * pix]; memcpy((void *)pixels, (void *)colorbuffer, width * height * 3); FIBITMAP *img = FreeImage_ConvertFromRawBits(pixels, width, height, width * 3, 24, 0xFF0000, 0x00FF00, 0x0000FF, false); std::cout << "Saving screenshot: " << fname << "\n"; FreeImage_Save(FIF_PNG, img, fname.c_str(), 0); delete pixels; FreeImage_DeInitialise(); }
void save_png(gli::texture2D const & Texture, char const * Filename) { gli::texture2D Copy = gli::copy(Texture); switch(gli::component_count(Copy.format())) { default: assert(0); break; case 3: for(std::size_t Offset = 0; Offset < Copy.size() / 3; ++Offset) { glm::u8vec3 Src = *(reinterpret_cast<glm::u8vec3 const *>(Copy.data()) + Offset); *(reinterpret_cast<glm::u8vec3*>(Copy.data()) + Offset) = glm::u8vec3(Src.z, Src.y, Src.x); } break; case 4: for(std::size_t Offset = 0; Offset < Copy.size() / 4; ++Offset) { glm::u8vec4 Src = *(reinterpret_cast<glm::u8vec4 const *>(Copy.data()) + Offset); *(reinterpret_cast<glm::u8vec4*>(Copy.data()) + Offset) = glm::u8vec4(Src.z, Src.y, Src.x, Src.w); } break; } FreeImageInit(); FIBITMAP* Bitmap = FreeImage_ConvertFromRawBits( Copy.data<BYTE>(), Copy.dimensions().x, Copy.dimensions().y, static_cast<int>(Copy.dimensions().x * gli::component_count(Copy.format())), static_cast<unsigned int>(gli::component_count(Copy.format()) * 8), 0x0000FF, 0x00FF00, 0xFF0000, false); BOOL Result = FreeImage_Save(FIF_PNG, Bitmap, Filename, 0); assert(Result); FreeImage_Unload(Bitmap); }
freeimage::ImagePtr FrameBuffer::getImage() { #ifdef BRAYNS_USE_FREEIMAGE map(); const auto colorBuffer = getColorBuffer(); const auto& size = getSize(); freeimage::ImagePtr image( FreeImage_ConvertFromRawBits(const_cast<uint8_t*>(colorBuffer), size.x, size.y, getColorDepth() * size.x, 8 * getColorDepth(), 0xFF0000, 0x00FF00, 0x0000FF, false)); unmap(); #if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BGR freeimage::SwapRedBlue32(image.get()); #endif return image; #else return nullptr; #endif }
//---------------------------------------------------- FIBITMAP * getBmpFromPixels(ofPixels &pix){ FIBITMAP * bmp = NULL; int w = pix.getWidth(); int h = pix.getHeight(); unsigned char * pixels = pix.getPixels(); int bpp = pix.getBitsPerPixel(); int bytesPerPixel = pix.getBytesPerPixel(); bmp = FreeImage_ConvertFromRawBits(pixels, w,h, w*bytesPerPixel, bpp, 0,0,0, true); //this is for grayscale images they need to be paletted from: http://sourceforge.net/forum/message.php?msg_id=2856879 if( pix.getImageType() == OF_IMAGE_GRAYSCALE ){ RGBQUAD *pal = FreeImage_GetPalette(bmp); for(int i = 0; i < 256; i++) { pal[i].rgbRed = i; pal[i].rgbGreen = i; pal[i].rgbBlue = i; } } return bmp; }
//-------------------------------------------------------------- void ofxGifEncoder::save (vector <ofxGifFrame *> frames, string fileName, int nColors) { if (nColors < 2 || nColors > 256) { ofLog(OF_LOG_WARNING, "nColors must be between 2 and 256. your gif won't be saved"); return; } // create a multipage bitmap FIMULTIBITMAP *multi = FreeImage_OpenMultiBitmap(FIF_GIF, ofToDataPath(fileName).c_str(), TRUE, FALSE); FIBITMAP * bmp = NULL; for(int i = 0; i < frames.size(); i++ ) { // we need to swap the channels if we're on little endian (see ofImage::swapRgb); #ifdef TARGET_LITTLE_ENDIAN swapRgb(frames[i]); #endif // get the pixel data bmp = FreeImage_ConvertFromRawBits( frames[i]->pixels, frames[i]->width, frames[i]->height, frames[i]->width*(frames[i]->bitsPerPixel/8), frames[i]->bitsPerPixel, 0, 0, 0, true // in of006 this (topdown) had to be false. ); #ifdef TARGET_LITTLE_ENDIAN swapRgb(frames[i]); #endif DWORD frameDuration = (DWORD) frames[i]->duration * 1000.f; // bmp = FreeImage_ColorQuantize(bmp, FIQ_NNQUANT); // if we want to set a reduced color palette (2 to 256); bmp = FreeImage_ColorQuantizeEx(bmp, FIQ_NNQUANT, nColors); // dithering :) // you can set a different dither pattern for each frame // bmp = FreeImage_Dither(bmp, (FREE_IMAGE_DITHER)((i+1)%6)); //bmp = FreeImage_Dither(bmp, FID_BAYER8x8); // clear any animation metadata used by this dib as we’ll adding our own ones FreeImage_SetMetadata(FIMD_ANIMATION, bmp, NULL, NULL); // add animation tags to dib[i] FITAG *tag = FreeImage_CreateTag(); if(tag) { FreeImage_SetTagKey(tag, "FrameTime"); FreeImage_SetTagType(tag, FIDT_LONG); FreeImage_SetTagCount(tag, 1); FreeImage_SetTagLength(tag, 4); FreeImage_SetTagValue(tag, &frameDuration); FreeImage_SetMetadata(FIMD_ANIMATION, bmp, FreeImage_GetTagKey(tag), tag); FreeImage_DeleteTag(tag); } FreeImage_AppendPage(multi, bmp); } FreeImage_Unload(bmp); FreeImage_CloseMultiBitmap(multi); }
void ProcessKeyboard(void) { //======================================================================================= //======================================================================================= if (keys['L']) { jadeMonkey_LIGHT_POSITION_01[0] += .1; } if (keys['J']) { jadeMonkey_LIGHT_POSITION_01[0] -= .1; } if (keys['I']) { jadeMonkey_LIGHT_POSITION_01[1] += .1; } if (keys['K']) { jadeMonkey_LIGHT_POSITION_01[1] -= .1; } if (keys['O']) { jadeMonkey_LIGHT_POSITION_01[2] += .1; } if (keys['U']) { jadeMonkey_LIGHT_POSITION_01[2] -= .1; } //-------------------------------------------------------------------------- if (keys['X']) { jadeMonkey_SHININESS += 1.01; } if (keys['Z']) { jadeMonkey_SHININESS -= 1.01; } //================================================================================================================================== if(keys[VK_F8]) { ofstream outSettings("settings.cpp"); //------------------------------------------------------------------------------------------------------------------------------ outSettings << "var jadeMonkey_LIGHT_POSITION_01[] = {" << jadeMonkey_LIGHT_POSITION_01[0] << ", " << jadeMonkey_LIGHT_POSITION_01[1] << ", " << jadeMonkey_LIGHT_POSITION_01[2] << ", " << jadeMonkey_LIGHT_POSITION_01[3] << "};\n\n"; //------------------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------------------- outSettings << "var jadeMonkey_SHININESS = " << jadeMonkey_SHININESS << ";\n"; //------------------------------------------------------------------------------------------------------------------------------ // for(int i = 0; i < 512; i++) // { // outSettings << "var frequency[" << i << "] = " << frequency[i] << ";\n"; // } // outSettings << "var selectFrequency = " // << selectFrequency << ";\n\n"; //--------------------------------------------------------------------------------------------------------------------------- outSettings << "var eyeposition[] = {" << eyeposition[0] << ", " << eyeposition[1] << ", " << eyeposition[2] << ", 0.0};\n"; //------------------------------------------------------------------------------------------------------------------------------ outSettings << "var lookAt[] = {" << lookAt[0] << ", " << lookAt[1] << ", " << lookAt[2] << ", 0.0};\n"; //------------------------------------------------------------------------------------------------------------------------------ outSettings << "var rotateModelWithLeftMouse[] = {" << rotateModelWithLeftMouse[0] << ", " << rotateModelWithLeftMouse[1] << "};\n\n"; //------------------------------------------------------------------------------------------------------------------------------ outSettings << "var eyeposition_SHADOW[] = {" << eyeposition_SHADOW[0] << ", " << eyeposition_SHADOW[1] << ", " << eyeposition_SHADOW[2] << ", 1.0};\n"; //------------------------------------------------------------------------------------------------------------------------------ outSettings << "var eyeposition_SHADOW[] = {" << eyeposition_SHADOW[0] << ", " << eyeposition_SHADOW[1] << ", " << eyeposition_SHADOW[2] << "}; \n"; //---------------------------------------------------------------------------------------------------------------- } //==================================================================================================================================== //==================================================================================================================================== if (keys['Y'] && KEY_Y_IS_RESET) { GLubyte *pixmap =(GLubyte *)malloc(1920*1080*4); glReadPixels(0,0,1920,1080,GL_BGRA,GL_UNSIGNED_BYTE,pixmap); FIBITMAP *texture = FreeImage_ConvertFromRawBits( pixmap, 1920, 1080, 1920*4, 32, 0xFF0000, 0x00FF00, 0x0000FF, true); FreeImage_Save(FIF_BMP, texture, "AAAAA.bmp", 0); free(pixmap); KEY_Y_IS_RESET = false; } //------------------------------------ if (!keys['Y']) { KEY_Y_IS_RESET = true; } //==================================================================================================================================== //==================================================================================================================================== //======================================================================================= if (keys['A'] && !keys[VK_SHIFT]) { eyeposition[0] += 0.15; lookAt[0] += 0.15; } //----------------------------------- if (keys['D'] && !keys[VK_SHIFT]) { eyeposition[0] -= 0.15; lookAt[0] -= 0.15; } //=================================== if (keys['S'] && !keys[VK_SHIFT]) { eyeposition[1] += 0.15; lookAt[1] += 0.15; } //----------------------------------- if (keys['W'] && !keys[VK_SHIFT]) { eyeposition[1] -= 0.15; lookAt[1] -= 0.15; //----------------------------------- } if (keys['Q'] && !keys[VK_SHIFT]) { eyeposition[2] += 0.15; lookAt[2] += 0.15; } //=================================== if (keys['E'] && !keys[VK_SHIFT]) { eyeposition[2] -= 0.15; lookAt[2] -= 0.15; } //=================================== //======================================================================================= //======================================================================================= if (keys['A'] && keys[VK_SHIFT]) { eyeposition_SHADOW[0] += 0.01; } //----------------------------------- if (keys['D'] && keys[VK_SHIFT]) { eyeposition_SHADOW[0] -= 0.01; } //=================================== if (keys['S'] && keys[VK_SHIFT]) { eyeposition_SHADOW[1] += 0.01; } //----------------------------------- if (keys['W'] && keys[VK_SHIFT]) { eyeposition_SHADOW[1] -= 0.01; } //=================================== if (keys['Q'] && keys[VK_SHIFT]) { eyeposition_SHADOW[2] += 0.01; } //----------------------------------- if (keys['E'] && keys[VK_SHIFT]) { eyeposition_SHADOW[2] -= 0.01; } //======================================================================================= }//_END_ProcessKeyboard()
void HighResolutionRender(renderStruct *render, imageStruct *image, RenderMandelbrotPtr RenderMandelbrot) { // Set new resolution image->xRes = image->xRes*HIGHRESOLUTIONMULTIPLIER; image->yRes = image->yRes*HIGHRESOLUTIONMULTIPLIER; //Set updateTex flag to 0 so we don't try to draw it on screen. render->updateTex = 0; // Allocate new host pixels array of larger size. We need this regardless of interop free(image->pixels); // CAREFUL: these sizes can easily overflow a 32bit int. Use uint64_t uint64_t allocSize = image->xRes * image->yRes * sizeof*(image->pixels) *3; printf(" --- reallocating host pixels array: %.2lfMB\n", allocSize/1024.0/1024.0); image->pixels = malloc(allocSize); #ifdef WITHOPENCL // Here, it is likely that the array(s) of colour values will not fit in device global memory. // We have to render the frame in tiles, each of which fits. // // OpenCL platform gives us a max allocation, which is "at least" 1/4 of the memory size. We // can't therefore, allocate two arrays of the max allocation -- they are not guaranteed to fit. // We allocate two arrays, each half the max allocation. cl_int err; // Determine the size (in bytes) of one row of pixels uint64_t rowSize = image->xRes * sizeof *(image->pixels) * 3; // Determine how many rows we can fit in half the max allocation uint64_t maxAllocRows = (render->deviceMaxAlloc/2) / rowSize; // The number of tiles required to render the frame: int tiles = (int)ceil((double)image->yRes/(double)maxAllocRows); // Size of a single tile uint64_t fullTileSize = maxAllocRows * rowSize; // Allocate tile-sized global memory arrays on device. // Store handle to OpenGL texture so it can be recovered later. // The struct variable will be reassigned, this makes running the kernels simpler. cl_mem keepPixelsTex = render->pixelsTex; // Release the existing pixels array err = clReleaseMemObject(render->pixelsDevice); CheckOpenCLError(err, __LINE__); // Allocate new arrays printf(" --- allocating tile arrays on device: %lfMB\n", 2.0*fullTileSize/1024.0/1024.0); render->pixelsDevice = clCreateBuffer(render->contextCL, CL_MEM_READ_WRITE, fullTileSize, NULL, &err); CheckOpenCLError(err, __LINE__); render->pixelsTex = clCreateBuffer(render->contextCL, CL_MEM_READ_WRITE, fullTileSize, NULL, &err); CheckOpenCLError(err, __LINE__); // Store full image resolution and boundaries, we will adjust the values in the struct int yResFull = image->yRes; double yMinFull = image->yMin; double yMaxFull = image->yMax; // Render tiles, and copy data back to the host array for (int t = 0; t < tiles; t++) { printf(" --- computing tile %d/%d...\n", t+1, tiles); // Set tile resolution. Each has maxAllocRows apart from the last, // which might have fewer as it contains the remainder. image->yRes = maxAllocRows; if (t == tiles-1) { image->yRes = yResFull % maxAllocRows; } // Reset global size, as the resolution has changed render->globalSize = image->yRes * image->xRes; assert(render->globalSize % render->localSize == 0); // Set tile boundaries. We are computing a fraction maxAllocRows/yResFull of the full //image, starting at the beginning of the t-th tile. The final tile uses xMaxFull for xMax. image->yMin = yMinFull + t*((double)maxAllocRows/(double)yResFull)*(yMaxFull-yMinFull); image->yMax = yMinFull + (t+1)*((double)maxAllocRows/(double)yResFull)*(yMaxFull-yMinFull); if (t == tiles-1) { image->yMax = yMaxFull; } // Render RenderMandelbrot(render, image); // Copy data from render->pixelsTex (the output of GaussianBlurKernel2) uint64_t storeOffset = t * (maxAllocRows * image->xRes * 3); // The final tile is smaller if (t == tiles-1) { fullTileSize = image->yRes * image->xRes * sizeof *(image->pixels) * 3; } err = clEnqueueReadBuffer(render->queue, render->pixelsTex, CL_TRUE, 0, fullTileSize, &(image->pixels[storeOffset]), 0, NULL, NULL); CheckOpenCLError(err, __LINE__); } // Reset image boundaries and resolution image->yRes = yResFull; image->yMin = yMinFull; image->yMax = yMaxFull; #else // If not using OpenCL, simply render directly onto the reallocated image->pixels array RenderMandelbrot(render, image); #endif // Save png printf(" --- creating png...\n"); // Create raw pixel array GLubyte * rawPixels; uint64_t rawAllocSize = image->xRes * image->yRes * sizeof *rawPixels *3; rawPixels = malloc(rawAllocSize); for (uint64_t i = 0; i < image->xRes*image->yRes*3; i+=3) { // note change in order, rgb -> bgr! rawPixels[i+0] = (GLubyte)((image->pixels)[i+2]*255); rawPixels[i+1] = (GLubyte)((image->pixels)[i+1]*255); rawPixels[i+2] = (GLubyte)((image->pixels)[i+0]*255); } FIBITMAP* img = FreeImage_ConvertFromRawBits(rawPixels, image->xRes, image->yRes, 3*image->xRes, 24, 0x000000, 0x000000, 0x000000, TRUE); FreeImage_Save(FIF_PNG, img, "test.png", 0); FreeImage_Unload(img); free(rawPixels); // Reset original values to continue with live rendering image->xRes = image->xRes/HIGHRESOLUTIONMULTIPLIER; image->yRes = image->yRes/HIGHRESOLUTIONMULTIPLIER; render->updateTex = 1; free(image->pixels); image->pixels = malloc(image->xRes * image->yRes * sizeof *(image->pixels) *3); #ifdef WITHOPENCL // Release large global memory buffers clReleaseMemObject(render->pixelsDevice); clReleaseMemObject(render->pixelsTex); // Recover handle to OpenGL texture render->pixelsTex = keepPixelsTex; size_t allocSizeOrig = image->xRes * image->yRes * 3 * sizeof *(image->pixels); render->pixelsDevice = clCreateBuffer(render->contextCL, CL_MEM_READ_WRITE, allocSizeOrig, NULL, &err); CheckOpenCLError(err, __LINE__); // Reset global size, as the resolution has changed render->globalSize = image->yRes * image->xRes; assert(render->globalSize % render->localSize == 0); #endif }
void ParticleRenderer::drawFrame() { /* clear all pixels */ auto t1 = Clock::now(); if (calculate) { sys.doFrameGPU(mousePos[0]*COORD_TO_PIXEL*(10000/1024), mousePos[1]*COORD_TO_PIXEL*(10000/1024)); } //std::cout << "frame" << std::endl; //sys.doFrameCPU(); if (COORD_TO_PIXEL != 1) { for (int i = 0; i < numParticles * 3; i++) //normalize coordinates for display { screenParticles[i] = particles[i] / COORD_TO_PIXEL; } } else { screenParticles = particles; } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //parameters glColor4f(0.0f, 0.0f, 1.0f, .05f); glPointSize(1); glEnable(GL_POINT_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //glDisable(GL_CULL_FACE); //drawing vertex array glEnableClientState(GL_VERTEX_ARRAY); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(p_type) * 3 * numParticles, screenParticles, GL_STATIC_DRAW); glVertexPointer(3, GL_DOUBLE, sizeof(double) * 3, 0); //glPushMatrix(); //glRotatef(rotation[0], rotation[1], rotation[2], rotation[3]); gluLookAt(camera[0], camera[1], camera[2], 0, 0, 0, 0, 1, 0); glDrawArrays(GL_POINTS, 0, numParticles); glColor4f(1.0, 0.0, 0.0, 1.0); glPointSize(10); glBegin(GL_POINTS); glVertex3f(mousePos[0]*(10000/1024), mousePos[1]*(10000/1024), 0); glEnd(); //glPopMatrix(); //glUseProgram(0); //glBindBuffer(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glDisableClientState(GL_VERTEX_ARRAY); glDisable(GL_BLEND); glDisable(GL_POINT_SMOOTH); auto t2 = Clock::now(); // Make the BYTE array, factor of 3 because it's RBG. #ifdef SAVE_IMAGES if (frameCounter%3 == 0 && save) { saveCounter++; int renderWidth = 1024; int renderHeight = 1024; GLubyte* pixels = new GLubyte[3 * renderWidth * renderHeight]; glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glReadPixels(0, 0, renderWidth, renderHeight, GL_RGB, GL_UNSIGNED_BYTE, pixels); std::string filePath = "E:/CudaOutput/final/frames/" + toString<int>(saveCounter) +".bmp"; // Convert to FreeImage format & save to file FIBITMAP* image = FreeImage_ConvertFromRawBits(pixels, renderWidth, renderHeight, renderWidth * 3, 24, 0x00FF00, 0x0000FF, 0xFF0000, false); FreeImage_Save(FIF_BMP, image, filePath.c_str(), 0); // Free resources FreeImage_Unload(image); delete[] pixels; } #endif #ifdef SAVE_DATA if (savedata && frameCounter % 100 == 0) { sys.writeData(frameCounter); std::cout << "saved stuff" << std::endl; } #endif if (spin) { rotation[0] += .0002; camera[0] = sin(rotation[1]) * cos(rotation[0])*rotation[2]; camera[1] = cos(rotation[1]) * rotation[2]; camera[2] = sin(rotation[1]) * sin(rotation[0])*rotation[2]; } frameCounter++; glutPostRedisplay(); }
// Private function used to save the backbuffer void DX8_GetBackBuffer(){ HRESULT hResult; IDirect3DSurface8 * pBackBuffer; D3DSURFACE_DESC surfaceDescription; D3DLOCKED_RECT lockedRect; // Get back buffer hResult = g_pDirect3DDevice8->lpVtbl->GetBackBuffer(g_pDirect3DDevice8, 0, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer); if(hResult != D3D_OK){ MessageBox(NULL, "Could not capture back buffer", "USARSim Image Server", MB_OK); return; } hResult = pBackBuffer->lpVtbl->GetDesc(pBackBuffer, &surfaceDescription); if(hResult != D3D_OK){ MessageBox(NULL, "Could not get description of the back buffer", "USARSim Image Server", MB_OK); pBackBuffer->lpVtbl->Release(pBackBuffer); } hResult = g_pDirect3DDevice8->lpVtbl->CreateImageSurface(g_pDirect3DDevice8, surfaceDescription.Width, surfaceDescription.Height, surfaceDescription.Format, &g_pBackBufferCopy8); if(FAILED(hResult)) MessageBox(NULL, "CreateImageSurface failed", "USARSim Image Server", MB_OK); hResult = g_pDirect3DDevice8->lpVtbl->CopyRects(g_pDirect3DDevice8, pBackBuffer, NULL, 0, g_pBackBufferCopy8, NULL); if(FAILED(hResult)) MessageBox(NULL, "CopyRects failed", "USARSim Image Server", MB_OK); pBackBuffer->lpVtbl->Release(pBackBuffer); // Lock the back buffer copy hResult = g_pBackBufferCopy8->lpVtbl->LockRect(g_pBackBufferCopy8, &lockedRect, NULL, D3DLOCK_READONLY); if(hResult != D3D_OK){ MessageBox(NULL, "Could not lock backbuffer copy", "USARSim Image Server", MB_OK); g_pBackBufferCopy8->lpVtbl->Release(g_pBackBufferCopy8); } // Load image in FreeImage structure FIBITMAP * fiImageOld; FIBITMAP * fiImageNew = FreeImage_ConvertFromRawBits((BYTE *)lockedRect.pBits, surfaceDescription.Width, surfaceDescription.Height, lockedRect.Pitch, 8*DX8_RAW_VIDEO_BPP, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK, true); // Swap global image pointer and trigger image event EnterCriticalSection( &g_CriticalSection ); { fiImageOld = g_fiImage; g_fiImage = fiImageNew; } LeaveCriticalSection( &g_CriticalSection ); // Signal that new frame was captured InterlockedExchange( &g_lRequestFlag, FALSE ); g_pRequestEvent->pulseEvent(); // Clean up old buffer FreeImage_Unload( fiImageOld ); // Unlock the back buffer hResult = g_pBackBufferCopy8->lpVtbl->UnlockRect(g_pBackBufferCopy8); if(hResult != D3D_OK){ MessageBox(NULL, "Could not unlock backbuffer copy", "USARSim Image Server", MB_OK); g_pBackBufferCopy8->lpVtbl->Release(g_pBackBufferCopy8); } g_pBackBufferCopy8->lpVtbl->Release(g_pBackBufferCopy8); g_pBackBufferCopy8 = NULL; }
void ofxGifEncoder::processFrame(ofxGifFrame * frame, FIMULTIBITMAP *multi){ FIBITMAP * bmp = NULL; // we need to swap the channels if we're on little endian (see ofImage::swapRgb); if (frame->bitsPerPixel ==32){ ofLog() << "image is transaprent!"; frame = convertTo24BitsWithGreenScreen(frame); } #ifdef TARGET_LITTLE_ENDIAN swapRgb(frame); #endif // from here on, we can only deal with 24 bits // get the pixel data bmp = FreeImage_ConvertFromRawBits( frame->pixels, frame->width, frame->height, frame->width*(frame->bitsPerPixel/8), frame->bitsPerPixel, 0, 0, 0, true // in of006 this (topdown) had to be false. ); FIBITMAP * bmpConverted; #ifdef TARGET_LITTLE_ENDIAN swapRgb(frame); #endif FIBITMAP * quantizedBmp = NULL; FIBITMAP * ditheredBmp = NULL; FIBITMAP * processedBmp = NULL; quantizedBmp = FreeImage_ColorQuantizeEx(bmp, FIQ_WUQUANT, nColors); processedBmp = quantizedBmp; if (nChannels == 4){ calculatePalette(processedBmp); FreeImage_SetTransparentIndex(processedBmp,getClosestToGreenScreenPaletteColorIndex()); } // dithering :) if(ditherMode > OFX_GIF_DITHER_NONE) { ditheredBmp = FreeImage_Dither(processedBmp, (FREE_IMAGE_DITHER)ditherMode); processedBmp = ditheredBmp; } DWORD frameDuration = (DWORD) (frame->duration * 1000.f); // clear any animation metadata used by this dib as we’ll adding our own ones FreeImage_SetMetadata(FIMD_ANIMATION, processedBmp, NULL, NULL); // add animation tags to dib[frameNum] FITAG *tag = FreeImage_CreateTag(); if(tag) { FreeImage_SetTagKey(tag, "FrameTime"); FreeImage_SetTagType(tag, FIDT_LONG); FreeImage_SetTagCount(tag, 1); FreeImage_SetTagLength(tag, 4); FreeImage_SetTagValue(tag, &frameDuration); FreeImage_SetMetadata(FIMD_ANIMATION, processedBmp, FreeImage_GetTagKey(tag), tag); FreeImage_DeleteTag(tag); } FreeImage_AppendPage(multi, processedBmp); // clear freeimage stuff if(bmp != NULL) FreeImage_Unload(bmp); if(quantizedBmp != NULL) FreeImage_Unload(quantizedBmp); if(ditheredBmp != NULL) FreeImage_Unload(ditheredBmp); // no need to unload processedBmp, as it points to either of the above }
static FIMULTIBITMAP* ReadFromAvi(const char* filename) { int err=0; AVIFileInit(); PAVISTREAM pavi; // Handle To An Open Stream if( AVIStreamOpenFromFile(&pavi, filename, streamtypeVIDEO, 0, OF_READ, NULL) != 0) { AVIFileExit(); return NULL; } AVISTREAMINFO psi; // Pointer To A Structure Containing Stream Info AVIStreamInfo(pavi, &psi, sizeof(psi)); // Reads Information About The Stream Into psi int width = psi.rcFrame.right-psi.rcFrame.left; // Width Is Right Side Of Frame Minus Left int height = psi.rcFrame.bottom-psi.rcFrame.top; // Height Is Bottom Of Frame Minus Top int frameCount = AVIStreamLength(pavi); // The Last Frame Of The Stream double mpf = AVIStreamSampleToTime(pavi, frameCount) / (double)frameCount; // Calculate Rough Milliseconds Per Frame PGETFRAME pgf = AVIStreamGetFrameOpen(pavi, NULL); // Create The PGETFRAME Using Our Request Mode if (pgf==NULL) { // An Error Occurred Opening The Frame error("Failed To Open frame from AVI"); } //HDC hdc = GetDC(0); HDRAWDIB hdd = DrawDibOpen(); // Handle For Our Dib BITMAPINFOHEADER bmih; // Header Information For DrawDibDraw Decoding bmih.biSize = sizeof (BITMAPINFOHEADER); // Size Of The BitmapInfoHeader bmih.biPlanes = 1; // Bitplanes bmih.biBitCount = 24; // Bits Format We Want (24 Bit, 3 Bytes) bmih.biWidth = width; // Width We Want (256 Pixels) bmih.biHeight = height; // Height We Want (256 Pixels) bmih.biCompression = BI_RGB; // Requested Mode = RGB char *data; // Pointer To Texture Data HBITMAP hBitmap = CreateDIBSection(hdc, (BITMAPINFO*)(&bmih), DIB_RGB_COLORS, (void**)(&data), NULL, NULL); SelectObject(hdc, hBitmap); // Select hBitmap Into Our Device Context (hdc) // create a new freeimage anim someError=false; FIMULTIBITMAP* ret = FreeImage_OpenMultiBitmap(FIF_TIFF, "temp.tiff", TRUE, FALSE); if (!ret || someError) { error("Couldnt create multibitmap"); } for (int frame=0; frame<frameCount; frame++) { fprintf(stderr, "Loading frame %i\n", frame); // Grab Data From The AVI Stream LPBITMAPINFOHEADER lpbi = (LPBITMAPINFOHEADER)AVIStreamGetFrame(pgf, frame); // Pointer To Data Returned By AVIStreamGetFrame // (Skip The Header Info To Get To The Data) char* pdata = (char *)lpbi + lpbi->biSize + lpbi->biClrUsed * sizeof(RGBQUAD); // Convert Data To Requested Bitmap Format DrawDibDraw(hdd, hdc, 0, 0, width, height, lpbi, pdata, 0, 0, width, height, 0); // copy into the freeimage thing FIBITMAP* fiBitmap = FreeImage_ConvertFromRawBits((BYTE*)data, width, height, width*3, 24, 0xFF0000, 0x00FF00, 0x0000FF); /* BYTE* src = (BYTE*)data; for (int y=0; y<height; y++) { BYTE* dst = FreeImage_GetScanLine(fiBitmap, y); for (int x=0; x<width; x++) { //src++; *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; } } */ FIBITMAP* grayBitmap = FreeImage_ConvertToGreyscale(fiBitmap); FreeImage_Unload(fiBitmap); FreeImage_AppendPage(ret, grayBitmap); } FreeImage_CloseMultiBitmap(ret); ret = FreeImage_OpenMultiBitmap(FIF_TIFF, "temp.tiff", FALSE, TRUE); DeleteObject(hBitmap); // Delete The Device Dependant Bitmap Object DrawDibClose(hdd); // Closes The DrawDib Device Context AVIStreamGetFrameClose(pgf); // Deallocates The GetFrame Resources AVIStreamRelease(pavi); // Release The Stream AVIFileExit(); // Release The File return ret; }
void ProcessKeyboard(void) { configureShader = 1; #include "_SHADERS/baseRoom/baseRoom_SHADER_KEYBOARD.cpp" //================================================================================================================= #include "KEYBOARD/mainRoomControls.cpp" //======================================================================================= //-------------------------------------------------------------------------- //======================================__LIGHTING__====================== //----------------------------------------------------------- if (keys['X'] && !keys[VK_SHIFT] && !keys[VK_CONTROL]) { adjustShadow_Pos_RadialBlur[0] += 0.00001; } if (keys['Z'] && !keys[VK_SHIFT] && !keys[VK_CONTROL]) { adjustShadow_Pos_RadialBlur[0] -= 0.00001; } //----------------------------------------------------------- if (keys['V'] && !keys[VK_SHIFT] && !keys[VK_CONTROL]) { shadow_BIAS += 0.0001; } if (keys['C'] && !keys[VK_SHIFT] && !keys[VK_CONTROL]) { shadow_BIAS -= 0.0001; } //----------------------------------------------------------- if (keys['G'] && gKeyIsReset && !keys[VK_SHIFT] && !keys[VK_CONTROL]) { selectBaseRoomLight += 1; gKeyIsReset = false; } if (keys['F'] && fKeyIsReset && !keys[VK_SHIFT] && !keys[VK_CONTROL]) { selectBaseRoomLight -= 1; fKeyIsReset = false; } //======================================__LIGHTING__====================== //-------------------------------------------------------------------------- //================================================================================================================= if(keys[VK_F8] && !keys[VK_SHIFT] && !keys[VK_CONTROL]) { ofstream outSettings("settings.cpp"); //------------------------------------------------------------------------------------------------------------------------------ outSettings << "var adjustShadowPos[] = {" << adjustShadowPos[0] << ", " << adjustShadowPos[1] << "};\n\n"; //------------------------------------------------------------------------------------------------------------------------------ outSettings << "var eyePosition[] = {" << eyePosition[0] << ", " << eyePosition[1] << ", " << eyePosition[2] << ", " << eyePosition[3] << "};\n\n"; //------------------------------------------------------------------------------------------------------------------------------ outSettings << "var secondsElapsed = " << (GLfloat)milliSecondsElapsed * 0.001 << ";\n\n"; //------------------------------------------------------------------------------------------------------------------------------ outSettings << "var shadow_BIAS = " << shadow_BIAS << ";\n\n"; //------------------------------------------------------------------------------------------------------------------------------ outSettings << "var adjustShadow_Pos_RadialBlur[] = {" << adjustShadow_Pos_RadialBlur[0] << ", " << adjustShadow_Pos_RadialBlur[1] << "};\n\n"; //------------------------------------------------------------------------------------------------------------------------------ outSettings << "var marc_POSITION[] = {" << marc_POSITION[0] << ", " << marc_POSITION[1] << ", " << marc_POSITION[2] << ", " << marc_POSITION[3] << "};\n\n"; //------------------------------------------------------------------------------------------------------------------------------ outSettings << "var eyePosition_SHADOW[] = {" << eyePosition_SHADOW[0] << ", " << eyePosition_SHADOW[1] << ", " << eyePosition_SHADOW[2] << ", " << eyePosition_SHADOW[3] << "};\n\n"; //------------------------------------------------------------------------------------------------------------------------------ outSettings << "var eyePosition[] = {" << eyePosition[0] << ", " << eyePosition[1] << ", " << eyePosition[2] << ", 0.0};\n"; //------------------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------------------ outSettings << "var rotateModelWithMiddleMouse[] = {" << rotateModelWithMiddleMouse[0] << ", " << rotateModelWithMiddleMouse[1] << "};\n\n"; //------------------------------------------------------------------------------------------------------------------------------ outSettings << "var moveSet[] = {" << moveSet[0] << ", " << moveSet[1] << ", " << moveSet[2] << ", 1.0};\n"; //------------------------------------------------------------------------------------------------------------------------------ //---------------------------------------------------------------------------------------------------------------- }//_END_F8 //======================================================================================= //--------------------------------------------------------------------------------------- //_______________________________________________________________________________________ if(keys[VK_F9]) { GLsizei screenCaptureWidth = (GLsizei)viewWidth; GLsizei screenCaptureHeight = (GLsizei)viewHeight; GLubyte *pixmap =(GLubyte *)malloc(screenCaptureWidth*screenCaptureHeight*4); glReadPixels(0,0,screenCaptureWidth,screenCaptureHeight,GL_BGRA,GL_UNSIGNED_BYTE,pixmap); FIBITMAP *texture = FreeImage_ConvertFromRawBits( pixmap, screenCaptureWidth, screenCaptureHeight, screenCaptureWidth*4, 32, 0xFF0000, 0x00FF00, 0x0000FF, true); FreeImage_Save(FIF_BMP, texture, "AAAAA.bmp", 0); free(pixmap); } //_______________________________________________________________________________________ //--------------------------------------------------------------------------------------- //======================================================================================= if (keys[VK_NUMPAD6] && !keys[VK_SHIFT] && !keys[VK_CONTROL]) { marc_POSITION[0] += 0.01; } //------------------------------------------------------------------------------ if (keys[VK_NUMPAD4] && !keys[VK_SHIFT] && !keys[VK_CONTROL]) { marc_POSITION[0] -= 0.01; } //------------------------------------------------------------------------------ if (keys[VK_NUMPAD8] && !keys[VK_SHIFT] && !keys[VK_CONTROL]) { marc_POSITION[1] += 0.01; } //------------------------------------------------------------------------------ if (keys[VK_NUMPAD2] && !keys[VK_SHIFT] && !keys[VK_CONTROL]) { marc_POSITION[1] -= 0.01; } //------------------------------------------------------------------------------ if (keys[VK_NUMPAD9] && !keys[VK_SHIFT] && !keys[VK_CONTROL]) { marc_POSITION[2] += 0.01; } //------------------------------------------------------------------------------ if (keys[VK_NUMPAD7] && !keys[VK_SHIFT] && !keys[VK_CONTROL]) { marc_POSITION[2] -= 0.01; } //------------------------------------------------------------------------------ //======================================================================================= #include "KEYBOARD/keyboard_RESET.c" //================================================================================================================= //-------------------------------------------------------------------------- //======================================__SELECT_MODEL====================== if (keys[VK_OEM_PERIOD] && VK_OEM_PERIOD_KeyIsReset && !keys[VK_SHIFT] && !keys[VK_CONTROL]) { selectedModel += 1; VK_OEM_PERIOD_KeyIsReset = false; } //============================================================= if (keys[VK_OEM_COMMA] && VK_OEM_COMMA_KeyIsReset && !keys[VK_SHIFT] && !keys[VK_CONTROL]) { selectedModel -= 1; VK_OEM_COMMA_KeyIsReset = false; } //======================================__SELECT_MODEL__==================== //-------------------------------------------------------------------------- //================================================================================================================= //================================================================================================================= //-------------------------------------------------------------------------- //======================================__BOX_COUNT__==================== if (keys[VK_PRIOR] && VK_PRIOR_KeyIsReset && !keys[VK_SHIFT] && !keys[VK_CONTROL]) { boxCount += 1; VK_PRIOR_KeyIsReset = false; } if (keys[VK_NEXT] && VK_NEXT_KeyIsReset && !keys[VK_SHIFT] && !keys[VK_CONTROL]) { boxCount -= 1; VK_NEXT_KeyIsReset = false; } //======================================__BOX_COUNT__==================== //-------------------------------------------------------------------------- //================================================================================================================= }//_END_ProcessKeyboard()
void save_stream_to_alpha_image(Stream* str, GfxImageColorMap* colorMap, int width, int height, Stream* maskStr, GfxImageColorMap* maskColorMap, int maskWidth, int maskHeight, char* file_name) { if (fif != FIF_PNG || width == 0 || height == 0 || maskWidth == 0 || maskHeight == 0) { save_stream_to_image(str, colorMap, width, height, colorMap->getNumPixelComps() == 1 && colorMap->getBits() == 1, file_name, gFalse); return; } // allocate buffer int row_size = width * 4; unsigned char* buf = (unsigned char*)malloc(height * row_size); if (!buf) return; // read mask data ImageStream* mask_str = new ImageStream(maskStr, maskWidth, maskColorMap->getNumPixelComps(), maskColorMap->getBits()); mask_str->reset(); Guchar* mask_line = mask_str->getLine(); int old_mask_row = 0; for (int y = 0; y < height; ++y) { unsigned char* pbuf = buf + row_size * y; int new_mask_row = y * maskHeight / height; for (int i = old_mask_row; i < new_mask_row; ++i) { mask_line = mask_str->getLine(); } old_mask_row = new_mask_row; int old_mask_column = 0; for (int x = 0; x < width; ++x) { int new_mask_column = x * maskWidth / width; mask_line += maskColorMap->getNumPixelComps() * (new_mask_column - old_mask_column); old_mask_column = new_mask_column; GfxGray gray; maskColorMap->getGray(mask_line, &gray); pbuf[3] = colToByte(gray); pbuf += 4; } } delete mask_str; // read image data ImageStream* img_str = new ImageStream(str, width, colorMap->getNumPixelComps(), colorMap->getBits()); img_str->reset(); for (int y = 0; y < height; ++y) { unsigned char* pbuf = buf + row_size * y; Guchar* line = img_str->getLine(); for (int x = 0; x < width; ++x) { GfxRGB rgb; colorMap->getRGB(line, &rgb); // int alpha = pbuf[3]; // if (alpha < 255 && alpha > 0) // { // pbuf[0] = (colToByte(rgb.b) + alpha - 255) * 255 / alpha; // pbuf[1] = (colToByte(rgb.g) + alpha - 255) * 255 / alpha; // pbuf[2] = (colToByte(rgb.r) + alpha - 255) * 255 / alpha; // } // else { pbuf[0] = colToByte(rgb.b); pbuf[1] = colToByte(rgb.g); pbuf[2] = colToByte(rgb.r); } line += colorMap->getNumPixelComps(); pbuf += 4; } } delete img_str; // create image FIBITMAP* fib = FreeImage_ConvertFromRawBits(buf, width, height, row_size, 32, 0, 0, 0, 1); free(buf); // save FreeImage_SetDotsPerMeterX(fib, 72 * 10000 / 254); FreeImage_SetDotsPerMeterY(fib, 72 * 10000 / 254); int flag = 0; if (fif == FIF_JPEG) flag = jpg_quality; else if (fif == FIF_TIFF && tiff_jpeg) flag = TIFF_JPEG; if (!FreeImage_Save(fif, fib, file_name, flag)) error(-1, "Couldn't create file '%s'", file_name); FreeImage_Unload(fib); }
bool Texture::saveImToFile(const std::string& filename, const uint8_t* im, const uint32_t width, const uint32_t height, const bool save_flipped, const uint32_t num_channels) { freeimage_init_lock_.lock(); if (!freeimage_init_) { freeimage_init_lock_.unlock(); throw std::wruntime_error("Texture::Texture() - ERROR: Please call " "initTextureSystem() before loading textures from file!"); } freeimage_init_lock_.unlock(); // NEW CODE USING THE FREEIMAGE LIBRARY FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; //image format // if still unknown, try to guess the file format from the file extension if (fif == FIF_UNKNOWN) { fif = FreeImage_GetFIFFromFilename(filename.c_str()); } // if still unkown, return failure if (fif == FIF_UNKNOWN) { throw wruntime_error(wstring(L"saveRGBToFile() - ERROR: Cannot deduce " L"format of the filename: ") + string_util::ToWideString(filename)); } if (!FreeImage_FIFSupportsWriting(fif)) { throw std::wruntime_error("saveRGBToFile() - ERROR: Freeimage does not " "support writing to this image format!"); return false; } BYTE* fi_bits = NULL; uint8_t* im_rev = NULL; // Unfortunately, Freeimage has a bug: // http://sourceforge.net/p/freeimage/bugs/172/ // It ignores the mask properties and so the red and blue channels (24bpp) // get flipped. Unfortunately, we have to swap them around. // As of 4/26/2013 this issue still isn't fixed. switch (num_channels) { case 0: throw std::wruntime_error("saveImToFile() - ERROR: num_channels == 0"); case 1: fi_bits = (BYTE*)im; break; case 2: case 3: im_rev = new uint8_t[width * height * num_channels]; for (uint32_t i = 0; i < width * height * num_channels; i+=num_channels) { for (uint32_t j = 0; j < num_channels; j++) { im_rev[i + j] = im[i + (num_channels - 1 - j)]; } } fi_bits = (BYTE*)im_rev; break; default: throw std::wruntime_error("saveImToFile() - ERROR: num_channels > 0." " Saving images with alpha not yet supported."); } uint32_t pitch = num_channels * width; uint32_t bpp = 8 * num_channels; uint32_t red_mask = 0x0000FF; // Free image likes the mask backwards? uint32_t green_mask = 0x00FF00; uint32_t blue_mask = 0xFF0000; FIBITMAP* fi_bit_map = FreeImage_ConvertFromRawBits(fi_bits, width, height, pitch, bpp, red_mask, blue_mask, green_mask, save_flipped); bool ret = false; if (fi_bit_map) { ret = (bool)FreeImage_Save(fif, fi_bit_map, filename.c_str(), JPEG_QUALITYSUPERB); } if (fi_bit_map) { FreeImage_Unload(fi_bit_map); } SAFE_DELETE_ARR(im_rev); return ret; }
void save_stream_to_image(Stream* str, GfxImageColorMap* color_map, int width, int height, GBool mono, char* file_name, GBool mask) { // read raw data from memory FIBITMAP* fib; if (mono) { int size = height * ((width + 7) / 8); unsigned char* buf = (unsigned char*)malloc(size); if (!buf) return; unsigned char* p = buf; str->reset(); for (int i = 0; i < size; i++) *p++ = str->getChar(); str->close(); fib = FreeImage_ConvertFromRawBits(buf, width, height, (width + 7) / 8, 1, 0, 0, 0, 1); RGBQUAD* pal = FreeImage_GetPalette(fib); pal[0].rgbRed = pal[0].rgbGreen = pal[0].rgbBlue = (mask ? 0 : 255); pal[1].rgbRed = pal[1].rgbGreen = pal[1].rgbBlue = (mask ? 255 : 0); free(buf); } else { int row_size = width * 3; if (row_size % 4) row_size += (4 - row_size % 4); unsigned char* buf = (unsigned char*)malloc(height * row_size); if (!buf) return; ImageStream* img_str = new ImageStream(str, width, color_map->getNumPixelComps(), color_map->getBits()); img_str->reset(); Guchar* p; unsigned char* pbuf; GfxRGB rgb; for (int y = 0; y < height; ++y) { p = img_str->getLine(); pbuf = buf + row_size * y; for (int x = 0; x < width; ++x) { color_map->getRGB(p, &rgb); pbuf[0] = colToByte(rgb.b); pbuf[1] = colToByte(rgb.g); pbuf[2] = colToByte(rgb.r); p += color_map->getNumPixelComps(); pbuf += 3; } } fib = FreeImage_ConvertFromRawBits(buf, width, height, row_size, 24, 0, 0, 0, 1); delete img_str; free(buf); } // adjust color depth if (fif == FIF_GIF && !mono) { FIBITMAP* fib_temp = fib; fib = FreeImage_ColorQuantize(fib_temp, FIQ_WUQUANT); FreeImage_Unload(fib_temp); } else if (fif == FIF_JPEG && mono) { FIBITMAP* fib_temp = fib; fib = FreeImage_ConvertTo8Bits(fib_temp); FreeImage_Unload(fib_temp); } // save FreeImage_SetDotsPerMeterX(fib, 72 * 10000 / 254); FreeImage_SetDotsPerMeterY(fib, 72 * 10000 / 254); int flag = 0; if (fif == FIF_JPEG) flag = jpg_quality; else if (fif == FIF_TIFF && tiff_jpeg && !mono) flag = TIFF_JPEG; if (!FreeImage_Save(fif, fib, file_name, flag)) error(-1, "Couldn't create file '%s'", file_name); FreeImage_Unload(fib); }
void capture() { if (doo > 0){ doo = 0; } else{ doo++; return; } if (capture_frame >= 250) exit(0); int mWin_width = 800; int mWin_height = 600; // Make the BYTE array, factor of 3 because it's RBG. BYTE* pixels = new BYTE[3 * mWin_width * mWin_height]; glReadPixels(0, 0, mWin_width, mWin_height, GL_RGB, GL_UNSIGNED_BYTE, pixels); for (int i = 0; i < mWin_height; i++) for (int j = 0; j < mWin_width; j++) { BYTE tmp = pixels[i*(mWin_width * 3) + (j * 3) + 0]; pixels[i*(mWin_width * 3) + (j * 3) + 0] = pixels[i*(mWin_width * 3) + (j * 3) + 2]; pixels[i*(mWin_width * 3) + (j * 3) + 2] = tmp; } // Convert to FreeImage format & save to file FIBITMAP* image = FreeImage_ConvertFromRawBits(pixels, mWin_width, mWin_height, 3 * mWin_width, 24, 0xFF0000, 0x00FF00, 0x0000FF, false); char filename[200]; sprintf(filename, "F:/Result_Seen/temp/Image/%05d.png", capture_frame); capture_frame++; FreeImage_Save(FIF_PNG, image, filename, 0); // Free resources FreeImage_Unload(image); delete[] pixels; }