PointCloudOctree.js 32 KB

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