• Advertisement
Sign in to follow this  

Trying to make an ingame text editor.

This topic is 1833 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Okay, third fourth try at writing this code:

 

[code] 

/*
Showing the applyText function here for reference:
void applyText(int x,int y,string text)
{
blitImage(TTF_RenderText_Solid( font, text.c_str(), fontcolor ),x,y);
}
 
 * also for reference:
 
void blitImage(SDL_Surface *in,int tx,int ty)
{
SDL_Rect tmp;
tmp.x = tx;
tmp.y = ty;
SDL_BlitSurface(in,NULL,screen,&tmp);
}
 */
 
int textOffset = 0;
 
void showString(const std::string &text)
{
    try
    {
unsigned int lineNum = 0;
        std::string lineText;
 
for(unsigned int i = 0; i < text.size(); i++)
{
//Check if it's the end of the line.
if(text[i] == '\n')
{
//Check if there's something to display.
if(!lineText.empty())
{
//Display the line.
applyText(20, (20 * lineNum), lineText);
 
//Clear the temporary string.
lineText.clear();
}
 
//Increase the line number.
lineNum++;
}
else
{
//Add this character to the temporary string.
lineText.push_back(text[i]);
}
}
 
//Display the final line (because there is no final endline).
if(!lineText.empty())
{
applyText(20, (20 * lineNum), lineText);
}
    }
    catch(exception& e)
    {
        cerr<<"Exception thrown "<<e.what()<<"\n";
    }
    catch(...)
    {
        cerr<<"other exception cought.\n";
    } 
}
 
int getCursorX(string whatToEdit, int cursor)
{
    int x = 0;
    int y = 0;
    for(int a = 0; a<cursor; a++)
    {
        if(whatToEdit[a] == 0 || whatToEdit[a] == '\n')
        {
            x = 0;
            y++;
        }
        else
            x++;
    }
    return x;
}
 
int getCursorY(string whatToEdit, int cursor)
{
    int x = 0;
    int y = 0;
    for(int a = 0; a<cursor; a++)
    {
        if(whatToEdit[a] == 0 || whatToEdit[a] == '\n')
        {
            x = 0;
            y++;
        }
        else
            x++;
    }
    return y;
}
 
int xToNextY(string whatToEdit,int cursor)
{
    int totalPos = 0;
    for(int a = cursor; a<whatToEdit.length(); a++)
    {
        totalPos++;
        if(whatToEdit[a] == 0 || whatToEdit[a] == '\n')
            break;
    }
    return totalPos;
}
 
int xToLastY(string whatToEdit,int cursor)
{
    int totalPos = 0;
    for(int a = cursor; a>0; a--)
    {
        totalPos++;
        if(whatToEdit[a] == 0 || whatToEdit[a] == '\n')
            break;
    }
    return totalPos;
}
 
bool cont = true;
 
void scriptingWindow(int mobID)
{
    try
    {
    //mob refers to a character in the game
    //the string we're probably editing is the characters ai script
    
    string whatToEdit = mobs[mobID].scriptL;
    
    textOffset = 0;
    int loopStartTime = 0;
    bool programcont = true;
    SDL_Event programEvent; //there's also another SDL_Event for the main loop
    int cursorPos = 0;
    Uint8 *keystates;
    
    while(programcont)
    {
        loopStartTime = SDL_GetTicks(); //get the time the loop started at
     
        keystates = SDL_GetKeyState(NULL);
        
        while(SDL_PollEvent(&programEvent))
        {
            if(programEvent.type == SDL_QUIT) //break both this loop, and the main loop
            {
                programcont = false;
                cont = false;
                break;
            }
            if(programEvent.type == SDL_KEYDOWN) //only break this loop
            {
                if(programEvent.key.keysym.sym == SDLK_ESCAPE)
                {
                    programcont = false;
                    break;
                }
                else if(programEvent.key.keysym.sym == SDLK_RIGHT)
                    cursorPos++;
                else if(programEvent.key.keysym.sym == SDLK_LEFT)
                    cursorPos--;
                else if(programEvent.key.keysym.sym == SDLK_DOWN)
                    cursorPos += xToNextY(whatToEdit,cursorPos);
                else if(programEvent.key.keysym.sym == SDLK_UP)
                {
                    cursorPos -= xToLastY(whatToEdit,cursorPos);
                    if(getCursorX(whatToEdit,cursorPos)-textOffset < 5 && textOffset > 0)
                        textOffset--;
                }
                else if(keystates[SDLK_LCTRL] && programEvent.key.keysym.sym == SDLK_s)
                {
                    mobs[mobID].scriptL = whatToEdit;
                    mobs[mobID].ready = false;
                    programcont = false;
                }
                else if(programEvent.key.keysym.unicode >= ' ' && programEvent.key.keysym.unicode <= '}')
                {
                    whatToEdit = whatToEdit.substr(0,cursorPos) + (char)programEvent.key.keysym.unicode + whatToEdit.substr(cursorPos,whatToEdit.length()-cursorPos);
                    cursorPos++;
                }
                else if(programEvent.key.keysym.sym == SDLK_BACKSPACE && cursorPos > 0)
                {
                    whatToEdit.erase(cursorPos-1,1);
                    cursorPos--;
                }
                else if(programEvent.key.keysym.sym == SDLK_DELETE && cursorPos < whatToEdit.length()-1)
                    whatToEdit.erase(cursorPos,1);
                else if(programEvent.key.keysym.sym == SDLK_RETURN)
                {
                    whatToEdit = whatToEdit.substr(0,cursorPos) + '\n' + whatToEdit.substr(cursorPos,whatToEdit.length()-cursorPos);
                    cursorPos++;
                }
            }
            else if(programEvent.type == SDL_MOUSEBUTTONDOWN)
            {
                if(programEvent.button.button == SDL_BUTTON_WHEELUP)
                {
                    cursorPos -= xToLastY(whatToEdit,cursorPos);
                    if(getCursorX(whatToEdit,cursorPos)-textOffset < 5 && textOffset > 0)
                        textOffset--;
                }
                else if(programEvent.button.button == SDL_BUTTON_WHEELDOWN)
                    cursorPos += xToNextY(whatToEdit,cursorPos);
            }
        }
        
        if(cursorPos < 0)
            cursorPos = 0;
        if(cursorPos > whatToEdit.length()-1)
            cursorPos = whatToEdit.length()-1;
        
        if(getCursorY(whatToEdit,cursorPos)-textOffset > 30)
            textOffset++;
        
        clearScreen();  //Paint a black rectangle over the whole screen.
        
        showString(whatToEdit); //show the lines of text
        applyTextRed(20+(getCursorX(whatToEdit,cursorPos)*10),20*(getCursorY(whatToEdit,cursorPos)-textOffset),"|");
                
        flipScreen();   //SDL_Flip(screen);
        
        if(SDL_GetTicks()-loopStartTime > 200)
        {
            cerr<<"Crash prevention executed.\n";
            programcont = false;
            cont = false;               //crash prevention
            break;                      //exit the program if this loop takes far longer than normal to complete
        }
    }
    }
    catch (exception& e)
    {
        cerr<<"Exception cought "<<e.what()<<"\n";
    }
    catch(...)
    {
        cerr<<"other exception cought.\n";
    }
}
[/code]
 
 
Still seems to crash.
Edited by Syerjchep

Share this post


Link to post
Share on other sites
Advertisement

Can you comment this like just a little so we can follow the logic please thank you.

Share this post


Link to post
Share on other sites

Why are you wasting 1/3 of most lines with spaces so you have to sidescroll all the time?

Also there are so many magic numbers in there where one cannot know what those are.

I would also put some smaller parts of it into their own functions and use a switch statement.

Share this post


Link to post
Share on other sites
Why are you wasting 1/3 of most lines with spaces so you have to sidescroll all the time?

Also there are so many magic numbers in there where one cannot know what those are.

I would also put some smaller parts of it into their own functions and use a switch statement.

Well, the indents are because it's already inside a bunch of if and while statements, as it's just a small segment of the much larger program.

I'm not quite sure what you mean by magic numbers, but most of the variables are probably not relavant.

 

 

Can you comment this like just a little so we can follow the logic please thank you.

Sure.

Share this post


Link to post
Share on other sites

Magic numbers like those 20, 100, 1000, 999999 you repeatedly use, I would put into constants with an informative name thats defined only once to prevent errors and aid in understanding the program.

If thats a function that is even longer than shown and needs that much indentation its a sure sign its too huge, which makes it difficult to debug.

 

From reading your code I even get doubts if that is just C and not C++. So if this is C++, how about programming a class first that implements all logic to the console and then some other class to place, align and draw everything in a window on your screen that can be used from your main loop? And if its really C, why not use some similarly split up functions in separate files?

Share this post


Link to post
Share on other sites

Just because it's c++ doesn't mean I'm using a console? What on earth would make you think that?

And who said it's C?

 

And no, it's not a function, it's inside an if statement inside an events loop inside the main function.

Share this post


Link to post
Share on other sites

[quote name='Syerjchep' timestamp='1357767598' post='5019637']
Just because it's c++ doesn't mean I'm using a console? What on earth would make you think that?

And who said it's C?
[/quote]

console as in "that thing people build in their graphics mode game for typing in text" not console as in "guy makes text mode game that runs inside a shell window".

And noone said its C, but you are just using C constructs like C array, C style struct access, C style number twiddling loops, ...; theres nothing really looking C++ like using STL, method calls,... wink.png

[quote name='Syerjchep' timestamp='1357767598' post='5019637']
And no, it's not a function, it's inside an if statement inside an events loop inside the main function.
[/quote]

I know and thats whats wrong with it.smile.png

Share this post


Link to post
Share on other sites

Updated the origional post.

Even though I haven't even finished rewriting what I had before (you can't actually edit the text yet), it still seems to crash it.

Share this post


Link to post
Share on other sites

Why are you using a 'character grid' instead of an std::list<std::string>? You could check each string and split it when you encounter a newline, pushing back multiple substrings to the list, and popping the front of the list when you get beyond your desired buffer size (say, 100 lines or more).

 

Which function is crashing? Under what conditions does it crash?

 

Are you saying the program crashes before you even enter int main()? If so, it's probably because your "char charactergrid[1000][1000];" takes up almost a full megabyte on the stack. You shouldn't put that kind of memory on the stack, it's not made for that. Using a std::vector (not 2D!) or std::list of std::strings is a far superior and 'correct' solution.

Share this post


Link to post
Share on other sites
Why are you using a 'character grid' instead of an std::list<std::string>? You could check each string and split it when you encounter a newline, pushing back multiple substrings to the list, and popping the front of the list when you get beyond your desired buffer size (say, 100 lines or more).

 

Which function is crashing? Under what conditions does it crash?

 

Are you saying the program crashes before you even enter int main()? If so, it's probably because your "char charactergrid[1000][1000];" takes up almost a full megabyte on the stack. You shouldn't put that kind of memory on the stack, it's not made for that. Using a std::vector (not 2D!) or std::list of std::strings is a far superior and 'correct' solution.

After a bit of testing, I found It is the character show function.

Also, I can't just make the strings into smaller strings, as they are going to be edited, which may or may not include adding or removing newline characters that would move all the other rows around.

 

 

Also, apparently the loop doesn't immedently crash the program, rather, at some point something goes wrong a few seconds in randomly, and suddenly every single iteration of the loop takes over a second, so I was able to add a crash prevention of sorts, that will automatically shut down the whole program if a single iteration of the scripting loop takes over 200ms.

Edited by Syerjchep

Share this post


Link to post
Share on other sites
 Also, I can't just make the strings into smaller strings, as they are going to be edited, which may or may not include adding or removing newline characters that would move all the other rows around.

 
In that case, why not have the entire "buffer" be a single string, with newlines and all?
Then anytime the string changes in response to keypresses, you parse the the string into a std::vector<std::string> at every location there is a newline and at every location where a line is greater than 'n' characters wide.
 
The std::vector<std::string> is the formatted data ready for drawing and is generated from the huge std::string which is the text the user edits.
 

Also, apparently the loop doesn't immedently crash the program, rather, at some point something goes wrong a few seconds in randomly, and suddenly every single iteration of the loop takes over a second, so I was able to add a crash prevention of sorts, that will automatically shut down the whole program if a single iteration of the scripting loop takes over 200ms.

 
That sounds like you are hiding the problem rather than understanding and fixing the problem. wink.png

Edited by Servant of the Lord

Share this post


Link to post
Share on other sites
 Also, I can't just make the strings into smaller strings, as they are going to be edited, which may or may not include adding or removing newline characters that would move all the other rows around.

 
In that case, why not have the entire "buffer" be a single string, with newlines and all?
Then anytime the string changes in response to keypresses, you parse the the string into a std::vector<std::string> at every location there is a newline and at every location where a line is greater than 'n' characters wide.
 
The std::vector<std::string> is the formatted data ready for drawing and is generated from the huge std::string which is the text the user edits.
 

Also, apparently the loop doesn't immedently crash the program, rather, at some point something goes wrong a few seconds in randomly, and suddenly every single iteration of the loop takes over a second, so I was able to add a crash prevention of sorts, that will automatically shut down the whole program if a single iteration of the scripting loop takes over 200ms.

 
That sounds like you are hiding the problem rather than understanding and fixing the problem. wink.png

 

Well in my last rewrite (updated like 5 minutes ago) that's what I did, without the vectors.

It's all just one string, no more characterGrid.

 

But, for whatever reason, it still crashed.

I guess I'll try to isolate the function again.

Share this post


Link to post
Share on other sites

Random guess: applyText() doesn't like being passed empty strings?

Using a debugger, you can find out exactly where something is crashing and why.

 

void DisplayText(const std::string &text)
{
	unsigned int lineNum = 0;
    std::string lineText;
	
	for(unsigned int i = 0; i < text.size(); i++)
	{
		//Check if it's the end of the line.
		if(text[i] == '\n')
		{
			//Check if there's something to display.
			if(!lineText.empty())
			{
				//Display the line.
				applyText(20, (20 * lineNum), lineText);
				
				//Clear the temporary string.
				lineText.clear();
			}
			
			//Increase the line number.
			lineNum++;
		}
		else
		{
			//Add this character to the temporary string.
			lineText.push_back(text[i]);
		}
	}
	
	//Display the final line (because there is no final endline).
	if(!lineText.empty())
	{
		applyText(20, (20 * lineNum), lineText);
	}
}

Share this post


Link to post
Share on other sites

Random guess: applyText() doesn't like being passed empty strings?

Using a debugger, you can find out exactly where something is crashing and why.

 

void DisplayText(const std::string &text)
{
	unsigned int lineNum = 0;
    std::string lineText;
	
	for(unsigned int i = 0; i < text.size(); i++)
	{
		//Check if it's the end of the line.
		if(text[i] == '\n')
		{
			//Check if there's something to display.
			if(!lineText.empty())
			{
				//Display the line.
				applyText(20, (20 * lineNum), lineText);
				
				//Clear the temporary string.
				lineText.clear();
			}
			
			//Increase the line number.
			lineNum++;
		}
		else
		{
			//Add this character to the temporary string.
			lineText.push_back(text[i]);
		}
	}
	
	//Display the final line (because there is no final endline).
	if(!lineText.empty())
	{
		applyText(20, (20 * lineNum), lineText);
	}
}

This works, and I'm sure it's better.

Yet it's still crashing.

I added try catch statements, yet they return nothing.

 

Gonna try and figure out how to use a debugger now.

Share this post


Link to post
Share on other sites

I finally fixed it after almost a week of fustration.

And I only had to add one like of code.

 

Guess what it was?

I forgot to free the textures created by applyText. e.g. it was just a memory leak

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement