terrImport.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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 "terrain/terrData.h"
  24. #include "gfx/bitmap/gBitmap.h"
  25. #include "sim/netConnection.h"
  26. #include "core/strings/stringUnit.h"
  27. #include "core/resourceManager.h"
  28. #include "gui/worldEditor/terrainEditor.h"
  29. #include "util/noise2d.h"
  30. #include "core/volume.h"
  31. #include "T3D/Scene.h"
  32. using namespace Torque;
  33. DefineEngineStaticMethod( TerrainBlock, createNew, S32, (String terrainName, U32 resolution, String materialName, bool genNoise),,
  34. "" )
  35. {
  36. Vector<String> materials;
  37. materials.push_back( materialName );
  38. TerrainBlock *terrain = new TerrainBlock();
  39. // We create terrains based on level name. If the user wants to rename the terrain names; they have to
  40. // rename it themselves in their file browser. The main reason for this is so we can easily increment for ourselves;
  41. // and because its too easy to rename the terrain object and forget to take care of the terrain filename afterwards.
  42. String terrainDirectory( Con::getVariable( "$pref::Directories::Terrain" ) );
  43. if ( terrainDirectory.isEmpty() )
  44. {
  45. terrainDirectory = "data/terrains/";
  46. }
  47. String terrFileName = terrainDirectory + "/" + terrainName + ".ter";
  48. TerrainFile::create( &terrFileName, resolution, materials );
  49. if( !terrain->setFile( terrFileName ) )
  50. {
  51. Con::errorf( "TerrainBlock::createNew - error creating '%s'", terrFileName.c_str() );
  52. return 0;
  53. }
  54. terrain->setPosition( Point3F( 0, 0, 0 ) );
  55. const U32 blockSize = terrain->getBlockSize();
  56. if ( genNoise )
  57. {
  58. TerrainFile *file = terrain->getFile();
  59. Vector<F32> floatHeights;
  60. floatHeights.setSize( blockSize * blockSize );
  61. Noise2D noise;
  62. noise.setSeed( 134208587 );
  63. // Set up some defaults.
  64. const F32 octaves = 3.0f;
  65. const U32 freq = 4;
  66. const F32 roughness = 0.0f;
  67. noise.fBm( &floatHeights, blockSize, freq, 1.0f - roughness, octaves );
  68. F32 height = 0;
  69. F32 omax, omin;
  70. noise.getMinMax( &floatHeights, &omin, &omax, blockSize );
  71. const F32 terrscale = 300.0f / (omax - omin);
  72. for ( S32 y = 0; y < blockSize; y++ )
  73. {
  74. for ( S32 x = 0; x < blockSize; x++ )
  75. {
  76. // Very important to subtract the min
  77. // noise value when using the noise functions
  78. // for terrain, otherwise floatToFixed() will
  79. // wrap negative values to U16_MAX, creating
  80. // a very ugly terrain.
  81. height = (floatHeights[ x + (y * blockSize) ] - omin) * terrscale + 30.0f;
  82. file->setHeight( x, y, floatToFixed( height ) );
  83. }
  84. }
  85. terrain->updateGrid( Point2I::Zero, Point2I( blockSize, blockSize ) );
  86. terrain->updateGridMaterials( Point2I::Zero, Point2I( blockSize, blockSize ) );
  87. }
  88. terrain->registerObject( terrainName.c_str() );
  89. // Add to mission group!
  90. Scene* scene = Scene::getRootScene();
  91. if(scene)
  92. scene->addObject( terrain );
  93. return terrain->getId();
  94. }
  95. DefineEngineStaticMethod( TerrainBlock, import, S32, (S32 terrainObjectId, String heightMapFile, F32 metersPerPixel, F32 heightScale, String opacityLayerFiles, String materialsStr, bool flipYAxis), (true),
  96. "" )
  97. {
  98. // First load the height map and validate it.
  99. Resource<GBitmap> heightmap = GBitmap::load(heightMapFile);
  100. if ( !heightmap )
  101. {
  102. Con::errorf( "Heightmap failed to load!" );
  103. return 0;
  104. }
  105. U32 terrSize = heightmap->getWidth();
  106. U32 hheight = heightmap->getHeight();
  107. if ( terrSize != hheight || !isPow2( terrSize ) )
  108. {
  109. Con::errorf( "Height map must be square and power of two in size!" );
  110. return 0;
  111. }
  112. else if ( terrSize < 128 || terrSize > 4096 )
  113. {
  114. Con::errorf( "Height map must be between 128 and 4096 in size!" );
  115. return 0;
  116. }
  117. U32 fileCount = StringUnit::getUnitCount(opacityLayerFiles, "\n" );
  118. Vector<U8> layerMap;
  119. layerMap.setSize( terrSize * terrSize );
  120. {
  121. Vector<GBitmap*> bitmaps;
  122. for ( U32 i = 0; i < fileCount; i++ )
  123. {
  124. String fileNameWithChannel = StringUnit::getUnit(opacityLayerFiles, i, "\n" );
  125. String fileName = StringUnit::getUnit( fileNameWithChannel, 0, "\t" );
  126. String channel = StringUnit::getUnit( fileNameWithChannel, 1, "\t" );
  127. if ( fileName.isEmpty() )
  128. continue;
  129. if ( !channel.isEmpty() )
  130. {
  131. // Load and push back the bitmap here.
  132. Resource<GBitmap> opacityMap = ResourceManager::get().load( fileName );
  133. if ( terrSize != opacityMap->getWidth() || terrSize != opacityMap->getHeight() )
  134. {
  135. Con::errorf( "The opacity map '%s' doesn't match height map size!", fileName.c_str() );
  136. return 0;
  137. }
  138. // Always going to be one channel.
  139. GBitmap *opacityMapChannel = new GBitmap( terrSize,
  140. terrSize,
  141. false,
  142. GFXFormatA8 );
  143. if ( opacityMap->getBytesPerPixel() > 1 )
  144. {
  145. if ( channel.equal( "R", 1 ) )
  146. opacityMap->copyChannel( 0, opacityMapChannel );
  147. else if ( channel.equal( "G", 1 ) )
  148. opacityMap->copyChannel( 1, opacityMapChannel );
  149. else if ( channel.equal( "B", 1 ) )
  150. opacityMap->copyChannel( 2, opacityMapChannel );
  151. else if ( channel.equal( "A", 1 ) )
  152. opacityMap->copyChannel( 3, opacityMapChannel );
  153. bitmaps.push_back( opacityMapChannel );
  154. }
  155. else
  156. {
  157. opacityMapChannel->copyRect( opacityMap, RectI( 0, 0, terrSize, terrSize ), Point2I( 0, 0 ) );
  158. bitmaps.push_back( opacityMapChannel );
  159. }
  160. }
  161. }
  162. // Ok... time to convert all this opacity layer
  163. // mess to the layer index map!
  164. U32 layerCount = bitmaps.size() - 1;
  165. U32 layer, lastValue;
  166. U8 value;
  167. for ( U32 i = 0; i < terrSize * terrSize; i++ )
  168. {
  169. // Find the greatest layer.
  170. layer = lastValue = 0;
  171. for ( U32 k=0; k < bitmaps.size(); k++ )
  172. {
  173. value = bitmaps[k]->getBits()[i];
  174. if ( value >= lastValue )
  175. {
  176. layer = k;
  177. lastValue = value;
  178. }
  179. }
  180. // Set the layer index.
  181. layerMap[i] = getMin( layer, layerCount );
  182. }
  183. // Cleanup the bitmaps.
  184. for ( U32 i=0; i < bitmaps.size(); i++ )
  185. delete bitmaps[i];
  186. }
  187. U32 matCount = StringUnit::getUnitCount( materialsStr, "\t\n" );
  188. if( matCount != fileCount)
  189. {
  190. Con::errorf("Number of Materials and Layer maps must be equal.");
  191. return 0;
  192. }
  193. Vector<String> materials;
  194. for ( U32 i = 0; i < matCount; i++ )
  195. {
  196. String matStr = StringUnit::getUnit( materialsStr, i, "\t\n" );
  197. // even if matStr is empty, insert it as a placeholder (will be replaced with warning material later)
  198. materials.push_back( matStr );
  199. }
  200. // Do we have an existing terrain with that name... then update it!
  201. TerrainBlock *terrain = dynamic_cast<TerrainBlock*>( Sim::findObject( terrainObjectId ) );
  202. if ( terrain )
  203. terrain->import( (*heightmap), heightScale, metersPerPixel, layerMap, materials, flipYAxis );
  204. else
  205. {
  206. terrain = new TerrainBlock();
  207. terrain->import( (*heightmap), heightScale, metersPerPixel, layerMap, materials, flipYAxis );
  208. terrain->registerObject();
  209. // Add to scene!
  210. Scene* scene = Scene::getRootScene();
  211. if (scene)
  212. scene->addObject( terrain );
  213. }
  214. return terrain->getId();
  215. }
  216. bool TerrainBlock::import( const GBitmap &heightMap,
  217. F32 heightScale,
  218. F32 metersPerPixel,
  219. const Vector<U8> &layerMap,
  220. const Vector<String> &materials,
  221. bool flipYAxis)
  222. {
  223. AssertFatal( isServerObject(), "TerrainBlock::import - This should only be called on the server terrain!" );
  224. AssertFatal( heightMap.getWidth() == heightMap.getHeight(), "TerrainBlock::import - Height map is not square!" );
  225. AssertFatal( isPow2( heightMap.getWidth() ), "TerrainBlock::import - Height map is not power of two!" );
  226. // If we don't have a terrain file then add one.
  227. if ( !mFile )
  228. {
  229. // Get a unique file name for the terrain.
  230. String fileName( getName() );
  231. if (fileName.isEmpty())
  232. {
  233. fileName = Torque::Path(Con::getVariable("$Client::MissionFile")).getFileName();
  234. if (fileName.isEmpty())
  235. fileName = "terrain";
  236. }
  237. String terrainFileName = FS::MakeUniquePath( "levels", fileName, "ter" );
  238. if (!TerrainAsset::getAssetByFilename(terrainFileName, &mTerrainAsset))
  239. {
  240. return false;
  241. }
  242. else
  243. {
  244. mFile = mTerrainAsset->getTerrainResource();
  245. }
  246. /*// TODO: We have to save and reload the file to get
  247. // it into the resource system. This creates lots
  248. // of temporary unused files when the terrain is
  249. // discarded because of undo or quit.
  250. TerrainFile *file = new TerrainFile;
  251. file->save( mTerrFileName );
  252. delete file;
  253. mFile = ResourceManager::get().load( mTerrFileName );*/
  254. }
  255. // The file does a bunch of the work.
  256. mFile->import( heightMap, heightScale, layerMap, materials, flipYAxis );
  257. // Set the square size.
  258. mSquareSize = metersPerPixel;
  259. if ( isProperlyAdded() )
  260. {
  261. // Update the server bounds.
  262. _updateBounds();
  263. // Make sure the client gets updated.
  264. setMaskBits( HeightMapChangeMask | SizeMask );
  265. }
  266. return true;
  267. }