D3D9Texture2D.cpp 16 KB

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