Checkers game in SDL - c

i'm trying to make a checkers game and atm i'm doing the interface with SDL, but i'm just learning C and SDL, how can I move a surface I added to the screen ? I want it the simplest as possible, just remove from X and show on Y, how do I remove a surface to make it appear on another place on the screen ? here is my code:
#include "SDL.h"
#define BRANCA 2
#define PRETA 1
#define DAMA 2
#define NORMAL 1
//The attributes of the screen
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BPP = 32;
//The surfaces that will be used
SDL_Surface *pecaPreta = NULL;
SDL_Surface *pecaBranca = NULL;
SDL_Surface *pecaDamaPreta = NULL;
SDL_Surface *pecaDamaBranca = NULL;
SDL_Surface *background = NULL;
SDL_Surface *screen = NULL;
SDL_Event event;
SDL_Surface *load_image(char * filename )
{
SDL_Surface* loadedImage = NULL;
SDL_Surface* optimizedImage = NULL;
loadedImage = SDL_LoadBMP(filename);
if( loadedImage != NULL )
{
optimizedImage = SDL_DisplayFormat( loadedImage );
SDL_FreeSurface( loadedImage );
if( optimizedImage != NULL )
{
Uint32 colorkey = SDL_MapRGB( optimizedImage->format, 0, 0xFF, 0xFF );
SDL_SetColorKey( optimizedImage, SDL_SRCCOLORKEY, colorkey );
}
}
return optimizedImage;
}
void apply_surface( int x, int y, SDL_Surface* source, SDL_Surface* destination )
{
SDL_Rect offset;
offset.x = x;
offset.y = y;
SDL_BlitSurface( source, NULL, destination, &offset );
}
void inserePeca(int tipo, int posX, int posY, int cor)
{
switch(cor)
{
case 1:
switch (tipo)
{
case 1:
apply_surface(posX, posY, pecaPreta, screen);
break;
case 2:
apply_surface(posX, posY, pecaDamaPreta, screen);
break;
}
break;
case 2:
switch (tipo)
{
case 1:
apply_surface(posX, posY, pecaBranca, screen);
break;
case 2:
apply_surface(posX, posY, pecaDamaBranca, screen);
break;
}
break;
}
}
int main()
{
int quit = 0;
if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
{
return 1;
}
screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );
if( screen == NULL )
{
return 1;
}
//Set the window caption
SDL_WM_SetCaption( "Jogo de Damas 0.1b", NULL );
//Load the images
pecaPreta = load_image( "pecapreta.bmp" );
pecaBranca = load_image("pecabranca.bmp");
pecaDamaPreta = load_image("pecadamapreta.bmp");
pecaDamaBranca = load_image("pecadamabranca.bmp");
background = load_image( "tabuleiro.bmp" );
//Apply the background to the screen
apply_surface( 0, 0, background, screen );
inserePeca(DAMA, 0,0, BRANCA);
inserePeca(NORMAL, 80,0, PRETA);
//Update the screen
if( SDL_Flip( screen ) == -1 )
{
return 1;
}
while( quit == 0 )
{
//While there's an event to handle
while( SDL_PollEvent( &event ) )
{
//If the user has Xed out the window
if( event.type == SDL_QUIT )
{
//Quit the program
quit = -1;
}
}
}
//Free the surfaces
SDL_FreeSurface( pecaPreta );
SDL_FreeSurface( background );
//Quit SDL
SDL_Quit();
return 0;
}
as you can see I add a block on "inserePeca", I want to move it after I create it

The buffer for the screen doesn't keep all the things you draw on it as separate items -- it just holds the end result of all the drawing operations. So, you can't just draw the background, then draw a piece on it, then move the piece around -- you need to redraw the affected parts of the screen with the required changes.
You still have the images of the pieces, and you still have the background image; the way to move a piece you've drawn is simply to restore the background to the old position by blitting it again, and then blit the piece in the new position. Rather than drawing the whole screen and all the pieces over again, though, you can just draw the changed areas: blit just a part of the background to erase the old square, and then blit the piece onto the new square.
The following function is similar to your apply_surface() function, but instead of copying the whole source image to the the given coordinates of the destination, it copies a region of a given width and height from the given coordinates of the source image to the same coordinates of the destination. This can then be used to restore the background for a small part of the screen.
/* Blit a region from src to the corresponding region in dest. Uses the same
* x and y coordinates for the regions in both src and dest. w and h give the
* width and height of the region, respectively.
*/
void erase_rect( int x, int y, int w, int h, SDL_Surface *src, SDL_Surface *dest)
{
SDL_Rect offset;
offset.x = x;
offset.y = y;
offset.w = w;
offset.h = h;
SDL_BlitSurface( src, &offset, dest, &offset );
}
So if your squares are 50x50, and you need to move a piece from a square at (120, 40) to the square at (170, 90), you could do something like the following:
/* erase old 50x50 square at (120,40) (to background image) */
erase_rect( 120, 40, 50, 50, background, screen );
/* draw piece at new position of (170,90) */
inserePeca(NORMAL, 170, 90, PRETA);

Related

SDL - Update Surface in C

i use SDL Lib and SDL_TTF Lib
I have a code that allows you to enter text
And then display the text on my window
so here the code
TTF_Init();
SDL_Init(SDL_INIT_VIDEO);
TTF_Font * font = TTF_OpenFont("C:\\Windows\\Fonts\\Arial.ttf", 25);
SDL_Color color = { 255, 255, 255 };
SDL_Surface * surface = TTF_RenderText_Solid(font,"", color);
SDL_Window * window = SDL_CreateWindow("SDL_ttf in SDL2",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640,
480, 0);
SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0);
SDL_Texture * texture = SDL_CreateTextureFromSurface(renderer, surface);
int texW = 200;
int texH = 200;
SDL_QueryTexture(texture, NULL, NULL, &texW, &texH);
SDL_Rect dstrect = { 200, 200, texW, texH };
SDL_RenderCopy(renderer, texture, NULL, &dstrect);
SDL_RenderPresent(renderer);
while (program_launched)
{
SDL_bool has_type = SDL_FALSE;
SDL_WaitEvent(&event);
if(event.type == SDL_QUIT)
program_launched = SDL_FALSE;
else if( event.type == SDL_KEYDOWN)
{
if(event.key.keysym.sym == SDLK_BACKSPACE && len)
{
rep[len - 1] = 0;
len--;
has_type = SDL_TRUE;
}
if(event.key.keysym.sym == SDLK_v && (SDL_GetModState() & KMOD_CTRL) && SDL_HasClipboardText())
{
char *tmp = SDL_GetClipboardText();
size_t l = strlen(tmp);
size_t l_copy = len + l < LEN_MAX ? l : LEN_MAX - len;
strncpy(rep + len, tmp, l_copy);
len += l_copy;
SDL_free(tmp);
has_type = SDL_TRUE;
}
if(event.key.keysym.sym == SDLK_c && (SDL_GetModState() & KMOD_CTRL))
SDL_SetClipboardText(rep);
}
else if(event.type == SDL_TEXTINPUT)
{
size_t l = strlen(event.text.text);
size_t l_copy = len + l < LEN_MAX ? l : LEN_MAX - len;
strncpy(rep + len, event.text.text, l_copy);
len += l_copy;
has_type = SDL_TRUE;
}
if(has_type)
surface = TTF_RenderText_Solid(font,rep, color);
texture = SDL_CreateTextureFromSurface(renderer, surface);
SDL_QueryTexture(texture, NULL, NULL, &texW, &texH);
SDL_Rect dstrect = { 0, 0, texW, texH };
SDL_RenderCopy(renderer, texture, NULL, &dstrect);
SDL_RenderPresent(renderer);
}
It's to (has-type) that I display the buff (rep)
But my problem is here:
I can write and display in the window a text
But if i do a backspace and i write
The texts overlap because the window, at least the rectangle is not updated
Is it possible to delete the content of my window (to display the buff without overlapping) ?
I use this documentation
https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.pdf
I had tried with this function: SDL_UpdateWindowSurface(window);
But nothing helps
Compiler: GCC
OS: Windows
It's because once you've outputed something to the screen, it stays there unless you clear it or put something above it.
Think of it as a painter plotting things on his canvas. If you want to overwrite something, you have to overwrite the previous shape.
The simplest way to deal with this would be to call SDL_RenderClear at the beginning of every draw, it clears the whole screen clean, and then every time you render something it'll never overlap the previous stuff.

How to use text in EFI graphic mode?

I am super new to creating efi application. My aim is to create a small application in efi, that displays some text on a background. But I am stuck with trying to display text on the display (Great would be to have a custom font, but that is not necessary at this stage). I want the app (also) to run on apple systems (to boot from a usb)
How do I find good documentation on the EFI functions? It seems super hard to find good examples etc.
How can I display a text on a background with EFI?
This is what I got so far. I change the background to a color using the graphics protocol. How do I display a text on it. The Output String doesn't seem to work.
#include "efibind.h"
#include "efidef.h"
#include "efidevp.h"
#include "eficon.h"
#include "efiapi.h"
#include "efierr.h"
#include "efiprot.h"
static EFI_GUID GraphicsOutputProtocolGUID = EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID;
/**
* efi_main - The entry point for the EFI application
* #image: firmware-allocated handle that identifies the image
* #SystemTable: EFI system table
*/
EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *systemTable) {
EFI_BOOT_SERVICES *bs = systemTable->BootServices;
EFI_STATUS status;
EFI_GRAPHICS_OUTPUT_PROTOCOL *graphicsProtocol;
SIMPLE_TEXT_OUTPUT_INTERFACE *conOut = systemTable->ConOut;
EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *info;
UINTN SizeOfInfo, sWidth, sHeight;
status = bs->LocateProtocol(&GraphicsOutputProtocolGUID, NULL,
(void**)&graphicsProtocol);
if (EFI_ERROR(status) || graphicsProtocol == NULL) {
conOut->OutputString(conOut, L"Failed to init gfx!\r\n");
return status;
}
conOut->ClearScreen(conOut);
//Switch to current mode so gfx is started.
status = graphicsProtocol->SetMode(graphicsProtocol, graphicsProtocol->Mode->Mode);
if (EFI_ERROR(status)) {
conOut->OutputString(conOut, L"Failed to set default mode!\r\n");
return status;
}
EFI_GRAPHICS_OUTPUT_BLT_PIXEL p;
p.Red = 200;
p.Green = 77;
p.Blue = 13;
graphicsProtocol->QueryMode(graphicsProtocol, graphicsProtocol->Mode->Mode, &SizeOfInfo, &info);
sWidth = info->HorizontalResolution;
sHeight = info->VerticalResolution;
status = graphicsProtocol->Blt(graphicsProtocol, &p, EfiBltVideoFill, 0, 0, 0, 0, sWidth, sHeight, 0);
while (1) {
conOut->OutputString(conOut, L"Some text that I want to display\r\n");
bs->Stall(500000);
}
return EFI_SUCCESS;
}
UEFI supports graphics output. It also supports text output (which can mean either output to a serial console, or text rendered to a graphical console, or both). But there is no defined way to interact between these in a controlled manner.
Applications that provide a graphical environment with text elements (BIOS configuration menu, GRUB) generally do this using their own frameworks to draw text on the graphical console using GRAPHICS_OUTPUT_PROTOCOL.
This is a short example of a text renderer using the font module from LVGL (which can be used standalone, replace #include "../../lv_conf.h" in the lv_font.h file with #define USE_LV_FONT_DEJAVU_20 8) and the Blt method from the GRAPHICS_OUTPUT_PROTOCOL
#include <Uefi.h>
#include <Library\UefiLib.h>
#include <Protocol\GraphicsOutput.h>
#include "lv_font.h"
#define LETTER_SPACE 2
#define WAIT_SECONDS 10
#define FONT &lv_font_dejavu_20
static EFI_BOOT_SERVICES *gBS;
static EFI_RUNTIME_SERVICES *gRT;
static EFI_GRAPHICS_OUTPUT_PROTOCOL *gGOP = (EFI_GRAPHICS_OUTPUT_PROTOCOL *)NULL;
static EFI_GRAPHICS_OUTPUT_BLT_PIXEL gWhite = { 255,255,255,0 };
static void _util_render_glyph(UINT32 x, UINT32 y, CHAR8 letter)
{
UINT32 height;
UINT32 width;
UINT32 pm_x;
UINT32 pm_y;
UINT32 index;
const UINT8* bitmap;
EFI_GRAPHICS_OUTPUT_BLT_PIXEL *pixelmap;
if (gGOP == NULL) {
return;
}
height = lv_font_get_height(FONT);
width = lv_font_get_width(FONT, letter);
// glyph is not defined in this font
if (width == 0) {
return;
}
bitmap = lv_font_get_bitmap(FONT, letter);
// using 8 bpp for simplicity
if (EFI_ERROR(gBS->AllocatePool(EfiLoaderData, height * width * sizeof(*pixelmap), (VOID**)&pixelmap))) {
return;
}
gBS->SetMem((VOID*)pixelmap, height * width * sizeof(*pixelmap), 0);
// get the current content of the framebuffer to allow 'transparent' blt operations
gGOP->Blt(gGOP, pixelmap, EfiBltVideoToBltBuffer, x, y, 0, 0, width, height, 0);
for (pm_y = 0; pm_y < height; pm_y++) {
for (pm_x = 0; pm_x < width; pm_x++) {
index = width * pm_y + pm_x;
if (bitmap[index] > 200) {
pixelmap[index].Red = 0;
pixelmap[index].Blue = 0;
pixelmap[index].Green = 0;
pixelmap[index].Reserved = 0;
}
else if (bitmap[index] > 100) {
pixelmap[index].Red = 105;
pixelmap[index].Blue = 105;
pixelmap[index].Green = 105;
pixelmap[index].Reserved = 0;
}
}
}
gGOP->Blt(gGOP, pixelmap, EfiBltBufferToVideo, 0, 0, x, y, width, height, 0);
gBS->FreePool(pixelmap);
}
static void _util_render_text(UINT32 x, UINT32 y, const CHAR8 *string)
{
UINT32 index;
UINTN length;
UINT32 scr_w;
UINT32 scr_h;
UINT32 str_x;
UINT32 gly_w;
UINT32 gly_h;
if (string == NULL) {
return;
}
if (gGOP == NULL) {
return;
}
scr_w = gGOP->Mode->Info->HorizontalResolution;
scr_h = gGOP->Mode->Info->VerticalResolution;
length = AsciiStrnLenS(string, 32);
gly_h = lv_font_get_height(FONT);
// check if the string can be printed
if ((y + gly_h) > scr_h) {
return;
}
if (x > scr_w) {
return;
}
// print the string glyph by glyph
str_x = x;
for (index = 0; index < length; index++) {
// check if the glyph can be printed
gly_w = lv_font_get_width(FONT, string[index]);
if ((str_x + gly_w) > scr_w) {
break;
}
// print the glyph
_util_render_glyph(str_x, y, string[index]);
// calculate the position of the next glyph
str_x += gly_w + LETTER_SPACE;
}
}
static void _util_fill_screen(EFI_GRAPHICS_OUTPUT_BLT_PIXEL *color)
{
if (gGOP == NULL) {
return;
}
gGOP->Blt(gGOP, color, EfiBltVideoFill, 0, 0, 0, 0, gGOP->Mode->Info->HorizontalResolution, gGOP->Mode->Info->VerticalResolution, 0);
}
static void _util_wait(UINT32 seconds)
{
EFI_TIME time;
UINT8 current_second = 255;
UINT32 elapsed_seconds = 0;
//wait for some seconds
while (elapsed_seconds <= WAIT_SECONDS) {
if (!EFI_ERROR(gRT->GetTime(&time, (EFI_TIME_CAPABILITIES*)NULL))) {
if (current_second != time.Second) {
elapsed_seconds++;
current_second = time.Second;
}
}
else {
break;
}
CpuPause();
}
}
EFI_STATUS
EFIAPI
UefiMain(
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable)
{
EFI_STATUS eRc;
gBS = SystemTable->BootServices;
gRT = SystemTable->RuntimeServices;
eRc = gBS->LocateProtocol(
&gEfiGraphicsOutputProtocolGuid,
NULL,
(VOID**)&gGOP);
if (EFI_ERROR(eRc) || gGOP == NULL) {
return EFI_SUCCESS;
}
_util_fill_screen(&gWhite);
_util_render_text(0, 0, "HELLO WORLD!");
_util_wait(WAIT_SECONDS);
return EFI_SUCCESS;
}
I tested it on a pc and on a mac it runs on both. Using the tools provided by LVGL on their website you can use any font you want.
If you target MacEFI specifically, you'll need an additional protocol call to force the console into text mode, like this.

Pixel manipulation using sdl

I am trying to manipulate pixel using sdl and manage to read them up now. Below is my sample code. When I print I this printf("\npixelvalue is is : %d",MyPixel); I get values like this
11275780
11275776
etc
I know these are not in hex form but how to manipulate say I want to filter just the blue colors out? Secondly after manipulation how to generate the new image?
#include "SDL.h"
int main( int argc, char* argv[] )
{
SDL_Surface *screen, *image;
SDL_Event event;
Uint8 *keys;
int done = 0;
if (SDL_Init(SDL_INIT_VIDEO) == -1)
{
printf("Can't init SDL: %s\n", SDL_GetError());
exit(1);
}
atexit(SDL_Quit);
SDL_WM_SetCaption("sample1", "app.ico");
/* obtain the SDL surfance of the video card */
screen = SDL_SetVideoMode(640, 480, 24, SDL_HWSURFACE);
if (screen == NULL)
{
printf("Can't set video mode: %s\n", SDL_GetError());
exit(1);
}
printf("Loading here");
/* load BMP file */
image = SDL_LoadBMP("testa.bmp");
Uint32* pixels = (Uint32*)image->pixels;
int width = image->w;
int height = image->h;
printf("Widts is : %d",image->w);
for(int iH = 1; iH<=height; iH++)
for(int iW = 1; iW<=width; iW++)
{
printf("\nIh is : %d",iH);
printf("\nIw is : %d",iW);
Uint32* MyPixel = pixels + ( (iH-1) + image->w ) + iW;
printf("\npixelvalue is is : %d",MyPixel);
}
if (image == NULL) {
printf("Can't load image of tux: %s\n", SDL_GetError());
exit(1);
}
/* Blit image to the video surface */
SDL_BlitSurface(image, NULL, screen, NULL);
SDL_UpdateRect(screen, 0, 0, screen->w, screen->h);
/* free the image if it is no longer needed */
SDL_FreeSurface(image);
/* process the keyboard event */
while (!done)
{
// Poll input queue, run keyboard loop
while ( SDL_PollEvent(&event) )
{
if ( event.type == SDL_QUIT )
{
done = 1;
break;
}
}
keys = SDL_GetKeyState(NULL);
if (keys[SDLK_q])
{
done = 1;
}
// Release CPU for others
SDL_Delay(100);
}
// Release memeory and Quit SDL
SDL_FreeSurface(screen);
SDL_Quit();
return 0;
}
Use SDL_MapRGB and SDL_MapRGBA to sort colors out. SDL will filter it out for you, based on surface format.
Just like this:
Uint32 rawpixel = getpixel(surface, x, y);
Uint8 red, green, blue;
SDL_GetRGB(rawpixel, surface->format, &red, &green, &blue);
You are printing the value of the pointer MyPixel. To get the value you have to dereference the pointer to the pixel value like this: *MyPixel
Then the printf would look like this:
printf("\npixelvalue is : %d and the address of that pixel is: %p\n",*MyPixel , MyPixel);
Other errors:
Your for loops are incorrect. You should loop from 0 to less than width or height, or else you will read uninitialized memory.
You didn't lock the surface. Although you are only reading the pixels and nothing should go wrong it is still not correct.
Test for correctness if the image pointer comes after you are already using the pointer. Put the test right after the initialization.
If I recall correctly I used sdl_gfx for pixel manipulation.
It also contains function like drawing a circle, oval etc.

Severe breaks and leaks

I have a code which basically detects playing cards, isolates them from a dynamic background based on HSV settings, then uses contours to detect the 4 points of the card to find the exact x and y position of the card. From there, the ROI is set and I can perform further processing to detect the face value of the card.
However, I the code seems to be breaking and I can't seem to find the root cause of it.
I have cleared images & memory storages, I've ensured that all the Iplimages have the same formatting and resolution.
IplImage* GetThresholdedImage(IplImage* imgHSV){
IplImage* imgThresh=cvCreateImage(cvGetSize(imgHSV),IPL_DEPTH_8U, 1);
cvInRangeS(imgHSV, cvScalar(95,67,170), cvScalar(110,119,254), imgThresh); //Morning
return imgThresh;
}
IplImage* RedCheck(IplImage* imgBGR){
IplImage* img=cvCreateImage(cvGetSize(imgBGR),IPL_DEPTH_8U, 1);
cvInRangeS(imgBGR, cvScalar(0,0,100), cvScalar(100,100,254), img); //BGR
return img;
}
int main()
{
CvCapture* capture =0;
capture = cvCaptureFromCAM(0);
if(!capture)
{
printf("Capture failure\n");
return -1;
}
IplImage* frame = cvCreateImage(cvSize(48,64),IPL_DEPTH_8U,3);
while(true)
{
frame = cvQueryFrame(capture);
if(!frame) break;
frame=cvCloneImage(frame);
cvSmooth(frame, frame, CV_GAUSSIAN,3,3); //smooth the original image using Gaussian kernel
IplImage* imgHSV = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3);
cvCvtColor(frame, imgHSV, CV_BGR2HSV); //Change the color format from BGR to HSV
IplImage* imgThresh = GetThresholdedImage(imgHSV);
cvSmooth(imgThresh, imgThresh, CV_GAUSSIAN,3,3); //smooth the binary image using Gaussian kernel
CvSeq* contours;
CvSeq* result;
CvMemStorage *storage = cvCreateMemStorage(0);
cvFindContours(imgThresh, storage, &contours, sizeof(CvContour), CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0));
while(contours)
{
result = cvApproxPoly(contours, sizeof(CvContour),storage,CV_POLY_APPROX_DP,cvContourPerimeter(contours)*0.02,0);
if(result->total == 4)
{
CvPoint *pt[4];
for(int i=0;i<4;i++)
{
pt[i] = (CvPoint*)cvGetSeqElem(result,i);
}
if (cvArcLength(result,CV_WHOLE_SEQ,1) >= 400)
{
cvLine(imgThresh,*pt[0],*pt[1],cvScalar(255,0,0),4);
cvLine(imgThresh,*pt[1],*pt[2],cvScalar(255,0,0),4);
cvLine(imgThresh,*pt[2],*pt[3],cvScalar(255,0,0),4);
cvLine(imgThresh,*pt[3],*pt[0],cvScalar(255,0,0),4);
int ROIwidth = abs((*pt[0]).x - (*pt[1]).x);
int ROIheight = abs((*pt[1]).y - (*pt[2]).y);
cvSetImageROI(frame,cvRect((*pt[1]).x,(*pt[1]).y,ROIwidth,ROIheight));
IplImage* temp = cvCreateImage(cvGetSize(frame),IPL_DEPTH_8U,3);
cvCopy(frame,temp,0);
cvResetImageROI(frame);
cvNamedWindow( "ROI", CV_WINDOW_AUTOSIZE );
cvShowImage( "ROI", temp);
printf("Width = %d\n",ROIwidth); //255-275
printf("Height = %d\n",ROIheight); //140-160
//Card Value Detection Starts Here
IplImage* colorcheck = RedCheck(temp);
int redpixelcheck = cvCountNonZero(colorcheck);
if (redpixelcheck <= 15)
{
printf("Card is Black\n");
}
else if (redpixelcheck >= 16)
{
printf("Card is Red\n");
}
//Card Value Detection Ends Here
cvReleaseImage(&temp);
cvReleaseImage(&frame);
cvReleaseImage(&colorcheck);
delete &ROIwidth;
delete &ROIheight;
delete &redpixelcheck;
}
//delete [] pt[4];
}
delete &result;
contours = contours->h_next;
//cvPutText (frame_t,text,cvPoint(200,400), &font, cvScalar(255,255,0));
}
cvNamedWindow( "Contour", CV_WINDOW_AUTOSIZE );
cvShowImage( "Contour", imgThresh);
cvNamedWindow("Video",CV_WINDOW_AUTOSIZE);
cvShowImage("Video", frame);
//Clean up used images
cvReleaseImage(&imgHSV);
cvReleaseImage(&imgThresh);
cvReleaseImage(&frame);
cvClearMemStorage(storage);
cvReleaseMemStorage(&storage);
//Wait 50mS
int c = cvWaitKey(10);
//If 'ESC' is pressed, break the loop
if((char)c==27 ) break;
}
cvDestroyAllWindows() ;
cvReleaseCapture(&capture);
return 0;
}
The disassembly always points to the same address
770915DE add esp,4

Why is my openGL texture only covering half of my quad? Source included

Here is my code. I'm attempting to draw a simple quadrilateral, and place a checkerboard pattern on both sides of it. I want to allow the user to rotate around this piece with the mouse. Everything works fine, other than the texture - it is slanted, and only covers about half of the quad. Can anyone see something glaringly obvious that I am doing wrong? Thanks.
#include "glut-3.7.6-bin\glut.h"
// Constants for rotating camera
#define CAMERA_RELEASE 0
#define CAMERA_ROTATE 1
#define CAMERA_ZOOM 2
// Current camera control setting
int cameraSetting;
// Current viewing angle and scale of the scene
float viewAngleX, viewAngleY, scaleFactor = 1.0;
// Click coordinates
int clickX, clickY;
// Screen size
const int screenWidth = 600;
const int screenHeight = 600;
// Texture data
GLuint texture;
////////////////////////////////////////////////////////////////
// Function Prototypes
////////////////////////////////////////////////////////////////
GLuint loadTexture(const char * filename);
////////////////////////////////////////////////////////////////
// Callback and Initialization Functions
////////////////////////////////////////////////////////////////
void callbackMouse(int button, int state, int x, int y)
{
if (state == GLUT_DOWN)
{
// Store clicked coordinates
clickX = x;
clickY = y;
// Set camera mode to rotate
if (button == GLUT_LEFT_BUTTON)
{
cameraSetting = CAMERA_ROTATE;
}
// Set camera mode to zoom
else if (button == GLUT_RIGHT_BUTTON)
{
cameraSetting = CAMERA_ZOOM;
}
}
// Ignore camera commands if no button is clicked
else if (state == GLUT_UP)
{
cameraSetting = CAMERA_RELEASE;
}
}
void callbackKeyboard(unsigned char key, int x, int y)
{
if (key == 'q') {
exit(0);
}
}
void callbackMotion(int x, int y)
{
if (cameraSetting == CAMERA_ROTATE)
{
// Camera rotate setting - adjust the viewing angle by the direction of motion
viewAngleX += (x - clickX) / 5.0;
viewAngleX = viewAngleX > 180 ? (viewAngleX - 360) : (viewAngleX < - 180 ? (viewAngleX + 360) : viewAngleX);
clickX = x;
viewAngleY += (y - clickY) / 5.0;
viewAngleY = viewAngleY > 180 ? (viewAngleY - 360) : (viewAngleY < - 180 ? (viewAngleY + 360) : viewAngleY);
clickY = y;
}
else if (cameraSetting == CAMERA_ZOOM)
{
// Polygonal scale to simulate camera zoom
float currentScaleFactor = scaleFactor;
scaleFactor *= (1+ (y - clickY) / 60.0);
scaleFactor = scaleFactor < 0 ? currentScaleFactor : scaleFactor;
clickY = y;
}
glutPostRedisplay();
}
void callbackDisplay()
{
// Clear the screen
glEnable(GL_DEPTH_TEST);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
// Set world window
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60, 1, 1, 100);
// Setup 3D environment
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0,0,5,
0,0,0,
0,1,0);
// Rotate and scale 3D environment to current user settings
glRotatef(viewAngleX, 0, 1, 0);
glRotatef(viewAngleY, 1, 0, 0);
glScalef(scaleFactor, scaleFactor, scaleFactor);
glBegin(GL_QUADS);
glTexCoord2d(0.0, 0.0); glVertex3f(-30, -5, -30);
glTexCoord2d(1.0, 0.0); glVertex3f(30, -5, -30);
glTexCoord2d(1.0, 1.0); glVertex3f(30, -5, 30);
glTexCoord2d(0.0, 1.0); glVertex3f(-30, -5, 30);
glEnd();
// Swap frame buffers
glutSwapBuffers();
}
void windowInitialization() {
// Enable textures by default
glEnable(GL_TEXTURE_2D);
// Load texture
texture = loadTexture("checkerboard.raw");
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
}
////////////////////////////////////////////////////////////////
// Main
////////////////////////////////////////////////////////////////
int main(int argc, char** argv)
{
// GLUT Initialization
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE|GLUT_DEPTH);
glutInitWindowSize(screenWidth,screenHeight);
// Create main window
glutCreateWindow("Test");
windowInitialization();
// Register callback functions
glutDisplayFunc(callbackDisplay);
glutMouseFunc(callbackMouse);
glutMotionFunc(callbackMotion);
glutKeyboardFunc(callbackKeyboard);
// Enter event processing loop
glutMainLoop();
}
////////////////////////////////////////////////////////////////
// Prototyped Functions
////////////////////////////////////////////////////////////////
GLuint loadTexture(const char * filename)
{
GLuint texture;
int width, height;
BYTE * data;
FILE * file;
// open texture data
file = fopen( filename, "rb" );
if ( file == NULL ) return 0;
// allocate buffer
width = 256;
height = 256;
data = (BYTE *) malloc( width * height * 3 );
// read texture data
fread( data, width * height * 3, 1, file );
fclose( file );
glGenTextures( 1, &texture );
glBindTexture( GL_TEXTURE_2D, texture );
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
// texture wraps over at the edges
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, 1 );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, 1);
// build texture
gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height,
GL_RGB, GL_UNSIGNED_BYTE, data );
// free buffer
free( data );
return texture;
}
Your code works fine for me; I suspect the problem is in the source image you're using for the texture. Double-check that the image is what you think it is. For example, using ImageMagick:
# Convert an image into raw RGB:
convert checkerboard.png checkerboard.rgb
# Convert raw RGB back to an image (assuming we know the size and color depth):
convert -size 256x256 -depth 8 checkerboard.rgb checkerboard.png

Resources