createVerticesFromHeightmap.js 106 KB

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