ImagePacker.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  1. /*
  2. ** Command & Conquer Generals Zero Hour(tm)
  3. ** Copyright 2025 Electronic Arts Inc.
  4. **
  5. ** This program is free software: you can redistribute it and/or modify
  6. ** it under the terms of the GNU General Public License as published by
  7. ** the Free Software Foundation, either version 3 of the License, or
  8. ** (at your option) any later version.
  9. **
  10. ** This program is distributed in the hope that it will be useful,
  11. ** but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ** GNU General Public License for more details.
  14. **
  15. ** You should have received a copy of the GNU General Public License
  16. ** along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. // FILE: ImagePacker.cpp //////////////////////////////////////////////////////
  19. //-----------------------------------------------------------------------------
  20. //
  21. // Westwood Studios Pacific.
  22. //
  23. // Confidential Information
  24. // Copyright (C) 2001 - All Rights Reserved
  25. //
  26. //-----------------------------------------------------------------------------
  27. //
  28. // Project: ImagePacker
  29. //
  30. // File name: ImagePacker.cpp
  31. //
  32. // Created: Colin Day, August 2001
  33. //
  34. // Desc: Entry point for the image packer. This program takes
  35. // separate image files and combines them into a single
  36. // image as close as possible so that we can conserve texture
  37. // memory
  38. //
  39. //-----------------------------------------------------------------------------
  40. ///////////////////////////////////////////////////////////////////////////////
  41. // SYSTEM INCLUDES ////////////////////////////////////////////////////////////
  42. #include <stdio.h>
  43. #include <io.h>
  44. #include <assert.h>
  45. // USER INCLUDES //////////////////////////////////////////////////////////////
  46. #include "Common/Debug.h"
  47. #include "WWLib/Targa.h"
  48. #include "Resource.h"
  49. #include "ImagePacker.h"
  50. #include "WinMain.h"
  51. #include "WindowProc.h"
  52. // DEFINES ////////////////////////////////////////////////////////////////////
  53. char *gAppPrefix = "ip_"; // So IP can have a different debug log file name if we need it.
  54. // PRIVATE TYPES //////////////////////////////////////////////////////////////
  55. ///////////////////////////////////////////////////////////////////////////////
  56. // PRIVATE DATA ///////////////////////////////////////////////////////////////
  57. ///////////////////////////////////////////////////////////////////////////////
  58. ImagePacker *TheImagePacker = NULL;
  59. // PUBLIC DATA ////////////////////////////////////////////////////////////////
  60. // PRIVATE PROTOTYPES /////////////////////////////////////////////////////////
  61. ///////////////////////////////////////////////////////////////////////////////
  62. // PRIVATE FUNCTIONS //////////////////////////////////////////////////////////
  63. ///////////////////////////////////////////////////////////////////////////////
  64. // ImagePacker::createNewTexturePage ==========================================
  65. /** Create a new texture page and add to the list */
  66. //=============================================================================
  67. TexturePage *ImagePacker::createNewTexturePage( void )
  68. {
  69. TexturePage *page;
  70. // allocate new page
  71. page = new TexturePage( getTargetWidth(), getTargetHeight() );
  72. if( page == NULL )
  73. {
  74. DEBUG_ASSERTCRASH( page, ("Unable to allocate new texture page.\n") );
  75. return NULL;
  76. } // end if
  77. // link page to list
  78. page->m_prev = NULL;
  79. page->m_next = m_pageList;
  80. if( m_pageList )
  81. m_pageList->m_prev = page;
  82. m_pageList = page;
  83. // add the tail pointer if this is the first page
  84. if( m_pageTail == NULL )
  85. m_pageTail = page;
  86. // we got a new page now
  87. m_pageCount++;
  88. // set page id as the current page count
  89. page->setID( m_pageCount );
  90. return page;
  91. } // end createNewTexturePage
  92. // ImagePacker::validateImages ================================================
  93. /** Check all the images in the image list, if any of them cannot be
  94. * processed we will flag them as so. If we have some images that can't
  95. * be processed, we will warn the user of these images and ask them
  96. * whether or not to proceed.
  97. *
  98. * Returns TRUE to proceed
  99. * Returns FALSE to cancel build
  100. */
  101. //=============================================================================
  102. Bool ImagePacker::validateImages( void )
  103. {
  104. UnsignedInt i;
  105. ImageInfo *image;
  106. Bool errors = FALSE;
  107. Bool proceed = TRUE;
  108. // loop through all images
  109. for( i = 0; i < m_imageCount; i++ )
  110. {
  111. // get this image
  112. image = m_imageList[ i ];
  113. // sanity
  114. if( image == NULL )
  115. {
  116. DEBUG_ASSERTCRASH( image, ("Image in imagelist is NULL") );
  117. continue; // should never happen
  118. } // end if
  119. //
  120. // if this image is too big to fit in the target page size as a whole
  121. // then there is nothing we can do about it
  122. //
  123. if( image->m_size.x > getTargetWidth() ||
  124. image->m_size.y > getTargetHeight() )
  125. {
  126. errors = TRUE;
  127. BitSet( image->m_status, ImageInfo::TOOBIG );
  128. BitSet( image->m_status, ImageInfo::CANTPROCESS );
  129. } // end if
  130. //
  131. // if this image is not the right format we can't process it, at
  132. // present we only understand 32 and 24 bit images
  133. //
  134. if( image->m_colorDepth != 32 && image->m_colorDepth != 24 )
  135. {
  136. errors = TRUE;
  137. BitSet( image->m_status, ImageInfo::INVALIDCOLORDEPTH );
  138. BitSet( image->m_status, ImageInfo::CANTPROCESS );
  139. } // end if
  140. } // end for i
  141. //
  142. // if we have errors, build a list and show them to the user
  143. //
  144. if( errors == TRUE )
  145. {
  146. proceed = DialogBox( ApplicationHInstance,
  147. (LPCTSTR)IMAGE_ERRORS,
  148. TheImagePacker->getWindowHandle(),
  149. (DLGPROC)ImageErrorProc );
  150. } // end if
  151. return proceed;
  152. } // end validateImages
  153. // ImagePacker::packImages ====================================================
  154. /** Pack all the images in the image list, starting from the top and
  155. * working from there */
  156. //=============================================================================
  157. Bool ImagePacker::packImages( void )
  158. {
  159. UnsignedInt i;
  160. TexturePage *page = NULL;
  161. ImageInfo *image = NULL;
  162. //
  163. // first sanity check all images loaded, if there are images that cannot
  164. // be processed the user will be given a list of these and asked wether
  165. // or not to proceed
  166. //
  167. Bool proceed;
  168. proceed = validateImages();
  169. if( proceed == FALSE )
  170. {
  171. statusMessage( "Build Cancelled By User." );
  172. return FALSE;
  173. } // end if
  174. // loop through all images
  175. for( i = 0; i < m_imageCount; i++ )
  176. {
  177. // update status
  178. sprintf( m_statusBuffer, "Fitting Image %d of %d.", i, m_imageCount );
  179. statusMessage( m_statusBuffer );
  180. // get this image out of the list
  181. image = m_imageList[ i ];
  182. // ignore images that we cannot process
  183. if( BitTest( image->m_status, ImageInfo::CANTPROCESS) )
  184. continue;
  185. // try to put image on each page
  186. for( page = m_pageTail; page; page = page->m_prev )
  187. {
  188. if( page->addImage( image ) == TRUE )
  189. break; // page added, stop trying to add into pages
  190. } // end for page
  191. // if image was not able to go on any existing page create a new page for it
  192. if( page == NULL )
  193. {
  194. page = createNewTexturePage();
  195. if( page == NULL )
  196. return FALSE;
  197. // try to add the image to this page
  198. if( page->addImage( image ) == FALSE )
  199. {
  200. char buffer[ _MAX_PATH ];
  201. sprintf( buffer, "Unable to add image '%s' to a brand new page!\n", image->m_path );
  202. DEBUG_ASSERTCRASH( 0, (buffer) );
  203. MessageBox( NULL, buffer, "Internal Error", MB_OK | MB_ICONERROR );
  204. return FALSE;
  205. } // end if
  206. } // end if
  207. } // end for i
  208. return TRUE; // success
  209. } // end packImages
  210. // ImagePacker::writeFinalTextures ============================================
  211. /** Generate and write the final textures to the output directory
  212. * of the packed images along with a definition file for which images
  213. * are where on the page */
  214. //=============================================================================
  215. void ImagePacker::writeFinalTextures( void )
  216. {
  217. TexturePage *page;
  218. Bool errors = FALSE;
  219. char buffer[ 128 ];
  220. //
  221. // go through each page, let's start from the end of the list since
  222. // that's where we packed first, but it doesn't matter
  223. //
  224. for( page = m_pageTail; page; page = page->m_prev )
  225. {
  226. // update status message
  227. sprintf( buffer, "Generating texture #%d of %d.",
  228. page->getID(), m_pageCount );
  229. statusMessage( buffer );
  230. // generate the final texture for this page
  231. if( page->generateTexture() == FALSE )
  232. {
  233. errors = TRUE;
  234. continue; // could not generate this page, but try to continue
  235. } // end if
  236. //
  237. // write this page out to a file using the filename given by
  238. // the user and the texture page ID to keep it unique
  239. //
  240. if( page->writeFile( m_outputFile ) == FALSE )
  241. {
  242. errors = TRUE;
  243. continue; // could not write page, but try to go on
  244. } // end if
  245. } // end for page
  246. // check for any errors and notify the user
  247. if( errors == TRUE )
  248. {
  249. DialogBox( ApplicationHInstance,
  250. (LPCTSTR)PAGE_ERRORS,
  251. TheImagePacker->getWindowHandle(),
  252. (DLGPROC)PageErrorProc );
  253. } // end if
  254. } // end writeFinalTextures
  255. // sortImageCompare ===========================================================
  256. /** Compare function for qsort
  257. * -1 item1 less than item2
  258. * 0 item1 identical to item2
  259. * 1 item1 greater than item2
  260. */
  261. //=============================================================================
  262. static Int sortImageCompare( const void *aa, const void *bb )
  263. {
  264. const ImageInfo **a = (const ImageInfo **)aa;
  265. const ImageInfo **b = (const ImageInfo **)bb;
  266. if( (*a)->m_area < (*b)->m_area )
  267. return 1;
  268. else if( (*a)->m_area > (*b)->m_area )
  269. return -1;
  270. else
  271. return 0;
  272. } // end sortImageCompare
  273. // ImagePacker::sortImageList =================================================
  274. /** Sort the image list */
  275. //=============================================================================
  276. void ImagePacker::sortImageList( void )
  277. {
  278. // sort all images so that largest area ones are first
  279. qsort( (void *)m_imageList, m_imageCount, sizeof( ImageInfo *), sortImageCompare );
  280. } // end sortImageList
  281. // ImagePacker::addImagesInDirectory ==========================================
  282. /** Add all the images in the specified directory */
  283. //=============================================================================
  284. void ImagePacker::addImagesInDirectory( char *dir )
  285. {
  286. // sanity
  287. if( dir == NULL )
  288. return;
  289. char currDir[ _MAX_PATH ];
  290. char filePath[ _MAX_PATH ];
  291. WIN32_FIND_DATA item; // search item
  292. HANDLE hFile; // handle for search resources
  293. Int len;
  294. // save the current directory
  295. GetCurrentDirectory( _MAX_PATH, currDir );
  296. // change into the directory
  297. SetCurrentDirectory( dir );
  298. // go through each item in the output directory
  299. hFile = FindFirstFile( "*", &item);
  300. if( hFile != INVALID_HANDLE_VALUE )
  301. {
  302. // if this is a file count it
  303. if( !(item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
  304. strcmp( item.cFileName, "." ) &&
  305. strcmp( item.cFileName, ".." ) )
  306. {
  307. len = strlen( item.cFileName );
  308. if( len > 4 &&
  309. item.cFileName[ len - 4 ] == '.' &&
  310. (item.cFileName[ len - 3 ] == 't' || item.cFileName[ len - 3 ] == 'T') &&
  311. (item.cFileName[ len - 2 ] == 'g' || item.cFileName[ len - 2 ] == 'G') &&
  312. (item.cFileName[ len - 1 ] == 'a' || item.cFileName[ len - 1 ] == 'A') )
  313. {
  314. sprintf( filePath, "%s%s", dir, item.cFileName );
  315. addImage( filePath );
  316. } // end if
  317. } // end if
  318. // find the rest of the files
  319. while( FindNextFile( hFile, &item ) != 0 )
  320. {
  321. // if this is a file count it
  322. if( !(item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
  323. strcmp( item.cFileName, "." ) &&
  324. strcmp( item.cFileName, ".." ) )
  325. {
  326. len = strlen( item.cFileName );
  327. if( len > 4 &&
  328. item.cFileName[ len - 4 ] == '.' &&
  329. (item.cFileName[ len - 3 ] == 't' || item.cFileName[ len - 3 ] == 'T') &&
  330. (item.cFileName[ len - 2 ] == 'g' || item.cFileName[ len - 2 ] == 'G') &&
  331. (item.cFileName[ len - 1 ] == 'a' || item.cFileName[ len - 1 ] == 'A') )
  332. {
  333. sprintf( filePath, "%s%s", dir, item.cFileName );
  334. addImage( filePath );
  335. } // end if
  336. } // end if
  337. } // end while
  338. // close search
  339. FindClose( hFile );
  340. } //end if, items found
  341. // restore our current directory
  342. SetCurrentDirectory( currDir );
  343. } // end addImagesInDirectory
  344. // ImagePacker::checkOutputDirectory ==========================================
  345. /** Verify that there are no files in the output directory ... if there
  346. * are give the user the option to delete them, cancel the operation,
  347. * or proceed with possibly overwriting any files there
  348. *
  349. * Returns TRUE to proceed with the process, FALSE if the user wants
  350. * to cancel the process
  351. */
  352. //=============================================================================
  353. Bool ImagePacker::checkOutputDirectory( void )
  354. {
  355. WIN32_FIND_DATA item; // search item
  356. HANDLE hFile; // handle for search resources
  357. Int fileCount = 0;
  358. char currDir[ _MAX_PATH ];
  359. // get the working directory
  360. GetCurrentDirectory( _MAX_PATH, currDir );
  361. // create the output directory if it does not exist
  362. CreateDirectory( m_outputDirectory, NULL );
  363. // change into the output directory
  364. SetCurrentDirectory( m_outputDirectory );
  365. // go through each item in the output directory
  366. hFile = FindFirstFile( "*", &item);
  367. if( hFile != INVALID_HANDLE_VALUE )
  368. {
  369. // if this is a file count it
  370. if( !(item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
  371. strcmp( item.cFileName, "." ) &&
  372. strcmp( item.cFileName, ".." ) )
  373. fileCount++;
  374. // find the rest of the files
  375. while( FindNextFile( hFile, &item ) != 0 )
  376. {
  377. // if this is a file count it
  378. if( !(item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
  379. strcmp( item.cFileName, "." ) &&
  380. strcmp( item.cFileName, ".." ) )
  381. fileCount++;
  382. } // end while
  383. // close search
  384. FindClose( hFile );
  385. } //end if, items found
  386. // switch back to the current directory
  387. SetCurrentDirectory( currDir );
  388. if( fileCount != 0 )
  389. {
  390. char buffer[ 256 ];
  391. Int response;
  392. sprintf( buffer, "The output directory (%s) must be empty before proceeding. Delete '%d' files and continue with build process?",
  393. m_outputDirectory, fileCount );
  394. response = MessageBox( NULL, buffer,
  395. "Delete files to continue?",
  396. MB_YESNO | MB_ICONWARNING );
  397. // if they said no, do not delete the files and abort the pack process
  398. if( response == IDNO )
  399. return FALSE;
  400. //
  401. // they said yes, delete all the files in the output directory
  402. //
  403. // change into the output directory
  404. SetCurrentDirectory( m_outputDirectory );
  405. // go through each item in the output directory
  406. hFile = FindFirstFile( "*", &item);
  407. if( hFile != INVALID_HANDLE_VALUE )
  408. {
  409. // if this is a file count it
  410. if( !(item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
  411. strcmp( item.cFileName, "." ) &&
  412. strcmp( item.cFileName, ".." ) )
  413. DeleteFile( item.cFileName );
  414. // find the rest of the files
  415. while( FindNextFile( hFile, &item ) != 0 )
  416. {
  417. // if this is a file count it
  418. if( !(item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
  419. strcmp( item.cFileName, "." ) &&
  420. strcmp( item.cFileName, ".." ) )
  421. DeleteFile( item.cFileName );
  422. } // end while
  423. // close search
  424. FindClose( hFile );
  425. } //end if, items found
  426. // switch back to the current directory
  427. SetCurrentDirectory( currDir );
  428. } // end if
  429. return TRUE; // proceed
  430. } // end checkOutputDirectory
  431. // ImagePacker::resetPageList =================================================
  432. /** Clear the page list */
  433. //=============================================================================
  434. void ImagePacker::resetPageList( void )
  435. {
  436. TexturePage *next;
  437. while( m_pageList )
  438. {
  439. next = m_pageList->m_next;
  440. delete m_pageList;
  441. m_pageList = next;
  442. } // end while
  443. m_pageTail = NULL;
  444. m_pageCount = 0;
  445. m_targetPreviewPage = 1;
  446. } // end resetPageList
  447. // ImagePacker::resetImageDirectoryList =======================================
  448. /** Clear the image directory list */
  449. //=============================================================================
  450. void ImagePacker::resetImageDirectoryList( void )
  451. {
  452. ImageDirectory *next;
  453. while( m_dirList )
  454. {
  455. next = m_dirList->m_next;
  456. delete m_dirList;
  457. m_dirList = next;
  458. } // end while
  459. m_dirCount = 0;
  460. m_imagesInDirs = 0;
  461. } // end resetImageDirectoryList
  462. // ImagePacker::resetImageList ================================================
  463. /** Clear the image list */
  464. //=============================================================================
  465. void ImagePacker::resetImageList( void )
  466. {
  467. if( m_imageList )
  468. delete [] m_imageList;
  469. m_imageList = NULL;
  470. m_imageCount = 0;
  471. } // end resetImageList
  472. // ImagePacker::addDirectory ==================================================
  473. /** Add the directory to the directory list, do not add it if it is already
  474. * in the directory list. We want to have that sanity check so that
  475. * we can be assured that each image being added to the image list from
  476. * each directory will be unique and we therefore don't have to do
  477. * any further checking for duplicates */
  478. //=============================================================================
  479. void ImagePacker::addDirectory( char *path, Bool subDirs )
  480. {
  481. char currDir[ _MAX_PATH ];
  482. WIN32_FIND_DATA item; // search item
  483. HANDLE hFile; // handle for search resources
  484. // santiy
  485. if( path == NULL )
  486. return;
  487. // check to see if path is already in list
  488. ImageDirectory *dir;
  489. for( dir = m_dirList; dir; dir = dir->m_next )
  490. if( stricmp( dir->m_path, path ) == 0 )
  491. return; // already in list
  492. // save our current directory
  493. GetCurrentDirectory( _MAX_PATH, currDir );
  494. // set our directory to this one
  495. if( SetCurrentDirectory( path ) == 0 )
  496. return; // directory does not exist
  497. // image is not in list, make a new entry and link to the list
  498. dir = new ImageDirectory;
  499. if( dir == NULL )
  500. {
  501. MessageBox( NULL, "Unable to allocate image directory", "Error",
  502. MB_OK | MB_ICONERROR );
  503. return;
  504. } // end if
  505. // allocate space for the path
  506. Int len = strlen( path );
  507. dir->m_path = new char[ len + 1 ];
  508. strcpy( dir->m_path, path );
  509. if( dir->m_path == NULL )
  510. {
  511. MessageBox( NULL, "Unable to allocate path for directory", "Error",
  512. MB_OK | MB_ICONERROR );
  513. delete dir;
  514. return;
  515. } // end if
  516. // tie to list
  517. dir->m_prev = NULL;
  518. dir->m_next = m_dirList;
  519. if( m_dirList )
  520. m_dirList->m_prev = dir;
  521. m_dirList = dir;
  522. // increase our directory count
  523. m_dirCount++;
  524. // update status
  525. sprintf( m_statusBuffer, "Folder Added: %d.", m_dirCount );
  526. statusMessage( m_statusBuffer );
  527. // count how many image files are in this directory
  528. hFile = FindFirstFile( "*", &item);
  529. if( hFile != INVALID_HANDLE_VALUE )
  530. {
  531. // if this is a file count it
  532. if( !(item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
  533. strcmp( item.cFileName, "." ) &&
  534. strcmp( item.cFileName, ".." ) )
  535. {
  536. len = strlen( item.cFileName );
  537. if( len > 4 &&
  538. item.cFileName[ len - 4 ] == '.' &&
  539. (item.cFileName[ len - 3 ] == 't' || item.cFileName[ len - 3 ] == 'T') &&
  540. (item.cFileName[ len - 2 ] == 'g' || item.cFileName[ len - 2 ] == 'G') &&
  541. (item.cFileName[ len - 1 ] == 'a' || item.cFileName[ len - 1 ] == 'A') )
  542. dir->m_imageCount++;
  543. } // end if
  544. // find the rest of the files
  545. while( FindNextFile( hFile, &item ) != 0 )
  546. {
  547. // if this is a file count it
  548. if( !(item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
  549. strcmp( item.cFileName, "." ) &&
  550. strcmp( item.cFileName, ".." ) )
  551. {
  552. len = strlen( item.cFileName );
  553. if( len > 4 &&
  554. item.cFileName[ len - 4 ] == '.' &&
  555. (item.cFileName[ len - 3 ] == 't' || item.cFileName[ len - 3 ] == 'T') &&
  556. (item.cFileName[ len - 2 ] == 'g' || item.cFileName[ len - 2 ] == 'G') &&
  557. (item.cFileName[ len - 1 ] == 'a' || item.cFileName[ len - 1 ] == 'A') )
  558. dir->m_imageCount++;
  559. } // end if
  560. } // end while
  561. // close search
  562. FindClose( hFile );
  563. } //end if, items found
  564. // add the image count of this directory to the total image count
  565. m_imagesInDirs += dir->m_imageCount;
  566. // if we are adding subdirectories add them all
  567. if( subDirs )
  568. {
  569. char subDir[ _MAX_PATH ];
  570. // go through each item in the output directory
  571. hFile = FindFirstFile( "*", &item);
  572. if( hFile != INVALID_HANDLE_VALUE )
  573. {
  574. // if this is a file count it
  575. if( (item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
  576. strcmp( item.cFileName, "." ) &&
  577. strcmp( item.cFileName, ".." ) )
  578. {
  579. sprintf( subDir, "%s%s\\", path, item.cFileName );
  580. addDirectory( subDir, subDirs );
  581. } // end if
  582. // find the rest of the files
  583. while( FindNextFile( hFile, &item ) != 0 )
  584. {
  585. // if this is a file count it
  586. if( (item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
  587. strcmp( item.cFileName, "." ) &&
  588. strcmp( item.cFileName, ".." ) )
  589. {
  590. sprintf( subDir, "%s%s\\", path, item.cFileName );
  591. addDirectory( subDir, subDirs );
  592. } // end if
  593. } // end while
  594. // close search
  595. FindClose( hFile );
  596. } //end if, items found
  597. } // end if
  598. // restore our current directory
  599. SetCurrentDirectory( currDir );
  600. } // end addDirectory
  601. // ImagePacker::addImage ======================================================
  602. /** Add the image to the image list */
  603. //=============================================================================
  604. void ImagePacker::addImage( char *path )
  605. {
  606. // sanity
  607. if( path == NULL )
  608. return;
  609. // allocate a new entry
  610. ImageInfo *info = new ImageInfo;
  611. if( info == NULL )
  612. {
  613. MessageBox( NULL, "Unable to allocate image info", "Error",
  614. MB_OK | MB_ICONERROR );
  615. return;
  616. } // end if
  617. // allocate space for the path
  618. Int len = strlen( path );
  619. info->m_path = new char[ len + 1 ];
  620. strcpy( info->m_path, path );
  621. if( info->m_path == NULL )
  622. {
  623. MessageBox( NULL, "Unable to allcoate image path info", "Error",
  624. MB_OK | MB_ICONERROR );
  625. delete info;
  626. return;
  627. } // end if
  628. // load just the header information from the targa
  629. m_targa->Load( info->m_path, 0, TRUE );
  630. // get the data we need out of the targa header
  631. info->m_colorDepth = m_targa->Header.PixelDepth;
  632. info->m_size.x = m_targa->Header.Width;
  633. info->m_size.y = m_targa->Header.Height;
  634. info->m_area = info->m_size.x * info->m_size.y;
  635. // save the filename only without path
  636. Int i;
  637. char *c;
  638. for( i = len - 1; i >= 0; i-- )
  639. {
  640. if( path[ i ] == '\\' )
  641. {
  642. c = &path[ i + 1 ];
  643. break;
  644. }
  645. } // end for i
  646. Int nameLen = strlen( c );
  647. info->m_filenameOnly = new char[ nameLen + 1 ];
  648. strcpy( info->m_filenameOnly, c );
  649. info->m_filenameOnlyNoExt = new char[ nameLen - 4 + 1 ];
  650. strncpy( info->m_filenameOnlyNoExt, c, nameLen - 4 );
  651. info->m_filenameOnlyNoExt[ nameLen - 4 ] = '\0';
  652. // assign to array
  653. m_imageList[ m_imageCount++ ] = info;
  654. // update status
  655. sprintf( m_statusBuffer, "Loading Image %d of %d.",
  656. m_imageCount, m_imagesInDirs );
  657. statusMessage( m_statusBuffer );
  658. } // end addImage
  659. // ImagePacker::generateINIFile ===============================================
  660. /** Generate the INI image file definition for the final packed images */
  661. //=============================================================================
  662. Bool ImagePacker::generateINIFile( void )
  663. {
  664. FILE *fp;
  665. char filename[ _MAX_PATH ];
  666. // construct filename we'll use
  667. sprintf( filename, "%s%s.INI", m_outputDirectory, m_outputFile );
  668. // open the file
  669. fp = fopen( filename, "w" );
  670. if( fp == NULL )
  671. {
  672. char buffer[ _MAX_PATH + 64 ];
  673. sprintf( buffer, "Cannot open INI file '%s' for writing.", filename );
  674. MessageBox( NULL, buffer, "Error Opening File", MB_OK | MB_ICONERROR );
  675. return FALSE;
  676. } // end if
  677. // print header for file
  678. fprintf( fp, "; ------------------------------------------------------------\n" );
  679. fprintf( fp, "; Do NOT edit by hand, ImagePacker.exe auto generated INI file\n" );
  680. fprintf( fp, "; ------------------------------------------------------------\n\n" );
  681. //
  682. // loop through all the pages so that we write image definitions that
  683. // are on the same page close together in the file, note we're
  684. // going backwards through the page list because page 1 is at the
  685. // tail and I want them to print out in number order, but it
  686. // doesn't really matter
  687. //
  688. TexturePage *page;
  689. ImageInfo *image;
  690. for( page = m_pageTail; page; page = page->m_prev )
  691. {
  692. // ignore texture pages that generated errors
  693. if( BitTest( page->m_status, TexturePage::PAGE_ERROR ) )
  694. continue;
  695. // go through each image on this page
  696. for( image = page->getFirstImage();
  697. image;
  698. image = image->m_nextPageImage )
  699. {
  700. //
  701. // write the item definition, note when we output the texture coords
  702. // we add on to the right and bottom to include that pixel in the
  703. // texture calculations ... need to do this since we are using a zero
  704. // based region for the "filled regions" in the image packer
  705. //
  706. fprintf( fp, "MappedImage %s\n", image->m_filenameOnlyNoExt );
  707. fprintf( fp, " Texture = %s_%03d.tga\n", m_outputFile, page->getID() );
  708. fprintf( fp, " TextureWidth = %d\n", page->getWidth() );
  709. fprintf( fp, " TextureHeight = %d\n", page->getHeight() );
  710. fprintf( fp, " Coords = Left:%d Top:%d Right:%d Bottom:%d\n",
  711. image->m_pagePos.lo.x, image->m_pagePos.lo.y,
  712. image->m_pagePos.hi.x + 1, image->m_pagePos.hi.y + 1 );
  713. fprintf( fp, " Status = %s\n",
  714. BitTest( image->m_status, ImageInfo::ROTATED90C ) ?
  715. "ROTATED_90_CLOCKWISE" : "NONE" );
  716. fprintf( fp, "End\n\n" );
  717. } // end for image
  718. } // end for page
  719. // close the file
  720. fclose( fp );
  721. return TRUE; // success
  722. } // end generateINIFile
  723. ///////////////////////////////////////////////////////////////////////////////
  724. // PUBLIC FUNCTIONS ///////////////////////////////////////////////////////////
  725. ///////////////////////////////////////////////////////////////////////////////
  726. // ImagePacker::getSettingsFromDialog =========================================
  727. /** Given the current state of the option dialog passed in, get all the
  728. * settings we need for the image packer from the GUI and validate them */
  729. //=============================================================================
  730. Bool ImagePacker::getSettingsFromDialog( HWND dialog )
  731. {
  732. Int i;
  733. // sanity
  734. if( dialog == NULL )
  735. return FALSE;
  736. // if we are using a user target image size, it must be a power of 2
  737. if( IsDlgButtonChecked( dialog, RADIO_TARGET_OTHER ) )
  738. {
  739. UnsignedInt size, val;
  740. Int bitCount = 0;
  741. size = GetDlgItemInt( dialog, EDIT_WIDTH, NULL, FALSE );
  742. for( val = size; val; val >>= 1 )
  743. if( BitTest( val, 0x1 ) )
  744. bitCount++;
  745. //
  746. // if bit count was not 1, this is not a power of 2 ... it also
  747. // guards us from entering a size of zero :)
  748. //
  749. if( bitCount != 1 )
  750. {
  751. MessageBox( NULL, "The target image size must be a power of 2.",
  752. "Must Be Power Of 2", MB_OK | MB_ICONERROR );
  753. return FALSE;
  754. } // end if
  755. // set the size for the image packer
  756. setTargetSize( size, size );
  757. } // end if
  758. else if( IsDlgButtonChecked( dialog, RADIO_128X128 ) )
  759. setTargetSize( 128, 128 );
  760. else if( IsDlgButtonChecked( dialog, RADIO_256X256 ) )
  761. setTargetSize( 256, 256 );
  762. else if( IsDlgButtonChecked( dialog, RADIO_512X512 ) )
  763. setTargetSize( 512, 512 );
  764. else
  765. {
  766. MessageBox( NULL, "Internal Error. Target Size Unknown.",
  767. "Error", MB_OK | MB_ICONERROR );
  768. return FALSE;
  769. } // end else
  770. // get alpha option
  771. Bool outputAlpha = FALSE;
  772. if( IsDlgButtonChecked( dialog, CHECK_ALPHA ) == BST_CHECKED )
  773. outputAlpha = TRUE;
  774. TheImagePacker->setOutputAlpha( outputAlpha );
  775. // get create INI option
  776. Bool createINI = FALSE;
  777. if( IsDlgButtonChecked( dialog, CHECK_INI ) == BST_CHECKED )
  778. createINI = TRUE;
  779. TheImagePacker->setINICreate( createINI );
  780. // get preview with image option
  781. Bool useBitmap = FALSE;
  782. if( IsDlgButtonChecked( dialog, CHECK_BITMAP_PREVIEW ) == BST_CHECKED )
  783. useBitmap = TRUE;
  784. TheImagePacker->setUseTexturePreview( useBitmap );
  785. // get option to compress final textures
  786. Bool compress = FALSE;
  787. if( IsDlgButtonChecked( dialog, CHECK_COMPRESS ) == BST_CHECKED )
  788. compress = TRUE;
  789. TheImagePacker->setCompressTextures( compress );
  790. // get options for the gap options
  791. TheImagePacker->clearGapMethod( ImagePacker::GAP_METHOD_EXTEND_RGB );
  792. if( IsDlgButtonChecked( dialog, CHECK_GAP_EXTEND_RGB ) == BST_CHECKED )
  793. TheImagePacker->setGapMethod( ImagePacker::GAP_METHOD_EXTEND_RGB );
  794. TheImagePacker->clearGapMethod( ImagePacker::GAP_METHOD_GUTTER );
  795. if( IsDlgButtonChecked( dialog, CHECK_GAP_GUTTER ) == BST_CHECKED )
  796. TheImagePacker->setGapMethod( ImagePacker::GAP_METHOD_GUTTER );
  797. // get gutter size whether we are using that option or not
  798. Int gutter = GetDlgItemInt( dialog, EDIT_GUTTER, NULL, FALSE );
  799. if( gutter < 0 )
  800. gutter = 0;
  801. setGutter( gutter );
  802. // save the filename to output
  803. GetDlgItemText( dialog, EDIT_FILENAME, m_outputFile, MAX_OUTPUT_FILE_LEN - 1 );
  804. // check for illegal characters in the output name
  805. Int len = strlen( m_outputFile );
  806. for( i = 0; i < len; i++ )
  807. {
  808. char *illegal = "/\\:*?<>|";
  809. Int illegalLen = strlen( illegal );
  810. for( Int j = 0; j < illegalLen; j++ )
  811. {
  812. if( m_outputFile[ i ] == illegal[ j ] )
  813. {
  814. char buffer[ 256 ];
  815. sprintf( buffer, "Output filename '%s' contains one or more of the following illegal characters:\n\n%s",
  816. m_outputFile, illegal );
  817. MessageBox( NULL, buffer, "Illegal Filename", MB_OK | MB_ICONERROR );
  818. return FALSE;
  819. } // end if
  820. } // end for j
  821. } // end for i
  822. // get the work on sub-folders option
  823. m_useSubFolders = IsDlgButtonChecked( dialog, CHECK_USE_SUB_FOLDERS );
  824. // clear our list of image directories
  825. resetImageDirectoryList();
  826. // set a status message
  827. statusMessage( "Gathering Directory Information, Please Wait ..." );
  828. // add all the image directories specified in the folder listbox
  829. Int count = SendDlgItemMessage( dialog, LIST_FOLDERS, LB_GETCOUNT, 0, 0 );
  830. char buffer[ _MAX_PATH ];
  831. for( i = 0; i < count; i++ )
  832. {
  833. // get text from the listbox
  834. SendDlgItemMessage( dialog, LIST_FOLDERS,
  835. LB_GETTEXT, i, (LPARAM)buffer );
  836. // add the directory
  837. addDirectory( buffer, m_useSubFolders );
  838. } // end for i
  839. // all done
  840. return TRUE;
  841. } // end getSettingsFromDialog
  842. // ImagePacker::ImagePacker ===================================================
  843. /** */
  844. //=============================================================================
  845. ImagePacker::ImagePacker( void )
  846. {
  847. m_hWnd = NULL;
  848. m_targetSize.x = DEFAULT_TARGET_SIZE;
  849. m_targetSize.y = DEFAULT_TARGET_SIZE;
  850. m_useSubFolders = TRUE;
  851. strcpy( m_outputFile, "" );
  852. strcpy( m_outputDirectory, "" );
  853. m_dirList = NULL;
  854. m_dirCount = 0;
  855. m_imagesInDirs = 0;
  856. m_imageList = NULL;
  857. m_imageCount = 0;
  858. strcpy( m_statusBuffer, "" );
  859. m_pageList = NULL;
  860. m_pageTail = NULL;
  861. m_pageCount = 0;
  862. m_gapMethod = GAP_METHOD_EXTEND_RGB;
  863. m_gutterSize = 1;
  864. m_outputAlpha = TRUE;
  865. m_createINI = TRUE;
  866. m_targetPreviewPage = 1;
  867. m_hWndPreview = NULL;
  868. m_showTextureInPreview = FALSE;
  869. m_targa = NULL;
  870. m_compressTextures = FALSE;
  871. } // end ImagePacker
  872. // ImagePacker::~ImagePacker ==================================================
  873. /** */
  874. //=============================================================================
  875. ImagePacker::~ImagePacker( void )
  876. {
  877. // delete our lists
  878. resetImageDirectoryList();
  879. resetImageList();
  880. resetPageList();
  881. // delete our targa header loader
  882. if( m_targa )
  883. delete m_targa;
  884. } // end ~ImagePacker
  885. // ImagePacker::init ==========================================================
  886. /** Initialize the image packer system */
  887. //=============================================================================
  888. Bool ImagePacker::init( void )
  889. {
  890. // allocate a targa to read the headers for the images
  891. m_targa = new Targa;
  892. if( m_targa == NULL )
  893. {
  894. DEBUG_ASSERTCRASH( m_targa, ("Unable to allocate targa header during init\n") );
  895. MessageBox( NULL, "ImagePacker can't init, unable to create targa",
  896. "Internal Error", MB_OK | MB_ICONERROR );
  897. return FALSE;
  898. } // end if
  899. return TRUE;
  900. } // end init
  901. // ImagePacker::statusMessage =================================================
  902. /** Status message for the program */
  903. //=============================================================================
  904. void ImagePacker::statusMessage( char *message )
  905. {
  906. SetDlgItemText( getWindowHandle(), STATIC_STATUS, message );
  907. } // end statusMessage
  908. // ImagePacker::process =======================================================
  909. /** Run the packing process */
  910. //=============================================================================
  911. Bool ImagePacker::process( void )
  912. {
  913. // build the output directory based on the base name of the output images
  914. char currDir[ _MAX_PATH ];
  915. GetCurrentDirectory( _MAX_PATH, currDir );
  916. sprintf( m_outputDirectory, "%s\\ImagePackerOutput\\", currDir );
  917. CreateDirectory( m_outputDirectory, NULL );
  918. // subdir of output directory based on output image name
  919. strcat( m_outputDirectory, m_outputFile );
  920. strcat( m_outputDirectory, "\\" );
  921. //
  922. // check for existing images in the output directory ... if we have
  923. // some then ask the user if they want to delete them or proceed with
  924. // a possible overwrite
  925. //
  926. if( checkOutputDirectory() == FALSE )
  927. {
  928. statusMessage( "Build Process Cancelled." );
  929. return FALSE;
  930. } // end if
  931. // reset the contents of our image list and existing textures
  932. resetImageList();
  933. resetPageList();
  934. // set a status message
  935. statusMessage( "Gathering Image Information, Please Wait ..." );
  936. // allocate an array to hold all the images
  937. m_imageList = new ImageInfo *[ m_imagesInDirs ];
  938. // load our image list with all the art files from the specified directories
  939. ImageDirectory *dir;
  940. for( dir = m_dirList; dir; dir = dir->m_next )
  941. addImagesInDirectory( dir->m_path );
  942. // sort the images with the largest biggest images at the top of the list
  943. sortImageList();
  944. // pack all images
  945. if( packImages() )
  946. {
  947. // generate the actual final textures and write them out to the file
  948. writeFinalTextures();
  949. // generate the INI definition file if requested
  950. if( createINIFile() == TRUE )
  951. generateINIFile();
  952. // update preview window
  953. UpdatePreviewWindow();
  954. // all done
  955. sprintf( m_statusBuffer, "Image Packing Complete: '%d' Texture Pages Generated from '%d' Images in '%d' Folder(s)",
  956. m_pageCount, m_imageCount, m_dirCount );
  957. statusMessage( m_statusBuffer );
  958. } // end if
  959. return TRUE;
  960. } // end process