D3D9TextureCube.cpp 19 KB

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