void FormatText()
{
if (formatting == false || wordWrapWidth == 0 || _fontInst.texelSize == Vector2.zero)
{
_formattedText = _text;
return;
}
float lineWidth = _fontInst.texelSize.x * wordWrapWidth;
System.Text.StringBuilder target = new System.Text.StringBuilder(_text.Length);
float widthSoFar = 0.0f;
float wordStart = 0.0f;
int targetWordStartIndex = -1;
int fmtWordStartIndex = -1;
for (int i = 0; i < _text.Length; ++i)
{
char idx = _text[i];
tk2dFontChar chr;
if (_fontInst.useDictionary)
{
if (!_fontInst.charDict.ContainsKey(idx)) idx = (char)0;
chr = _fontInst.charDict[idx];
}
else
{
if (idx >= _fontInst.chars.Length) idx = (char)0; // should be space
chr = _fontInst.chars[idx];
}
if (idx == '\n')
{
widthSoFar = 0.0f;
wordStart = 0.0f;
targetWordStartIndex = target.Length;
fmtWordStartIndex = i;
}
else if (idx == ' ' || idx == '.' || idx == ',' || idx == ':' || idx == ';' || idx == '!')
{
if ((widthSoFar + chr.p1.x * _scale.x) > lineWidth)
{
target.Append('\n');
widthSoFar = chr.advance * _scale.x;
}
else
{
widthSoFar += chr.advance * _scale.x;
}
wordStart = widthSoFar;
targetWordStartIndex = target.Length;
fmtWordStartIndex = i;
}
else
{
if ((widthSoFar + chr.p1.x * _scale.x) > lineWidth)
{
// If the last word started after the start of the line
if (wordStart > 0.0f)
{
wordStart = 0.0f;
widthSoFar = 0.0f;
// rewind
target.Remove(targetWordStartIndex + 1, target.Length - targetWordStartIndex - 1);
target.Append('\n');
i = fmtWordStartIndex;
continue; // don't add this character
}
else
{
target.Append('\n');
widthSoFar = chr.advance * _scale.x;
}
}
else
{
widthSoFar += chr.advance * _scale.x;
}
}
target.Append(idx);
}
_formattedText = target.ToString();
}