D3D9Texture3D.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  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 deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // 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 FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Context.h"
  24. #include "FileSystem.h"
  25. #include "Graphics.h"
  26. #include "GraphicsEvents.h"
  27. #include "GraphicsImpl.h"
  28. #include "Log.h"
  29. #include "Renderer.h"
  30. #include "Profiler.h"
  31. #include "ResourceCache.h"
  32. #include "Texture3D.h"
  33. #include "XMLFile.h"
  34. #include "DebugNew.h"
  35. namespace Urho3D
  36. {
  37. Texture3D::Texture3D(Context* context) :
  38. Texture(context)
  39. {
  40. }
  41. Texture3D::~Texture3D()
  42. {
  43. Release();
  44. }
  45. void Texture3D::RegisterObject(Context* context)
  46. {
  47. context->RegisterFactory<Texture3D>();
  48. }
  49. bool Texture3D::BeginLoad(Deserializer& source)
  50. {
  51. ResourceCache* cache = GetSubsystem<ResourceCache>();
  52. // In headless mode, do not actually load the texture, just return success
  53. if (!graphics_)
  54. return true;
  55. // If device is lost, retry later
  56. if (graphics_->IsDeviceLost())
  57. {
  58. LOGWARNING("Texture load while device is lost");
  59. dataPending_ = true;
  60. return true;
  61. }
  62. String texPath, texName, texExt;
  63. SplitPath(GetName(), texPath, texName, texExt);
  64. cache->ResetDependencies(this);
  65. loadParameters_ = new XMLFile(context_);
  66. if (!loadParameters_->Load(source))
  67. {
  68. loadParameters_.Reset();
  69. return false;
  70. }
  71. XMLElement textureElem = loadParameters_->GetRoot();
  72. XMLElement volumeElem = textureElem.GetChild("volume");
  73. XMLElement colorlutElem = textureElem.GetChild("colorlut");
  74. if (volumeElem)
  75. {
  76. String name = volumeElem.GetAttribute("name");
  77. String volumeTexPath, volumeTexName, volumeTexExt;
  78. SplitPath(name, volumeTexPath, volumeTexName, volumeTexExt);
  79. // If path is empty, add the XML file path
  80. if (volumeTexPath.Empty())
  81. name = texPath + name;
  82. loadImage_ = cache->GetTempResource<Image>(name);
  83. // Precalculate mip levels if async loading
  84. if (loadImage_ && GetAsyncLoadState() == ASYNC_LOADING)
  85. loadImage_->PrecalculateLevels();
  86. cache->StoreResourceDependency(this, name);
  87. }
  88. else if (colorlutElem)
  89. {
  90. String name = colorlutElem.GetAttribute("name");
  91. String colorlutTexPath, colorlutTexName, colorlutTexExt;
  92. SplitPath(name, colorlutTexPath, colorlutTexName, colorlutTexExt);
  93. // If path is empty, add the XML file path
  94. if (colorlutTexPath.Empty())
  95. name = texPath + name;
  96. SharedPtr<File> file = GetSubsystem<ResourceCache>()->GetFile(name);
  97. loadImage_ = new Image(context_);
  98. if (!loadImage_->LoadColorLUT(*(file.Get())))
  99. {
  100. loadParameters_.Reset();
  101. loadImage_.Reset();
  102. return false;
  103. }
  104. // Precalculate mip levels if async loading
  105. if (loadImage_ && GetAsyncLoadState() == ASYNC_LOADING)
  106. loadImage_->PrecalculateLevels();
  107. cache->StoreResourceDependency(this, name);
  108. }
  109. return false;
  110. }
  111. bool Texture3D::EndLoad()
  112. {
  113. // In headless mode, do not actually load the texture, just return success
  114. if (!graphics_ || graphics_->IsDeviceLost())
  115. return true;
  116. // If over the texture budget, see if materials can be freed to allow textures to be freed
  117. CheckTextureBudget(GetTypeStatic());
  118. SetParameters(loadParameters_);
  119. bool success = SetData(loadImage_);
  120. loadImage_.Reset();
  121. loadParameters_.Reset();
  122. return success;
  123. }
  124. void Texture3D::OnDeviceLost()
  125. {
  126. if (pool_ == D3DPOOL_DEFAULT)
  127. Release();
  128. }
  129. void Texture3D::OnDeviceReset()
  130. {
  131. if (pool_ == D3DPOOL_DEFAULT || !object_ || dataPending_)
  132. {
  133. // If has a resource file, reload through the resource cache. Otherwise just recreate.
  134. ResourceCache* cache = GetSubsystem<ResourceCache>();
  135. if (cache->Exists(GetName()))
  136. dataLost_ = !cache->ReloadResource(this);
  137. if (!object_)
  138. {
  139. Create();
  140. dataLost_ = true;
  141. }
  142. }
  143. dataPending_ = false;
  144. }
  145. void Texture3D::Release()
  146. {
  147. if (object_)
  148. {
  149. if (!graphics_)
  150. return;
  151. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  152. {
  153. if (graphics_->GetTexture(i) == this)
  154. graphics_->SetTexture(i, 0);
  155. }
  156. if (renderSurface_)
  157. renderSurface_->Release();
  158. ((IDirect3DVolumeTexture9*)object_)->Release();
  159. object_ = 0;
  160. }
  161. else
  162. {
  163. if (renderSurface_)
  164. renderSurface_->Release();
  165. }
  166. }
  167. bool Texture3D::SetSize(int width, int height, int depth, unsigned format, TextureUsage usage)
  168. {
  169. // Delete the old rendersurface if any
  170. renderSurface_.Reset();
  171. pool_ = D3DPOOL_MANAGED;
  172. usage_ = 0;
  173. if (usage == TEXTURE_RENDERTARGET)
  174. {
  175. renderSurface_ = new RenderSurface(this);
  176. usage_ |= D3DUSAGE_RENDERTARGET;
  177. pool_ = D3DPOOL_DEFAULT;
  178. // Clamp mode addressing by default, nearest filtering, and mipmaps disabled
  179. addressMode_[COORD_U] = ADDRESS_CLAMP;
  180. addressMode_[COORD_V] = ADDRESS_CLAMP;
  181. filterMode_ = FILTER_NEAREST;
  182. requestedLevels_ = 1;
  183. }
  184. else if (usage == TEXTURE_DYNAMIC)
  185. {
  186. usage_ |= D3DUSAGE_DYNAMIC;
  187. pool_ = D3DPOOL_DEFAULT;
  188. }
  189. if (usage == TEXTURE_RENDERTARGET)
  190. SubscribeToEvent(E_RENDERSURFACEUPDATE, HANDLER(Texture3D, HandleRenderSurfaceUpdate));
  191. else
  192. UnsubscribeFromEvent(E_RENDERSURFACEUPDATE);
  193. width_ = width;
  194. height_ = height;
  195. depth_ = depth;
  196. format_ = format;
  197. return Create();
  198. }
  199. bool Texture3D::SetData(unsigned level, int x, int y, int z, int width, int height, int depth, const void* data)
  200. {
  201. PROFILE(SetTextureData);
  202. if (!object_)
  203. {
  204. LOGERROR("No texture created, can not set data");
  205. return false;
  206. }
  207. if (!data)
  208. {
  209. LOGERROR("Null source for setting data");
  210. return false;
  211. }
  212. if (level >= levels_)
  213. {
  214. LOGERROR("Illegal mip level for setting data");
  215. return false;
  216. }
  217. if (graphics_->IsDeviceLost())
  218. {
  219. LOGWARNING("Texture data assignment while device is lost");
  220. dataPending_ = true;
  221. return true;
  222. }
  223. if (IsCompressed())
  224. {
  225. x &= ~3;
  226. y &= ~3;
  227. }
  228. int levelWidth = GetLevelWidth(level);
  229. int levelHeight = GetLevelHeight(level);
  230. int levelDepth = GetLevelDepth(level);
  231. if (x < 0 || x + width > levelWidth || y < 0 || y + height > levelHeight || z < 0 || z + depth > levelDepth || width <= 0 || height <= 0 || depth <= 0)
  232. {
  233. LOGERROR("Illegal dimensions for setting data");
  234. return false;
  235. }
  236. D3DLOCKED_BOX d3dLockedBox;
  237. D3DBOX d3dBox;
  238. d3dBox.Left = x;
  239. d3dBox.Top = y;
  240. d3dBox.Front = z;
  241. d3dBox.Right = x + width;
  242. d3dBox.Bottom = y + height;
  243. d3dBox.Back = z + depth;
  244. DWORD flags = 0;
  245. if (level == 0 && x == 0 && y == 0 && z == 0 && width == levelWidth && height == levelHeight && depth == levelDepth && pool_ == D3DPOOL_DEFAULT)
  246. flags |= D3DLOCK_DISCARD;
  247. if (FAILED(((IDirect3DVolumeTexture9*)object_)->LockBox(level, &d3dLockedBox, (flags & D3DLOCK_DISCARD) ? 0 : &d3dBox, flags)))
  248. {
  249. LOGERROR("Could not lock texture");
  250. return false;
  251. }
  252. if (IsCompressed())
  253. {
  254. height = (height + 3) >> 2;
  255. y >>= 2;
  256. }
  257. unsigned char* src = (unsigned char*)data;
  258. unsigned rowSize = GetRowDataSize(width);
  259. // GetRowDataSize() returns CPU-side (source) data size, so need to convert for X8R8G8B8
  260. if (format_ == D3DFMT_X8R8G8B8)
  261. rowSize = rowSize / 3 * 4;
  262. // Perform conversion from RGB / RGBA as necessary
  263. switch (format_)
  264. {
  265. default:
  266. for (int k = 0; k < levelDepth; ++k)
  267. {
  268. for (int i = 0; i < height; ++i)
  269. {
  270. unsigned char* dest = (unsigned char*)d3dLockedBox.pBits + (k * d3dLockedBox.SlicePitch) + i * d3dLockedBox.RowPitch;
  271. memcpy(dest, src, rowSize);
  272. src += rowSize;
  273. }
  274. }
  275. break;
  276. case D3DFMT_X8R8G8B8:
  277. for (int k = 0; k < levelDepth; ++k)
  278. {
  279. for (int i = 0; i < height; ++i)
  280. {
  281. unsigned char* dest = (unsigned char*)d3dLockedBox.pBits + (k * d3dLockedBox.SlicePitch) + i * d3dLockedBox.RowPitch;
  282. for (int j = 0; j < width; ++j)
  283. {
  284. *dest++ = src[2]; *dest++ = src[1]; *dest++ = src[0]; *dest++ = 255;
  285. src += 3;
  286. }
  287. }
  288. }
  289. break;
  290. case D3DFMT_A8R8G8B8:
  291. for (int k = 0; k < levelDepth; ++k)
  292. {
  293. for (int i = 0; i < height; ++i)
  294. {
  295. unsigned char* dest = (unsigned char*)d3dLockedBox.pBits + (k * d3dLockedBox.SlicePitch) + i * d3dLockedBox.RowPitch;
  296. for (int j = 0; j < width; ++j)
  297. {
  298. *dest++ = src[2]; *dest++ = src[1]; *dest++ = src[0]; *dest++ = src[3];
  299. src += 4;
  300. }
  301. }
  302. }
  303. break;
  304. }
  305. ((IDirect3DVolumeTexture9*)object_)->UnlockBox(level);
  306. return true;
  307. }
  308. bool Texture3D::SetData(SharedPtr<Image> image, bool useAlpha)
  309. {
  310. if (!image)
  311. {
  312. LOGERROR("Null image, can not load texture");
  313. return false;
  314. }
  315. unsigned memoryUse = sizeof(Texture3D);
  316. int quality = QUALITY_HIGH;
  317. Renderer* renderer = GetSubsystem<Renderer>();
  318. if (renderer)
  319. quality = renderer->GetTextureQuality();
  320. if (!image->IsCompressed())
  321. {
  322. unsigned char* levelData = image->GetData();
  323. int levelWidth = image->GetWidth();
  324. int levelHeight = image->GetHeight();
  325. int levelDepth = image->GetDepth();
  326. unsigned components = image->GetComponents();
  327. unsigned format = 0;
  328. // Discard unnecessary mip levels
  329. for (unsigned i = 0; i < mipsToSkip_[quality]; ++i)
  330. {
  331. image = image->GetNextLevel();
  332. levelData = image->GetData();
  333. levelWidth = image->GetWidth();
  334. levelHeight = image->GetHeight();
  335. levelDepth = image->GetDepth();
  336. }
  337. switch (components)
  338. {
  339. case 1:
  340. format = useAlpha ? Graphics::GetAlphaFormat() : Graphics::GetLuminanceFormat();
  341. break;
  342. case 2:
  343. format = Graphics::GetLuminanceAlphaFormat();
  344. break;
  345. case 3:
  346. format = Graphics::GetRGBFormat();
  347. break;
  348. case 4:
  349. format = Graphics::GetRGBAFormat();
  350. break;
  351. }
  352. // If image was previously compressed, reset number of requested levels to avoid error if level count is too high for new size
  353. if (IsCompressed() && requestedLevels_ > 1)
  354. requestedLevels_ = 0;
  355. SetSize(levelWidth, levelHeight, levelDepth, format);
  356. for (unsigned i = 0; i < levels_; ++i)
  357. {
  358. SetData(i, 0, 0, 0, levelWidth, levelHeight, levelDepth, levelData);
  359. memoryUse += levelWidth * levelHeight * levelDepth * components;
  360. if (i < levels_ - 1)
  361. {
  362. image = image->GetNextLevel();
  363. levelData = image->GetData();
  364. levelWidth = image->GetWidth();
  365. levelHeight = image->GetHeight();
  366. levelDepth = image->GetDepth();
  367. }
  368. }
  369. }
  370. else
  371. {
  372. int width = image->GetWidth();
  373. int height = image->GetHeight();
  374. int depth = image->GetDepth();
  375. unsigned levels = image->GetNumCompressedLevels();
  376. unsigned format = graphics_->GetFormat(image->GetCompressedFormat());
  377. bool needDecompress = false;
  378. if (!format)
  379. {
  380. format = Graphics::GetRGBAFormat();
  381. needDecompress = true;
  382. }
  383. unsigned mipsToSkip = mipsToSkip_[quality];
  384. if (mipsToSkip >= levels)
  385. mipsToSkip = levels - 1;
  386. while (mipsToSkip && (width / (1 << mipsToSkip) < 4 || height / (1 << mipsToSkip) < 4 || depth / (1 << mipsToSkip) < 4))
  387. --mipsToSkip;
  388. width /= (1 << mipsToSkip);
  389. height /= (1 << mipsToSkip);
  390. depth /= (1 << mipsToSkip);
  391. SetNumLevels(Max((int)(levels - mipsToSkip), 1));
  392. SetSize(width, height, depth, format);
  393. for (unsigned i = 0; i < levels_ && i < levels - mipsToSkip; ++i)
  394. {
  395. CompressedLevel level = image->GetCompressedLevel(i + mipsToSkip);
  396. if (!needDecompress)
  397. {
  398. SetData(i, 0, 0, 0, level.width_, level.height_, level.depth_, level.data_);
  399. memoryUse += level.depth_ * level.rows_ * level.rowSize_;
  400. }
  401. else
  402. {
  403. unsigned char* rgbaData = new unsigned char[level.width_ * level.height_ * level.depth_ * 4];
  404. level.Decompress(rgbaData);
  405. SetData(i, 0, 0, 0, level.width_, level.height_, level.depth_, rgbaData);
  406. memoryUse += level.width_ * level.height_ * level.depth_ * 4;
  407. delete[] rgbaData;
  408. }
  409. }
  410. }
  411. SetMemoryUse(memoryUse);
  412. return true;
  413. }
  414. bool Texture3D::GetData(unsigned level, void* dest) const
  415. {
  416. if (!object_)
  417. {
  418. LOGERROR("No texture created, can not get data");
  419. return false;
  420. }
  421. if (!dest)
  422. {
  423. LOGERROR("Null destination for getting data");
  424. return false;
  425. }
  426. if (level >= levels_)
  427. {
  428. LOGERROR("Illegal mip level for getting data");
  429. return false;
  430. }
  431. if (graphics_->IsDeviceLost())
  432. {
  433. LOGWARNING("Getting texture data while device is lost");
  434. return false;
  435. }
  436. int levelWidth = GetLevelWidth(level);
  437. int levelHeight = GetLevelHeight(level);
  438. int levelDepth = GetLevelDepth(level);
  439. D3DLOCKED_BOX d3dLockedBox;
  440. D3DBOX d3dBox;
  441. d3dBox.Left = 0;
  442. d3dBox.Top = 0;
  443. d3dBox.Front = 0;
  444. d3dBox.Right = levelWidth;
  445. d3dBox.Bottom = levelHeight;
  446. d3dBox.Back = levelDepth;
  447. if (FAILED(((IDirect3DVolumeTexture9*)object_)->LockBox(level, &d3dLockedBox, &d3dBox, D3DLOCK_READONLY)))
  448. {
  449. LOGERROR("Could not lock texture");
  450. return false;
  451. }
  452. int height = levelHeight;
  453. if (IsCompressed())
  454. height = (height + 3) >> 2;
  455. unsigned char* destPtr = (unsigned char*)dest;
  456. unsigned rowSize = GetRowDataSize(levelWidth);
  457. // GetRowDataSize() returns CPU-side (destination) data size, so need to convert for X8R8G8B8
  458. if (format_ == D3DFMT_X8R8G8B8)
  459. rowSize = rowSize / 3 * 4;
  460. // Perform conversion to RGB / RGBA as necessary
  461. switch (format_)
  462. {
  463. default:
  464. for (int k = 0; k < levelDepth; ++k)
  465. {
  466. for (int i = 0; i < height; ++i)
  467. {
  468. unsigned char* src = (unsigned char*)d3dLockedBox.pBits + (k * d3dLockedBox.SlicePitch) + i * d3dLockedBox.RowPitch;
  469. memcpy(destPtr, src, rowSize);
  470. destPtr += rowSize;
  471. }
  472. }
  473. break;
  474. case D3DFMT_X8R8G8B8:
  475. for (int k = 0; k < levelDepth; ++k)
  476. {
  477. for (int i = 0; i < height; ++i)
  478. {
  479. unsigned char* src = (unsigned char*)d3dLockedBox.pBits + (k * d3dLockedBox.SlicePitch) + i * d3dLockedBox.RowPitch;
  480. for (int j = 0; j < levelWidth; ++j)
  481. {
  482. destPtr[2] = *src++; destPtr[1] = *src++; destPtr[0] = *src++; ++src;
  483. destPtr += 3;
  484. }
  485. }
  486. }
  487. break;
  488. case D3DFMT_A8R8G8B8:
  489. for (int k = 0; k < levelDepth; ++k)
  490. {
  491. for (int i = 0; i < height; ++i)
  492. {
  493. unsigned char* src = (unsigned char*)d3dLockedBox.pBits + (k * d3dLockedBox.SlicePitch) + i * d3dLockedBox.RowPitch;
  494. for (int j = 0; j < levelWidth; ++j)
  495. {
  496. destPtr[2] = *src++; destPtr[1] = *src++; destPtr[0] = *src++; destPtr[3] = *src++;
  497. destPtr += 4;
  498. }
  499. }
  500. }
  501. break;
  502. }
  503. ((IDirect3DVolumeTexture9*)object_)->UnlockBox(level);
  504. return true;
  505. }
  506. bool Texture3D::Create()
  507. {
  508. Release();
  509. if (!graphics_ || !width_ || !height_)
  510. return false;
  511. if (graphics_->IsDeviceLost())
  512. {
  513. LOGWARNING("Texture creation while device is lost");
  514. return true;
  515. }
  516. IDirect3DDevice9* device = graphics_->GetImpl()->GetDevice();
  517. if (!device || FAILED(graphics_->GetImpl()->GetDevice()->CreateVolumeTexture(
  518. width_,
  519. height_,
  520. depth_,
  521. requestedLevels_,
  522. usage_,
  523. (D3DFORMAT)format_,
  524. (D3DPOOL)pool_,
  525. (IDirect3DVolumeTexture9**)&object_,
  526. 0)))
  527. {
  528. LOGERROR("Could not create texture");
  529. return false;
  530. }
  531. levels_ = ((IDirect3DVolumeTexture9*)object_)->GetLevelCount();
  532. return true;
  533. }
  534. void Texture3D::HandleRenderSurfaceUpdate(StringHash eventType, VariantMap& eventData)
  535. {
  536. if (renderSurface_ && renderSurface_->GetUpdateMode() == SURFACE_UPDATEALWAYS)
  537. renderSurface_->QueueUpdate();
  538. }
  539. }