PotreeRenderer.js 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482
  1. import * as THREE from "../libs/three.js/build/three.module.js";
  2. import {PointCloudTree} from "./PointCloudTree.js";
  3. import {PointCloudOctreeNode} from "./PointCloudOctree.js";
  4. import {PointCloudArena4DNode} from "./arena4d/PointCloudArena4D.js";
  5. import {PointSizeType, ClipTask, ElevationGradientRepeat} from "./defines.js";
  6. // Copied from three.js: WebGLRenderer.js
  7. function paramThreeToGL(_gl, p) {
  8. let extension;
  9. if (p === THREE.RepeatWrapping) return _gl.REPEAT;
  10. if (p === THREE.ClampToEdgeWrapping) return _gl.CLAMP_TO_EDGE;
  11. if (p === THREE.MirroredRepeatWrapping) return _gl.MIRRORED_REPEAT;
  12. if (p === THREE.NearestFilter) return _gl.NEAREST;
  13. if (p === THREE.NearestMipMapNearestFilter) return _gl.NEAREST_MIPMAP_NEAREST;
  14. if (p === THREE.NearestMipMapLinearFilter) return _gl.NEAREST_MIPMAP_LINEAR;
  15. if (p === THREE.LinearFilter) return _gl.LINEAR;
  16. if (p === THREE.LinearMipMapNearestFilter) return _gl.LINEAR_MIPMAP_NEAREST;
  17. if (p === THREE.LinearMipMapLinearFilter) return _gl.LINEAR_MIPMAP_LINEAR;
  18. if (p === THREE.UnsignedByteType) return _gl.UNSIGNED_BYTE;
  19. if (p === THREE.UnsignedShort4444Type) return _gl.UNSIGNED_SHORT_4_4_4_4;
  20. if (p === THREE.UnsignedShort5551Type) return _gl.UNSIGNED_SHORT_5_5_5_1;
  21. if (p === THREE.UnsignedShort565Type) return _gl.UNSIGNED_SHORT_5_6_5;
  22. if (p === THREE.ByteType) return _gl.BYTE;
  23. if (p === THREE.ShortType) return _gl.SHORT;
  24. if (p === THREE.UnsignedShortType) return _gl.UNSIGNED_SHORT;
  25. if (p === THREE.IntType) return _gl.INT;
  26. if (p === THREE.UnsignedIntType) return _gl.UNSIGNED_INT;
  27. if (p === THREE.FloatType) return _gl.FLOAT;
  28. if (p === THREE.HalfFloatType) {
  29. extension = extensions.get('OES_texture_half_float');
  30. if (extension !== null) return extension.HALF_FLOAT_OES;
  31. }
  32. if (p === THREE.AlphaFormat) return _gl.ALPHA;
  33. if (p === THREE.RGBFormat) return _gl.RGB;
  34. if (p === THREE.RGBAFormat) return _gl.RGBA;
  35. if (p === THREE.LuminanceFormat) return _gl.LUMINANCE;
  36. if (p === THREE.LuminanceAlphaFormat) return _gl.LUMINANCE_ALPHA;
  37. if (p === THREE.DepthFormat) return _gl.DEPTH_COMPONENT;
  38. if (p === THREE.DepthStencilFormat) return _gl.DEPTH_STENCIL;
  39. if (p === THREE.AddEquation) return _gl.FUNC_ADD;
  40. if (p === THREE.SubtractEquation) return _gl.FUNC_SUBTRACT;
  41. if (p === THREE.ReverseSubtractEquation) return _gl.FUNC_REVERSE_SUBTRACT;
  42. if (p === THREE.ZeroFactor) return _gl.ZERO;
  43. if (p === THREE.OneFactor) return _gl.ONE;
  44. if (p === THREE.SrcColorFactor) return _gl.SRC_COLOR;
  45. if (p === THREE.OneMinusSrcColorFactor) return _gl.ONE_MINUS_SRC_COLOR;
  46. if (p === THREE.SrcAlphaFactor) return _gl.SRC_ALPHA;
  47. if (p === THREE.OneMinusSrcAlphaFactor) return _gl.ONE_MINUS_SRC_ALPHA;
  48. if (p === THREE.DstAlphaFactor) return _gl.DST_ALPHA;
  49. if (p === THREE.OneMinusDstAlphaFactor) return _gl.ONE_MINUS_DST_ALPHA;
  50. if (p === THREE.DstColorFactor) return _gl.DST_COLOR;
  51. if (p === THREE.OneMinusDstColorFactor) return _gl.ONE_MINUS_DST_COLOR;
  52. if (p === THREE.SrcAlphaSaturateFactor) return _gl.SRC_ALPHA_SATURATE;
  53. if (p === THREE.RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  54. p === THREE.RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  55. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  56. if (extension !== null) {
  57. if (p === THREE.RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  58. if (p === THREE.RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  59. if (p === THREE.RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  60. if (p === THREE.RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  61. }
  62. }
  63. if (p === THREE.RGB_PVRTC_4BPPV1_Format || p === THREE.RGB_PVRTC_2BPPV1_Format ||
  64. p === THREE.RGBA_PVRTC_4BPPV1_Format || p === THREE.RGBA_PVRTC_2BPPV1_Format) {
  65. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  66. if (extension !== null) {
  67. if (p === THREE.RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  68. if (p === THREE.RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  69. if (p === THREE.RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  70. if (p === THREE.RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  71. }
  72. }
  73. if (p === THREE.RGB_ETC1_Format) {
  74. extension = extensions.get('WEBGL_compressed_texture_etc1');
  75. if (extension !== null) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  76. }
  77. if (p === THREE.MinEquation || p === THREE.MaxEquation) {
  78. extension = extensions.get('EXT_blend_minmax');
  79. if (extension !== null) {
  80. if (p === THREE.MinEquation) return extension.MIN_EXT;
  81. if (p === THREE.MaxEquation) return extension.MAX_EXT;
  82. }
  83. }
  84. if (p === UnsignedInt248Type) {
  85. extension = extensions.get('WEBGL_depth_texture');
  86. if (extension !== null) return extension.UNSIGNED_INT_24_8_WEBGL;
  87. }
  88. return 0;
  89. };
  90. let attributeLocations = {
  91. "position": {name: "position", location: 0},
  92. "color": {name: "color", location: 1},
  93. "rgba": {name: "color", location: 1},
  94. "intensity": {name: "intensity", location: 2},
  95. "classification": {name: "classification", location: 3},
  96. "returnNumber": {name: "returnNumber", location: 4},
  97. "return number": {name: "returnNumber", location: 4},
  98. "returns": {name: "returnNumber", location: 4},
  99. "numberOfReturns": {name: "numberOfReturns", location: 5},
  100. "number of returns": {name: "numberOfReturns", location: 5},
  101. "pointSourceID": {name: "pointSourceID", location: 6},
  102. "source id": {name: "pointSourceID", location: 6},
  103. "point source id": {name: "pointSourceID", location: 6},
  104. "indices": {name: "indices", location: 7},
  105. "normal": {name: "normal", location: 8},
  106. "spacing": {name: "spacing", location: 9},
  107. "gps-time": {name: "gpsTime", location: 10},
  108. "aExtra": {name: "aExtra", location: 11},
  109. };
  110. class Shader {
  111. constructor(gl, name, vsSource, fsSource) {
  112. this.gl = gl;
  113. this.name = name;
  114. this.vsSource = vsSource;
  115. this.fsSource = fsSource;
  116. this.cache = new Map();
  117. this.vs = null;
  118. this.fs = null;
  119. this.program = null;
  120. this.uniformLocations = {};
  121. this.attributeLocations = {};
  122. this.uniformBlockIndices = {};
  123. this.uniformBlocks = {};
  124. this.uniforms = {};
  125. this.update(vsSource, fsSource);
  126. }
  127. update(vsSource, fsSource) {
  128. this.vsSource = vsSource;
  129. this.fsSource = fsSource;
  130. this.linkProgram();
  131. }
  132. compileShader(shader, source){
  133. let gl = this.gl;
  134. gl.shaderSource(shader, source);
  135. gl.compileShader(shader);
  136. let success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  137. if (!success) {
  138. let info = gl.getShaderInfoLog(shader);
  139. let numberedSource = source.split("\n").map((a, i) => `${i + 1}`.padEnd(5) + a).join("\n");
  140. throw `could not compile shader ${this.name}: ${info}, \n${numberedSource}`;
  141. }
  142. }
  143. linkProgram() {
  144. const tStart = performance.now();
  145. let gl = this.gl;
  146. this.uniformLocations = {};
  147. this.attributeLocations = {};
  148. this.uniforms = {};
  149. gl.useProgram(null);
  150. let cached = this.cache.get(`${this.vsSource}, ${this.fsSource}`);
  151. if (cached) {
  152. this.program = cached.program;
  153. this.vs = cached.vs;
  154. this.fs = cached.fs;
  155. this.attributeLocations = cached.attributeLocations;
  156. this.uniformLocations = cached.uniformLocations;
  157. this.uniformBlocks = cached.uniformBlocks;
  158. this.uniforms = cached.uniforms;
  159. return;
  160. } else {
  161. this.vs = gl.createShader(gl.VERTEX_SHADER);
  162. this.fs = gl.createShader(gl.FRAGMENT_SHADER);
  163. this.program = gl.createProgram();
  164. for(let name of Object.keys(attributeLocations)){
  165. let location = attributeLocations[name].location;
  166. let glslName = attributeLocations[name].name;
  167. gl.bindAttribLocation(this.program, location, glslName);
  168. }
  169. this.compileShader(this.vs, this.vsSource);
  170. this.compileShader(this.fs, this.fsSource);
  171. let program = this.program;
  172. gl.attachShader(program, this.vs);
  173. gl.attachShader(program, this.fs);
  174. gl.linkProgram(program);
  175. gl.detachShader(program, this.vs);
  176. gl.detachShader(program, this.fs);
  177. let success = gl.getProgramParameter(program, gl.LINK_STATUS);
  178. if (!success) {
  179. let info = gl.getProgramInfoLog(program);
  180. throw `could not link program ${this.name}: ${info}`;
  181. }
  182. { // attribute locations
  183. let numAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  184. for (let i = 0; i < numAttributes; i++) {
  185. let attribute = gl.getActiveAttrib(program, i);
  186. let location = gl.getAttribLocation(program, attribute.name);
  187. this.attributeLocations[attribute.name] = location;
  188. }
  189. }
  190. { // uniform locations
  191. let numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  192. for (let i = 0; i < numUniforms; i++) {
  193. let uniform = gl.getActiveUniform(program, i);
  194. let location = gl.getUniformLocation(program, uniform.name);
  195. this.uniformLocations[uniform.name] = location;
  196. this.uniforms[uniform.name] = {
  197. location: location,
  198. value: null,
  199. };
  200. }
  201. }
  202. // uniform blocks
  203. if(typeof WebGL2RenderingContext != 'undefined' && gl instanceof WebGL2RenderingContext){
  204. let numBlocks = gl.getProgramParameter(program, gl.ACTIVE_UNIFORM_BLOCKS);
  205. for (let i = 0; i < numBlocks; i++) {
  206. let blockName = gl.getActiveUniformBlockName(program, i);
  207. let blockIndex = gl.getUniformBlockIndex(program, blockName);
  208. this.uniformBlockIndices[blockName] = blockIndex;
  209. gl.uniformBlockBinding(program, blockIndex, blockIndex);
  210. let dataSize = gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_DATA_SIZE);
  211. let uBuffer = gl.createBuffer();
  212. gl.bindBuffer(gl.UNIFORM_BUFFER, uBuffer);
  213. gl.bufferData(gl.UNIFORM_BUFFER, dataSize, gl.DYNAMIC_READ);
  214. gl.bindBufferBase(gl.UNIFORM_BUFFER, blockIndex, uBuffer);
  215. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  216. this.uniformBlocks[blockName] = {
  217. name: blockName,
  218. index: blockIndex,
  219. dataSize: dataSize,
  220. buffer: uBuffer
  221. };
  222. }
  223. }
  224. let cached = {
  225. program: this.program,
  226. vs: this.vs,
  227. fs: this.fs,
  228. attributeLocations: this.attributeLocations,
  229. uniformLocations: this.uniformLocations,
  230. uniforms: this.uniforms,
  231. uniformBlocks: this.uniformBlocks,
  232. };
  233. this.cache.set(`${this.vsSource}, ${this.fsSource}`, cached);
  234. }
  235. const tEnd = performance.now();
  236. const duration = tEnd - tStart;
  237. console.log(`shader compile duration: ${duration.toFixed(3)}`);
  238. }
  239. setUniformMatrix4(name, value) {
  240. const gl = this.gl;
  241. const location = this.uniformLocations[name];
  242. if (location == null) {
  243. return;
  244. }
  245. let tmp = new Float32Array(value.elements);
  246. gl.uniformMatrix4fv(location, false, tmp);
  247. }
  248. setUniform1f(name, value) {
  249. const gl = this.gl;
  250. const uniform = this.uniforms[name];
  251. if (uniform === undefined) {
  252. return;
  253. }
  254. if(uniform.value === value){
  255. return;
  256. }
  257. uniform.value = value;
  258. gl.uniform1f(uniform.location, value);
  259. }
  260. setUniformBoolean(name, value) {
  261. const gl = this.gl;
  262. const uniform = this.uniforms[name];
  263. if (uniform === undefined) {
  264. return;
  265. }
  266. if(uniform.value === value){
  267. return;
  268. }
  269. uniform.value = value;
  270. gl.uniform1i(uniform.location, value);
  271. }
  272. setUniformTexture(name, value) {
  273. const gl = this.gl;
  274. const location = this.uniformLocations[name];
  275. if (location == null) {
  276. return;
  277. }
  278. gl.uniform1i(location, value);
  279. }
  280. setUniform2f(name, value) {
  281. const gl = this.gl;
  282. const location = this.uniformLocations[name];
  283. if (location == null) {
  284. return;
  285. }
  286. gl.uniform2f(location, value[0], value[1]);
  287. }
  288. setUniform3f(name, value) {
  289. const gl = this.gl;
  290. const location = this.uniformLocations[name];
  291. if (location == null) {
  292. return;
  293. }
  294. gl.uniform3f(location, value[0], value[1], value[2]);
  295. }
  296. setUniform(name, value) {
  297. if (value.constructor === THREE.Matrix4) {
  298. this.setUniformMatrix4(name, value);
  299. } else if (typeof value === "number") {
  300. this.setUniform1f(name, value);
  301. } else if (typeof value === "boolean") {
  302. this.setUniformBoolean(name, value);
  303. } else if (value instanceof WebGLTexture) {
  304. this.setUniformTexture(name, value);
  305. } else if (value instanceof Array) {
  306. if (value.length === 2) {
  307. this.setUniform2f(name, value);
  308. } else if (value.length === 3) {
  309. this.setUniform3f(name, value);
  310. }
  311. } else {
  312. console.error("unhandled uniform type: ", name, value);
  313. }
  314. }
  315. setUniform1i(name, value) {
  316. let gl = this.gl;
  317. let location = this.uniformLocations[name];
  318. if (location == null) {
  319. return;
  320. }
  321. gl.uniform1i(location, value);
  322. }
  323. };
  324. class WebGLTexture {
  325. constructor(gl, texture) {
  326. this.gl = gl;
  327. this.texture = texture;
  328. this.id = gl.createTexture();
  329. this.target = gl.TEXTURE_2D;
  330. this.version = -1;
  331. this.update(texture);
  332. }
  333. update() {
  334. if (!this.texture.image) {
  335. this.version = this.texture.version;
  336. return;
  337. }
  338. let gl = this.gl;
  339. let texture = this.texture;
  340. if (this.version === texture.version) {
  341. return;
  342. }
  343. this.target = gl.TEXTURE_2D;
  344. gl.bindTexture(this.target, this.id);
  345. let level = 0;
  346. let internalFormat = paramThreeToGL(gl, texture.format);
  347. let width = texture.image.width;
  348. let height = texture.image.height;
  349. let border = 0;
  350. let srcFormat = internalFormat;
  351. let srcType = paramThreeToGL(gl, texture.type);
  352. let data;
  353. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  354. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  355. gl.pixelStorei(gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  356. if (texture instanceof THREE.DataTexture) {
  357. data = texture.image.data;
  358. gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  359. gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  360. gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, paramThreeToGL(gl, texture.magFilter));
  361. gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, paramThreeToGL(gl, texture.minFilter));
  362. gl.texImage2D(this.target, level, internalFormat,
  363. width, height, border, srcFormat, srcType,
  364. data);
  365. } else if ((texture instanceof THREE.CanvasTexture) || (texture instanceof THREE.Texture)) {
  366. data = texture.image;
  367. gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, paramThreeToGL(gl, texture.wrapS));
  368. gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, paramThreeToGL(gl, texture.wrapT));
  369. gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, paramThreeToGL(gl, texture.magFilter));
  370. gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, paramThreeToGL(gl, texture.minFilter));
  371. gl.texImage2D(this.target, level, internalFormat,
  372. internalFormat, srcType, data);
  373. if (texture instanceof THREE.Texture) {gl.generateMipmap(gl.TEXTURE_2D);}
  374. }
  375. gl.bindTexture(this.target, null);
  376. this.version = texture.version;
  377. }
  378. };
  379. class WebGLBuffer {
  380. constructor() {
  381. this.numElements = 0;
  382. this.vao = null;
  383. this.vbos = new Map();
  384. }
  385. };
  386. export class Renderer {
  387. constructor(threeRenderer) {
  388. this.threeRenderer = threeRenderer;
  389. this.gl = this.threeRenderer.getContext();
  390. this.buffers = new Map();
  391. this.shaders = new Map();
  392. this.textures = new Map();
  393. this.glTypeMapping = new Map();
  394. this.glTypeMapping.set(Float32Array, this.gl.FLOAT);
  395. this.glTypeMapping.set(Uint8Array, this.gl.UNSIGNED_BYTE);
  396. this.glTypeMapping.set(Uint16Array, this.gl.UNSIGNED_SHORT);
  397. this.toggle = 0;
  398. }
  399. deleteBuffer(geometry) {
  400. let gl = this.gl;
  401. let webglBuffer = this.buffers.get(geometry);
  402. if (webglBuffer != null) {
  403. for (let attributeName in geometry.attributes) {
  404. gl.deleteBuffer(webglBuffer.vbos.get(attributeName).handle);
  405. }
  406. this.buffers.delete(geometry);
  407. }
  408. }
  409. createBuffer(geometry){
  410. let gl = this.gl;
  411. let webglBuffer = new WebGLBuffer();
  412. webglBuffer.vao = gl.createVertexArray();
  413. webglBuffer.numElements = geometry.attributes.position.count;
  414. gl.bindVertexArray(webglBuffer.vao);
  415. for(let attributeName in geometry.attributes){
  416. let bufferAttribute = geometry.attributes[attributeName];
  417. let vbo = gl.createBuffer();
  418. gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
  419. gl.bufferData(gl.ARRAY_BUFFER, bufferAttribute.array, gl.STATIC_DRAW);
  420. let normalized = bufferAttribute.normalized;
  421. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  422. if(attributeLocations[attributeName] === undefined){
  423. //attributeLocation = attributeLocations["aExtra"];
  424. }else{
  425. let attributeLocation = attributeLocations[attributeName].location;
  426. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  427. gl.enableVertexAttribArray(attributeLocation);
  428. }
  429. webglBuffer.vbos.set(attributeName, {
  430. handle: vbo,
  431. name: attributeName,
  432. count: bufferAttribute.count,
  433. itemSize: bufferAttribute.itemSize,
  434. type: geometry.attributes.position.array.constructor,
  435. version: 0
  436. });
  437. }
  438. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  439. gl.bindVertexArray(null);
  440. let disposeHandler = (event) => {
  441. this.deleteBuffer(geometry);
  442. geometry.removeEventListener("dispose", disposeHandler);
  443. };
  444. geometry.addEventListener("dispose", disposeHandler);
  445. return webglBuffer;
  446. }
  447. updateBuffer(geometry){
  448. let gl = this.gl;
  449. let webglBuffer = this.buffers.get(geometry);
  450. gl.bindVertexArray(webglBuffer.vao);
  451. for(let attributeName in geometry.attributes){
  452. let bufferAttribute = geometry.attributes[attributeName];
  453. let normalized = bufferAttribute.normalized;
  454. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  455. let vbo = null;
  456. if(!webglBuffer.vbos.has(attributeName)){
  457. vbo = gl.createBuffer();
  458. webglBuffer.vbos.set(attributeName, {
  459. handle: vbo,
  460. name: attributeName,
  461. count: bufferAttribute.count,
  462. itemSize: bufferAttribute.itemSize,
  463. type: geometry.attributes.position.array.constructor,
  464. version: bufferAttribute.version
  465. });
  466. }else{
  467. vbo = webglBuffer.vbos.get(attributeName).handle;
  468. webglBuffer.vbos.get(attributeName).version = bufferAttribute.version;
  469. }
  470. gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
  471. gl.bufferData(gl.ARRAY_BUFFER, bufferAttribute.array, gl.STATIC_DRAW);
  472. if(attributeLocations[attributeName] === undefined){
  473. //attributeLocation = attributeLocations["aExtra"];
  474. }else{
  475. let attributeLocation = attributeLocations[attributeName].location;
  476. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  477. gl.enableVertexAttribArray(attributeLocation);
  478. }
  479. }
  480. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  481. gl.bindVertexArray(null);
  482. }
  483. traverse(scene) {
  484. let octrees = [];
  485. let stack = [scene];
  486. while (stack.length > 0) {
  487. let node = stack.pop();
  488. if (node instanceof PointCloudTree) {
  489. octrees.push(node);
  490. continue;
  491. }
  492. let visibleChildren = node.children.filter(c => c.visible);
  493. stack.push(...visibleChildren);
  494. }
  495. let result = {
  496. octrees: octrees
  497. };
  498. return result;
  499. }
  500. renderNodes(octree, nodes, visibilityTextureData, camera, target, shader, params) {
  501. if (exports.measureTimings) performance.mark("renderNodes-start");
  502. let gl = this.gl;
  503. let material = params.material ? params.material : octree.material;
  504. let shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps;
  505. let view = camera.matrixWorldInverse;
  506. if(params.viewOverride){
  507. view = params.viewOverride;
  508. }
  509. let worldView = new THREE.Matrix4();
  510. let mat4holder = new Float32Array(16);
  511. let i = 0;
  512. for (let node of nodes) {
  513. if(exports.debug.allowedNodes !== undefined){
  514. if(!exports.debug.allowedNodes.includes(node.name)){
  515. continue;
  516. }
  517. }
  518. let world = node.sceneNode.matrixWorld;
  519. worldView.multiplyMatrices(view, world);
  520. if (visibilityTextureData) {
  521. let vnStart = visibilityTextureData.offsets.get(node);
  522. shader.setUniform1f("uVNStart", vnStart);
  523. }
  524. let level = node.getLevel();
  525. if(node.debug){
  526. shader.setUniform("uDebug", true);
  527. }else{
  528. shader.setUniform("uDebug", false);
  529. }
  530. // let isLeaf = false;
  531. // if(node instanceof PointCloudOctreeNode){
  532. // isLeaf = Object.keys(node.children).length === 0;
  533. // }else if(node instanceof PointCloudArena4DNode){
  534. // isLeaf = node.geometryNode.isLeaf;
  535. // }
  536. // shader.setUniform("uIsLeafNode", isLeaf);
  537. // let isLeaf = node.children.filter(n => n != null).length === 0;
  538. // if(!isLeaf){
  539. // continue;
  540. // }
  541. // TODO consider passing matrices in an array to avoid uniformMatrix4fv overhead
  542. const lModel = shader.uniformLocations["modelMatrix"];
  543. if (lModel) {
  544. mat4holder.set(world.elements);
  545. gl.uniformMatrix4fv(lModel, false, mat4holder);
  546. }
  547. const lModelView = shader.uniformLocations["modelViewMatrix"];
  548. //mat4holder.set(worldView.elements);
  549. // faster then set in chrome 63
  550. for(let j = 0; j < 16; j++){
  551. mat4holder[j] = worldView.elements[j];
  552. }
  553. gl.uniformMatrix4fv(lModelView, false, mat4holder);
  554. { // Clip Polygons
  555. if(material.clipPolygons && material.clipPolygons.length > 0){
  556. let clipPolygonVCount = [];
  557. let worldViewProjMatrices = [];
  558. for(let clipPolygon of material.clipPolygons){
  559. let view = clipPolygon.viewMatrix;
  560. let proj = clipPolygon.projMatrix;
  561. let worldViewProj = proj.clone().multiply(view).multiply(world);
  562. clipPolygonVCount.push(clipPolygon.markers.length);
  563. worldViewProjMatrices.push(worldViewProj);
  564. }
  565. let flattenedMatrices = [].concat(...worldViewProjMatrices.map(m => m.elements));
  566. let flattenedVertices = new Array(8 * 3 * material.clipPolygons.length);
  567. for(let i = 0; i < material.clipPolygons.length; i++){
  568. let clipPolygon = material.clipPolygons[i];
  569. for(let j = 0; j < clipPolygon.markers.length; j++){
  570. flattenedVertices[i * 24 + (j * 3 + 0)] = clipPolygon.markers[j].position.x;
  571. flattenedVertices[i * 24 + (j * 3 + 1)] = clipPolygon.markers[j].position.y;
  572. flattenedVertices[i * 24 + (j * 3 + 2)] = clipPolygon.markers[j].position.z;
  573. }
  574. }
  575. const lClipPolygonVCount = shader.uniformLocations["uClipPolygonVCount[0]"];
  576. gl.uniform1iv(lClipPolygonVCount, clipPolygonVCount);
  577. const lClipPolygonVP = shader.uniformLocations["uClipPolygonWVP[0]"];
  578. gl.uniformMatrix4fv(lClipPolygonVP, false, flattenedMatrices);
  579. const lClipPolygons = shader.uniformLocations["uClipPolygonVertices[0]"];
  580. gl.uniform3fv(lClipPolygons, flattenedVertices);
  581. }
  582. }
  583. //shader.setUniformMatrix4("modelMatrix", world);
  584. //shader.setUniformMatrix4("modelViewMatrix", worldView);
  585. shader.setUniform1f("uLevel", level);
  586. shader.setUniform1f("uNodeSpacing", node.geometryNode.estimatedSpacing);
  587. shader.setUniform1f("uPCIndex", i);
  588. // uBBSize
  589. if (shadowMaps.length > 0) {
  590. const lShadowMap = shader.uniformLocations["uShadowMap[0]"];
  591. shader.setUniform3f("uShadowColor", material.uniforms.uShadowColor.value);
  592. let bindingStart = 5;
  593. let bindingPoints = new Array(shadowMaps.length).fill(bindingStart).map((a, i) => (a + i));
  594. gl.uniform1iv(lShadowMap, bindingPoints);
  595. for (let i = 0; i < shadowMaps.length; i++) {
  596. let shadowMap = shadowMaps[i];
  597. let bindingPoint = bindingPoints[i];
  598. let glTexture = this.threeRenderer.properties.get(shadowMap.target.texture).__webglTexture;
  599. gl.activeTexture(gl[`TEXTURE${bindingPoint}`]);
  600. gl.bindTexture(gl.TEXTURE_2D, glTexture);
  601. }
  602. {
  603. let worldViewMatrices = shadowMaps
  604. .map(sm => sm.camera.matrixWorldInverse)
  605. .map(view => new THREE.Matrix4().multiplyMatrices(view, world))
  606. let flattenedMatrices = [].concat(...worldViewMatrices.map(c => c.elements));
  607. const lWorldView = shader.uniformLocations["uShadowWorldView[0]"];
  608. gl.uniformMatrix4fv(lWorldView, false, flattenedMatrices);
  609. }
  610. {
  611. let flattenedMatrices = [].concat(...shadowMaps.map(sm => sm.camera.projectionMatrix.elements));
  612. const lProj = shader.uniformLocations["uShadowProj[0]"];
  613. gl.uniformMatrix4fv(lProj, false, flattenedMatrices);
  614. }
  615. }
  616. const geometry = node.geometryNode.geometry;
  617. if(geometry.attributes["gps-time"]){
  618. const bufferAttribute = geometry.attributes["gps-time"];
  619. const attGPS = octree.getAttribute("gps-time");
  620. let initialRange = attGPS.initialRange;
  621. let initialRangeSize = initialRange[1] - initialRange[0];
  622. let globalRange = attGPS.range;
  623. let globalRangeSize = globalRange[1] - globalRange[0];
  624. let scale = initialRangeSize / globalRangeSize;
  625. let offset = -(globalRange[0] - initialRange[0]) / initialRangeSize;
  626. scale = Number.isNaN(scale) ? 1 : scale;
  627. offset = Number.isNaN(offset) ? 0 : offset;
  628. shader.setUniform1f("uGpsScale", scale);
  629. shader.setUniform1f("uGpsOffset", offset);
  630. //shader.setUniform2f("uFilterGPSTimeClipRange", [-Infinity, Infinity]);
  631. let uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value;
  632. // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0]
  633. // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1]
  634. // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]);
  635. let normalizedClipRange = [
  636. (uFilterGPSTimeClipRange[0] - globalRange[0]) / globalRangeSize,
  637. (uFilterGPSTimeClipRange[1] - globalRange[0]) / globalRangeSize,
  638. ];
  639. shader.setUniform2f("uFilterGPSTimeClipRange", normalizedClipRange);
  640. // // ranges in full gps coordinate system
  641. // const globalRange = attGPS.range;
  642. // const bufferRange = bufferAttribute.potree.range;
  643. // // ranges in [0, 1]
  644. // // normalizedGlobalRange = [0, 1]
  645. // // normalizedBufferRange: norm buffer within norm global range e.g. [0.2, 0.8]
  646. // const globalWidth = globalRange[1] - globalRange[0];
  647. // const normalizedBufferRange = [
  648. // (bufferRange[0] - globalRange[0]) / globalWidth,
  649. // (bufferRange[1] - globalRange[0]) / globalWidth,
  650. // ];
  651. // shader.setUniform2f("uNormalizedGpsBufferRange", normalizedBufferRange);
  652. // let uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value;
  653. // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0]
  654. // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1]
  655. // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]);
  656. // shader.setUniform1f("uGpsScale", bufferAttribute.potree.scale);
  657. // shader.setUniform1f("uGpsOffset", bufferAttribute.potree.offset);
  658. }
  659. {
  660. let uFilterReturnNumberRange = material.uniforms.uFilterReturnNumberRange.value;
  661. let uFilterNumberOfReturnsRange = material.uniforms.uFilterNumberOfReturnsRange.value;
  662. let uFilterPointSourceIDClipRange = material.uniforms.uFilterPointSourceIDClipRange.value;
  663. shader.setUniform2f("uFilterReturnNumberRange", uFilterReturnNumberRange);
  664. shader.setUniform2f("uFilterNumberOfReturnsRange", uFilterNumberOfReturnsRange);
  665. shader.setUniform2f("uFilterPointSourceIDClipRange", uFilterPointSourceIDClipRange);
  666. }
  667. let webglBuffer = null;
  668. if(!this.buffers.has(geometry)){
  669. webglBuffer = this.createBuffer(geometry);
  670. this.buffers.set(geometry, webglBuffer);
  671. }else{
  672. webglBuffer = this.buffers.get(geometry);
  673. for(let attributeName in geometry.attributes){
  674. let attribute = geometry.attributes[attributeName];
  675. if(attribute.version > webglBuffer.vbos.get(attributeName).version){
  676. this.updateBuffer(geometry);
  677. }
  678. }
  679. }
  680. gl.bindVertexArray(webglBuffer.vao);
  681. let isExtraAttribute =
  682. attributeLocations[material.activeAttributeName] === undefined
  683. && Object.keys(geometry.attributes).includes(material.activeAttributeName);
  684. if(isExtraAttribute){
  685. const attributeLocation = attributeLocations["aExtra"].location;
  686. for(const attributeName in geometry.attributes){
  687. const bufferAttribute = geometry.attributes[attributeName];
  688. const vbo = webglBuffer.vbos.get(attributeName);
  689. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  690. gl.disableVertexAttribArray(attributeLocation);
  691. }
  692. const attName = material.activeAttributeName;
  693. const bufferAttribute = geometry.attributes[attName];
  694. const vbo = webglBuffer.vbos.get(attName);
  695. if(bufferAttribute !== undefined && vbo !== undefined){
  696. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  697. let normalized = bufferAttribute.normalized;
  698. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  699. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  700. gl.enableVertexAttribArray(attributeLocation);
  701. }
  702. {
  703. const attExtra = octree.pcoGeometry.pointAttributes.attributes
  704. .find(a => a.name === attName);
  705. let range = material.getRange(attName);
  706. if(!range){
  707. range = attExtra.range;
  708. }
  709. if(!range){
  710. range = [0, 1];
  711. }
  712. let initialRange = attExtra.initialRange;
  713. let initialRangeSize = initialRange[1] - initialRange[0];
  714. let globalRange = range;
  715. let globalRangeSize = globalRange[1] - globalRange[0];
  716. let scale = initialRangeSize / globalRangeSize;
  717. let offset = -(globalRange[0] - initialRange[0]) / initialRangeSize;
  718. scale = Number.isNaN(scale) ? 1 : scale;
  719. offset = Number.isNaN(offset) ? 0 : offset;
  720. shader.setUniform1f("uExtraScale", scale);
  721. shader.setUniform1f("uExtraOffset", offset);
  722. }
  723. }else{
  724. for(const attributeName in geometry.attributes){
  725. const bufferAttribute = geometry.attributes[attributeName];
  726. const vbo = webglBuffer.vbos.get(attributeName);
  727. if(attributeLocations[attributeName] !== undefined){
  728. const attributeLocation = attributeLocations[attributeName].location;
  729. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  730. let normalized = bufferAttribute.normalized;
  731. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  732. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  733. gl.enableVertexAttribArray(attributeLocation);
  734. }
  735. }
  736. }
  737. let numPoints = webglBuffer.numElements;
  738. gl.drawArrays(gl.POINTS, 0, numPoints);
  739. i++;
  740. }
  741. gl.bindVertexArray(null);
  742. if (exports.measureTimings) {
  743. performance.mark("renderNodes-end");
  744. performance.measure("render.renderNodes", "renderNodes-start", "renderNodes-end");
  745. }
  746. }
  747. renderOctree(octree, nodes, camera, target, params = {}){
  748. let gl = this.gl;
  749. let material = params.material ? params.material : octree.material;
  750. let shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps;
  751. let view = camera.matrixWorldInverse;
  752. let viewInv = camera.matrixWorld;
  753. if(params.viewOverride){
  754. view = params.viewOverride;
  755. viewInv = view.clone().invert();
  756. }
  757. let proj = camera.projectionMatrix;
  758. let projInv = proj.clone().invert();
  759. //let worldView = new THREE.Matrix4();
  760. let shader = null;
  761. let visibilityTextureData = null;
  762. let currentTextureBindingPoint = 0;
  763. if (material.pointSizeType >= 0) {
  764. if (material.pointSizeType === PointSizeType.ADAPTIVE ||
  765. material.activeAttributeName === "level of detail") {
  766. let vnNodes = (params.vnTextureNodes != null) ? params.vnTextureNodes : nodes;
  767. visibilityTextureData = octree.computeVisibilityTextureData(vnNodes, camera);
  768. const vnt = material.visibleNodesTexture;
  769. const data = vnt.image.data;
  770. data.set(visibilityTextureData.data);
  771. vnt.needsUpdate = true;
  772. }
  773. }
  774. { // UPDATE SHADER AND TEXTURES
  775. if (!this.shaders.has(material)) {
  776. let [vs, fs] = [material.vertexShader, material.fragmentShader];
  777. let shader = new Shader(gl, "pointcloud", vs, fs);
  778. this.shaders.set(material, shader);
  779. }
  780. shader = this.shaders.get(material);
  781. //if(material.needsUpdate){
  782. {
  783. let [vs, fs] = [material.vertexShader, material.fragmentShader];
  784. let numSnapshots = material.snapEnabled ? material.numSnapshots : 0;
  785. let numClipBoxes = (material.clipBoxes && material.clipBoxes.length) ? material.clipBoxes.length : 0;
  786. let numClipSpheres = (params.clipSpheres && params.clipSpheres.length) ? params.clipSpheres.length : 0;
  787. let numClipPolygons = (material.clipPolygons && material.clipPolygons.length) ? material.clipPolygons.length : 0;
  788. let defines = [
  789. `#define num_shadowmaps ${shadowMaps.length}`,
  790. `#define num_snapshots ${numSnapshots}`,
  791. `#define num_clipboxes ${numClipBoxes}`,
  792. `#define num_clipspheres ${numClipSpheres}`,
  793. `#define num_clippolygons ${numClipPolygons}`,
  794. ];
  795. if(octree.pcoGeometry.root.isLoaded()){
  796. let attributes = octree.pcoGeometry.root.geometry.attributes;
  797. if(attributes["gps-time"]){
  798. defines.push("#define clip_gps_enabled");
  799. }
  800. if(attributes["return number"]){
  801. defines.push("#define clip_return_number_enabled");
  802. }
  803. if(attributes["number of returns"]){
  804. defines.push("#define clip_number_of_returns_enabled");
  805. }
  806. if(attributes["source id"] || attributes["point source id"]){
  807. defines.push("#define clip_point_source_id_enabled");
  808. }
  809. }
  810. let definesString = defines.join("\n");
  811. let vsVersionIndex = vs.indexOf("#version ");
  812. let fsVersionIndex = fs.indexOf("#version ");
  813. if(vsVersionIndex >= 0){
  814. vs = vs.replace(/(#version .*)/, `$1\n${definesString}`)
  815. }else{
  816. vs = `${definesString}\n${vs}`;
  817. }
  818. if(fsVersionIndex >= 0){
  819. fs = fs.replace(/(#version .*)/, `$1\n${definesString}`)
  820. }else{
  821. fs = `${definesString}\n${fs}`;
  822. }
  823. shader.update(vs, fs);
  824. material.needsUpdate = false;
  825. }
  826. for (let uniformName of Object.keys(material.uniforms)) {
  827. let uniform = material.uniforms[uniformName];
  828. if (uniform.type == "t") {
  829. let texture = uniform.value;
  830. if (!texture) {
  831. continue;
  832. }
  833. if (!this.textures.has(texture)) {
  834. let webglTexture = new WebGLTexture(gl, texture);
  835. this.textures.set(texture, webglTexture);
  836. }
  837. let webGLTexture = this.textures.get(texture);
  838. webGLTexture.update();
  839. }
  840. }
  841. }
  842. gl.useProgram(shader.program);
  843. let transparent = false;
  844. if(params.transparent !== undefined){
  845. transparent = params.transparent && material.opacity < 1;
  846. }else{
  847. transparent = material.opacity < 1;
  848. }
  849. if (transparent){
  850. gl.enable(gl.BLEND);
  851. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  852. gl.depthMask(false);
  853. gl.disable(gl.DEPTH_TEST);
  854. } else {
  855. gl.disable(gl.BLEND);
  856. gl.depthMask(true);
  857. gl.enable(gl.DEPTH_TEST);
  858. }
  859. if(params.blendFunc !== undefined){
  860. gl.enable(gl.BLEND);
  861. gl.blendFunc(...params.blendFunc);
  862. }
  863. if(params.depthTest !== undefined){
  864. if(params.depthTest === true){
  865. gl.enable(gl.DEPTH_TEST);
  866. }else{
  867. gl.disable(gl.DEPTH_TEST);
  868. }
  869. }
  870. if(params.depthWrite !== undefined){
  871. if(params.depthWrite === true){
  872. gl.depthMask(true);
  873. }else{
  874. gl.depthMask(false);
  875. }
  876. }
  877. { // UPDATE UNIFORMS
  878. shader.setUniformMatrix4("projectionMatrix", proj);
  879. shader.setUniformMatrix4("viewMatrix", view);
  880. shader.setUniformMatrix4("uViewInv", viewInv);
  881. shader.setUniformMatrix4("uProjInv", projInv);
  882. let screenWidth = target ? target.width : material.screenWidth;
  883. let screenHeight = target ? target.height : material.screenHeight;
  884. shader.setUniform1f("uScreenWidth", screenWidth);
  885. shader.setUniform1f("uScreenHeight", screenHeight);
  886. shader.setUniform1f("fov", Math.PI * camera.fov / 180);
  887. shader.setUniform1f("near", camera.near);
  888. shader.setUniform1f("far", camera.far);
  889. if(camera instanceof THREE.OrthographicCamera){
  890. shader.setUniform("uUseOrthographicCamera", true);
  891. shader.setUniform("uOrthoWidth", camera.right - camera.left);
  892. shader.setUniform("uOrthoHeight", camera.top - camera.bottom);
  893. }else{
  894. shader.setUniform("uUseOrthographicCamera", false);
  895. }
  896. if(material.clipBoxes.length + material.clipPolygons.length === 0){
  897. shader.setUniform1i("clipTask", ClipTask.NONE);
  898. }else{
  899. shader.setUniform1i("clipTask", material.clipTask);
  900. }
  901. shader.setUniform1i("clipMethod", material.clipMethod);
  902. if (material.clipBoxes && material.clipBoxes.length > 0) {
  903. //let flattenedMatrices = [].concat(...material.clipBoxes.map(c => c.inverse.elements));
  904. //const lClipBoxes = shader.uniformLocations["clipBoxes[0]"];
  905. //gl.uniformMatrix4fv(lClipBoxes, false, flattenedMatrices);
  906. const lClipBoxes = shader.uniformLocations["clipBoxes[0]"];
  907. gl.uniformMatrix4fv(lClipBoxes, false, material.uniforms.clipBoxes.value);
  908. }
  909. // TODO CLIPSPHERES
  910. if(params.clipSpheres && params.clipSpheres.length > 0){
  911. let clipSpheres = params.clipSpheres;
  912. let matrices = [];
  913. for(let clipSphere of clipSpheres){
  914. //let mScale = new THREE.Matrix4().makeScale(...clipSphere.scale.toArray());
  915. //let mTranslate = new THREE.Matrix4().makeTranslation(...clipSphere.position.toArray());
  916. //let clipToWorld = new THREE.Matrix4().multiplyMatrices(mTranslate, mScale);
  917. let clipToWorld = clipSphere.matrixWorld;
  918. let viewToWorld = camera.matrixWorld
  919. let worldToClip = clipToWorld.clone().invert();
  920. let viewToClip = new THREE.Matrix4().multiplyMatrices(worldToClip, viewToWorld);
  921. matrices.push(viewToClip);
  922. }
  923. let flattenedMatrices = [].concat(...matrices.map(matrix => matrix.elements));
  924. const lClipSpheres = shader.uniformLocations["uClipSpheres[0]"];
  925. gl.uniformMatrix4fv(lClipSpheres, false, flattenedMatrices);
  926. //const lClipSpheres = shader.uniformLocations["uClipSpheres[0]"];
  927. //gl.uniformMatrix4fv(lClipSpheres, false, material.uniforms.clipSpheres.value);
  928. }
  929. shader.setUniform1f("size", material.size);
  930. shader.setUniform1f("maxSize", material.uniforms.maxSize.value);
  931. shader.setUniform1f("minSize", material.uniforms.minSize.value);
  932. // uniform float uPCIndex
  933. shader.setUniform1f("uOctreeSpacing", material.spacing);
  934. shader.setUniform("uOctreeSize", material.uniforms.octreeSize.value);
  935. //uniform vec3 uColor;
  936. shader.setUniform3f("uColor", material.color.toArray());
  937. //uniform float opacity;
  938. shader.setUniform1f("uOpacity", material.opacity);
  939. shader.setUniform2f("elevationRange", material.elevationRange);
  940. shader.setUniform2f("intensityRange", material.intensityRange);
  941. shader.setUniform3f("uIntensity_gbc", [
  942. material.intensityGamma,
  943. material.intensityBrightness,
  944. material.intensityContrast
  945. ]);
  946. shader.setUniform3f("uRGB_gbc", [
  947. material.rgbGamma,
  948. material.rgbBrightness,
  949. material.rgbContrast
  950. ]);
  951. shader.setUniform1f("uTransition", material.transition);
  952. shader.setUniform1f("wRGB", material.weightRGB);
  953. shader.setUniform1f("wIntensity", material.weightIntensity);
  954. shader.setUniform1f("wElevation", material.weightElevation);
  955. shader.setUniform1f("wClassification", material.weightClassification);
  956. shader.setUniform1f("wReturnNumber", material.weightReturnNumber);
  957. shader.setUniform1f("wSourceID", material.weightSourceID);
  958. shader.setUniform("backfaceCulling", material.uniforms.backfaceCulling.value);
  959. let vnWebGLTexture = this.textures.get(material.visibleNodesTexture);
  960. if(vnWebGLTexture){
  961. shader.setUniform1i("visibleNodesTexture", currentTextureBindingPoint);
  962. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  963. gl.bindTexture(vnWebGLTexture.target, vnWebGLTexture.id);
  964. currentTextureBindingPoint++;
  965. }
  966. let gradientTexture = this.textures.get(material.gradientTexture);
  967. shader.setUniform1i("gradient", currentTextureBindingPoint);
  968. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  969. gl.bindTexture(gradientTexture.target, gradientTexture.id);
  970. const repeat = material.elevationGradientRepeat;
  971. if(repeat === ElevationGradientRepeat.REPEAT){
  972. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.REPEAT);
  973. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.REPEAT);
  974. }else if(repeat === ElevationGradientRepeat.MIRRORED_REPEAT){
  975. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT);
  976. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT);
  977. }else{
  978. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  979. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  980. }
  981. currentTextureBindingPoint++;
  982. let classificationTexture = this.textures.get(material.classificationTexture);
  983. shader.setUniform1i("classificationLUT", currentTextureBindingPoint);
  984. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  985. gl.bindTexture(classificationTexture.target, classificationTexture.id);
  986. currentTextureBindingPoint++;
  987. let matcapTexture = this.textures.get(material.matcapTexture);
  988. shader.setUniform1i("matcapTextureUniform", currentTextureBindingPoint);
  989. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  990. gl.bindTexture(matcapTexture.target, matcapTexture.id);
  991. currentTextureBindingPoint++;
  992. if (material.snapEnabled === true) {
  993. {
  994. const lSnapshot = shader.uniformLocations["uSnapshot[0]"];
  995. const lSnapshotDepth = shader.uniformLocations["uSnapshotDepth[0]"];
  996. let bindingStart = currentTextureBindingPoint;
  997. let lSnapshotBindingPoints = new Array(5).fill(bindingStart).map((a, i) => (a + i));
  998. let lSnapshotDepthBindingPoints = new Array(5)
  999. .fill(1 + Math.max(...lSnapshotBindingPoints))
  1000. .map((a, i) => (a + i));
  1001. currentTextureBindingPoint = 1 + Math.max(...lSnapshotDepthBindingPoints);
  1002. gl.uniform1iv(lSnapshot, lSnapshotBindingPoints);
  1003. gl.uniform1iv(lSnapshotDepth, lSnapshotDepthBindingPoints);
  1004. for (let i = 0; i < 5; i++) {
  1005. let texture = material.uniforms[`uSnapshot`].value[i];
  1006. let textureDepth = material.uniforms[`uSnapshotDepth`].value[i];
  1007. if (!texture) {
  1008. break;
  1009. }
  1010. let snapTexture = this.threeRenderer.properties.get(texture).__webglTexture;
  1011. let snapTextureDepth = this.threeRenderer.properties.get(textureDepth).__webglTexture;
  1012. let bindingPoint = lSnapshotBindingPoints[i];
  1013. let depthBindingPoint = lSnapshotDepthBindingPoints[i];
  1014. gl.activeTexture(gl[`TEXTURE${bindingPoint}`]);
  1015. gl.bindTexture(gl.TEXTURE_2D, snapTexture);
  1016. gl.activeTexture(gl[`TEXTURE${depthBindingPoint}`]);
  1017. gl.bindTexture(gl.TEXTURE_2D, snapTextureDepth);
  1018. }
  1019. }
  1020. {
  1021. let flattenedMatrices = [].concat(...material.uniforms.uSnapView.value.map(c => c.elements));
  1022. const lSnapView = shader.uniformLocations["uSnapView[0]"];
  1023. gl.uniformMatrix4fv(lSnapView, false, flattenedMatrices);
  1024. }
  1025. {
  1026. let flattenedMatrices = [].concat(...material.uniforms.uSnapProj.value.map(c => c.elements));
  1027. const lSnapProj = shader.uniformLocations["uSnapProj[0]"];
  1028. gl.uniformMatrix4fv(lSnapProj, false, flattenedMatrices);
  1029. }
  1030. {
  1031. let flattenedMatrices = [].concat(...material.uniforms.uSnapProjInv.value.map(c => c.elements));
  1032. const lSnapProjInv = shader.uniformLocations["uSnapProjInv[0]"];
  1033. gl.uniformMatrix4fv(lSnapProjInv, false, flattenedMatrices);
  1034. }
  1035. {
  1036. let flattenedMatrices = [].concat(...material.uniforms.uSnapViewInv.value.map(c => c.elements));
  1037. const lSnapViewInv = shader.uniformLocations["uSnapViewInv[0]"];
  1038. gl.uniformMatrix4fv(lSnapViewInv, false, flattenedMatrices);
  1039. }
  1040. }
  1041. }
  1042. this.renderNodes(octree, nodes, visibilityTextureData, camera, target, shader, params);
  1043. gl.activeTexture(gl.TEXTURE2);
  1044. gl.bindTexture(gl.TEXTURE_2D, null);
  1045. gl.activeTexture(gl.TEXTURE0);
  1046. }
  1047. render(scene, camera, target = null, params = {}) {
  1048. const gl = this.gl;
  1049. // PREPARE
  1050. if (target != null) {
  1051. this.threeRenderer.setRenderTarget(target);
  1052. }
  1053. //camera.updateProjectionMatrix();
  1054. // camera.matrixWorldInverse.invert(camera.matrixWorld);
  1055. const traversalResult = this.traverse(scene);
  1056. // RENDER
  1057. for (const octree of traversalResult.octrees) {
  1058. let nodes = octree.visibleNodes;
  1059. this.renderOctree(octree, nodes, camera, target, params);
  1060. }
  1061. // CLEANUP
  1062. gl.activeTexture(gl.TEXTURE1);
  1063. gl.bindTexture(gl.TEXTURE_2D, null);
  1064. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  1065. gl.bindVertexArray(null);
  1066. this.threeRenderer.resetState();
  1067. }
  1068. };