D3D9Texture2D.cpp 18 KB

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