D3D9Texture2D.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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 (Graphics::IsUnmanagedPool(pool_))
  93. Release();
  94. }
  95. void Texture2D::OnDeviceReset()
  96. {
  97. if (Graphics::IsUnmanagedPool(pool_) || !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_ = Graphics::GetDefaultD3D9Pool();
  138. usage_ = Graphics::GetDefaultD3D9Usage();
  139. if (usage == TEXTURE_RENDERTARGET || usage == TEXTURE_DEPTHSTENCIL)
  140. {
  141. usage_ &= ~Graphics::GetDefaultD3D9Usage();
  142. renderSurface_ = new RenderSurface(this);
  143. if (usage == TEXTURE_RENDERTARGET)
  144. usage_ |= D3DUSAGE_RENDERTARGET;
  145. else
  146. usage_ |= D3DUSAGE_DEPTHSTENCIL;
  147. pool_ = D3DPOOL_DEFAULT;
  148. // Clamp mode addressing by default, nearest filtering, and mipmaps disabled
  149. addressMode_[COORD_U] = ADDRESS_CLAMP;
  150. addressMode_[COORD_V] = ADDRESS_CLAMP;
  151. filterMode_ = FILTER_NEAREST;
  152. requestedLevels_ = 1;
  153. }
  154. else if (usage == TEXTURE_DYNAMIC)
  155. {
  156. usage_ |= D3DUSAGE_DYNAMIC;
  157. pool_ = D3DPOOL_DEFAULT;
  158. }
  159. if (usage == TEXTURE_RENDERTARGET)
  160. SubscribeToEvent(E_RENDERSURFACEUPDATE, HANDLER(Texture2D, HandleRenderSurfaceUpdate));
  161. else
  162. UnsubscribeFromEvent(E_RENDERSURFACEUPDATE);
  163. width_ = width;
  164. height_ = height;
  165. format_ = format;
  166. return Create();
  167. }
  168. bool Texture2D::SetData(unsigned level, int x, int y, int width, int height, const void* data)
  169. {
  170. PROFILE(SetTextureData);
  171. if (!object_)
  172. {
  173. LOGERROR("No texture created, can not set data");
  174. return false;
  175. }
  176. if (!data)
  177. {
  178. LOGERROR("Null source for setting data");
  179. return false;
  180. }
  181. if (level >= levels_)
  182. {
  183. LOGERROR("Illegal mip level for setting data");
  184. return false;
  185. }
  186. if (graphics_->IsDeviceLost())
  187. {
  188. LOGWARNING("Texture data assignment while device is lost");
  189. dataPending_ = true;
  190. return true;
  191. }
  192. if (IsCompressed())
  193. {
  194. x &= ~3;
  195. y &= ~3;
  196. }
  197. int levelWidth = GetLevelWidth(level);
  198. int levelHeight = GetLevelHeight(level);
  199. if (x < 0 || x + width > levelWidth || y < 0 || y + height > levelHeight || width <= 0 || height <= 0)
  200. {
  201. LOGERROR("Illegal dimensions for setting data");
  202. return false;
  203. }
  204. D3DLOCKED_RECT d3dLockedRect;
  205. RECT d3dRect;
  206. d3dRect.left = x;
  207. d3dRect.top = y;
  208. d3dRect.right = x + width;
  209. d3dRect.bottom = y + height;
  210. DWORD flags = 0;
  211. if (level == 0 && x == 0 && y == 0 && width == levelWidth && height == levelHeight && usage_ & D3DUSAGE_DYNAMIC)
  212. flags |= D3DLOCK_DISCARD;
  213. if (FAILED(((IDirect3DTexture9*)object_)->LockRect(level, &d3dLockedRect, (flags & D3DLOCK_DISCARD) ? 0 : &d3dRect, flags)))
  214. {
  215. LOGERROR("Could not lock texture");
  216. return false;
  217. }
  218. if (IsCompressed())
  219. {
  220. height = (height + 3) >> 2;
  221. y >>= 2;
  222. }
  223. unsigned char* src = (unsigned char*)data;
  224. unsigned rowSize = GetRowDataSize(width);
  225. // GetRowDataSize() returns CPU-side (source) data size, so need to convert for X8R8G8B8
  226. if (format_ == D3DFMT_X8R8G8B8)
  227. rowSize = rowSize / 3 * 4;
  228. // Perform conversion from RGB / RGBA as necessary
  229. switch (format_)
  230. {
  231. default:
  232. for (int i = 0; i < height; ++i)
  233. {
  234. unsigned char* dest = (unsigned char*)d3dLockedRect.pBits + i * d3dLockedRect.Pitch;
  235. memcpy(dest, src, rowSize);
  236. src += rowSize;
  237. }
  238. break;
  239. case D3DFMT_X8R8G8B8:
  240. for (int i = 0; i < height; ++i)
  241. {
  242. unsigned char* dest = (unsigned char*)d3dLockedRect.pBits + i * d3dLockedRect.Pitch;
  243. for (int j = 0; j < width; ++j)
  244. {
  245. *dest++ = src[2];
  246. *dest++ = src[1];
  247. *dest++ = src[0];
  248. *dest++ = 255;
  249. src += 3;
  250. }
  251. }
  252. break;
  253. case D3DFMT_A8R8G8B8:
  254. for (int i = 0; i < height; ++i)
  255. {
  256. unsigned char* dest = (unsigned char*)d3dLockedRect.pBits + i * d3dLockedRect.Pitch;
  257. for (int j = 0; j < width; ++j)
  258. {
  259. *dest++ = src[2];
  260. *dest++ = src[1];
  261. *dest++ = src[0];
  262. *dest++ = src[3];
  263. src += 4;
  264. }
  265. }
  266. break;
  267. }
  268. ((IDirect3DTexture9*)object_)->UnlockRect(level);
  269. return true;
  270. }
  271. bool Texture2D::SetData(SharedPtr<Image> image, bool useAlpha)
  272. {
  273. if (!image)
  274. {
  275. LOGERROR("Null image, can not load texture");
  276. return false;
  277. }
  278. unsigned memoryUse = sizeof(Texture2D);
  279. int quality = QUALITY_HIGH;
  280. Renderer* renderer = GetSubsystem<Renderer>();
  281. if (renderer)
  282. quality = renderer->GetTextureQuality();
  283. if (!image->IsCompressed())
  284. {
  285. unsigned char* levelData = image->GetData();
  286. int levelWidth = image->GetWidth();
  287. int levelHeight = image->GetHeight();
  288. unsigned components = image->GetComponents();
  289. unsigned format = 0;
  290. // Discard unnecessary mip levels
  291. for (unsigned i = 0; i < mipsToSkip_[quality]; ++i)
  292. {
  293. image = image->GetNextLevel();
  294. levelData = image->GetData();
  295. levelWidth = image->GetWidth();
  296. levelHeight = image->GetHeight();
  297. }
  298. switch (components)
  299. {
  300. case 1:
  301. format = useAlpha ? Graphics::GetAlphaFormat() : Graphics::GetLuminanceFormat();
  302. break;
  303. case 2:
  304. format = Graphics::GetLuminanceAlphaFormat();
  305. break;
  306. case 3:
  307. format = Graphics::GetRGBFormat();
  308. break;
  309. case 4:
  310. format = Graphics::GetRGBAFormat();
  311. break;
  312. default:
  313. assert(false); // Should never reach here
  314. break;
  315. }
  316. // If image was previously compressed, reset number of requested levels to avoid error if level count is too high for new size
  317. if (IsCompressed() && requestedLevels_ > 1)
  318. requestedLevels_ = 0;
  319. SetSize(levelWidth, levelHeight, format);
  320. for (unsigned i = 0; i < levels_; ++i)
  321. {
  322. SetData(i, 0, 0, levelWidth, levelHeight, levelData);
  323. memoryUse += levelWidth * levelHeight * components;
  324. if (i < levels_ - 1)
  325. {
  326. image = image->GetNextLevel();
  327. levelData = image->GetData();
  328. levelWidth = image->GetWidth();
  329. levelHeight = image->GetHeight();
  330. }
  331. }
  332. }
  333. else
  334. {
  335. int width = image->GetWidth();
  336. int height = image->GetHeight();
  337. unsigned levels = image->GetNumCompressedLevels();
  338. unsigned format = graphics_->GetFormat(image->GetCompressedFormat());
  339. bool needDecompress = false;
  340. if (!format)
  341. {
  342. format = Graphics::GetRGBAFormat();
  343. needDecompress = true;
  344. }
  345. unsigned mipsToSkip = mipsToSkip_[quality];
  346. if (mipsToSkip >= levels)
  347. mipsToSkip = levels - 1;
  348. while (mipsToSkip && (width / (1 << mipsToSkip) < 4 || height / (1 << mipsToSkip) < 4))
  349. --mipsToSkip;
  350. width /= (1 << mipsToSkip);
  351. height /= (1 << mipsToSkip);
  352. SetNumLevels((unsigned)Max((int)(levels - mipsToSkip), 1));
  353. SetSize(width, height, format);
  354. for (unsigned i = 0; i < levels_ && i < levels - mipsToSkip; ++i)
  355. {
  356. CompressedLevel level = image->GetCompressedLevel(i + mipsToSkip);
  357. if (!needDecompress)
  358. {
  359. SetData(i, 0, 0, level.width_, level.height_, level.data_);
  360. memoryUse += level.rows_ * level.rowSize_;
  361. }
  362. else
  363. {
  364. unsigned char* rgbaData = new unsigned char[level.width_ * level.height_ * 4];
  365. level.Decompress(rgbaData);
  366. SetData(i, 0, 0, level.width_, level.height_, rgbaData);
  367. memoryUse += level.width_ * level.height_ * 4;
  368. delete[] rgbaData;
  369. }
  370. }
  371. }
  372. SetMemoryUse(memoryUse);
  373. return true;
  374. }
  375. bool Texture2D::GetData(unsigned level, void* dest) const
  376. {
  377. if (!object_)
  378. {
  379. LOGERROR("No texture created, can not get data");
  380. return false;
  381. }
  382. if (!dest)
  383. {
  384. LOGERROR("Null destination for getting data");
  385. return false;
  386. }
  387. if (level >= levels_)
  388. {
  389. LOGERROR("Illegal mip level for getting data");
  390. return false;
  391. }
  392. if (graphics_->IsDeviceLost())
  393. {
  394. LOGWARNING("Getting texture data while device is lost");
  395. return false;
  396. }
  397. int levelWidth = GetLevelWidth(level);
  398. int levelHeight = GetLevelHeight(level);
  399. D3DLOCKED_RECT d3dLockedRect;
  400. RECT d3dRect;
  401. d3dRect.left = 0;
  402. d3dRect.top = 0;
  403. d3dRect.right = levelWidth;
  404. d3dRect.bottom = levelHeight;
  405. IDirect3DSurface9* offscreenSurface = 0;
  406. // Need to use a offscreen surface & GetRenderTargetData() for rendertargets
  407. if (renderSurface_)
  408. {
  409. if (level != 0)
  410. {
  411. LOGERROR("Can only get mip level 0 data from a rendertarget");
  412. return false;
  413. }
  414. IDirect3DDevice9* device = graphics_->GetImpl()->GetDevice();
  415. device->CreateOffscreenPlainSurface((UINT)width_, (UINT)height_, (D3DFORMAT)format_,
  416. D3DPOOL_SYSTEMMEM, &offscreenSurface, 0);
  417. if (!offscreenSurface)
  418. {
  419. LOGERROR("Could not create surface for getting rendertarget data");
  420. return false;
  421. }
  422. device->GetRenderTargetData((IDirect3DSurface9*)renderSurface_->GetSurface(), offscreenSurface);
  423. if (FAILED(offscreenSurface->LockRect(&d3dLockedRect, &d3dRect, D3DLOCK_READONLY)))
  424. {
  425. LOGERROR("Could not lock surface for getting rendertarget data");
  426. offscreenSurface->Release();
  427. return false;
  428. }
  429. }
  430. else
  431. {
  432. if (FAILED(((IDirect3DTexture9*)object_)->LockRect(level, &d3dLockedRect, &d3dRect, D3DLOCK_READONLY)))
  433. {
  434. LOGERROR("Could not lock texture");
  435. return false;
  436. }
  437. }
  438. int height = levelHeight;
  439. if (IsCompressed())
  440. height = (height + 3) >> 2;
  441. unsigned char* destPtr = (unsigned char*)dest;
  442. unsigned rowSize = GetRowDataSize(levelWidth);
  443. // GetRowDataSize() returns CPU-side (destination) data size, so need to convert for X8R8G8B8
  444. if (format_ == D3DFMT_X8R8G8B8)
  445. rowSize = rowSize / 3 * 4;
  446. // Perform conversion to RGB / RGBA as necessary
  447. switch (format_)
  448. {
  449. default:
  450. for (int i = 0; i < height; ++i)
  451. {
  452. unsigned char* src = (unsigned char*)d3dLockedRect.pBits + i * d3dLockedRect.Pitch;
  453. memcpy(destPtr, src, rowSize);
  454. destPtr += rowSize;
  455. }
  456. break;
  457. case D3DFMT_X8R8G8B8:
  458. for (int i = 0; i < height; ++i)
  459. {
  460. unsigned char* src = (unsigned char*)d3dLockedRect.pBits + i * d3dLockedRect.Pitch;
  461. for (int j = 0; j < levelWidth; ++j)
  462. {
  463. destPtr[2] = *src++;
  464. destPtr[1] = *src++;
  465. destPtr[0] = *src++;
  466. ++src;
  467. destPtr += 3;
  468. }
  469. }
  470. break;
  471. case D3DFMT_A8R8G8B8:
  472. for (int i = 0; i < height; ++i)
  473. {
  474. unsigned char* src = (unsigned char*)d3dLockedRect.pBits + i * d3dLockedRect.Pitch;
  475. for (int j = 0; j < levelWidth; ++j)
  476. {
  477. destPtr[2] = *src++;
  478. destPtr[1] = *src++;
  479. destPtr[0] = *src++;
  480. destPtr[3] = *src++;
  481. destPtr += 4;
  482. }
  483. }
  484. break;
  485. }
  486. if (offscreenSurface)
  487. {
  488. offscreenSurface->UnlockRect();
  489. offscreenSurface->Release();
  490. }
  491. else
  492. ((IDirect3DTexture9*)object_)->UnlockRect(level);
  493. return true;
  494. }
  495. bool Texture2D::Create()
  496. {
  497. Release();
  498. if (!graphics_ || !width_ || !height_)
  499. return false;
  500. if (graphics_->IsDeviceLost())
  501. {
  502. LOGWARNING("Texture creation while device is lost");
  503. return true;
  504. }
  505. IDirect3DDevice9* device = graphics_->GetImpl()->GetDevice();
  506. // If creating a depth-stencil texture, and it is not supported, create a depth-stencil surface instead
  507. if (usage_ & D3DUSAGE_DEPTHSTENCIL && !graphics_->GetImpl()->CheckFormatSupport((D3DFORMAT)format_, usage_, D3DRTYPE_TEXTURE))
  508. {
  509. if (!device || FAILED(device->CreateDepthStencilSurface(
  510. (UINT)width_,
  511. (UINT)height_,
  512. (D3DFORMAT)format_,
  513. D3DMULTISAMPLE_NONE,
  514. 0,
  515. FALSE,
  516. (IDirect3DSurface9**)&renderSurface_->surface_,
  517. 0)))
  518. {
  519. LOGERROR("Could not create depth-stencil surface");
  520. return false;
  521. }
  522. levels_ = 1;
  523. }
  524. else
  525. {
  526. HANDLE sharedHandle = 0;
  527. if (gpuShared_ && gpuSharedHandle_)
  528. sharedHandle = (HANDLE) gpuSharedHandle_;
  529. if (!device || FAILED(graphics_->GetImpl()->GetDevice()->CreateTexture(
  530. (UINT)width_,
  531. (UINT)height_,
  532. requestedLevels_,
  533. usage_,
  534. (D3DFORMAT)format_,
  535. (D3DPOOL)pool_,
  536. (IDirect3DTexture9**)&object_,
  537. gpuShared_ ? &sharedHandle : 0 )))
  538. {
  539. LOGERROR("Could not create texture");
  540. return false;
  541. }
  542. gpuSharedHandle_ = (void*) sharedHandle;
  543. levels_ = ((IDirect3DTexture9*)object_)->GetLevelCount();
  544. if (usage_ & (D3DUSAGE_RENDERTARGET | D3DUSAGE_DEPTHSTENCIL))
  545. ((IDirect3DTexture9*)object_)->GetSurfaceLevel(0, (IDirect3DSurface9**)&renderSurface_->surface_);
  546. }
  547. return true;
  548. }
  549. void Texture2D::HandleRenderSurfaceUpdate(StringHash eventType, VariantMap& eventData)
  550. {
  551. if (renderSurface_ && renderSurface_->GetUpdateMode() == SURFACE_UPDATEALWAYS)
  552. renderSurface_->QueueUpdate();
  553. }
  554. }