In SDL programming in c++ (I write codes in Ubuntu Linux), for drawing a text on the screen, I made a function and the second argument of it, gets the text. The type of it, is char*.
In the main function, what should I send to the above function for the second argument. For example in this code, I get error in compiling:
(I want to draw the text (Player1 must play...) on the screen by using the function)
#include<iostream>
#include"SDL/SDL.h"
#include<SDL/SDL_gfxPrimitives.h>
#include "SDL/SDL_ttf.h"
using namespace std;
void drawText(SDL_Surface* screen,char* strin1 ,int size,int x, int y,int fR, int fG, int fB,int bR, int bG, int bB)
{
TTF_Font*font = TTF_OpenFont("ARIAL.TTF", size);
SDL_Color foregroundColor = { fR, fG, fB };
SDL_Color backgroundColor = { bR, bG, bB };
SDL_Surface* textSurface = TTF_RenderText_Shaded(font, strin1,foregroundColor, backgroundColor);
SDL_Rect textLocation = { x, y, 0, 0 };
SDL_BlitSurface(textSurface, NULL, screen, &textLocation);
SDL_FreeSurface(textSurface);
TTF_CloseFont(font);
}
int main(){
SDL_Init( SDL_INIT_VIDEO);
TTF_Init();
SDL_Surface* screen = SDL_SetVideoMode(1200,800,32,0);
SDL_WM_SetCaption("Ping Pong", 0 );
SDL_Delay(500);
drawText(screen,"Player1 must play with ESCAPE & SPACE Keys and player2 must play with UP & DOWN Keys. . . Have Fun!!!",20,15,550,50,50,100,180,180,180);
return 0;
}
What you're getting isn't an error, it is a warning. Compiler isn't forcing you to fix the code it doesn't like, just hinting that it could be problematic.
In C, it is valid to handle string constants as char*, but because you still aren't allowed to modify this constants this approach considered dangerous and therefore deprecated. As far as I remember, newer C++ standards forbids that and forces using string literals as constants only.
So while code in question may be formally correct (depending on language standard version), it is adviced to change parameter type in your function to const char*.
Related
My C++/SDL2 program uses a Sprites class with a std::map of pointers to SDL_Textures and member functions for loading and rendering images, however when the program ran none of the loaded images showed up in the window.
I've found that the Sprites instance is given a correct pointer to the renderer and IMG_LoadTexture did not return 0. The renderer is also working properly since primitives like SDL_RenderDrawLine are drawn just fine.
Interestingly when I wanted to check if SDL_QueryTexture gave correct dimensions by printing the source rectangle's width and height, the program rendered the images properly. The printed dimensions were also correct, and trying to print the x and y fixed it too.
Why does this happen?
Here's the two important member functions in the Sprites class.
void Sprites::load(std::string id, std::string filename, int length) {
SDL_Texture* tex = IMG_LoadTexture(renderer, filename.c_str());
if (tex == 0) {
printf("Texture %s could not be loaded\n", filename.c_str());
}
sprmap[id] = tex;
lengthmap[id] = length;
printf("%s should be loaded now\n", id.c_str());
}
void Sprites::render(std::string id, float x, float y, int frame) {
SDL_Rect src;
SDL_Rect dest;
SDL_QueryTexture(sprmap[id], NULL, NULL, &src.w, &src.h);
src.w /= lengthmap[id];
printf("src x: %s, src y %s\n", std::to_string(src.x).c_str(), std::to_string(src.y).c_str());
//Images do not render when above line is omitted
src.x = frame*src.w;
dest.x = x;
dest.y = y;
dest.w = src.w;
dest.h = src.h;
SDL_RenderCopy(renderer, sprmap[id], &src, &dest);
}
Your SDL_Rect is not correctly initialised. Printing "fixes" it, but only by chance.
Your SDL_QueryTexture allows you to initialise w and h, but x and y have completely random values. As to why EXACTLY printing the values fixes things is beyond me, but I suspect that the random values don't go well with SDL_RenderCopy (especially negative values).
If you give proper values to x and y, your problem should go away.
If you want to read more about how variables are initialised this SO post should be a good place to start.
An alternative could be zero initialisation to make sure your structs always have a default value of 0.
The simplest way should be like this : SDL_Rect src{};
I draw some text to a surface (using SDL_ttf) and then I want to change the text on the surface. If I just redraw the surface the text does not go away. I have looked at several forum posts on how to fix the problem but I just cannot seem to figure it out. In particular I cannot understand why this solution does not work: (code is long so this just gives the essentials)
In Class file declared:
SDL_Surface* box; // These two are initialised to the
SDL_Surface* boxCopy; // same image
At the start of my render function:
*box = *boxCopy; \\Reset box surface
My understanding of pointers and C++ (which is admittedly limited) suggests that this should make the surface pointed at by box equal to the surface pointed at by boxCopy. Instead the boxCopy surface becomes a copy of box. I have no idea how boxCopy can be changed by this line of code but it seems like that is what is happening.
I'm not sure i completely understand your problem but hopefully this can help.. It's easier to update the text whenever the surface it's drawn on is to be updated rather than updating it whenever the actual text is updated. It might not be as optimized performance wise but i would say it's easier in most cases.
A typical program loop would include a re-rendering of a surface representing the screen followed by an SDL_Flip of this surface. You can of course optimize your re-rendering so you only render what has actually been updated since last frame. Is that what you're working on perhaps? If so, and if you use the method below you should be aware that the new text only covers the size of the new text and not the entire old text. I usually solve this by first drawing a filled rectangle and then the new text.
Here is a TTF example showing how text can be drawn on a surface (here called m_Screen, which is the surface flipped to screen every frame) in the simple case where i have one background color only:
void drawText(const char* string, int x, int y,
int fR, int fG, int fB, int bR, int bG, int bB)
{
SDL_Color foregroundColor = { fR, fG, fB };
SDL_Color backgroundColor = { bR, bG, bB };
SDL_Surface* textSurface = TTF_RenderText_Shaded(m_Font, string,
foregroundColor,
backgroundColor);
SDL_Rect textLocation = { x, y, 0, 0 };
SDL_BlitSurface(textSurface, NULL, m_Screen, &textLocation);
SDL_FreeSurface(textSurface);
}
Notice that this has been done before calling drawText (with some suitable font size):
m_Font = TTF_OpenFont("arial.ttf", size);
And this is done at cleanup:
TTF_CloseFont(m_Font);
I am writing an application using Xlib. I set the foreground of the window up like this:
XSetForeground (dpy, gc, WhitePixel (dpy, scr));
But now I need to change the drawing colour to something else, I first wanted to do that like this:
void update_window (Display* d, Window w, GC gc, Colormap cmap)
{
XWindowAttributes winatt;
XColor bcolor;
char bar_color[] = "#4E4E4E";
XGetWindowAttributes (d, w, &winatt);
XParseColor(d, cmap, bar_color, &bcolor);
XAllocColor(d, cmap, &bcolor);
// Draws the menu bar.
XFillRectangle (d, w, gc, 0, 0, winatt.width, 30);
XFreeColormap (d, cmap);
}
But this doesn't work. What does XParseColor and XAllocColor do then? And do I need to use XSetForeground again to change the colour?
You need to use XSetForeground. Try something like this:
XColor xcolour;
// I guess XParseColor will work here
xcolour.red = 32000; xcolour.green = 65000; xcolour.blue = 32000;
xcolour.flags = DoRed | DoGreen | DoBlue;
XAllocColor(d, cmap, &xcolour);
XSetForeground(d, gc, xcolour.pixel);
XFillRectangle(d, w, gc, 0, 0, winatt.width, 30);
XFlush(d);
Also, I don't think you can use that color string. Take a look into this page:
A numerical color specification consists of a color space name and a set of values in the following syntax:
<color_space_name>:<value>/.../<value>
The following are examples of valid color strings.
"CIEXYZ:0.3227/0.28133/0.2493"
"RGBi:1.0/0.0/0.0"
"rgb:00/ff/00"
"CIELuv:50.0/0.0/0.0"
Edit/Update: as #JoL mentions in the comment, you can still use the old syntax, but the usage is discouraged:
For backward compatibility, an older syntax for RGB Device is supported, but its continued use is not encouraged. The syntax is an initial sharp sign character followed by a numeric specification, in one of the following formats:
//I write additional function _RGB(...) where r,g,b is components in range 0...255
unsigned long _RGB(int r,int g, int b)
{
return b + (g<<8) + (r<<16);
}
void some_fun()
{
//sample set color, where r=255 g=0 b=127
XSetForeground(display, gc, _RGB(255,0,127));
//draw anything
XFillRectangle( display, window, gc, x, y, len, hei );
}
All colour changes are done with respect to a certain GC. That GC is then used for drawing. Yes XSetForeground is the most convenient way to do that.
You can have several GCs if you have a handful of colours you use often.
I'm using NeHe's tutorial on FreeType and OpenGL, and I'm having a problem defining members of
struct font_data within namespace freetype. It doesn't recognize font_data as a struct when I define its members in the namespace.
CE_Text.h:
#ifndef CE_TEXT
#define CE_TEXT
#include <Common/Headers.h>
/////////////////// MAJOR CREDIT TO NeHe FOR HIS TUTORIAL ON FREETPYE ///////////////////
///Wrap everything in a namespace, that we can use common
///function names like "print" without worrying about
///overlapping with anyone else's code.
namespace freetype {
//Inside of this namespace, give ourselves the ability
//to write just "vector" instead of "std::vector"
using std::vector;
//Ditto for string.
using std::string;
//This holds all of the information related to any
//freetype font that we want to create.
struct font_data{
float h; ///< Holds the height of the font.
GLuint * textures; ///< Holds the texture id's
GLuint list_base; ///< Holds the first display list id
//The init function will create a font of
//of the height h from the file fname.
void init(const char * fname, unsigned int h);
//Free all the resources assosiated with the font.
void clean();
};
//The flagship function of the library - this thing will print
//out text at window coordinates x,y, using the font ft_font.
//The current modelview matrix will also be applied to the text.
void print(const font_data &ft_font, float x, float y, const char *fmt) ;
}
#endif
CE_Text.cpp (my problem is at void font_data::init):
#include <Common/Headers.h>
using namespace freetype;
namespace freetype {
///This function gets the first power of 2 >= the
///int that we pass it.
inline int next_p2 ( int a )
{
int rval=1;
while(rval<a) rval<<=1;
return rval;
}
///Create a display list coresponding to the give character.
void make_dlist ( FT_Face face, char ch, GLuint list_base, GLuint * tex_base ) {
//The first thing we do is get FreeType to render our character
//into a bitmap. This actually requires a couple of FreeType commands:
//Load the Glyph for our character.
if(FT_Load_Glyph( face, FT_Get_Char_Index( face, ch ), FT_LOAD_DEFAULT ))
throw std::runtime_error("FT_Load_Glyph failed");
//Move the face's glyph into a Glyph object.
FT_Glyph glyph;
if(FT_Get_Glyph( face->glyph, &glyph ))
throw std::runtime_error("FT_Get_Glyph failed");
//Convert the glyph to a bitmap.
FT_Glyph_To_Bitmap( &glyph, ft_render_mode_normal, 0, 1 );
FT_BitmapGlyph bitmap_glyph = (FT_BitmapGlyph)glyph;
//This reference will make accessing the bitmap easier
FT_Bitmap& bitmap=bitmap_glyph->bitmap;
//Use our helper function to get the widths of
//the bitmap data that we will need in order to create
//our texture.
int width = next_p2( bitmap.width );
int height = next_p2( bitmap.rows );
//Allocate memory for the texture data.
GLubyte* expanded_data = new GLubyte[ 2 * width * height];
//Here we fill in the data for the expanded bitmap.
//Notice that we are using two channel bitmap (one for
//luminocity and one for alpha), but we assign
//both luminocity and alpha to the value that we
//find in the FreeType bitmap.
//We use the ?: operator so that value which we use
//will be 0 if we are in the padding zone, and whatever
//is the the Freetype bitmap otherwise.
for(int j=0; j <height;j++) {
for(int i=0; i < width; i++){
expanded_data[2*(i+j*width)]= expanded_data[2*(i+j*width)+1] =
(i>=bitmap.width || j>=bitmap.rows) ?
0 : bitmap.buffer[i + bitmap.width*j];
}
}
//Now we just setup some texture paramaters.
glBindTexture( GL_TEXTURE_2D, tex_base[ch]);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
//Here we actually create the texture itself, notice
//that we are using GL_LUMINANCE_ALPHA to indicate that
//we are using 2 channel data.
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height,
0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, expanded_data );
//With the texture created, we don't need to expanded data anymore
delete [] expanded_data;
//So now we can create the display list
glNewList(list_base+ch,GL_COMPILE);
glBindTexture(GL_TEXTURE_2D,tex_base[ch]);
glPushMatrix();
//first we need to move over a little so that
//the character has the right amount of space
//between it and the one before it.
glTranslatef(bitmap_glyph->left,0,0);
//Now we move down a little in the case that the
//bitmap extends past the bottom of the line
//(this is only true for characters like 'g' or 'y'.
glTranslatef(0,bitmap_glyph->top-bitmap.rows,0);
//Now we need to account for the fact that many of
//our textures are filled with empty padding space.
//We figure what portion of the texture is used by
//the actual character and store that information in
//the x and y variables, then when we draw the
//quad, we will only reference the parts of the texture
//that we contain the character itself.
float x=(float)bitmap.width / (float)width,
y=(float)bitmap.rows / (float)height;
//Here we draw the texturemaped quads.
//The bitmap that we got from FreeType was not
//oriented quite like we would like it to be,
//so we need to link the texture to the quad
//so that the result will be properly aligned.
glBegin(GL_QUADS);
glTexCoord2d(0,0); glVertex2f(0,bitmap.rows);
glTexCoord2d(0,y); glVertex2f(0,0);
glTexCoord2d(x,y); glVertex2f(bitmap.width,0);
glTexCoord2d(x,0); glVertex2f(bitmap.width,bitmap.rows);
glEnd();
glPopMatrix();
glTranslatef(face->glyph->advance.x >> 6 ,0,0);
//increment the raster position as if we were a bitmap font.
//(only needed if you want to calculate text length)
//glBitmap(0,0,0,0,face->glyph->advance.x >> 6,0,NULL);
//Finnish the display list
glEndList();
}
void font_data::init(const char * fname, unsigned int h) {
//Allocate some memory to store the texture ids.
textures = new GLuint[128];
this->h=h;
//Create and initilize a freetype font library.
FT_Library library;
if (FT_Init_FreeType( &library ))
throw std::runtime_error("FT_Init_FreeType failed");
//The object in which Freetype holds information on a given
//font is called a "face".
FT_Face face;
//This is where we load in the font information from the file.
//Of all the places where the code might die, this is the most likely,
//as FT_New_Face will die if the font file does not exist or is somehow broken.
if (FT_New_Face( library, fname, 0, &face ))
throw std::runtime_error("FT_New_Face failed (there is probably a problem with your font file)");
//For some twisted reason, Freetype measures font size
//in terms of 1/64ths of pixels. Thus, to make a font
//h pixels high, we need to request a size of h*64.
//(h << 6 is just a prettier way of writting h*64)
FT_Set_Char_Size( face, h << 6, h << 6, 96, 96);
//Here we ask opengl to allocate resources for
//all the textures and displays lists which we
//are about to create.
list_base=glGenLists(128);
glGenTextures( 128, textures );
//This is where we actually create each of the fonts display lists.
for(unsigned char i=0;i<128;i++)
make_dlist(face,i,list_base,textures);
//We don't need the face information now that the display
//lists have been created, so we free the assosiated resources.
FT_Done_Face(face);
//Ditto for the library.
FT_Done_FreeType(library);
}
void font_data::clean() {
glDeleteLists(list_base,128);
glDeleteTextures(128,textures);
delete [] textures;
}
/// A fairly straight forward function that pushes
/// a projection matrix that will make object world
/// coordinates identical to window coordinates.
inline void pushScreenCoordinateMatrix() {
glPushAttrib(GL_TRANSFORM_BIT);
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(viewport[0],viewport[2],viewport[1],viewport[3]);
glPopAttrib();
}
/// Pops the projection matrix without changing the current
/// MatrixMode.
inline void pop_projection_matrix() {
glPushAttrib(GL_TRANSFORM_BIT);
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glPopAttrib();
}
///Much like Nehe's glPrint function, but modified to work
///with freetype fonts.
void print(const font_data &ft_font, float x, float y, const char *fmt, ...) {
// We want a coordinate system where things coresponding to window pixels.
pushScreenCoordinateMatrix();
GLuint font=ft_font.list_base;
float h=ft_font.h/.63f; //We make the height about 1.5* that of
char text[256]; // Holds Our String
va_list ap; // Pointer To List Of Arguments
if (fmt == NULL) // If There's No Text
*text=0; // Do Nothing
else {
va_start(ap, fmt); // Parses The String For Variables
vsprintf(text, fmt, ap); // And Converts Symbols To Actual Numbers
va_end(ap); // Results Are Stored In Text
}
//Here is some code to split the text that we have been
//given into a set of lines.
//This could be made much neater by using
//a regular expression library such as the one avliable from
//boost.org (I've only done it out by hand to avoid complicating
//this tutorial with unnecessary library dependencies).
const char *start_line=text;
vector<string> lines;
for(const char *c=text;*c;c++) {
if(*c=='\n') {
string line;
for(const char *n=start_line;n<c;n++) line.append(1,*n);
lines.push_back(line);
start_line=c+1;
}
}
if(start_line) {
string line;
for(const char *n=start_line;n<c;n++) line.append(1,*n);
lines.push_back(line);
}
glPushAttrib(GL_LIST_BIT | GL_CURRENT_BIT | GL_ENABLE_BIT | GL_TRANSFORM_BIT);
glMatrixMode(GL_MODELVIEW);
glDisable(GL_LIGHTING);
glEnable(GL_TEXTURE_2D);
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glListBase(font);
float modelview_matrix[16];
glGetFloatv(GL_MODELVIEW_MATRIX, modelview_matrix);
//This is where the text display actually happens.
//For each line of text we reset the modelview matrix
//so that the line's text will start in the correct position.
//Notice that we need to reset the matrix, rather than just translating
//down by h. This is because when each character is
//draw it modifies the current matrix so that the next character
//will be drawn immediatly after it.
for(int i=0;i<lines.size();i++) {
glPushMatrix();
glLoadIdentity();
glTranslatef(x,y-h*i,0);
glMultMatrixf(modelview_matrix);
// The commented out raster position stuff can be useful if you need to
// know the length of the text that you are creating.
// If you decide to use it make sure to also uncomment the glBitmap command
// in make_dlist().
// glRasterPos2f(0,0);
glCallLists(lines[i].length(), GL_UNSIGNED_BYTE, lines[i].c_str());
// float rpos[4];
// glGetFloatv(GL_CURRENT_RASTER_POSITION ,rpos);
// float len=x-rpos[0];
glPopMatrix();
}
glPopAttrib();
pop_projection_matrix();
}
}
struct freetype::font_data{
should be
struct font_data{
The fact that font_data is in namespace freetype is already covered by the surrounding namespace freetype { }.
So, in fact, in your code it is true that you never did declare any freetype::font_data type! It's as if you were attempting to declare a freetype::freetype::font_data type instead.
This is analagous to how you do not write:
struct T
{
void T::foo();
};
but instead:
struct T
{
void foo();
};
You have to include CE_Text.h into CE_Text.cpp for that to work. Without seeing the definition for font_data class, the compiler will not allow you to define its members.
That's what it is telling you by "not recognizing font_data as a struct". Of course, it is not recognizing it, since it is completely unknown in CE_Text.cpp.
According to your comments, you included your header files in circular fashion. This is your problem right there. Never include header files circularly. Granted, your include guards make sure that the inclusion cycle gets broken in some way. But that does not in any way help your code to compile, as you can see in your example.
Until you completely remove any inclusion cycles from your code, trying to fix it is a crapshoot.
Ok, I'm trying to make a program that finds the position of a colored pixel within the desktop. To do this I make a screenshot of the desktop then go through the pixels and search for the one that has the matching RGB as i need. The only problem is that my program returs strange coordonates X,Y for the found pixel...
#include <stdio.h>
#include <windows.h>
#include <atlimage.h>
#include <iostream>
using namespace std;
struct rgbcolor{
int red;
int green;
int blue;} myColor;
struct point{
int x;
int y;
};
point SearchPixel(int r,int g, int b){
CImage bitmapzor;
bitmapzor.Load(("C:\\1.bmp"));
COLORREF PixColor=0; //This is a color data
int R=0,G=0,B=0; //These are the channel values
BYTE* byteptr = (BYTE*)bitmapzor.GetBits();
int ok=0;
int pitch = bitmapzor.GetPitch(); //This is a pointer offset to get new line of the bitmap
//Go through every pixel and compare the RGB code
for (int i=0; i<bitmapzor.GetWidth();i++)
for (int j=0; j<bitmapzor.GetHeight();j++)
{
B= *(byteptr+pitch*j+3*i);
G= *(byteptr+pitch*j+3*i+1);
R= *(byteptr+pitch*j+3*i+2);
if(R==r&&G==g&&B==b)
{ point p;
p.x=i;
p.y=j;
cout<<"First pixel found at:\n X:"<<p.x<<"\n Y:"<<p.y<<"\n-----------------\n";
return p;
}
}
bitmapzor.Destroy(); //destroy the bitmap
point p;
p.x=-1;
p.y=-1;
cout<<"Pixel not found!\n";
return p;
}
bool ScreenCapture(int x, int y, int width, int height, char *filename){
// get a DC compat. w/ the screen
HDC hDc = CreateCompatibleDC(0);
// make a bmp in memory to store the capture in
HBITMAP hBmp = CreateCompatibleBitmap(GetDC(0), width, height);
// join em up
SelectObject(hDc, hBmp);
// copy from the screen to my bitmap
BitBlt(hDc, 0, 0, width, height, GetDC(0), x, y, SRCCOPY);
CImage image;
image.Attach(hBmp);
image.Save(("C:\\1.bmp"), Gdiplus::ImageFormatBMP);
SearchPixel(myColor.red,myColor.green,myColor.blue);
// free the bitmap memory
DeleteObject(hBmp);
return 1;
}
int main()
{ //RGB for the searched color
myColor.red=200;
myColor.green=191;
myColor.blue=231;
int count=0;
while(true){
ScreenCapture(0, 0, 1366, 768, "c:\\1.bmp");
count++;
cout<<"Number of searches:"<<count<<"\n\n";
Sleep(500);
}
system("pause");
return 0;
}
Well, this code could be simplified quite a lot, but first I'd suggest you try a much, much simpler case, like finding a known integer in a small array of integers. Once you have that working, move up to more complex cases.
EDIT:
You have enough knowledge to do this? Cristy, please don't take this the wrong way, but of all the programmers I've had to deal with, the worst have been the ones who thought they had nothing to learn. I didn't actually look for the bug in your code because your code is overcomplicated, and if you had gone from simple to complex when building it, you would have caught your error a lot sooner.
I suggest that you print out the RGB values of the first few pixel to make sure you're even grabbing the pixel data correctly. If your offsets are wrong, you'll never get this to work.
Ok, finally I found a mistake that I think is the cause of this problem.
The pointer arithmetics:
B= *(byteptr+pitch*j+3*i);
G= *(byteptr+pitch*j+3*i+1);
R= *(byteptr+pitch*j+3*i+2);
Are done for 24bits images, but the screenshot is a 32bits image that means I have to change the multiplier to 4 insteand of 3. That means:
B= *(byteptr+pitch*j+4*i);
G= *(byteptr+pitch*j+4*i+1);
R= *(byteptr+pitch*j+4*i+2);
I think... I'll be back with an edit if this works or not.
EDIT: Yes it works, it gives the corect pixel position. Thanks everyone for your help :) .