UltraHDRLoader.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. import {
  2. ClampToEdgeWrapping,
  3. DataTexture,
  4. DataUtils,
  5. FileLoader,
  6. HalfFloatType,
  7. LinearFilter,
  8. LinearMipMapLinearFilter,
  9. LinearSRGBColorSpace,
  10. Loader,
  11. RGBAFormat,
  12. UVMapping,
  13. } from 'three';
  14. /**
  15. * UltraHDR Image Format - https://developer.android.com/media/platform/hdr-image-format
  16. *
  17. * Short format brief:
  18. *
  19. * [JPEG headers]
  20. * [XMP metadata describing the MPF container and *both* SDR and gainmap images]
  21. * [Optional metadata] [EXIF] [ICC Profile]
  22. * [SDR image]
  23. * [XMP metadata describing only the gainmap image]
  24. * [Gainmap image]
  25. *
  26. * Each section is separated by a 0xFFXX byte followed by a descriptor byte (0xFFE0, 0xFFE1, 0xFFE2.)
  27. * Binary image storages are prefixed with a unique 0xFFD8 16-bit descriptor.
  28. */
  29. // Calculating this SRGB powers is extremely slow for 4K images and can be sufficiently precalculated for a 3-4x speed boost
  30. const SRGB_TO_LINEAR = Array( 1024 )
  31. .fill( 0 )
  32. .map( ( _, value ) =>
  33. Math.pow( ( value / 255 ) * 0.9478672986 + 0.0521327014, 2.4 )
  34. );
  35. /**
  36. * A loader for the Ultra HDR Image Format.
  37. *
  38. * Existing HDR or EXR textures can be converted to Ultra HDR with this [tool]{@link https://gainmap-creator.monogrid.com/}.
  39. *
  40. * Current feature set:
  41. * - JPEG headers (required)
  42. * - XMP metadata (required)
  43. * - XMP validation (not implemented)
  44. * - EXIF profile (not implemented)
  45. * - ICC profile (not implemented)
  46. * - Binary storage for SDR & HDR images (required)
  47. * - Gainmap metadata (required)
  48. * - Non-JPEG image formats (not implemented)
  49. * - Primary image as an HDR image (not implemented)
  50. *
  51. * ```js
  52. * const loader = new UltraHDRLoader();
  53. * const texture = await loader.loadAsync( 'textures/equirectangular/ice_planet_close.jpg' );
  54. * texture.mapping = THREE.EquirectangularReflectionMapping;
  55. *
  56. * scene.background = texture;
  57. * scene.environment = texture;
  58. * ```
  59. *
  60. * @augments Loader
  61. */
  62. class UltraHDRLoader extends Loader {
  63. /**
  64. * Constructs a new Ultra HDR loader.
  65. *
  66. * @param {LoadingManager} [manager] - The loading manager.
  67. */
  68. constructor( manager ) {
  69. super( manager );
  70. /**
  71. * The texture type.
  72. *
  73. * @type {(HalfFloatType|FloatType)}
  74. * @default HalfFloatType
  75. */
  76. this.type = HalfFloatType;
  77. }
  78. /**
  79. * Sets the texture type.
  80. *
  81. * @param {(HalfFloatType|FloatType)} value - The texture type to set.
  82. * @return {RGBELoader} A reference to this loader.
  83. */
  84. setDataType( value ) {
  85. this.type = value;
  86. return this;
  87. }
  88. /**
  89. * Parses the given Ultra HDR texture data.
  90. *
  91. * @param {ArrayBuffer} buffer - The raw texture data.
  92. * @param {Function} onLoad - The `onLoad` callback.
  93. */
  94. parse( buffer, onLoad ) {
  95. const xmpMetadata = {
  96. version: null,
  97. baseRenditionIsHDR: null,
  98. gainMapMin: null,
  99. gainMapMax: null,
  100. gamma: null,
  101. offsetSDR: null,
  102. offsetHDR: null,
  103. hdrCapacityMin: null,
  104. hdrCapacityMax: null,
  105. };
  106. const textDecoder = new TextDecoder();
  107. const data = new DataView( buffer );
  108. let byteOffset = 0;
  109. const sections = [];
  110. while ( byteOffset < data.byteLength ) {
  111. const byte = data.getUint8( byteOffset );
  112. if ( byte === 0xff ) {
  113. const leadingByte = data.getUint8( byteOffset + 1 );
  114. if (
  115. [
  116. /* Valid section headers */
  117. 0xd8, // SOI
  118. 0xe0, // APP0
  119. 0xe1, // APP1
  120. 0xe2, // APP2
  121. ].includes( leadingByte )
  122. ) {
  123. sections.push( {
  124. sectionType: leadingByte,
  125. section: [ byte, leadingByte ],
  126. sectionOffset: byteOffset + 2,
  127. } );
  128. byteOffset += 2;
  129. } else {
  130. sections[ sections.length - 1 ].section.push( byte, leadingByte );
  131. byteOffset += 2;
  132. }
  133. } else {
  134. sections[ sections.length - 1 ].section.push( byte );
  135. byteOffset ++;
  136. }
  137. }
  138. let primaryImage, gainmapImage;
  139. for ( let i = 0; i < sections.length; i ++ ) {
  140. const { sectionType, section, sectionOffset } = sections[ i ];
  141. if ( sectionType === 0xe0 ) {
  142. /* JPEG Header - no useful information */
  143. } else if ( sectionType === 0xe1 ) {
  144. /* XMP Metadata */
  145. this._parseXMPMetadata(
  146. textDecoder.decode( new Uint8Array( section ) ),
  147. xmpMetadata
  148. );
  149. } else if ( sectionType === 0xe2 ) {
  150. /* Data Sections - MPF / EXIF / ICC Profile */
  151. const sectionData = new DataView(
  152. new Uint8Array( section.slice( 2 ) ).buffer
  153. );
  154. const sectionHeader = sectionData.getUint32( 2, false );
  155. if ( sectionHeader === 0x4d504600 ) {
  156. /* MPF Section */
  157. /* Section contains a list of static bytes and ends with offsets indicating location of SDR and gainmap images */
  158. /* First bytes after header indicate little / big endian ordering (0x49492A00 - LE / 0x4D4D002A - BE) */
  159. /*
  160. ... 60 bytes indicating tags, versions, etc. ...
  161. bytes | bits | description
  162. 4 32 primary image size
  163. 4 32 primary image offset
  164. 2 16 0x0000
  165. 2 16 0x0000
  166. 4 32 0x00000000
  167. 4 32 gainmap image size
  168. 4 32 gainmap image offset
  169. 2 16 0x0000
  170. 2 16 0x0000
  171. */
  172. const mpfLittleEndian = sectionData.getUint32( 6 ) === 0x49492a00;
  173. const mpfBytesOffset = 60;
  174. /* SDR size includes the metadata length, SDR offset is always 0 */
  175. const primaryImageSize = sectionData.getUint32(
  176. mpfBytesOffset,
  177. mpfLittleEndian
  178. );
  179. const primaryImageOffset = sectionData.getUint32(
  180. mpfBytesOffset + 4,
  181. mpfLittleEndian
  182. );
  183. /* Gainmap size is an absolute value starting from its offset, gainmap offset needs 6 bytes padding to take into account 0x00 bytes at the end of XMP */
  184. const gainmapImageSize = sectionData.getUint32(
  185. mpfBytesOffset + 16,
  186. mpfLittleEndian
  187. );
  188. const gainmapImageOffset =
  189. sectionData.getUint32( mpfBytesOffset + 20, mpfLittleEndian ) +
  190. sectionOffset +
  191. 6;
  192. primaryImage = new Uint8Array(
  193. data.buffer,
  194. primaryImageOffset,
  195. primaryImageSize
  196. );
  197. gainmapImage = new Uint8Array(
  198. data.buffer,
  199. gainmapImageOffset,
  200. gainmapImageSize
  201. );
  202. }
  203. }
  204. }
  205. /* Minimal sufficient validation - https://developer.android.com/media/platform/hdr-image-format#signal_of_the_format */
  206. if ( ! xmpMetadata.version ) {
  207. throw new Error( 'THREE.UltraHDRLoader: Not a valid UltraHDR image' );
  208. }
  209. if ( primaryImage && gainmapImage ) {
  210. this._applyGainmapToSDR(
  211. xmpMetadata,
  212. primaryImage,
  213. gainmapImage,
  214. ( hdrBuffer, width, height ) => {
  215. onLoad( {
  216. width,
  217. height,
  218. data: hdrBuffer,
  219. format: RGBAFormat,
  220. type: this.type,
  221. } );
  222. },
  223. ( error ) => {
  224. throw new Error( error );
  225. }
  226. );
  227. } else {
  228. throw new Error( 'THREE.UltraHDRLoader: Could not parse UltraHDR images' );
  229. }
  230. }
  231. /**
  232. * Starts loading from the given URL and passes the loaded Ultra HDR texture
  233. * to the `onLoad()` callback.
  234. *
  235. * @param {string} url - The path/URL of the files to be loaded. This can also be a data URI.
  236. * @param {function(DataTexture, Object)} onLoad - Executed when the loading process has been finished.
  237. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  238. * @param {onErrorCallback} onError - Executed when errors occur.
  239. * @return {DataTexture} The Ultra HDR texture.
  240. */
  241. load( url, onLoad, onProgress, onError ) {
  242. const texture = new DataTexture(
  243. this.type === HalfFloatType ? new Uint16Array() : new Float32Array(),
  244. 0,
  245. 0,
  246. RGBAFormat,
  247. this.type,
  248. UVMapping,
  249. ClampToEdgeWrapping,
  250. ClampToEdgeWrapping,
  251. LinearFilter,
  252. LinearMipMapLinearFilter,
  253. 1,
  254. LinearSRGBColorSpace
  255. );
  256. texture.generateMipmaps = true;
  257. texture.flipY = true;
  258. const loader = new FileLoader( this.manager );
  259. loader.setResponseType( 'arraybuffer' );
  260. loader.setRequestHeader( this.requestHeader );
  261. loader.setPath( this.path );
  262. loader.setWithCredentials( this.withCredentials );
  263. loader.load( url, ( buffer ) => {
  264. try {
  265. this.parse(
  266. buffer,
  267. ( texData ) => {
  268. texture.image = {
  269. data: texData.data,
  270. width: texData.width,
  271. height: texData.height,
  272. };
  273. texture.needsUpdate = true;
  274. if ( onLoad ) onLoad( texture, texData );
  275. }
  276. );
  277. } catch ( error ) {
  278. if ( onError ) onError( error );
  279. console.error( error );
  280. }
  281. }, onProgress, onError );
  282. return texture;
  283. }
  284. _parseXMPMetadata( xmpDataString, xmpMetadata ) {
  285. const domParser = new DOMParser();
  286. const xmpXml = domParser.parseFromString(
  287. xmpDataString.substring(
  288. xmpDataString.indexOf( '<' ),
  289. xmpDataString.lastIndexOf( '>' ) + 1
  290. ),
  291. 'text/xml'
  292. );
  293. /* Determine if given XMP metadata is the primary GContainer descriptor or a gainmap descriptor */
  294. const [ hasHDRContainerDescriptor ] = xmpXml.getElementsByTagName(
  295. 'Container:Directory'
  296. );
  297. if ( hasHDRContainerDescriptor ) {
  298. /* There's not much useful information in the container descriptor besides memory-validation */
  299. } else {
  300. /* Gainmap descriptor - defaults from https://developer.android.com/media/platform/hdr-image-format#HDR_gain_map_metadata */
  301. const [ gainmapNode ] = xmpXml.getElementsByTagName( 'rdf:Description' );
  302. xmpMetadata.version = gainmapNode.getAttribute( 'hdrgm:Version' );
  303. xmpMetadata.baseRenditionIsHDR =
  304. gainmapNode.getAttribute( 'hdrgm:BaseRenditionIsHDR' ) === 'True';
  305. xmpMetadata.gainMapMin = parseFloat(
  306. gainmapNode.getAttribute( 'hdrgm:GainMapMin' ) || 0.0
  307. );
  308. xmpMetadata.gainMapMax = parseFloat(
  309. gainmapNode.getAttribute( 'hdrgm:GainMapMax' ) || 1.0
  310. );
  311. xmpMetadata.gamma = parseFloat(
  312. gainmapNode.getAttribute( 'hdrgm:Gamma' ) || 1.0
  313. );
  314. xmpMetadata.offsetSDR = parseFloat(
  315. gainmapNode.getAttribute( 'hdrgm:OffsetSDR' ) / ( 1 / 64 )
  316. );
  317. xmpMetadata.offsetHDR = parseFloat(
  318. gainmapNode.getAttribute( 'hdrgm:OffsetHDR' ) / ( 1 / 64 )
  319. );
  320. xmpMetadata.hdrCapacityMin = parseFloat(
  321. gainmapNode.getAttribute( 'hdrgm:HDRCapacityMin' ) || 0.0
  322. );
  323. xmpMetadata.hdrCapacityMax = parseFloat(
  324. gainmapNode.getAttribute( 'hdrgm:HDRCapacityMax' ) || 1.0
  325. );
  326. }
  327. }
  328. _srgbToLinear( value ) {
  329. if ( value / 255 < 0.04045 ) {
  330. return ( value / 255 ) * 0.0773993808;
  331. }
  332. if ( value < 1024 ) {
  333. return SRGB_TO_LINEAR[ ~ ~ value ];
  334. }
  335. return Math.pow( ( value / 255 ) * 0.9478672986 + 0.0521327014, 2.4 );
  336. }
  337. _applyGainmapToSDR(
  338. xmpMetadata,
  339. sdrBuffer,
  340. gainmapBuffer,
  341. onSuccess,
  342. onError
  343. ) {
  344. const getImageDataFromBuffer = ( buffer ) =>
  345. new Promise( ( resolve, reject ) => {
  346. const imageLoader = document.createElement( 'img' );
  347. imageLoader.onload = () => {
  348. const image = {
  349. width: imageLoader.naturalWidth,
  350. height: imageLoader.naturalHeight,
  351. source: imageLoader,
  352. };
  353. URL.revokeObjectURL( imageLoader.src );
  354. resolve( image );
  355. };
  356. imageLoader.onerror = () => {
  357. URL.revokeObjectURL( imageLoader.src );
  358. reject();
  359. };
  360. imageLoader.src = URL.createObjectURL(
  361. new Blob( [ buffer ], { type: 'image/jpeg' } )
  362. );
  363. } );
  364. Promise.all( [
  365. getImageDataFromBuffer( sdrBuffer ),
  366. getImageDataFromBuffer( gainmapBuffer ),
  367. ] )
  368. .then( ( [ sdrImage, gainmapImage ] ) => {
  369. const sdrImageAspect = sdrImage.width / sdrImage.height;
  370. const gainmapImageAspect = gainmapImage.width / gainmapImage.height;
  371. if ( sdrImageAspect !== gainmapImageAspect ) {
  372. onError(
  373. 'THREE.UltraHDRLoader Error: Aspect ratio mismatch between SDR and Gainmap images'
  374. );
  375. return;
  376. }
  377. const canvas = document.createElement( 'canvas' );
  378. const ctx = canvas.getContext( '2d', {
  379. willReadFrequently: true,
  380. colorSpace: 'srgb',
  381. } );
  382. canvas.width = sdrImage.width;
  383. canvas.height = sdrImage.height;
  384. /* Use out-of-the-box interpolation of Canvas API to scale gainmap to fit the SDR resolution */
  385. ctx.drawImage(
  386. gainmapImage.source,
  387. 0,
  388. 0,
  389. gainmapImage.width,
  390. gainmapImage.height,
  391. 0,
  392. 0,
  393. sdrImage.width,
  394. sdrImage.height
  395. );
  396. const gainmapImageData = ctx.getImageData(
  397. 0,
  398. 0,
  399. sdrImage.width,
  400. sdrImage.height,
  401. { colorSpace: 'srgb' }
  402. );
  403. ctx.drawImage( sdrImage.source, 0, 0 );
  404. const sdrImageData = ctx.getImageData(
  405. 0,
  406. 0,
  407. sdrImage.width,
  408. sdrImage.height,
  409. { colorSpace: 'srgb' }
  410. );
  411. /* HDR Recovery formula - https://developer.android.com/media/platform/hdr-image-format#use_the_gain_map_to_create_adapted_HDR_rendition */
  412. let hdrBuffer;
  413. if ( this.type === HalfFloatType ) {
  414. hdrBuffer = new Uint16Array( sdrImageData.data.length ).fill( 23544 );
  415. } else {
  416. hdrBuffer = new Float32Array( sdrImageData.data.length ).fill( 255 );
  417. }
  418. const maxDisplayBoost = Math.sqrt(
  419. Math.pow(
  420. /* 1.8 instead of 2 near-perfectly rectifies approximations introduced by precalculated SRGB_TO_LINEAR values */
  421. 1.8,
  422. xmpMetadata.hdrCapacityMax
  423. )
  424. );
  425. const unclampedWeightFactor =
  426. ( Math.log2( maxDisplayBoost ) - xmpMetadata.hdrCapacityMin ) /
  427. ( xmpMetadata.hdrCapacityMax - xmpMetadata.hdrCapacityMin );
  428. const weightFactor = Math.min(
  429. Math.max( unclampedWeightFactor, 0.0 ),
  430. 1.0
  431. );
  432. const useGammaOne = xmpMetadata.gamma === 1.0;
  433. for (
  434. let pixelIndex = 0;
  435. pixelIndex < sdrImageData.data.length;
  436. pixelIndex += 4
  437. ) {
  438. const x = ( pixelIndex / 4 ) % sdrImage.width;
  439. const y = Math.floor( pixelIndex / 4 / sdrImage.width );
  440. for ( let channelIndex = 0; channelIndex < 3; channelIndex ++ ) {
  441. const sdrValue = sdrImageData.data[ pixelIndex + channelIndex ];
  442. const gainmapIndex = ( y * sdrImage.width + x ) * 4 + channelIndex;
  443. const gainmapValue = gainmapImageData.data[ gainmapIndex ] / 255.0;
  444. /* Gamma is 1.0 by default */
  445. const logRecovery = useGammaOne
  446. ? gainmapValue
  447. : Math.pow( gainmapValue, 1.0 / xmpMetadata.gamma );
  448. const logBoost =
  449. xmpMetadata.gainMapMin * ( 1.0 - logRecovery ) +
  450. xmpMetadata.gainMapMax * logRecovery;
  451. const hdrValue =
  452. ( sdrValue + xmpMetadata.offsetSDR ) *
  453. ( logBoost * weightFactor === 0.0
  454. ? 1.0
  455. : Math.pow( 2, logBoost * weightFactor ) ) -
  456. xmpMetadata.offsetHDR;
  457. const linearHDRValue = Math.min(
  458. Math.max( this._srgbToLinear( hdrValue ), 0 ),
  459. 65504
  460. );
  461. hdrBuffer[ pixelIndex + channelIndex ] =
  462. this.type === HalfFloatType
  463. ? DataUtils.toHalfFloat( linearHDRValue )
  464. : linearHDRValue;
  465. }
  466. }
  467. onSuccess( hdrBuffer, sdrImage.width, sdrImage.height );
  468. } )
  469. .catch( () => {
  470. throw new Error(
  471. 'THREE.UltraHDRLoader Error: Could not parse UltraHDR images'
  472. );
  473. } );
  474. }
  475. }
  476. export { UltraHDRLoader };
粤ICP备19079148号