PointCloudOctree.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  1. import * as THREE from "../libs/three.js/build/three.module.js";
  2. import {PointCloudTree, PointCloudTreeNode} from "./PointCloudTree.js";
  3. import {PointCloudOctreeGeometryNode} from "./PointCloudOctreeGeometry.js";
  4. import {Utils} from "./utils.js";
  5. import {PointCloudMaterial} from "./materials/PointCloudMaterial.js";
  6. //见ExtendPointCloudOctree
  7. export class PointCloudOctreeNode extends PointCloudTreeNode {
  8. constructor () {
  9. super();
  10. //this.children = {};
  11. this.children = [];
  12. this.sceneNode = null;
  13. this.octree = null;
  14. }
  15. getNumPoints () {
  16. return this.geometryNode.numPoints;
  17. }
  18. isLoaded () {
  19. return true;
  20. }
  21. isTreeNode () {
  22. return true;
  23. }
  24. isGeometryNode () {
  25. return false;
  26. }
  27. getLevel () {
  28. return this.geometryNode.level;
  29. }
  30. getBoundingSphere () {
  31. return this.geometryNode.boundingSphere;
  32. }
  33. getBoundingBox () {
  34. return this.geometryNode.boundingBox;
  35. }
  36. getChildren () {
  37. let children = [];
  38. for (let i = 0; i < 8; i++) {
  39. if (this.children[i]) {
  40. children.push(this.children[i]);
  41. }
  42. }
  43. return children;
  44. }
  45. getPointsInBox(boxNode){
  46. if(!this.sceneNode){
  47. return null;
  48. }
  49. let buffer = this.geometryNode.buffer;
  50. let posOffset = buffer.offset("position");
  51. let stride = buffer.stride;
  52. let view = new DataView(buffer.data);
  53. let worldToBox = boxNode.matrixWorld.clone().invert();
  54. let objectToBox = new THREE.Matrix4().multiplyMatrices(worldToBox, this.sceneNode.matrixWorld);
  55. let inBox = [];
  56. let pos = new THREE.Vector4();
  57. for(let i = 0; i < buffer.numElements; i++){
  58. let x = view.getFloat32(i * stride + posOffset + 0, true);
  59. let y = view.getFloat32(i * stride + posOffset + 4, true);
  60. let z = view.getFloat32(i * stride + posOffset + 8, true);
  61. pos.set(x, y, z, 1);
  62. pos.applyMatrix4(objectToBox);
  63. if(-0.5 < pos.x && pos.x < 0.5){
  64. if(-0.5 < pos.y && pos.y < 0.5){
  65. if(-0.5 < pos.z && pos.z < 0.5){
  66. pos.set(x, y, z, 1).applyMatrix4(this.sceneNode.matrixWorld);
  67. inBox.push(new THREE.Vector3(pos.x, pos.y, pos.z));
  68. }
  69. }
  70. }
  71. }
  72. return inBox;
  73. }
  74. get name () {
  75. return this.geometryNode.name;
  76. }
  77. };
  78. export class PointCloudOctree extends PointCloudTree {//base
  79. constructor (geometry, material) {
  80. super();
  81. this.pointBudget = Infinity; //一直是这个值
  82. this.pcoGeometry = geometry;
  83. this.boundingBox = this.pcoGeometry.boundingBox;
  84. this.boundingSphere = this.boundingBox.getBoundingSphere(new THREE.Sphere());
  85. this.material = material || new PointCloudMaterial();
  86. this.visiblePointsTarget = 2 * 1000 * 1000;
  87. this.minimumNodePixelSize = 150;
  88. this.level = 0;
  89. this.position.copy(geometry.offset);
  90. this.updateMatrix();
  91. {
  92. let priorityQueue = ["rgba", "rgb", "intensity", "classification"];
  93. let selected = "rgba";
  94. for(let attributeName of priorityQueue){
  95. let attribute = this.pcoGeometry.pointAttributes.attributes.find(a => a.name === attributeName);
  96. if(!attribute){
  97. continue;
  98. }
  99. let min = attribute.range[0].constructor.name === "Array" ? attribute.range[0] : [attribute.range[0]];
  100. let max = attribute.range[1].constructor.name === "Array" ? attribute.range[1] : [attribute.range[1]];
  101. let range_min = new THREE.Vector3(...min);
  102. let range_max = new THREE.Vector3(...max);
  103. let range = range_min.distanceTo(range_max);
  104. if(range === 0){
  105. continue;
  106. }
  107. selected = attributeName;
  108. break;
  109. }
  110. this.material.activeAttributeName = selected;
  111. }
  112. this.showBoundingBox = false;
  113. this.boundingBoxNodes = [];
  114. this.loadQueue = [];
  115. this.visibleBounds = new THREE.Box3();
  116. this.visibleNodes = [];
  117. this.visibleGeometry = [];
  118. this.generateDEM = false;
  119. this.profileRequests = [];
  120. this.name = '';
  121. this._visible = true;
  122. {
  123. let box = [this.pcoGeometry.tightBoundingBox, this.getBoundingBoxWorld()]
  124. .find(v => v !== undefined);
  125. this.updateMatrixWorld(true);
  126. box = Utils.computeTransformedBoundingBox(box, this.matrixWorld);
  127. let bMin = box.min.z;
  128. let bMax = box.max.z;
  129. this.material.heightMin = bMin;
  130. this.material.heightMax = bMax;
  131. }
  132. // TODO read projection from file instead
  133. this.projection = geometry.projection;
  134. this.fallbackProjection = geometry.fallbackProjection;
  135. this.root = this.pcoGeometry.root;
  136. }
  137. setName (name) {
  138. if (this.name !== name) {
  139. this.name = name;
  140. this.dispatchEvent({type: 'name_changed', name: name, pointcloud: this});
  141. }
  142. }
  143. getName () {
  144. return this.name;
  145. }
  146. getAttribute(name){
  147. const attribute = this.pcoGeometry.pointAttributes.attributes.find(a => a.name === name);
  148. if(attribute){
  149. return attribute;
  150. }else{
  151. return null;
  152. }
  153. }
  154. getAttributes(){
  155. return this.pcoGeometry.pointAttributes;
  156. }
  157. toTreeNode (geometryNode, parent) {
  158. let node = new PointCloudOctreeNode();
  159. let sceneNode = new THREE.Points(geometryNode.geometry, this.material);
  160. sceneNode.name = geometryNode.name;
  161. sceneNode.position.copy(geometryNode.boundingBox.min);
  162. sceneNode.frustumCulled = false;
  163. sceneNode.onBeforeRender = (_this, scene, camera, geometry, material, group) => {
  164. if (material.program) {
  165. _this.getContext().useProgram(material.program.program);
  166. if (material.program.getUniforms().map.level) {
  167. let level = geometryNode.getLevel();
  168. material.uniforms.level.value = level;
  169. material.program.getUniforms().map.level.setValue(_this.getContext(), level);
  170. }
  171. if (this.visibleNodeTextureOffsets && material.program.getUniforms().map.vnStart) {
  172. let vnStart = this.visibleNodeTextureOffsets.get(node);
  173. material.uniforms.vnStart.value = vnStart;
  174. material.program.getUniforms().map.vnStart.setValue(_this.getContext(), vnStart);
  175. }
  176. if (material.program.getUniforms().map.pcIndex) {
  177. let i = node.pcIndex ? node.pcIndex : this.visibleNodes.indexOf(node);
  178. material.uniforms.pcIndex.value = i;
  179. material.program.getUniforms().map.pcIndex.setValue(_this.getContext(), i);
  180. }
  181. }
  182. };
  183. // { // DEBUG
  184. // let sg = new THREE.SphereGeometry(1, 16, 16);
  185. // let sm = new THREE.MeshNormalMaterial();
  186. // let s = new THREE.Mesh(sg, sm);
  187. // s.scale.set(5, 5, 5);
  188. // s.position.copy(geometryNode.mean)
  189. // .add(this.position)
  190. // .add(geometryNode.boundingBox.min);
  191. //
  192. // viewer.scene.scene.add(s);
  193. // }
  194. node.geometryNode = geometryNode;
  195. node.sceneNode = sceneNode;
  196. node.pointcloud = this;
  197. node.children = [];
  198. //for (let key in geometryNode.children) {
  199. // node.children[key] = geometryNode.children[key];
  200. //}
  201. for(let i = 0; i < 8; i++){
  202. node.children[i] = geometryNode.children[i];
  203. }
  204. if (!parent) {
  205. this.root = node;
  206. this.add(sceneNode);
  207. } else {
  208. let childIndex = parseInt(geometryNode.name[geometryNode.name.length - 1]);
  209. parent.sceneNode.add(sceneNode);
  210. parent.children[childIndex] = node;
  211. }
  212. let disposeListener = function () {
  213. let childIndex = parseInt(geometryNode.name[geometryNode.name.length - 1]);
  214. parent.sceneNode.remove(node.sceneNode);
  215. parent.children[childIndex] = geometryNode;
  216. };
  217. geometryNode.oneTimeDisposeHandlers.push(disposeListener);
  218. return node;
  219. }
  220. updateVisibleBounds () {
  221. let leafNodes = [];
  222. for (let i = 0; i < this.visibleNodes.length; i++) {
  223. let node = this.visibleNodes[i];
  224. let isLeaf = true;
  225. for (let j = 0; j < node.children.length; j++) {
  226. let child = node.children[j];
  227. if (child instanceof PointCloudOctreeNode) {
  228. isLeaf = isLeaf && !child.sceneNode.visible;
  229. } else if (child instanceof PointCloudOctreeGeometryNode) {
  230. isLeaf = true;
  231. }
  232. }
  233. if (isLeaf) {
  234. leafNodes.push(node);
  235. }
  236. }
  237. this.visibleBounds.min = new THREE.Vector3(Infinity, Infinity, Infinity);
  238. this.visibleBounds.max = new THREE.Vector3(-Infinity, -Infinity, -Infinity);
  239. for (let i = 0; i < leafNodes.length; i++) {
  240. let node = leafNodes[i];
  241. this.visibleBounds.expandByPoint(node.getBoundingBox().min);
  242. this.visibleBounds.expandByPoint(node.getBoundingBox().max);
  243. }
  244. }
  245. updateMaterial (material, visibleNodes, camera, renderer) {
  246. material.fov = camera.fov * (Math.PI / 180);
  247. material.screenWidth = renderer.domElement.clientWidth;
  248. material.screenHeight = renderer.domElement.clientHeight;
  249. material.spacing = this.pcoGeometry.spacing; // * Math.max(this.scale.x, this.scale.y, this.scale.z);
  250. material.near = camera.near;
  251. material.far = camera.far;
  252. material.uniforms.octreeSize.value = this.pcoGeometry.boundingBox.getSize(new THREE.Vector3()).x;
  253. }
  254. computeVisibilityTextureData(nodes, camera){
  255. if(Potree.measureTimings) performance.mark("computeVisibilityTextureData-start");
  256. let data = new Uint8Array(nodes.length * 4);
  257. let visibleNodeTextureOffsets = new Map();
  258. // copy array
  259. nodes = nodes.slice();
  260. // sort by level and index, e.g. r, r0, r3, r4, r01, r07, r30, ...
  261. let sort = function (a, b) {
  262. let na = a.geometryNode.name;
  263. let nb = b.geometryNode.name;
  264. if (na.length !== nb.length) return na.length - nb.length;
  265. if (na < nb) return -1;
  266. if (na > nb) return 1;
  267. return 0;
  268. };
  269. nodes.sort(sort);
  270. let worldDir = new THREE.Vector3();
  271. let nodeMap = new Map();
  272. let offsetsToChild = new Array(nodes.length).fill(Infinity);
  273. for(let i = 0; i < nodes.length; i++){
  274. let node = nodes[i];
  275. nodeMap.set(node.name, node);
  276. visibleNodeTextureOffsets.set(node, i);
  277. if(i > 0){
  278. let index = parseInt(node.name.slice(-1));
  279. let parentName = node.name.slice(0, -1);
  280. let parent = nodeMap.get(parentName);
  281. let parentOffset = visibleNodeTextureOffsets.get(parent);
  282. let parentOffsetToChild = (i - parentOffset);
  283. offsetsToChild[parentOffset] = Math.min(offsetsToChild[parentOffset], parentOffsetToChild);
  284. data[parentOffset * 4 + 0] = data[parentOffset * 4 + 0] | (1 << index);
  285. data[parentOffset * 4 + 1] = (offsetsToChild[parentOffset] >> 8);
  286. data[parentOffset * 4 + 2] = (offsetsToChild[parentOffset] % 256);
  287. }
  288. let density = node.geometryNode.density;
  289. if(typeof density === "number"){
  290. let lodOffset = Math.log2(density) / 2 - 1.5;
  291. let offsetUint8 = (lodOffset + 10) * 10;
  292. data[i * 4 + 3] = offsetUint8;
  293. }else{
  294. data[i * 4 + 3] = 100;
  295. }
  296. }
  297. if(Potree.measureTimings){
  298. performance.mark("computeVisibilityTextureData-end");
  299. performance.measure("render.computeVisibilityTextureData", "computeVisibilityTextureData-start", "computeVisibilityTextureData-end");
  300. }
  301. return {
  302. data: data,
  303. offsets: visibleNodeTextureOffsets
  304. };
  305. }
  306. nodeIntersectsProfile (node, profile) {
  307. let bbWorld = node.boundingBox.clone().applyMatrix4(this.matrixWorld);
  308. let bsWorld = bbWorld.getBoundingSphere(new THREE.Sphere());
  309. let intersects = false;
  310. for (let i = 0; i < profile.points.length - 1; i++) {
  311. let start = new THREE.Vector3(profile.points[i + 0].x, profile.points[i + 0].y, bsWorld.center.z);
  312. let end = new THREE.Vector3(profile.points[i + 1].x, profile.points[i + 1].y, bsWorld.center.z);
  313. let closest = new THREE.Line3(start, end).closestPointToPoint(bsWorld.center, true, new THREE.Vector3());
  314. let distance = closest.distanceTo(bsWorld.center);
  315. intersects = intersects || (distance < (bsWorld.radius + profile.width));
  316. }
  317. //console.log(`${node.name}: ${intersects}`);
  318. return intersects;
  319. }
  320. deepestNodeAt(position){
  321. const toObjectSpace = this.matrixWorld.clone().invert();
  322. const objPos = position.clone().applyMatrix4(toObjectSpace);
  323. let current = this.root;
  324. while(true){
  325. let containingChild = null;
  326. for(const child of current.children){
  327. if(child !== undefined){
  328. if(child.getBoundingBox().containsPoint(objPos)){
  329. containingChild = child;
  330. }
  331. }
  332. }
  333. if(containingChild !== null && containingChild instanceof PointCloudOctreeNode){
  334. current = containingChild;
  335. }else{
  336. break;
  337. }
  338. }
  339. const deepest = current;
  340. return deepest;
  341. }
  342. nodesOnRay (nodes, ray) {
  343. let nodesOnRay = [];
  344. let _ray = ray.clone();
  345. for (let i = 0; i < nodes.length; i++) {
  346. let node = nodes[i];
  347. let sphere = node.getBoundingSphere().clone().applyMatrix4(this.matrixWorld);
  348. if (_ray.intersectsSphere(sphere)) {
  349. nodesOnRay.push(node);
  350. }
  351. }
  352. return nodesOnRay;
  353. }
  354. updateMatrixWorld (force) {
  355. if (this.matrixAutoUpdate === true) this.updateMatrix();
  356. if (this.matrixWorldNeedsUpdate === true || force === true) {
  357. if (!this.parent) {
  358. this.matrixWorld.copy(this.matrix);
  359. } else {
  360. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  361. }
  362. this.matrixWorldNeedsUpdate = false;
  363. force = true;
  364. }
  365. }
  366. hideDescendants (object) {
  367. let stack = [];
  368. for (let i = 0; i < object.children.length; i++) {
  369. let child = object.children[i];
  370. if (child.visible) {
  371. stack.push(child);
  372. }
  373. }
  374. while (stack.length > 0) {
  375. let object = stack.shift();
  376. object.visible = false;
  377. for (let i = 0; i < object.children.length; i++) {
  378. let child = object.children[i];
  379. if (child.visible) {
  380. stack.push(child);
  381. }
  382. }
  383. }
  384. }
  385. moveToOrigin () {
  386. this.position.set(0, 0, 0);
  387. this.updateMatrixWorld(true);
  388. let box = this.boundingBox;
  389. let transform = this.matrixWorld;
  390. let tBox = Utils.computeTransformedBoundingBox(box, transform);
  391. this.position.set(0, 0, 0).sub(tBox.getCenter(new THREE.Vector3()));
  392. };
  393. moveToGroundPlane () {
  394. this.updateMatrixWorld(true);
  395. let box = this.boundingBox;
  396. let transform = this.matrixWorld;
  397. let tBox = Utils.computeTransformedBoundingBox(box, transform);
  398. this.position.y += -tBox.min.y;
  399. };
  400. getBoundingBoxWorld () {
  401. this.updateMatrixWorld(true);
  402. let box = this.boundingBox;
  403. let transform = this.matrixWorld;
  404. let tBox = Utils.computeTransformedBoundingBox(box, transform);
  405. return tBox;
  406. };
  407. /**
  408. * returns points inside the profile points
  409. *
  410. * maxDepth: search points up to the given octree depth
  411. *
  412. *
  413. * The return value is an array with all segments of the profile path
  414. * let segment = {
  415. * start: THREE.Vector3,
  416. * end: THREE.Vector3,
  417. * points: {}
  418. * project: function()
  419. * };
  420. *
  421. * The project() function inside each segment can be used to transform
  422. * that segments point coordinates to line up along the x-axis.
  423. *
  424. *
  425. */
  426. getPointsInProfile (profile, maxDepth, callback) {
  427. if (callback) {
  428. let request = new Potree.ProfileRequest(this, profile, maxDepth, callback);
  429. this.profileRequests.push(request);
  430. return request;
  431. }
  432. let points = {
  433. segments: [],
  434. boundingBox: new THREE.Box3(),
  435. projectedBoundingBox: new THREE.Box2()
  436. };
  437. // evaluate segments
  438. for (let i = 0; i < profile.points.length - 1; i++) {
  439. let start = profile.points[i];
  440. let end = profile.points[i + 1];
  441. let ps = this.getProfile(start, end, profile.width, maxDepth);
  442. let segment = {
  443. start: start,
  444. end: end,
  445. points: ps,
  446. project: null
  447. };
  448. points.segments.push(segment);
  449. points.boundingBox.expandByPoint(ps.boundingBox.min);
  450. points.boundingBox.expandByPoint(ps.boundingBox.max);
  451. }
  452. // add projection functions to the segments
  453. let mileage = new THREE.Vector3();
  454. for (let i = 0; i < points.segments.length; i++) {
  455. let segment = points.segments[i];
  456. let start = segment.start;
  457. let end = segment.end;
  458. let project = (function (_start, _end, _mileage, _boundingBox) {
  459. let start = _start;
  460. let end = _end;
  461. let mileage = _mileage;
  462. let boundingBox = _boundingBox;
  463. let xAxis = new THREE.Vector3(1, 0, 0);
  464. let dir = new THREE.Vector3().subVectors(end, start);
  465. dir.y = 0;
  466. dir.normalize();
  467. let alpha = Math.acos(xAxis.dot(dir));
  468. if (dir.z > 0) {
  469. alpha = -alpha;
  470. }
  471. return function (position) {
  472. let toOrigin = new THREE.Matrix4().makeTranslation(-start.x, -boundingBox.min.y, -start.z);
  473. let alignWithX = new THREE.Matrix4().makeRotationY(-alpha);
  474. let applyMileage = new THREE.Matrix4().makeTranslation(mileage.x, 0, 0);
  475. let pos = position.clone();
  476. pos.applyMatrix4(toOrigin);
  477. pos.applyMatrix4(alignWithX);
  478. pos.applyMatrix4(applyMileage);
  479. return pos;
  480. };
  481. }(start, end, mileage.clone(), points.boundingBox.clone()));
  482. segment.project = project;
  483. mileage.x += new THREE.Vector3(start.x, 0, start.z).distanceTo(new THREE.Vector3(end.x, 0, end.z));
  484. mileage.y += end.y - start.y;
  485. }
  486. points.projectedBoundingBox.min.x = 0;
  487. points.projectedBoundingBox.min.y = points.boundingBox.min.y;
  488. points.projectedBoundingBox.max.x = mileage.x;
  489. points.projectedBoundingBox.max.y = points.boundingBox.max.y;
  490. return points;
  491. }
  492. /**
  493. * returns points inside the given profile bounds.
  494. *
  495. * start:
  496. * end:
  497. * width:
  498. * depth: search points up to the given octree depth
  499. * callback: if specified, points are loaded before searching
  500. *
  501. *
  502. */
  503. getProfile (start, end, width, depth, callback) {
  504. let request = new Potree.ProfileRequest(start, end, width, depth, callback);
  505. this.profileRequests.push(request);
  506. };
  507. getVisibleExtent () {
  508. return this.visibleBounds.applyMatrix4(this.matrixWorld);
  509. };
  510. intersectsPoint(position){
  511. let rootAvailable = this.pcoGeometry.root && this.pcoGeometry.root.geometry;
  512. if(!rootAvailable){
  513. return false;
  514. }
  515. if(typeof this.signedDistanceField === "undefined"){
  516. const resolution = 32;
  517. const field = new Float32Array(resolution ** 3).fill(Infinity);
  518. const positions = this.pcoGeometry.root.geometry.attributes.position;
  519. const boundingBox = this.boundingBox;
  520. const n = positions.count;
  521. for(let i = 0; i < n; i = i + 3){
  522. const x = positions.array[3 * i + 0];
  523. const y = positions.array[3 * i + 1];
  524. const z = positions.array[3 * i + 2];
  525. const ix = parseInt(Math.min(resolution * (x / boundingBox.max.x), resolution - 1));
  526. const iy = parseInt(Math.min(resolution * (y / boundingBox.max.y), resolution - 1));
  527. const iz = parseInt(Math.min(resolution * (z / boundingBox.max.z), resolution - 1));
  528. const index = ix + iy * resolution + iz * resolution * resolution;
  529. field[index] = 0;
  530. }
  531. const sdf = {
  532. resolution: resolution,
  533. field: field,
  534. };
  535. this.signedDistanceField = sdf;
  536. }
  537. {
  538. const sdf = this.signedDistanceField;
  539. const boundingBox = this.boundingBox;
  540. const toObjectSpace = this.matrixWorld.clone().invert();
  541. const objPos = position.clone().applyMatrix4(toObjectSpace);
  542. const resolution = sdf.resolution;
  543. const ix = parseInt(resolution * (objPos.x / boundingBox.max.x));
  544. const iy = parseInt(resolution * (objPos.y / boundingBox.max.y));
  545. const iz = parseInt(resolution * (objPos.z / boundingBox.max.z));
  546. if(ix < 0 || iy < 0 || iz < 0){
  547. return false;
  548. }
  549. if(ix >= resolution || iy >= resolution || iz >= resolution){
  550. return false;
  551. }
  552. const index = ix + iy * resolution + iz * resolution * resolution;
  553. const value = sdf.field[index];
  554. if(value === 0){
  555. return true;
  556. }
  557. }
  558. return false;
  559. }
  560. /**
  561. *
  562. *
  563. *
  564. * params.pickWindowSize: Look for points inside a pixel window of this size.
  565. * Use odd values: 1, 3, 5, ...
  566. *
  567. *
  568. * TODO: only draw pixels that are actually read with readPixels().
  569. *
  570. */
  571. pick(viewer, camera, ray, params = {}){
  572. let renderer = viewer.renderer;
  573. let pRenderer = viewer.pRenderer;
  574. performance.mark("pick-start");
  575. let getVal = (a, b) => a !== undefined ? a : b;
  576. let pickWindowSize = getVal(params.pickWindowSize, 65);
  577. let pickOutsideClipRegion = getVal(params.pickOutsideClipRegion, false);
  578. let size = renderer.getSize(new THREE.Vector2());
  579. let width = Math.ceil(getVal(params.width, size.width));
  580. let height = Math.ceil(getVal(params.height, size.height));
  581. let pointSizeType = getVal(params.pointSizeType, this.material.pointSizeType);
  582. let pointSize = getVal(params.pointSize, this.material.size);
  583. let nodes = this.nodesOnRay(this.visibleNodes, ray);
  584. if (nodes.length === 0) {
  585. return null;
  586. }
  587. if (!this.pickState) {
  588. let scene = new THREE.Scene();
  589. let material = new Potree.PointCloudMaterial();
  590. material.activeAttributeName = "indices";
  591. let renderTarget = new THREE.WebGLRenderTarget(
  592. 1, 1,
  593. { minFilter: THREE.LinearFilter,
  594. magFilter: THREE.NearestFilter,
  595. format: THREE.RGBAFormat }
  596. );
  597. this.pickState = {
  598. renderTarget: renderTarget,
  599. material: material,
  600. scene: scene
  601. };
  602. };
  603. let pickState = this.pickState;
  604. let pickMaterial = pickState.material;
  605. { // update pick material
  606. pickMaterial.pointSizeType = pointSizeType;
  607. //pickMaterial.shape = this.material.shape;
  608. pickMaterial.shape = Potree.PointShape.PARABOLOID;
  609. pickMaterial.uniforms.uFilterReturnNumberRange.value = this.material.uniforms.uFilterReturnNumberRange.value;
  610. pickMaterial.uniforms.uFilterNumberOfReturnsRange.value = this.material.uniforms.uFilterNumberOfReturnsRange.value;
  611. pickMaterial.uniforms.uFilterGPSTimeClipRange.value = this.material.uniforms.uFilterGPSTimeClipRange.value;
  612. pickMaterial.uniforms.uFilterPointSourceIDClipRange.value = this.material.uniforms.uFilterPointSourceIDClipRange.value;
  613. pickMaterial.activeAttributeName = "indices";
  614. pickMaterial.size = pointSize;
  615. pickMaterial.uniforms.minSize.value = this.material.uniforms.minSize.value;
  616. pickMaterial.uniforms.maxSize.value = this.material.uniforms.maxSize.value;
  617. pickMaterial.classification = this.material.classification;
  618. pickMaterial.recomputeClassification();
  619. if(params.pickClipped){
  620. pickMaterial.clipBoxes = this.material.clipBoxes;
  621. pickMaterial.uniforms.clipBoxes = this.material.uniforms.clipBoxes;
  622. if(this.material.clipTask === Potree.ClipTask.HIGHLIGHT){
  623. pickMaterial.clipTask = Potree.ClipTask.NONE;
  624. }else{
  625. pickMaterial.clipTask = this.material.clipTask;
  626. }
  627. pickMaterial.clipMethod = this.material.clipMethod;
  628. }else{
  629. pickMaterial.clipBoxes = [];
  630. }
  631. this.updateMaterial(pickMaterial, nodes, camera, renderer);
  632. }
  633. pickState.renderTarget.setSize(width, height);
  634. let pixelPos = new THREE.Vector2(params.x, params.y);
  635. let gl = renderer.getContext();
  636. gl.enable(gl.SCISSOR_TEST);
  637. gl.scissor(
  638. parseInt(pixelPos.x - (pickWindowSize - 1) / 2),
  639. parseInt(pixelPos.y - (pickWindowSize - 1) / 2),
  640. parseInt(pickWindowSize), parseInt(pickWindowSize));
  641. renderer.state.buffers.depth.setTest(pickMaterial.depthTest);
  642. renderer.state.buffers.depth.setMask(pickMaterial.depthWrite);
  643. renderer.state.setBlending(THREE.NoBlending);
  644. { // RENDER
  645. renderer.setRenderTarget(pickState.renderTarget);
  646. gl.clearColor(0, 0, 0, 0);
  647. renderer.clear(true, true, true);
  648. let tmp = this.material;
  649. this.material = pickMaterial;
  650. pRenderer.renderOctree(this, nodes, camera, pickState.renderTarget);
  651. this.material = tmp;
  652. }
  653. let clamp = (number, min, max) => Math.min(Math.max(min, number), max);
  654. let x = parseInt(clamp(pixelPos.x - (pickWindowSize - 1) / 2, 0, width));
  655. let y = parseInt(clamp(pixelPos.y - (pickWindowSize - 1) / 2, 0, height));
  656. let w = parseInt(Math.min(x + pickWindowSize, width) - x);
  657. let h = parseInt(Math.min(y + pickWindowSize, height) - y);
  658. let pixelCount = w * h;
  659. let buffer = new Uint8Array(4 * pixelCount);
  660. gl.readPixels(x, y, pickWindowSize, pickWindowSize, gl.RGBA, gl.UNSIGNED_BYTE, buffer);
  661. renderer.setRenderTarget(null);
  662. renderer.state.reset();
  663. renderer.setScissorTest(false);
  664. gl.disable(gl.SCISSOR_TEST);
  665. let pixels = buffer;
  666. let ibuffer = new Uint32Array(buffer.buffer);
  667. // find closest hit inside pixelWindow boundaries
  668. let min = Number.MAX_VALUE;
  669. let hits = [];
  670. for (let u = 0; u < pickWindowSize; u++) {
  671. for (let v = 0; v < pickWindowSize; v++) {
  672. let offset = (u + v * pickWindowSize);
  673. let distance = Math.pow(u - (pickWindowSize - 1) / 2, 2) + Math.pow(v - (pickWindowSize - 1) / 2, 2);
  674. let pcIndex = pixels[4 * offset + 3];
  675. pixels[4 * offset + 3] = 0;
  676. let pIndex = ibuffer[offset];
  677. if(!(pcIndex === 0 && pIndex === 0) && (pcIndex !== undefined) && (pIndex !== undefined)){
  678. let hit = {
  679. pIndex: pIndex,
  680. pcIndex: pcIndex,
  681. distanceToCenter: distance
  682. };
  683. if(params.all){
  684. hits.push(hit);
  685. }else{
  686. if(hits.length > 0){
  687. if(distance < hits[0].distanceToCenter){
  688. hits[0] = hit;
  689. }
  690. }else{
  691. hits.push(hit);
  692. }
  693. }
  694. }
  695. }
  696. }
  697. // { // DEBUG: show panel with pick image
  698. // let img = Utils.pixelsArrayToImage(buffer, w, h);
  699. // let screenshot = img.src;
  700. // if(!this.debugDIV){
  701. // this.debugDIV = $(`
  702. // <div id="pickDebug"
  703. // style="position: absolute;
  704. // right: 400px; width: 300px;
  705. // bottom: 44px; width: 300px;
  706. // z-index: 1000;
  707. // "></div>`);
  708. // $(document.body).append(this.debugDIV);
  709. // }
  710. // this.debugDIV.empty();
  711. // this.debugDIV.append($(`<img src="${screenshot}"
  712. // style="transform: scaleY(-1); width: 300px"/>`));
  713. // //$(this.debugWindow.document).append($(`<img src="${screenshot}"/>`));
  714. // //this.debugWindow.document.write('<img src="'+screenshot+'"/>');
  715. // }
  716. for(let hit of hits){
  717. let point = {};
  718. if (!nodes[hit.pcIndex]) {
  719. return null;
  720. }
  721. let node = nodes[hit.pcIndex];
  722. let pc = node.sceneNode;
  723. let geometry = node.geometryNode.geometry;
  724. for(let attributeName in geometry.attributes){
  725. let attribute = geometry.attributes[attributeName];
  726. if (attributeName === 'position') {
  727. let x = attribute.array[3 * hit.pIndex + 0];
  728. let y = attribute.array[3 * hit.pIndex + 1];
  729. let z = attribute.array[3 * hit.pIndex + 2];
  730. let position = new THREE.Vector3(x, y, z);
  731. position.applyMatrix4(pc.matrixWorld);
  732. point[attributeName] = position;
  733. } else if (attributeName === 'indices') {
  734. } else {
  735. let values = attribute.array.slice(attribute.itemSize * hit.pIndex, attribute.itemSize * (hit.pIndex + 1)) ;
  736. if(attribute.potree){
  737. const {scale, offset} = attribute.potree;
  738. values = values.map(v => v / scale + offset);
  739. }
  740. point[attributeName] = values;
  741. //debugger;
  742. //if (values.itemSize === 1) {
  743. // point[attribute.name] = values.array[hit.pIndex];
  744. //} else {
  745. // let value = [];
  746. // for (let j = 0; j < values.itemSize; j++) {
  747. // value.push(values.array[values.itemSize * hit.pIndex + j]);
  748. // }
  749. // point[attribute.name] = value;
  750. //}
  751. }
  752. }
  753. hit.point = point;
  754. }
  755. performance.mark("pick-end");
  756. performance.measure("pick", "pick-start", "pick-end");
  757. if(params.all){
  758. return hits.map(hit => hit.point);
  759. }else{
  760. if(hits.length === 0){
  761. return null;
  762. }else{
  763. return hits[0].point;
  764. //let sorted = hits.sort( (a, b) => a.distanceToCenter - b.distanceToCenter);
  765. //return sorted[0].point;
  766. }
  767. }
  768. };
  769. * getFittedBoxGen(boxNode){
  770. let start = performance.now();
  771. let shrinkedLocalBounds = new THREE.Box3();
  772. let worldToBox = boxNode.matrixWorld.clone().invert();
  773. for(let node of this.visibleNodes){
  774. if(!node.sceneNode){
  775. continue;
  776. }
  777. let buffer = node.geometryNode.buffer;
  778. let posOffset = buffer.offset("position");
  779. let stride = buffer.stride;
  780. let view = new DataView(buffer.data);
  781. let objectToBox = new THREE.Matrix4().multiplyMatrices(worldToBox, node.sceneNode.matrixWorld);
  782. let pos = new THREE.Vector4();
  783. for(let i = 0; i < buffer.numElements; i++){
  784. let x = view.getFloat32(i * stride + posOffset + 0, true);
  785. let y = view.getFloat32(i * stride + posOffset + 4, true);
  786. let z = view.getFloat32(i * stride + posOffset + 8, true);
  787. pos.set(x, y, z, 1);
  788. pos.applyMatrix4(objectToBox);
  789. if(-0.5 < pos.x && pos.x < 0.5){
  790. if(-0.5 < pos.y && pos.y < 0.5){
  791. if(-0.5 < pos.z && pos.z < 0.5){
  792. shrinkedLocalBounds.expandByPoint(pos);
  793. }
  794. }
  795. }
  796. }
  797. yield;
  798. }
  799. let fittedPosition = shrinkedLocalBounds.getCenter(new THREE.Vector3()).applyMatrix4(boxNode.matrixWorld);
  800. let fitted = new THREE.Object3D();
  801. fitted.position.copy(fittedPosition);
  802. fitted.scale.copy(boxNode.scale);
  803. fitted.rotation.copy(boxNode.rotation);
  804. let ds = new THREE.Vector3().subVectors(shrinkedLocalBounds.max, shrinkedLocalBounds.min);
  805. fitted.scale.multiply(ds);
  806. let duration = performance.now() - start;
  807. console.log("duration: ", duration);
  808. yield fitted;
  809. }
  810. getFittedBox(boxNode, maxLevel = Infinity){
  811. maxLevel = Infinity;
  812. let start = performance.now();
  813. let shrinkedLocalBounds = new THREE.Box3();
  814. let worldToBox = boxNode.matrixWorld.clone().invert();
  815. for(let node of this.visibleNodes){
  816. if(!node.sceneNode || node.getLevel() > maxLevel){
  817. continue;
  818. }
  819. let buffer = node.geometryNode.buffer;
  820. let posOffset = buffer.offset("position");
  821. let stride = buffer.stride;
  822. let view = new DataView(buffer.data);
  823. let objectToBox = new THREE.Matrix4().multiplyMatrices(worldToBox, node.sceneNode.matrixWorld);
  824. let pos = new THREE.Vector4();
  825. for(let i = 0; i < buffer.numElements; i++){
  826. let x = view.getFloat32(i * stride + posOffset + 0, true);
  827. let y = view.getFloat32(i * stride + posOffset + 4, true);
  828. let z = view.getFloat32(i * stride + posOffset + 8, true);
  829. pos.set(x, y, z, 1);
  830. pos.applyMatrix4(objectToBox);
  831. if(-0.5 < pos.x && pos.x < 0.5){
  832. if(-0.5 < pos.y && pos.y < 0.5){
  833. if(-0.5 < pos.z && pos.z < 0.5){
  834. shrinkedLocalBounds.expandByPoint(pos);
  835. }
  836. }
  837. }
  838. }
  839. }
  840. let fittedPosition = shrinkedLocalBounds.getCenter(new THREE.Vector3()).applyMatrix4(boxNode.matrixWorld);
  841. let fitted = new THREE.Object3D();
  842. fitted.position.copy(fittedPosition);
  843. fitted.scale.copy(boxNode.scale);
  844. fitted.rotation.copy(boxNode.rotation);
  845. let ds = new THREE.Vector3().subVectors(shrinkedLocalBounds.max, shrinkedLocalBounds.min);
  846. fitted.scale.multiply(ds);
  847. let duration = performance.now() - start;
  848. console.log("duration: ", duration);
  849. return fitted;
  850. }
  851. get progress () {
  852. return this.visibleNodes.length / this.visibleGeometry.length;
  853. }
  854. find(name){
  855. let node = null;
  856. for(let char of name){
  857. if(char === "r"){
  858. node = this.root;
  859. }else{
  860. node = node.children[char];
  861. }
  862. }
  863. return node;
  864. }
  865. get visible(){
  866. return this._visible;
  867. }
  868. set visible(value){
  869. if(value !== this._visible){
  870. this._visible = value;
  871. this.dispatchEvent({type: 'visibility_changed', pointcloud: this});
  872. }
  873. }
  874. }