gFont.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "gfx/gFont.h"
  24. #include "core/resourceManager.h"
  25. #include "core/stream/fileStream.h"
  26. #include "core/strings/unicode.h"
  27. #include "core/strings/findMatch.h"
  28. #include "core/strings/stringFunctions.h"
  29. #include "core/util/endian.h"
  30. #include "core/util/safeDelete.h"
  31. #include "console/console.h"
  32. #include "console/engineAPI.h"
  33. #include "platform/threads/mutex.h"
  34. #include "zlib/zlib.h"
  35. GFX_ImplementTextureProfile(GFXFontTextureProfile,
  36. GFXTextureProfile::DiffuseMap,
  37. GFXTextureProfile::PreserveSize |
  38. GFXTextureProfile::Static |
  39. GFXTextureProfile::KeepBitmap |
  40. GFXTextureProfile::NoMipmap,
  41. GFXTextureProfile::NONE);
  42. template<> void *Resource<GFont>::create(const Torque::Path &path)
  43. {
  44. #ifdef TORQUE_DEBUG_RES_MANAGER
  45. Con::printf( "Resource<GFont>::create - [%s]", path.getFullPath().c_str() );
  46. #endif
  47. return GFont::load( path );
  48. }
  49. template<> ResourceBase::Signature Resource<GFont>::signature()
  50. {
  51. return MakeFourCC('f','o','n','t');
  52. }
  53. /// Used for repacking in GFont::importStrip.
  54. struct GlyphMap
  55. {
  56. U32 charId;
  57. GBitmap *bitmap;
  58. };
  59. static S32 QSORT_CALLBACK GlyphMapCompare(const void *a, const void *b)
  60. {
  61. S32 ha = ((GlyphMap *) a)->bitmap->getHeight();
  62. S32 hb = ((GlyphMap *) b)->bitmap->getHeight();
  63. return hb - ha;
  64. }
  65. const U32 GFont::csm_fileVersion = 3;
  66. String GFont::getFontCacheFilename(const String &faceName, U32 size)
  67. {
  68. return String::ToString("%s/%s %d (%s).uft",
  69. Con::getVariable("$GUI::fontCacheDirectory"), faceName.c_str(), size, getCharSetName(0));
  70. }
  71. GFont* GFont::load( const Torque::Path& path )
  72. {
  73. FileStream stream;
  74. stream.open( path.getFullPath(), Torque::FS::File::Read );
  75. if ( stream.getStatus() != Stream::Ok )
  76. return NULL;
  77. GFont *ret = new GFont;
  78. ret->mGFTFile = path;
  79. if(!ret->read(stream))
  80. {
  81. Con::errorf( "GFont::load - error reading '%s'", path.getFullPath().c_str() );
  82. SAFE_DELETE(ret);
  83. }
  84. else
  85. {
  86. PlatformFont *platFont = createPlatformFont(ret->getFontFaceName(), ret->getFontSize(), ret->getFontCharSet());
  87. if ( platFont == NULL )
  88. {
  89. Con::errorf( "GFont::load - error creating platform font for '%s'", path.getFullPath().c_str() );
  90. SAFE_DELETE(ret);
  91. }
  92. else
  93. ret->setPlatformFont(platFont);
  94. }
  95. return ret;
  96. }
  97. Resource<GFont> GFont::create(const String &faceName, U32 size, const char *cacheDirectory, U32 charset /* = TGE_ANSI_CHARSET */)
  98. {
  99. if( !cacheDirectory )
  100. cacheDirectory = Con::getVariable( "$GUI::fontCacheDirectory" );
  101. const Torque::Path path( String::ToString("%s/%s %d (%s).uft",
  102. cacheDirectory, faceName.c_str(), size, getCharSetName(charset)) );
  103. Resource<GFont> ret;
  104. // If the file already exists attempt to load it
  105. if (Platform::isFile(path.getFullPath().c_str()))
  106. {
  107. ret = ResourceManager::get().load(path);
  108. if (ret != NULL)
  109. {
  110. ret->mGFTFile = path;
  111. return ret;
  112. }
  113. }
  114. // Otherwise attempt to have the platform generate a new font
  115. PlatformFont *platFont = createPlatformFont(faceName, size, charset);
  116. if (platFont == NULL)
  117. {
  118. String fontName;
  119. #ifdef _XBOX
  120. //AssertFatal( false, "Font creation is not supported on the Xbox platform. Create the font files (*.uft) using the Windows/MacOS build of the project." );
  121. if(!faceName.equal("arial", String::NoCase) || size != 14)
  122. {
  123. return create("Arial", 14, cacheDirectory, charset);
  124. }
  125. return ret;
  126. #endif
  127. // Couldn't load the requested font. This probably will be common
  128. // since many unix boxes don't have arial or lucida console installed.
  129. // Attempt to map the font name into a font we're pretty sure exist
  130. // Lucida Console is a common code & console font on windows, and
  131. // Monaco is the recommended code & console font on mac.
  132. if (faceName.equal("arial", String::NoCase))
  133. fontName = "Helvetica";
  134. else if (faceName.equal("lucida console", String::NoCase))
  135. fontName = "Monaco";
  136. else if (faceName.equal("monaco", String::NoCase))
  137. fontName = "Courier";
  138. else
  139. return ret;
  140. return create(fontName, size, cacheDirectory, charset);
  141. }
  142. // Create the actual GFont and set some initial properties
  143. GFont *font = new GFont;
  144. font->mPlatformFont = platFont;
  145. font->mGFTFile = path;
  146. font->mFaceName = faceName;
  147. font->mSize = size;
  148. font->mCharSet = charset;
  149. font->mHeight = platFont->getFontHeight();
  150. font->mBaseline = platFont->getFontBaseLine();
  151. font->mAscent = platFont->getFontBaseLine();
  152. font->mDescent = platFont->getFontHeight() - platFont->getFontBaseLine();
  153. // Flag it to save when we exit
  154. font->mNeedSave = true;
  155. // Load the newly created font into the ResourceManager
  156. ret.setResource(ResourceManager::get().load(path), font);
  157. return ret;
  158. }
  159. //-------------------------------------------------------------------------
  160. GFont::GFont()
  161. {
  162. VECTOR_SET_ASSOCIATION(mCharInfoList);
  163. VECTOR_SET_ASSOCIATION(mTextureSheets);
  164. std::fill_n(mRemapTable, Font_Table_MAX,-1);
  165. mCurX = mCurY = mCurSheet = -1;
  166. mPlatformFont = NULL;
  167. mSize = 0;
  168. mCharSet = 0;
  169. mHeight = 0;
  170. mBaseline = 0;
  171. mAscent = 0;
  172. mDescent = 0;
  173. mNeedSave = false;
  174. mMutex = Mutex::createMutex();
  175. }
  176. GFont::~GFont()
  177. {
  178. if(mNeedSave)
  179. {
  180. AssertFatal( mGFTFile.getFullPath().isNotEmpty(), "GFont::~GFont - path not set" );
  181. FileStream stream;
  182. stream.open(mGFTFile, Torque::FS::File::Write);
  183. if(stream.getStatus() == Stream::Ok)
  184. write(stream);
  185. stream.close();
  186. }
  187. S32 i;
  188. for(i = 0;i < mCharInfoList.size();i++)
  189. {
  190. SAFE_DELETE_ARRAY(mCharInfoList[i].bitmapData);
  191. }
  192. for(i=0; i<mTextureSheets.size(); i++)
  193. mTextureSheets[i] = NULL;
  194. SAFE_DELETE(mPlatformFont);
  195. Mutex::destroyMutex(mMutex);
  196. }
  197. void GFont::dumpInfo() const
  198. {
  199. // Number and extent of mapped characters?
  200. U32 mapCount = 0, mapBegin=0xFFFF, mapEnd=0;
  201. for(U32 i=0; i<0x10000; i++)
  202. {
  203. if(mRemapTable[i] != -1)
  204. {
  205. mapCount++;
  206. if(i<mapBegin) mapBegin = i;
  207. if(i>mapEnd) mapEnd = i;
  208. }
  209. }
  210. // Let's write out all the info we can on this font.
  211. Con::printf(" '%s' %dpt", mFaceName.c_str(), mSize);
  212. Con::printf(" - %d texture sheets, %d mapped characters.", mTextureSheets.size(), mapCount);
  213. if(mapCount)
  214. Con::printf(" - Codepoints range from 0x%x to 0x%x.", mapBegin, mapEnd);
  215. else
  216. Con::printf(" - No mapped codepoints.");
  217. Con::printf(" - Platform font is %s.", (mPlatformFont ? "present" : "not present") );
  218. }
  219. //-----------------------------------------------------------------------------
  220. bool GFont::loadCharInfo(const UTF16 ch)
  221. {
  222. PROFILE_SCOPE(GFont_loadCharInfo);
  223. if(mRemapTable[ch] != -1)
  224. return true; // Not really an error
  225. if(mPlatformFont && mPlatformFont->isValidChar(ch))
  226. {
  227. Mutex::lockMutex(mMutex); // the CharInfo returned by mPlatformFont is static data, must protect from changes.
  228. PlatformFont::CharInfo &ci = mPlatformFont->getCharInfo(ch);
  229. if(ci.bitmapData)
  230. addBitmap(ci);
  231. mCharInfoList.push_back(ci);
  232. mRemapTable[ch] = mCharInfoList.size() - 1;
  233. mNeedSave = true;
  234. Mutex::unlockMutex(mMutex);
  235. return true;
  236. }
  237. return false;
  238. }
  239. void GFont::addBitmap(PlatformFont::CharInfo &charInfo)
  240. {
  241. U32 nextCurX = U32(mCurX + charInfo.width ); /*7) & ~0x3;*/
  242. U32 nextCurY = U32(mCurY + mPlatformFont->getFontHeight()); // + 7) & ~0x3;
  243. // These are here for postmortem debugging.
  244. bool routeA = false, routeB = false;
  245. if(mCurSheet == -1 || nextCurY >= TextureSheetSize)
  246. {
  247. routeA = true;
  248. addSheet();
  249. // Recalc our nexts.
  250. nextCurX = U32(mCurX + charInfo.width); // + 7) & ~0x3;
  251. nextCurY = U32(mCurY + mPlatformFont->getFontHeight()); // + 7) & ~0x3;
  252. }
  253. if( nextCurX >= TextureSheetSize)
  254. {
  255. routeB = true;
  256. mCurX = 0;
  257. mCurY = nextCurY;
  258. // Recalc our nexts.
  259. nextCurX = U32(mCurX + charInfo.width); // + 7) & ~0x3;
  260. nextCurY = U32(mCurY + mPlatformFont->getFontHeight()); // + 7) & ~0x3;
  261. }
  262. // Check the Y once more - sometimes we advance to a new row and run off
  263. // the end.
  264. if(nextCurY >= TextureSheetSize)
  265. {
  266. routeA = true;
  267. addSheet();
  268. // Recalc our nexts.
  269. nextCurX = U32(mCurX + charInfo.width); // + 7) & ~0x3;
  270. nextCurY = U32(mCurY + mPlatformFont->getFontHeight()); // + 7) & ~0x3;
  271. }
  272. charInfo.bitmapIndex = mCurSheet;
  273. charInfo.xOffset = mCurX;
  274. charInfo.yOffset = mCurY;
  275. mCurX = nextCurX;
  276. S32 x, y;
  277. GBitmap *bmp = mTextureSheets[mCurSheet].getBitmap();
  278. AssertFatal(bmp->getFormat() == GFXFormatA8, "GFont::addBitmap - cannot added characters to non-greyscale textures!");
  279. for(y = 0;y < charInfo.height;y++)
  280. for(x = 0;x < charInfo.width;x++)
  281. *bmp->getAddress(x + charInfo.xOffset, y + charInfo.yOffset) = charInfo.bitmapData[y * charInfo.width + x];
  282. mTextureSheets[mCurSheet].refresh();
  283. }
  284. void GFont::addSheet()
  285. {
  286. GBitmap *bitmap = new GBitmap(TextureSheetSize, TextureSheetSize, false, GFXFormatA8 );
  287. // Set everything to transparent.
  288. U8 *bits = bitmap->getWritableBits();
  289. dMemset(bits, 0, sizeof(U8) *TextureSheetSize*TextureSheetSize);
  290. GFXTexHandle handle = GFXTexHandle( bitmap, &GFXFontTextureProfile, true, avar("%s() - (line %d)", __FUNCTION__, __LINE__) );
  291. mTextureSheets.increment();
  292. mTextureSheets.last() = handle;
  293. mCurX = 0;
  294. mCurY = 0;
  295. mCurSheet = mTextureSheets.size() - 1;
  296. }
  297. //-----------------------------------------------------------------------------
  298. const PlatformFont::CharInfo &GFont::getCharInfo(const UTF16 in_charIndex)
  299. {
  300. PROFILE_SCOPE(GFont_getCharInfo);
  301. AssertFatal(in_charIndex, "GFont::getCharInfo - can't get info for char 0!");
  302. if(mRemapTable[in_charIndex] == -1)
  303. loadCharInfo(in_charIndex);
  304. AssertFatal(mRemapTable[in_charIndex] != -1, "No remap info for this character");
  305. return mCharInfoList[mRemapTable[in_charIndex]];
  306. }
  307. const PlatformFont::CharInfo &GFont::getDefaultCharInfo()
  308. {
  309. static PlatformFont::CharInfo c;
  310. // c is initialized by the CharInfo default constructor.
  311. return c;
  312. }
  313. //-----------------------------------------------------------------------------
  314. U32 GFont::getStrWidth(const UTF8* in_pString)
  315. {
  316. AssertFatal(in_pString != NULL, "GFont::getStrWidth: String is NULL, height is undefined");
  317. // If we ain't running debug...
  318. if (in_pString == NULL || *in_pString == '\0')
  319. return 0;
  320. return getStrNWidth(in_pString, dStrlen(in_pString));
  321. }
  322. U32 GFont::getStrWidthPrecise(const UTF8* in_pString)
  323. {
  324. AssertFatal(in_pString != NULL, "GFont::getStrWidth: String is NULL, height is undefined");
  325. // If we ain't running debug...
  326. if (in_pString == NULL)
  327. return 0;
  328. return getStrNWidthPrecise(in_pString, dStrlen(in_pString));
  329. }
  330. //-----------------------------------------------------------------------------
  331. U32 GFont::getStrNWidth(const UTF8 *str, U32 n)
  332. {
  333. // UTF8 conversion is expensive. Avoid converting in a tight loop.
  334. FrameTemp<UTF16> str16(n + 1);
  335. convertUTF8toUTF16N(str, str16, n + 1);
  336. return getStrNWidth(str16, dStrlen(str16));
  337. }
  338. U32 GFont::getStrNWidth(const UTF16 *str, U32 n)
  339. {
  340. AssertFatal(str != NULL, "GFont::getStrNWidth: String is NULL");
  341. if (str == NULL || str[0] == '\0' || n == 0)
  342. return 0;
  343. U32 totWidth = 0;
  344. UTF16 curChar;
  345. U32 charCount;
  346. for(charCount = 0; charCount < n; charCount++)
  347. {
  348. curChar = str[charCount];
  349. if(curChar == '\0')
  350. break;
  351. if(isValidChar(curChar))
  352. {
  353. const PlatformFont::CharInfo& rChar = getCharInfo(curChar);
  354. totWidth += rChar.xIncrement;
  355. }
  356. else if (curChar == dT('\t'))
  357. {
  358. const PlatformFont::CharInfo& rChar = getCharInfo(dT(' '));
  359. totWidth += rChar.xIncrement * TabWidthInSpaces;
  360. }
  361. }
  362. return(totWidth);
  363. }
  364. U32 GFont::getStrNWidthPrecise(const UTF8 *str, U32 n)
  365. {
  366. FrameTemp<UTF16> str16(n + 1);
  367. convertUTF8toUTF16N(str, str16, n + 1);
  368. return getStrNWidthPrecise(str16, dStrlen(str16));
  369. }
  370. U32 GFont::getStrNWidthPrecise(const UTF16 *str, U32 n)
  371. {
  372. AssertFatal(str != NULL, "GFont::getStrNWidth: String is NULL");
  373. if (str == NULL || str[0] == '\0' || n == 0)
  374. return(0);
  375. U32 totWidth = 0;
  376. UTF16 curChar;
  377. U32 charCount = 0;
  378. for(charCount = 0; charCount < n; charCount++)
  379. {
  380. curChar = str[charCount];
  381. if(curChar == '\0')
  382. break;
  383. if(isValidChar(curChar))
  384. {
  385. const PlatformFont::CharInfo& rChar = getCharInfo(curChar);
  386. totWidth += rChar.xIncrement;
  387. }
  388. else if (curChar == dT('\t'))
  389. {
  390. const PlatformFont::CharInfo& rChar = getCharInfo(dT(' '));
  391. totWidth += rChar.xIncrement * TabWidthInSpaces;
  392. }
  393. }
  394. UTF16 endChar = str[getMin(charCount,n-1)];
  395. if (isValidChar(endChar))
  396. {
  397. const PlatformFont::CharInfo& rChar = getCharInfo(endChar);
  398. if (rChar.width != rChar.xIncrement)
  399. totWidth += (rChar.width - rChar.xIncrement);
  400. }
  401. return(totWidth);
  402. }
  403. U32 GFont::getBreakPos(const UTF16 *str16, U32 slen, U32 width, bool breakOnWhitespace)
  404. {
  405. // Some early out cases.
  406. if(slen==0)
  407. return 0;
  408. U32 ret = 0;
  409. U32 lastws = 0;
  410. UTF16 c;
  411. U32 charCount = 0;
  412. for( charCount=0; charCount < slen; charCount++)
  413. {
  414. c = str16[charCount];
  415. if(c == '\0')
  416. break;
  417. if(c == dT('\t'))
  418. c = dT(' ');
  419. if(!isValidChar(c))
  420. {
  421. ret++;
  422. continue;
  423. }
  424. if(c == dT(' '))
  425. lastws = ret+1;
  426. const PlatformFont::CharInfo& rChar = getCharInfo(c);
  427. if(rChar.width > width || rChar.xIncrement > width)
  428. {
  429. if(lastws && breakOnWhitespace)
  430. return lastws;
  431. return ret;
  432. }
  433. width -= rChar.xIncrement;
  434. ret++;
  435. }
  436. return ret;
  437. }
  438. void GFont::wrapString(const UTF8 *txt, U32 lineWidth, Vector<U32> &startLineOffset, Vector<U32> &lineLen)
  439. {
  440. // TODO: Is this error still true?
  441. //Con::errorf("GFont::wrapString(): Not yet converted to be UTF-8 safe");
  442. startLineOffset.clear();
  443. lineLen.clear();
  444. if (!txt || !txt[0] || lineWidth < getCharWidth('W')) //make sure the line width is greater then a single character
  445. return;
  446. U32 len = dStrlen(txt);
  447. U32 startLine;
  448. for (U32 i = 0; i < len;)
  449. {
  450. U32 wide = 0;
  451. startLine = i;
  452. startLineOffset.push_back(startLine);
  453. // loop until the string is too large
  454. bool needsNewLine = false;
  455. U32 lineStrWidth = 0;
  456. for (; i < len; i++)
  457. {
  458. if( txt[ i ] == '\n' )
  459. {
  460. needsNewLine = true;
  461. break;
  462. }
  463. else if(isValidChar(txt[i]))
  464. {
  465. lineStrWidth += getCharInfo(txt[i]).xIncrement;
  466. if(txt[i] < 0) // symbols which code > 127
  467. {
  468. wide++; i++;
  469. }
  470. if( lineStrWidth > lineWidth )
  471. {
  472. needsNewLine = true;
  473. break;
  474. }
  475. }
  476. }
  477. if (!needsNewLine)
  478. {
  479. // we are done!
  480. lineLen.push_back(i - startLine - wide);
  481. return;
  482. }
  483. S32 j;
  484. // Did we hit a hardwrap (newline character) in the string.
  485. bool hardwrap = ( txt[i] == '\n' );
  486. if ( hardwrap )
  487. {
  488. j = i;
  489. }
  490. // determine where to put the newline
  491. // we need to backtrack until we find a space character
  492. // we don't do this for hardwrap(s)
  493. else
  494. {
  495. for (j = i - 1; j >= startLine; j--)
  496. {
  497. if ( dIsspace(txt[j]) || txt[i] == '\n' )
  498. break;
  499. }
  500. if (j < startLine)
  501. {
  502. // the line consists of a single word!
  503. // So, just break up the word
  504. j = i - 1;
  505. }
  506. }
  507. lineLen.push_back(j - startLine - wide);
  508. i = j;
  509. // Now we need to increment through any space characters at the
  510. // beginning of the next line.
  511. // We don't skip spaces after a hardwrap because they were obviously intended.
  512. for (i++; i < len; i++)
  513. {
  514. if ( txt[i] == '\n' )
  515. continue;
  516. if ( dIsspace( txt[i] ) && !hardwrap )
  517. continue;
  518. break;
  519. }
  520. }
  521. }
  522. //-----------------------------------------------------------------------------
  523. bool GFont::read(Stream& io_rStream)
  524. {
  525. // Handle versioning
  526. U32 version;
  527. io_rStream.read(&version);
  528. if(version != csm_fileVersion)
  529. return false;
  530. char buf[256];
  531. io_rStream.readString(buf);
  532. mFaceName = buf;
  533. io_rStream.read(&mSize);
  534. io_rStream.read(&mCharSet);
  535. io_rStream.read(&mHeight);
  536. io_rStream.read(&mBaseline);
  537. io_rStream.read(&mAscent);
  538. io_rStream.read(&mDescent);
  539. U32 size = 0;
  540. io_rStream.read(&size);
  541. mCharInfoList.setSize(size);
  542. U32 i;
  543. for(i = 0; i < size; i++)
  544. {
  545. PlatformFont::CharInfo *ci = &mCharInfoList[i];
  546. io_rStream.read(&ci->bitmapIndex);
  547. io_rStream.read(&ci->xOffset);
  548. io_rStream.read(&ci->yOffset);
  549. io_rStream.read(&ci->width);
  550. io_rStream.read(&ci->height);
  551. io_rStream.read(&ci->xOrigin);
  552. io_rStream.read(&ci->yOrigin);
  553. io_rStream.read(&ci->xIncrement);
  554. ci->bitmapData = NULL;
  555. }
  556. U32 numSheets = 0;
  557. io_rStream.read(&numSheets);
  558. for(i = 0; i < numSheets; i++)
  559. {
  560. GBitmap *bmp = new GBitmap;
  561. if(!bmp->readBitmap("png", io_rStream))
  562. {
  563. delete bmp;
  564. return false;
  565. }
  566. GFXTexHandle handle = GFXTexHandle(bmp, &GFXFontTextureProfile, true, avar("%s() - Read Font Sheet for %s %d (line %d)", __FUNCTION__, mFaceName.c_str(), mSize, __LINE__));
  567. //handle.setFilterNearest();
  568. mTextureSheets.push_back(handle);
  569. }
  570. // Read last position info
  571. io_rStream.read(&mCurX);
  572. io_rStream.read(&mCurY);
  573. io_rStream.read(&mCurSheet);
  574. // Read the remap table.
  575. U32 minGlyph, maxGlyph;
  576. io_rStream.read(&minGlyph);
  577. io_rStream.read(&maxGlyph);
  578. if(maxGlyph >= minGlyph)
  579. {
  580. // Length of buffer..
  581. U32 buffLen;
  582. io_rStream.read(&buffLen);
  583. // Read the buffer.
  584. FrameTemp<S32> inBuff(buffLen);
  585. io_rStream.read(buffLen, inBuff);
  586. // Decompress.
  587. uLongf destLen = (maxGlyph-minGlyph+1)*sizeof(S32);
  588. uncompress((Bytef*)&mRemapTable[minGlyph], &destLen, (Bytef*)(S32*)inBuff, buffLen);
  589. AssertISV(destLen == (maxGlyph-minGlyph+1)*sizeof(S32), "GFont::read - invalid remap table data!");
  590. // Make sure we've got the right endianness.
  591. for(i = minGlyph; i <= maxGlyph; i++)
  592. mRemapTable[i] = convertBEndianToHost(mRemapTable[i]);
  593. }
  594. return (io_rStream.getStatus() == Stream::Ok);
  595. }
  596. bool GFont::write(Stream& stream)
  597. {
  598. // Handle versioning
  599. stream.write(csm_fileVersion);
  600. // Write font info
  601. stream.write(mFaceName);
  602. stream.write(mSize);
  603. stream.write(mCharSet);
  604. stream.write(mHeight);
  605. stream.write(mBaseline);
  606. stream.write(mAscent);
  607. stream.write(mDescent);
  608. // Write char info list
  609. stream.write(U32(mCharInfoList.size()));
  610. U32 i;
  611. for(i = 0; i < mCharInfoList.size(); i++)
  612. {
  613. const PlatformFont::CharInfo *ci = &mCharInfoList[i];
  614. stream.write(ci->bitmapIndex);
  615. stream.write(ci->xOffset);
  616. stream.write(ci->yOffset);
  617. stream.write(ci->width);
  618. stream.write(ci->height);
  619. stream.write(ci->xOrigin);
  620. stream.write(ci->yOrigin);
  621. stream.write(ci->xIncrement);
  622. }
  623. stream.write(mTextureSheets.size());
  624. for(i = 0; i < mTextureSheets.size(); i++)
  625. mTextureSheets[i].getBitmap()->writeBitmap("png", stream);
  626. stream.write(mCurX);
  627. stream.write(mCurY);
  628. stream.write(mCurSheet);
  629. // Get the min/max we have values for, and only write that range out.
  630. S32 minGlyph = S32_MAX, maxGlyph = 0;
  631. for(i = 0; i < 65536; i++)
  632. {
  633. if(mRemapTable[i] != -1)
  634. {
  635. if(i>maxGlyph) maxGlyph = i;
  636. if(i<minGlyph) minGlyph = i;
  637. }
  638. }
  639. stream.write(minGlyph);
  640. stream.write(maxGlyph);
  641. // Skip it if we don't have any glyphs to do...
  642. if(maxGlyph >= minGlyph)
  643. {
  644. // Put everything big endian, to be consistent. Do this inplace.
  645. for(i = minGlyph; i <= maxGlyph; i++)
  646. mRemapTable[i] = convertHostToBEndian(mRemapTable[i]);
  647. {
  648. // Compress.
  649. const U32 buffSize = 128 * 1024;
  650. FrameTemp<S32> outBuff(buffSize);
  651. uLongf destLen = buffSize * sizeof(S32);
  652. compress2((Bytef*)(S32*)outBuff, &destLen, (Bytef*)(S32*)&mRemapTable[minGlyph], (maxGlyph-minGlyph+1)*sizeof(S32), 9);
  653. // Write out.
  654. stream.write((U32)destLen);
  655. stream.write(destLen, outBuff);
  656. }
  657. // Put us back to normal.
  658. for(i = minGlyph; i <= maxGlyph; i++)
  659. mRemapTable[i] = convertBEndianToHost(mRemapTable[i]);
  660. }
  661. return (stream.getStatus() == Stream::Ok);
  662. }
  663. void GFont::exportStrip(const char *fileName, U32 padding, U32 kerning)
  664. {
  665. // Figure dimensions of our strip by iterating over all the char infos.
  666. U32 totalHeight = 0;
  667. U32 totalWidth = 0;
  668. S32 heightMin=0, heightMax=0;
  669. for(S32 i=0; i<mCharInfoList.size(); i++)
  670. {
  671. totalWidth += mCharInfoList[i].width + kerning + 2*padding;
  672. heightMin = getMin((S32)heightMin, (S32)getBaseline() - (S32)mCharInfoList[i].yOrigin);
  673. heightMax = getMax((S32)heightMax, (S32)getBaseline() - (S32)mCharInfoList[i].yOrigin + (S32)mCharInfoList[i].height);
  674. }
  675. totalHeight = heightMax - heightMin + 2*padding;
  676. // Make the bitmap.
  677. GBitmap gb(totalWidth, totalHeight, false, mTextureSheets[0].getBitmap()->getFormat());
  678. dMemset(gb.getWritableBits(), 0, sizeof(U8) * totalHeight * totalWidth );
  679. // Ok, copy some rects, taking into account padding, kerning, offset.
  680. U32 curWidth = kerning + padding;
  681. for(S32 i=0; i<mCharInfoList.size(); i++)
  682. {
  683. // Skip invalid stuff.
  684. if(mCharInfoList[i].bitmapIndex == -1 || mCharInfoList[i].height == 0 || mCharInfoList[i].width == 0)
  685. continue;
  686. // Copy the rect.
  687. U32 bitmap = mCharInfoList[i].bitmapIndex;
  688. RectI ri(mCharInfoList[i].xOffset, mCharInfoList[i].yOffset, mCharInfoList[i].width, mCharInfoList[i].height );
  689. Point2I outRi(curWidth, padding + getBaseline() - mCharInfoList[i].yOrigin);
  690. gb.copyRect(mTextureSheets[bitmap].getBitmap(), ri, outRi);
  691. // Advance.
  692. curWidth += mCharInfoList[i].width + kerning + 2*padding;
  693. }
  694. // Write the image!
  695. FileStream fs;
  696. fs.open( fileName, Torque::FS::File::Write );
  697. if(fs.getStatus() != Stream::Ok)
  698. {
  699. Con::errorf("GFont::exportStrip - failed to open '%s' for writing.", fileName);
  700. return;
  701. }
  702. // Done!
  703. gb.writeBitmap("png", fs);
  704. }
  705. void GFont::setPlatformFont(PlatformFont *inPlatformFont)
  706. {
  707. AssertFatal( mPlatformFont == NULL, "Trying to set platform font which already exists");
  708. mPlatformFont = inPlatformFont;
  709. }
  710. void GFont::importStrip(const char *fileName, U32 padding, U32 kerning)
  711. {
  712. // Wipe our texture sheets, and reload bitmap data from the specified file.
  713. // Also deal with kerning.
  714. // Also, we may have to load RGBA instead of RGB.
  715. // Wipe our texture sheets.
  716. mCurSheet = mCurX = mCurY = 0;
  717. mTextureSheets.clear();
  718. // Now, load the font strip.
  719. Resource<GBitmap> strip = GBitmap::load(fileName);
  720. if(!strip)
  721. {
  722. Con::errorf("GFont::importStrip - could not load file '%s'!", fileName);
  723. return;
  724. }
  725. // And get parsing and copying - load up all the characters as separate
  726. // GBitmaps, sort, then pack. Not terribly efficient but this is basically
  727. // on offline task anyway.
  728. // Ok, snag some glyphs.
  729. Vector<GlyphMap> glyphList;
  730. glyphList.reserve(mCharInfoList.size());
  731. U32 curWidth = 0;
  732. for(S32 i=0; i<mCharInfoList.size(); i++)
  733. {
  734. // Skip invalid stuff.
  735. if(mCharInfoList[i].bitmapIndex == -1 || mCharInfoList[i].height == 0 || mCharInfoList[i].width == 0)
  736. continue;
  737. // Allocate a new bitmap for this glyph, taking into account kerning and padding.
  738. glyphList.increment();
  739. GlyphMap& lastGlyphMap = glyphList.last();
  740. lastGlyphMap.bitmap = new GBitmap(mCharInfoList[i].width + kerning + 2 * padding, mCharInfoList[i].height + 2 * padding, false, strip->getFormat());
  741. lastGlyphMap.charId = i;
  742. // Copy the rect.
  743. RectI ri(curWidth, getBaseline() - mCharInfoList[i].yOrigin, lastGlyphMap.bitmap->getWidth(), lastGlyphMap.bitmap->getHeight());
  744. Point2I outRi(0,0);
  745. lastGlyphMap.bitmap->copyRect(strip, ri, outRi);
  746. // Update glyph attributes.
  747. mCharInfoList[i].width = lastGlyphMap.bitmap->getWidth();
  748. mCharInfoList[i].height = lastGlyphMap.bitmap->getHeight();
  749. mCharInfoList[i].xOffset -= kerning + padding;
  750. mCharInfoList[i].xIncrement += kerning;
  751. mCharInfoList[i].yOffset -= padding;
  752. // Advance.
  753. curWidth += ri.extent.x;
  754. }
  755. // Ok, we have a big list of glyphmaps now. So let's sort them, then pack them.
  756. dQsort(glyphList.address(), glyphList.size(), sizeof(GlyphMap), GlyphMapCompare);
  757. // They're sorted by height, so now we can do some sort of awesome packing.
  758. Point2I curSheetSize(256, 256);
  759. Vector<U32> sheetSizes;
  760. S32 curY = 0;
  761. S32 curX = 0;
  762. S32 curLnHeight = 0;
  763. S32 maxHeight = 0;
  764. for(U32 i = 0; i < glyphList.size(); i++)
  765. {
  766. PlatformFont::CharInfo *ci = &mCharInfoList[glyphList[i].charId];
  767. if(ci->height > maxHeight)
  768. maxHeight = ci->height;
  769. if(curX + ci->width > curSheetSize.x)
  770. {
  771. curY += curLnHeight;
  772. curX = 0;
  773. curLnHeight = 0;
  774. }
  775. if(curY + ci->height > curSheetSize.y)
  776. {
  777. sheetSizes.push_back(curSheetSize.y);
  778. curX = 0;
  779. curY = 0;
  780. curLnHeight = 0;
  781. }
  782. if(ci->height > curLnHeight)
  783. curLnHeight = ci->height;
  784. ci->bitmapIndex = sheetSizes.size();
  785. ci->xOffset = curX;
  786. ci->yOffset = curY;
  787. curX += ci->width;
  788. }
  789. // Terminate the packing loop calculations.
  790. curY += curLnHeight;
  791. if(curY < 64)
  792. curSheetSize.y = 64;
  793. else if(curY < 128)
  794. curSheetSize.y = 128;
  795. sheetSizes.push_back(curSheetSize.y);
  796. if(getHeight() + padding * 2 > maxHeight)
  797. maxHeight = getHeight() + padding * 2;
  798. // Allocate texture pages.
  799. for(S32 i=0; i<sheetSizes.size(); i++)
  800. {
  801. GBitmap *bitmap = new GBitmap(TextureSheetSize, TextureSheetSize, false, strip->getFormat());
  802. // Set everything to transparent.
  803. U8 *bits = bitmap->getWritableBits();
  804. dMemset(bits, 0, sizeof(U8) *TextureSheetSize*TextureSheetSize * strip->getBytesPerPixel());
  805. GFXTexHandle handle = GFXTexHandle( bitmap, &GFXFontTextureProfile, true, avar("%s() - Font Sheet for %s (line %d)", __FUNCTION__, fileName, __LINE__) );
  806. mTextureSheets.increment();
  807. mTextureSheets.last() = handle;
  808. }
  809. // Alright, we're ready to copy bits!
  810. for(S32 i=0; i<glyphList.size(); i++)
  811. {
  812. // Copy each glyph into the appropriate place.
  813. PlatformFont::CharInfo *ci = &mCharInfoList[glyphList[i].charId];
  814. U32 bi = ci->bitmapIndex;
  815. mTextureSheets[bi]->getBitmap()->copyRect(glyphList[i].bitmap, RectI(0,0, glyphList[i].bitmap->getWidth(),glyphList[i].bitmap->getHeight()), Point2I(ci->xOffset, ci->yOffset));
  816. }
  817. // Ok, all done! Just refresh some textures and we're set.
  818. for(S32 i=0; i<sheetSizes.size(); i++)
  819. mTextureSheets[i].refresh();
  820. }
  821. DefineEngineFunction( populateFontCacheString, void, ( const char *faceName, S32 fontSize, const char *string ),,
  822. "Populate the font cache for the specified font with characters from the specified string.\n"
  823. "@param faceName The name of the font face.\n"
  824. "@param fontSize The size of the font in pixels.\n"
  825. "@param string The string to populate.\n"
  826. "@ingroup Font\n" )
  827. {
  828. Resource<GFont> f = GFont::create(faceName, fontSize, Con::getVariable("$GUI::fontCacheDirectory"));
  829. if(f == NULL)
  830. {
  831. Con::errorf("populateFontCacheString - could not load font '%s %d'", faceName, fontSize);
  832. return;
  833. }
  834. if(!f->hasPlatformFont())
  835. {
  836. Con::errorf("populateFontCacheString - font '%s %d' has no platform font. Cannot generate more characters.", faceName, fontSize);
  837. return;
  838. }
  839. // This has the side effect of generating character info, including the bitmaps.
  840. f->getStrWidthPrecise( string );
  841. }
  842. DefineEngineFunction( populateFontCacheRange, void, ( const char *faceName, S32 fontSize, U32 rangeStart, U32 rangeEnd ),,
  843. "Populate the font cache for the specified font with Unicode code points in the specified range.\n"
  844. "@param faceName The name of the font face.\n"
  845. "@param fontSize The size of the font in pixels.\n"
  846. "@param rangeStart The start Unicode point.\n"
  847. "@param rangeEnd The end Unicode point.\n"
  848. "@note We only support BMP-0, so code points range from 0 to 65535.\n"
  849. "@ingroup Font\n" )
  850. {
  851. Resource<GFont> f = GFont::create(faceName, fontSize, Con::getVariable("$GUI::fontCacheDirectory"));
  852. if(f == NULL)
  853. {
  854. Con::errorf("populateFontCacheRange - could not load font '%s %d'", faceName, fontSize);
  855. return;
  856. }
  857. if(rangeStart > rangeEnd)
  858. {
  859. Con::errorf("populateFontCacheRange - range start is after end");
  860. return;
  861. }
  862. if(!f->hasPlatformFont())
  863. {
  864. Con::errorf("populateFontCacheRange - font '%s %d' has no platform font Cannot generate more characters.", faceName, fontSize);
  865. return;
  866. }
  867. // This has the side effect of generating character info, including the bitmaps.
  868. for(U32 i=rangeStart; i<rangeEnd; i++)
  869. {
  870. if(f->isValidChar(i))
  871. f->getCharWidth(i);
  872. else
  873. Con::warnf("populateFontCacheRange - skipping invalid char 0x%x", i);
  874. }
  875. // All done!
  876. }
  877. DefineEngineFunction( dumpFontCacheStatus, void, (),,
  878. "Dumps to the console a full description of all cached fonts, along with "
  879. "info on the codepoints each contains.\n"
  880. "@ingroup Font\n" )
  881. {
  882. Resource<GFont> theFont = ResourceManager::get().startResourceList( Resource<GFont>::signature() );
  883. Con::printf("--------------------------------------------------------------------------");
  884. Con::printf(" Font Cache Usage Report");
  885. while( theFont != NULL )
  886. {
  887. theFont->dumpInfo();
  888. theFont = ResourceManager::get().nextResource();
  889. }
  890. }
  891. DefineEngineFunction( writeFontCache, void, (),,
  892. "Force all cached fonts to serialize themselves to the cache.\n"
  893. "@ingroup Font\n" )
  894. {
  895. Resource<GFont> theFont = ResourceManager::get().startResourceList( Resource<GFont>::signature() );
  896. Con::printf("--------------------------------------------------------------------------");
  897. Con::printf(" Writing font cache to disk");
  898. while( theFont != NULL )
  899. {
  900. const String fileName( theFont.getPath() );
  901. FileStream stream;
  902. stream.open(fileName, Torque::FS::File::Write);
  903. if(stream.getStatus() == Stream::Ok)
  904. {
  905. Con::printf(" o Writing '%s' to disk...", fileName.c_str());
  906. theFont->write(stream);
  907. }
  908. else
  909. {
  910. Con::errorf(" o Could not open '%s' for write", fileName.c_str());
  911. }
  912. theFont = ResourceManager::get().nextResource();
  913. }
  914. }
  915. DefineEngineFunction( populateAllFontCacheString, void, ( const char *string ),,
  916. "Populate the font cache for all fonts with characters from the specified string.\n"
  917. "@ingroup Font\n" )
  918. {
  919. Resource<GFont> theFont = ResourceManager::get().startResourceList( Resource<GFont>::signature() );
  920. Con::printf("Populating font cache with string '%s'", string);
  921. while( theFont != NULL )
  922. {
  923. if(theFont->hasPlatformFont())
  924. {
  925. // This has the side effect of generating character info, including the bitmaps.
  926. theFont->getStrWidthPrecise( string );
  927. }
  928. else
  929. {
  930. const String fileName( theFont.getPath() );
  931. Con::errorf("populateAllFontCacheString - font '%s' has no platform font. Cannot generate more characters.", fileName.c_str());
  932. }
  933. theFont = ResourceManager::get().nextResource();
  934. }
  935. }
  936. DefineEngineFunction( populateAllFontCacheRange, void, ( U32 rangeStart, U32 rangeEnd ),,
  937. "Populate the font cache for all fonts with Unicode code points in the specified range.\n"
  938. "@param rangeStart The start Unicode point.\n"
  939. "@param rangeEnd The end Unicode point.\n"
  940. "@note We only support BMP-0, so code points range from 0 to 65535.\n"
  941. "@ingroup Font\n" )
  942. {
  943. if(rangeStart > rangeEnd)
  944. {
  945. Con::errorf("populateAllFontCacheRange - range start is after end!");
  946. return;
  947. }
  948. Resource<GFont> theFont = ResourceManager::get().startResourceList( Resource<GFont>::signature() );
  949. Con::printf("Populating font cache with range 0x%x to 0x%x", rangeStart, rangeEnd);
  950. while( theFont != NULL )
  951. {
  952. const String fileName( theFont.getPath() );
  953. if(theFont->hasPlatformFont())
  954. {
  955. // This has the side effect of generating character info, including the bitmaps.
  956. Con::printf(" o Populating font '%s'", fileName.c_str());
  957. for(U32 i=rangeStart; i<rangeEnd; i++)
  958. {
  959. if(theFont->isValidChar(i))
  960. theFont->getCharWidth(i);
  961. else
  962. Con::warnf("populateAllFontCacheRange - skipping invalid char 0x%x", i);
  963. }
  964. }
  965. else
  966. {
  967. Con::errorf("populateAllFontCacheRange - font '%s' has no platform font. Cannot generate more characters.", fileName.c_str());
  968. }
  969. theFont = ResourceManager::get().nextResource();
  970. }
  971. }
  972. DefineEngineFunction( exportCachedFont, void,
  973. ( const char *faceName, S32 fontSize, const char *fileName, S32 padding, S32 kerning ),,
  974. "Export specified font to the specified filename as a PNG. The "
  975. "image can then be processed in Photoshop or another tool and "
  976. "reimported using importCachedFont. Characters in the font are "
  977. "exported as one long strip.\n"
  978. "@param faceName The name of the font face.\n"
  979. "@param fontSize The size of the font in pixels.\n"
  980. "@param fileName The file name and path for the output PNG.\n"
  981. "@param padding The padding between characters.\n"
  982. "@param kerning The kerning between characters.\n"
  983. "@ingroup Font\n" )
  984. {
  985. // Tell the font to export itself.
  986. Resource<GFont> f = GFont::create(faceName, fontSize, Con::getVariable("$GUI::fontCacheDirectory"));
  987. if(f == NULL)
  988. {
  989. Con::errorf("exportCachedFont - could not load font '%s %d'", faceName, fontSize);
  990. return;
  991. }
  992. f->exportStrip(fileName, padding, kerning);
  993. }
  994. DefineEngineFunction( importCachedFont, void,
  995. ( const char *faceName, S32 fontSize, const char *fileName, S32 padding, S32 kerning ),,
  996. "Import an image strip from exportCachedFont. Call with the "
  997. "same parameters you called exportCachedFont.\n"
  998. "@param faceName The name of the font face.\n"
  999. "@param fontSize The size of the font in pixels.\n"
  1000. "@param fileName The file name and path for the input PNG.\n"
  1001. "@param padding The padding between characters.\n"
  1002. "@param kerning The kerning between characters.\n"
  1003. "@ingroup Font\n" )
  1004. {
  1005. // Tell the font to import itself.
  1006. Resource<GFont> f = GFont::create(faceName, fontSize, Con::getVariable("$GUI::fontCacheDirectory"));
  1007. if(f == NULL)
  1008. {
  1009. Con::errorf("importCachedFont - could not load font '%s %d'", faceName, fontSize);
  1010. return;
  1011. }
  1012. f->importStrip(fileName, padding, kerning);
  1013. }
  1014. DefineEngineFunction( duplicateCachedFont, void,
  1015. ( const char *oldFontName, S32 oldFontSize, const char *newFontName ),,
  1016. "Copy the specified old font to a new name. The new copy will not have a "
  1017. "platform font backing it, and so will never have characters added to it. "
  1018. "But this is useful for making copies of fonts to add postprocessing effects "
  1019. "to via exportCachedFont.\n"
  1020. "@param oldFontName The name of the font face to copy.\n"
  1021. "@param oldFontSize The size of the font to copy.\n"
  1022. "@param newFontName The name of the new font face.\n"
  1023. "@ingroup Font\n" )
  1024. {
  1025. String newFontFile = GFont::getFontCacheFilename(newFontName, oldFontSize);
  1026. // Load the original font.
  1027. Resource<GFont> font = GFont::create(oldFontName, oldFontSize, Con::getVariable("$GUI::fontCacheDirectory"));
  1028. // Deal with inexplicably missing or failed to load fonts.
  1029. if (font == NULL)
  1030. {
  1031. Con::errorf(" o Couldn't find font : %s", oldFontName);
  1032. return;
  1033. }
  1034. // Ok, dump info!
  1035. FileStream stream;
  1036. stream.open( newFontFile, Torque::FS::File::Write );
  1037. if(stream.getStatus() == Stream::Ok)
  1038. {
  1039. Con::printf( " o Writing duplicate font '%s' to disk...", newFontFile.c_str() );
  1040. font->write(stream);
  1041. stream.close();
  1042. }
  1043. else
  1044. {
  1045. Con::errorf( " o Could not open '%s' for write", newFontFile.c_str() );
  1046. }
  1047. }