D3D9Texture2D.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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 "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_ || dataPending_)
  77. {
  78. // If has a resource file, reload through the resource cache. Otherwise just recreate.
  79. ResourceCache* cache = GetSubsystem<ResourceCache>();
  80. if (cache->Exists(GetName()))
  81. dataLost_ = !cache->ReloadResource(this);
  82. if (!object_)
  83. {
  84. Create();
  85. dataLost_ = true;
  86. }
  87. }
  88. dataPending_ = false;
  89. }
  90. void Texture2D::Release()
  91. {
  92. if (object_)
  93. {
  94. if (!graphics_)
  95. return;
  96. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  97. {
  98. if (graphics_->GetTexture(i) == this)
  99. graphics_->SetTexture(i, 0);
  100. }
  101. if (renderSurface_)
  102. renderSurface_->Release();
  103. ((IDirect3DTexture9*)object_)->Release();
  104. object_ = 0;
  105. }
  106. else
  107. {
  108. if (renderSurface_)
  109. renderSurface_->Release();
  110. }
  111. }
  112. bool Texture2D::SetSize(int width, int height, unsigned format, TextureUsage usage)
  113. {
  114. // Delete the old rendersurface if any
  115. renderSurface_.Reset();
  116. pool_ = D3DPOOL_MANAGED;
  117. usage_ = 0;
  118. if (usage == TEXTURE_RENDERTARGET || usage == TEXTURE_DEPTHSTENCIL)
  119. {
  120. renderSurface_ = new RenderSurface(this);
  121. if (usage == TEXTURE_RENDERTARGET)
  122. usage_ |= D3DUSAGE_RENDERTARGET;
  123. else
  124. usage_ |= D3DUSAGE_DEPTHSTENCIL;
  125. pool_ = D3DPOOL_DEFAULT;
  126. // Clamp mode addressing by default, nearest filtering, and mipmaps disabled
  127. addressMode_[COORD_U] = ADDRESS_CLAMP;
  128. addressMode_[COORD_V] = ADDRESS_CLAMP;
  129. filterMode_ = FILTER_NEAREST;
  130. requestedLevels_ = 1;
  131. }
  132. else if (usage == TEXTURE_DYNAMIC)
  133. {
  134. usage_ |= D3DUSAGE_DYNAMIC;
  135. pool_ = D3DPOOL_DEFAULT;
  136. }
  137. if (usage == TEXTURE_RENDERTARGET)
  138. SubscribeToEvent(E_RENDERSURFACEUPDATE, HANDLER(Texture2D, HandleRenderSurfaceUpdate));
  139. else
  140. UnsubscribeFromEvent(E_RENDERSURFACEUPDATE);
  141. width_ = width;
  142. height_ = height;
  143. format_ = format;
  144. return Create();
  145. }
  146. bool Texture2D::SetData(unsigned level, int x, int y, int width, int height, const void* data)
  147. {
  148. if (!object_)
  149. {
  150. LOGERROR("No texture created, can not set data");
  151. return false;
  152. }
  153. if (!data)
  154. {
  155. LOGERROR("Null source for setting data");
  156. return false;
  157. }
  158. if (level >= levels_)
  159. {
  160. LOGERROR("Illegal mip level for setting data");
  161. return false;
  162. }
  163. if (graphics_->IsDeviceLost())
  164. {
  165. LOGWARNING("Texture data assignment while device is lost");
  166. dataPending_ = true;
  167. return true;
  168. }
  169. if (IsCompressed())
  170. {
  171. x &= ~3;
  172. y &= ~3;
  173. }
  174. int levelWidth = GetLevelWidth(level);
  175. int levelHeight = GetLevelHeight(level);
  176. if (x < 0 || x + width > levelWidth || y < 0 || y + height > levelHeight || width <= 0 || height <= 0)
  177. {
  178. LOGERROR("Illegal dimensions for setting data");
  179. return false;
  180. }
  181. D3DLOCKED_RECT d3dLockedRect;
  182. RECT d3dRect;
  183. d3dRect.left = x;
  184. d3dRect.top = y;
  185. d3dRect.right = x + width;
  186. d3dRect.bottom = y + height;
  187. DWORD flags = 0;
  188. if (level == 0 && x == 0 && y == 0 && width == levelWidth && height == levelHeight && pool_ == D3DPOOL_DEFAULT)
  189. flags |= D3DLOCK_DISCARD;
  190. if (FAILED(((IDirect3DTexture9*)object_)->LockRect(level, &d3dLockedRect, (flags & 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. ((IDirect3DTexture9*)object_)->UnlockRect(level);
  240. return true;
  241. }
  242. bool Texture2D::Load(SharedPtr<Image> image, bool useAlpha)
  243. {
  244. if (!image)
  245. {
  246. LOGERROR("Null image, can not load texture");
  247. return false;
  248. }
  249. unsigned memoryUse = sizeof(Texture2D);
  250. int quality = QUALITY_HIGH;
  251. Renderer* renderer = GetSubsystem<Renderer>();
  252. if (renderer)
  253. quality = renderer->GetTextureQuality();
  254. if (!image->IsCompressed())
  255. {
  256. unsigned char* levelData = image->GetData();
  257. int levelWidth = image->GetWidth();
  258. int levelHeight = image->GetHeight();
  259. unsigned components = image->GetComponents();
  260. unsigned format = 0;
  261. // Discard unnecessary mip levels
  262. for (unsigned i = 0; i < mipsToSkip_[quality]; ++i)
  263. {
  264. image = image->GetNextLevel();
  265. levelData = image->GetData();
  266. levelWidth = image->GetWidth();
  267. levelHeight = image->GetHeight();
  268. }
  269. switch (components)
  270. {
  271. case 1:
  272. format = useAlpha ? Graphics::GetAlphaFormat() : Graphics::GetLuminanceFormat();
  273. break;
  274. case 2:
  275. format = Graphics::GetLuminanceAlphaFormat();
  276. break;
  277. case 3:
  278. format = Graphics::GetRGBFormat();
  279. break;
  280. case 4:
  281. format = Graphics::GetRGBAFormat();
  282. break;
  283. }
  284. // If image was previously compressed, reset number of requested levels to avoid error if level count is too high for new size
  285. if (IsCompressed() && requestedLevels_ > 1)
  286. requestedLevels_ = 0;
  287. SetSize(levelWidth, levelHeight, format);
  288. for (unsigned i = 0; i < levels_; ++i)
  289. {
  290. SetData(i, 0, 0, levelWidth, levelHeight, levelData);
  291. memoryUse += levelWidth * levelHeight * components;
  292. if (i < levels_ - 1)
  293. {
  294. image = image->GetNextLevel();
  295. levelData = image->GetData();
  296. levelWidth = image->GetWidth();
  297. levelHeight = image->GetHeight();
  298. }
  299. }
  300. }
  301. else
  302. {
  303. int width = image->GetWidth();
  304. int height = image->GetHeight();
  305. unsigned levels = image->GetNumCompressedLevels();
  306. unsigned format = graphics_->GetFormat(image->GetCompressedFormat());
  307. bool needDecompress = false;
  308. if (!format)
  309. {
  310. format = Graphics::GetRGBAFormat();
  311. needDecompress = true;
  312. }
  313. unsigned mipsToSkip = mipsToSkip_[quality];
  314. if (mipsToSkip >= levels)
  315. mipsToSkip = levels - 1;
  316. while (mipsToSkip && (width / (1 << mipsToSkip) < 4 || height / (1 << mipsToSkip) < 4))
  317. --mipsToSkip;
  318. width /= (1 << mipsToSkip);
  319. height /= (1 << mipsToSkip);
  320. SetNumLevels(Max((int)(levels - mipsToSkip), 1));
  321. SetSize(width, height, format);
  322. for (unsigned i = 0; i < levels_ && i < levels - mipsToSkip; ++i)
  323. {
  324. CompressedLevel level = image->GetCompressedLevel(i + mipsToSkip);
  325. if (!needDecompress)
  326. {
  327. SetData(i, 0, 0, level.width_, level.height_, level.data_);
  328. memoryUse += level.rows_ * level.rowSize_;
  329. }
  330. else
  331. {
  332. unsigned char* rgbaData = new unsigned char[level.width_ * level.height_ * 4];
  333. level.Decompress(rgbaData);
  334. SetData(i, 0, 0, level.width_, level.height_, rgbaData);
  335. memoryUse += level.width_ * level.height_ * 4;
  336. delete[] rgbaData;
  337. }
  338. }
  339. }
  340. SetMemoryUse(memoryUse);
  341. return true;
  342. }
  343. bool Texture2D::GetData(unsigned level, void* dest) const
  344. {
  345. if (!object_)
  346. {
  347. LOGERROR("No texture created, can not get data");
  348. return false;
  349. }
  350. if (!dest)
  351. {
  352. LOGERROR("Null destination for getting data");
  353. return false;
  354. }
  355. if (level >= levels_)
  356. {
  357. LOGERROR("Illegal mip level for getting data");
  358. return false;
  359. }
  360. if (graphics_->IsDeviceLost())
  361. {
  362. LOGWARNING("Getting texture data while device is lost");
  363. return false;
  364. }
  365. int levelWidth = GetLevelWidth(level);
  366. int levelHeight = GetLevelHeight(level);
  367. D3DLOCKED_RECT d3dLockedRect;
  368. RECT d3dRect;
  369. d3dRect.left = 0;
  370. d3dRect.top = 0;
  371. d3dRect.right = levelWidth;
  372. d3dRect.bottom = levelHeight;
  373. if (FAILED(((IDirect3DTexture9*)object_)->LockRect(level, &d3dLockedRect, &d3dRect, D3DLOCK_READONLY)))
  374. {
  375. LOGERROR("Could not lock texture");
  376. return false;
  377. }
  378. int height = levelHeight;
  379. if (IsCompressed())
  380. height = (height + 3) >> 2;
  381. unsigned char* destPtr = (unsigned char*)dest;
  382. unsigned rowSize = GetRowDataSize(levelWidth);
  383. // GetRowDataSize() returns CPU-side (destination) data size, so need to convert for X8R8G8B8
  384. if (format_ == D3DFMT_X8R8G8B8)
  385. rowSize = rowSize / 3 * 4;
  386. // Perform conversion to RGB / RGBA as necessary
  387. switch (format_)
  388. {
  389. default:
  390. for (int i = 0; i < height; ++i)
  391. {
  392. unsigned char* src = (unsigned char*)d3dLockedRect.pBits + i * d3dLockedRect.Pitch;
  393. memcpy(destPtr, src, rowSize);
  394. destPtr += rowSize;
  395. }
  396. break;
  397. case D3DFMT_X8R8G8B8:
  398. for (int i = 0; i < height; ++i)
  399. {
  400. unsigned char* src = (unsigned char*)d3dLockedRect.pBits + i * d3dLockedRect.Pitch;
  401. for (int j = 0; j < levelWidth; ++j)
  402. {
  403. destPtr[2] = *src++; destPtr[1] = *src++; destPtr[0] = *src++; ++src;
  404. destPtr += 3;
  405. }
  406. }
  407. break;
  408. case D3DFMT_A8R8G8B8:
  409. for (int i = 0; i < height; ++i)
  410. {
  411. unsigned char* src = (unsigned char*)d3dLockedRect.pBits + i * d3dLockedRect.Pitch;
  412. for (int j = 0; j < levelWidth; ++j)
  413. {
  414. destPtr[2] = *src++; destPtr[1] = *src++; destPtr[0] = *src++; destPtr[3] = *src++;
  415. destPtr += 4;
  416. }
  417. }
  418. break;
  419. }
  420. ((IDirect3DTexture9*)object_)->UnlockRect(level);
  421. return true;
  422. }
  423. bool Texture2D::Create()
  424. {
  425. Release();
  426. if (!graphics_ || !width_ || !height_)
  427. return false;
  428. if (graphics_->IsDeviceLost())
  429. {
  430. LOGWARNING("Texture creation while device is lost");
  431. return true;
  432. }
  433. IDirect3DDevice9* device = graphics_->GetImpl()->GetDevice();
  434. // If creating a depth-stencil texture, and it is not supported, create a depth-stencil surface instead
  435. if (usage_ & D3DUSAGE_DEPTHSTENCIL && !graphics_->GetImpl()->CheckFormatSupport((D3DFORMAT)format_, usage_, D3DRTYPE_TEXTURE))
  436. {
  437. if (!device || FAILED(device->CreateDepthStencilSurface(
  438. width_,
  439. height_,
  440. (D3DFORMAT)format_,
  441. D3DMULTISAMPLE_NONE,
  442. 0,
  443. FALSE,
  444. (IDirect3DSurface9**)&renderSurface_->surface_,
  445. 0)))
  446. {
  447. LOGERROR("Could not create depth-stencil surface");
  448. return false;
  449. }
  450. levels_ = 1;
  451. }
  452. else
  453. {
  454. if (!device || FAILED(graphics_->GetImpl()->GetDevice()->CreateTexture(
  455. width_,
  456. height_,
  457. requestedLevels_,
  458. usage_,
  459. (D3DFORMAT)format_,
  460. (D3DPOOL)pool_,
  461. (IDirect3DTexture9**)&object_,
  462. 0)))
  463. {
  464. LOGERROR("Could not create texture");
  465. return false;
  466. }
  467. levels_ = ((IDirect3DTexture9*)object_)->GetLevelCount();
  468. if (usage_ & (D3DUSAGE_RENDERTARGET | D3DUSAGE_DEPTHSTENCIL))
  469. ((IDirect3DTexture9*)object_)->GetSurfaceLevel(0, (IDirect3DSurface9**)&renderSurface_->surface_);
  470. }
  471. return true;
  472. }
  473. void Texture2D::HandleRenderSurfaceUpdate(StringHash eventType, VariantMap& eventData)
  474. {
  475. if (renderSurface_ && renderSurface_->GetUpdateMode() == SURFACE_UPDATEALWAYS)
  476. renderSurface_->QueueUpdate();
  477. }
  478. }