D3D9TextureCube.cpp 19 KB

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