Okay, here's some pseudocode to demonstrate what my function does:
class Textbox {
std::vector<sf::Sprite> drawable_characters;
sf::Font font;
public:
setString(const std::string& input);
draw(sf::RenderTarget& target); // you figure out this part
}
void Textbox::setString(const std::string& input) {
std::size_t n = 0;
unsigned int fontSize = 12;
bool bold = false;
sf::Vector2i position = /* some initial position */;
sf::Color color = sf::Color(255, 255, 255);
sf::Glyph glyph;
char last_literal = -1;
drawable_characters.clear();
while(n <= input.length()) {
// process escape sequences
while(input[n] == '\\') {
n++;
switch(input[n]) {
case 'n':
// insert a linebreak
position.y += font.getLineSpacing(fontSize);
position.x = /* x of initial position */;
last_literal = -1;
n++;
break;
case '{':
if( /* the following characters are "red}" */ ) {
color = sf::Color(255, 0, 0);
n += 4;
} else if( ... ) {
// more colors!
} else if( /* the next character is '}' */ ) {
color = sf::Color(255, 255, 255);
n++;
}
break;
default:
// throw an error?
break;
}
}
// done processing any escape sequences, so now we're on a literal character
char current_literal = input[n];
glyph = font.getGlyph(current_literal, fontSize, bold);
drawable_characters.push_back( sf::Sprite(font, glyph.getTextureRect()) );
drawable_characters.back().setColor(color);
// skip kerning if we're at the start of the current line
if(last_literal != -1)
position.x += font.getKerning(last_literal, current_literal, fontSize);
drawable_characters.back().setPosition(position.x, position.y + glyph.bounds.top);
position.x += glyph.advance;
last_literal = current_literal;
n++;
}
}
I should stress that this is something I scribbled down just now based on my real code, so while it should include all the important steps, there's almost certainly some bugs and missing pieces (beyond the obvious ones). And of course I left out word wrapping. But still, this should be enough for you to get your head around what's required and figure out the rest on your own.
In particular, keep an eye out for premature destruction errors. Remember things like the "white square problem" from the Texture tutorial? Similar things can happen when working with fonts, except for some reason they give you invisible squares instead of white squares so it's much less obvious that it's your fault.
P.S. If you're feeling particularly masochistic,
here's what this function looks like in my real program.