D3D9Texture3D.cpp 19 KB

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