OGLTexture3D.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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 "Texture3D.h"
  33. #include "XMLFile.h"
  34. #include "DebugNew.h"
  35. namespace Urho3D
  36. {
  37. Texture3D::Texture3D(Context* context) :
  38. Texture(context)
  39. {
  40. #ifndef GL_ES_VERSION_2_0
  41. target_ = GL_TEXTURE_3D;
  42. #else
  43. target_ = 0;
  44. #endif
  45. }
  46. Texture3D::~Texture3D()
  47. {
  48. Release();
  49. }
  50. void Texture3D::RegisterObject(Context* context)
  51. {
  52. context->RegisterFactory<Texture3D>();
  53. }
  54. bool Texture3D::Load(Deserializer& source)
  55. {
  56. PROFILE(LoadTexture3D);
  57. // In headless mode, do not actually load the texture, just return success
  58. if (!graphics_)
  59. return true;
  60. // If device is lost, retry later
  61. if (graphics_->IsDeviceLost())
  62. {
  63. LOGWARNING("Texture load while device is lost");
  64. dataPending_ = true;
  65. return true;
  66. }
  67. // If over the texture budget, see if materials can be freed to allow textures to be freed
  68. CheckTextureBudget(GetTypeStatic());
  69. // Before actually loading the texture, get optional parameters from an XML description file
  70. LoadParameters();
  71. String texPath, texName, texExt;
  72. SplitPath(GetName(), texPath, texName, texExt);
  73. SharedPtr<XMLFile> xml(new XMLFile(context_));
  74. if (!xml->Load(source))
  75. return false;
  76. XMLElement textureElem = xml->GetRoot();
  77. XMLElement volumeElem = textureElem.GetChild("volume");
  78. XMLElement colorlutElem = textureElem.GetChild("colorlut");
  79. if (volumeElem)
  80. {
  81. String name = volumeElem.GetAttribute("name");
  82. String volumeTexPath, volumeTexName, volumeTexExt;
  83. SplitPath(name, volumeTexPath, volumeTexName, volumeTexExt);
  84. // If path is empty, add the XML file path
  85. if (volumeTexPath.Empty())
  86. name = texPath + name;
  87. SharedPtr<Image> image(GetSubsystem<ResourceCache>()->GetResource<Image>(name));
  88. return Load(image);
  89. }
  90. else if (colorlutElem)
  91. {
  92. String name = colorlutElem.GetAttribute("name");
  93. String colorlutTexPath, colorlutTexName, colorlutTexExt;
  94. SplitPath(name, colorlutTexPath, colorlutTexName, colorlutTexExt);
  95. // If path is empty, add the XML file path
  96. if (colorlutTexPath.Empty())
  97. name = texPath + name;
  98. SharedPtr<File> file = GetSubsystem<ResourceCache>()->GetFile(name);
  99. SharedPtr<Image> image(new Image(context_));
  100. if (!image->LoadColorLUT(*(file.Get())))
  101. return false;
  102. return Load(image);
  103. }
  104. return false;
  105. }
  106. void Texture3D::OnDeviceLost()
  107. {
  108. GPUObject::OnDeviceLost();
  109. if (renderSurface_)
  110. renderSurface_->OnDeviceLost();
  111. }
  112. void Texture3D::OnDeviceReset()
  113. {
  114. // If has a file name, reload through the resource cache. Otherwise just recreate.
  115. if (!object_)
  116. {
  117. if (!GetName().Trimmed().Empty())
  118. dataLost_ = !GetSubsystem<ResourceCache>()->ReloadResource(this);
  119. else
  120. {
  121. Create();
  122. dataLost_ = true;
  123. }
  124. }
  125. else if (dataPending_)
  126. {
  127. if (!GetName().Trimmed().Empty())
  128. dataLost_ = !GetSubsystem<ResourceCache>()->ReloadResource(this);
  129. else
  130. dataLost_ = true;
  131. }
  132. dataPending_ = false;
  133. }
  134. void Texture3D::Release()
  135. {
  136. if (object_)
  137. {
  138. if (!graphics_ || graphics_->IsDeviceLost())
  139. return;
  140. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  141. {
  142. if (graphics_->GetTexture(i) == this)
  143. graphics_->SetTexture(i, 0);
  144. }
  145. if (renderSurface_)
  146. renderSurface_->Release();
  147. glDeleteTextures(1, &object_);
  148. object_ = 0;
  149. }
  150. else
  151. {
  152. if (renderSurface_)
  153. renderSurface_->Release();
  154. }
  155. }
  156. bool Texture3D::SetSize(int width, int height, int depth, unsigned format, TextureUsage usage)
  157. {
  158. // Delete the old rendersurface if any
  159. renderSurface_.Reset();
  160. usage_ = usage;
  161. if (usage >= TEXTURE_RENDERTARGET)
  162. {
  163. renderSurface_ = new RenderSurface(this);
  164. // Clamp mode addressing by default, nearest filtering, and mipmaps disabled
  165. addressMode_[COORD_U] = ADDRESS_CLAMP;
  166. addressMode_[COORD_V] = ADDRESS_CLAMP;
  167. filterMode_ = FILTER_NEAREST;
  168. requestedLevels_ = 1;
  169. }
  170. if (usage == TEXTURE_RENDERTARGET)
  171. SubscribeToEvent(E_RENDERSURFACEUPDATE, HANDLER(Texture3D, HandleRenderSurfaceUpdate));
  172. else
  173. UnsubscribeFromEvent(E_RENDERSURFACEUPDATE);
  174. width_ = width;
  175. height_ = height;
  176. depth_ = depth;
  177. format_ = format;
  178. return Create();
  179. }
  180. bool Texture3D::SetData(unsigned level, int x, int y, int z, int width, int height, int depth, const void* data)
  181. {
  182. if (!object_ || !graphics_)
  183. {
  184. LOGERROR("No texture created, can not set data");
  185. return false;
  186. }
  187. if (!data)
  188. {
  189. LOGERROR("Null source for setting data");
  190. return false;
  191. }
  192. if (level >= levels_)
  193. {
  194. LOGERROR("Illegal mip level for setting data");
  195. return false;
  196. }
  197. if (graphics_->IsDeviceLost())
  198. {
  199. LOGWARNING("Texture data assignment while device is lost");
  200. dataPending_ = true;
  201. return true;
  202. }
  203. if (IsCompressed())
  204. {
  205. x &= ~3;
  206. y &= ~3;
  207. }
  208. int levelWidth = GetLevelWidth(level);
  209. int levelHeight = GetLevelHeight(level);
  210. int levelDepth = GetLevelDepth(level);
  211. if (x < 0 || x + width > levelWidth || y < 0 || y + height > levelHeight || z < 0 || z + depth > levelDepth || width <= 0 || height <= 0 || depth <= 0)
  212. {
  213. LOGERROR("Illegal dimensions for setting data");
  214. return false;
  215. }
  216. graphics_->SetTextureForUpdate(this);
  217. bool wholeLevel = x == 0 && y == 0 && z == 0 && width == levelWidth && height == levelHeight && depth == levelDepth;
  218. unsigned format = GetSRGB() ? GetSRGBFormat(format_) : format_;
  219. #ifndef GL_ES_VERSION_2_0
  220. if (!IsCompressed())
  221. {
  222. if (wholeLevel)
  223. glTexImage3D(target_, level, format, width, height, depth, 0, GetExternalFormat(format_), GetDataType(format_), data);
  224. else
  225. glTexSubImage3D(target_, level, x, y, z, width, height, depth, GetExternalFormat(format_), GetDataType(format_), data);
  226. }
  227. else
  228. {
  229. if (wholeLevel)
  230. glCompressedTexImage3D(target_, level, format, width, height, depth, 0, GetDataSize(width, height, depth), data);
  231. else
  232. glCompressedTexSubImage3D(target_, level, x, y, z, width, height, depth, format, GetDataSize(width, height, depth), data);
  233. }
  234. #endif
  235. graphics_->SetTexture(0, 0);
  236. return true;
  237. }
  238. bool Texture3D::Load(SharedPtr<Image> image, bool useAlpha)
  239. {
  240. if (!image)
  241. {
  242. LOGERROR("Null image, can not load texture");
  243. return false;
  244. }
  245. unsigned memoryUse = sizeof(Texture3D);
  246. int quality = QUALITY_HIGH;
  247. Renderer* renderer = GetSubsystem<Renderer>();
  248. if (renderer)
  249. quality = renderer->GetTextureQuality();
  250. if (!image->IsCompressed())
  251. {
  252. unsigned char* levelData = image->GetData();
  253. int levelWidth = image->GetWidth();
  254. int levelHeight = image->GetHeight();
  255. int levelDepth = image->GetDepth();
  256. unsigned components = image->GetComponents();
  257. unsigned format = 0;
  258. // Discard unnecessary mip levels
  259. for (unsigned i = 0; i < mipsToSkip_[quality]; ++i)
  260. {
  261. image = image->GetNextLevel();
  262. levelData = image->GetData();
  263. levelWidth = image->GetWidth();
  264. levelHeight = image->GetHeight();
  265. levelDepth = image->GetDepth();
  266. }
  267. switch (components)
  268. {
  269. case 1:
  270. format = useAlpha ? Graphics::GetAlphaFormat() : Graphics::GetLuminanceFormat();
  271. break;
  272. case 2:
  273. format = Graphics::GetLuminanceAlphaFormat();
  274. break;
  275. case 3:
  276. format = Graphics::GetRGBFormat();
  277. break;
  278. case 4:
  279. format = Graphics::GetRGBAFormat();
  280. break;
  281. }
  282. // If image was previously compressed, reset number of requested levels to avoid error if level count is too high for new size
  283. if (IsCompressed() && requestedLevels_ > 1)
  284. requestedLevels_ = 0;
  285. SetSize(levelWidth, levelHeight, levelDepth, format);
  286. if (!object_)
  287. return false;
  288. for (unsigned i = 0; i < levels_; ++i)
  289. {
  290. SetData(i, 0, 0, 0, levelWidth, levelHeight, levelDepth, levelData);
  291. memoryUse += levelWidth * levelHeight * levelDepth * components;
  292. if (i < levels_ - 1)
  293. {
  294. image = image->GetNextLevel();
  295. levelData = image->GetData();
  296. levelWidth = image->GetWidth();
  297. levelHeight = image->GetHeight();
  298. levelDepth = image->GetDepth();
  299. }
  300. }
  301. }
  302. else
  303. {
  304. int width = image->GetWidth();
  305. int height = image->GetHeight();
  306. int depth = image->GetDepth();
  307. unsigned levels = image->GetNumCompressedLevels();
  308. unsigned format = graphics_->GetFormat(image->GetCompressedFormat());
  309. bool needDecompress = false;
  310. if (!format)
  311. {
  312. format = Graphics::GetRGBAFormat();
  313. needDecompress = true;
  314. }
  315. unsigned mipsToSkip = mipsToSkip_[quality];
  316. if (mipsToSkip >= levels)
  317. mipsToSkip = levels - 1;
  318. while (mipsToSkip && (width / (1 << mipsToSkip) < 4 || height / (1 << mipsToSkip) < 4 || depth / (1 << mipsToSkip) < 4))
  319. --mipsToSkip;
  320. width /= (1 << mipsToSkip);
  321. height /= (1 << mipsToSkip);
  322. depth /= (1 << mipsToSkip);
  323. SetNumLevels(Max((int)(levels - mipsToSkip), 1));
  324. SetSize(width, height, depth, 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, 0, level.width_, level.height_, level.depth_, level.data_);
  331. memoryUse += level.depth_ * level.rows_ * level.rowSize_;
  332. }
  333. else
  334. {
  335. unsigned char* rgbaData = new unsigned char[level.width_ * level.height_ * level.depth_ * 4];
  336. level.Decompress(rgbaData);
  337. SetData(i, 0, 0, 0, level.width_, level.height_, level.depth_, rgbaData);
  338. memoryUse += level.width_ * level.height_ * level.depth_ * 4;
  339. delete[] rgbaData;
  340. }
  341. }
  342. }
  343. SetMemoryUse(memoryUse);
  344. return true;
  345. }
  346. bool Texture3D::GetData(unsigned level, void* dest) const
  347. {
  348. #ifndef GL_ES_VERSION_2_0
  349. if (!object_ || !graphics_)
  350. {
  351. LOGERROR("No texture created, can not get data");
  352. return false;
  353. }
  354. if (!dest)
  355. {
  356. LOGERROR("Null destination for getting data");
  357. return false;
  358. }
  359. if (level >= levels_)
  360. {
  361. LOGERROR("Illegal mip level for getting data");
  362. return false;
  363. }
  364. if (graphics_->IsDeviceLost())
  365. {
  366. LOGWARNING("Getting texture data while device is lost");
  367. return false;
  368. }
  369. graphics_->SetTextureForUpdate(const_cast<Texture3D*>(this));
  370. if (!IsCompressed())
  371. glGetTexImage(target_, level, GetExternalFormat(format_), GetDataType(format_), dest);
  372. else
  373. glGetCompressedTexImage(target_, level, dest);
  374. graphics_->SetTexture(0, 0);
  375. return true;
  376. #else
  377. LOGERROR("Getting texture data not supported");
  378. return false;
  379. #endif
  380. }
  381. bool Texture3D::Create()
  382. {
  383. Release();
  384. #ifdef GL_ES_VERSION_2_0
  385. LOGERROR("Failed to create 3D texture, currently unsupported on OpenGL ES 2");
  386. return false;
  387. #else
  388. if (!graphics_ || !width_ || !height_ || !depth_)
  389. return false;
  390. if (graphics_->IsDeviceLost())
  391. {
  392. LOGWARNING("Texture creation while device is lost");
  393. return true;
  394. }
  395. unsigned format = GetSRGB() ? GetSRGBFormat(format_) : format_;
  396. unsigned externalFormat = GetExternalFormat(format_);
  397. unsigned dataType = GetDataType(format_);
  398. glGenTextures(1, &object_);
  399. // Ensure that our texture is bound to OpenGL texture unit 0
  400. graphics_->SetTextureForUpdate(this);
  401. // If not compressed, create the initial level 0 texture with null data
  402. bool success = true;
  403. if (!IsCompressed())
  404. {
  405. glGetError();
  406. glTexImage3D(target_, 0, format, width_, height_, depth_, 0, externalFormat, dataType, 0);
  407. if (glGetError())
  408. {
  409. LOGERROR("Failed to create texture");
  410. success = false;
  411. }
  412. }
  413. // Set mipmapping
  414. levels_ = requestedLevels_;
  415. if (!levels_)
  416. {
  417. unsigned maxSize = Max(Max((int)width_, (int)height_), (int)depth_);
  418. while (maxSize)
  419. {
  420. maxSize >>= 1;
  421. ++levels_;
  422. }
  423. }
  424. glTexParameteri(target_, GL_TEXTURE_BASE_LEVEL, 0);
  425. glTexParameteri(target_, GL_TEXTURE_MAX_LEVEL, levels_ - 1);
  426. // Set initial parameters, then unbind the texture
  427. UpdateParameters();
  428. graphics_->SetTexture(0, 0);
  429. return success;
  430. #endif
  431. }
  432. void Texture3D::HandleRenderSurfaceUpdate(StringHash eventType, VariantMap& eventData)
  433. {
  434. if (renderSurface_ && renderSurface_->GetUpdateMode() == SURFACE_UPDATEALWAYS)
  435. renderSurface_->QueueUpdate();
  436. }
  437. }