Comparing images in which some parts are variable, but should not matter - c

I am concerned about to find dissimilarities between images as shown in the samples underneath with the black oval shape.
My problem is that some part of image is also variable, but I do not want to consider this part when finding dissimilarities. To overcome this problem I want to make "transparent" that area which is now marked with red color: the variable part Date/Time and the Date/Time edit field should be excluded from comparison as can be seen from image below:
One way is:
I can use a “transparent” color to mark image areas that should not be compared. To do this, I need to modify the baseline copy of an image in the following manner:
Open the baseline image in an image editor (for instance, in MSPaint).
Select the color that you will use as the “transparent” color.
Change the color of the top-left pixel to the “transparent” color.
Use the “transparent” color to fill image areas that you want to exclude from comparison.
How to do automate above manual work through coding? I want to implement above behavior in C code.

My suggestion is:
First implement the solution as a command line with ImageMagick.
Once this works, port this command line over to ImageMagick's C API.
Here are a few answers about comparing images using ImageMagick compare. They may not apply to your precise question, but thy provide enough theoretical background with practical examples to get you started:
ImageMagick compare executable: unrecognized option -metric
Can we programatically compare different images of same resolutions?
ImageMagick: “Diff” an Image
ImageMagick compare: Disregard white matches from the PSNR result
If I understand your question correctly, you do want to compare only some parts of two images, any you want to exclude other parts from the comparison where you already know there are (uninteresting) differences. Right?
Taking these two images as an example:
BTW, these two images have been born as PDFs, and I could apply the procedure described below to PDF pages too (without a need to convert them to image files first).
You do not necessarily need a transparent mask -- you can use a black (or any color) one too.
Create a green mask of 280x20 pixels size:
convert -size 280x20 xc:green greenmask-280x20.png
Now use composite to place the mask on top of each of the images:
convert \
http://i.stack.imgur.com/Q1pyC.png \
greenmask-280x20.png \
-geometry +32+35 \
-compose over \
-composite \
c.png
convert \
http://i.stack.imgur.com/JVije.png \
greenmask-280x20.png \
-geometry +32+35 \
-compose over \
-composite \
r.png
The -geometry +32+35 parameter maybe requires some explanation: it tells ImageMagick to place the top left corner of the greenmask 32 pixels to the right and 35 pixels to the bottom of the top left corner of the original image.
The resulting images are here:
An answer that discusses the different compose methods known to ImageMagick is here:
Superpose two sets of images
Now your images are ready for either statistical or visual comparison, provided by ImageMagick's compare command:
compare c.png r.png -compose src delta.png
The delta.png shows all pixels in red which are different, the rest is white:
Or, using the most simple compare command, where the reference image serves as a pale background with red delta pixels on top:
compare c.png r.png delta2.png

If you are providing a rectangle to colour in, why not just ignore a rectangular area in the first place? Here is some pseudo code
int compareimages (char *im1, char* im2, int wid, int dep, int x0, int y0, int x1, int y1) {
int x, y;
for (y=0; y<dep; y++)
for (x=0; x<wid; x++)
if (x<x0 || x>x1 || y<y0 || y>y1) // if outside rectangle
if im1[y*wid+x] != im2[y*wid+x] // compare pixels
return 0;
return 1;
}
UPDATE for several areas to be ignored, which may overlap.
Still not hard: just provide an array of rectangles. It is still going to be easier than going to the trouble of painting out areas when you can check them in the first place.
#include <stdio.h>
#define WID 200
#define DEP 600
typedef struct {
int left;
int top;
int right;
int bot;
} rect;
char image1[WID*DEP];
char image2[WID*DEP];
int inrect (int x, int y, rect r) {
if (x<r.left || x>r.right || y<r.top || y>r.bot)
return 0;
return 1;
}
int compareimages (char *im1, char* im2, int wid, int dep, rect *rarr, int rects) {
int x, y, n, ignore;
for (y=0; y<dep; y++)
for (x=0; x<wid; x++) {
ignore = 0;
for (n=0; n<rects; n++)
ignore |= inrect (x, y, rarr[n]);
if (!ignore)
if (im1[y*wid+x] != im2[y*wid+x]) // compare pixels
return 0;
}
return 1;
}
int main(void) {
rect rectarr[2] = { {10, 10, 50, 50}, { 40, 40, 90, 90 }};
// ... load images ...
// put pixel in one of the rectangles
image1[20*WID+20] = 1;
if (compareimages (image1, image2, WID, DEP, rectarr, 2))
printf ("Same\n");
else
printf ("Different\n");
// put pixel outside any rectangles
image1[0] = 1;
if (compareimages (image1, image2, WID, DEP, rectarr, 2))
printf ("Same\n");
else
printf ("Different\n");
return 0;
}
Program output:
Same
Different
EDIT added another version of the function, comparing 4 pixel components.
int compareimages (char *im1, char* im2, int wid, int dep, rect *rarr, int rects) {
int x, y, n, ignore;
for (y=0; y<dep; y++)
for (x=0; x<wid; x++) {
ignore = 0;
for (n=0; n<rects; n++)
ignore |= inrect (x, y, rarr[n]);
if (!ignore) {
if (im1[y*wid*4+x] != im2[y*wid*4+x]) // compare pixels
return 0;
if (im1[y*wid*4+x+1] != im2[y*wid*4+x+1])
return 0;
if (im1[y*wid*4+x+2] != im2[y*wid*4+x+2])
return 0;
if (im1[y*wid*4+x+3] != im2[y*wid*4+x+3])
return 0;
}
}
return 1;
}

Normally, such an 'image' as is used in the example is NOT a single image.
Rather it is a large number of images overlaying each other.
Most likely, the 'image' is made of:
the background
the outside border (which has 4 parts)
the upper left icon
the upper border clickable button( three of them)
the text field: Date/Time:
the input field: (for the date/time)
the text field: 'Table:'
the input multi line field/ with initial text 'Customers'
etc etc etc
I.E. that is not a single image but rather many images
that overlay each other
a single image would be something like a .bmp or .tif or .jpg file

Related

C/Ncurses how to wrap text in a textfield

I would like to wrap a short text in a Text Box in Ncurses, but somehow my text keeps going off screen. How can I wrap the text so it (automatically) goes to a new line when reaching the end of the screen on the right?
I tried playing with '\n' and setting limits but witout results. Any tips what I am doing wrong? See below code for what is going on.
Thanks from a beginner programmer.
#include <ncurses.h>
#include <string.h>
void text(WINDOW* textborder, int wymax, int wxmax, char text5[], int size)
{
for (int i=0;i<size;i++)
{
mvwaddch(textborder,2,i+i, text5[i]);
if (i==wxmax)
{
mvwaddch(textborder,2,i+i, '\n');
}
}
}
int main()
{
char text5[]={"Somebody is watching over us... controlling us. It's true, I tell you. It's true! We are merely sprites that dance at the beck and call of our button-pressing overlord. This is a video game. Don't you see? We are characters in a video game."};
int size;
size=strlen(text5);
int wymax; int wxmax;
initscr();
WINDOW* textborder=newwin(LINES/4, COLS, LINES-LINES/4, 0);
box(textborder,-1,-1);
getmaxyx(textborder, wymax,wxmax);
wxmax=wxmax-4;
text(textborder, wymax, wxmax, text5, size);
wgetch(textborder);
endwin();
return 0;
}
In theory the text should wrap itself. I think your issue may be coming from using mvwaddch, ch generally causes the text not to wrap. This may help Ncurses no-wrap mode when adding strings to window. Sorry I can't be more helpful :)
Applications that draw a box with a border in curses do this using two windows, one within the other. The outer box gets the border; the inner box gets the text. Text printed within the inner box does not affect the outer box.
For example, some of the demo/example programs in ncurses do this, e.g., test_addstr creates look (for the box) and show (for the text):
limit = LINES - 5;
if (level > 0) {
look = newwin(limit, COLS - (2 * (level - 1)), 0, level - 1);
work = newwin(limit - 2, COLS - (2 * level), 1, level);
show = newwin(4, COLS, limit + 1, 0);
box(look, 0, 0);
wnoutrefresh(look);
limit -= 2;
} else {
work = stdscr;
show = derwin(stdscr, 4, COLS, limit + 1, 0);
}
keypad(work, TRUE);

OpenCV Tiff Wrong Color Values Readout

I have a 16-bit tiff image with no color profile (camera profile embedded) and I am trying to read its RGB values in OpenCV. However, comparing the output values to the values given when the image is opened by GIMP for example gives totally different values (GIMP being opened with keeping the image's profile option; no profile conversion). I have tried also another image studio software like CaptureOne and the result accords with GIMP differs from OpenCV output.
Not sure if reading and opening the image in OpenCV is wrong somehow, in spite of using IMREAD_UNCHANGED flag.
I have as well tried to read the image using FreeImage library but still the same result.
Here is a snippet of the code reading pixels' values in OpenCV
const float Conv16_8 = 255.f / 65535.f;
cv::Vec3d curVal;
// upperLeft/lowerRight are just some pre-defined corners for the ROI
for (int row = upperLeft.y; row <= lowerRight.y; row++) {
unsigned char* dataUCPtr = img.data + row * img.step[0];
unsigned short* dataUSPtr = (unsigned short*)dataUCPtr;
dataUCPtr += 3 * upperLeft.x;
dataUSPtr += 3 * upperLeft.x;
for (int col = upperLeft.x; col <= lowerRight.x; col++) {
if (/* some check if the pixel is valid */) {
if (img.depth() == CV_8U) {
for (int chan = 0; chan < 3; chan++) {
curVal[chan] = *dataUCPtr++;
}
}
else if (img.depth() == CV_16U) {
for (int chan = 0; chan < 3; chan++) {
curVal[chan] = (*dataUSPtr++)*Conv16_8;
}
}
avgX += curVal;
}
else {
dataUCPtr += 3;
dataUSPtr += 3;
}
}
}
and here is the image (download the image) I am reading with its RGB readouts in
CaptureOne Studio AdobeRGB:
vs OpenCV RGB (A1=white --> F1=Black):
PS1: I have tried also to change the output color space in GIMP/CaptureOne to sRGB but still the difference is almost the same, not any closer to OpenCV
PS2: I am reversing OpenCV imread channels' order before extracting the RGB values from the image COLOR_RGB2BGR
OP said:
I have a 16-bit tiff image with no color profile (camera profile embedded)
Well no, your image definitely has a color profile, and it should not be ignored. The embedded profile is as important as the numeric values of each pixel. Without a defined profile, the pixel values are somewhat meaningless.
From what I can tell, OpenCV does not linearize gamma by default... except when it does... Regardless, the gamma indicated in the profile is unique:
Now compare that to sRGB:
So the sRGB transformations can't be used.
If you are looking for performance, applying the curve via LUT is usually more efficient than a full-on color management system.
In this case, using a LUT. The following LUT was taken from the color profile, 16bit values, and 256 steps:
// Phase One TRC from color profile
profileTRC = [0x0000,0x032A,0x0653,0x097A,0x0CA0,0x0FC2,0x12DF,0x15F8,0x190C,0x1C19,0x1F1E,0x221C,0x2510,0x27FB,0x2ADB,0x2DB0,0x3079,0x3334,0x35E2,0x3882,0x3B11,0x3D91,0x4000,0x425D,0x44A8,0x46E3,0x490C,0x4B26,0x4D2F,0x4F29,0x5113,0x52EF,0x54BC,0x567B,0x582D,0x59D1,0x5B68,0x5CF3,0x5E71,0x5FE3,0x614A,0x62A6,0x63F7,0x653E,0x667B,0x67AE,0x68D8,0x69F9,0x6B12,0x6C23,0x6D2C,0x6E2D,0x6F28,0x701C,0x710A,0x71F2,0x72D4,0x73B2,0x748B,0x755F,0x762F,0x76FC,0x77C6,0x788D,0x7951,0x7A13,0x7AD4,0x7B93,0x7C51,0x7D0F,0x7DCC,0x7E8A,0x7F48,0x8007,0x80C8,0x8189,0x824C,0x8310,0x83D5,0x849B,0x8562,0x862B,0x86F4,0x87BF,0x888A,0x8956,0x8A23,0x8AF2,0x8BC0,0x8C90,0x8D61,0x8E32,0x8F04,0x8FD7,0x90AA,0x917E,0x9252,0x9328,0x93FD,0x94D3,0x95AA,0x9681,0x9758,0x9830,0x9908,0x99E1,0x9ABA,0x9B93,0x9C6C,0x9D45,0x9E1F,0x9EF9,0x9FD3,0xA0AD,0xA187,0xA260,0xA33A,0xA414,0xA4EE,0xA5C8,0xA6A1,0xA77B,0xA854,0xA92D,0xAA05,0xAADD,0xABB5,0xAC8D,0xAD64,0xAE3B,0xAF11,0xAFE7,0xB0BC,0xB191,0xB265,0xB339,0xB40C,0xB4DE,0xB5B0,0xB680,0xB750,0xB820,0xB8EE,0xB9BC,0xBA88,0xBB54,0xBC1F,0xBCE9,0xBDB1,0xBE79,0xBF40,0xC005,0xC0CA,0xC18D,0xC24F,0xC310,0xC3D0,0xC48F,0xC54D,0xC609,0xC6C5,0xC780,0xC839,0xC8F2,0xC9A9,0xCA60,0xCB16,0xCBCA,0xCC7E,0xCD31,0xCDE2,0xCE93,0xCF43,0xCFF2,0xD0A0,0xD14D,0xD1FA,0xD2A5,0xD350,0xD3FA,0xD4A3,0xD54B,0xD5F2,0xD699,0xD73E,0xD7E3,0xD887,0xD92B,0xD9CE,0xDA6F,0xDB11,0xDBB1,0xDC51,0xDCF0,0xDD8F,0xDE2C,0xDEC9,0xDF66,0xE002,0xE09D,0xE138,0xE1D2,0xE26B,0xE304,0xE39C,0xE434,0xE4CB,0xE562,0xE5F8,0xE68D,0xE722,0xE7B7,0xE84B,0xE8DF,0xE972,0xEA04,0xEA97,0xEB29,0xEBBA,0xEC4B,0xECDC,0xED6C,0xEDFC,0xEE8B,0xEF1A,0xEFA9,0xF038,0xF0C6,0xF154,0xF1E1,0xF26F,0xF2FC,0xF388,0xF415,0xF4A1,0xF52D,0xF5B9,0xF645,0xF6D0,0xF75B,0xF7E6,0xF871,0xF8FC,0xF987,0xFA11,0xFA9B,0xFB26,0xFBB0,0xFC3A,0xFCC4,0xFD4E,0xFDD7,0xFE61,0xFEEB,0xFF75,0xFFFF]
If a matching array of the linearized values was needed, it would be
[0x0000,0x0101,0x0202,0x0303,0x0404....
But such an array is not neded for most uses, as the index value of the PhaseOne TRC array directly relates to the linear value.
I.e. phaseOneTRC[0x80] is 0xAD64
and the linear value is 0x80 * 0x101.
It turned out, it is all about having, loading and applying the proper ICC profile on the cv::Mat data. To do that one must use a color management engine along side OpenCV such as LittleCMS.

Trouble registering screen boundaries for certain inputs (down and right)

I am creating a scrolling shooter for DMG using gbdk, it is based off some youtube tutorials and this example. In fact the link is the skeleton of my program. My issue is that the screen boundary conditions aren't working properly for down and right inputs. For up and left, they work correctly however, and the code for those is basically the exact same. I have also compiled the code from the link above, and it works correctly there. Apologies in advance, I have a childish sense of humor, so the game is penis-based.
The main differences between the skeleton code and mine is that I use a meta-sprite for the player, and an array for the x and y coordinates of the player. I have tried using individual integers for the locations and changing the bounds of the screen, but nothing seems to work.
#include <gb/gb.h>
#include <stdio.h>
#include "gameDicks.c"
#include "DickSprites.c"
#define SCREEN_WIDTH 160
BOOLEAN ishard = TRUE, playing = TRUE;
struct gameDicks flacid;
struct gameDicks hard;
INT8 spritesize = 8, dicklocation[2] = {20, 80};
int i;
void moveGameDicks(struct gameDicks* Dick, UINT8 x, UINT8 y){
move_sprite(Dick->spriteids[0], x, y);
move_sprite(Dick->spriteids[1], x + spritesize, y);
move_sprite(Dick->spriteids[2], x, y + spritesize);
move_sprite(Dick->spriteids[3], x + spritesize, y + spritesize);
}
void setuphard(INT8 dicklocation[2]){
hard.x = dicklocation[0];
hard.y = dicklocation[1];
hard.width = 16;
hard.height = 16;
//load sprites
set_sprite_tile(0,0);
hard.spriteids[0] = 0;
set_sprite_tile(1,1);
hard.spriteids[1] = 1;
set_sprite_tile(2,2);
hard.spriteids[2] = 2;
set_sprite_tile(3,3);
hard.spriteids[3] = 3;
}
void init_screen()
{
SHOW_BKG;
SHOW_SPRITES;
DISPLAY_ON;
}
void init_player()
{
SHOW_SPRITES;
set_sprite_data(0, 8, DickSprites);
setuphard(dicklocation);
}
void input()
{
if (joypad() & J_UP && dicklocation[1])
{
if (dicklocation[1] <= 16){
dicklocation[1] = 16;
}
else{
dicklocation[1]--;
}
}
if (joypad() & J_DOWN && dicklocation[1])
{
if (dicklocation[1] >= 150){
dicklocation[1] = 150;
}
else{
dicklocation[1]++;
}
}
}
void update_sprites()
{
moveGameDicks(&hard, dicklocation[0], dicklocation[1]);
}
int main()
{
init_screen();
init_player();
init_screen();
while(playing)
{
wait_vbl_done(2);
input();
update_sprites();
}
return 0;
}
What I expect is to be able to move the player up to y = 16, and down to y = 150. When it hits these values, it stops moving until you go the other direction. Instead, what I see happen is that the up direction works as expected, but as soon as the down key is pressed - no matter the y-location - the player is immediately sent to the bottom of the screen. From there, pressing up sends it to the very top. Further, the player can only move from the top position to the bottom, and not scroll in between. I'm baffled by this because the conditions are the exact same (except for the y-values), so I don't understand why they behave so differently.
Using an unsigned int may help here as an 8-bit integer will only hold values from -128 to 127, which might cause undefined behaviour when you compare it with over 150, pushing it to a negative value?
You have defined dicklocation as an INT8, when it would be better as a UINT8 or even longer if you plan on ever having a screen size larger than 255 bytes.

Print doesn't show in printed array although specified

I'm working a simple candy crush game for my year 1 assignment.
I am at this stage where I need to show my self-made simple marker( *box made of '|' and '_'* ) on the center of the board ( board[5][5] ) once the program is executed.
Here is the current code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//FUNCTION: Draw the Board
int drawBoard()
{
//Declare array size
int board[9][9];
//initialize variables
int rows, columns, randomNumber, flag;
//random number seed generator
srand(time(NULL));
for ( rows = 0 ; rows < 9 ; rows++ )
{
for ( columns = 0 ; columns < 9 ; columns++ )
{
flag = 0;
do
{
//generate random numbers from 2 - 8
randomNumber = rand() %7 + 2;
board[rows][columns] = randomNumber;
//Checks for 2 adjacent numbers.
if ( board[rows][columns] == board[rows - 1][columns] || board[rows][columns] == board[rows][columns - 1] )
{
flag = 0;
continue;
}
else
{
flag = 1;
printf( " %d ", board[rows][columns] );
}
} while ( flag == 0 );
}//end inner for-loop
printf("\n\n");
}//end outer for-loop
//call FUNCTION marker() to display marker around board[5][5]
marker( board[5][5] );
}//end FUNCTION drawBoard
//FUNCTION: Mark the surrounding of the number with "|" and "_" at board[5][5]
void marker( int a )
{
printf( " _ \n" );
printf( "|%c|\n", a );
printf( " _ \n" );
}
int main()
{
drawBoard();
}
At the end of function drawBoard(), I placed the code marker( board[5][5] ).
This should have printed the markers around the number printed at coordinate board[5][5]..but for some reason it displays right after the board has been printed.
So why doesn't it print at that coordinate although I specified it at board[5][5]?
What could be the problem here?
so in your marker function you need to pass the board and the coordinate you want to print at
void marker( int x, int y, int** board )
{
board[x][y-1]="_";
board[x-1][y]="|";
board[x+1][y]="|";
board[x][y+1]="_";
}
then after the call to marker(5,5,board), call drawboard again
my code's a bit off but that's the logic, except you need to check for the case that the marker is at the edge of the board
in other words, you need to keep board around, and any time you make a change to it, clear the screen and print the whole board out again.
There is no persistent drawing in the way that you are doing this. You are just printing straight to the shell/command prompt. The way that you trying to do things will not work. You can't edit something drawn to the prompt after you have drawn it, you need to basically clear the screen and then draw again but with your indicated maker.
I don't know if you are able to use libraries in your assignment, but a very good library that WILL let you do is ncurses
EDIT Full rewrite of answer
Drawing Things On Top of One Another In CMD
Alright, I had some downtime at work, so I wrote a project to do what you need and I'm going to post code and explain what it does and why you need it along the way.
First thin that you are going to need a basically a render buffer or a render context. Whenever you are programming in a graphics API such as OpenGL, you don't just render straight to the screen, you render each object that you have to a buffer that rasterizes your content and turns it into pixels. Once it's in that form, the API shoves the rendered picture onto the screen. We are going to take a similar approach where instead of drawing to a pixel buffer on the GPU, we are going to draw to a character buffer. Think about each character as a pixel on the screen.
Here is a pastebin of the complete source:
Complete Source of Project
RenderContext
Our class to do this will be the RenderContext class. It has fields to hold width and height as well as an array of chars and a special char that we fill our buffer with whenever we clear it.
This class simply holds an array and functions to let us render to it. It makes sure that when we draw to it, we are within bounds. It is possible for an object to try to draw outside of the clipping space (off screen). However, whatever is drawn there is discarded.
class RenderContext {
private:
int m_width, m_height; // Width and Height of this canvas
char* m_renderBuffer; // Array to hold "pixels" of canvas
char m_clearChar; // What to clear the array to
public:
RenderContext() : m_width(50), m_height(20), m_clearChar(' ') {
m_renderBuffer = new char[m_width * m_height];
}
RenderContext(int width, int height) : m_width(width), m_height(height), m_clearChar(' ') {
m_renderBuffer = new char[m_width * m_height];
}
~RenderContext();
char getContentAt(int x, int y);
void setContentAt(int x, int y, char val);
void setClearChar(char clearChar);
void render();
void clear();
};
The two most important functions of this class are setContentAt and render
setContentAt is what an object calls to fill in a "pixel" value. To make this a little more flexible, our class uses a pointer to an array of chars rather than a straight array (or even a two dimensional array). This lets us set the size of our canvas at runtime. Because of this, we access elements of this array with x + (y * m_width) which replaces a two dimensional dereference such as arr[i][j]
// Fill a specific "pixel" on the canvas
void RenderContext::setContentAt(int x, int y, char val) {
if (((0 <= x) && (x < m_width)) && ((0 <= y) && (y < m_height))) {
m_renderBuffer[(x + (y * m_width))] = val;
}
}
render is what actually draws to the prompt. All it does is iterate over all the "pixels" in it's buffer and place them on screen and then moves to the next line.
// Paint the canvas to the shell
void RenderContext::render() {
int row, column;
for (row = 0; row < m_height; row++) {
for (column = 0; column < m_width; column++) {
printf("%c", getContentAt(column, row));
}
printf("\n");
}
}
I_Drawable
Our next class is an Interface that lets us contract with objects that they can draw to our RenderContext. It is pure virtual because we don't want to actually be able to instantiate it, we only want to derive from it. It's only function is draw which accepts a RenderContext. Derived classes use this call to receive the RenderContext and then use RenderContext's setContentAt to put "pixels" into the buffer.
class I_Drawable {
public:
virtual void draw(RenderContext&) = 0;
};
GameBoard
The first class to implement the I_Drawable, thus being able to render to our RenderContext, is the GameBoard class. This is where a majority of the logic comes in. It has fields for width, height, and a integer array that holds the values of the elements on the board. It also has two other fields for spacing. Since when you draw your board using your code, you have spaces between each element. We don't need to incorporate this into the underlying structure of the board, we just need to use them when we draw.
class GameBoard : public I_Drawable {
private:
int m_width, m_height; // Width and height of the board
int m_verticalSpacing, m_horizontalSpacing; // Spaces between each element on the board
Marker m_marker; // The cursor that will draw on this board
int* m_board; // Array of elements on this board
void setAtPos(int x, int y, int val);
void generateBoard();
public:
GameBoard() : m_width(10), m_height(10), m_verticalSpacing(5), m_horizontalSpacing(3), m_marker(Marker()) {
m_board = new int[m_width * m_height];
generateBoard();
}
GameBoard(int width, int height) : m_width(width), m_height(height), m_verticalSpacing(5), m_horizontalSpacing(3), m_marker(Marker()) {
m_board = new int[m_width * m_height];
generateBoard();
}
~GameBoard();
int getAtPos(int x, int y);
void draw(RenderContext& renderTarget);
void handleInput(MoveDirection moveDirection);
int getWidth();
int getHeight();
};
It's key functions are generateBoard, handleInput, and the derived virtual function draw. However, do note that in its constructor it creates a new int array and gives it to its pointer. Then its destructor automatically removes the allocated memory whenever the board goes away.
generateBoard is what we use to actual create the board and fill it with numbers. It will iterate over each location on the board. Each time, it will look at the elements directly to the left and above and store them. Then it will generate a random number until the number it generates does not match either of the stored elements, then it stores the number in the array. I rewrote this to get rid of the flag usage. This function gets called during the construction of the class.
// Actually create the board
void GameBoard::generateBoard() {
int row, column, randomNumber, valToLeft, valToTop;
// Iterate over all rows and columns
for (row = 0; row < m_height; row++) {
for (column = 0; column < m_width; column++) {
// Get the previous elements
valToLeft = getAtPos(column - 1, row);
valToTop = getAtPos(column, row - 1);
// Generate random numbers until we have one
// that is not the same as an adjacent element
do {
randomNumber = (2 + (rand() % 7));
} while ((valToLeft == randomNumber) || (valToTop == randomNumber));
setAtPos(column, row, randomNumber);
}
}
}
handleInput is what deals with moving the cursor around on the board. It's basically a freebie and your next step after getting the cursor to draw over the board. I needed a way to test the drawing. It accepts an enumeration that we switch on to know where to move our cursor to next. If you maybe wanted to have your cursor wrap around the board whenever you reach an edge, you would want to do that here.
void GameBoard::handleInput(MoveDirection moveDirection) {
switch (moveDirection) {
case MD_UP:
if (m_marker.getYPos() > 0)
m_marker.setYPos(m_marker.getYPos() - 1);
break;
case MD_DOWN:
if (m_marker.getYPos() < m_height - 1)
m_marker.setYPos(m_marker.getYPos() + 1);
break;
case MD_LEFT:
if (m_marker.getXPos() > 0)
m_marker.setXPos(m_marker.getXPos() - 1);
break;
case MD_RIGHT:
if (m_marker.getXPos() < m_width - 1)
m_marker.setXPos(m_marker.getXPos() + 1);
break;
}
}
draw is very important because it's what gets the numbers into the RenderContext. To summarize, it iterates over every element on the board, and draws in the correct location on the canvas placing an element under the correct "pixel". This is where we incorporate the spacing. Also, take care and note that we render the cursor in this function.
It's a matter of choice, but you can either store a marker outside of the GameBoard class and render it yourself in the main loop (this would be a good choice because it loosens the coupling between the GameBoard class and the Marker class. However, since they are fairly coupled, I chose to let GameBoard render it. If we used a scene graph, as we probably would with a more complex scene/game, the Marker would probably be a child node of the GameBoard so it would be similar to this implementation but still more generic by not storing an explicit Marker in the GameBoard class.
// Function to draw to the canvas
void GameBoard::draw(RenderContext& renderTarget) {
int row, column;
char buffer[8];
// Iterate over every element
for (row = 0; row < m_height; row++) {
for (column = 0; column < m_width; column++) {
// Convert the integer to a char
sprintf(buffer, "%d", getAtPos(column, row));
// Set the canvas "pixel" to the char at the
// desired position including the padding
renderTarget.setContentAt(
((column * m_verticalSpacing) + 1),
((row * m_horizontalSpacing) + 1),
buffer[0]);
}
}
// Draw the marker
m_marker.draw(renderTarget);
}
Marker
Speaking of the Marker class, let's look at that now. The Marker class is actually very similar to the GameBoard class. However, it lacks a lot of the logic that GameBoard has since it doesn't need to worry about a bunch of elements on the board. The important thing is the draw function.
class Marker : public I_Drawable {
private:
int m_xPos, m_yPos; // Position of cursor
public:
Marker() : m_xPos(0), m_yPos(0) {
}
Marker(int xPos, int yPos) : m_xPos(xPos), m_yPos(yPos) {
}
void draw(RenderContext& renderTarget);
int getXPos();
int getYPos();
void setXPos(int xPos);
void setYPos(int yPos);
};
draw simply puts four symbols onto the RenderContext to outline the selected element on the board. Take note that Marker has no clue about the GameBoard class. It has no reference to it, it doesn't know how large it is, or what elements it holds. You should note though, that I got lazy and didn't take out the hard coded offsets that sort of depend on the padding that the GameBoard has. You should implement a better solution to this because if you change the padding in the GameBoard class, your cursor will be off.
Besides that, whenever the symbols get drawn, they overwrite whatever is in the ContextBuffer. This is important because the main point of your question was how to draw the cursor on top of the GameBoard. This also goes to the importance of draw order. Let's say that whenever we draw our GameBoard, we drew a '=' between each element. If we drew the cursor first and then the board, the GameBoard would draw over the cursor making it invisible.
If this were a more complex scene, we might have to do something fancy like use a depth buffer that would record the z-index of an element. Then whenever we drew, we would check and see if the z-index of the new element was closer or further away than whatever was already in the RenderContext's buffer. Depending on that, we might skip drawing the "pixel" altogether.
We don't though, so take care to order your draw calls!
// Draw the cursor to the canvas
void Marker::draw(RenderContext& renderTarget) {
// Adjust marker by board spacing
// (This is kind of a hack and should be changed)
int tmpX, tmpY;
tmpX = ((m_xPos * 5) + 1);
tmpY = ((m_yPos * 3) + 1);
// Set surrounding elements
renderTarget.setContentAt(tmpX - 0, tmpY - 1, '-');
renderTarget.setContentAt(tmpX - 1, tmpY - 0, '|');
renderTarget.setContentAt(tmpX - 0, tmpY + 1, '-');
renderTarget.setContentAt(tmpX + 1, tmpY - 0, '|');
}
CmdPromptHelper
The last class that I'm going to talk about is the CmdPromptHelper. You don't have anything like this in your original question. However, you will need to worry about it soon. This class is also only useful on Windows so if you are on linux/unix, you will need to worry about dealing with drawing to the shell yourself.
class CmdPromptHelper {
private:
DWORD inMode; // Attributes of std::in before we change them
DWORD outMode; // Attributes of std::out before we change them
HANDLE hstdin; // Handle to std::in
HANDLE hstdout; // Handle to std::out
public:
CmdPromptHelper();
void reset();
WORD getKeyPress();
void clearScreen();
};
Each one of the functions is important. The constructor gets handles to the std::in and std::out of the current command prompt. The getKeyPress function returns what key the user presses down (key-up events are ignored). And the clearScreen function clears the prompt (not really, it actually moves whatever is already in the prompt up).
getKeyPress just makes sure you have a handle and then reads what has been typed into the console. It makes sure that whatever it is, it is a key and that it is being pressed down. Then it returns the key code as a Windows specific enum usually prefaced by VK_.
// See what key is pressed by the user and return it
WORD CmdPromptHelper::getKeyPress() {
if (hstdin != INVALID_HANDLE_VALUE) {
DWORD count;
INPUT_RECORD inrec;
// Get Key Press
ReadConsoleInput(hstdin, &inrec, 1, &count);
// Return key only if it is key down
if (inrec.Event.KeyEvent.bKeyDown) {
return inrec.Event.KeyEvent.wVirtualKeyCode;
} else {
return 0;
}
// Flush input
FlushConsoleInputBuffer(hstdin);
} else {
return 0;
}
}
clearScreen is a little deceiving. You would think that it clears out the text in the prompt. As far as I know, it doesn't. I'm pretty sure it actually shifts all the content up and then writes a ton of characters to the prompt to make it look like the screen was cleared.
An important concept that this function brings up though is the idea of buffered rendering. Again, if this were a more robust system, we would want to implement the concept of double buffering which means rendering to an invisible buffer and waiting until all drawing is finished and then swap the invisible buffer with the visible one. This makes for a much cleaner view of the render because we don't see things while they are still getting drawn. The way we do things here, we see the rendering process happen right in front of us. It's not a major concern, it just looks ugly sometimes.
// Flood the console with empty space so that we can
// simulate single buffering (I have no idea how to double buffer this)
void CmdPromptHelper::clearScreen() {
if (hstdout != INVALID_HANDLE_VALUE) {
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD cellCount; // How many cells to paint
DWORD count; // How many we painted
COORD homeCoord = {0, 0}; // Where to put the cursor to clear
// Get console info
if (!GetConsoleScreenBufferInfo(hstdout, &csbi)) {
return;
}
// Get cell count
cellCount = csbi.dwSize.X * csbi.dwSize.Y;
// Fill the screen with spaces
FillConsoleOutputCharacter(
hstdout,
(TCHAR) ' ',
cellCount,
homeCoord,
&count
);
// Set cursor position
SetConsoleCursorPosition(hstdout, homeCoord);
}
}
main
The very last thing that you need to worry about is how to use all these things. That's where main comes in. You need a game loop. Game loops are probably the most important thing in any game. Any game that you look at will have a game loop.
The idea is:
Show something on screen
Read input
Handle the input
GOTO 1
This program is no different. The first thing it does is create a GameBoard and a RenderContext. It also makes a CmdPromptHelper which lets of interface with the command prompt. After that, it starts the loop and lets the loop continue until we hit the exit condition (for us that's pressing escape). We could have a separate class or function do dispatch input, but since we just dispatch the input to another input handler, I kept it in the main loop. After you get the input, you send if off to the GameBoard which alters itself accordingly. The next step is to clear the RenderContext and the screen/prompt. Then rerun the loop if escape wasn't pressed.
int main() {
WORD key;
GameBoard gb(5, 5);
RenderContext rc(25, 15);
CmdPromptHelper cph;
do {
gb.draw(rc);
rc.render();
key = cph.getKeyPress();
switch (key) {
case VK_UP:
gb.handleInput(MD_UP);
break;
case VK_DOWN:
gb.handleInput(MD_DOWN);
break;
case VK_LEFT:
gb.handleInput(MD_LEFT);
break;
case VK_RIGHT:
gb.handleInput(MD_RIGHT);
break;
}
rc.clear();
cph.clearScreen();
} while (key != VK_ESCAPE);
}
After you have taken into consideration all of these things, you understand why and where you need to be drawing your cursor. It's not a matter of calling a function after another, you need to composite your draws. You can't just draw the GameBoard and then draw the Marker. At least not with the command prompt. I hope this helps. It definitely alleviated the down time at work.

Convert BMP to pure RGB, no color map?

Using the EasyBMP library (a close adaptation, anyway), I have code to convert a BMP to greyscale.
int monochromeValue (RGBApixel foo)
{
return (foo.Red+foo.Green+foo.Blue)/3;
}
void setToColor (RGBApixel* loc, int newColor)
{
loc->Red = loc->Green = loc->Blue = newColor;
}
void greyscaleImage (BMP* image)
{
int x, y;
for (x = 0; x < image->Width; ++x)
for (y = 0; y < image->Height; ++y)
{
RGBApixel* pixel = elementAt (image, x, y);
setToColor (pixel, monochromeValue (*pixel));
}
}
An RGBA pixel is
typedef unsigned char ebmpBYTE;
typedef struct RGBApixel
{
ebmpBYTE Blue;
ebmpBYTE Green;
ebmpBYTE Red;
ebmpBYTE Alpha;
} RGBApixel;
The code doesn't make it greyscale. One image is more sepia, and another is mostly greyscale but has some colored highlights.
I'm assuming this has something to do with the color map. What can I do to make it so that it just uses RGB, without running it through a palette? (Changing the bit depth is fine, if that'll work.)
TIA.
This page suggests that palettes aren't used on 16+ bit depth images. So I tried changing the bit depth to 32, and it worked. 24 also worked. So that seems to be the answer: use higher bit depths, and it won't need a palette, and it'll instead use the RGB values as they are.
My guess is your are being bitten by overflow in your monocromeValue(...) function. As you are adding 3 u8 values together in parenthesis, I don't think the compiler will up-convert the adds to a larger integer type. I would try:
int monochromeValue (RGBApixel foo)
{
return ((int)foo.Red+(int)foo.Green+(int)foo.Blue)/3;
}
As a test to be sure though.

Resources