createVerticesFromHeightmap.js 112 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623
  1. /**
  2. * Cesium - https://github.com/CesiumGS/cesium
  3. *
  4. * Copyright 2011-2020 Cesium Contributors
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. *
  18. * Columbus View (Pat. Pend.)
  19. *
  20. * Portions licensed separately.
  21. * See https://github.com/CesiumGS/cesium/blob/master/LICENSE.md for full licensing details.
  22. */
  23. define(['./when-8d13db60', './Check-70bec281', './Math-61ede240', './Cartographic-fe4be337', './Cartesian4-5af5bb24', './createTaskProcessorWorker', './Cartesian2-85064f09', './BoundingSphere-8f8a682c', './RuntimeError-ba10bc3e', './WebGLConstants-4c11ee5f', './ComponentDatatype-5862616f', './FeatureDetection-7bd32c34', './Transforms-878b6816', './buildModuleUrl-e7952659', './AttributeCompression-84a90a13', './IntersectionTests-ca40c01c', './Plane-b1361c67', './WebMercatorProjection-80c70558', './EllipsoidTangentPlane-0b4ce564', './OrientedBoundingBox-0ede1598', './TerrainEncoding-a807a704'], function (when, Check, _Math, Cartographic, Cartesian4, createTaskProcessorWorker, Cartesian2, BoundingSphere, RuntimeError, WebGLConstants, ComponentDatatype, FeatureDetection, Transforms, buildModuleUrl, AttributeCompression, IntersectionTests, Plane, WebMercatorProjection, EllipsoidTangentPlane, OrientedBoundingBox, TerrainEncoding) { 'use strict';
  24. /**
  25. * The encoding that is used for a heightmap
  26. *
  27. * @exports HeightmapEncoding
  28. */
  29. var HeightmapEncoding = {
  30. /**
  31. * No encoding
  32. *
  33. * @type {Number}
  34. * @constant
  35. */
  36. NONE: 0,
  37. /**
  38. * LERC encoding
  39. *
  40. * @type {Number}
  41. * @constant
  42. *
  43. * @see {@link https://github.com/Esri/lerc|The LERC specification}
  44. */
  45. LERC: 1
  46. };
  47. var HeightmapEncoding$1 = Object.freeze(HeightmapEncoding);
  48. /**
  49. * Contains functions to create a mesh from a heightmap image.
  50. *
  51. * @exports HeightmapTessellator
  52. *
  53. * @private
  54. */
  55. var HeightmapTessellator = {};
  56. /**
  57. * The default structure of a heightmap, as given to {@link HeightmapTessellator.computeVertices}.
  58. *
  59. * @constant
  60. */
  61. HeightmapTessellator.DEFAULT_STRUCTURE = Object.freeze({
  62. heightScale : 1.0,
  63. heightOffset : 0.0,
  64. elementsPerHeight : 1,
  65. stride : 1,
  66. elementMultiplier : 256.0,
  67. isBigEndian : false
  68. });
  69. var cartesian3Scratch = new Cartographic.Cartesian3();
  70. var matrix4Scratch = new BoundingSphere.Matrix4();
  71. var minimumScratch = new Cartographic.Cartesian3();
  72. var maximumScratch = new Cartographic.Cartesian3();
  73. /**
  74. * Fills an array of vertices from a heightmap image.
  75. *
  76. * @param {Object} options Object with the following properties:
  77. * @param {TypedArray} options.heightmap The heightmap to tessellate.
  78. * @param {Number} options.width The width of the heightmap, in height samples.
  79. * @param {Number} options.height The height of the heightmap, in height samples.
  80. * @param {Number} options.skirtHeight The height of skirts to drape at the edges of the heightmap.
  81. * @param {Rectangle} options.nativeRectangle A rectangle in the native coordinates of the heightmap's projection. For
  82. * a heightmap with a geographic projection, this is degrees. For the web mercator
  83. * projection, this is meters.
  84. * @param {Number} [options.exaggeration=1.0] The scale used to exaggerate the terrain.
  85. * @param {Rectangle} [options.rectangle] The rectangle covered by the heightmap, in geodetic coordinates with north, south, east and
  86. * west properties in radians. Either rectangle or nativeRectangle must be provided. If both
  87. * are provided, they're assumed to be consistent.
  88. * @param {Boolean} [options.isGeographic=true] True if the heightmap uses a {@link GeographicProjection}, or false if it uses
  89. * a {@link WebMercatorProjection}.
  90. * @param {Cartesian3} [options.relativeToCenter=Cartesian3.ZERO] The positions will be computed as <code>Cartesian3.subtract(worldPosition, relativeToCenter)</code>.
  91. * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to which the heightmap applies.
  92. * @param {Object} [options.structure] An object describing the structure of the height data.
  93. * @param {Number} [options.structure.heightScale=1.0] The factor by which to multiply height samples in order to obtain
  94. * the height above the heightOffset, in meters. The heightOffset is added to the resulting
  95. * height after multiplying by the scale.
  96. * @param {Number} [options.structure.heightOffset=0.0] The offset to add to the scaled height to obtain the final
  97. * height in meters. The offset is added after the height sample is multiplied by the
  98. * heightScale.
  99. * @param {Number} [options.structure.elementsPerHeight=1] The number of elements in the buffer that make up a single height
  100. * sample. This is usually 1, indicating that each element is a separate height sample. If
  101. * it is greater than 1, that number of elements together form the height sample, which is
  102. * computed according to the structure.elementMultiplier and structure.isBigEndian properties.
  103. * @param {Number} [options.structure.stride=1] The number of elements to skip to get from the first element of
  104. * one height to the first element of the next height.
  105. * @param {Number} [options.structure.elementMultiplier=256.0] The multiplier used to compute the height value when the
  106. * stride property is greater than 1. For example, if the stride is 4 and the strideMultiplier
  107. * is 256, the height is computed as follows:
  108. * `height = buffer[index] + buffer[index + 1] * 256 + buffer[index + 2] * 256 * 256 + buffer[index + 3] * 256 * 256 * 256`
  109. * This is assuming that the isBigEndian property is false. If it is true, the order of the
  110. * elements is reversed.
  111. * @param {Number} [options.structure.lowestEncodedHeight] The lowest value that can be stored in the height buffer. Any heights that are lower
  112. * than this value after encoding with the `heightScale` and `heightOffset` are clamped to this value. For example, if the height
  113. * buffer is a `Uint16Array`, this value should be 0 because a `Uint16Array` cannot store negative numbers. If this parameter is
  114. * not specified, no minimum value is enforced.
  115. * @param {Number} [options.structure.highestEncodedHeight] The highest value that can be stored in the height buffer. Any heights that are higher
  116. * than this value after encoding with the `heightScale` and `heightOffset` are clamped to this value. For example, if the height
  117. * buffer is a `Uint16Array`, this value should be `256 * 256 - 1` or 65535 because a `Uint16Array` cannot store numbers larger
  118. * than 65535. If this parameter is not specified, no maximum value is enforced.
  119. * @param {Boolean} [options.structure.isBigEndian=false] Indicates endianness of the elements in the buffer when the
  120. * stride property is greater than 1. If this property is false, the first element is the
  121. * low-order element. If it is true, the first element is the high-order element.
  122. *
  123. * @example
  124. * var width = 5;
  125. * var height = 5;
  126. * var statistics = Cesium.HeightmapTessellator.computeVertices({
  127. * heightmap : [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0],
  128. * width : width,
  129. * height : height,
  130. * skirtHeight : 0.0,
  131. * nativeRectangle : {
  132. * west : 10.0,
  133. * east : 20.0,
  134. * south : 30.0,
  135. * north : 40.0
  136. * }
  137. * });
  138. *
  139. * var encoding = statistics.encoding;
  140. * var position = encoding.decodePosition(statistics.vertices, index * encoding.getStride());
  141. */
  142. HeightmapTessellator.computeVertices = function(options) {
  143. //>>includeStart('debug', pragmas.debug);
  144. if (!when.defined(options) || !when.defined(options.heightmap)) {
  145. throw new Check.DeveloperError('options.heightmap is required.');
  146. }
  147. if (!when.defined(options.width) || !when.defined(options.height)) {
  148. throw new Check.DeveloperError('options.width and options.height are required.');
  149. }
  150. if (!when.defined(options.nativeRectangle)) {
  151. throw new Check.DeveloperError('options.nativeRectangle is required.');
  152. }
  153. if (!when.defined(options.skirtHeight)) {
  154. throw new Check.DeveloperError('options.skirtHeight is required.');
  155. }
  156. //>>includeEnd('debug');
  157. // This function tends to be a performance hotspot for terrain rendering,
  158. // so it employs a lot of inlining and unrolling as an optimization.
  159. // In particular, the functionality of Ellipsoid.cartographicToCartesian
  160. // is inlined.
  161. var cos = Math.cos;
  162. var sin = Math.sin;
  163. var sqrt = Math.sqrt;
  164. var atan = Math.atan;
  165. var exp = Math.exp;
  166. var piOverTwo = _Math.CesiumMath.PI_OVER_TWO;
  167. var toRadians = _Math.CesiumMath.toRadians;
  168. var heightmap = options.heightmap;
  169. var width = options.width;
  170. var height = options.height;
  171. var skirtHeight = options.skirtHeight;
  172. var isGeographic = when.defaultValue(options.isGeographic, true);
  173. var ellipsoid = when.defaultValue(options.ellipsoid, Cartesian2.Ellipsoid.WGS84);
  174. var oneOverGlobeSemimajorAxis = 1.0 / ellipsoid.maximumRadius;
  175. var nativeRectangle = options.nativeRectangle;
  176. var geographicWest;
  177. var geographicSouth;
  178. var geographicEast;
  179. var geographicNorth;
  180. var rectangle = options.rectangle;
  181. if (!when.defined(rectangle)) {
  182. if (isGeographic) {
  183. geographicWest = toRadians(nativeRectangle.west);
  184. geographicSouth = toRadians(nativeRectangle.south);
  185. geographicEast = toRadians(nativeRectangle.east);
  186. geographicNorth = toRadians(nativeRectangle.north);
  187. } else {
  188. geographicWest = nativeRectangle.west * oneOverGlobeSemimajorAxis;
  189. geographicSouth = piOverTwo - (2.0 * atan(exp(-nativeRectangle.south * oneOverGlobeSemimajorAxis)));
  190. geographicEast = nativeRectangle.east * oneOverGlobeSemimajorAxis;
  191. geographicNorth = piOverTwo - (2.0 * atan(exp(-nativeRectangle.north * oneOverGlobeSemimajorAxis)));
  192. }
  193. } else {
  194. geographicWest = rectangle.west;
  195. geographicSouth = rectangle.south;
  196. geographicEast = rectangle.east;
  197. geographicNorth = rectangle.north;
  198. }
  199. var relativeToCenter = options.relativeToCenter;
  200. var hasRelativeToCenter = when.defined(relativeToCenter);
  201. relativeToCenter = hasRelativeToCenter ? relativeToCenter : Cartographic.Cartesian3.ZERO;
  202. var exaggeration = when.defaultValue(options.exaggeration, 1.0);
  203. var includeWebMercatorT = when.defaultValue(options.includeWebMercatorT, false);
  204. var structure = when.defaultValue(options.structure, HeightmapTessellator.DEFAULT_STRUCTURE);
  205. var heightScale = when.defaultValue(structure.heightScale, HeightmapTessellator.DEFAULT_STRUCTURE.heightScale);
  206. var heightOffset = when.defaultValue(structure.heightOffset, HeightmapTessellator.DEFAULT_STRUCTURE.heightOffset);
  207. var elementsPerHeight = when.defaultValue(structure.elementsPerHeight, HeightmapTessellator.DEFAULT_STRUCTURE.elementsPerHeight);
  208. var stride = when.defaultValue(structure.stride, HeightmapTessellator.DEFAULT_STRUCTURE.stride);
  209. var elementMultiplier = when.defaultValue(structure.elementMultiplier, HeightmapTessellator.DEFAULT_STRUCTURE.elementMultiplier);
  210. var isBigEndian = when.defaultValue(structure.isBigEndian, HeightmapTessellator.DEFAULT_STRUCTURE.isBigEndian);
  211. var rectangleWidth = Cartesian2.Rectangle.computeWidth(nativeRectangle);
  212. var rectangleHeight = Cartesian2.Rectangle.computeHeight(nativeRectangle);
  213. var granularityX = rectangleWidth / (width - 1);
  214. var granularityY = rectangleHeight / (height - 1);
  215. if (!isGeographic) {
  216. rectangleWidth *= oneOverGlobeSemimajorAxis;
  217. rectangleHeight *= oneOverGlobeSemimajorAxis;
  218. }
  219. var radiiSquared = ellipsoid.radiiSquared;
  220. var radiiSquaredX = radiiSquared.x;
  221. var radiiSquaredY = radiiSquared.y;
  222. var radiiSquaredZ = radiiSquared.z;
  223. var minimumHeight = 65536.0;
  224. var maximumHeight = -65536.0;
  225. var fromENU = Transforms.Transforms.eastNorthUpToFixedFrame(relativeToCenter, ellipsoid);
  226. var toENU = BoundingSphere.Matrix4.inverseTransformation(fromENU, matrix4Scratch);
  227. var southMercatorY;
  228. var oneOverMercatorHeight;
  229. if (includeWebMercatorT) {
  230. southMercatorY = WebMercatorProjection.WebMercatorProjection.geodeticLatitudeToMercatorAngle(geographicSouth);
  231. oneOverMercatorHeight = 1.0 / (WebMercatorProjection.WebMercatorProjection.geodeticLatitudeToMercatorAngle(geographicNorth) - southMercatorY);
  232. }
  233. var minimum = minimumScratch;
  234. minimum.x = Number.POSITIVE_INFINITY;
  235. minimum.y = Number.POSITIVE_INFINITY;
  236. minimum.z = Number.POSITIVE_INFINITY;
  237. var maximum = maximumScratch;
  238. maximum.x = Number.NEGATIVE_INFINITY;
  239. maximum.y = Number.NEGATIVE_INFINITY;
  240. maximum.z = Number.NEGATIVE_INFINITY;
  241. var hMin = Number.POSITIVE_INFINITY;
  242. var gridVertexCount = width * height;
  243. var edgeVertexCount = skirtHeight > 0.0 ? (width * 2 + height * 2) : 0;
  244. var vertexCount = gridVertexCount + edgeVertexCount;
  245. var positions = new Array(vertexCount);
  246. var heights = new Array(vertexCount);
  247. var uvs = new Array(vertexCount);
  248. var webMercatorTs = includeWebMercatorT ? new Array(vertexCount) : [];
  249. var startRow = 0;
  250. var endRow = height;
  251. var startCol = 0;
  252. var endCol = width;
  253. if (skirtHeight > 0.0) {
  254. --startRow;
  255. ++endRow;
  256. --startCol;
  257. ++endCol;
  258. }
  259. var skirtOffsetPercentage = 0.00001;
  260. for (var rowIndex = startRow; rowIndex < endRow; ++rowIndex) {
  261. var row = rowIndex;
  262. if (row < 0) {
  263. row = 0;
  264. }
  265. if (row >= height) {
  266. row = height - 1;
  267. }
  268. var latitude = nativeRectangle.north - granularityY * row;
  269. if (!isGeographic) {
  270. latitude = piOverTwo - (2.0 * atan(exp(-latitude * oneOverGlobeSemimajorAxis)));
  271. } else {
  272. latitude = toRadians(latitude);
  273. }
  274. var v = (latitude - geographicSouth) / (geographicNorth - geographicSouth);
  275. v = _Math.CesiumMath.clamp(v, 0.0, 1.0);
  276. var isNorthEdge = rowIndex === startRow;
  277. var isSouthEdge = rowIndex === endRow - 1;
  278. if (skirtHeight > 0.0) {
  279. if (isNorthEdge) {
  280. latitude += skirtOffsetPercentage * rectangleHeight;
  281. } else if (isSouthEdge) {
  282. latitude -= skirtOffsetPercentage * rectangleHeight;
  283. }
  284. }
  285. var cosLatitude = cos(latitude);
  286. var nZ = sin(latitude);
  287. var kZ = radiiSquaredZ * nZ;
  288. var webMercatorT;
  289. if (includeWebMercatorT) {
  290. webMercatorT = (WebMercatorProjection.WebMercatorProjection.geodeticLatitudeToMercatorAngle(latitude) - southMercatorY) * oneOverMercatorHeight;
  291. }
  292. for (var colIndex = startCol; colIndex < endCol; ++colIndex) {
  293. var col = colIndex;
  294. if (col < 0) {
  295. col = 0;
  296. }
  297. if (col >= width) {
  298. col = width - 1;
  299. }
  300. var terrainOffset = row * (width * stride) + col * stride;
  301. var heightSample;
  302. if (elementsPerHeight === 1) {
  303. heightSample = heightmap[terrainOffset];
  304. } else {
  305. heightSample = 0;
  306. var elementOffset;
  307. if (isBigEndian) {
  308. for (elementOffset = 0; elementOffset < elementsPerHeight; ++elementOffset) {
  309. heightSample = (heightSample * elementMultiplier) + heightmap[terrainOffset + elementOffset];
  310. }
  311. } else {
  312. for (elementOffset = elementsPerHeight - 1; elementOffset >= 0; --elementOffset) {
  313. heightSample = (heightSample * elementMultiplier) + heightmap[terrainOffset + elementOffset];
  314. }
  315. }
  316. }
  317. heightSample = (heightSample * heightScale + heightOffset) * exaggeration;
  318. maximumHeight = Math.max(maximumHeight, heightSample);
  319. minimumHeight = Math.min(minimumHeight, heightSample);
  320. var longitude = nativeRectangle.west + granularityX * col;
  321. if (!isGeographic) {
  322. longitude = longitude * oneOverGlobeSemimajorAxis;
  323. } else {
  324. longitude = toRadians(longitude);
  325. }
  326. var u = (longitude - geographicWest) / (geographicEast - geographicWest);
  327. u = _Math.CesiumMath.clamp(u, 0.0, 1.0);
  328. var index = row * width + col;
  329. if (skirtHeight > 0.0) {
  330. var isWestEdge = colIndex === startCol;
  331. var isEastEdge = colIndex === endCol - 1;
  332. var isEdge = isNorthEdge || isSouthEdge || isWestEdge || isEastEdge;
  333. var isCorner = (isNorthEdge || isSouthEdge) && (isWestEdge || isEastEdge);
  334. if (isCorner) {
  335. // Don't generate skirts on the corners.
  336. continue;
  337. } else if (isEdge) {
  338. heightSample -= skirtHeight;
  339. if (isWestEdge) {
  340. // The outer loop iterates north to south but the indices are ordered south to north, hence the index flip below
  341. index = gridVertexCount + (height - row - 1);
  342. longitude -= skirtOffsetPercentage * rectangleWidth;
  343. } else if (isSouthEdge) {
  344. // Add after west indices. South indices are ordered east to west.
  345. index = gridVertexCount + height + (width - col - 1);
  346. } else if (isEastEdge) {
  347. // Add after west and south indices. East indices are ordered north to south. The index is flipped like above.
  348. index = gridVertexCount + height + width + row;
  349. longitude += skirtOffsetPercentage * rectangleWidth;
  350. } else if (isNorthEdge) {
  351. // Add after west, south, and east indices. North indices are ordered west to east.
  352. index = gridVertexCount + height + width + height + col;
  353. }
  354. }
  355. }
  356. var nX = cosLatitude * cos(longitude);
  357. var nY = cosLatitude * sin(longitude);
  358. var kX = radiiSquaredX * nX;
  359. var kY = radiiSquaredY * nY;
  360. var gamma = sqrt((kX * nX) + (kY * nY) + (kZ * nZ));
  361. var oneOverGamma = 1.0 / gamma;
  362. var rSurfaceX = kX * oneOverGamma;
  363. var rSurfaceY = kY * oneOverGamma;
  364. var rSurfaceZ = kZ * oneOverGamma;
  365. var position = new Cartographic.Cartesian3();
  366. position.x = rSurfaceX + nX * heightSample;
  367. position.y = rSurfaceY + nY * heightSample;
  368. position.z = rSurfaceZ + nZ * heightSample;
  369. positions[index] = position;
  370. heights[index] = heightSample;
  371. uvs[index] = new Cartesian2.Cartesian2(u, v);
  372. if (includeWebMercatorT) {
  373. webMercatorTs[index] = webMercatorT;
  374. }
  375. BoundingSphere.Matrix4.multiplyByPoint(toENU, position, cartesian3Scratch);
  376. Cartographic.Cartesian3.minimumByComponent(cartesian3Scratch, minimum, minimum);
  377. Cartographic.Cartesian3.maximumByComponent(cartesian3Scratch, maximum, maximum);
  378. hMin = Math.min(hMin, heightSample);
  379. }
  380. }
  381. var boundingSphere3D = BoundingSphere.BoundingSphere.fromPoints(positions);
  382. var orientedBoundingBox;
  383. if (when.defined(rectangle)) {
  384. orientedBoundingBox = OrientedBoundingBox.OrientedBoundingBox.fromRectangle(rectangle, minimumHeight, maximumHeight, ellipsoid);
  385. }
  386. var occludeePointInScaledSpace;
  387. if (hasRelativeToCenter) {
  388. var occluder = new TerrainEncoding.EllipsoidalOccluder(ellipsoid);
  389. occludeePointInScaledSpace = occluder.computeHorizonCullingPointPossiblyUnderEllipsoid(relativeToCenter, positions, minimumHeight);
  390. }
  391. var aaBox = new EllipsoidTangentPlane.AxisAlignedBoundingBox(minimum, maximum, relativeToCenter);
  392. var encoding = new TerrainEncoding.TerrainEncoding(aaBox, hMin, maximumHeight, fromENU, false, includeWebMercatorT);
  393. var vertices = new Float32Array(vertexCount * encoding.getStride());
  394. var bufferIndex = 0;
  395. for (var j = 0; j < vertexCount; ++j) {
  396. bufferIndex = encoding.encode(vertices, bufferIndex, positions[j], uvs[j], heights[j], undefined, webMercatorTs[j]);
  397. }
  398. return {
  399. vertices : vertices,
  400. maximumHeight : maximumHeight,
  401. minimumHeight : minimumHeight,
  402. encoding : encoding,
  403. boundingSphere3D : boundingSphere3D,
  404. orientedBoundingBox : orientedBoundingBox,
  405. occludeePointInScaledSpace : occludeePointInScaledSpace
  406. };
  407. };
  408. /* jshint forin: false, bitwise: false */
  409. /*
  410. Copyright 2015-2018 Esri
  411. Licensed under the Apache License, Version 2.0 (the "License");
  412. you may not use this file except in compliance with the License.
  413. You may obtain a copy of the License at
  414. http://www.apache.org/licenses/LICENSE-2.0
  415. Unless required by applicable law or agreed to in writing, software
  416. distributed under the License is distributed on an "AS IS" BASIS,
  417. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  418. See the License for the specific language governing permissions and
  419. limitations under the License.
  420. A copy of the license and additional notices are located with the
  421. source distribution at:
  422. http://github.com/Esri/lerc/
  423. Contributors: Johannes Schmid, (LERC v1)
  424. Chayanika Khatua, (LERC v1)
  425. Wenxue Ju (LERC v1, v2.x)
  426. */
  427. /* Copyright 2015-2018 Esri. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 @preserve */
  428. var tmp = {};
  429. /**
  430. * a module for decoding LERC blobs
  431. * @module Lerc
  432. */
  433. (function() {
  434. //the original LercDecode for Version 1
  435. var LercDecode = (function() {
  436. // WARNING: This decoder version can only read old version 1 Lerc blobs. Use with caution.
  437. // Note: currently, this module only has an implementation for decoding LERC data, not encoding. The name of
  438. // the class was chosen to be future proof.
  439. var CntZImage = {};
  440. CntZImage.defaultNoDataValue = -3.4027999387901484e+38; // smallest Float32 value
  441. /**
  442. * Decode a LERC byte stream and return an object containing the pixel data and some required and optional
  443. * information about it, such as the image's width and height.
  444. *
  445. * @param {ArrayBuffer} input The LERC input byte stream
  446. * @param {object} [options] Decoding options, containing any of the following properties:
  447. * @config {number} [inputOffset = 0]
  448. * Skip the first inputOffset bytes of the input byte stream. A valid LERC file is expected at that position.
  449. * @config {Uint8Array} [encodedMask = null]
  450. * If specified, the decoder will not read mask information from the input and use the specified encoded
  451. * mask data instead. Mask header/data must not be present in the LERC byte stream in this case.
  452. * @config {number} [noDataValue = LercCode.defaultNoDataValue]
  453. * Pixel value to use for masked pixels.
  454. * @config {ArrayBufferView|Array} [pixelType = Float32Array]
  455. * The desired type of the pixelData array in the return value. Note that it is the caller's responsibility to
  456. * provide an appropriate noDataValue if the default pixelType is overridden.
  457. * @config {boolean} [returnMask = false]
  458. * If true, the return value will contain a maskData property of type Uint8Array which has one element per
  459. * pixel, the value of which is 1 or 0 depending on whether that pixel's data is present or masked. If the
  460. * input LERC data does not contain a mask, maskData will not be returned.
  461. * @config {boolean} [returnEncodedMask = false]
  462. * If true, the return value will contain a encodedMaskData property, which can be passed into encode() as
  463. * encodedMask.
  464. * @config {boolean} [returnFileInfo = false]
  465. * If true, the return value will have a fileInfo property that contains metadata obtained from the
  466. * LERC headers and the decoding process.
  467. * @config {boolean} [computeUsedBitDepths = false]
  468. * If true, the fileInfo property in the return value will contain the set of all block bit depths
  469. * encountered during decoding. Will only have an effect if returnFileInfo option is true.
  470. * @returns {{width, height, pixelData, minValue, maxValue, noDataValue, maskData, encodedMaskData, fileInfo}}
  471. */
  472. CntZImage.decode = function(input, options) {
  473. options = options || {};
  474. var skipMask = options.encodedMaskData || (options.encodedMaskData === null);
  475. var parsedData = parse(input, options.inputOffset || 0, skipMask);
  476. var noDataValue = (options.noDataValue !== null) ? options.noDataValue : CntZImage.defaultNoDataValue;
  477. var uncompressedData = uncompressPixelValues(parsedData, options.pixelType || Float32Array,
  478. options.encodedMaskData, noDataValue, options.returnMask);
  479. var result = {
  480. width: parsedData.width,
  481. height: parsedData.height,
  482. pixelData: uncompressedData.resultPixels,
  483. minValue: uncompressedData.minValue,
  484. maxValue: parsedData.pixels.maxValue,
  485. noDataValue: noDataValue
  486. };
  487. if (uncompressedData.resultMask) {
  488. result.maskData = uncompressedData.resultMask;
  489. }
  490. if (options.returnEncodedMask && parsedData.mask) {
  491. result.encodedMaskData = parsedData.mask.bitset ? parsedData.mask.bitset : null;
  492. }
  493. if (options.returnFileInfo) {
  494. result.fileInfo = formatFileInfo(parsedData);
  495. if (options.computeUsedBitDepths) {
  496. result.fileInfo.bitDepths = computeUsedBitDepths(parsedData);
  497. }
  498. }
  499. return result;
  500. };
  501. var uncompressPixelValues = function(data, TypedArrayClass, maskBitset, noDataValue, storeDecodedMask) {
  502. var blockIdx = 0;
  503. var numX = data.pixels.numBlocksX;
  504. var numY = data.pixels.numBlocksY;
  505. var blockWidth = Math.floor(data.width / numX);
  506. var blockHeight = Math.floor(data.height / numY);
  507. var scale = 2 * data.maxZError;
  508. var minValue = Number.MAX_VALUE, currentValue;
  509. maskBitset = maskBitset || ((data.mask) ? data.mask.bitset : null);
  510. var resultPixels, resultMask;
  511. resultPixels = new TypedArrayClass(data.width * data.height);
  512. if (storeDecodedMask && maskBitset) {
  513. resultMask = new Uint8Array(data.width * data.height);
  514. }
  515. var blockDataBuffer = new Float32Array(blockWidth * blockHeight);
  516. var xx, yy;
  517. for (var y = 0; y <= numY; y++) {
  518. var thisBlockHeight = (y !== numY) ? blockHeight : (data.height % numY);
  519. if (thisBlockHeight === 0) {
  520. continue;
  521. }
  522. for (var x = 0; x <= numX; x++) {
  523. var thisBlockWidth = (x !== numX) ? blockWidth : (data.width % numX);
  524. if (thisBlockWidth === 0) {
  525. continue;
  526. }
  527. var outPtr = y * data.width * blockHeight + x * blockWidth;
  528. var outStride = data.width - thisBlockWidth;
  529. var block = data.pixels.blocks[blockIdx];
  530. var blockData, blockPtr, constValue;
  531. if (block.encoding < 2) {
  532. // block is either uncompressed or bit-stuffed (encodings 0 and 1)
  533. if (block.encoding === 0) {
  534. // block is uncompressed
  535. blockData = block.rawData;
  536. } else {
  537. // block is bit-stuffed
  538. unstuff(block.stuffedData, block.bitsPerPixel, block.numValidPixels, block.offset, scale, blockDataBuffer, data.pixels.maxValue);
  539. blockData = blockDataBuffer;
  540. }
  541. blockPtr = 0;
  542. }
  543. else if (block.encoding === 2) {
  544. // block is all 0
  545. constValue = 0;
  546. }
  547. else {
  548. // block has constant value (encoding === 3)
  549. constValue = block.offset;
  550. }
  551. var maskByte;
  552. if (maskBitset) {
  553. for (yy = 0; yy < thisBlockHeight; yy++) {
  554. if (outPtr & 7) {
  555. //
  556. maskByte = maskBitset[outPtr >> 3];
  557. maskByte <<= outPtr & 7;
  558. }
  559. for (xx = 0; xx < thisBlockWidth; xx++) {
  560. if (!(outPtr & 7)) {
  561. // read next byte from mask
  562. maskByte = maskBitset[outPtr >> 3];
  563. }
  564. if (maskByte & 128) {
  565. // pixel data present
  566. if (resultMask) {
  567. resultMask[outPtr] = 1;
  568. }
  569. currentValue = (block.encoding < 2) ? blockData[blockPtr++] : constValue;
  570. minValue = minValue > currentValue ? currentValue : minValue;
  571. resultPixels[outPtr++] = currentValue;
  572. } else {
  573. // pixel data not present
  574. if (resultMask) {
  575. resultMask[outPtr] = 0;
  576. }
  577. resultPixels[outPtr++] = noDataValue;
  578. }
  579. maskByte <<= 1;
  580. }
  581. outPtr += outStride;
  582. }
  583. } else {
  584. // mask not present, simply copy block over
  585. if (block.encoding < 2) {
  586. // duplicating this code block for performance reasons
  587. // blockData case:
  588. for (yy = 0; yy < thisBlockHeight; yy++) {
  589. for (xx = 0; xx < thisBlockWidth; xx++) {
  590. currentValue = blockData[blockPtr++];
  591. minValue = minValue > currentValue ? currentValue : minValue;
  592. resultPixels[outPtr++] = currentValue;
  593. }
  594. outPtr += outStride;
  595. }
  596. }
  597. else {
  598. // constValue case:
  599. minValue = minValue > constValue ? constValue : minValue;
  600. for (yy = 0; yy < thisBlockHeight; yy++) {
  601. for (xx = 0; xx < thisBlockWidth; xx++) {
  602. resultPixels[outPtr++] = constValue;
  603. }
  604. outPtr += outStride;
  605. }
  606. }
  607. }
  608. if ((block.encoding === 1) && (blockPtr !== block.numValidPixels)) {
  609. throw "Block and Mask do not match";
  610. }
  611. blockIdx++;
  612. }
  613. }
  614. return {
  615. resultPixels: resultPixels,
  616. resultMask: resultMask,
  617. minValue: minValue
  618. };
  619. };
  620. var formatFileInfo = function(data) {
  621. return {
  622. "fileIdentifierString": data.fileIdentifierString,
  623. "fileVersion": data.fileVersion,
  624. "imageType": data.imageType,
  625. "height": data.height,
  626. "width": data.width,
  627. "maxZError": data.maxZError,
  628. "eofOffset": data.eofOffset,
  629. "mask": data.mask ? {
  630. "numBlocksX": data.mask.numBlocksX,
  631. "numBlocksY": data.mask.numBlocksY,
  632. "numBytes": data.mask.numBytes,
  633. "maxValue": data.mask.maxValue
  634. } : null,
  635. "pixels": {
  636. "numBlocksX": data.pixels.numBlocksX,
  637. "numBlocksY": data.pixels.numBlocksY,
  638. "numBytes": data.pixels.numBytes,
  639. "maxValue": data.pixels.maxValue,
  640. "noDataValue": data.noDataValue
  641. }
  642. };
  643. };
  644. var computeUsedBitDepths = function(data) {
  645. var numBlocks = data.pixels.numBlocksX * data.pixels.numBlocksY;
  646. var bitDepths = {};
  647. for (var i = 0; i < numBlocks; i++) {
  648. var block = data.pixels.blocks[i];
  649. if (block.encoding === 0) {
  650. bitDepths.float32 = true;
  651. } else if (block.encoding === 1) {
  652. bitDepths[block.bitsPerPixel] = true;
  653. } else {
  654. bitDepths[0] = true;
  655. }
  656. }
  657. return Object.keys(bitDepths);
  658. };
  659. var parse = function(input, fp, skipMask) {
  660. var data = {};
  661. // File header
  662. var fileIdView = new Uint8Array(input, fp, 10);
  663. data.fileIdentifierString = String.fromCharCode.apply(null, fileIdView);
  664. if (data.fileIdentifierString.trim() !== "CntZImage") {
  665. throw "Unexpected file identifier string: " + data.fileIdentifierString;
  666. }
  667. fp += 10;
  668. var view = new DataView(input, fp, 24);
  669. data.fileVersion = view.getInt32(0, true);
  670. data.imageType = view.getInt32(4, true);
  671. data.height = view.getUint32(8, true);
  672. data.width = view.getUint32(12, true);
  673. data.maxZError = view.getFloat64(16, true);
  674. fp += 24;
  675. // Mask Header
  676. if (!skipMask) {
  677. view = new DataView(input, fp, 16);
  678. data.mask = {};
  679. data.mask.numBlocksY = view.getUint32(0, true);
  680. data.mask.numBlocksX = view.getUint32(4, true);
  681. data.mask.numBytes = view.getUint32(8, true);
  682. data.mask.maxValue = view.getFloat32(12, true);
  683. fp += 16;
  684. // Mask Data
  685. if (data.mask.numBytes > 0) {
  686. var bitset = new Uint8Array(Math.ceil(data.width * data.height / 8));
  687. view = new DataView(input, fp, data.mask.numBytes);
  688. var cnt = view.getInt16(0, true);
  689. var ip = 2, op = 0;
  690. do {
  691. if (cnt > 0) {
  692. while (cnt--) { bitset[op++] = view.getUint8(ip++); }
  693. } else {
  694. var val = view.getUint8(ip++);
  695. cnt = -cnt;
  696. while (cnt--) { bitset[op++] = val; }
  697. }
  698. cnt = view.getInt16(ip, true);
  699. ip += 2;
  700. } while (ip < data.mask.numBytes);
  701. if ((cnt !== -32768) || (op < bitset.length)) {
  702. throw "Unexpected end of mask RLE encoding";
  703. }
  704. data.mask.bitset = bitset;
  705. fp += data.mask.numBytes;
  706. }
  707. else if ((data.mask.numBytes | data.mask.numBlocksY | data.mask.maxValue) === 0) { // Special case, all nodata
  708. data.mask.bitset = new Uint8Array(Math.ceil(data.width * data.height / 8));
  709. }
  710. }
  711. // Pixel Header
  712. view = new DataView(input, fp, 16);
  713. data.pixels = {};
  714. data.pixels.numBlocksY = view.getUint32(0, true);
  715. data.pixels.numBlocksX = view.getUint32(4, true);
  716. data.pixels.numBytes = view.getUint32(8, true);
  717. data.pixels.maxValue = view.getFloat32(12, true);
  718. fp += 16;
  719. var numBlocksX = data.pixels.numBlocksX;
  720. var numBlocksY = data.pixels.numBlocksY;
  721. // the number of blocks specified in the header does not take into account the blocks at the end of
  722. // each row/column with a special width/height that make the image complete in case the width is not
  723. // evenly divisible by the number of blocks.
  724. var actualNumBlocksX = numBlocksX + ((data.width % numBlocksX) > 0 ? 1 : 0);
  725. var actualNumBlocksY = numBlocksY + ((data.height % numBlocksY) > 0 ? 1 : 0);
  726. data.pixels.blocks = new Array(actualNumBlocksX * actualNumBlocksY);
  727. var blockI = 0;
  728. for (var blockY = 0; blockY < actualNumBlocksY; blockY++) {
  729. for (var blockX = 0; blockX < actualNumBlocksX; blockX++) {
  730. // Block
  731. var size = 0;
  732. var bytesLeft = input.byteLength - fp;
  733. view = new DataView(input, fp, Math.min(10, bytesLeft));
  734. var block = {};
  735. data.pixels.blocks[blockI++] = block;
  736. var headerByte = view.getUint8(0); size++;
  737. block.encoding = headerByte & 63;
  738. if (block.encoding > 3) {
  739. throw "Invalid block encoding (" + block.encoding + ")";
  740. }
  741. if (block.encoding === 2) {
  742. fp++;
  743. continue;
  744. }
  745. if ((headerByte !== 0) && (headerByte !== 2)) {
  746. headerByte >>= 6;
  747. block.offsetType = headerByte;
  748. if (headerByte === 2) {
  749. block.offset = view.getInt8(1); size++;
  750. } else if (headerByte === 1) {
  751. block.offset = view.getInt16(1, true); size += 2;
  752. } else if (headerByte === 0) {
  753. block.offset = view.getFloat32(1, true); size += 4;
  754. } else {
  755. throw "Invalid block offset type";
  756. }
  757. if (block.encoding === 1) {
  758. headerByte = view.getUint8(size); size++;
  759. block.bitsPerPixel = headerByte & 63;
  760. headerByte >>= 6;
  761. block.numValidPixelsType = headerByte;
  762. if (headerByte === 2) {
  763. block.numValidPixels = view.getUint8(size); size++;
  764. } else if (headerByte === 1) {
  765. block.numValidPixels = view.getUint16(size, true); size += 2;
  766. } else if (headerByte === 0) {
  767. block.numValidPixels = view.getUint32(size, true); size += 4;
  768. } else {
  769. throw "Invalid valid pixel count type";
  770. }
  771. }
  772. }
  773. fp += size;
  774. if (block.encoding === 3) {
  775. continue;
  776. }
  777. var arrayBuf, store8;
  778. if (block.encoding === 0) {
  779. var numPixels = (data.pixels.numBytes - 1) / 4;
  780. if (numPixels !== Math.floor(numPixels)) {
  781. throw "uncompressed block has invalid length";
  782. }
  783. arrayBuf = new ArrayBuffer(numPixels * 4);
  784. store8 = new Uint8Array(arrayBuf);
  785. store8.set(new Uint8Array(input, fp, numPixels * 4));
  786. var rawData = new Float32Array(arrayBuf);
  787. block.rawData = rawData;
  788. fp += numPixels * 4;
  789. } else if (block.encoding === 1) {
  790. var dataBytes = Math.ceil(block.numValidPixels * block.bitsPerPixel / 8);
  791. var dataWords = Math.ceil(dataBytes / 4);
  792. arrayBuf = new ArrayBuffer(dataWords * 4);
  793. store8 = new Uint8Array(arrayBuf);
  794. store8.set(new Uint8Array(input, fp, dataBytes));
  795. block.stuffedData = new Uint32Array(arrayBuf);
  796. fp += dataBytes;
  797. }
  798. }
  799. }
  800. data.eofOffset = fp;
  801. return data;
  802. };
  803. var unstuff = function(src, bitsPerPixel, numPixels, offset, scale, dest, maxValue) {
  804. var bitMask = (1 << bitsPerPixel) - 1;
  805. var i = 0, o;
  806. var bitsLeft = 0;
  807. var n, buffer;
  808. var nmax = Math.ceil((maxValue - offset) / scale);
  809. // get rid of trailing bytes that are already part of next block
  810. var numInvalidTailBytes = src.length * 4 - Math.ceil(bitsPerPixel * numPixels / 8);
  811. src[src.length - 1] <<= 8 * numInvalidTailBytes;
  812. for (o = 0; o < numPixels; o++) {
  813. if (bitsLeft === 0) {
  814. buffer = src[i++];
  815. bitsLeft = 32;
  816. }
  817. if (bitsLeft >= bitsPerPixel) {
  818. n = (buffer >>> (bitsLeft - bitsPerPixel)) & bitMask;
  819. bitsLeft -= bitsPerPixel;
  820. } else {
  821. var missingBits = (bitsPerPixel - bitsLeft);
  822. n = ((buffer & bitMask) << missingBits) & bitMask;
  823. buffer = src[i++];
  824. bitsLeft = 32 - missingBits;
  825. n += (buffer >>> bitsLeft);
  826. }
  827. //pixel values may exceed max due to quantization
  828. dest[o] = n < nmax ? offset + n * scale : maxValue;
  829. }
  830. return dest;
  831. };
  832. return CntZImage;
  833. })();
  834. //version 2. Supports 2.1, 2.2, 2.3
  835. var Lerc2Decode = (function() {
  836. // Note: currently, this module only has an implementation for decoding LERC data, not encoding. The name of
  837. // the class was chosen to be future proof, following LercDecode.
  838. /*****************************************
  839. * private static class bitsutffer used by Lerc2Decode
  840. *******************************************/
  841. var BitStuffer = {
  842. //methods ending with 2 are for the new byte order used by Lerc2.3 and above.
  843. //originalUnstuff is used to unpack Huffman code table. code is duplicated to unstuffx for performance reasons.
  844. unstuff: function(src, dest, bitsPerPixel, numPixels, lutArr, offset, scale, maxValue) {
  845. var bitMask = (1 << bitsPerPixel) - 1;
  846. var i = 0, o;
  847. var bitsLeft = 0;
  848. var n, buffer, missingBits, nmax;
  849. // get rid of trailing bytes that are already part of next block
  850. var numInvalidTailBytes = src.length * 4 - Math.ceil(bitsPerPixel * numPixels / 8);
  851. src[src.length - 1] <<= 8 * numInvalidTailBytes;
  852. if (lutArr) {
  853. for (o = 0; o < numPixels; o++) {
  854. if (bitsLeft === 0) {
  855. buffer = src[i++];
  856. bitsLeft = 32;
  857. }
  858. if (bitsLeft >= bitsPerPixel) {
  859. n = (buffer >>> (bitsLeft - bitsPerPixel)) & bitMask;
  860. bitsLeft -= bitsPerPixel;
  861. }
  862. else {
  863. missingBits = (bitsPerPixel - bitsLeft);
  864. n = ((buffer & bitMask) << missingBits) & bitMask;
  865. buffer = src[i++];
  866. bitsLeft = 32 - missingBits;
  867. n += (buffer >>> bitsLeft);
  868. }
  869. dest[o] = lutArr[n];//offset + lutArr[n] * scale;
  870. }
  871. }
  872. else {
  873. nmax = Math.ceil((maxValue - offset) / scale);
  874. for (o = 0; o < numPixels; o++) {
  875. if (bitsLeft === 0) {
  876. buffer = src[i++];
  877. bitsLeft = 32;
  878. }
  879. if (bitsLeft >= bitsPerPixel) {
  880. n = (buffer >>> (bitsLeft - bitsPerPixel)) & bitMask;
  881. bitsLeft -= bitsPerPixel;
  882. }
  883. else {
  884. missingBits = (bitsPerPixel - bitsLeft);
  885. n = ((buffer & bitMask) << missingBits) & bitMask;
  886. buffer = src[i++];
  887. bitsLeft = 32 - missingBits;
  888. n += (buffer >>> bitsLeft);
  889. }
  890. //pixel values may exceed max due to quantization
  891. dest[o] = n < nmax ? offset + n * scale : maxValue;
  892. }
  893. }
  894. },
  895. unstuffLUT: function(src, bitsPerPixel, numPixels, offset, scale, maxValue) {
  896. var bitMask = (1 << bitsPerPixel) - 1;
  897. var i = 0, o = 0, missingBits = 0, bitsLeft = 0, n = 0;
  898. var buffer;
  899. var dest = [];
  900. // get rid of trailing bytes that are already part of next block
  901. var numInvalidTailBytes = src.length * 4 - Math.ceil(bitsPerPixel * numPixels / 8);
  902. src[src.length - 1] <<= 8 * numInvalidTailBytes;
  903. var nmax = Math.ceil((maxValue - offset) / scale);
  904. for (o = 0; o < numPixels; o++) {
  905. if (bitsLeft === 0) {
  906. buffer = src[i++];
  907. bitsLeft = 32;
  908. }
  909. if (bitsLeft >= bitsPerPixel) {
  910. n = (buffer >>> (bitsLeft - bitsPerPixel)) & bitMask;
  911. bitsLeft -= bitsPerPixel;
  912. } else {
  913. missingBits = (bitsPerPixel - bitsLeft);
  914. n = ((buffer & bitMask) << missingBits) & bitMask;
  915. buffer = src[i++];
  916. bitsLeft = 32 - missingBits;
  917. n += (buffer >>> bitsLeft);
  918. }
  919. //dest.push(n);
  920. dest[o] = n < nmax ? offset + n * scale : maxValue;
  921. }
  922. dest.unshift(offset);//1st one
  923. return dest;
  924. },
  925. unstuff2: function(src, dest, bitsPerPixel, numPixels, lutArr, offset, scale, maxValue) {
  926. var bitMask = (1 << bitsPerPixel) - 1;
  927. var i = 0, o;
  928. var bitsLeft = 0, bitPos = 0;
  929. var n, buffer, missingBits;
  930. if (lutArr) {
  931. for (o = 0; o < numPixels; o++) {
  932. if (bitsLeft === 0) {
  933. buffer = src[i++];
  934. bitsLeft = 32;
  935. bitPos = 0;
  936. }
  937. if (bitsLeft >= bitsPerPixel) {
  938. n = ((buffer >>> bitPos) & bitMask);
  939. bitsLeft -= bitsPerPixel;
  940. bitPos += bitsPerPixel;
  941. } else {
  942. missingBits = (bitsPerPixel - bitsLeft);
  943. n = (buffer >>> bitPos) & bitMask;
  944. buffer = src[i++];
  945. bitsLeft = 32 - missingBits;
  946. n |= (buffer & ((1 << missingBits) - 1)) << (bitsPerPixel - missingBits);
  947. bitPos = missingBits;
  948. }
  949. dest[o] = lutArr[n];
  950. }
  951. }
  952. else {
  953. var nmax = Math.ceil((maxValue - offset) / scale);
  954. for (o = 0; o < numPixels; o++) {
  955. if (bitsLeft === 0) {
  956. buffer = src[i++];
  957. bitsLeft = 32;
  958. bitPos = 0;
  959. }
  960. if (bitsLeft >= bitsPerPixel) {
  961. //no unsigned left shift
  962. n = ((buffer >>> bitPos) & bitMask);
  963. bitsLeft -= bitsPerPixel;
  964. bitPos += bitsPerPixel;
  965. } else {
  966. missingBits = (bitsPerPixel - bitsLeft);
  967. n = (buffer >>> bitPos) & bitMask;//((buffer & bitMask) << missingBits) & bitMask;
  968. buffer = src[i++];
  969. bitsLeft = 32 - missingBits;
  970. n |= (buffer & ((1 << missingBits) - 1)) << (bitsPerPixel - missingBits);
  971. bitPos = missingBits;
  972. }
  973. //pixel values may exceed max due to quantization
  974. dest[o] = n < nmax ? offset + n * scale : maxValue;
  975. }
  976. }
  977. return dest;
  978. },
  979. unstuffLUT2: function(src, bitsPerPixel, numPixels, offset, scale, maxValue) {
  980. var bitMask = (1 << bitsPerPixel) - 1;
  981. var i = 0, o = 0, missingBits = 0, bitsLeft = 0, n = 0, bitPos = 0;
  982. var buffer;
  983. var dest = [];
  984. var nmax = Math.ceil((maxValue - offset) / scale);
  985. for (o = 0; o < numPixels; o++) {
  986. if (bitsLeft === 0) {
  987. buffer = src[i++];
  988. bitsLeft = 32;
  989. bitPos = 0;
  990. }
  991. if (bitsLeft >= bitsPerPixel) {
  992. //no unsigned left shift
  993. n = ((buffer >>> bitPos) & bitMask);
  994. bitsLeft -= bitsPerPixel;
  995. bitPos += bitsPerPixel;
  996. } else {
  997. missingBits = (bitsPerPixel - bitsLeft);
  998. n = (buffer >>> bitPos) & bitMask;//((buffer & bitMask) << missingBits) & bitMask;
  999. buffer = src[i++];
  1000. bitsLeft = 32 - missingBits;
  1001. n |= (buffer & ((1 << missingBits) - 1)) << (bitsPerPixel - missingBits);
  1002. bitPos = missingBits;
  1003. }
  1004. //dest.push(n);
  1005. dest[o] = n < nmax ? offset + n * scale : maxValue;
  1006. }
  1007. dest.unshift(offset);
  1008. return dest;
  1009. },
  1010. originalUnstuff: function(src, dest, bitsPerPixel, numPixels) {
  1011. var bitMask = (1 << bitsPerPixel) - 1;
  1012. var i = 0, o;
  1013. var bitsLeft = 0;
  1014. var n, buffer, missingBits;
  1015. // get rid of trailing bytes that are already part of next block
  1016. var numInvalidTailBytes = src.length * 4 - Math.ceil(bitsPerPixel * numPixels / 8);
  1017. src[src.length - 1] <<= 8 * numInvalidTailBytes;
  1018. for (o = 0; o < numPixels; o++) {
  1019. if (bitsLeft === 0) {
  1020. buffer = src[i++];
  1021. bitsLeft = 32;
  1022. }
  1023. if (bitsLeft >= bitsPerPixel) {
  1024. n = (buffer >>> (bitsLeft - bitsPerPixel)) & bitMask;
  1025. bitsLeft -= bitsPerPixel;
  1026. }
  1027. else {
  1028. missingBits = (bitsPerPixel - bitsLeft);
  1029. n = ((buffer & bitMask) << missingBits) & bitMask;
  1030. buffer = src[i++];
  1031. bitsLeft = 32 - missingBits;
  1032. n += (buffer >>> bitsLeft);
  1033. }
  1034. dest[o] = n;
  1035. }
  1036. return dest;
  1037. },
  1038. originalUnstuff2: function(src, dest, bitsPerPixel, numPixels) {
  1039. var bitMask = (1 << bitsPerPixel) - 1;
  1040. var i = 0, o;
  1041. var bitsLeft = 0, bitPos = 0;
  1042. var n, buffer, missingBits;
  1043. //micro-optimizations
  1044. for (o = 0; o < numPixels; o++) {
  1045. if (bitsLeft === 0) {
  1046. buffer = src[i++];
  1047. bitsLeft = 32;
  1048. bitPos = 0;
  1049. }
  1050. if (bitsLeft >= bitsPerPixel) {
  1051. //no unsigned left shift
  1052. n = ((buffer >>> bitPos) & bitMask);
  1053. bitsLeft -= bitsPerPixel;
  1054. bitPos += bitsPerPixel;
  1055. } else {
  1056. missingBits = (bitsPerPixel - bitsLeft);
  1057. n = (buffer >>> bitPos) & bitMask;//((buffer & bitMask) << missingBits) & bitMask;
  1058. buffer = src[i++];
  1059. bitsLeft = 32 - missingBits;
  1060. n |= (buffer & ((1 << missingBits) - 1)) << (bitsPerPixel - missingBits);
  1061. bitPos = missingBits;
  1062. }
  1063. dest[o] = n;
  1064. }
  1065. return dest;
  1066. }
  1067. };
  1068. /*****************************************
  1069. *private static class used by Lerc2Decode
  1070. ******************************************/
  1071. var Lerc2Helpers = {
  1072. HUFFMAN_LUT_BITS_MAX: 12, //use 2^12 lut, treat it like constant
  1073. computeChecksumFletcher32: function(input) {
  1074. var sum1 = 0xffff, sum2 = 0xffff;
  1075. var len = input.length;
  1076. var words = Math.floor(len / 2);
  1077. var i = 0;
  1078. while (words) {
  1079. var tlen = (words >= 359) ? 359 : words;
  1080. words -= tlen;
  1081. do {
  1082. sum1 += (input[i++] << 8);
  1083. sum2 += sum1 += input[i++];
  1084. } while (--tlen);
  1085. sum1 = (sum1 & 0xffff) + (sum1 >>> 16);
  1086. sum2 = (sum2 & 0xffff) + (sum2 >>> 16);
  1087. }
  1088. // add the straggler byte if it exists
  1089. if (len & 1) {
  1090. sum2 += sum1 += (input[i] << 8);
  1091. }
  1092. // second reduction step to reduce sums to 16 bits
  1093. sum1 = (sum1 & 0xffff) + (sum1 >>> 16);
  1094. sum2 = (sum2 & 0xffff) + (sum2 >>> 16);
  1095. return (sum2 << 16 | sum1) >>> 0;
  1096. },
  1097. readHeaderInfo: function(input, data) {
  1098. var ptr = data.ptr;
  1099. var fileIdView = new Uint8Array(input, ptr, 6);
  1100. var headerInfo = {};
  1101. headerInfo.fileIdentifierString = String.fromCharCode.apply(null, fileIdView);
  1102. if (headerInfo.fileIdentifierString.lastIndexOf("Lerc2", 0) !== 0) {
  1103. throw "Unexpected file identifier string (expect Lerc2 ): " + headerInfo.fileIdentifierString;
  1104. }
  1105. ptr += 6;
  1106. var view = new DataView(input, ptr, 8);
  1107. var fileVersion = view.getInt32(0, true);
  1108. headerInfo.fileVersion = fileVersion;
  1109. ptr += 4;
  1110. if (fileVersion >= 3) {
  1111. headerInfo.checksum = view.getUint32(4, true); //nrows
  1112. ptr += 4;
  1113. }
  1114. //keys start from here
  1115. view = new DataView(input, ptr, 12);
  1116. headerInfo.height = view.getUint32(0, true); //nrows
  1117. headerInfo.width = view.getUint32(4, true); //ncols
  1118. ptr += 8;
  1119. if (fileVersion >= 4) {
  1120. headerInfo.numDims = view.getUint32(8, true);
  1121. ptr += 4;
  1122. }
  1123. else {
  1124. headerInfo.numDims = 1;
  1125. }
  1126. view = new DataView(input, ptr, 40);
  1127. headerInfo.numValidPixel = view.getUint32(0, true);
  1128. headerInfo.microBlockSize = view.getInt32(4, true);
  1129. headerInfo.blobSize = view.getInt32(8, true);
  1130. headerInfo.imageType = view.getInt32(12, true);
  1131. headerInfo.maxZError = view.getFloat64(16, true);
  1132. headerInfo.zMin = view.getFloat64(24, true);
  1133. headerInfo.zMax = view.getFloat64(32, true);
  1134. ptr += 40;
  1135. data.headerInfo = headerInfo;
  1136. data.ptr = ptr;
  1137. var checksum, keyLength;
  1138. if (fileVersion >= 3) {
  1139. keyLength = fileVersion >= 4 ? 52 : 48;
  1140. checksum = this.computeChecksumFletcher32(new Uint8Array(input, ptr - keyLength, headerInfo.blobSize - 14));
  1141. if (checksum !== headerInfo.checksum) {
  1142. throw "Checksum failed.";
  1143. }
  1144. }
  1145. return true;
  1146. },
  1147. checkMinMaxRanges: function(input, data) {
  1148. var headerInfo = data.headerInfo;
  1149. var OutPixelTypeArray = this.getDataTypeArray(headerInfo.imageType);
  1150. var rangeBytes = headerInfo.numDims * this.getDataTypeSize(headerInfo.imageType);
  1151. var minValues = this.readSubArray(input, data.ptr, OutPixelTypeArray, rangeBytes);
  1152. var maxValues = this.readSubArray(input, data.ptr + rangeBytes, OutPixelTypeArray, rangeBytes);
  1153. data.ptr += (2 * rangeBytes);
  1154. var i, equal = true;
  1155. for (i = 0; i < headerInfo.numDims; i++) {
  1156. if (minValues[i] !== maxValues[i]) {
  1157. equal = false;
  1158. break;
  1159. }
  1160. }
  1161. headerInfo.minValues = minValues;
  1162. headerInfo.maxValues = maxValues;
  1163. return equal;
  1164. },
  1165. readSubArray: function(input, ptr, OutPixelTypeArray, numBytes) {
  1166. var rawData;
  1167. if (OutPixelTypeArray === Uint8Array) {
  1168. rawData = new Uint8Array(input, ptr, numBytes);
  1169. }
  1170. else {
  1171. var arrayBuf = new ArrayBuffer(numBytes);
  1172. var store8 = new Uint8Array(arrayBuf);
  1173. store8.set(new Uint8Array(input, ptr, numBytes));
  1174. rawData = new OutPixelTypeArray(arrayBuf);
  1175. }
  1176. return rawData;
  1177. },
  1178. readMask: function(input, data) {
  1179. var ptr = data.ptr;
  1180. var headerInfo = data.headerInfo;
  1181. var numPixels = headerInfo.width * headerInfo.height;
  1182. var numValidPixel = headerInfo.numValidPixel;
  1183. var view = new DataView(input, ptr, 4);
  1184. var mask = {};
  1185. mask.numBytes = view.getUint32(0, true);
  1186. ptr += 4;
  1187. // Mask Data
  1188. if ((0 === numValidPixel || numPixels === numValidPixel) && 0 !== mask.numBytes) {
  1189. throw ("invalid mask");
  1190. }
  1191. var bitset, resultMask;
  1192. if (numValidPixel === 0) {
  1193. bitset = new Uint8Array(Math.ceil(numPixels / 8));
  1194. mask.bitset = bitset;
  1195. resultMask = new Uint8Array(numPixels);
  1196. data.pixels.resultMask = resultMask;
  1197. ptr += mask.numBytes;
  1198. }// ????? else if (data.mask.numBytes > 0 && data.mask.numBytes< data.numValidPixel) {
  1199. else if (mask.numBytes > 0) {
  1200. bitset = new Uint8Array(Math.ceil(numPixels / 8));
  1201. view = new DataView(input, ptr, mask.numBytes);
  1202. var cnt = view.getInt16(0, true);
  1203. var ip = 2, op = 0, val = 0;
  1204. do {
  1205. if (cnt > 0) {
  1206. while (cnt--) { bitset[op++] = view.getUint8(ip++); }
  1207. } else {
  1208. val = view.getUint8(ip++);
  1209. cnt = -cnt;
  1210. while (cnt--) { bitset[op++] = val; }
  1211. }
  1212. cnt = view.getInt16(ip, true);
  1213. ip += 2;
  1214. } while (ip < mask.numBytes);
  1215. if ((cnt !== -32768) || (op < bitset.length)) {
  1216. throw "Unexpected end of mask RLE encoding";
  1217. }
  1218. resultMask = new Uint8Array(numPixels);
  1219. var mb = 0, k = 0;
  1220. for (k = 0; k < numPixels; k++) {
  1221. if (k & 7) {
  1222. mb = bitset[k >> 3];
  1223. mb <<= k & 7;
  1224. }
  1225. else {
  1226. mb = bitset[k >> 3];
  1227. }
  1228. if (mb & 128) {
  1229. resultMask[k] = 1;
  1230. }
  1231. }
  1232. data.pixels.resultMask = resultMask;
  1233. mask.bitset = bitset;
  1234. ptr += mask.numBytes;
  1235. }
  1236. data.ptr = ptr;
  1237. data.mask = mask;
  1238. return true;
  1239. },
  1240. readDataOneSweep: function(input, data, OutPixelTypeArray) {
  1241. var ptr = data.ptr;
  1242. var headerInfo = data.headerInfo;
  1243. var numDims = headerInfo.numDims;
  1244. var numPixels = headerInfo.width * headerInfo.height;
  1245. var imageType = headerInfo.imageType;
  1246. var numBytes = headerInfo.numValidPixel * Lerc2Helpers.getDataTypeSize(imageType) * numDims;
  1247. //data.pixels.numBytes = numBytes;
  1248. var rawData;
  1249. var mask = data.pixels.resultMask;
  1250. if (OutPixelTypeArray === Uint8Array) {
  1251. rawData = new Uint8Array(input, ptr, numBytes);
  1252. }
  1253. else {
  1254. var arrayBuf = new ArrayBuffer(numBytes);
  1255. var store8 = new Uint8Array(arrayBuf);
  1256. store8.set(new Uint8Array(input, ptr, numBytes));
  1257. rawData = new OutPixelTypeArray(arrayBuf);
  1258. }
  1259. if (rawData.length === numPixels * numDims) {
  1260. data.pixels.resultPixels = rawData;
  1261. }
  1262. else //mask
  1263. {
  1264. data.pixels.resultPixels = new OutPixelTypeArray(numPixels * numDims);
  1265. var z = 0, k = 0, i = 0, nStart = 0;
  1266. if (numDims > 1) {
  1267. for (i=0; i < numDims; i++) {
  1268. nStart = i * numPixels;
  1269. for (k = 0; k < numPixels; k++) {
  1270. if (mask[k]) {
  1271. data.pixels.resultPixels[nStart + k] = rawData[z++];
  1272. }
  1273. }
  1274. }
  1275. }
  1276. else {
  1277. for (k = 0; k < numPixels; k++) {
  1278. if (mask[k]) {
  1279. data.pixels.resultPixels[k] = rawData[z++];
  1280. }
  1281. }
  1282. }
  1283. }
  1284. ptr += numBytes;
  1285. data.ptr = ptr; //return data;
  1286. return true;
  1287. },
  1288. readHuffmanTree: function(input, data) {
  1289. var BITS_MAX = this.HUFFMAN_LUT_BITS_MAX; //8 is slow for the large test image
  1290. //var size_max = 1 << BITS_MAX;
  1291. /* ************************
  1292. * reading code table
  1293. *************************/
  1294. var view = new DataView(input, data.ptr, 16);
  1295. data.ptr += 16;
  1296. var version = view.getInt32(0, true);
  1297. if (version < 2) {
  1298. throw "unsupported Huffman version";
  1299. }
  1300. var size = view.getInt32(4, true);
  1301. var i0 = view.getInt32(8, true);
  1302. var i1 = view.getInt32(12, true);
  1303. if (i0 >= i1) {
  1304. return false;
  1305. }
  1306. var blockDataBuffer = new Uint32Array(i1 - i0);
  1307. Lerc2Helpers.decodeBits(input, data, blockDataBuffer);
  1308. var codeTable = []; //size
  1309. var i, j, k, len;
  1310. for (i = i0; i < i1; i++) {
  1311. j = i - (i < size ? 0 : size);//wrap around
  1312. codeTable[j] = { first: blockDataBuffer[i - i0], second: null };
  1313. }
  1314. var dataBytes = input.byteLength - data.ptr;
  1315. var dataWords = Math.ceil(dataBytes / 4);
  1316. var arrayBuf = new ArrayBuffer(dataWords * 4);
  1317. var store8 = new Uint8Array(arrayBuf);
  1318. store8.set(new Uint8Array(input, data.ptr, dataBytes));
  1319. var stuffedData = new Uint32Array(arrayBuf); //must start from x*4
  1320. var bitPos = 0, word, srcPtr = 0;
  1321. word = stuffedData[0];
  1322. for (i = i0; i < i1; i++) {
  1323. j = i - (i < size ? 0 : size);//wrap around
  1324. len = codeTable[j].first;
  1325. if (len > 0) {
  1326. codeTable[j].second = (word << bitPos) >>> (32 - len);
  1327. if (32 - bitPos >= len) {
  1328. bitPos += len;
  1329. if (bitPos === 32) {
  1330. bitPos = 0;
  1331. srcPtr++;
  1332. word = stuffedData[srcPtr];
  1333. }
  1334. }
  1335. else {
  1336. bitPos += len - 32;
  1337. srcPtr++;
  1338. word = stuffedData[srcPtr];
  1339. codeTable[j].second |= word >>> (32 - bitPos);
  1340. }
  1341. }
  1342. }
  1343. //finished reading code table
  1344. /* ************************
  1345. * building lut
  1346. *************************/
  1347. var numBitsLUT = 0, numBitsLUTQick = 0;
  1348. var tree = new TreeNode();
  1349. for (i = 0; i < codeTable.length; i++) {
  1350. if (codeTable[i] !== undefined) {
  1351. numBitsLUT = Math.max(numBitsLUT, codeTable[i].first);
  1352. }
  1353. }
  1354. if (numBitsLUT >= BITS_MAX) {
  1355. numBitsLUTQick = BITS_MAX;
  1356. }
  1357. else {
  1358. numBitsLUTQick = numBitsLUT;
  1359. }
  1360. if (numBitsLUT >= 30) {
  1361. console.log("WARning, large NUM LUT BITS IS " + numBitsLUT);
  1362. }
  1363. var decodeLut = [], entry, code, numEntries, jj, currentBit, node;
  1364. for (i = i0; i < i1; i++) {
  1365. j = i - (i < size ? 0 : size);//wrap around
  1366. len = codeTable[j].first;
  1367. if (len > 0) {
  1368. entry = [len, j];
  1369. if (len <= numBitsLUTQick) {
  1370. code = codeTable[j].second << (numBitsLUTQick - len);
  1371. numEntries = 1 << (numBitsLUTQick - len);
  1372. for (k = 0; k < numEntries; k++) {
  1373. decodeLut[code | k] = entry;
  1374. }
  1375. }
  1376. else {
  1377. //build tree
  1378. code = codeTable[j].second;
  1379. node = tree;
  1380. for (jj = len - 1; jj >= 0; jj--) {
  1381. currentBit = code >>> jj & 1; //no left shift as length could be 30,31
  1382. if (currentBit) {
  1383. if (!node.right) {
  1384. node.right = new TreeNode();
  1385. }
  1386. node = node.right;
  1387. }
  1388. else {
  1389. if (!node.left) {
  1390. node.left = new TreeNode();
  1391. }
  1392. node = node.left;
  1393. }
  1394. if (jj === 0 && !node.val) {
  1395. node.val = entry[1];
  1396. }
  1397. }
  1398. }
  1399. }
  1400. }
  1401. return {
  1402. decodeLut: decodeLut,
  1403. numBitsLUTQick: numBitsLUTQick,
  1404. numBitsLUT: numBitsLUT,
  1405. tree: tree,
  1406. stuffedData: stuffedData,
  1407. srcPtr: srcPtr,
  1408. bitPos: bitPos
  1409. };
  1410. },
  1411. readHuffman: function(input, data, OutPixelTypeArray) {
  1412. var headerInfo = data.headerInfo;
  1413. var numDims = headerInfo.numDims;
  1414. var height = data.headerInfo.height;
  1415. var width = data.headerInfo.width;
  1416. var numPixels = width * height;
  1417. //var size_max = 1 << BITS_MAX;
  1418. /* ************************
  1419. * reading huffman structure info
  1420. *************************/
  1421. var huffmanInfo = this.readHuffmanTree(input, data);
  1422. var decodeLut = huffmanInfo.decodeLut;
  1423. var tree = huffmanInfo.tree;
  1424. //stuffedData includes huffman headers
  1425. var stuffedData = huffmanInfo.stuffedData;
  1426. var srcPtr = huffmanInfo.srcPtr;
  1427. var bitPos = huffmanInfo.bitPos;
  1428. var numBitsLUTQick = huffmanInfo.numBitsLUTQick;
  1429. var numBitsLUT = huffmanInfo.numBitsLUT;
  1430. var offset = data.headerInfo.imageType === 0 ? 128 : 0;
  1431. /*************************
  1432. * decode
  1433. ***************************/
  1434. var node, val, delta, mask = data.pixels.resultMask, valTmp, valTmpQuick, currentBit;
  1435. var i, j, k, ii;
  1436. var prevVal = 0;
  1437. if (bitPos > 0) {
  1438. srcPtr++;
  1439. bitPos = 0;
  1440. }
  1441. var word = stuffedData[srcPtr];
  1442. var deltaEncode = data.encodeMode === 1;
  1443. var resultPixelsAllDim = new OutPixelTypeArray(numPixels * numDims);
  1444. var resultPixels = resultPixelsAllDim;
  1445. var iDim;
  1446. for (iDim = 0; iDim < headerInfo.numDims; iDim++) {
  1447. if (numDims > 1) {
  1448. //get the mem block of current dimension
  1449. resultPixels = new OutPixelTypeArray(resultPixelsAllDim.buffer, numPixels * iDim, numPixels);
  1450. prevVal = 0;
  1451. }
  1452. if (data.headerInfo.numValidPixel === width * height) { //all valid
  1453. for (k = 0, i = 0; i < height; i++) {
  1454. for (j = 0; j < width; j++, k++) {
  1455. val = 0;
  1456. valTmp = (word << bitPos) >>> (32 - numBitsLUTQick);
  1457. valTmpQuick = valTmp;// >>> deltaBits;
  1458. if (32 - bitPos < numBitsLUTQick) {
  1459. valTmp |= ((stuffedData[srcPtr + 1]) >>> (64 - bitPos - numBitsLUTQick));
  1460. valTmpQuick = valTmp;// >>> deltaBits;
  1461. }
  1462. if (decodeLut[valTmpQuick]) // if there, move the correct number of bits and done
  1463. {
  1464. val = decodeLut[valTmpQuick][1];
  1465. bitPos += decodeLut[valTmpQuick][0];
  1466. }
  1467. else {
  1468. valTmp = (word << bitPos) >>> (32 - numBitsLUT);
  1469. valTmpQuick = valTmp;// >>> deltaBits;
  1470. if (32 - bitPos < numBitsLUT) {
  1471. valTmp |= ((stuffedData[srcPtr + 1]) >>> (64 - bitPos - numBitsLUT));
  1472. valTmpQuick = valTmp;// >>> deltaBits;
  1473. }
  1474. node = tree;
  1475. for (ii = 0; ii < numBitsLUT; ii++) {
  1476. currentBit = valTmp >>> (numBitsLUT - ii - 1) & 1;
  1477. node = currentBit ? node.right : node.left;
  1478. if (!(node.left || node.right)) {
  1479. val = node.val;
  1480. bitPos = bitPos + ii + 1;
  1481. break;
  1482. }
  1483. }
  1484. }
  1485. if (bitPos >= 32) {
  1486. bitPos -= 32;
  1487. srcPtr++;
  1488. word = stuffedData[srcPtr];
  1489. }
  1490. delta = val - offset;
  1491. if (deltaEncode) {
  1492. if (j > 0) {
  1493. delta += prevVal; // use overflow
  1494. }
  1495. else if (i > 0) {
  1496. delta += resultPixels[k - width];
  1497. }
  1498. else {
  1499. delta += prevVal;
  1500. }
  1501. delta &= 0xFF; //overflow
  1502. resultPixels[k] = delta;//overflow
  1503. prevVal = delta;
  1504. }
  1505. else {
  1506. resultPixels[k] = delta;
  1507. }
  1508. }
  1509. }
  1510. }
  1511. else { //not all valid, use mask
  1512. for (k = 0, i = 0; i < height; i++) {
  1513. for (j = 0; j < width; j++, k++) {
  1514. if (mask[k]) {
  1515. val = 0;
  1516. valTmp = (word << bitPos) >>> (32 - numBitsLUTQick);
  1517. valTmpQuick = valTmp;// >>> deltaBits;
  1518. if (32 - bitPos < numBitsLUTQick) {
  1519. valTmp |= ((stuffedData[srcPtr + 1]) >>> (64 - bitPos - numBitsLUTQick));
  1520. valTmpQuick = valTmp;// >>> deltaBits;
  1521. }
  1522. if (decodeLut[valTmpQuick]) // if there, move the correct number of bits and done
  1523. {
  1524. val = decodeLut[valTmpQuick][1];
  1525. bitPos += decodeLut[valTmpQuick][0];
  1526. }
  1527. else {
  1528. valTmp = (word << bitPos) >>> (32 - numBitsLUT);
  1529. valTmpQuick = valTmp;// >>> deltaBits;
  1530. if (32 - bitPos < numBitsLUT) {
  1531. valTmp |= ((stuffedData[srcPtr + 1]) >>> (64 - bitPos - numBitsLUT));
  1532. valTmpQuick = valTmp;// >>> deltaBits;
  1533. }
  1534. node = tree;
  1535. for (ii = 0; ii < numBitsLUT; ii++) {
  1536. currentBit = valTmp >>> (numBitsLUT - ii - 1) & 1;
  1537. node = currentBit ? node.right : node.left;
  1538. if (!(node.left || node.right)) {
  1539. val = node.val;
  1540. bitPos = bitPos + ii + 1;
  1541. break;
  1542. }
  1543. }
  1544. }
  1545. if (bitPos >= 32) {
  1546. bitPos -= 32;
  1547. srcPtr++;
  1548. word = stuffedData[srcPtr];
  1549. }
  1550. delta = val - offset;
  1551. if (deltaEncode) {
  1552. if (j > 0 && mask[k - 1]) {
  1553. delta += prevVal; // use overflow
  1554. }
  1555. else if (i > 0 && mask[k - width]) {
  1556. delta += resultPixels[k - width];
  1557. }
  1558. else {
  1559. delta += prevVal;
  1560. }
  1561. delta &= 0xFF; //overflow
  1562. resultPixels[k] = delta;//overflow
  1563. prevVal = delta;
  1564. }
  1565. else {
  1566. resultPixels[k] = delta;
  1567. }
  1568. }
  1569. }
  1570. }
  1571. }
  1572. data.ptr = data.ptr + (srcPtr + 1) * 4 + (bitPos > 0 ? 4 : 0);
  1573. }
  1574. data.pixels.resultPixels = resultPixelsAllDim;
  1575. },
  1576. decodeBits: function(input, data, blockDataBuffer, offset, iDim) {
  1577. {
  1578. //bitstuff encoding is 3
  1579. var headerInfo = data.headerInfo;
  1580. var fileVersion = headerInfo.fileVersion;
  1581. //var block = {};
  1582. var blockPtr = 0;
  1583. var viewByteLength = ((input.byteLength - data.ptr) >= 5) ? 5 : (input.byteLength - data.ptr);
  1584. var view = new DataView(input, data.ptr, viewByteLength);
  1585. var headerByte = view.getUint8(0);
  1586. blockPtr++;
  1587. var bits67 = headerByte >> 6;
  1588. var n = (bits67 === 0) ? 4 : 3 - bits67;
  1589. var doLut = (headerByte & 32) > 0 ? true : false;//5th bit
  1590. var numBits = headerByte & 31;
  1591. var numElements = 0;
  1592. if (n === 1) {
  1593. numElements = view.getUint8(blockPtr); blockPtr++;
  1594. } else if (n === 2) {
  1595. numElements = view.getUint16(blockPtr, true); blockPtr += 2;
  1596. } else if (n === 4) {
  1597. numElements = view.getUint32(blockPtr, true); blockPtr += 4;
  1598. } else {
  1599. throw "Invalid valid pixel count type";
  1600. }
  1601. //fix: huffman codes are bit stuffed, but not bound by data's max value, so need to use originalUnstuff
  1602. //offset = offset || 0;
  1603. var scale = 2 * headerInfo.maxZError;
  1604. var stuffedData, arrayBuf, store8, dataBytes, dataWords;
  1605. var lutArr, lutData, lutBytes, bitsPerPixel;
  1606. var zMax = headerInfo.numDims > 1 ? headerInfo.maxValues[iDim] : headerInfo.zMax;
  1607. if (doLut) {
  1608. data.counter.lut++;
  1609. lutBytes = view.getUint8(blockPtr);
  1610. blockPtr++;
  1611. dataBytes = Math.ceil((lutBytes - 1) * numBits / 8);
  1612. dataWords = Math.ceil(dataBytes / 4);
  1613. arrayBuf = new ArrayBuffer(dataWords * 4);
  1614. store8 = new Uint8Array(arrayBuf);
  1615. data.ptr += blockPtr;
  1616. store8.set(new Uint8Array(input, data.ptr, dataBytes));
  1617. lutData = new Uint32Array(arrayBuf);
  1618. data.ptr += dataBytes;
  1619. bitsPerPixel = 0;
  1620. while ((lutBytes - 1) >>> bitsPerPixel) {
  1621. bitsPerPixel++;
  1622. }
  1623. dataBytes = Math.ceil(numElements * bitsPerPixel / 8);
  1624. dataWords = Math.ceil(dataBytes / 4);
  1625. arrayBuf = new ArrayBuffer(dataWords * 4);
  1626. store8 = new Uint8Array(arrayBuf);
  1627. store8.set(new Uint8Array(input, data.ptr, dataBytes));
  1628. stuffedData = new Uint32Array(arrayBuf);
  1629. data.ptr += dataBytes;
  1630. if (fileVersion >= 3) {
  1631. lutArr = BitStuffer.unstuffLUT2(lutData, numBits, lutBytes - 1, offset, scale, zMax);
  1632. }
  1633. else {
  1634. lutArr = BitStuffer.unstuffLUT(lutData, numBits, lutBytes - 1, offset, scale, zMax);
  1635. }
  1636. //lutArr.unshift(0);
  1637. if (fileVersion >= 3) {
  1638. //BitStuffer.unstuff2(block, blockDataBuffer, headerInfo.zMax);
  1639. BitStuffer.unstuff2(stuffedData, blockDataBuffer, bitsPerPixel, numElements, lutArr);
  1640. }
  1641. else {
  1642. BitStuffer.unstuff(stuffedData, blockDataBuffer, bitsPerPixel, numElements, lutArr);
  1643. }
  1644. }
  1645. else {
  1646. //console.debug("bitstuffer");
  1647. data.counter.bitstuffer++;
  1648. bitsPerPixel = numBits;
  1649. data.ptr += blockPtr;
  1650. if (bitsPerPixel > 0) {
  1651. dataBytes = Math.ceil(numElements * bitsPerPixel / 8);
  1652. dataWords = Math.ceil(dataBytes / 4);
  1653. arrayBuf = new ArrayBuffer(dataWords * 4);
  1654. store8 = new Uint8Array(arrayBuf);
  1655. store8.set(new Uint8Array(input, data.ptr, dataBytes));
  1656. stuffedData = new Uint32Array(arrayBuf);
  1657. data.ptr += dataBytes;
  1658. if (fileVersion >= 3) {
  1659. if (offset === null) {
  1660. BitStuffer.originalUnstuff2(stuffedData, blockDataBuffer, bitsPerPixel, numElements);
  1661. }
  1662. else {
  1663. BitStuffer.unstuff2(stuffedData, blockDataBuffer, bitsPerPixel, numElements, false, offset, scale, zMax);
  1664. }
  1665. }
  1666. else {
  1667. if (offset === null) {
  1668. BitStuffer.originalUnstuff(stuffedData, blockDataBuffer, bitsPerPixel, numElements);
  1669. }
  1670. else {
  1671. BitStuffer.unstuff(stuffedData, blockDataBuffer, bitsPerPixel, numElements, false, offset, scale, zMax);
  1672. }
  1673. }
  1674. }
  1675. }
  1676. }
  1677. },
  1678. readTiles: function(input, data, OutPixelTypeArray) {
  1679. var headerInfo = data.headerInfo;
  1680. var width = headerInfo.width;
  1681. var height = headerInfo.height;
  1682. var microBlockSize = headerInfo.microBlockSize;
  1683. var imageType = headerInfo.imageType;
  1684. var dataTypeSize = Lerc2Helpers.getDataTypeSize(imageType);
  1685. var numBlocksX = Math.ceil(width / microBlockSize);
  1686. var numBlocksY = Math.ceil(height / microBlockSize);
  1687. data.pixels.numBlocksY = numBlocksY;
  1688. data.pixels.numBlocksX = numBlocksX;
  1689. data.pixels.ptr = 0;
  1690. var row = 0, col = 0, blockY = 0, blockX = 0, thisBlockHeight = 0, thisBlockWidth = 0, bytesLeft = 0, headerByte = 0, bits67 = 0, testCode = 0, outPtr = 0, outStride = 0, numBytes = 0, bytesleft = 0, z = 0, blockPtr = 0;
  1691. var view, block, arrayBuf, store8, rawData;
  1692. var blockEncoding;
  1693. var blockDataBuffer = new OutPixelTypeArray(microBlockSize * microBlockSize);
  1694. var lastBlockHeight = (height % microBlockSize) || microBlockSize;
  1695. var lastBlockWidth = (width % microBlockSize) || microBlockSize;
  1696. var offsetType, offset;
  1697. var numDims = headerInfo.numDims, iDim;
  1698. var mask = data.pixels.resultMask;
  1699. var resultPixels = data.pixels.resultPixels;
  1700. for (blockY = 0; blockY < numBlocksY; blockY++) {
  1701. thisBlockHeight = (blockY !== numBlocksY - 1) ? microBlockSize : lastBlockHeight;
  1702. for (blockX = 0; blockX < numBlocksX; blockX++) {
  1703. //console.debug("y" + blockY + " x" + blockX);
  1704. thisBlockWidth = (blockX !== numBlocksX - 1) ? microBlockSize : lastBlockWidth;
  1705. outPtr = blockY * width * microBlockSize + blockX * microBlockSize;
  1706. outStride = width - thisBlockWidth;
  1707. for (iDim = 0; iDim < numDims; iDim++) {
  1708. if (numDims > 1) {
  1709. resultPixels = new OutPixelTypeArray(data.pixels.resultPixels.buffer, width * height * iDim * dataTypeSize, width * height);
  1710. }
  1711. bytesLeft = input.byteLength - data.ptr;
  1712. view = new DataView(input, data.ptr, Math.min(10, bytesLeft));
  1713. block = {};
  1714. blockPtr = 0;
  1715. headerByte = view.getUint8(0);
  1716. blockPtr++;
  1717. bits67 = (headerByte >> 6) & 0xFF;
  1718. testCode = (headerByte >> 2) & 15; // use bits 2345 for integrity check
  1719. if (testCode !== (((blockX * microBlockSize) >> 3) & 15)) {
  1720. throw "integrity issue";
  1721. //return false;
  1722. }
  1723. blockEncoding = headerByte & 3;
  1724. if (blockEncoding > 3) {
  1725. data.ptr += blockPtr;
  1726. throw "Invalid block encoding (" + blockEncoding + ")";
  1727. }
  1728. else if (blockEncoding === 2) { //constant 0
  1729. data.counter.constant++;
  1730. data.ptr += blockPtr;
  1731. continue;
  1732. }
  1733. else if (blockEncoding === 0) { //uncompressed
  1734. data.counter.uncompressed++;
  1735. data.ptr += blockPtr;
  1736. numBytes = thisBlockHeight * thisBlockWidth * dataTypeSize;
  1737. bytesleft = input.byteLength - data.ptr;
  1738. numBytes = numBytes < bytesleft ? numBytes : bytesleft;
  1739. //bit alignment
  1740. arrayBuf = new ArrayBuffer((numBytes % dataTypeSize) === 0 ? numBytes : (numBytes + dataTypeSize - numBytes % dataTypeSize));
  1741. store8 = new Uint8Array(arrayBuf);
  1742. store8.set(new Uint8Array(input, data.ptr, numBytes));
  1743. rawData = new OutPixelTypeArray(arrayBuf);
  1744. z = 0;
  1745. if (mask) {
  1746. for (row = 0; row < thisBlockHeight; row++) {
  1747. for (col = 0; col < thisBlockWidth; col++) {
  1748. if (mask[outPtr]) {
  1749. resultPixels[outPtr] = rawData[z++];
  1750. }
  1751. outPtr++;
  1752. }
  1753. outPtr += outStride;
  1754. }
  1755. }
  1756. else {//all valid
  1757. for (row = 0; row < thisBlockHeight; row++) {
  1758. for (col = 0; col < thisBlockWidth; col++) {
  1759. resultPixels[outPtr++] = rawData[z++];
  1760. }
  1761. outPtr += outStride;
  1762. }
  1763. }
  1764. data.ptr += z * dataTypeSize;
  1765. }
  1766. else { //1 or 3
  1767. offsetType = Lerc2Helpers.getDataTypeUsed(imageType, bits67);
  1768. offset = Lerc2Helpers.getOnePixel(block, blockPtr, offsetType, view);
  1769. blockPtr += Lerc2Helpers.getDataTypeSize(offsetType);
  1770. if (blockEncoding === 3) //constant offset value
  1771. {
  1772. data.ptr += blockPtr;
  1773. data.counter.constantoffset++;
  1774. //you can delete the following resultMask case in favor of performance because val is constant and users use nodata mask, otherwise nodatavalue post processing handles it too.
  1775. //while the above statement is true, we're not doing it as we want to keep invalid pixel value at 0 rather than arbitrary values
  1776. if (mask) {
  1777. for (row = 0; row < thisBlockHeight; row++) {
  1778. for (col = 0; col < thisBlockWidth; col++) {
  1779. if (mask[outPtr]) {
  1780. resultPixels[outPtr] = offset;
  1781. }
  1782. outPtr++;
  1783. }
  1784. outPtr += outStride;
  1785. }
  1786. }
  1787. else {
  1788. for (row = 0; row < thisBlockHeight; row++) {
  1789. for (col = 0; col < thisBlockWidth; col++) {
  1790. resultPixels[outPtr++] = offset;
  1791. }
  1792. outPtr += outStride;
  1793. }
  1794. }
  1795. }
  1796. else { //bitstuff encoding is 3
  1797. data.ptr += blockPtr;
  1798. //heavy lifting
  1799. Lerc2Helpers.decodeBits(input, data, blockDataBuffer, offset, iDim);
  1800. blockPtr = 0;
  1801. if (mask) {
  1802. for (row = 0; row < thisBlockHeight; row++) {
  1803. for (col = 0; col < thisBlockWidth; col++) {
  1804. if (mask[outPtr]) {
  1805. resultPixels[outPtr] = blockDataBuffer[blockPtr++];
  1806. }
  1807. outPtr++;
  1808. }
  1809. outPtr += outStride;
  1810. }
  1811. }
  1812. else {
  1813. for (row = 0; row < thisBlockHeight; row++) {
  1814. for (col = 0; col < thisBlockWidth; col++) {
  1815. resultPixels[outPtr++] = blockDataBuffer[blockPtr++];
  1816. }
  1817. outPtr += outStride;
  1818. }
  1819. }
  1820. }
  1821. }
  1822. }
  1823. }
  1824. }
  1825. },
  1826. /*****************
  1827. * private methods (helper methods)
  1828. *****************/
  1829. formatFileInfo: function(data) {
  1830. return {
  1831. "fileIdentifierString": data.headerInfo.fileIdentifierString,
  1832. "fileVersion": data.headerInfo.fileVersion,
  1833. "imageType": data.headerInfo.imageType,
  1834. "height": data.headerInfo.height,
  1835. "width": data.headerInfo.width,
  1836. "numValidPixel": data.headerInfo.numValidPixel,
  1837. "microBlockSize": data.headerInfo.microBlockSize,
  1838. "blobSize": data.headerInfo.blobSize,
  1839. "maxZError": data.headerInfo.maxZError,
  1840. "pixelType": Lerc2Helpers.getPixelType(data.headerInfo.imageType),
  1841. "eofOffset": data.eofOffset,
  1842. "mask": data.mask ? {
  1843. "numBytes": data.mask.numBytes
  1844. } : null,
  1845. "pixels": {
  1846. "numBlocksX": data.pixels.numBlocksX,
  1847. "numBlocksY": data.pixels.numBlocksY,
  1848. //"numBytes": data.pixels.numBytes,
  1849. "maxValue": data.headerInfo.zMax,
  1850. "minValue": data.headerInfo.zMin,
  1851. "noDataValue": data.noDataValue
  1852. }
  1853. };
  1854. },
  1855. constructConstantSurface: function(data) {
  1856. var val = data.headerInfo.zMax;
  1857. var numDims = data.headerInfo.numDims;
  1858. var numPixels = data.headerInfo.height * data.headerInfo.width;
  1859. var numPixelAllDims = numPixels * numDims;
  1860. var i=0, k = 0, nStart=0;
  1861. var mask = data.pixels.resultMask;
  1862. if (mask) {
  1863. if (numDims > 1) {
  1864. for (i=0; i < numDims; i++) {
  1865. nStart = i * numPixels;
  1866. for (k = 0; k < numPixels; k++) {
  1867. if (mask[k]) {
  1868. data.pixels.resultPixels[nStart + k] = val;
  1869. }
  1870. }
  1871. }
  1872. }
  1873. else {
  1874. for (k = 0; k < numPixels; k++) {
  1875. if (mask[k]) {
  1876. data.pixels.resultPixels[k] = val;
  1877. }
  1878. }
  1879. }
  1880. }
  1881. else {
  1882. if (data.pixels.resultPixels.fill) {
  1883. data.pixels.resultPixels.fill(val);
  1884. }
  1885. else {
  1886. for (k = 0; k < numPixelAllDims; k++) {
  1887. data.pixels.resultPixels[k] = val;
  1888. }
  1889. }
  1890. }
  1891. return;
  1892. },
  1893. getDataTypeArray: function(t) {
  1894. var tp;
  1895. switch (t) {
  1896. case 0: //char
  1897. tp = Int8Array;
  1898. break;
  1899. case 1: //byte
  1900. tp = Uint8Array;
  1901. break;
  1902. case 2: //short
  1903. tp = Int16Array;
  1904. break;
  1905. case 3: //ushort
  1906. tp = Uint16Array;
  1907. break;
  1908. case 4:
  1909. tp = Int32Array;
  1910. break;
  1911. case 5:
  1912. tp = Uint32Array;
  1913. break;
  1914. case 6:
  1915. tp = Float32Array;
  1916. break;
  1917. case 7:
  1918. tp = Float64Array;
  1919. break;
  1920. default:
  1921. tp = Float32Array;
  1922. }
  1923. return tp;
  1924. },
  1925. getPixelType: function(t) {
  1926. var tp;
  1927. switch (t) {
  1928. case 0: //char
  1929. tp = "S8";
  1930. break;
  1931. case 1: //byte
  1932. tp = "U8";
  1933. break;
  1934. case 2: //short
  1935. tp = "S16";
  1936. break;
  1937. case 3: //ushort
  1938. tp = "U16";
  1939. break;
  1940. case 4:
  1941. tp = "S32";
  1942. break;
  1943. case 5:
  1944. tp = "U32";
  1945. break;
  1946. case 6:
  1947. tp = "F32";
  1948. break;
  1949. case 7:
  1950. tp = "F64"; //not supported
  1951. break;
  1952. default:
  1953. tp = "F32";
  1954. }
  1955. return tp;
  1956. },
  1957. isValidPixelValue: function(t, val) {
  1958. if (val === null) {
  1959. return false;
  1960. }
  1961. var isValid;
  1962. switch (t) {
  1963. case 0: //char
  1964. isValid = val >= -128 && val <= 127;
  1965. break;
  1966. case 1: //byte (unsigned char)
  1967. isValid = val >= 0 && val <= 255;
  1968. break;
  1969. case 2: //short
  1970. isValid = val >= -32768 && val <= 32767;
  1971. break;
  1972. case 3: //ushort
  1973. isValid = val >= 0 && val <= 65536;
  1974. break;
  1975. case 4: //int 32
  1976. isValid = val >= -2147483648 && val <= 2147483647;
  1977. break;
  1978. case 5: //uinit 32
  1979. isValid = val >= 0 && val <= 4294967296;
  1980. break;
  1981. case 6:
  1982. isValid = val >= -3.4027999387901484e+38 && val <= 3.4027999387901484e+38;
  1983. break;
  1984. case 7:
  1985. isValid = val >= 5e-324 && val <= 1.7976931348623157e+308;
  1986. break;
  1987. default:
  1988. isValid = false;
  1989. }
  1990. return isValid;
  1991. },
  1992. getDataTypeSize: function(t) {
  1993. var s = 0;
  1994. switch (t) {
  1995. case 0: //ubyte
  1996. case 1: //byte
  1997. s = 1;
  1998. break;
  1999. case 2: //short
  2000. case 3: //ushort
  2001. s = 2;
  2002. break;
  2003. case 4:
  2004. case 5:
  2005. case 6:
  2006. s = 4;
  2007. break;
  2008. case 7:
  2009. s = 8;
  2010. break;
  2011. default:
  2012. s = t;
  2013. }
  2014. return s;
  2015. },
  2016. getDataTypeUsed: function(dt, tc) {
  2017. var t = dt;
  2018. switch (dt) {
  2019. case 2: //short
  2020. case 4: //long
  2021. t = dt - tc;
  2022. break;
  2023. case 3: //ushort
  2024. case 5: //ulong
  2025. t = dt - 2 * tc;
  2026. break;
  2027. case 6: //float
  2028. if (0 === tc) {
  2029. t = dt;
  2030. }
  2031. else if (1 === tc) {
  2032. t = 2;
  2033. }
  2034. else {
  2035. t = 1;//byte
  2036. }
  2037. break;
  2038. case 7: //double
  2039. if (0 === tc) {
  2040. t = dt;
  2041. }
  2042. else {
  2043. t = dt - 2 * tc + 1;
  2044. }
  2045. break;
  2046. default:
  2047. t = dt;
  2048. break;
  2049. }
  2050. return t;
  2051. },
  2052. getOnePixel: function(block, blockPtr, offsetType, view) {
  2053. var temp = 0;
  2054. switch (offsetType) {
  2055. case 0: //char
  2056. temp = view.getInt8(blockPtr);
  2057. break;
  2058. case 1: //byte
  2059. temp = view.getUint8(blockPtr);
  2060. break;
  2061. case 2:
  2062. temp = view.getInt16(blockPtr, true);
  2063. break;
  2064. case 3:
  2065. temp = view.getUint16(blockPtr, true);
  2066. break;
  2067. case 4:
  2068. temp = view.getInt32(blockPtr, true);
  2069. break;
  2070. case 5:
  2071. temp = view.getUInt32(blockPtr, true);
  2072. break;
  2073. case 6:
  2074. temp = view.getFloat32(blockPtr, true);
  2075. break;
  2076. case 7:
  2077. //temp = view.getFloat64(blockPtr, true);
  2078. //blockPtr += 8;
  2079. //lerc2 encoding doesnt handle float 64, force to float32???
  2080. temp = view.getFloat64(blockPtr, true);
  2081. break;
  2082. default:
  2083. throw ("the decoder does not understand this pixel type");
  2084. }
  2085. return temp;
  2086. }
  2087. };
  2088. /***************************************************
  2089. *private class for a tree node. Huffman code is in Lerc2Helpers
  2090. ****************************************************/
  2091. var TreeNode = function(val, left, right) {
  2092. this.val = val;
  2093. this.left = left;
  2094. this.right = right;
  2095. };
  2096. var Lerc2Decode = {
  2097. /*
  2098. * ********removed options compared to LERC1. We can bring some of them back if needed.
  2099. * removed pixel type. LERC2 is typed and doesn't require user to give pixel type
  2100. * changed encodedMaskData to maskData. LERC2 's js version make it faster to use maskData directly.
  2101. * removed returnMask. mask is used by LERC2 internally and is cost free. In case of user input mask, it's returned as well and has neglible cost.
  2102. * removed nodatavalue. Because LERC2 pixels are typed, nodatavalue will sacrify a useful value for many types (8bit, 16bit) etc,
  2103. * user has to be knowledgable enough about raster and their data to avoid usability issues. so nodata value is simply removed now.
  2104. * We can add it back later if their's a clear requirement.
  2105. * removed encodedMask. This option was not implemented in LercDecode. It can be done after decoding (less efficient)
  2106. * removed computeUsedBitDepths.
  2107. *
  2108. *
  2109. * response changes compared to LERC1
  2110. * 1. encodedMaskData is not available
  2111. * 2. noDataValue is optional (returns only if user's noDataValue is with in the valid data type range)
  2112. * 3. maskData is always available
  2113. */
  2114. /*****************
  2115. * public properties
  2116. ******************/
  2117. //HUFFMAN_LUT_BITS_MAX: 12, //use 2^12 lut, not configurable
  2118. /*****************
  2119. * public methods
  2120. *****************/
  2121. /**
  2122. * Decode a LERC2 byte stream and return an object containing the pixel data and optional metadata.
  2123. *
  2124. * @param {ArrayBuffer} input The LERC input byte stream
  2125. * @param {object} [options] options Decoding options
  2126. * @param {number} [options.inputOffset] The number of bytes to skip in the input byte stream. A valid LERC file is expected at that position
  2127. * @param {boolean} [options.returnFileInfo] If true, the return value will have a fileInfo property that contains metadata obtained from the LERC headers and the decoding process
  2128. */
  2129. decode: function(/*byte array*/ input, /*object*/ options) {
  2130. //currently there's a bug in the sparse array, so please do not set to false
  2131. options = options || {};
  2132. var noDataValue = options.noDataValue;
  2133. //initialize
  2134. var i = 0, data = {};
  2135. data.ptr = options.inputOffset || 0;
  2136. data.pixels = {};
  2137. // File header
  2138. if (!Lerc2Helpers.readHeaderInfo(input, data)) {
  2139. return;
  2140. }
  2141. var headerInfo = data.headerInfo;
  2142. var fileVersion = headerInfo.fileVersion;
  2143. var OutPixelTypeArray = Lerc2Helpers.getDataTypeArray(headerInfo.imageType);
  2144. // Mask Header
  2145. Lerc2Helpers.readMask(input, data);
  2146. if (headerInfo.numValidPixel !== headerInfo.width * headerInfo.height && !data.pixels.resultMask) {
  2147. data.pixels.resultMask = options.maskData;
  2148. }
  2149. var numPixels = headerInfo.width * headerInfo.height;
  2150. data.pixels.resultPixels = new OutPixelTypeArray(numPixels * headerInfo.numDims);
  2151. data.counter = {
  2152. onesweep: 0,
  2153. uncompressed: 0,
  2154. lut: 0,
  2155. bitstuffer: 0,
  2156. constant: 0,
  2157. constantoffset: 0
  2158. };
  2159. if (headerInfo.numValidPixel !== 0) {
  2160. //not tested
  2161. if (headerInfo.zMax === headerInfo.zMin) //constant surface
  2162. {
  2163. Lerc2Helpers.constructConstantSurface(data);
  2164. }
  2165. else if (fileVersion >= 4 && Lerc2Helpers.checkMinMaxRanges(input, data)) {
  2166. Lerc2Helpers.constructConstantSurface(data);
  2167. }
  2168. else {
  2169. var view = new DataView(input, data.ptr, 2);
  2170. var bReadDataOneSweep = view.getUint8(0);
  2171. data.ptr++;
  2172. if (bReadDataOneSweep) {
  2173. //console.debug("OneSweep");
  2174. Lerc2Helpers.readDataOneSweep(input, data, OutPixelTypeArray);
  2175. }
  2176. else {
  2177. //lerc2.1: //bitstuffing + lut
  2178. //lerc2.2: //bitstuffing + lut + huffman
  2179. //lerc2.3: new bitstuffer
  2180. if (fileVersion > 1 && headerInfo.imageType <= 1 && Math.abs(headerInfo.maxZError - 0.5) < 0.00001) {
  2181. //this is 2.x plus 8 bit (unsigned and signed) data, possiblity of Huffman
  2182. var flagHuffman = view.getUint8(1);
  2183. data.ptr++;
  2184. data.encodeMode = flagHuffman;
  2185. if (flagHuffman > 2 || (fileVersion < 4 && flagHuffman > 1)) {
  2186. throw "Invalid Huffman flag " + flagHuffman;
  2187. }
  2188. if (flagHuffman) {//1 - delta Huffman, 2 - Huffman
  2189. //console.log("Huffman");
  2190. Lerc2Helpers.readHuffman(input, data, OutPixelTypeArray);
  2191. }
  2192. else {
  2193. //console.log("Tiles");
  2194. Lerc2Helpers.readTiles(input, data, OutPixelTypeArray);
  2195. }
  2196. }
  2197. else { //lerc2.x non-8 bit data
  2198. //console.log("Tiles");
  2199. Lerc2Helpers.readTiles(input, data, OutPixelTypeArray);
  2200. }
  2201. }
  2202. }
  2203. }
  2204. data.eofOffset = data.ptr;
  2205. var diff;
  2206. if (options.inputOffset) {
  2207. diff = data.headerInfo.blobSize + options.inputOffset - data.ptr;
  2208. if (Math.abs(diff) >= 1) {
  2209. //console.debug("incorrect eof: dataptr " + data.ptr + " offset " + options.inputOffset + " blobsize " + data.headerInfo.blobSize + " diff: " + diff);
  2210. data.eofOffset = options.inputOffset + data.headerInfo.blobSize;
  2211. }
  2212. }
  2213. else {
  2214. diff = data.headerInfo.blobSize - data.ptr;
  2215. if (Math.abs(diff) >= 1) {
  2216. //console.debug("incorrect first band eof: dataptr " + data.ptr + " blobsize " + data.headerInfo.blobSize + " diff: " + diff);
  2217. data.eofOffset = data.headerInfo.blobSize;
  2218. }
  2219. }
  2220. var result = {
  2221. width: headerInfo.width,
  2222. height: headerInfo.height,
  2223. pixelData: data.pixels.resultPixels,
  2224. minValue: headerInfo.zMin,
  2225. maxValue: headerInfo.zMax,
  2226. validPixelCount: headerInfo.numValidPixel,
  2227. dimCount: headerInfo.numDims,
  2228. dimStats: {
  2229. minValues: headerInfo.minValues,
  2230. maxValues: headerInfo.maxValues
  2231. },
  2232. maskData: data.pixels.resultMask
  2233. //noDataValue: noDataValue
  2234. };
  2235. //we should remove this if there's no existing client
  2236. //optional noDataValue processing, it's user's responsiblity
  2237. if (data.pixels.resultMask && Lerc2Helpers.isValidPixelValue(headerInfo.imageType, noDataValue)) {
  2238. var mask = data.pixels.resultMask;
  2239. for (i = 0; i < numPixels; i++) {
  2240. if (!mask[i]) {
  2241. result.pixelData[i] = noDataValue;
  2242. }
  2243. }
  2244. result.noDataValue = noDataValue;
  2245. }
  2246. data.noDataValue = noDataValue;
  2247. if (options.returnFileInfo) {
  2248. result.fileInfo = Lerc2Helpers.formatFileInfo(data);
  2249. }
  2250. return result;
  2251. },
  2252. getBandCount: function(/*byte array*/ input) {
  2253. var count = 0;
  2254. var i = 0;
  2255. var temp = {};
  2256. temp.ptr = 0;
  2257. temp.pixels = {};
  2258. while (i < input.byteLength - 58) {
  2259. Lerc2Helpers.readHeaderInfo(input, temp);
  2260. i += temp.headerInfo.blobSize;
  2261. count++;
  2262. temp.ptr = i;
  2263. }
  2264. return count;
  2265. }
  2266. };
  2267. return Lerc2Decode;
  2268. })();
  2269. var isPlatformLittleEndian = (function() {
  2270. var a = new ArrayBuffer(4);
  2271. var b = new Uint8Array(a);
  2272. var c = new Uint32Array(a);
  2273. c[0] = 1;
  2274. return b[0] === 1;
  2275. })();
  2276. var Lerc = {
  2277. /************wrapper**********************************************/
  2278. /**
  2279. * A wrapper for decoding both LERC1 and LERC2 byte streams capable of handling multiband pixel blocks for various pixel types.
  2280. *
  2281. * @alias module:Lerc
  2282. * @param {ArrayBuffer} input The LERC input byte stream
  2283. * @param {object} [options] The decoding options below are optional.
  2284. * @param {number} [options.inputOffset] The number of bytes to skip in the input byte stream. A valid Lerc file is expected at that position.
  2285. * @param {string} [options.pixelType] (LERC1 only) Default value is F32. Valid pixel types for input are U8/S8/S16/U16/S32/U32/F32.
  2286. * @param {number} [options.noDataValue] (LERC1 only). It is recommended to use the returned mask instead of setting this value.
  2287. * @returns {{width, height, pixels, pixelType, mask, statistics}}
  2288. * @property {number} width Width of decoded image.
  2289. * @property {number} height Height of decoded image.
  2290. * @property {array} pixels [band1, band2, …] Each band is a typed array of width*height.
  2291. * @property {string} pixelType The type of pixels represented in the output.
  2292. * @property {mask} mask Typed array with a size of width*height, or null if all pixels are valid.
  2293. * @property {array} statistics [statistics_band1, statistics_band2, …] Each element is a statistics object representing min and max values
  2294. **/
  2295. decode: function(encodedData, options) {
  2296. if (!isPlatformLittleEndian) {
  2297. throw "Big endian system is not supported.";
  2298. }
  2299. options = options || {};
  2300. var inputOffset = options.inputOffset || 0;
  2301. var fileIdView = new Uint8Array(encodedData, inputOffset, 10);
  2302. var fileIdentifierString = String.fromCharCode.apply(null, fileIdView);
  2303. var lerc, majorVersion;
  2304. if (fileIdentifierString.trim() === "CntZImage") {
  2305. lerc = LercDecode;
  2306. majorVersion = 1;
  2307. }
  2308. else if (fileIdentifierString.substring(0, 5) === "Lerc2") {
  2309. lerc = Lerc2Decode;
  2310. majorVersion = 2;
  2311. }
  2312. else {
  2313. throw "Unexpected file identifier string: " + fileIdentifierString;
  2314. }
  2315. var iPlane = 0, eof = encodedData.byteLength - 10, encodedMaskData, bandMasks = [], bandMask, maskData;
  2316. var decodedPixelBlock = {
  2317. width: 0,
  2318. height: 0,
  2319. pixels: [],
  2320. pixelType: options.pixelType,
  2321. mask: null,
  2322. statistics: []
  2323. };
  2324. while (inputOffset < eof) {
  2325. var result = lerc.decode(encodedData, {
  2326. inputOffset: inputOffset,//for both lerc1 and lerc2
  2327. encodedMaskData: encodedMaskData,//lerc1 only
  2328. maskData: maskData,//lerc2 only
  2329. returnMask: iPlane === 0 ? true : false,//lerc1 only
  2330. returnEncodedMask: iPlane === 0 ? true : false,//lerc1 only
  2331. returnFileInfo: true,//for both lerc1 and lerc2
  2332. pixelType: options.pixelType || null,//lerc1 only
  2333. noDataValue: options.noDataValue || null//lerc1 only
  2334. });
  2335. inputOffset = result.fileInfo.eofOffset;
  2336. if (iPlane === 0) {
  2337. encodedMaskData = result.encodedMaskData;//lerc1
  2338. maskData = result.maskData;//lerc2
  2339. decodedPixelBlock.width = result.width;
  2340. decodedPixelBlock.height = result.height;
  2341. decodedPixelBlock.dimCount = result.dimCount || 1;
  2342. //decodedPixelBlock.dimStats = decodedPixelBlock.dimStats;
  2343. decodedPixelBlock.pixelType = result.pixelType || result.fileInfo.pixelType;
  2344. decodedPixelBlock.mask = result.maskData;
  2345. }
  2346. if (majorVersion >1 && result.fileInfo.mask && result.fileInfo.mask.numBytes > 0) {
  2347. bandMasks.push(result.maskData);
  2348. }
  2349. iPlane++;
  2350. decodedPixelBlock.pixels.push(result.pixelData);
  2351. decodedPixelBlock.statistics.push({
  2352. minValue: result.minValue,
  2353. maxValue: result.maxValue,
  2354. noDataValue: result.noDataValue,
  2355. dimStats: result.dimStats
  2356. });
  2357. }
  2358. var i, j, numPixels;
  2359. if (majorVersion > 1 && bandMasks.length > 1) {
  2360. numPixels = decodedPixelBlock.width * decodedPixelBlock.height;
  2361. decodedPixelBlock.bandMasks = bandMasks;
  2362. maskData = new Uint8Array(numPixels);
  2363. maskData.set(bandMasks[0]);
  2364. for (i = 1; i < bandMasks.length; i++) {
  2365. bandMask = bandMasks[i];
  2366. for (j = 0; j < numPixels; j++) {
  2367. maskData[j] = maskData[j] & bandMask[j];
  2368. }
  2369. }
  2370. decodedPixelBlock.maskData = maskData;
  2371. }
  2372. return decodedPixelBlock;
  2373. }
  2374. };
  2375. tmp.Lerc = Lerc;
  2376. })();
  2377. var Lerc = tmp.Lerc;
  2378. function createVerticesFromHeightmap(parameters, transferableObjects) {
  2379. // LERC encoded buffers must be decoded, then we can process them like normal
  2380. if (parameters.encoding === HeightmapEncoding$1.LERC) {
  2381. var result;
  2382. try {
  2383. result = Lerc.decode(parameters.heightmap);
  2384. } catch (error) {
  2385. throw new RuntimeError.RuntimeError(error);
  2386. }
  2387. var lercStatistics = result.statistics[0];
  2388. if (lercStatistics.minValue === Number.MAX_VALUE) {
  2389. throw new RuntimeError.RuntimeError('Invalid tile data');
  2390. }
  2391. parameters.heightmap = result.pixels[0];
  2392. parameters.width = result.width;
  2393. parameters.height = result.height;
  2394. }
  2395. parameters.ellipsoid = Cartesian2.Ellipsoid.clone(parameters.ellipsoid);
  2396. parameters.rectangle = Cartesian2.Rectangle.clone(parameters.rectangle);
  2397. var statistics = HeightmapTessellator.computeVertices(parameters);
  2398. var vertices = statistics.vertices;
  2399. transferableObjects.push(vertices.buffer);
  2400. return {
  2401. vertices : vertices.buffer,
  2402. numberOfAttributes : statistics.encoding.getStride(),
  2403. minimumHeight : statistics.minimumHeight,
  2404. maximumHeight : statistics.maximumHeight,
  2405. gridWidth : parameters.width,
  2406. gridHeight : parameters.height,
  2407. boundingSphere3D : statistics.boundingSphere3D,
  2408. orientedBoundingBox : statistics.orientedBoundingBox,
  2409. occludeePointInScaledSpace : statistics.occludeePointInScaledSpace,
  2410. encoding : statistics.encoding,
  2411. westIndicesSouthToNorth : statistics.westIndicesSouthToNorth,
  2412. southIndicesEastToWest : statistics.southIndicesEastToWest,
  2413. eastIndicesNorthToSouth : statistics.eastIndicesNorthToSouth,
  2414. northIndicesWestToEast : statistics.northIndicesWestToEast
  2415. };
  2416. }
  2417. var createVerticesFromHeightmap$1 = createTaskProcessorWorker(createVerticesFromHeightmap);
  2418. return createVerticesFromHeightmap$1;
  2419. });