D3D9TextureCube.cpp 19 KB

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