llimagegl.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533
  1. /**
  2. * @file llimagegl.cpp
  3. * @brief Generic GL image handler
  4. *
  5. * $LicenseInfo:firstyear=2001&license=viewergpl$
  6. *
  7. * Copyright (c) 2001-2009, Linden Research, Inc.
  8. *
  9. * Second Life Viewer Source Code
  10. * The source code in this file ("Source Code") is provided by Linden Lab
  11. * to you under the terms of the GNU General Public License, version 2.0
  12. * ("GPL"), unless you have obtained a separate licensing agreement
  13. * ("Other License"), formally executed by you and Linden Lab. Terms of
  14. * the GPL can be found in doc/GPL-license.txt in this distribution, or
  15. * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
  16. *
  17. * There are special exceptions to the terms and conditions of the GPL as
  18. * it is applied to this Source Code. View the full text of the exception
  19. * in the file doc/FLOSS-exception.txt in this software distribution, or
  20. * online at
  21. * http://secondlifegrid.net/programs/open_source/licensing/flossexception
  22. *
  23. * By copying, modifying or distributing this software, you acknowledge
  24. * that you have read and understood your obligations described above,
  25. * and agree to abide by those obligations.
  26. *
  27. * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
  28. * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
  29. * COMPLETENESS OR PERFORMANCE.
  30. * $/LicenseInfo$
  31. */
  32. #include "linden_common.h"
  33. #include "llimagegl.h"
  34. #include "llglslshader.h"
  35. #include "llgltexture.h"
  36. #include "llimage.h"
  37. #include "llmath.h"
  38. #include "llsys.h" // For LLCPUInfo
  39. #include "lltimer.h" // For ms_sleep()
  40. #include "hbtracy.h"
  41. #include "llvertexbuffer.h" // For wpo2()
  42. #include "llwindow.h"
  43. #define FIX_MASKS 1
  44. // Static members
  45. U32 LLImageGL::sUniqueCount = 0;
  46. U32 LLImageGL::sBindCount = 0;
  47. LLAtomicS64 LLImageGL::sGlobalTexMemBytes(0);
  48. std::vector<U32> LLImageGL::sFreeList[4];
  49. U32 LLImageGL::sCurrentFrame = 0;
  50. S64 LLImageGL::sBoundTexMemBytes = 0;
  51. S32 LLImageGL::sCount = 0;
  52. bool LLImageGL::sGlobalUseAnisotropic = false;
  53. bool LLImageGL::sPreserveDiscard = false;
  54. bool LLImageGL::sCompressTextures = false;
  55. bool LLImageGL::sSetSubImagePerLine = false;
  56. bool LLImageGL::sSyncInThread = true;
  57. bool LLImageGL::sDelayedTextureDelete = false;
  58. U32 LLImageGL::sCompressThreshold = 262144U;
  59. F32 LLImageGL::sLastFrameTime = 0.f;
  60. LLImageGL* LLImageGL::sDefaultGLImagep = NULL;
  61. LLImageGL::glimage_list_t LLImageGL::sImageList;
  62. LLImageGLThread* LLImageGL::sThread = NULL;
  63. constexpr S8 INVALID_OFFSET = -99;
  64. constexpr F32 STALE_IMAGES_TIMEOUT = 10.f;
  65. ///////////////////////////////////////////////////////////////////////////////
  66. // Helper functions to track bound GL textures allocations.
  67. static LLMutex sTexMemMutex;
  68. typedef flat_hmap<U32, S64> alloc_map_t;
  69. static alloc_map_t sTextureAllocs;
  70. static LLAtomicS64 sCurBoundTexBytes(0);
  71. void image_bound(U32 width, U32 height, U32 pixformat, U32 count = 1,
  72. U32 tex_name = 0)
  73. {
  74. if (!tex_name)
  75. {
  76. tex_name =
  77. gGL.getTexUnit(gGL.getCurrentTexUnitIndex())->getCurrTexture();
  78. }
  79. if (!tex_name)
  80. {
  81. return;
  82. }
  83. S64 new_size = S64(count) *
  84. LLImageGL::dataFormatBytes(pixformat, width, height);
  85. S64 old_size = 0;
  86. sTexMemMutex.lock();
  87. alloc_map_t::iterator it = sTextureAllocs.find(tex_name);
  88. if (it == sTextureAllocs.end())
  89. {
  90. sTextureAllocs[tex_name] = new_size;
  91. }
  92. else
  93. {
  94. old_size = it->second;
  95. it->second = new_size;
  96. }
  97. sCurBoundTexBytes += new_size - old_size;
  98. sTexMemMutex.unlock();
  99. }
  100. void image_unbound(U32 tex_name)
  101. {
  102. if (tex_name)
  103. {
  104. S64 size = 0;
  105. sTexMemMutex.lock();
  106. alloc_map_t::iterator it = sTextureAllocs.find(tex_name);
  107. if (it != sTextureAllocs.end())
  108. {
  109. size = it->second;
  110. sTextureAllocs.erase(it);
  111. }
  112. sCurBoundTexBytes -= size;
  113. sTexMemMutex.unlock();
  114. }
  115. }
  116. ///////////////////////////////////////////////////////////////////////////////
  117. //static
  118. U32 LLImageGL::dataFormatBits(S32 dataformat)
  119. {
  120. switch (dataformat)
  121. {
  122. case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: return 4;
  123. case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: return 4;
  124. case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: return 8;
  125. case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: return 8;
  126. case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: return 8;
  127. case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: return 8;
  128. case GL_LUMINANCE: return 8;
  129. case GL_ALPHA: return 8;
  130. case GL_COLOR_INDEX: return 8;
  131. case GL_LUMINANCE_ALPHA: return 16;
  132. case GL_RED: return 8;
  133. case GL_RG: return 16;
  134. case GL_RGB: return 24;
  135. case GL_SRGB: return 24;
  136. case GL_RGB8: return 24;
  137. case GL_RGB16F: return 48;
  138. case GL_RGBA: return 32;
  139. case GL_RGBA8: return 32;
  140. case GL_RGBA16F: return 64;
  141. case GL_SRGB_ALPHA: return 32;
  142. // Used for QuickTime media textures on the Mac:
  143. case GL_BGRA: return 32;
  144. case GL_DEPTH_COMPONENT: return 24;
  145. default:
  146. llerrs << "Unknown format: " << dataformat << llendl;
  147. return 0;
  148. }
  149. }
  150. //static
  151. S64 LLImageGL::dataFormatBytes(S32 dataformat, U32 width, U32 height)
  152. {
  153. if (width < 4 || height < 4)
  154. {
  155. if (dataformat == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT ||
  156. dataformat == GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT ||
  157. dataformat == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT ||
  158. dataformat == GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT ||
  159. dataformat == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT ||
  160. dataformat == GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT)
  161. {
  162. width = llmax(width, 4);
  163. height = llmax(height, 4);
  164. }
  165. }
  166. S64 bytes = ((S64)width * (S64)height *
  167. (S64)dataFormatBits(dataformat) + 7) >> 3;
  168. return (bytes + 3) & ~3L; // Keep it a multiple of 4 bytes
  169. }
  170. //static
  171. U32 LLImageGL::dataFormatComponents(S32 dataformat)
  172. {
  173. switch (dataformat)
  174. {
  175. case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: return 3;
  176. case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: return 3;
  177. case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: return 4;
  178. case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: return 4;
  179. case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: return 4;
  180. case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: return 4;
  181. case GL_LUMINANCE: return 1;
  182. case GL_ALPHA: return 1;
  183. case GL_COLOR_INDEX: return 1;
  184. case GL_LUMINANCE_ALPHA: return 2;
  185. case GL_RED: return 1;
  186. case GL_RG: return 2;
  187. case GL_RGB: return 3;
  188. case GL_SRGB: return 3;
  189. case GL_RGBA: return 4;
  190. case GL_SRGB_ALPHA: return 4;
  191. // Used for QuickTime media textures on the Mac
  192. case GL_BGRA: return 4;
  193. default:
  194. llerrs << "Unknown format: " << dataformat << llendl;
  195. return 0;
  196. }
  197. }
  198. bool LLImageGL::isCompressed() const
  199. {
  200. switch (mFormatPrimary)
  201. {
  202. case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
  203. case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:
  204. case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:
  205. case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT:
  206. case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
  207. case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:
  208. return true;
  209. default:
  210. return false;
  211. }
  212. }
  213. //static
  214. void LLImageGL::destroyGL(bool save_state)
  215. {
  216. // Release all textures pending for deletion. HB
  217. freeDeletedTextures(true);
  218. for (S32 stage = 0; stage < gGLManager.mNumTextureImageUnits; ++stage)
  219. {
  220. gGL.getTexUnit(stage)->unbind(LLTexUnit::TT_TEXTURE);
  221. }
  222. for (glimage_list_t::iterator iter = sImageList.begin(),
  223. end = sImageList.end();
  224. iter != end; ++iter)
  225. {
  226. LLImageGL* imagep = *iter;
  227. imagep->syncTexName();
  228. if (imagep->mTexName)
  229. {
  230. if (save_state && imagep->isGLTextureCreated() &&
  231. imagep->mComponents)
  232. {
  233. imagep->mSaveData = new LLImageRaw;
  234. if (!imagep->readBackRaw(imagep->mCurrentDiscardLevel,
  235. imagep->mSaveData, false))
  236. {
  237. imagep->mSaveData = NULL;
  238. }
  239. }
  240. imagep->destroyGLTexture();
  241. stop_glerror();
  242. }
  243. }
  244. }
  245. //static
  246. void LLImageGL::restoreGL()
  247. {
  248. for (glimage_list_t::iterator iter = sImageList.begin(),
  249. end = sImageList.end();
  250. iter != end; ++iter)
  251. {
  252. LLImageGL* imagep = *iter;
  253. if (imagep->getTexName())
  254. {
  255. llwarns << "Tex name is not 0." << llendl;
  256. }
  257. if (imagep->mSaveData.notNull())
  258. {
  259. if (imagep->getComponents() &&
  260. imagep->mSaveData->getComponents())
  261. {
  262. imagep->createGLTexture(imagep->mCurrentDiscardLevel,
  263. imagep->mSaveData, 0, true);
  264. stop_glerror();
  265. }
  266. imagep->mSaveData = NULL; // Deletes data
  267. }
  268. }
  269. }
  270. //static
  271. void LLImageGL::dirtyTexOptions()
  272. {
  273. for (glimage_list_t::iterator iter = sImageList.begin(),
  274. end = sImageList.end();
  275. iter != end; ++iter)
  276. {
  277. LLImageGL* imagep = *iter;
  278. imagep->mTexOptionsDirty = true;
  279. }
  280. }
  281. // This method is used to allow releasing old NO_DELETE fetched textures which
  282. // associated GL image have not been used for rendering in a while. It only
  283. // affects fetched textures, and not the ones that must be kept untouched or
  284. // the "manual"/local GL textures (UI textures, bump maps, map tiles, media
  285. // textures, preview textures, etc). Without a periodic call to this method,
  286. // the viewer "leaks" (keeps uselessly) GL textures around, which clobber the
  287. // RAM, and worst, the VRAM. HB
  288. //static
  289. U32 LLImageGL::activateStaleTextures()
  290. {
  291. U32 activated = 0;
  292. for (glimage_list_t::iterator iter = sImageList.begin(),
  293. end = sImageList.end();
  294. iter != end; ++iter)
  295. {
  296. LLImageGL* imagep = *iter;
  297. // If this image has been recently bound, then it is not a candidate.
  298. if (sLastFrameTime - imagep->mLastBindTime < STALE_IMAGES_TIMEOUT)
  299. {
  300. continue;
  301. }
  302. LLGLTexture* ownerp = imagep->getOwner();
  303. // We only care about fetched textures, i.e. the ones with an owner.
  304. if (!ownerp)
  305. {
  306. continue;
  307. }
  308. U32 boost_level = ownerp->getBoostLevel();
  309. // Do not touch avatar bakes, sculpties, UI, map, preview, bumps, media
  310. // textures...
  311. if (boost_level <= LLGLTexture::BOOST_SUPER_HIGH &&
  312. boost_level != LLGLTexture::BOOST_SCULPTED &&
  313. // And only textures in NO_DELETE state need to be re-ACTIVATEd
  314. ownerp->getTextureState() == LLGLTexture::NO_DELETE)
  315. {
  316. ownerp->forceActive();
  317. ++activated;
  318. }
  319. }
  320. return activated;
  321. }
  322. LLImageGL::LLImageGL(bool usemipmaps)
  323. : mOwnerp(NULL),
  324. mSaveData(NULL),
  325. mAutoGenMips(false)
  326. {
  327. init(usemipmaps);
  328. setSize(0, 0, 0);
  329. sImageList.insert(this);
  330. ++sCount;
  331. }
  332. LLImageGL::LLImageGL(U32 width, U32 height, U8 components, bool usemipmaps)
  333. : mOwnerp(NULL),
  334. mSaveData(NULL),
  335. mAutoGenMips(false)
  336. {
  337. llassert(components <= 4);
  338. init(usemipmaps);
  339. setSize(width, height, components);
  340. sImageList.insert(this);
  341. ++sCount;
  342. }
  343. LLImageGL::LLImageGL(const LLImageRaw* imagerawp, bool usemipmaps)
  344. : mOwnerp(NULL),
  345. mSaveData(NULL),
  346. mAutoGenMips(false)
  347. {
  348. init(usemipmaps);
  349. setSize(0, 0, 0);
  350. sImageList.insert(this);
  351. ++sCount;
  352. createGLTexture(0, imagerawp);
  353. }
  354. LLImageGL::LLImageGL(U32 tex_name, U32 components, U32 target,
  355. S32 internal_fmt, S32 primary_fmt, S32 format_type,
  356. LLTexUnit::eTextureAddressMode mode)
  357. : mOwnerp(NULL),
  358. mSaveData(NULL),
  359. mAutoGenMips(false)
  360. {
  361. init(false);
  362. mTexName = tex_name;
  363. mComponents = components;
  364. mTarget = target;
  365. mFormatInternal = internal_fmt;
  366. mFormatPrimary = primary_fmt;
  367. mFormatType = format_type;
  368. mAddressMode = mode;
  369. }
  370. LLImageGL::~LLImageGL()
  371. {
  372. syncTexName();
  373. sImageList.erase(this);
  374. --sCount;
  375. cleanup();
  376. }
  377. void LLImageGL::init(bool usemipmaps)
  378. {
  379. mNewTexName = 0;
  380. mTexNameDirty = false;
  381. mTexNameSync = 0;
  382. mTextureMemory = 0;
  383. mLastBindTime = 0.f;
  384. mPickMask = NULL;
  385. mPickMaskWidth = 0;
  386. mPickMaskHeight = 0;
  387. mUseMipMaps = usemipmaps;
  388. mHasExplicitFormat = false;
  389. mIsMask = false;
  390. #if FIX_MASKS
  391. mNeedsAlphaAndPickMask = false;
  392. mAlphaOffset = INVALID_OFFSET;
  393. #else
  394. mNeedsAlphaAndPickMask = true;
  395. mAlphaOffset = 0;
  396. #endif
  397. mAlphaStride = 0;
  398. mGLTextureCreated = false;
  399. mTexName = 0;
  400. mWidth = 0;
  401. mHeight = 0;
  402. mCurrentDiscardLevel = -1;
  403. mAllowCompression = true;
  404. mTarget = GL_TEXTURE_2D;
  405. mBindTarget = LLTexUnit::TT_TEXTURE;
  406. mHasMipMaps = false;
  407. mMipLevels = -1;
  408. mComponents = 0;
  409. mMaxDiscardLevel = MAX_DISCARD_LEVEL;
  410. mTexOptionsDirty = true;
  411. mAddressMode = LLTexUnit::TAM_WRAP;
  412. mFilterOption = LLTexUnit::TFO_ANISOTROPIC;
  413. mFormatInternal = -1;
  414. mFormatPrimary = 0;
  415. mFormatType = GL_UNSIGNED_BYTE;
  416. mFormatSwapBytes = false;
  417. }
  418. void LLImageGL::cleanup()
  419. {
  420. if (!gGLManager.mIsDisabled)
  421. {
  422. destroyGLTexture();
  423. }
  424. freePickMask();
  425. mSaveData = NULL; // Delete data
  426. }
  427. // Helper function used to check the size of a texture image. So dim should be
  428. // a positive number
  429. LL_INLINE static bool check_power_of_two(S32 dim)
  430. {
  431. return !dim || (dim > 0 && !(dim & (dim - 1)));
  432. }
  433. //static
  434. bool LLImageGL::checkSize(S32 width, S32 height)
  435. {
  436. return check_power_of_two(width) && check_power_of_two(height);
  437. }
  438. bool LLImageGL::setSize(U32 width, U32 height, U8 ncomponents,
  439. S32 discard_level)
  440. {
  441. if (width != mWidth || height != mHeight || ncomponents != mComponents)
  442. {
  443. // Check if dimensions are a power of two
  444. if (!checkSize(width, height))
  445. {
  446. llwarns << "Texture has non power of two dimension: " << width
  447. << "x" << height << ". Aborted." << llendl;
  448. return false;
  449. }
  450. // Pick mask validity depends on old image size, delete it
  451. freePickMask();
  452. mWidth = width;
  453. mHeight = height;
  454. mComponents = ncomponents;
  455. if (ncomponents > 0)
  456. {
  457. mMaxDiscardLevel = 0;
  458. while (width > 1 && height > 1 &&
  459. mMaxDiscardLevel < MAX_DISCARD_LEVEL)
  460. {
  461. ++mMaxDiscardLevel;
  462. width >>= 1;
  463. height >>= 1;
  464. }
  465. if (!sPreserveDiscard && discard_level > 0)
  466. {
  467. mMaxDiscardLevel = llmax(mMaxDiscardLevel, (S8)discard_level);
  468. }
  469. }
  470. else
  471. {
  472. mMaxDiscardLevel = MAX_DISCARD_LEVEL;
  473. }
  474. }
  475. return true;
  476. }
  477. //virtual
  478. void LLImageGL::dump()
  479. {
  480. llinfos << "mMaxDiscardLevel = " << S32(mMaxDiscardLevel)
  481. << " - mLastBindTime = " << mLastBindTime
  482. << " - mTarget = " << S32(mTarget)
  483. << " - mBindTarget = " << S32(mBindTarget)
  484. << " - mUseMipMaps = " << S32(mUseMipMaps)
  485. << " - mHasMipMaps = " << S32(mHasMipMaps)
  486. << " - mCurrentDiscardLevel = " << S32(mCurrentDiscardLevel)
  487. << " - mFormatInternal = " << S32(mFormatInternal)
  488. << " - mFormatPrimary = " << S32(mFormatPrimary)
  489. << " - mFormatType = " << S32(mFormatType)
  490. << " - mFormatSwapBytes = " << S32(mFormatSwapBytes)
  491. << " - mHasExplicitFormat = " << S32(mHasExplicitFormat)
  492. << " - mTextureMemory = " << mTextureMemory
  493. << " - mTexName = " << mTexName
  494. << llendl;
  495. }
  496. //static
  497. void LLImageGL::dumpStaleList()
  498. {
  499. U32 num_stale_images = 0;
  500. S64 total_stale_memory = 0;
  501. U32 num_scuplties = 0;
  502. S64 scuplties_memory = 0;
  503. for (glimage_list_t::iterator iter = sImageList.begin(),
  504. end = sImageList.end();
  505. iter != end; ++iter)
  506. {
  507. LLImageGL* imagep = *iter;
  508. if (sLastFrameTime - imagep->mLastBindTime < STALE_IMAGES_TIMEOUT)
  509. {
  510. continue;
  511. }
  512. LLGLTexture* ownerp = imagep->getOwner();
  513. U32 boost_level = ownerp ? ownerp->getBoostLevel() : 0;
  514. if (boost_level == LLGLTexture::BOOST_SCULPTED)
  515. {
  516. scuplties_memory += imagep->mTextureMemory;
  517. ++num_scuplties;
  518. }
  519. else if (boost_level <= LLGLTexture::BOOST_SUPER_HIGH)
  520. {
  521. llinfos << "Image " << std::hex << (intptr_t)imagep << std::dec;
  522. if (boost_level >= 0)
  523. {
  524. llcont << " with boost level " << boost_level;
  525. }
  526. else
  527. {
  528. llcont << " not owned by a fetched texture";
  529. }
  530. llcont << ":" << llendl;
  531. imagep->dump();
  532. total_stale_memory += imagep->mTextureMemory;
  533. ++num_stale_images;
  534. }
  535. }
  536. llinfos << "Total number of sculpt textures: " << num_scuplties
  537. << " (using " << scuplties_memory / 1024
  538. << "KB) - Total number of stale images: " << num_stale_images
  539. << " - Total leaked memory: " << total_stale_memory / 1024 << "KB."
  540. << llendl;
  541. }
  542. //static
  543. void LLImageGL::freeDeletedTextures(bool delete_all)
  544. {
  545. LL_TRACY_TIMER(TRC_FREE_DELETED_IMAGE);
  546. U32 idx = 0;
  547. if (!delete_all)
  548. {
  549. ++sCurrentFrame;
  550. idx = (sCurrentFrame + 3) % 4;
  551. }
  552. do
  553. {
  554. if (!sFreeList[idx].empty())
  555. {
  556. std::vector<U32>& textures = sFreeList[idx];
  557. U32 num_textures = textures.size();
  558. if (gGLManager.mInited)
  559. {
  560. glDeleteTextures(num_textures, textures.data());
  561. }
  562. for (U32 i = 0; i < num_textures; ++i)
  563. {
  564. image_unbound(textures[i]);
  565. }
  566. textures.clear();
  567. }
  568. }
  569. while (delete_all && ++idx < 4);
  570. if (sCurBoundTexBytes < 0 || gDebugGL)
  571. {
  572. sTexMemMutex.lock();
  573. S64 total = 0;
  574. for (alloc_map_t::iterator it = sTextureAllocs.begin(),
  575. end = sTextureAllocs.end();
  576. it != end; ++it)
  577. {
  578. total += it->second;
  579. }
  580. if (total != sCurBoundTexBytes)
  581. {
  582. llwarns << "Bound textures accounting mismatch: "
  583. << sCurBoundTexBytes << ", against: " << total
  584. << ". Resynced." << llendl;
  585. sCurBoundTexBytes = total;
  586. }
  587. sTexMemMutex.unlock();
  588. }
  589. }
  590. //static
  591. void LLImageGL::updateStats(F32 current_time)
  592. {
  593. sLastFrameTime = current_time;
  594. sBoundTexMemBytes = sCurBoundTexBytes;
  595. }
  596. bool LLImageGL::updateBindStats() const
  597. {
  598. const_cast<LLImageGL*>(this)->syncTexName();
  599. if (mTexName)
  600. {
  601. ++sBindCount;
  602. if (mLastBindTime != sLastFrameTime)
  603. {
  604. // We have not accounted for this texture yet this frame
  605. ++sUniqueCount;
  606. mLastBindTime = sLastFrameTime;
  607. return true;
  608. }
  609. }
  610. return false;
  611. }
  612. void LLImageGL::setExplicitFormat(S32 internal_format, U32 primary_format,
  613. U32 type_format, bool swap_bytes)
  614. {
  615. // Notes:
  616. // - Must be called before createTexture()
  617. // - It is up to the caller to ensure that the format matches the number
  618. // of components.
  619. mHasExplicitFormat = true;
  620. mFormatInternal = internal_format;
  621. mFormatPrimary = primary_format;
  622. mFormatType = type_format == 0 ? GL_UNSIGNED_BYTE : type_format;
  623. mFormatSwapBytes = swap_bytes;
  624. calcAlphaChannelOffsetAndStride();
  625. }
  626. void LLImageGL::setImage(const LLImageRaw* imagerawp)
  627. {
  628. llassert(imagerawp->getWidth() == getWidth(mCurrentDiscardLevel) &&
  629. imagerawp->getHeight() == getHeight(mCurrentDiscardLevel) &&
  630. imagerawp->getComponents() == getComponents());
  631. const U8* rawdatap = imagerawp->getData();
  632. setImage(rawdatap, false);
  633. }
  634. bool LLImageGL::setImage(const U8* data_in, bool data_hasmips, S32 usename)
  635. {
  636. LL_TRACY_TIMER(TRC_SET_IMAGE);
  637. bool is_compressed = isCompressed();
  638. LLTexUnit* unit0 = gGL.getTexUnit(0);
  639. if (mUseMipMaps)
  640. {
  641. // Set has mip maps to true before binding image so tex parameters get
  642. // set properly
  643. unit0->unbind(mBindTarget);
  644. mHasMipMaps = true;
  645. mTexOptionsDirty = true;
  646. setFilteringOption(LLTexUnit::TFO_ANISOTROPIC);
  647. }
  648. else
  649. {
  650. mHasMipMaps = false;
  651. }
  652. unit0->bind(this, false, usename);
  653. if (!data_in)
  654. {
  655. setManualImage(mTarget, 0, mFormatInternal, getWidth(), getHeight(),
  656. mFormatPrimary, mFormatType, (void*)data_in,
  657. mAllowCompression);
  658. }
  659. else if (mUseMipMaps)
  660. {
  661. if (data_hasmips)
  662. {
  663. // NOTE: data_in points to largest image; smaller images are stored
  664. // BEFORE the largest image
  665. for (S32 d = mCurrentDiscardLevel; d <= mMaxDiscardLevel; ++d)
  666. {
  667. U32 w = getWidth(d);
  668. U32 h = getHeight(d);
  669. S32 gl_level = d - mCurrentDiscardLevel;
  670. mMipLevels = llmax(mMipLevels, gl_level);
  671. if (d > mCurrentDiscardLevel)
  672. {
  673. // See above comment
  674. data_in -= dataFormatBytes(mFormatPrimary, w, h);
  675. }
  676. if (is_compressed)
  677. {
  678. U32 tex_size = (U32)dataFormatBytes(mFormatPrimary, w, h);
  679. glCompressedTexImage2D(mTarget, gl_level, mFormatPrimary,
  680. w, h, 0, tex_size,
  681. (GLvoid*)data_in);
  682. stop_glerror();
  683. }
  684. else
  685. {
  686. if (mFormatSwapBytes)
  687. {
  688. glPixelStorei(GL_UNPACK_SWAP_BYTES, 1);
  689. stop_glerror();
  690. }
  691. setManualImage(mTarget, gl_level, mFormatInternal, w, h,
  692. mFormatPrimary, GL_UNSIGNED_BYTE,
  693. (GLvoid*)data_in, mAllowCompression);
  694. if (gl_level == 0)
  695. {
  696. analyzeAlpha(data_in, w, h);
  697. }
  698. updatePickMask(w, h, data_in);
  699. if (mFormatSwapBytes)
  700. {
  701. glPixelStorei(GL_UNPACK_SWAP_BYTES, 0);
  702. stop_glerror();
  703. }
  704. }
  705. }
  706. }
  707. else if (!is_compressed)
  708. {
  709. if (mAutoGenMips)
  710. {
  711. if (mFormatSwapBytes)
  712. {
  713. glPixelStorei(GL_UNPACK_SWAP_BYTES, 1);
  714. stop_glerror();
  715. }
  716. U32 w = getWidth(mCurrentDiscardLevel);
  717. U32 h = getHeight(mCurrentDiscardLevel);
  718. mMipLevels = wpo2(llmax(w, h));
  719. // Use legacy mipmap generation mode only when core profile is
  720. // not enabled (to avoid deprecation warnings), or GL version
  721. // is below 3.0 (to avoid rendering issues).
  722. bool use_legacy_mimap = !LLRender::sGLCoreProfile ||
  723. gGLManager.mGLVersion < 3.f;
  724. if (use_legacy_mimap)
  725. {
  726. glTexParameteri(mTarget, GL_GENERATE_MIPMAP, GL_TRUE);
  727. }
  728. setManualImage(mTarget, 0, mFormatInternal, w, h,
  729. mFormatPrimary, mFormatType, data_in,
  730. mAllowCompression);
  731. analyzeAlpha(data_in, w, h);
  732. updatePickMask(w, h, data_in);
  733. if (mFormatSwapBytes)
  734. {
  735. glPixelStorei(GL_UNPACK_SWAP_BYTES, 0);
  736. stop_glerror();
  737. }
  738. if (!use_legacy_mimap)
  739. {
  740. glGenerateMipmap(mTarget);
  741. stop_glerror();
  742. }
  743. }
  744. else
  745. {
  746. // Create mips by hand
  747. // ~4x faster than gluBuild2DMipmaps
  748. U32 width = getWidth(mCurrentDiscardLevel);
  749. U32 height = getHeight(mCurrentDiscardLevel);
  750. U32 nummips = mMaxDiscardLevel - mCurrentDiscardLevel + 1;
  751. U32 w = width;
  752. U32 h = height;
  753. U8* prev_mip_data = NULL;
  754. U8* cur_mip_data = NULL;
  755. mMipLevels = nummips;
  756. for (U32 m = 0; m < nummips; ++m)
  757. {
  758. if (m == 0)
  759. {
  760. cur_mip_data = const_cast<U8*>(data_in);
  761. }
  762. else
  763. {
  764. S32 bytes = w * h * mComponents;
  765. llassert(prev_mip_data);
  766. U8* new_data = new (std::nothrow) U8[bytes];
  767. if (!new_data)
  768. {
  769. if (prev_mip_data)
  770. {
  771. delete[] prev_mip_data;
  772. }
  773. if (cur_mip_data && cur_mip_data != prev_mip_data)
  774. {
  775. delete[] cur_mip_data;
  776. }
  777. mGLTextureCreated = false;
  778. return false;
  779. }
  780. LLImageBase::generateMip(prev_mip_data, new_data, w, h,
  781. mComponents);
  782. cur_mip_data = new_data;
  783. }
  784. if (w > 0 && h > 0 && cur_mip_data)
  785. {
  786. if (mFormatSwapBytes)
  787. {
  788. glPixelStorei(GL_UNPACK_SWAP_BYTES, 1);
  789. stop_glerror();
  790. }
  791. setManualImage(mTarget, m, mFormatInternal, w, h,
  792. mFormatPrimary, mFormatType,
  793. cur_mip_data, mAllowCompression);
  794. if (m == 0)
  795. {
  796. analyzeAlpha(data_in, w, h);
  797. updatePickMask(w, h, cur_mip_data);
  798. }
  799. if (mFormatSwapBytes)
  800. {
  801. glPixelStorei(GL_UNPACK_SWAP_BYTES, 0);
  802. stop_glerror();
  803. }
  804. }
  805. else
  806. {
  807. llassert(false);
  808. }
  809. if (prev_mip_data && prev_mip_data != data_in)
  810. {
  811. delete[] prev_mip_data;
  812. }
  813. prev_mip_data = cur_mip_data;
  814. w >>= 1;
  815. h >>= 1;
  816. }
  817. if (prev_mip_data && prev_mip_data != data_in)
  818. {
  819. delete[] prev_mip_data;
  820. prev_mip_data = NULL;
  821. }
  822. }
  823. }
  824. else
  825. {
  826. llerrs << "Compressed Image has mipmaps but data does not (can not auto generate compressed mips)"
  827. << llendl;
  828. }
  829. }
  830. else
  831. {
  832. mMipLevels = 0;
  833. U32 w = getWidth();
  834. U32 h = getHeight();
  835. if (is_compressed)
  836. {
  837. U32 tex_size = (U32)dataFormatBytes(mFormatPrimary, w, h);
  838. glCompressedTexImage2D(mTarget, 0, mFormatPrimary, w, h, 0,
  839. tex_size, (GLvoid*)data_in);
  840. stop_glerror();
  841. }
  842. else
  843. {
  844. if (mFormatSwapBytes)
  845. {
  846. glPixelStorei(GL_UNPACK_SWAP_BYTES, 1);
  847. stop_glerror();
  848. }
  849. setManualImage(mTarget, 0, mFormatInternal, w, h, mFormatPrimary,
  850. mFormatType, (GLvoid*)data_in, mAllowCompression);
  851. analyzeAlpha(data_in, w, h);
  852. updatePickMask(w, h, data_in);
  853. if (mFormatSwapBytes)
  854. {
  855. glPixelStorei(GL_UNPACK_SWAP_BYTES, 0);
  856. stop_glerror();
  857. }
  858. }
  859. }
  860. mGLTextureCreated = true;
  861. return true;
  862. }
  863. #if !LL_DARWIN
  864. // Breaks up glTexSubImage2D() calls to a manageable size for the GL command
  865. // buffer.
  866. static void sub_image_lines(U32 target, S32 miplevel, S32 x_offset, S32 y_offset,
  867. U32 width, U32 height, U32 pixformat, U32 pixtype,
  868. const U8* srcp, U32 data_width)
  869. {
  870. U32 components = LLImageGL::dataFormatComponents(pixformat);
  871. U32 type_width = 4;
  872. switch (pixtype)
  873. {
  874. case GL_UNSIGNED_BYTE:
  875. case GL_BYTE:
  876. case GL_UNSIGNED_INT_8_8_8_8_REV:
  877. type_width = 1;
  878. break;
  879. case GL_UNSIGNED_SHORT:
  880. case GL_SHORT:
  881. type_width = 2;
  882. break;
  883. case GL_UNSIGNED_INT:
  884. case GL_INT:
  885. case GL_FLOAT:
  886. type_width = 4;
  887. break;
  888. default:
  889. type_width = 1;
  890. llwarns << "Unknown type: " << pixtype << llendl;
  891. }
  892. U32 line_width = data_width * components * type_width;
  893. U32 y_offset_end = y_offset + height;
  894. for (U32 y_pos = y_offset; y_pos < y_offset_end; ++y_pos)
  895. {
  896. glTexSubImage2D(target, miplevel, x_offset, y_pos, width, 1, pixformat,
  897. pixtype, srcp);
  898. srcp += line_width;
  899. }
  900. }
  901. #endif
  902. bool LLImageGL::setSubImage(const U8* datap, U32 data_width, U32 data_height,
  903. S32 x_pos, S32 y_pos, U32 width, U32 height,
  904. bool force_fast_update, U32 use_name)
  905. {
  906. if (!width || !height)
  907. {
  908. return true;
  909. }
  910. syncTexName();
  911. if (use_name == 0)
  912. {
  913. use_name = mTexName;
  914. }
  915. if (!datap || use_name == 0)
  916. {
  917. // *TODO: Re-add warning ? Ran into thread locking issues ? - DK
  918. return false;
  919. }
  920. // *HACK: allow the caller to explicitly force the fast path (i.e. using
  921. // glTexSubImage2D here instead of calling setImage) even when updating the
  922. // full texture.
  923. if (!force_fast_update && x_pos == 0 && y_pos == 0 &&
  924. data_width == width && data_height == height &&
  925. width == getWidth() && height == getHeight())
  926. {
  927. setImage(datap, false, use_name);
  928. }
  929. else
  930. {
  931. if (mUseMipMaps)
  932. {
  933. dump();
  934. llerrs << "Called with mipmapped image (not supported)" << llendl;
  935. }
  936. llassert_always(mCurrentDiscardLevel == 0 && x_pos >= 0 && y_pos >= 0);
  937. if (U32(x_pos + width) > getWidth() ||
  938. U32(y_pos + height) > getHeight())
  939. {
  940. dump();
  941. llerrs << "Subimage not wholly in target image !"
  942. << " x_pos " << x_pos
  943. << " y_pos " << y_pos
  944. << " width " << width
  945. << " height " << height
  946. << " getWidth() " << getWidth()
  947. << " getHeight() " << getHeight()
  948. << llendl;
  949. }
  950. if (U32(x_pos + width) > data_width ||
  951. U32(y_pos + height) > data_height)
  952. {
  953. dump();
  954. llerrs << "Subimage not wholly in source image !"
  955. << " x_pos " << x_pos
  956. << " y_pos " << y_pos
  957. << " width " << width
  958. << " height " << height
  959. << " source_width " << data_width
  960. << " source_height " << data_height
  961. << llendl;
  962. }
  963. glPixelStorei(GL_UNPACK_ROW_LENGTH, data_width);
  964. stop_glerror();
  965. if (mFormatSwapBytes)
  966. {
  967. glPixelStorei(GL_UNPACK_SWAP_BYTES, 1);
  968. stop_glerror();
  969. }
  970. datap += (y_pos * data_width + x_pos) * getComponents();
  971. // Update the GL texture
  972. LLTexUnit* unit0 = gGL.getTexUnit(0);
  973. bool res = unit0->bindManual(mBindTarget, use_name);
  974. if (!res)
  975. {
  976. llerrs << "gGL.getTexUnit(0)->bindManual() failed" << llendl;
  977. }
  978. #if !LL_DARWIN
  979. if (sSetSubImagePerLine && !isCompressed() && is_main_thread())
  980. {
  981. sub_image_lines(mTarget, 0, x_pos, y_pos, width, height,
  982. mFormatPrimary, mFormatType, datap, data_width);
  983. }
  984. else
  985. #endif
  986. {
  987. glTexSubImage2D(mTarget, 0, x_pos, y_pos,
  988. width, height, mFormatPrimary, mFormatType, datap);
  989. }
  990. unit0->disable();
  991. stop_glerror();
  992. if (mFormatSwapBytes)
  993. {
  994. glPixelStorei(GL_UNPACK_SWAP_BYTES, 0);
  995. stop_glerror();
  996. }
  997. glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
  998. stop_glerror();
  999. mGLTextureCreated = true;
  1000. }
  1001. return true;
  1002. }
  1003. bool LLImageGL::setSubImage(const LLImageRaw* imagerawp, S32 x_pos, S32 y_pos,
  1004. U32 width, U32 height, bool force_fast_update,
  1005. U32 use_name)
  1006. {
  1007. return setSubImage(imagerawp->getData(), imagerawp->getWidth(),
  1008. imagerawp->getHeight(), x_pos, y_pos, width, height,
  1009. force_fast_update, use_name);
  1010. }
  1011. // Copy sub image from frame buffer
  1012. bool LLImageGL::setSubImageFromFrameBuffer(S32 fb_x, S32 fb_y, S32 x_pos,
  1013. S32 y_pos, U32 width, U32 height)
  1014. {
  1015. if (gGL.getTexUnit(0)->bind(this, true))
  1016. {
  1017. glCopyTexSubImage2D(GL_TEXTURE_2D, 0, fb_x, fb_y, x_pos, y_pos, width,
  1018. height);
  1019. stop_glerror();
  1020. mGLTextureCreated = true;
  1021. return true;
  1022. }
  1023. return false;
  1024. }
  1025. //static
  1026. void LLImageGL::generateTextures(U32 num_textures, U32* textures)
  1027. {
  1028. LL_TRACY_TIMER(TRC_GENERATE_TEXTURES);
  1029. for (U32 i = 0; i < num_textures; ++i)
  1030. {
  1031. image_unbound(textures[i]);
  1032. }
  1033. constexpr size_t pool_size = 1024;
  1034. thread_local U32 name_pool[pool_size]; // Pool of texture names
  1035. thread_local U32 name_count = 0; // Available names in pool
  1036. if (!name_count)
  1037. {
  1038. glGenTextures(pool_size, name_pool);
  1039. name_count = pool_size;
  1040. }
  1041. if (num_textures < name_count)
  1042. {
  1043. memcpy((void*)textures, (void*)(name_pool + name_count - num_textures),
  1044. sizeof(U32) * num_textures);
  1045. name_count -= num_textures;
  1046. }
  1047. else
  1048. {
  1049. glGenTextures(num_textures, textures);
  1050. }
  1051. }
  1052. //static
  1053. void LLImageGL::deleteTextures(U32 num_textures, const U32* textures)
  1054. {
  1055. LL_TRACY_TIMER(TRC_DELETE_IMAGE);
  1056. if (gGLManager.mInited)
  1057. {
  1058. if (sDelayedTextureDelete)
  1059. {
  1060. U32 idx = sCurrentFrame % 4;
  1061. for (U32 i = 0; i < num_textures; ++i)
  1062. {
  1063. sFreeList[idx].push_back(textures[i]);
  1064. }
  1065. }
  1066. else
  1067. {
  1068. glDeleteTextures(num_textures,textures);
  1069. for (U32 i = 0; i < num_textures; ++i)
  1070. {
  1071. image_unbound(textures[i]);
  1072. }
  1073. }
  1074. }
  1075. }
  1076. //static
  1077. void LLImageGL::setManualImage(U32 target, S32 miplevel, S32 intformat,
  1078. U32 width, U32 height, U32 pixformat,
  1079. U32 pixtype, const void* pixels,
  1080. bool allow_compression)
  1081. {
  1082. LL_TRACY_TIMER(TRC_SET_MANUAL_IMAGE);
  1083. const U32 pixels_count = width * height;
  1084. if (LLRender::sGLCoreProfile)
  1085. {
  1086. #if GL_ARB_texture_swizzle
  1087. if (gGLManager.mHasTextureSwizzle)
  1088. {
  1089. if (pixformat == GL_ALPHA)
  1090. {
  1091. // GL_ALPHA is deprecated, convert to RGBA
  1092. const GLint mask[] = { GL_ZERO, GL_ZERO, GL_ZERO, GL_RED };
  1093. glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, mask);
  1094. pixformat = GL_RED;
  1095. intformat = GL_R8;
  1096. }
  1097. if (pixformat == GL_LUMINANCE)
  1098. {
  1099. // GL_LUMINANCE is deprecated, convert to RGBA
  1100. const GLint mask[] = { GL_RED, GL_RED, GL_RED, GL_ONE };
  1101. glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, mask);
  1102. pixformat = GL_RED;
  1103. intformat = GL_R8;
  1104. }
  1105. if (pixformat == GL_LUMINANCE_ALPHA)
  1106. {
  1107. // GL_LUMINANCE_ALPHA is deprecated, convert to RGBA
  1108. const GLint mask[] = { GL_RED, GL_RED, GL_RED, GL_GREEN };
  1109. glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, mask);
  1110. pixformat = GL_RG;
  1111. intformat = GL_RG8;
  1112. }
  1113. }
  1114. else
  1115. #endif
  1116. {
  1117. thread_local std::vector<U32> scratch;
  1118. if (pixformat == GL_ALPHA && pixtype == GL_UNSIGNED_BYTE)
  1119. {
  1120. if (pixels)
  1121. {
  1122. // GL_ALPHA is deprecated, convert to RGBA
  1123. scratch.reserve(pixels_count);
  1124. for (U32 i = 0; i < pixels_count; ++i)
  1125. {
  1126. U8* pix = (U8*)&scratch[i];
  1127. pix[0] = pix[1] = pix[2] = 0;
  1128. pix[3] = ((U8*)pixels)[i];
  1129. }
  1130. pixels = (void*)scratch.data();
  1131. }
  1132. pixformat = GL_RGBA;
  1133. intformat = GL_RGBA8;
  1134. }
  1135. if (pixformat == GL_LUMINANCE_ALPHA && pixtype == GL_UNSIGNED_BYTE)
  1136. {
  1137. // GL_LUMINANCE_ALPHA is deprecated, convert to RGBA
  1138. if (pixels)
  1139. {
  1140. scratch.reserve(pixels_count);
  1141. for (U32 i = 0; i < pixels_count; ++i)
  1142. {
  1143. U8 lum = ((U8*)pixels)[2 * i];
  1144. U8 alpha = ((U8*)pixels)[2 * i + 1];
  1145. U8* pix = (U8*)&scratch[i];
  1146. pix[0] = pix[1] = pix[2] = lum;
  1147. pix[3] = alpha;
  1148. }
  1149. pixels = (void*)scratch.data();
  1150. }
  1151. pixformat = GL_RGBA;
  1152. intformat = GL_RGBA8;
  1153. }
  1154. if (pixformat == GL_LUMINANCE && pixtype == GL_UNSIGNED_BYTE)
  1155. {
  1156. // GL_LUMINANCE is deprecated, convert to RGBA
  1157. if (pixels)
  1158. {
  1159. scratch.reserve(pixels_count);
  1160. for (U32 i = 0; i < pixels_count; ++i)
  1161. {
  1162. U8 lum = ((U8*)pixels)[i];
  1163. U8* pix = (U8*)&scratch[i];
  1164. pix[0] = pix[1] = pix[2] = lum;
  1165. pix[3] = 255;
  1166. }
  1167. pixels = (void*)scratch.data();
  1168. }
  1169. pixformat = GL_RGBA;
  1170. intformat = GL_RGB8;
  1171. }
  1172. }
  1173. }
  1174. bool compress = allow_compression && sCompressTextures &&
  1175. pixels_count > sCompressThreshold;
  1176. if (compress)
  1177. {
  1178. switch (intformat)
  1179. {
  1180. case GL_RED:
  1181. case GL_R8:
  1182. intformat = GL_COMPRESSED_RED;
  1183. break;
  1184. case GL_RG:
  1185. case GL_RG8:
  1186. intformat = GL_COMPRESSED_RG;
  1187. break;
  1188. case GL_RGB:
  1189. case GL_RGB8:
  1190. intformat = GL_COMPRESSED_RGB;
  1191. break;
  1192. case GL_SRGB:
  1193. case GL_SRGB8:
  1194. intformat = GL_COMPRESSED_SRGB;
  1195. break;
  1196. case GL_RGBA:
  1197. case GL_RGBA8:
  1198. intformat = GL_COMPRESSED_RGBA;
  1199. break;
  1200. case GL_SRGB_ALPHA:
  1201. case GL_SRGB8_ALPHA8:
  1202. intformat = GL_COMPRESSED_SRGB_ALPHA;
  1203. break;
  1204. case GL_LUMINANCE:
  1205. case GL_LUMINANCE8:
  1206. intformat = GL_COMPRESSED_LUMINANCE;
  1207. break;
  1208. case GL_LUMINANCE_ALPHA:
  1209. case GL_LUMINANCE8_ALPHA8:
  1210. intformat = GL_COMPRESSED_LUMINANCE_ALPHA;
  1211. break;
  1212. case GL_ALPHA:
  1213. case GL_ALPHA8:
  1214. intformat = GL_COMPRESSED_ALPHA;
  1215. break;
  1216. default:
  1217. llwarns_once << "Could not compress format: " << std::hex
  1218. << intformat << std::dec << llendl;
  1219. }
  1220. }
  1221. #if !LL_DARWIN
  1222. if (sSetSubImagePerLine && !compress && is_main_thread())
  1223. {
  1224. glTexImage2D(target, miplevel, intformat, width, height, 0, pixformat,
  1225. pixtype, NULL);
  1226. if (pixels)
  1227. {
  1228. sub_image_lines(target, miplevel, 0, 0, width, height, pixformat,
  1229. pixtype, (U8*)pixels, width);
  1230. }
  1231. }
  1232. else
  1233. #endif
  1234. {
  1235. glTexImage2D(target, miplevel, intformat, width, height, 0, pixformat,
  1236. pixtype, pixels);
  1237. }
  1238. image_bound(width, height, pixformat);
  1239. stop_glerror();
  1240. }
  1241. // Create an empty GL texture: just create a texture name. The texture is
  1242. // associated with some image by calling glTexImage outside LLImageGL.
  1243. bool LLImageGL::createGLTexture()
  1244. {
  1245. LL_TRACY_TIMER(TRC_CREATE_GL_TEXTURE1);
  1246. if (gGLManager.mIsDisabled)
  1247. {
  1248. llwarns << "Trying to create a texture while GL is disabled !"
  1249. << llendl;
  1250. return false;
  1251. }
  1252. // Do not save this texture when gl is destroyed.
  1253. mGLTextureCreated = false;
  1254. llassert(gGLManager.mInited);
  1255. stop_glerror();
  1256. syncTexName();
  1257. if (mTexName)
  1258. {
  1259. deleteTextures(1, &mTexName);
  1260. mTexName = 0;
  1261. }
  1262. generateTextures(1, &mTexName);
  1263. stop_glerror();
  1264. if (!mTexName)
  1265. {
  1266. llwarns << "Failed to make an empty texture" << llendl;
  1267. return false;
  1268. }
  1269. return true;
  1270. }
  1271. bool LLImageGL::createGLTexture(S32 discard_level, const LLImageRaw* imagerawp,
  1272. S32 usename, bool to_create, bool defer_copy,
  1273. U32* tex_name)
  1274. {
  1275. LL_TRACY_TIMER(TRC_CREATE_GL_TEXTURE2);
  1276. if (gGLManager.mIsDisabled || !gGLManager.mInited)
  1277. {
  1278. llwarns << "Trying to create a texture while GL is disabled or not initialized !"
  1279. << llendl;
  1280. return false;
  1281. }
  1282. if (!imagerawp || !imagerawp->getData())
  1283. {
  1284. llwarns_sparse << "Trying to create a texture from invalid image data"
  1285. << llendl;
  1286. mGLTextureCreated = false;
  1287. return false;
  1288. }
  1289. if (discard_level < 0)
  1290. {
  1291. llassert(mCurrentDiscardLevel >= 0);
  1292. discard_level = mCurrentDiscardLevel;
  1293. }
  1294. if (sPreserveDiscard)
  1295. {
  1296. discard_level = llclamp(discard_level, 0, (S32)mMaxDiscardLevel);
  1297. }
  1298. // Actual image width/height = raw image width/height * 2^discard_level
  1299. U32 raw_w = imagerawp->getWidth();
  1300. U32 raw_h = imagerawp->getHeight();
  1301. U32 w = raw_w << discard_level;
  1302. U32 h = raw_h << discard_level;
  1303. // setSize may call destroyGLTexture if the size does not match
  1304. if (!setSize(w, h, imagerawp->getComponents(), discard_level))
  1305. {
  1306. mGLTextureCreated = false;
  1307. return false;
  1308. }
  1309. if (mHasExplicitFormat &&
  1310. ((mFormatPrimary == GL_RGBA && mComponents < 4) ||
  1311. (mFormatPrimary == GL_RGB && mComponents < 3)))
  1312. {
  1313. llwarns << "Incorrect format: " << std::hex << mFormatPrimary
  1314. << std::dec << " - Number of components: " << (U32)mComponents
  1315. << llendl;
  1316. mHasExplicitFormat = false;
  1317. }
  1318. if (!mHasExplicitFormat)
  1319. {
  1320. switch (mComponents)
  1321. {
  1322. case 1:
  1323. // Use luminance alpha (for fonts)
  1324. mFormatInternal = GL_LUMINANCE8;
  1325. mFormatPrimary = GL_LUMINANCE;
  1326. mFormatType = GL_UNSIGNED_BYTE;
  1327. break;
  1328. case 2:
  1329. // Use luminance alpha (for fonts)
  1330. mFormatInternal = GL_LUMINANCE8_ALPHA8;
  1331. mFormatPrimary = GL_LUMINANCE_ALPHA;
  1332. mFormatType = GL_UNSIGNED_BYTE;
  1333. break;
  1334. case 3:
  1335. mFormatInternal = GL_RGB8;
  1336. mFormatPrimary = GL_RGB;
  1337. mFormatType = GL_UNSIGNED_BYTE;
  1338. break;
  1339. case 4:
  1340. mFormatInternal = GL_RGBA8;
  1341. mFormatPrimary = GL_RGBA;
  1342. mFormatType = GL_UNSIGNED_BYTE;
  1343. break;
  1344. default:
  1345. llwarns << "Bad number of components for texture: "
  1346. << (U32)getComponents() << LL_ENDL;
  1347. to_create = false;
  1348. }
  1349. calcAlphaChannelOffsetAndStride();
  1350. }
  1351. if (!to_create) // Do not create a GL texture
  1352. {
  1353. destroyGLTexture();
  1354. mCurrentDiscardLevel = discard_level;
  1355. mLastBindTime = sLastFrameTime;
  1356. mGLTextureCreated = false;
  1357. return true;
  1358. }
  1359. const U8* rawdatap = imagerawp->getData();
  1360. return createGLTexture(discard_level, rawdatap, false, usename, defer_copy,
  1361. tex_name);
  1362. }
  1363. bool LLImageGL::createGLTexture(S32 discard_level, const U8* data_in,
  1364. bool data_hasmips, S32 usename,
  1365. bool defer_copy, U32* tex_name)
  1366. {
  1367. LL_TRACY_TIMER(TRC_CREATE_GL_TEXTURE3);
  1368. bool main_thread = is_main_thread();
  1369. if (defer_copy)
  1370. {
  1371. data_in = NULL;
  1372. }
  1373. llassert(defer_copy || data_in);
  1374. stop_glerror();
  1375. if (discard_level < 0)
  1376. {
  1377. llassert(mCurrentDiscardLevel >= 0);
  1378. discard_level = mCurrentDiscardLevel;
  1379. }
  1380. discard_level = llclamp(discard_level, 0, (S32)mMaxDiscardLevel);
  1381. // Note: always force creation of new texname when not on main thread or
  1382. // when defer copy is set.
  1383. if (main_thread)
  1384. {
  1385. syncTexName();
  1386. if (!defer_copy && mTexName && discard_level == mCurrentDiscardLevel)
  1387. {
  1388. // This will only be true if the size has not changed
  1389. if (tex_name)
  1390. {
  1391. *tex_name = mTexName;
  1392. }
  1393. return setImage(data_in, data_hasmips);
  1394. }
  1395. }
  1396. LLTexUnit* unit0 = gGL.getTexUnit(0);
  1397. U32 old_name = mTexName;
  1398. U32 new_name = 0;
  1399. if (usename)
  1400. {
  1401. llassert(main_thread);
  1402. new_name = usename;
  1403. }
  1404. else
  1405. {
  1406. generateTextures(1, &new_name);
  1407. unit0->bind(this, false, new_name);
  1408. U32 type = LLTexUnit::getInternalType(mBindTarget);
  1409. glTexParameteri(type, GL_TEXTURE_BASE_LEVEL, 0);
  1410. glTexParameteri(type, GL_TEXTURE_MAX_LEVEL,
  1411. mMaxDiscardLevel - discard_level);
  1412. }
  1413. if (tex_name)
  1414. {
  1415. *tex_name = new_name;
  1416. }
  1417. if (mUseMipMaps)
  1418. {
  1419. mAutoGenMips = true;
  1420. }
  1421. mCurrentDiscardLevel = discard_level;
  1422. if (!setImage(data_in, data_hasmips, new_name))
  1423. {
  1424. return false;
  1425. }
  1426. // Set texture options to our defaults.
  1427. unit0->setHasMipMaps(mHasMipMaps);
  1428. unit0->setTextureAddressMode(mAddressMode);
  1429. unit0->setTextureFilteringOption(mFilterOption);
  1430. // Things will break if we do not unbind after creation
  1431. unit0->unbind(mBindTarget);
  1432. if (old_name)
  1433. {
  1434. sGlobalTexMemBytes -= mTextureMemory;
  1435. }
  1436. if (!defer_copy)
  1437. {
  1438. if (main_thread) // Not on background thread, immediately set mTexName
  1439. {
  1440. if (old_name != 0 && old_name != new_name)
  1441. {
  1442. deleteTextures(1, &old_name);
  1443. }
  1444. mTexName = new_name;
  1445. }
  1446. else
  1447. {
  1448. // If we are on the image loading thread, be sure to delete the
  1449. // old texname and update mTexName on the main thread.
  1450. syncToMainThread(new_name);
  1451. }
  1452. }
  1453. mTextureMemory = getMipBytes(mCurrentDiscardLevel);
  1454. sGlobalTexMemBytes += mTextureMemory;
  1455. // Mark this as bound at this point, so we do not throw it out immediately
  1456. mLastBindTime = sLastFrameTime;
  1457. return true;
  1458. }
  1459. void LLImageGL::syncToMainThread(U32 new_tex_name)
  1460. {
  1461. LL_TRACY_TIMER(TRC_IMAGEGL_SYNC);
  1462. llassert(!is_main_thread());
  1463. // We must now make sure all the GL commands have been flushed down the
  1464. // thread's GL pipeline; without this, you would see flickering/black
  1465. // images, or sudden random texture corruptions (e.g. for UI ones).
  1466. if (gGLManager.mHasSync)
  1467. {
  1468. if (mTexNameSync)
  1469. {
  1470. glDeleteSync(mTexNameSync);
  1471. }
  1472. mTexNameSync = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
  1473. glFlush();
  1474. // With NVIDIA, we do not need to do the sync in the main thread, which
  1475. // avoids to risk stalling the main thread GL pipeline at all. HB
  1476. if (gGLManager.mIsNVIDIA && sSyncInThread)
  1477. {
  1478. glClientWaitSync(mTexNameSync, 0, GL_TIMEOUT_IGNORED);
  1479. glDeleteSync(mTexNameSync);
  1480. mTexNameSync = 0;
  1481. }
  1482. }
  1483. else
  1484. {
  1485. glFinish(); // Ouch, costly !... HB
  1486. }
  1487. // Note: instead of using a post to the main thread work queue to swap the
  1488. // tex name and delete the old one, we delay these operations (now both
  1489. // performed in syncTexName(), which is called everytime before we use
  1490. // mTexName) until we actually need to use the texture: this avoids to
  1491. // needlessly stall the GL pipeline with a syncing when we could naturally
  1492. // get past the fence due to the delay between the image creation and its
  1493. // use (this was Kathrine Jansma's idea, that I reimplemented so that the
  1494. // modification of mTexName is done only in the main thread, which also
  1495. // allowed to remove the queueing of the deleteTextures() call into the
  1496. // work queue). We therefore only register here the new tex name and we set
  1497. // an atomic flag indicating that mTexName needs to be updated. HB
  1498. mNewTexName = new_tex_name;
  1499. mTexNameDirty = true;
  1500. }
  1501. void LLImageGL::setTexName(U32 name)
  1502. {
  1503. syncTexName();
  1504. if (mTexName != name) // We need to update the GL image stats then. HB
  1505. {
  1506. image_unbound(mTexName);
  1507. // The format may not yet have been set... In this case, the image will
  1508. // be created later, and the bound memory will then be updated. HB
  1509. if (mFormatPrimary > 0)
  1510. {
  1511. image_bound(mWidth, mHeight, mFormatPrimary, 1, name);
  1512. }
  1513. }
  1514. mTexName = name;
  1515. }
  1516. void LLImageGL::syncTexName()
  1517. {
  1518. if (mTexNameDirty && is_main_thread())
  1519. {
  1520. if (mTexNameSync)
  1521. {
  1522. glClientWaitSync(mTexNameSync, 0, GL_TIMEOUT_IGNORED);
  1523. glDeleteSync(mTexNameSync);
  1524. mTexNameSync = 0;
  1525. }
  1526. if (mTexName && mTexName != mNewTexName)
  1527. {
  1528. deleteTextures(1, &mTexName);
  1529. }
  1530. mTexName = mNewTexName;
  1531. mNewTexName = 0;
  1532. mTexNameDirty = false;
  1533. }
  1534. }
  1535. void LLImageGL::syncTexName(U32 texname)
  1536. {
  1537. if (texname)
  1538. {
  1539. syncTexName();
  1540. if (mTexName && mTexName != texname)
  1541. {
  1542. deleteTextures(1, &mTexName);
  1543. }
  1544. mTexName = texname;
  1545. }
  1546. }
  1547. bool LLImageGL::readBackRaw(S32 discard_level, LLImageRaw* imagerawp,
  1548. bool compressed_ok) const
  1549. {
  1550. const_cast<LLImageGL*>(this)->syncTexName();
  1551. if (discard_level < 0)
  1552. {
  1553. discard_level = mCurrentDiscardLevel;
  1554. }
  1555. if (mTexName == 0 || discard_level < mCurrentDiscardLevel ||
  1556. discard_level > mMaxDiscardLevel)
  1557. {
  1558. return false;
  1559. }
  1560. GLint gl_discard = discard_level - mCurrentDiscardLevel;
  1561. // Explicitly unbind texture
  1562. LLTexUnit* unit0 = gGL.getTexUnit(0);
  1563. unit0->unbind(mBindTarget);
  1564. #if 1
  1565. if (!unit0->bindManual(mBindTarget, mTexName))
  1566. {
  1567. llwarns << "Failed to bind." << llendl;
  1568. return false;
  1569. }
  1570. #else
  1571. unit0->bindManual(mBindTarget, mTexName);
  1572. #endif
  1573. // This is necessary to prevent previous, unrelated errors causing GL
  1574. // textures creation failures, due to the fact we are testing here for GL
  1575. // errors and aborting when finding one. HB
  1576. clear_glerror();
  1577. GLint glwidth = 0;
  1578. glGetTexLevelParameteriv(mTarget, gl_discard, GL_TEXTURE_WIDTH, &glwidth);
  1579. if (glwidth == 0)
  1580. {
  1581. // No mip data smaller than current discard level
  1582. return false;
  1583. }
  1584. U32 width = getWidth(discard_level);
  1585. U32 height = getHeight(discard_level);
  1586. U8 ncomponents = getComponents();
  1587. if (ncomponents == 0)
  1588. {
  1589. return false;
  1590. }
  1591. if ((GLint)width < glwidth)
  1592. {
  1593. llwarns << "Texture size is smaller than it should be: width: "
  1594. << width << " - glwidth: " << glwidth << " - mWidth: "
  1595. << mWidth << " - mCurrentDiscardLevel: "
  1596. << (S32)mCurrentDiscardLevel << " - discard_level: "
  1597. << (S32)discard_level << llendl;
  1598. return false;
  1599. }
  1600. if (width <= 0 || width > 2048 || height <= 0 || height > 2048 ||
  1601. ncomponents < 1 || ncomponents > 4)
  1602. {
  1603. llwarns << "Bogus size/components: " << width << "x" << height << "x"
  1604. << ncomponents << llendl;
  1605. return false;
  1606. }
  1607. GLint is_compressed = 0;
  1608. if (compressed_ok)
  1609. {
  1610. glGetTexLevelParameteriv(mTarget, is_compressed, GL_TEXTURE_COMPRESSED,
  1611. &is_compressed);
  1612. }
  1613. GLenum error = glGetError();
  1614. if (error != GL_NO_ERROR)
  1615. {
  1616. llwarns << "GL Error happens before reading back texture. Error code: "
  1617. << error << llendl;
  1618. stop_glerror();
  1619. // If there has been an error, we must abort (missing in LL's code). HB
  1620. return false;
  1621. }
  1622. if (is_compressed)
  1623. {
  1624. GLint glbytes;
  1625. glGetTexLevelParameteriv(mTarget, gl_discard,
  1626. GL_TEXTURE_COMPRESSED_IMAGE_SIZE, &glbytes);
  1627. if (!imagerawp->allocateDataSize(width, height, ncomponents, glbytes))
  1628. {
  1629. llwarns << "Memory allocation failed for reading back texture. Size is: "
  1630. << glbytes << " - width: " << width << " - height: "
  1631. << height << " - components: " << ncomponents << llendl;
  1632. return false;
  1633. }
  1634. glGetCompressedTexImage(mTarget, gl_discard,
  1635. (GLvoid*)imagerawp->getData());
  1636. }
  1637. else
  1638. {
  1639. if (!imagerawp->allocateDataSize(width, height, ncomponents))
  1640. {
  1641. llwarns << "Memory allocation failed for reading back texture: width: "
  1642. << width << " - height: " << height << " - components: "
  1643. << ncomponents << llendl;
  1644. return false;
  1645. }
  1646. glGetTexImage(GL_TEXTURE_2D, gl_discard, mFormatPrimary, mFormatType,
  1647. (GLvoid*)(imagerawp->getData()));
  1648. }
  1649. error = glGetError();
  1650. if (error != GL_NO_ERROR)
  1651. {
  1652. llwarns << "GL Error happens after reading back texture. Error code: "
  1653. << error << llendl;
  1654. stop_glerror();
  1655. imagerawp->deleteData();
  1656. return false;
  1657. }
  1658. return true;
  1659. }
  1660. void LLImageGL::destroyGLTexture()
  1661. {
  1662. syncTexName();
  1663. if (mTexName)
  1664. {
  1665. sGlobalTexMemBytes -= mTextureMemory;
  1666. mTextureMemory = 0;
  1667. deleteTextures(1, &mTexName);
  1668. mCurrentDiscardLevel = -1; // Invalidate mCurrentDiscardLevel.
  1669. mTexName = 0;
  1670. mGLTextureCreated = false;
  1671. }
  1672. }
  1673. // Force to invalidate the gl texture, most likely a sculpty texture
  1674. void LLImageGL::forceToInvalidateGLTexture()
  1675. {
  1676. syncTexName();
  1677. if (mTexName)
  1678. {
  1679. destroyGLTexture();
  1680. }
  1681. else
  1682. {
  1683. mCurrentDiscardLevel = -1 ; // Invalidate mCurrentDiscardLevel.
  1684. }
  1685. }
  1686. void LLImageGL::setAddressMode(LLTexUnit::eTextureAddressMode mode)
  1687. {
  1688. syncTexName();
  1689. if (mAddressMode != mode)
  1690. {
  1691. mTexOptionsDirty = true;
  1692. mAddressMode = mode;
  1693. }
  1694. LLTexUnit* unit = gGL.getTexUnit(gGL.getCurrentTexUnitIndex());
  1695. if (unit->getCurrTexture() == mTexName)
  1696. {
  1697. unit->setTextureAddressMode(mode);
  1698. mTexOptionsDirty = false;
  1699. }
  1700. }
  1701. void LLImageGL::setFilteringOption(LLTexUnit::eTextureFilterOptions option)
  1702. {
  1703. syncTexName();
  1704. if (mFilterOption != option)
  1705. {
  1706. mTexOptionsDirty = true;
  1707. mFilterOption = option;
  1708. }
  1709. if (mTexName == 0)
  1710. {
  1711. return;
  1712. }
  1713. LLTexUnit* unit = gGL.getTexUnit(gGL.getCurrentTexUnitIndex());
  1714. if (unit->getCurrTexture() == mTexName)
  1715. {
  1716. unit->setTextureFilteringOption(option);
  1717. mTexOptionsDirty = false;
  1718. stop_glerror();
  1719. }
  1720. }
  1721. U32 LLImageGL::getHeight(S32 discard_level) const
  1722. {
  1723. if (discard_level < 0)
  1724. {
  1725. discard_level = mCurrentDiscardLevel;
  1726. }
  1727. U32 height = mHeight >> discard_level;
  1728. return height < 1 ? 1 : height;
  1729. }
  1730. U32 LLImageGL::getWidth(S32 discard_level) const
  1731. {
  1732. if (discard_level < 0)
  1733. {
  1734. discard_level = mCurrentDiscardLevel;
  1735. }
  1736. U32 width = mWidth >> discard_level;
  1737. if (width < 1) width = 1;
  1738. return width;
  1739. }
  1740. S64 LLImageGL::getBytes(S32 discard_level) const
  1741. {
  1742. if (discard_level < 0)
  1743. {
  1744. discard_level = mCurrentDiscardLevel;
  1745. }
  1746. S64 w = mWidth >> discard_level;
  1747. S64 h = mHeight >> discard_level;
  1748. if (w == 0) w = 1;
  1749. if (h == 0) h = 1;
  1750. return dataFormatBytes(mFormatPrimary, w, h);
  1751. }
  1752. S64 LLImageGL::getMipBytes(S32 discard_level) const
  1753. {
  1754. if (discard_level < 0)
  1755. {
  1756. discard_level = mCurrentDiscardLevel;
  1757. }
  1758. S64 w = mWidth >> discard_level;
  1759. S64 h = mHeight >> discard_level;
  1760. S64 res = dataFormatBytes(mFormatPrimary, w, h);
  1761. if (mUseMipMaps)
  1762. {
  1763. while (w > 1 && h > 1)
  1764. {
  1765. w >>= 1;
  1766. if (w == 0)
  1767. {
  1768. w = 1;
  1769. }
  1770. h >>= 1;
  1771. if (h == 0)
  1772. {
  1773. h = 1;
  1774. }
  1775. res += dataFormatBytes(mFormatPrimary, w, h);
  1776. }
  1777. }
  1778. return res;
  1779. }
  1780. void LLImageGL::setTarget(U32 target, LLTexUnit::eTextureType bind_target)
  1781. {
  1782. mTarget = target;
  1783. mBindTarget = bind_target;
  1784. }
  1785. void LLImageGL::setNeedsAlphaAndPickMask(bool need_mask)
  1786. {
  1787. if (mNeedsAlphaAndPickMask != need_mask)
  1788. {
  1789. mNeedsAlphaAndPickMask = need_mask;
  1790. if (mNeedsAlphaAndPickMask)
  1791. {
  1792. mAlphaOffset = 0;
  1793. }
  1794. else // Do not need alpha mask
  1795. {
  1796. mAlphaOffset = INVALID_OFFSET;
  1797. mIsMask = false;
  1798. }
  1799. }
  1800. }
  1801. // Helper function
  1802. LL_INLINE static bool is_little_endian()
  1803. {
  1804. S32 a = 0x12345678;
  1805. U8* c = (U8*)(&a);
  1806. return *c == 0x78;
  1807. }
  1808. void LLImageGL::calcAlphaChannelOffsetAndStride()
  1809. {
  1810. if (mAlphaOffset == INVALID_OFFSET) // Do not need alpha mask
  1811. {
  1812. return;
  1813. }
  1814. mAlphaStride = -1;
  1815. switch (mFormatPrimary)
  1816. {
  1817. case GL_LUMINANCE:
  1818. case GL_ALPHA:
  1819. mAlphaStride = 1;
  1820. break;
  1821. case GL_LUMINANCE_ALPHA:
  1822. mAlphaStride = 2;
  1823. break;
  1824. case GL_RED:
  1825. case GL_RGB:
  1826. case GL_SRGB:
  1827. mNeedsAlphaAndPickMask = mIsMask = false;
  1828. #if FIX_MASKS
  1829. mAlphaOffset = INVALID_OFFSET;
  1830. #endif
  1831. return; // No alpha channel.
  1832. case GL_RGBA:
  1833. case GL_SRGB_ALPHA:
  1834. mAlphaStride = 4;
  1835. break;
  1836. case GL_BGRA_EXT:
  1837. mAlphaStride = 4;
  1838. break;
  1839. default:
  1840. break;
  1841. }
  1842. mAlphaOffset = -1;
  1843. if (mFormatType == GL_UNSIGNED_BYTE)
  1844. {
  1845. mAlphaOffset = mAlphaStride - 1;
  1846. }
  1847. else if (is_little_endian())
  1848. {
  1849. if (mFormatType == GL_UNSIGNED_INT_8_8_8_8)
  1850. {
  1851. mAlphaOffset = 0;
  1852. }
  1853. else if (mFormatType == GL_UNSIGNED_INT_8_8_8_8_REV)
  1854. {
  1855. mAlphaOffset = 3;
  1856. }
  1857. }
  1858. else // Big endian
  1859. {
  1860. if (mFormatType == GL_UNSIGNED_INT_8_8_8_8)
  1861. {
  1862. mAlphaOffset = 3;
  1863. }
  1864. else if (mFormatType == GL_UNSIGNED_INT_8_8_8_8_REV)
  1865. {
  1866. mAlphaOffset = 0;
  1867. }
  1868. }
  1869. if (mAlphaStride < 1 || // Unsupported format
  1870. mAlphaOffset < 0 || // Unsupported type
  1871. (mFormatPrimary == GL_BGRA_EXT &&
  1872. mFormatType != GL_UNSIGNED_BYTE)) // Unknown situation
  1873. {
  1874. llwarns << "Cannot analyze alpha for image with format type "
  1875. << std::hex << mFormatType << std::dec << llendl;
  1876. mNeedsAlphaAndPickMask = mIsMask = false;
  1877. #if FIX_MASKS
  1878. mAlphaOffset = INVALID_OFFSET;
  1879. #endif
  1880. }
  1881. }
  1882. void LLImageGL::analyzeAlpha(const void* data_in, U32 w, U32 h)
  1883. {
  1884. if (!mNeedsAlphaAndPickMask)
  1885. {
  1886. return;
  1887. }
  1888. U32 length = w * h;
  1889. U32 alphatotal = 0;
  1890. U32 sample[16];
  1891. memset(sample, 0, sizeof(U32) * 16);
  1892. // Generate histogram of quantized alpha. Also add-in the histogram of a
  1893. // 2x2 box-sampled version. The idea is this will mid-skew the data (and
  1894. // thus increase the chances of not being used as a mask) from high-
  1895. // frequency alpha maps which suffer the worst from aliasing when used as
  1896. // alpha masks.
  1897. if (w >= 2 && h >= 2)
  1898. {
  1899. llassert(w % 2 == 0);
  1900. llassert(h % 2 == 0);
  1901. const GLubyte* rowstart = (const GLubyte*)data_in + mAlphaOffset;
  1902. for (U32 y = 0; y < h; y += 2)
  1903. {
  1904. const GLubyte* current = rowstart;
  1905. for (U32 x = 0; x < w; x += 2)
  1906. {
  1907. const U32 s1 = current[0];
  1908. alphatotal += s1;
  1909. const U32 s2 = current[w * mAlphaStride];
  1910. alphatotal += s2;
  1911. current += mAlphaStride;
  1912. const U32 s3 = current[0];
  1913. alphatotal += s3;
  1914. const U32 s4 = current[w * mAlphaStride];
  1915. alphatotal += s4;
  1916. current += mAlphaStride;
  1917. ++sample[s1 / 16];
  1918. ++sample[s2 / 16];
  1919. ++sample[s3 / 16];
  1920. ++sample[s4 / 16];
  1921. const U32 asum = (s1 + s2 + s3 + s4);
  1922. alphatotal += asum;
  1923. sample[asum / 64] += 4;
  1924. }
  1925. rowstart += 2 * w * mAlphaStride;
  1926. }
  1927. length *= 2; // we sampled everything twice, essentially
  1928. }
  1929. else
  1930. {
  1931. const GLubyte* current = ((const GLubyte*)data_in) + mAlphaOffset;
  1932. for (U32 i = 0; i < length; ++i)
  1933. {
  1934. const U32 s1 = *current;
  1935. alphatotal += s1;
  1936. ++sample[s1 / 16];
  1937. current += mAlphaStride;
  1938. }
  1939. }
  1940. // If more than 1/16th of alpha samples are mid-range, this shouldn't be
  1941. // treated as a 1-bit mask. Also, if all of the alpha samples are clumped
  1942. // on one half of the range (but not at an absolute extreme), then consider
  1943. // this to be an intentional effect and don't treat as a mask.
  1944. U32 midrangetotal = 0;
  1945. for (U32 i = 2; i < 13; ++i)
  1946. {
  1947. midrangetotal += sample[i];
  1948. }
  1949. U32 lowerhalftotal = 0;
  1950. for (U32 i = 0; i < 8; ++i)
  1951. {
  1952. lowerhalftotal += sample[i];
  1953. }
  1954. U32 upperhalftotal = 0;
  1955. for (U32 i = 8; i < 16; ++i)
  1956. {
  1957. upperhalftotal += sample[i];
  1958. }
  1959. if (midrangetotal > length / 48 || // Lots of midrange, or
  1960. // All close to transparent but not all totally transparent, or
  1961. (lowerhalftotal == length && alphatotal != 0) ||
  1962. // All close to opaque but not all totally opaque
  1963. (upperhalftotal == length && alphatotal != 255 * length))
  1964. {
  1965. mIsMask = false; // Not suitable for masking
  1966. }
  1967. else
  1968. {
  1969. mIsMask = true;
  1970. }
  1971. }
  1972. U32 LLImageGL::createPickMask(U32 width, U32 height)
  1973. {
  1974. freePickMask();
  1975. U32 pick_width = width / 2 + 1;
  1976. U32 pick_height = height / 2 + 1;
  1977. U32 size = pick_width * pick_height;
  1978. size = (size + 7) / 8; // pixelcount-to-bits
  1979. mPickMask = new (std::nothrow) U8[size];
  1980. if (mPickMask)
  1981. {
  1982. mPickMaskWidth = pick_width - 1;
  1983. mPickMaskHeight = pick_height - 1;
  1984. memset(mPickMask, 0, sizeof(U8) * size);
  1985. }
  1986. else
  1987. {
  1988. mPickMaskWidth = 0;
  1989. mPickMaskHeight = 0;
  1990. size = 0;
  1991. }
  1992. return size;
  1993. }
  1994. void LLImageGL::freePickMask()
  1995. {
  1996. if (mPickMask)
  1997. {
  1998. delete[] mPickMask;
  1999. mPickMask = NULL;
  2000. }
  2001. mPickMaskWidth = mPickMaskHeight = 0;
  2002. }
  2003. void LLImageGL::updatePickMask(U32 width, U32 height, const U8* data_in)
  2004. {
  2005. if (!mNeedsAlphaAndPickMask)
  2006. {
  2007. return;
  2008. }
  2009. if (mFormatType != GL_UNSIGNED_BYTE ||
  2010. (mFormatPrimary != GL_RGBA && mFormatPrimary != GL_SRGB_ALPHA))
  2011. {
  2012. // Cannot generate a pick mask for this texture
  2013. freePickMask();
  2014. return;
  2015. }
  2016. #if LL_HAS_ASSERT
  2017. const U32 size =
  2018. #endif
  2019. createPickMask(width, height);
  2020. U32 pick_bit = 0;
  2021. for (U32 y = 0; y < height; y += 2)
  2022. {
  2023. for (U32 x = 0; x < width; x += 2)
  2024. {
  2025. U8 alpha = data_in[(y * width + x) * 4 + 3];
  2026. if (alpha > 32)
  2027. {
  2028. U32 pick_idx = pick_bit / 8;
  2029. U32 pick_offset = pick_bit % 8;
  2030. llassert(pick_idx < size);
  2031. mPickMask[pick_idx] |= 1 << pick_offset;
  2032. }
  2033. ++pick_bit;
  2034. }
  2035. }
  2036. }
  2037. bool LLImageGL::getMask(const LLVector2& tc)
  2038. {
  2039. bool res = true;
  2040. if (mPickMask)
  2041. {
  2042. F32 u, v;
  2043. if (LL_LIKELY(tc.isFinite()))
  2044. {
  2045. u = tc.mV[0] - floorf(tc.mV[0]);
  2046. v = tc.mV[1] - floorf(tc.mV[1]);
  2047. }
  2048. else
  2049. {
  2050. llwarns_sparse << "Non-finite u/v in mask pick !" << llendl;
  2051. u = v = 0.f;
  2052. // removing assert per EXT-4388
  2053. //llassert(false);
  2054. }
  2055. if (LL_UNLIKELY(u < 0.f || u > 1.f || v < 0.f || v > 1.f))
  2056. {
  2057. llwarns_sparse << "u/v out of range in image mask pick !"
  2058. << llendl;
  2059. u = v = 0.f;
  2060. // removing assert per EXT-4388
  2061. //llassert(false);
  2062. }
  2063. U32 x = llfloor(u * mPickMaskWidth);
  2064. U32 y = llfloor(v * mPickMaskHeight);
  2065. if (LL_UNLIKELY(x > mPickMaskWidth))
  2066. {
  2067. llwarns_sparse << "Width overrun on pick mask read !" << llendl;
  2068. x = llmax(mPickMaskWidth, 0);
  2069. }
  2070. if (LL_UNLIKELY(y > mPickMaskHeight))
  2071. {
  2072. llwarns_sparse << "Height overrun on pick mask read !" << llendl;
  2073. y = llmax(mPickMaskHeight, 0);
  2074. }
  2075. U32 idx = y * mPickMaskWidth + x;
  2076. U32 offset = idx % 8;
  2077. res = (mPickMask[idx / 8] & (1 << offset)) != 0;
  2078. }
  2079. return res;
  2080. }
  2081. //static
  2082. void LLImageGL::initThread(LLWindow* windowp, S32 threads)
  2083. {
  2084. if (!threads || sThread)
  2085. {
  2086. return;
  2087. }
  2088. if (threads < 0) // Automatic setting requested
  2089. {
  2090. // Limit our pool to 32 threads (and thus 32 GL contexts); this matches
  2091. // the limit for the threaded image decoder (see LLImageDecodeThread's
  2092. // construtor code). HB
  2093. threads = llmin(LLCPUInfo::getInstance()->getMaxThreadConcurrency(),
  2094. 32U);
  2095. }
  2096. sThread = new LLImageGLThread(windowp, threads);
  2097. gImageQueuep = LLWorkQueue::getNamedInstance("LLImageGL");
  2098. }
  2099. //static
  2100. void LLImageGL::stopThread()
  2101. {
  2102. LLImageGLThread::sEnabled = false;
  2103. if (sThread)
  2104. {
  2105. gImageQueuep.reset();
  2106. sThread->close();
  2107. // Note: thread instances are kept in memory and cleared at viewer
  2108. // exit, which prevents crashes... HB
  2109. sThread = NULL;
  2110. }
  2111. }
  2112. ///////////////////////////////////////////////////////////////////////////////
  2113. // LLImageGLThread class
  2114. ///////////////////////////////////////////////////////////////////////////////
  2115. // Global variable
  2116. LLWorkQueue::weak_t gImageQueuep;
  2117. // Used to track the LLImageGLThread instances and destroy them on viewer
  2118. // shutdown (i.e. once their child threads have been stopped). HB
  2119. typedef std::set<std::unique_ptr<LLImageGLThread> > instances_set_t;
  2120. static instances_set_t sThreadInstances;
  2121. // Static members
  2122. bool LLImageGLThread::sEnabled = false;
  2123. // -1 = free VRAM is unknown.
  2124. LLAtomicS32 LLImageGLThread::sFreeVRAMMegabytes(-1);
  2125. // Must be called from main thread
  2126. LLImageGLThread::LLImageGLThread(LLWindow* window, U32 threads)
  2127. : LLThreadPool("LLImageGL", threads),
  2128. mWindow(window),
  2129. mTheadCounter(0)
  2130. {
  2131. assert_main_thread();
  2132. llassert_always(threads > 0); // At least one thread, please !
  2133. sThreadInstances.emplace(this);
  2134. llinfos << "Initializing with " << threads << " worker threads." << llendl;
  2135. // We must create one GL context per thread, while still in the main thread
  2136. for (U32 i = 0; i < threads; ++i)
  2137. {
  2138. mContexts.push_back(mWindow->createSharedContext());
  2139. }
  2140. LLThreadPool::start(true); // true = wait until all threads are started.
  2141. // Restore the main thread context
  2142. mWindow->makeContextCurrent(NULL);
  2143. // We can now use the threaded image creation
  2144. sEnabled = true;
  2145. }
  2146. // Called from child threads in LLThreadPool.
  2147. //virtual
  2148. void LLImageGLThread::run()
  2149. {
  2150. // We must perform setup on this thread before actually servicing our
  2151. // LLWorkQueue, likewise cleanup afterwards.
  2152. // Do not let threads race for GL contexts on mWindow, and protect
  2153. // mTheadCounter from thread concurrency.
  2154. mThreadsMutex.lock();
  2155. if ((size_t)mTheadCounter >= mContexts.size()) // Paranoia
  2156. {
  2157. llerrs << "More threads created than available contexts ("
  2158. << mContexts.size() << ")" << llendl;
  2159. }
  2160. // Keep these values on stack for use on thread exit (see below)
  2161. void* context = mContexts[mTheadCounter++];
  2162. std::string name = getThreadName(LLThread::thisThreadIdHash());
  2163. if (!context)
  2164. {
  2165. llwarns << "No available GL context for thread " << name
  2166. << ". Aborting this thread !" << llendl;
  2167. mThreadsMutex.unlock();
  2168. doIncStartedThreads(); // Account as started nonetheless.
  2169. return;
  2170. }
  2171. llinfos << "Initializing GL for thread " << name << " with context: "
  2172. << std::hex << (intptr_t)context << std::dec << llendl;
  2173. // Set the context on the viewer window and start GL for our thread (gGL is
  2174. // thread_local).
  2175. mWindow->makeContextCurrent(context);
  2176. gGL.init();
  2177. mThreadsMutex.unlock();
  2178. // It is now safe to consider that this thread has indeed fully started.
  2179. doIncStartedThreads();
  2180. // Run the queue servicing, until the queue is closed.
  2181. LLThreadPool::run();
  2182. llinfos << "Shutting down GL for thread " << name << " with GL context: "
  2183. << std::hex << (intptr_t)context << std::dec << llendl;
  2184. gGL.shutdown();
  2185. mWindow->destroySharedContext(context);
  2186. }
  2187. // Must be called from main thread
  2188. //static
  2189. void LLImageGLThread::cleanup()
  2190. {
  2191. assert_main_thread();
  2192. size_t count = sThreadInstances.size();
  2193. // Since this is a set of std::unique_ptr's, clearing it will cause all
  2194. // stored instances to get automatically destroyed.
  2195. sThreadInstances.clear();
  2196. llinfos << "Number of destroyed instances: " << count << llendl;
  2197. }
  2198. // Called from main thread
  2199. //static
  2200. void LLImageGLThread::updateFreeVRAM()
  2201. {
  2202. LL_TRACY_TIMER(TRC_IMAGEGLTHREAD_UPDATE_FREE_VRAM);
  2203. // Post update to background thread if available, otherwise execute
  2204. // immediately.
  2205. if (sEnabled)
  2206. {
  2207. auto queue = gImageQueuep.lock();
  2208. if (queue)
  2209. {
  2210. queue->post([]() { readFreeVRAM(); });
  2211. return;
  2212. }
  2213. }
  2214. readFreeVRAM();
  2215. }
  2216. // Called from main or child threads
  2217. //static
  2218. void LLImageGLThread::readFreeVRAM()
  2219. {
  2220. LL_TRACY_TIMER(TRC_IMAGEGLTHREAD_READ_VRAM);
  2221. if (gGLManager.mHasATIMemInfo)
  2222. {
  2223. // Reference:
  2224. // https://registry.khronos.org/OpenGL/extensions/ATI/ATI_meminfo.txt
  2225. GLint meminfo[4] = { -1, 0, 0, 0 };
  2226. glGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, meminfo);
  2227. if (meminfo[0] >= 0) // If call succeeded. HB
  2228. {
  2229. sFreeVRAMMegabytes = meminfo[0] / 1024; // Convert to MB ! HB
  2230. LL_DEBUGS("ImageGLThread") << "Free VRAM: " << sFreeVRAMMegabytes
  2231. << "MB" << LL_ENDL;
  2232. }
  2233. else
  2234. {
  2235. LL_DEBUGS_ONCE("ImageGLThread") << "GL_TEXTURE_FREE_MEMORY_ATI failed."
  2236. << LL_ENDL;
  2237. }
  2238. stop_glerror(); // Clear any error resulting from this call. HB
  2239. }
  2240. else if (gGLManager.mHasNVXMemInfo)
  2241. {
  2242. GLint free_memory_kb = -1;
  2243. glGetIntegerv(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX,
  2244. &free_memory_kb);
  2245. if (free_memory_kb >= 0) // If call succeeded. HB
  2246. {
  2247. sFreeVRAMMegabytes = free_memory_kb / 1024; // Convert to MB
  2248. LL_DEBUGS("ImageGLThread") << "Free VRAM: " << sFreeVRAMMegabytes
  2249. << "MB" << LL_ENDL;
  2250. }
  2251. else
  2252. {
  2253. LL_DEBUGS_ONCE("ImageGLThread") << "GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX failed."
  2254. << LL_ENDL;
  2255. }
  2256. stop_glerror(); // Clear any error resulting from this call. HB
  2257. }
  2258. }