import * as THREE from "../../../../libs/three.js/build/three.module.js";
import {TextSprite} from "../../objects/TextSprite.js";
import ModelTextureMaterial from "../../materials/ModelTextureMaterial.js";
import FastTranPass from '../../materials/FastTranPass.js'
import Common from "../../utils/Common.js";
import math from "../../utils/math.js";
import cameraLight from "../../utils/cameraLight.js";
import {MeshDraw, LineDraw} from '../../utils/DrawUtil.js'
import Panorama from "./Panorama.js";
import browser from '../../utils/browser.js'
import QualityManager from './tile/QualityManager.js'
import TileDownloader from './tile/TileDownloader.js'
import PanoRenderer from './tile/PanoRenderer.js'
import TilePrioritizer from './tile/TilePrioritizer.js'
import {transitions, easing, lerp} from "../../utils/transitions.js";
import DepthImageSampler from './DepthImageSampler.js'
let {PanoSizeClass,Vectors,GLCubeFaces, PanoramaEvents} = Potree.defines
var rot90 = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,0,1), Math.PI/2 ); //使用的是刚好适合全景图的,给cube贴图需要转90°
let raycaster = new THREE.Raycaster();
//let currentlyHovered = null;
let texLoader = new THREE.TextureLoader()
let addLine = (origin, dir, len, color='#fff') => {
var line1 = LineDraw.createLine([origin, origin.clone().add(dir.clone().multiplyScalar(len || 1))], { color })
//console.log(origin.toArray(), dir.toArray())
viewer.scene.scene.add(line1)
return line1
}
let tileArr = []
let previousView = {
controls: null,
position: null,
target: null,
};
const HighMapCubeWidth = 1
const directionFactor = 400 //原先10,几乎只往距离近的走了;设置太大容易略过近处漫游点走向下坡,因为鼠标一般在地面,下坡的漫游点更有利
export class Images360 extends THREE.EventDispatcher{
constructor(viewer ){
super();
this.viewer = viewer;
this.panos = [];
this.neighbourMap = {}
this.node = new THREE.Object3D();
this.node.name = 'ImagesNode'
this.cubePanos = [];
this.fastTranMaskPass = new FastTranPass(viewer.renderer)
{
this.cube = new THREE.Mesh(new THREE.BoxBufferGeometry(1,1,1,1),new ModelTextureMaterial());
Potree.Utils.updateVisible(this.cube,'showSkybox', false )
this.cube.layers.set(Potree.config.renderLayers.skybox)
this.cube.name = 'skyboxCube'
viewer.scene.scene.add(this.cube)
}
if(Potree.settings.testCube){
this.cubeTest = this.cube.clone()
this.cubeTest.material = new THREE.MeshBasicMaterial({
wireframe:true,
color:'#FF3377',
transparent:true,
opacity:0.7,
depthWrite:false,
depthTest:false,
})
viewer.scene.scene.add(this.cubeTest)
this.cubeTest.visible = true
}
this.flying_ = false
this.currentPano = null;
this.mouseLastMoveTime = Date.now()
this.scrollZoomSpeed = 0.06
this.zoomLevel = 1
this.tileDownloader = new TileDownloader;
this.qualityManager = new QualityManager
this.panoRenderer = new PanoRenderer(viewer, this.tileDownloader, this.qualityManager)
this.basePanoSize = this.qualityManager.getPanoSize(PanoSizeClass.BASE);
this.standardPanoSize = this.qualityManager.getPanoSize(PanoSizeClass.STANDARD);
this.highPanoSize = this.qualityManager.getPanoSize(PanoSizeClass.HIGH);
this.ultraHighPanoSize = this.qualityManager.getPanoSize(PanoSizeClass.ULTRAHIGH);
this.tileDownloader.processPriorityQueue = !1;
this.tileDownloader.tilePrioritizer = new TilePrioritizer(this.qualityManager, this.basePanoSize, this.standardPanoSize, this.highPanoSize, this.ultraHighPanoSize);
{//高分辨率cube 放大
this.addHighMapCube()
viewer.addEventListener(PanoramaEvents.Enter,(e)=>{
this.setHighMap(e.newPano)
})
viewer.addEventListener('panoSetZoom',(e)=>{
if(Potree.settings.displayMode == 'showPanos'){
e.zoomed ? this.showHighMap() : this.hideHighMap() //add
}
})
}
this.depthSampler = new DepthImageSampler();
viewer.fpControls.addEventListener('dollyStopCauseUnable',(e)=>{
if(/* e.hoverViewport != viewer.mainViewport || */!Potree.settings.zoom.enabled)return
if(e.scale != void 0){//触屏
this.zoomBy(e.scale, e.pointer)
}else{//滚轮
let zoom;
if(e.delta > 0){
zoom = 1 + this.scrollZoomSpeed
}else{
zoom = 1 - this.scrollZoomSpeed
}
e.delta != 0 && this.zoomBy(zoom)
}
})
let click = (e) => {//不用"mouseup" 是因为 mouseup有drag object时也会触发
if(e.clickElement ||
Potree.settings.unableNavigate || this.flying || !e.isTouch && e.button != THREE.MOUSE.LEFT || e.drag && e.drag.object //拖拽结束时不算
|| Potree.settings.editType == 'pano' && viewer.modules.PanoEditor.activeViewName != 'mainView'
|| Potree.settings.editType == 'merge' && !e.intersectPoint || viewer.inputHandler.hoveredElements[0] && viewer.inputHandler.hoveredElements[0].isModel && e.intersectPoint.distance > viewer.inputHandler.hoveredElements[0].distance
) return
if(Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge'){
if( e.hoverViewport == viewer.mapViewer.viewports[0]){
return viewer.mapViewer.dispatchEvent(e/* {type:'global_click',e } */)
}else if(e.hoverViewport != viewer.mainViewport){ //如数据集校准其他viewport
return
}
}
if(!Potree.settings.dblToFocusPoint/* && this.currentPano */){//双击不会focus点云 或者 已经focusPano了
this.flyToPanoClosestToMouse()
}
}
viewer.addEventListener('global_click' , click)
viewer.addEventListener("global_mousemove", (e) => {
if(!Potree.settings.unableNavigate && Potree.settings.ifShowMarker && e.hoverViewport == viewer.mainViewport){//如果不显示marker,就在点击时再更新
this.updateClosestPano(e.intersect)
}
});
this.addEventListener('markerHover',(e)=>{
this.updateClosestPano(e.pano, e.hovered)
})
if(!Potree.settings.isOfficial){
this.domRoot = viewer.renderer.domElement.parentElement;
let elUnfocus = $("");
elUnfocus.css({
position : "absolute",
right : '25%',
bottom: '20px',
zIndex: "10000",
fontSize:'1em', color:"black",
display:'none',
background:'rgba(255,255,255,0.8)',
})
elUnfocus.on("click", () => this.unfocus());
this.elUnfocus = elUnfocus;
this.domRoot.appendChild(elUnfocus[0]);
if(Potree.settings.editType != 'merge'){
let elHide = $("")
elHide.css({
position : "absolute",
right : '40%',
bottom: '20px',
zIndex: "10000",
fontSize:'1em' ,color:"black",
width : '100px',
background:'rgba(255,255,255,0.8)',
})
this.domRoot.appendChild(elHide[0]);
elHide.on("click", (e) => {
let visi = Potree.Utils.getObjVisiByReason(viewer.scene.pointclouds[0], 'force')
viewer.scene.pointclouds.forEach(e=>{
Potree.Utils.updateVisible(e, 'force', !visi)
})
elHide.val(!visi ? "隐藏点云" : "显示点云")
});
}
let elDisplayModel = $("")
elDisplayModel.css({
position : "absolute",
right : '65%',
bottom: '20px',
zIndex: "10000",
fontSize:'1em',color:"black",
width : '100px',
background:'rgba(255,255,255,0.8)',
})
this.domRoot.appendChild(elDisplayModel[0]);
elDisplayModel.on("click", (e) => {
if(Potree.settings.displayMode == 'showPointCloud' && this.panos.length == 0)return
Potree.settings.displayMode = Potree.settings.displayMode == 'showPointCloud' ? 'showPanos' : 'showPointCloud'
});
this.elDisplayModel = elDisplayModel
if(viewer.mapViewer){
let mapStyleBtn = $("")
mapStyleBtn.css({
position : "absolute",
right : '50%',
bottom: '20px',
zIndex: "10000",
fontSize:'1em' ,color:"black",
width : '100px',
background:'rgba(255,255,255,0.8)',
})
this.domRoot.appendChild(mapStyleBtn[0]);
let map = viewer.mapViewer.mapLayer.maps.find(e=>e.name == 'map')
mapStyleBtn.on("click", (e) => {
map.switchStyle(map.style == 'satellite' ? 'standard' : 'satellite')
mapStyleBtn.val(map.style == 'satellite' ? '卫星' : '普通')
});
}
}
{//切换模式
let displayMode = '';
this.latestRequestMode = '';//因为可能延迟,所以记录下每次的请求模式,延迟后判断这个
Object.defineProperty(Potree.settings , "displayMode",{
get: function() {
return displayMode
},
set: (mode)=> {
this.latestRequestMode = mode
console.warn('Request setMode: ' + mode)
this.dispatchEvent({type:'requestMode',mode})
let config2
let config = Potree.config.displayMode[mode]
if(this.isAtPano() && !this.latestToPano){
config2 = config.atPano
}else{
config2 = config.transition
}
let changeTileDownload = ()=>{
if(config2.showSkybox || config2.showPoint && config2.pointUsePanoTex){
this.tileDownloader.start()
this.currentPano && this.currentPano.enter()
}else{
this.tileDownloader.stop()
this.currentPano && this.currentPano.exit()
this.nextPano && (viewer.cancelLoad(this.nextPano))
}
}
if(mode != displayMode){
let camera = viewer.scene.getActiveCamera()
if(mode == 'showPanos' && viewer.mainViewport.view.isFlying()){//飞完才能切换全景
let f = ()=>{
if(this.latestRequestMode == mode){//如果ui还是停在这个模式的话
Potree.settings.displayMode = mode
}
viewer.mainViewport.view.removeEventListener('flyingDone', f)
}
viewer.mainViewport.view.addEventListener('flyingDone', f) //once
return
}
if(this.isAtPano() && !this.latestToPano){
config2 = config.atPano
}else{
config2 = config.transition
if(mode == 'showPanos'){//自动飞入一个pano
//要改成飞进最近的。。。
if(this.panos.length == 0)return
//this.modeChanging = true //主要是因为到全景图不会立刻成功
let wait = (e)=>{
console.log('flyToPanoDone')
this.removeEventListener('flyToPanoDone',wait)
setTimeout(()=>{
if(this.latestRequestMode == mode ){
Potree.settings.displayMode = mode
}
},e.makeIt ? 1 : 50)
}
this.addEventListener('flyToPanoDone',wait) //等待飞行完毕。flyToPano的callback可能不执行所以换这个。但也可能被cancel
this.flyToPano({
pano: this.findNearestPano(),
//dealDoneWhenCancel:true,
/* callback: ()=>{
setTimeout(()=>{ //防止循环,所以延迟
if(this.latestRequestMode == mode ){
Potree.settings.displayMode = mode
}
},1)
} */
})
return;
}else{
}
}
changeTileDownload()
if(config2.showSkybox || config2.pointUsePanoTex){
let wait = ( )=> {
//console.log('waitdone')
//if(e.pano && e.pano != this.currentPano)return //loadedDepthImg
setTimeout( ()=>{
if(this.latestRequestMode == mode ){
Potree.settings.displayMode = mode
}
},1)
}
//this.updateDepthTex()
if(this.checkAndWaitForPanoLoad(this.currentPano, this.basePanoSize, wait)){
//console.log('等待贴图加载2', this.currentPano.id)
return
}
}
viewer.scene.pointclouds.forEach(e=>{
Potree.Utils.updateVisible(e, 'displayMode', config2.showPoint, 2 )
})
if(config2.pointUsePanoTex){
viewer.scene.pointclouds.forEach(e=>{
e.material.setProjectedPanos(this.currentPano,this.currentPano, 1)
})
}else{
viewer.scene.pointclouds.forEach(e=>{
e.material.stopProjectedPanos()
})
}
Potree.Utils.updateVisible(this.cube,'showSkybox',config2.showSkybox )// this.cube.visible = config2.showSkybox
//this.cube.visible = config.atPano.showSkybox
if(this.cube.visible){
//this.cube.material.setProjectedPanos(this.currentPano, this.currentPano, 1)
this.setProjectedPanos({
progress:1,
ifSkybox: true,
ifPointcloud : false,
easeInOutRatio : 0,
pano0:this.currentPano,
pano1:this.currentPano
})
}else{
this.smoothZoomTo(1)
this.resetHighMap()
this.hideHighMap()
}
/* viewer.dispatchEvent({
type: "enableChangePos",
canLeavePano : config.canLeavePano ,
viewport:
}) */
//viewer.mainViewport.unableChangePos = !config.canLeavePano
displayMode = mode
if(mode == 'showPanos'){
camera.far = viewer.farWhenShowPano //修改far
Potree.settings.pointDensity = 'panorama'
if(Potree.config.displayMode.showPanos.transition.pointUsePanoTex){
viewer.scene.pointclouds.forEach(e=>{
e.material.pointSizeType = 'FIXED'
})
}
this.updateCube(this.currentPano)
}else{
if(camera.limitFar) camera.far = Potree.settings.cameraFar;//修改far
Potree.settings.pointDensity = Potree.settings.UserPointDensity
//Potree.sdk && Potree.sdk.scene.changePointOpacity()
if(Potree.config.displayMode.showPanos.transition.pointUsePanoTex){
viewer.scene.pointclouds.forEach(e=>{
e.material.pointSizeType = Potree.config.material.pointSizeType
})
}
}
camera.updateProjectionMatrix()
if(this.elDisplayModel){
this.elDisplayModel.val( mode == 'showPointCloud' ? ">>全景" : '>>点云')
}
/* this.panos.forEach(e=>{
Potree.Utils.updateVisible(e, 'modeIsShowPanos', mode == 'showPanos', 1, mode == 'showPanos' ? 'add':'cancel') //
}) */
this.dispatchEvent({type:'endChangeMode',mode})
console.log('setModeSuccess: ' + mode)
}else{
changeTileDownload()
//this.dispatchEvent({type:'endChangeMode',mode})
}
}
})
Potree.settings.displayMode = 'showPointCloud'
}// 切换模式 end
{//
let currentPano = null;
Object.defineProperty(this , "currentPano",{
get: function() {
return currentPano
},
set: function(e) {
if(e != currentPano){
//console.log('set currentPano ', e.id)
currentPano && currentPano.exit()
e && e.enter()
currentPano = e
}
}
})
}
{//是否显示marker
let ifShowMarker = true;
Object.defineProperty(Potree.settings, "ifShowMarker",{
get: function() {
return ifShowMarker
},
set: (show)=>{
show = !!show
if(show != ifShowMarker){
this.panos.forEach(pano=>{
Potree.Utils.updateVisible(pano, 'ifShowMarker', show, 1 )
})
//this.emit('markersDisplayChange', show)
ifShowMarker = show
viewer.dispatchEvent('showMarkerChanged')
viewer.dispatchEvent('content_changed')
}
}
})
}
viewer.addEventListener("update", () => {
this.update(viewer);
});
//viewer.inputHandler.addInputListener(this);
var keys = {
FORWARD: ['W'.charCodeAt(0), 38],
BACKWARD: ['S'.charCodeAt(0), 40],
LEFT: ['A'.charCodeAt(0), 37],
RIGHT: ['D'.charCodeAt(0), 39],
}
viewer.inputHandler.addEventListener('keydown',(e)=>{
if(Potree.settings.displayMode == 'showPanos'){
for(let i in keys){
if(keys[i].some(a => a == e.keyCode)){
switch(i){
case 'FORWARD':
this.flyLocalDirection(Vectors.FORWARD.clone());
break;
case 'BACKWARD':
this.flyLocalDirection(Vectors.BACK.clone());
break;
case 'LEFT':
this.flyLocalDirection(Vectors.LEFT.clone());
break;
case 'RIGHT':
this.flyLocalDirection(Vectors.RIGHT.clone());
break;
}
break;
}
}
}
})
};
updateDepthTex(pano){
if(this.currentPano != pano || !pano.depthTex)return
//this.depthSampler.changeImg(pano.depthTex.image); //pick sampler要飞到了才能切换图,而skybox贴图是随着全景图切换而切换的
this.cube.material.updateDepthTex(pano) //确保一下
}
findNearestPano(pos){
pos = pos ? new THREE.Vector3().copy(pos) : this.position
let result = Common.sortByScore(this.panos,[Images360.filters.isEnabled()],[e=>-e.position.distanceTo(pos)])
let pano = result[0] && result[0].item
return pano
}
/* set flying(v){//正在飞向pano
this.flying_ = !!v
//console.log('this.flying_ ', !!v )
//this.emit('flying', this.flying_)
let config = Potree.config.displayMode[Potree.settings.displayMode]
viewer.mainViewport.unableChangePos = !config.canLeavePano || !!v
}
get flying(){
return this.flying_
} */
flyLocalDirection(dir) {
var direction = this.getDirection(dir),
option1 = 1 === dir.y ? .4 : .75,
option2 = 1 === Math.abs(dir.x);
return this.flyDirection(direction, option1, option2, true)
}
getDirection(e) {
if(!e){
return viewer.scene.view.direction
}else{
return e = e ? e : (new THREE.Vector3).copy(Vectors.FORWARD),
e.applyQuaternion(viewer.mainViewport.camera.quaternion)
}
}
get position(){
return this.viewer.scene.view.position.clone()
}
isAtPano(precision){//是否在某个漫游点上
if(precision){
return this.currentPano && math.closeTo(viewer.scene.view.position, this.currentPano.position, precision)
}
return this.currentPano && viewer.scene.view.position.equals(this.currentPano.position)
}
updateProjectedPanos(){//更新材质贴图
//console.warn('updateProjectedPanos')
this.projectedPano0 && this.projectedPano1 && this.setProjectedPanos({pano0:this.projectedPano0, pano1:this.projectedPano1})
}
setProjectedPanos(o={}){//设置cube和点云的材质贴图
this.cube.material.setProjectedPanos(o.pano0, o.pano1, o.progress)
if(o.ifPointcloud){
viewer.scene.pointclouds.forEach(e=>{
e.material.setProjectedPanos(o.pano0, o.pano1, o.progress, o.easeInOutRatio)
})
}
//console.warn('setProjectedPanos ', o.pano0.id , o.pano1.id)
this.projectedPano0 = o.pano0
this.projectedPano1 = o.pano1
}
cancelFlyToPano(toPano){//取消当前已有的飞行准备,前提是相机还未移动
if(viewer.mainViewport.view.isFlying() || toPano && this.latestToPano != toPano)return
//Potree.Log('cancelFlyToPano', this.latestToPano && this.latestToPano.pano.id)
this.nextPano = null
this.latestToPano = null
}
flyToPano(toPano) { //飞向漫游点
if(!toPano)return
if(typeof toPano == 'number')toPano = this.panos[toPano]
if(toPano instanceof Panorama){
toPano = {pano: toPano}
}
let done = (makeIt, disturb)=>{
//console.log('flyToPano done ', toPano.pano.id, makeIt, disturb )
if(makeIt || disturb) { // disturb已经开始飞行但中途取消
toPano.callback && toPano.callback(makeIt)
//this.flying = false
this.cancelFlyToPano(toPano)
this.updateClosestPano(this.closestPano,false) //飞行结束后取消点击漫游点时得到的closestPano
}else{
}
this.dispatchEvent({type:'flyToPanoDone', makeIt, disturb})
this.fastTranMaskPass.stop()
toPano.deferred && toPano.deferred.resolve(makeIt) //测量线截图时发现,resolve需要写在flying=false 后才行。
}
if(!toPano.pano.enabled)return done(false,true);
//Potree.Log('hope flyToPano: '+toPano.pano.id, toPano.pano.position.toArray() )
if(this.latestToPano && this.latestToPano != toPano && (//还在飞
this.latestToPano.pano != this.currentPano || !this.isAtPano())){//如果旧的toPano只在pano旋转镜头,就直接取消旧的,继续执行
return done(false)
}
if(this.currentPano == toPano.pano && this.isAtPano() && !toPano.target && !toPano.quaternion ){
//已在该pano
this.dispatchEvent({type:'flyToPano', toPano})
return done(true);
}
//Potree.Log('flyToPano: '+toPano.pano.id, toPano.pano.position.toArray() /* this.latestToPano && this.latestToPano.pano.id */ )
let target = toPano.target
let config = Potree.config.displayMode[Potree.settings.displayMode]
let pano = toPano.pano
let dis = pano.position.distanceTo(this.position)
this.nextPano = pano
this.latestToPano = toPano
//this.flying = true //防止新的请求
//Potree.Log('flyToPano:'+pano.id + ' , duration:'+toPano.duration, null, 12)
{//不飞的话是否不要执行这段?
let wait = (e)=> {
//console.log('wait done', pano.id)
if(/* e.pano && */this.latestToPano && pano != this.latestToPano.pano)return//loadedDepthImg
if(this.latestToPano != toPano)return Potree.Log('已经取消', pano.id) //如果取消了
setTimeout(()=>{
if(this.latestToPano != toPano)return
this.flyToPano(toPano)
},1)
}
if(!pano.depthTex && pano.pointcloud.hasDepthTex){ //点云模式也要加载depthTex,因获取neighbour需要用到
console.log('等待加载depthtex', pano.id)
pano.addEventListener('loadedDepthImg', wait, {once:true})
return pano.loadDepthImg()
}
if(config.atPano.showSkybox || config.atPano.pointUsePanoTex){
let a = this.updateCube(this.currentPano, toPano.pano)
if(a == 'useBound'){
toPano.useBound = true
}
if(this.checkAndWaitForPanoLoad(pano, toPano.basePanoSize || this.basePanoSize, wait )){
//console.log('等待贴图加载',pano.id)
return
}
}
}
config = Potree.config.displayMode[Potree.settings.displayMode] //可能换了
let pointcloudVisi = config.atPano.showPoint //viewer.scene.pointclouds[0].visible
Potree.Utils.updateVisible(this.cube,'showSkybox', config.atPano.showSkybox ) // this.cube.visible = config.atPano.showSkybox
//console.log('开始飞1')
if(config.transition.showPoint){
viewer.scene.pointclouds.forEach(e=>{
Potree.Utils.updateVisible(e, 'displayMode', true)
})
}
const endPosition = pano.position.clone()
let T = Potree.config.transitionsTime
/* let maxTime = this.isAtPano() ? T.panoToPanoMax : T.flyIn
let duration = toPano.duration == void 0 ? (T.flyMinTime+Math.min(T.flytimeDistanceMultiplier * dis, maxTime)) : toPano.duration
*/
/* let maxDis = this.isAtPano() ? T.maxDistanceThreshold : T.maxDistanceThresholdFlyIn
let duration = toPano.duration == void 0 ? Math.min(dis, T.maxDistanceThreshold) * T.flytimeDistanceMultiplier + T.flyMinTime : toPano.duration
*/
let maxDis = 7
let duration = toPano.duration == void 0 ? Math.min(dis, maxDis) * T.flytimeDistanceMultiplier + T.flyMinTime : toPano.duration
if(config.transition.showSkybox || config.transition.pointUsePanoTex){
if(Potree.settings.fastTran ){
this.fastTranMaskPass.start() //截图当前画面
viewer.scene.view.position.copy(endPosition)
}
this.setProjectedPanos({
progress: 0,
ifSkybox: this.cube.visible,
ifPointcloud : config.transition.pointUsePanoTex,
easeInOutRatio : pointcloudVisi ? 0.3 : 0,
pano0:this.currentPano,
pano1:pano
})
}
if(toPano.useBound){
duration = Math.min(1500, duration)
toPano.easeName = 'easeInOutQuad'
}else{
if(endPosition.equals(this.position))toPano.easeName = 'easeOutSine'
}
{
toPano.easeName = toPano.easeName || 'linearTween'
toPano.duration = duration
this.beforeFlyToPano(toPano)
}
/* let fly = ()=>{
this.dispatchEvent({type:'flyToPano', toPano})
viewer.scene.view.setView({position:endPosition, target, quaternion:toPano.quaternion , duration,
callback:()=>{
if(!config.atPano.pointUsePanoTex){
viewer.scene.pointclouds.forEach(e=>{
e.material.stopProjectedPanos()
})
}
this.currentPano = pano;
this.nextPano = null;
if(Potree.settings.displayMode == 'showPanos'){
viewer.scene.pointclouds.forEach(e=>{
Potree.Utils.updateVisible(e, 'displayMode',pointcloudVisi)
})
}
done(true);
this.updateDepthTex(this.currentPano)
}, onUpdate:(progress)=>{
//console.log('uniforms progress',progress)
this.cube.material.uniforms.progress.value = progress
viewer.scene.pointclouds.forEach(e=>{
e.material.uniforms.progress.value = progress
})
},
cancelFun:()=>{ done(false, true) },
Easing:easeName
})
//duration > 0 && (this.flying = true) //再写一遍 防止cancel其他项目导致flying为false
} */
let onUpdate = (progress)=>{
this.cube.material.uniforms.progress.value = progress
viewer.scene.pointclouds.forEach(e=>{
e.material.uniforms.progress.value = progress
})
}
let fly = ()=>{
let startProgress = toPano.progress = toPano.progress || 0
let loadNextProgress = THREE.MathUtils.clamp(1 - 2.5 / dis, 0.3, 0.8)
//console.log(loadNextProgress, (1-loadNextProgress) * dis )
this.dispatchEvent({type:'flyToPano', toPano})
viewer.scene.view.setView({position:endPosition, target, quaternion:toPano.quaternion , duration:toPano.duration,
onUpdate:(progress_, delta)=>{
let progress = startProgress + progress_ * (1 - startProgress)
let currentSpeed
if (progress_ != 1 && progress_ != 0) { // 1的时候不准,往往偏小, 0的时候速度为0,也不记录
currentSpeed = ((progress - toPano.progress) * dis) / delta //记录下当前速度,当变为匀速时可以过渡到flySpeed
} else {
currentSpeed = toPano.currentSpeed || 0
}
toPano.currentSpeed = currentSpeed
toPano.progress = progress
//console.log('progress_', progress_, 'delta',delta , 'progress', progress/*, 'currentSpeed', currentSpeed, */ )
if (progress > loadNextProgress && toPano.easeName == 'linearTween' && currentSpeed){// 减速. 如果仅旋转就不停止
//console.log('减速', /* currentSpeed , */progress_ )
toPano.easeName = 'easeOutSine'
let restDis = (1 - progress) * dis
toPano.duration = (Math.PI / 2 * restDis) / currentSpeed // 这样能保证初始速度为currentSpeed
viewer.scene.view.cancelFlying('all',false) //为了防止执行cancelFun先主动cancel
toPano.flyCount = 2
fly(toPano)
}
onUpdate(progress)
},
callback:()=>{
if(!config.atPano.pointUsePanoTex){
viewer.scene.pointclouds.forEach(e=>{
e.material.stopProjectedPanos()
})
}
this.lastPano = this.currentPano //记录,调试
this.currentPano = pano;
this.nextPano = null;
if(Potree.settings.displayMode == 'showPanos'){
viewer.scene.pointclouds.forEach(e=>{
Potree.Utils.updateVisible(e, 'displayMode',pointcloudVisi)
})
}
done(true);
this.updateDepthTex(this.currentPano) //删除dispose的depthTex
},
cancelFun:()=>{ done(false, true) },
Easing:toPano.easeName,
ignoreFirstFrame : toPano.flyCount != 2 //变换transition时不停一帧
})
}
if(Potree.settings.displayMode == 'showPanos'){
setTimeout(fly, 40); //更新geo后缓冲
}else{
fly()
}
//console.log('flyToPano:', toPano.pano.id)
}
beforeFlyToPano(toPano){
if(this.currentPano != toPano.pano) {
if(Potree.settings.displayMode == 'showPanos'){
this.resetHighMap()
}
this.smoothZoomTo(toPano.zoomLevel || 1, toPano.duration / 2);
}
}
/* updateCube(pano0, pano1){
if(Potree.settings.displayMode != 'showPanos')return
if(!viewer.scene.pointclouds.some(e=>!e.hasDepthTex)) return this.updateCube2(pano0, pano1) //都hasDepthTex的话
let useBound = (bound, size)=>{
size = size || bound.getSize(new THREE.Vector3)
let center = bound.getCenter(new THREE.Vector3)
size.max(new THREE.Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth))
this.cube.scale.copy(size)
this.cube.position.copy(center)
}
let getPanoBound = (pano)=>{//因漫游点可能在点云外部,如室外平地,所以需要union进漫游点
let panoBound = new THREE.Box3
panoBound.expandByPoint(pano.position)
panoBound.expandByVector(new THREE.Vector3(10,10,10));//give pano a margin
return pano.pointcloud.bound.clone().union(panoBound)
}
let getDis = (bound1, bound2)=>{ //获取bound1边界到bound2边界距离
if(bound1.intersectsBox(bound2))return 0
let center1 = bound1.getCenter(new THREE.Vector3)
let center2 = bound2.getCenter(new THREE.Vector3)
let dis = center1.distanceTo(center2)
let dis1 = bound1.distanceToPoint(center2)
let dis2 = bound2.distanceToPoint(center1)
return dis1 + dis2 - dis
}
if(pano1){//过渡
if(pano0.pointcloud == pano1.pointcloud){//同一个数据集内的过渡
useBound(getPanoBound(pano0))
}else{//非同一个数据集内的过渡
let bound = getPanoBound(pano0).union(getPanoBound(pano1))
if(getDis(pano0.pointcloud.bound, pano1.pointcloud.bound) < 100){
useBound(bound)
}else{//如果两个数据集boundingbox距离大于这个距离,扩大一下,防止精度问题导致失真//对很远的数据集似乎没有什么用
let size = bound.getSize(new THREE.Vector3)
let max = Math.max(size.x, size.y, size.z)
size.set(max,max,max)
useBound(pano0.pointcloud.bound.clone().union(pano1.pointcloud.bound), size)
}
}
}else{
useBound(getPanoBound(pano0)) //假定一个数据集不会太大,否则会造成失真,且bump时移动距离看起来很小。或者可以考虑用固定大小
}
} */
getIntersect(pano, dir, origin){
if(pano && pano.pointcloud.hasDepthTex ){
return this.depthSampler.sample( {dir }, pano, true )
}else{
origin = origin || pano.position
return viewer.inputHandler.getIntersect({
viewport:viewer.inputHandler.hoverViewport,
onlyGetIntersect:true, usePointcloud:true,
point: origin.clone().add(dir),
cameraPos: origin
})
}
}
/* updateCube(pano0, pano1){//增加细分的版本,且垂直方向上也分多个
if(Potree.settings.displayMode != 'showPanos')return
console.log('updateCube',pano0.id, pano1&&pano1.id)
let f = (bound, size)=>{
size = size || bound.getSize(new THREE.Vector3)
let center = bound.getCenter(new THREE.Vector3)
size.max(new THREE.Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth))
this.cube.scale.copy(size)
this.cube.position.copy(center)
}
this.cube.geometry.dispose();
if(pano1){//过渡
let count1, count2;
let panoIndex = 0
let add = (pano, dir )=>{
let getPI = function(index, panoIndex_){
if(panoIndex_ == void 0) panoIndex_ = panoIndex
return (count1 * count2 + 2 ) * panoIndex_ + index + 2
}
let minZ, maxZ
minZ = pano.floorPosition.z
{//天花板高度值
//用三个间隔120度散开,和中心垂直线成一定夹角的三个向量去求 最高高度 (不求平均的原因:万一是0不好算)
let rotMat = new THREE.Matrix4().makeRotationX(THREE.Math.degToRad(40))// 角度不能小于天花板中空的半径,大概就是0.2*Math.PI=36度
let dir1 = new THREE.Vector3(0,0,1).applyMatrix4(rotMat)
let rotMat1 = new THREE.Matrix4().makeRotationZ(Math.PI*2 / 3);
let rotMat2 = new THREE.Matrix4().makeRotationZ(-Math.PI*2 / 3);
let dir2 = dir1.clone().applyMatrix4(rotMat1)
let dir3 = dir1.clone().applyMatrix4(rotMat2)
let zs = [dir1,dir2,dir3].map(dir_=>{
let intersect = this.depthSampler.sample( {dir: dir_}, pano, true )
let z = intersect ? intersect.location.z : pano.position.z
return z
})
zs.sort((a,b)=>{return b-a});//得最大值
maxZ = zs[0]
let min = pano.position.z + 1
if(maxZ < pano.position.z + 0.04){//户外
maxZ = pano.position.z + 50
}
maxZ = Math.max(min,maxZ)
console.log(pano.id, 'maxZ:',maxZ )
console.log(pano.id, 'minZ:',minZ )
}
[maxZ, minZ ].forEach(z=>{
posArr.push(pano.position.clone().setZ(z))
})
const angle = Math.PI/8
let getDir = (angle_)=>{
let rotMat = new THREE.Matrix4().makeRotationZ(angle_)
return dir.clone().applyMatrix4(rotMat)
}
let dirs = [ getDir(angle*4), getDir(angle*3), getDir(angle*2), getDir(angle), dir.clone(), getDir(-angle) , getDir(-angle*2), getDir(-angle*3), getDir(-angle*4) ]; // 夹角总和180度
count1 = dirs.length
dirs.forEach((dir, index)=>{//获取在这个方向上和墙体intersect的最远距离,使用中、上、下三个方向
let dirs_ = [
dir.clone().setZ(Math.tan(THREE.Math.degToRad(30))).normalize(),
dir.clone().setZ(Math.tan(THREE.Math.degToRad(15))).normalize(),
dir.clone(), // 水平方向
dir.clone().setZ(-Math.tan(THREE.Math.degToRad(15))).normalize(),
dir.clone().setZ(-Math.tan(THREE.Math.degToRad(30))).normalize(),
];
count2 = dirs_.length
dirs_.forEach((dir_, i) =>{
let intersect = this.depthSampler.sample( {dir: dir_}, pano, true )
let location
if(!intersect){ //超级远
let distance = 100
location = dir_.clone().multiplyScalar(distance).add(pano.position)
intersect = {distance,location}
}
//intersect.distance
location = intersect.location.clone()
let shouldZ// = THREE.Math.clamp(intersect.location.z, minZ, maxZ);
let needShrink = false
if(i == 0){//最上方的点高度直接等于天花板
shouldZ = maxZ
if(location.zminZ)location.z = minZ
else needShrink = true
}
if(needShrink ){//需要在保持dir_不变的情况下修改z
let len = (shouldZ - pano.position.z) / (intersect.location.z - pano.position.z) * intersect.distance
location = dir_.clone().multiplyScalar(len).add(pano.position)
}
posArr.push(location)
if(index!=0 && i!=0){//加入一块四方面
let curIndex = getPI(count2 * index + i);
faceArr.push([curIndex-1, curIndex-count2-1, curIndex-count2],
[curIndex-1, curIndex, curIndex-count2])
}
})
if(index!=0){
let top = -2;
let btm = -1
faceArr.push([getPI(count2*(index-1) ), getPI(count2*index ), getPI(top) ])//天花板扇形
faceArr.push([getPI(count2*index-1), getPI(count2*(index+1)-1), getPI(btm) ] )//地板扇形
}else{
//加入和另一个pano连接的其中一个侧边
let panoIndex2 = (panoIndex + 1) % 2;
for(let i=1;i{ //该点前方近处是否都被遮挡 。 为了防止杂点干扰,多个方向探测
let vec = new THREE.Vector3().subVectors(subPano.position, mainPano.position).normalize()
let getDir = (angle_, upDown)=>{ //基于vec的方向 向左向右旋转
//if(upDown) vec.clone().applyAxisAngle(new THREE.Vector3(1, 0, 0), upDown);
return vec.clone().applyAxisAngle(new THREE.Vector3(0, 0, 1), angle_);
}
let minScore = 0.25
let angles = [20,16,12.5,10,8,6,4.5,3,1, -1,-3,-4.5,-6,-8,-10,-12.5,-16,-20] //水平方向角度 3之间有较大概率杂点, 3以外一部分有较大概率有空隙所以紧凑点
let wellCount = 0
let seccess = [];
for(let i=0; i dis ){//投影在vec方向的长度不超过漫游点间距
wellCount ++ ; seccess.push(angles[i]); color = new THREE.Color('#0f8')
}
ifLog && addLine(mainPano.position, dir, dis, color)
}
//console.log('ifSheltered')
if(ifLog){
console.log('ifSheltered seccess', seccess, 'id:', mainPano.originID, subPano.originID)
}
let score = wellCount / angles.length
if(score >= minScore){//合格个数
return score
}
}
/*
识别一定角度范围内是否有遮挡时
几种奇葩的情况:
1 在墙的两边的但是墙是倾斜的漫游点:
A /
/
/ B
从B出发和BA成20度的射线和墙面的交点会远于A,导致识别为无遮挡。
所以还是改为识别范围内多个深度图像素, 合格像素个数占比 至少要大于50%,因为半边墙壁是50%
如SG-9UsbysDufBw&formal&test 的 6、9点。 而SS-GTmFBp1JN8k&formal&test的 2、3两点是人物遮挡
2 可以通行,但是右边是墙,右边的都检测失败,左侧的又有一些杂点,导致成功dir个数很低。
所以minRatio 要降低于0.5
*/
//三个方向 : position0到position1, position0到floorPosition1, position1到floorPosition0。 只要有一个满足ifNeighbour就为true。 不过为了不使sampler总换图,先只考虑从主pano到副pano的方向
let getNeighbour = (mainPano, subPano )=>{
let dirPoints = [[subPano.position, mainPano.position]] //注: 点A能到B不代表点B能到A,因为拍摄时物体会移动,或点位相对位置不对,无论是否是意外遮挡都且记下来,反正最后只要有一方可行就算相邻。
if(dis < 20){//在远处去掉对floorPosition的判断
dirPoints.push([subPano.floorPosition.clone().add(new THREE.Vector3(0,0,0.1)), mainPano.position])
}
if(dis < 12){//为了防止楼梯拐角、杂点遮挡。 尽量只在穿墙时不可通行
dirPoints.push([subPano.position.clone().add(new THREE.Vector3(0,0,0.8)), mainPano.position])
let normal = math.getNormal2d({p1:subPano.position, p2:mainPano.position}).multiplyScalar(0.3) //左右方向
dirPoints.push([subPano.position.clone().add(new THREE.Vector3(normal.x,normal.y,0.1)), mainPano.position])
dirPoints.push([subPano.position.clone().add(new THREE.Vector3(-normal.x,-normal.y,0.1)), mainPano.position])
}
//console.warn('getNeighbour', mainPano.id,subPano.id)
for(let i=0; i dirPoints[i][0].distanceTo(dirPoints[i][1])){
//if(i>2)console.log('haha',i,'id:',mainPano.id,subPano.id)
return true
}
}
}
//if(!ifNeighbour && (map0[pano1.id] == void 0 || computeTwoDir && !map0[pano1.id] && map1[pano0.id] == void 0 )) {//主方向为空且不为邻居
if(pano0.pointcloud.hasDepthTex || pano1.pointcloud.hasDepthTex){
if(computeTwoDir ? (map0[pano1.id] == void 0 || map1[pano0.id] == void 0) : (map0[pano1.id] == void 0 && map1[pano0.id] !== false) ){
//2024.3.20改为必须两个方向都为true才行。 因为如果两个点分别在两个数据集相距很远,A确定有墙无法到B,B朝A看 没有B所在的数据集点云遮挡,因深度图不会包含别的数据集的点,故深度图探测到A处为无遮挡,就会导致会飞到遥远的A。 即使在同一个数据集,因为点云可以编辑位置,导致AB相对位置错误,也要避免这种情况可以互相乱走。 缺点是更容易被杂点阻挡,所以需要ifShelter降低阈值。
if(map0[pano1.id] == void 0 && pano0.depthTex){
let is = getNeighbour(pano0, pano1)
map0[pano1.id] = !!is
}
if(computeTwoDir && map0[pano1.id] && pano1.depthTex && map1[pano0.id] == void 0 ){ //computeTwoDir : 允许反向计算,即可以读取另一张的深度图 。 如果map0为false,map1就不用计算,只需要等待计算ifShelter
let is = getNeighbour(pano1, pano0)
map1[pano0.id] = !!is
}
if( map0[pano1.id] === false || map1[pano0.id] === false){
if(dis<20) {//再检查下 只要两方都没有被完全遮挡就算可通行 针对杂点较多的情况
if(pano0.depthTex && pano1.depthTex){
ifNeighbour = false
let a = ifSheltered(pano0,pano1)
if(a){
let b = ifSheltered(pano1,pano0)
if(b && (a+b >= 0.6)){
ifNeighbour = true
}
}
map0[pano1.id] = map1[pano0.id] = ifNeighbour
}
}else{
//标记为无需再计算, 因已经失败。 当map0和map1都不为void 0后就无法再计算了。
if(map0[pano1.id] === void 0) map0[pano1.id] = 0 ;
if(map1[pano0.id] === void 0) map1[pano0.id] = 0 ;
}
}
ifNeighbour = map1[pano0.id] == void 0 ? map0[pano1.id] : map0[pano1.id] && map1[pano0.id] //如果map1没计算就只要返回map0
if(ifLog){
console.log('isNeighbour', pano0.id+"("+pano0.originID+")", pano1.id+"("+pano1.originID+")", map0[pano1.id], map1[pano0.id])
}
}
}else if(!onlyUseTex && !ifNeighbour){//使用点云判断(有深度贴图时不会执行到这)
let inDirection = ()=>{
let dir = new THREE.Vector3().subVectors(pano1.position,pano0.position).normalize()
let dis = pano1.position.distanceTo(pano0.position)
let fov = THREE.Math.degToRad(viewer.mainViewport.camera.fov)
let hfov = cameraLight.getHFOVForCamera(viewer.mainViewport.camera , true );
let hov = Math.min(fov, hfov)
let max = Math.cos(THREE.Math.degToRad(10))
let min = Math.cos(THREE.Math.degToRad(40))
if(this.getDirection().dot(dir) > THREE.Math.clamp(Math.cos(hov/2 ) * dis / 10, min, max )){//距离越远要求和视线角度越接近
return true
}
}
if(computeDirFirst){//先计算方向,防止重复计算ifBlockedByIntersect
if(inDirection()){
ifNeighbour = !viewer.inputHandler.ifBlockedByIntersect({point:pano1.position, margin, cameraPos:pano0.position})
}
}else{
ifNeighbour = !viewer.inputHandler.ifBlockedByIntersect({point:pano1.position, margin, cameraPos:pano0.position})
if(ifNeighbour && !inDirection()){
ifNeighbour = undefined //不确定
}
}
map0[pano1.id] = map1[pano0.id] = ifNeighbour ? 'byCloud' : ifNeighbour//写简单点
}
if(map0[pano1.id] && map1[pano0.id]){
pano0.neighbours.includes(pano1) || pano0.neighbours.push(pano1)
pano1.neighbours.includes(pano0) || pano1.neighbours.push(pano0)
}
return ifNeighbour
}
bump(direction) {//撞墙弹回效果
if (!this.bumping && !this.latestToPano) {
let distance = Potree.settings.displayMode == 'showPanos' ? 0.15 : 0.12;//感觉点云模式比全景模式更明显,所以降低
let currentPos = this.position.clone()
let endPosition = new THREE.Vector3().addVectors(this.position, direction.clone().multiplyScalar(distance))
let duration = 150
viewer.scene.view.setView({position:endPosition, duration,
callback:()=>{
viewer.scene.view.setView({position:currentPos, duration: duration*5,
callback: ()=>{
this.bumping = false
//this.dispatchEvent('cameraMoveDone')
},
Easing:'easeInOutSine',
cancelFun:()=>{this.bumping = false}
})
this.bumping = true
},
cancelFun:()=>{this.bumping = false},
Easing:'easeInOutSine'
})
this.bumping = true
}
//备注:将4dkk中的‘前后方向变化fov、左右方向移动镜头’ 都改为移动镜头。 因为这里无法判断左右离壁距离。
}
flyToPanoClosestToMouse() {
/* if (Date.now() - this.mouseLastMoveTime > 50) {
//this.intersect = this.getMouseIntersect();
this.intersect && this.updateClosestPano(this.intersect);
} */
if(!Potree.settings.ifShowMarker){//不显示marker的时候mousemove没更新鼠标最近点所以更新
this.updateClosestPano(viewer.inputHandler.intersect)
}
//console.log('flyToPanoClosestToMouse',this.closestPano)
if (this.closestPano) {
let pano = this.closestPano
return this.flyToPano({
pano, easeName: this.isAtPano() ? 'linearTween' : 'easeInOutQuad'
});
}
var direction = this.viewer.inputHandler.getMouseDirection().direction;
this.flyDirection(direction)
}
flyDirection(direction, option1, option2, byKey) {
if(viewer.mainViewport.view.isFlying()){// closestPanoInDirection函数耗时长,飞行时运行会卡顿(如果以后加无缝过渡再说)
return
}
var deferred = $.Deferred();
//this.history.invalidate();
var panoSet = this.closestPanoInDirection(direction, option1, option2, byKey);
if (panoSet) {
this.flyToPano({
pano: panoSet,
callback: deferred.resolve.bind(deferred, !0)
} );
} else {
//如果离数据集较远,转动也很难找到点云,就飞到就近点:
if(Potree.settings.displayMode == 'showPointcloud'){
let po = viewer.scene.pointclouds.find(e=>e.visibleNodes.some(a=>a.getLevel() > Math.ceil(e.maxLevel * 0.15) )) //虽然当点云在前方很远的地方也可能符合
if(!po){//无可见点云
//console.log('no visi cloud')
if(!this.panos.length){//如果场景中没有漫游点,如SG-t-XPf1k9pv3Zg 点击后回到可见区域
if(viewer.scene.pointclouds.length == 0)return
let map = new Map()
let clouds = viewer.scene.pointclouds.filter(e=>e.root.geometryNode)
clouds.forEach(e=>map.set(e, e.bound.distanceToPoint(this.position)))
clouds.sort((a,b)=>map.get(a) - map.get(b))
viewer.flyToDataset({focusOnPoint:true, pointcloud:clouds[0], duration:500 })//飞最近的一个点云
return deferred.promise();
}
this.flyToPano({
pano: this.findNearestPano(),
duration:500,
callback: deferred.resolve.bind(deferred, !0)
});
return deferred.promise();
}
}
this.bump(direction);
deferred.resolve(!1);
}
return deferred.promise();
}
closestPanoInDirection(direction, option1, option2, byKey) {
return this.rankedPanoInDirection(0, direction, option1, option2, byKey)
}
rankedPanoInDirection(t, direction, option1, option2, byKey){
//此direction为mouseDirection,是否需要加上相机角度的权重
let startTime = Date.now()
var panoSet = {
pano: null,
candidates: [] //缓存顺序--如果需要打印的话
};
t || (t = 0);
option1 = void 0 !== option1 ? option1 : 0.6 //.75; 2024.3.22改小,也就是可以走的角度范围增加,主要针对像山野那种很大的场景,不知道可以走哪,容易因角度范围内无近点而飞到远处的情况。但不能太小,总是横着走路
var o = option2 ? "angle" : "direction";
var floor = viewer.modules.SiteModel.currentFloor;
var entity = viewer.modules.SiteModel.inEntity;
var getHeightDis = (pano)=>{
if(floor && !floor.panos.includes(pano) && pano.position.z < this.position.z){ //若是上方的漫游点,就正常走。因为一般不会点击天花板。
return this.position.z - pano.position.z
}else{
return 0
}
}
let disSquareMap = new Map()
this.panos.forEach(pano=>{
let dis2 = pano.position.distanceToSquared(this.position); //距离目标点
disSquareMap.set(pano, dis2)
})
let changeTexCount = 0, maxWaitDur = 300
//maxSamplerChangeTex = THREE.Math.clamp( maxWaitDur / Potree.timeCollect.depthSampler.median, 2, 10) //计算换贴图最大数目
var request = [//必要条件
Images360.filters.not(this.currentPano),
Images360.filters.isEnabled(),
//Images360.filters.inFloorDirection( this.position, direction, option1 ), //原先用inPanoDirection,但容易穿楼层,当mouse较低或较高 //因不束缚纵向所以可能往相反反向
(pano)=>{
/* let isNeighbour = this.isNeighbour(this.currentPano, pano, true, true); //不计算的
if(isNeighbour == void 0){
let willChangeTex = pano.depthTex && !this.depthSampler.imgDatas.some(e=>e.pano == pano)
if(changeTexCount < maxSamplerChangeTex || !willChangeTex ){
isNeighbour = this.isNeighbour(this.currentPano, pano, false, true);//计算
if(willChangeTex && isNeighbour != void 0) changeTexCount++
}else{
if(disSquareMap.get(pano) < 500)return true //因为费时,超过一定个数就不计算了,距离近的话先可通行。
}
} */
// 不会再changeTex了
let isNeighbour = this.isNeighbour(this.currentPano, pano, {onlyUseTex:true});
if(isNeighbour || pano.noNeighbour && disSquareMap.get(pano) < 200){//在靠近孤立点时可以通行。但是不好把握这个距离,太远的话很多地方都会不小心到孤立点,太近的话可能永远到不了。
return true
}
},
/* (pano)=>{ //防止不小心穿越地板到下一层, 尽量走楼梯,实在没有楼梯或楼梯漫游点稀疏的话就通过楼层按钮。
let dis = getHeightDis(pano)
//console.log('getHeightDis',pano.id,dis)
if(dis < 3){//不能超过最大高度差( 最大高度差暂定为接近一层楼的高度。)(最好的解决方案是设置漫游可行)
return true
}else{
return this.isNeighbour(this.currentPano, pano)
}
} */
]
if(!byKey){
request.push(Images360.filters.inPanoDirection( this.position, this.getDirection(), option1/* , true */)) //垂直方向上再稍微限制一下, 要接近视线方向,避免点击前方时因无路而到下一楼。但不能太高,否则楼梯上稍微朝下点击都到不了上方。之所以使用视线方向是因为镜头方向比鼠标方向目的性更强。
}
var list = [//决胜项目
(pano)=>{
return -disSquareMap.get(pano)
},
Images360.scoreFunctions[o]( this.position, direction, true),
(pano)=>{
let neighbour = this.isNeighbour(this.currentPano, pano, {dontCompute:true, isNeighbour:true}) //不计算的
return neighbour ? directionFactor : 0;
} ,
/* (pano)=>{//尽量不穿越地板到下一层
let dis = getHeightDis(pano)
return -dis * directionFactor * 0.1;
}, */
/* (pano)=>{ //尽量在一个建筑内行走,这样不易穿墙
let score = 0
if(entity ){
if(!entity.panos.includes(pano) ) score -= directionFactor * 0.01; //不能设置太高,否则会走不进大房间的小房间中,因为容易穿过小房间的一个门到另一个门外
if(!floor.panos.includes(pano)) {//避免穿楼层
let heightDiff = Math.abs(pano.position.z - this.position.z);
if(heightDiff > 2){
score -= directionFactor * 0.1 * heightDiff;
}
}
}
return score
} */
];
if(!byKey && viewer.inputHandler.intersect && this.currentPano ){//方便上下楼, 考虑panos之间的角度差
let pos1 = this.currentPano.floorPosition
let vec1 = new THREE.Vector3().subVectors(viewer.inputHandler.intersect.location, pos1 ).normalize()//应该只有atPano时才会执行到这吧?
list.push( function(pano) {
var pos2 = pano.floorPosition;
var vec2 = pos2.clone().sub(pos1).normalize();
return vec2.dot(vec1) * directionFactor * 4
})
}
this.findRankedByScore(t,request,list,panoSet);
//console.log( 'costTime:',Date.now() - startTime)
return panoSet.pano;
}
findRankedByScore(e, t, i, n) {
n && (n.candidates = null, //candidates 缓存顺序--如果需要打印的话
n.pano = null),
e || (e = 0);
var r = Common.sortByScore(this.panos, t, i);
//console.log('findRankedByScore', r && r.map(u=>u.item.id + '| ' + math.toPrecision(u.score,4) + " | " + math.toPrecision(u.scores,4)))
return !r || 0 === r.length || e >= r.length ? null : (n && (n.candidates = r,
n.pano = r[e].item),
r[e].item)
}
updateClosestPano(intersect, state) {//hover到的pano 大多数时候是null
var pano
if(intersect instanceof Panorama){ //漫游模式
pano = state ? intersect : null
}else{
if(this.isAtPano() || this.bumping){
return
}else{
var filterFuncs = [];
intersect = intersect && intersect.location
if(!intersect)return
let sortFuncs = Potree.settings.editType != 'pano'? [Images360.sortFunctions.floorDisSquaredToPoint(intersect)] : [Images360.sortFunctions.disSquaredToPoint(intersect)]
pano = Common.find(this.panos, filterFuncs, sortFuncs);
}
}
if (pano != this.closestPano) {
pano && (this.isPanoHover = !0);
this.closestPanoChanging(this.closestPano, pano) // 高亮marker
//console.log('closestPano '+ (pano ? pano.id : 'null' ))
this.closestPano = pano;
} else {
this.isPanoHover = !1;
}
}
closestPanoChanging(oldPano, newPano){
if(!Potree.settings.ifShowMarker)return
oldPano && oldPano.hoverOff({byImages360:true})
newPano && newPano.hoverOn({byImages360:true})
}
getTileDirection(){//根据不同dataset的来存储
var vectorForward = viewer.scene.view.direction.clone()
var vectorForwards = viewer.scene.pointclouds.map(e=>{
var inv = new THREE.Matrix4().copy(e.rotateMatrix).invert()//乘上dataset的旋转的反转
var direction = vectorForward.clone().applyMatrix4(inv)
return {
datasetId: e.dataset_id,
direction: math.convertVector.ZupToYup(direction)
}
})
//return vectorForwards[0].direction
return {
datasetsLocal: vectorForwards,
vectorForward
}
}
update(){
//if(this.tileDownloader.started){
var vectorForwards = this.getTileDirection()
//vectorForwards = vectorForwards[0].direction
this.updateTileDownloader(tileArr, vectorForwards);
this.updatePanoRenderer(vectorForwards)
//}
this.updateZoomPano();
}
updateTileDownloader(t, vectorForward) {
var i = this.nextPano || this.currentPano;
if(i){
this.tileDownloader.tilePrioritizer.updateCriteria(i, viewer.scene.view.position.clone() , vectorForward, t.length > 0 ? t : null),
this.tileDownloader.processPriorityQueue = !0
}
}
updatePanoRenderer(vectorForward) {
var i = this.nextPano || this.currentPano;
if(i){
if (this.panoRenderer.hasQueuedTiles() && i) {
this.panoRenderer.updateDirection(vectorForward);
}
}
}
//等待部分加载完
checkAndWaitForTiledPanoLoad(pano, basePanoSize, callback1, callback2, progressCallback, iswait, isclear, l) {
//console.log('checkAndWaitForTiledPanoLoad',pano.id)
if (!pano) {
console.error("Player.checkAndWaitForTiledPanoLoad() -> Cannot load texture for null pano.");
}
var vectorForward = this.getTileDirection()
if (!pano.isLoaded(basePanoSize)) {
iswait && viewer.waitForLoad(pano, function() {//发送loading
return pano.isLoaded(basePanoSize)
});
/* var fov = {//test for direction 预加载的边缘有一丢丢不准确,尤其在相机倾斜时(4dkk也是)。
hFov: cameraLight.getHFOVForCamera(viewer.scene.getActiveCamera() ),
vFov: viewer.scene.getActiveCamera().fov
}//原先是null,不要求方向 */
var fov = null //若不为null的话,因为可能可见范围的tile下载过了从而无法触发下载,然后得不到下载成功的消息,怎么办
pano.loadTiledPano(/* 1024 */ basePanoSize , vectorForward, fov, isclear, l, null).done(function(e, t) {
callback1 && callback1(e, t)
}
.bind(this)).fail(function(msg) {
callback2 && callback2(msg)
}
.bind(this)).progress(function(e, t, i) {
progressCallback && progressCallback(e, t, i)
}
.bind(this));
return !0;
}
}
fitPanoTowardPoint(o){ //寻找最适合的点位
var point = o.point, //相机最佳位置
target = o.target || o.point, //实际要看的位置
require = o.require || [],
rank = o.rank || [],
force = o.force,
getAll = o.getAll,
bestDistance = o.bestDistance || 0,
sameFloor = o.sameFloor,
maxDis = o.maxDis,
dir = o.dir
let camera = viewer.scene.getActiveCamera()
if(target && !dir){
dir = new THREE.Vector3().subVectors(target,point).normalize()
}
let atFloor = sameFloor && viewer.modules.SiteModel.pointInWhichEntity(point, 'floor')
//if(o.floor)require.push(Panorama.filters.atFloor(o.floor))
let checkIntersect = o.checkIntersect
let base = Math.max(300, viewer.bound.boundSize.length()*3);
if(o.boundSphere){//只接受boundSphere
let aspect = 1//size.x / size.y
let dis
if(camera.aspect > aspect){//视野更宽则用bound的纵向来决定
dis = /* size.y */o.boundSphere.radius/* / 2 *// THREE.Math.degToRad(camera.fov / 2)
}else{
let hfov = cameraLight.getHFOVForCamera(camera , true );
dis = /* size.x */ o.boundSphere.radius /* / 2 */ / (hfov / 2)
}
bestDistance = dis//*0.8
}
let disSquareMap = new Map()
let bestDisSquared = bestDistance * bestDistance
let maxDisSquared = maxDis && (maxDis * maxDis)
this.panos.forEach(pano=>{
let dis2 = pano.position.distanceToSquared(target); //距离目标点
disSquareMap.set(pano, dis2)
})
let panos = this.panos.sort((p1,p2)=>{return disSquareMap.get(p1)-disSquareMap.get(p2)})
if(maxDisSquared){//热点超过最大距离不可见的
let panos2 = [], pano, i=0
while(pano = panos[i], disSquareMap.get(pano) < maxDisSquared){
panos2.push(pano)
i++;
}
if(panos2.length == 0)return {pano, msg:'tooFar'} //全部都大于maxDis, 就返回最近的
panos = panos2
}
rank.push((pano)=>{
let dis1 = Math.abs(pano.position.distanceToSquared(point) - bestDisSquared); //距离最佳位置
disSquareMap.set(pano, dis1)
if(!target){
return -dis1
}else{
let dis2 = disSquareMap.get(pano)
if(o.gotoBestView){//忽略和当前视线的角度
return -(dis1 + dis2*0.3)
}
let vec2 = new THREE.Vector3().subVectors(target,pano.position).normalize()
let cos = dir.dot(vec2)
//let result = (- dis1 - Math.pow(dis2 , 1.5)) / (cos + 2) // cos+2是为了调整到1-3,
let result = (dis1 + dis2*0.3) * ( -1 + cos*0.9 ) //尽量贴近最佳位置的角度, 或贴近相机原来的角度 。尽量靠近最佳观测点,并且优先选择靠近目标点的位置.(注意cos的乘数不能太接近1,否则容易只考虑角度)
//Potree.Log(pano.id, dis1, dis2, cos, result,{font:{toFixed:2,fontSize:10}})
return result
}
//注:热点最好加上法线信息,这样可以多加一个限制,尽量顺着热点像展示的方向。
},
(pano)=>{
let score = 0
if(pano.depthTex && checkIntersect){
let intersect = !!viewer.ifPointBlockedByIntersect(target, pano.id, true) //viewer.inputHandler.ifBlockedByIntersect({point:target, margin:0.1, cameraPos:pano})
if(intersect){
score = 0
}else {
score = base * 2
}
}else{
score = base * 1.5 //没加载好的话,不管了 , 几乎当做无遮挡,否则容易到不了最近点
}
return score
}
)
var g = Common.sortByScore(panos, require, rank);
// console.log(g)
/* let result1 = g && g.slice(0, 10)
if(result1){
g = Common.sortByScore(result1, [], [(e)=>{//避免遮挡
let pano = e.item;
let score = 0, log = ''
if(atFloor && atFloor.panos.includes(pano)){//如果不在任何一楼呢?
score += 600, log+='atFloor'
}
return {score, log}
}]);
if(g){
g.forEach(e=>{e.item = e.item.item})
}
console.log(g)
} */
let pano = g && g.length > 0 && g[0].item
if(pano && checkIntersect){
let intersect = !!viewer.ifPointBlockedByIntersect(target, pano.id, true)
if(intersect){
return {pano, msg : 'sheltered'}
}
}
//if(getAll)return g;
return pano
//注:深度图有的位置会不准确,以至于会算出错误的遮挡、选择错误的pano,解决办法只能是移动下热点到更好的位置
}
//---------------scroll zoom ------------------------------------------
/* zoomIn = function() { //放大
this.zoomBy(1 + this.zoomSpeed);
}
zoomOut = function() {//缩小
this.zoomBy(1 - this.zoomSpeed);
} */
zoomBy(e, pointer) {//以倍数
this.zoomTo(this.zoomLevel * e, pointer);
}
zoomTo(zoomLevel, pointer) {//缩放到某绝对zoomLevel
let zoom = Potree.settings.zoom
if (zoom.enabled) {
zoomLevel = THREE.Math.clamp(zoomLevel, zoom.min, zoom.max)
//console.log(zoomLevel)
if(zoomLevel == this.zoomLevel) return;
this.zoomLevel = zoomLevel;
if(Potree.settings.panoZoomByPointer){
//定点缩放:使当前鼠标所在的位置缩放后不变
let view = viewer.scene.view
let originDir = viewer.scene.view.direction;
let oldPointerDir = viewer.inputHandler.getMouseDirection(pointer).direction
viewer.setFOV(Potree.config.view.fov * (1 / this.zoomLevel))
let newPointerDir = viewer.inputHandler.getMouseDirection(pointer).direction
view.direction = oldPointerDir; //获取一下鼠标所在位置的yaw 和 pitch
let oldPitch = view.pitch, oldYaw = view.yaw;
view.direction = newPointerDir;
let newPitch = view.pitch, newYaw = view.yaw;
view.direction = originDir //还原
viewer.scene.view.pitch -= newPitch - oldPitch
viewer.scene.view.yaw -= newYaw - oldYaw
}else{
viewer.setFOV(Potree.config.view.fov * (1 / this.zoomLevel))
}
}
}
zoomFovTo( fov ) { //通过fov来算zoomLevel
let zoomLevel = Potree.config.view.fov /* this.baseFov */ / fov;
this.zoomTo( zoomLevel );
}
smoothZoomTo(aimLevel, dur=0) {
var currentLevel = this.zoomLevel
if(currentLevel == aimLevel)return;
var fun = (progress)=>{
//progress > 1 && (progress = 1)
let level = currentLevel * (1 - progress) + aimLevel * progress
this.zoomTo(level, !0)
}
transitions.start(fun, dur, null, null, 0 , easing['easeInOutQuad'] )
}
updateZoomPano() {
if (!this.panoRenderer.zoomPanoRenderingDisabled && Potree.settings.displayMode == 'showPanos') {
var currentPano = this.currentPano;
if (currentPano) {
let levelThreshold1 = Potree.settings.navTileClass == '1k' ? 1.3 : 1.7 , levelThreshold2 = 2
var t = this.zoomLevel > levelThreshold1,
n = !(this.flying && this.nextPano && this.nextPano !== this.currentPano),
r = t && n;
this.tileDownloader.tilePrioritizer.setZoomingActive(r);
this.panoRenderer.setZoomingActive(r, currentPano, !0);
var o = (pano, ifZoom)=>{
this.panoRenderer.resetRenderStatus(pano.id, !1, !0, this.qualityManager.getMaxNavPanoSize());
this.panoRenderer.clearAllQueuedUploadsForPano(pano.id);
this.panoRenderer.renderPanoTiles(pano.id, null, !1, !1);
pano.setZoomed(ifZoom);
}
if (r && (!currentPano.zoomed || this.qualityManager.zoomLevelResolution && this.qualityManager.zoomLevelResolution != '4k')) {//needZoom
currentPano.zoomed || o(currentPano, !0);
if(Potree.settings.navTileClass == '1k' && Potree.settings.tileClass != '1k' && this.zoomLevel < levelThreshold2){
this.panoRenderer.enableHighQuality( function() {//开启2k
if(Potree.settings.tileClass != '4k') o(currentPano, !0);
}.bind(this));
}else{
this.panoRenderer.enableUltraHighQualityMode(function() {//开启4k getMaxZoomPanoSize
this.qualityManager.useUltraHighResolutionPanos && (Potree.settings.zoom.max = Potree.config.ultraHighQualityMaxZoom);
o(currentPano, !0)
}.bind(this));
}
} else {
!t && currentPano.zoomed && o(currentPano, !1);
}
if(r && Potree.settings.navTileClass == '1k' && Potree.settings.tileClass == '4k' ){ //目前只有手机端navTileClass == '1k' (分三个梯度)
var change = (zoomedFlag)=>{
this.qualityManager.updateMaximums()//更新maxZoomPanoSize
this.panoRenderer.setupZoomRenderTarget() //更新renderTarget
//currentPano.setZoomed(t);//更新uniforms贴图
}
this.qualityManager.zoomLevelResolution = this.zoomLevel >= levelThreshold2 ? '4k' : this.zoomLevel > levelThreshold1 ? '2k' : '1k'
if(this.oldZoomLevel < levelThreshold2 && this.zoomLevel >= levelThreshold2){//1k/2k-4k
change()
o(currentPano, t)
}else if(this.oldZoomLevel <= levelThreshold1 && this.zoomLevel > levelThreshold1){//1k-2k
change()
}else if(this.oldZoomLevel > levelThreshold2 && this.zoomLevel <= levelThreshold2){//4k-2k/1k
change()
o(currentPano, t)
}else if(this.oldZoomLevel > levelThreshold1 && this.zoomLevel <= levelThreshold1){//2k-1k
change()
}
this.oldZoomLevel = this.zoomLevel
}
}
}
}
//--------------------
addHighMapCube(){//创建8*8的tile cube 主要因手机版崩溃 要在电脑端测试得设置maxRenderTargetSize
if( Potree.settings.tileClass == '4k' && this.qualityManager.maxRenderTargetSize == 2048){
var geo = new THREE.PlaneGeometry(1, 1, 1, 1)
var cube = new THREE.Object3D;
cube.tiles = []
for(var cubeIndex=0; cubeIndex<6; cubeIndex++){
var face = new THREE.Object3D;
for(var i=0;i<8;i++){
for(var j=0;j<8;j++){
var tile = new THREE.Mesh(geo, new THREE.MeshBasicMaterial({
//side:THREE.DoubleSide
transparent:true,
opacity : 0.4,
depthTest:false,
}))
tile.position.set(i-3.5, j-3.5, -4);
if(Potree.settings.isTest){
var colorHue = Math.random();
tile.material.color = (new THREE.Color()).setHSL(colorHue, 0.6, 0.7)
/* tile.scoreLabel = new TextSprite( {
backgroundColor: { r: 0, g: 0, b: 0, a: 0 },
textColor: { r: 0, g: 0, b: 0, a: 1 },
borderRadius: 15,
renderOrder: 50, fontsize : 13,
text: '' ,
dontFixOrient:true
})
tile.scoreLabel.sprite.material.side = 2;
tile.scoreLabel.rotation.x = Math.PI
tile.add(tile.scoreLabel) */
}
tile.visible = false
tile.tileX = i
tile.tileY = j
tile.cubeFace = cubeIndex
//tile.renderOrder = RenderOrder.highTileCube
cube.tiles.push(tile)
face.add(tile)
}
}
switch(cubeIndex){
case GLCubeFaces.GL_TEXTURE_CUBE_MAP_POSITIVE_X:
face.rotation.set(0,Math.PI/2,0);
break;
case GLCubeFaces.GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
face.rotation.set(0,-Math.PI/2,0);
break;
case GLCubeFaces.GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
var rot1 = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,1,0),Math.PI)
var rot2 = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1,0,0),Math.PI/2)
face.quaternion.copy(rot1).multiply(rot2)
//face.rotation.set(Math.PI/2,0,0);
break;
case GLCubeFaces.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
//face.rotation.set(-Math.PI/2,0,0);
var rot1 = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,1,0),Math.PI)
var rot2 = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1,0,0),-Math.PI/2)
face.quaternion.copy(rot1).multiply(rot2)
break;
case GLCubeFaces.GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
face.rotation.set(0,Math.PI,0);
break;
case GLCubeFaces.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
face.rotation.set(0,0,0);
}
face.scale.set(1,-1,1)
face.cubeFace = cubeIndex
cube.add(face)
}
cube.name = 'highMapCube'
this.highMapCube = cube
viewer.scene.scene.add(cube)
{
let s = 0.1
cube.scale.set(s,s,s)
}//注:由于原本的mesh上加了深度贴图,可能距离镜头比这里的近。凡是在cube以内的部分都会挡住cube导致模糊。但是应该不常见吧(另外到天空的边缘也是很近)。姑且depthTest=false
this.highMapCube.visible = false;
Potree.Utils.setObjectLayers(this.highMapCube, 'sceneObjects'/* 'skybox' */) //因它的深度是错误的,故不在skybox层渲染,影响edlRT, 而在renderOverlay时渲染覆盖。
//console.warn('addHighMapCube')
viewer.addEventListener('update',()=>{
if (this.highMapCube.visibleTiles) {
this.updateTiles() //逐步将visibleTiles加载完
}
})
viewer.addEventListener('camera_changed',(e)=>{
if(e.viewport == viewer.mainViewport){
//重新获取visibleTiles
Common.intervalTool.isWaiting(
'update4kTiles',
() => {
let vectorForward = this.getDirection()
this.updateTiles(vectorForward)
},
500
)
}
})
}
}
isHighMapLoaded( cubeFace, tileX, tileY){
var tile = this.highMapCube.children[cubeFace].children[tileX*8+tileY];
return !!tile.material.map
}
updateTiles(direction) {
if (!this.highMapCube || !this.highMapCube.visible) return
if (this.highMapCube.tiles.filter(e => e.image).length <= 10) return //加载的太少了
//performance.mark('updateTiles-start')
if (direction) {
let camera = viewer.mainViewport.camera
let hfov = cameraLight.getHFOVForCamera(camera, true) / 2
let vfov = THREE.MathUtils.degToRad(camera.fov) / 2
/* let hcos = Math.cos(hfov / 2)
let vcos = Math.cos(vfov / 2) */
let list = this.highMapCube.tiles
list.forEach(e => {
//屏幕外的不显示
let pos = e.getWorldPosition(new THREE.Vector3())
let dir = new THREE.Vector3().subVectors(pos, this.highMapCube.position).normalize()
let hcos_ = dir.clone().setZ(direction.z).normalize().dot(direction) //在direction的斜面上水平角度差
let hRad = Math.acos(hcos_)
let vRad = -200
if (/* hRad > hfov + 0.08 */ hRad / hfov > 1.5 ) {
e.score = -100
} else {
vRad = Math.abs(Math.acos(dir.z) - Math.acos(direction.z))
if (/* vRad > vfov + 0.08 */ vRad / vfov > 1.5 ) {
e.score = -100
} else {
e.score = -(hRad / hfov + vRad / vfov)
}
}
e.scores = hRad.toFixed(3) + ', ' + vRad.toFixed(3)
if (e.score == -100) {
this.resetTile(e)
}
})
this.highMapCube.visibleTiles = list.filter(e => e.score > -100)
//list.forEach(e=>e.scoreLabel.setText(e.scores))
}
let needRecover = this.highMapCube.visibleTiles.filter(e => !e.material.map)
if (needRecover.length) {
let maxCount = Common.getBestCount( '4kmaxTileRecover', 0, 2, 1.5, 6, false, 2 )
let count = 0
console.log(maxCount)
needRecover.forEach((e, i) => {
//只更新若干个,因为太耗时了, 其余的等下帧更新
if (count >= maxCount) return
let r = this.recoverTile(e)
if (r) count++
})
}
}
getHighImage(image, cubeFace, tileX, tileY) {
let tile = this.highMapCube.children[cubeFace].children[tileX * 8 + tileY]
tile.image = image //先记录下来
}
updateHighMap(image, cubeFace, tileX, tileY){
//console.warn('updateHighMap')
var tile = this.highMapCube.children[cubeFace].children[tileX*8+tileY];
if (image) tile.image = image //先记录下来
if(tile.material.map)return
if (this.highMapCube.visibleTiles && !this.highMapCube.visibleTiles.includes(tile) /* this.highMapCube.texLoadedCount >= this.getMaxTileCount() */) {
return
}
//简易创建贴图
/* var tex = this.$app.core.get('SceneRenderer').initSizedTexture2D(512, THREE.ClampToEdgeWrapping)
//var loaded = this.$app.core.get('Player').model.isHighMapLoaded(tile.cubeFace, tile.tileX, tile.tileY)
this.$app.core.get('SceneRenderer').uploadTexture2D(image, tex, 0, 0, 512, 512) //只替换tex对应的img,不新建
*/
var tex = new THREE.Texture()
tex.image = image
tex.flipY = false
tex.wrapS = tex.wrapT = THREE.ClampToEdgeWrapping
tex.generateMipmaps = false
tex.minFilter = THREE.LinearFilter
tex.needsUpdate = true
tile.material.map = tex;
tile.material.opacity = 1;
tile.material.transparent = false
tile.visible = true
tile.material.needsUpdate = true //发现每次开始放大但还未放大到4k时也会把之前加载过的4k加载
}
recoverTile(tile) {
if (tile.material.map) return
if (tile.image) {
this.updateHighMap(tile.image, tile.cubeFace, tile.tileX, tile.tileY)
return true
} else {
//console.log('no image')
}
}
resetTile(tile, kill) {
if (kill) {
//完全消灭
tile.image = null
}
let map = tile.material.map
if (map) {
map.dispose() //这句执行了以后,h.__webglTexture一直就是undefined
map.loaded = !1
map.version = 0
//保底再执行一下这个,类似app.sceneRenderer.deallocateCubeTexture(tile.material.map)
var h = viewer.renderer.properties.get(map)
//console.log('__webglTexture',!!h.__webglTexture)
viewer.renderer.getContext().deleteTexture(h.__webglTexture)
tile.material.map = null
tile.material.needsUpdate = true
tile.visible = false
//this.highMapCube.texLoadedCount --
//console.log('resetTile'/* , tile.cubeFace, tile.tileX, tile.tileY */)
}
}
resetHighMap() {
if (!this.highMapCube) return
this.highMapCube.children.forEach(e =>
e.children.forEach(tile => {
this.resetTile(tile, true)
})
)
//this.highMapCube.texLoadedCount = 0
this.highMapCube.visibleTiles = null
this.hideHighMap()
//console.log('resetHighMap')
}
setHighMap(pano){
if(!this.highMapCube) return
this.highMapCube.position.copy(pano.position)
//可以利用第0个pano查看,其 rotation4dkk是(_x: 0, _y: -1.5707963267948966, _z: 0 )而手动旋转至(_x:1.5707963, _y: -1.57079, _z: 0)时才正确,说明要在4dkk的旋转基础上,绕x轴转90度,(也就是转成navvis坐标系), 然后得到YupToZup的函数写法的
this.highMapCube.quaternion.copy( math.convertQuaternion.YupToZup( pano.quaternion4dkk ) )
//乘上数据集整体的旋转:
let modelRotQua = new THREE.Quaternion().setFromRotationMatrix(pano.pointcloud.rotateMatrix)
this.highMapCube.quaternion.premultiply(modelRotQua)
}
showHighMap(){
if(!this.highMapCube) return
//console.warn('showHighMap')
this.highMapCube.visible = true;
}
hideHighMap(){
if(!this.highMapCube) return
//console.warn('hideHighMap')
this.highMapCube.visible = false;
}
//缩小后继续显示cube呢还是不显示? 不显示的话,就要把cube上的复制到renderTarget上……会不会又崩溃,or没加载的显示???
addPanoData(data, datasetId ){//加载漫游点
//data[0].file_id = '00019'
if(data.data) data = data.data
if(data.length == 0)console.error(datasetId + ' 没有漫游点')
//data = data.sort(function(a,b){return a.id-b.id})
data.forEach((info)=>{
//if(Potree.fileServer){
info.id = this.panos.length //把info的id的一长串数字改简单点
//}
let pano = new Panorama( info, this );
pano.addEventListener('dispose',(e)=>{
if(this.closestPano == pano) this.closestPano = null
})
this.panos.push(pano);
if(Potree.settings.editType == 'pano'){
Potree.settings.datasetsPanos[datasetId].panos.push(pano);
}
})
}
loadDone(){
Potree.Utils.setObjectLayers(this.node, 'sceneObjects')
//this.updateCube(/* viewer.bound */)
this.panos.forEach(e=>{
this.neighbourMap[e.id] = {}
e.label && Potree.Utils.setObjectLayers(e.label, 'bothMapAndScene')
e.label2 && Potree.Utils.setObjectLayers(e.label2, 'bothMapAndScene')
})
this.tileDownloader.setPanoData(this.panos, [] /* , Potree.settings.number */);
{
let minSize = new THREE.Vector3(1,1,1)
this.bound = math.getBoundByPoints(this.panos.map(e=>e.position), minSize)
viewer.scene.pointclouds.forEach(pointcloud=>pointcloud.getPanosBound())
}
if(viewer.scene.pointclouds.some(e=>e.panos.length == 0)){
//console.warn('存在数据集没有pano');
viewer.hasNoPanoDataset = true
}
}
getPano(value, typeName='id'){ //默认找的是id,也可以是sid、uuid
return this.panos.find(p=>p[typeName] == value)
}
};
//判断当前点是否加载了全景图
Images360.prototype.checkAndWaitForPanoLoad = function() {
var isLoadedPanos = {},
LoadedTimePanos = {},
loadedCallback = {}, //add
maxTime = 5e3;
var withinTime = function() {
for (var panoId in isLoadedPanos)
if (isLoadedPanos.hasOwnProperty(panoId) && isLoadedPanos[panoId]) {
var differTime = performance.now() - LoadedTimePanos[panoId];
if (differTime < maxTime)
return !0
}
return !1
}
return function(pano, basePanoSize, doneFun1, doneFun2, progressCallback, iswait, isclear, p ) {
loadedCallback[pano.id] = doneFun1//add 因为有可能之前请求的没加doneFun1, 如果加载好就执行最新的doneFun1
if (withinTime()){//距离上次请求时间很近
//console.log(11)
return !0; //这里感觉应该是!1
}
let changeMode = (e)=>{
if(e.mode == 'showPointCloud'){
console.warn('切到点云模式了,就删除loadedCallback记录',pano.id)//否则再次转为showPanos会被withinTime阻拦
delete isLoadedPanos[pano.id]
viewer.cancelLoad(pano)
loadedCallback[pano.id] && loadedCallback[pano.id](); //可以飞行了
doneFun2 && doneFun2();
this.removeEventListener('requestMode', changeMode)
}
}
this.addEventListener('requestMode', changeMode)
var callback1 = (param1, param2)=>{
setTimeout(()=>{
isLoadedPanos[pano.id] = !1;
loadedCallback[pano.id] && loadedCallback[pano.id](param1, param2);
this.removeEventListener('requestMode', changeMode)
},1)
}
var callback2 = (param)=>{//没有看到有传doneFun2的
setTimeout(()=>{
isLoadedPanos[pano.id] = !1;
doneFun2 && doneFun2(param);
},1)
}
try {
null !== iswait && void 0 !== iswait || (iswait = !0);
isLoadedPanos[pano.id] = this.checkAndWaitForTiledPanoLoad(pano, basePanoSize, callback1, callback2, progressCallback, iswait, isclear, p );
//true代表没加载好
isLoadedPanos[pano.id] && (LoadedTimePanos[pano.id] = performance.now());
return isLoadedPanos[pano.id];
} catch (msg) {
isLoadedPanos[pano.id] = !1;
LoadedTimePanos[pano.id] = performance.now() - maxTime;
throw msg;
}
}
}()//加载全景图的流程:请求下载当前点的最低分辨率图(不过有可能已经下载了),并且请求uploadTile渲染当前漫游点,若tile都upload完(先6个)会发送消息,LoadComplete 从而回调成功。
Images360.prototype.getNeighbours = function(){ //逐渐自动获取neighbours。 200个点差不多在半分钟内算完
let lastIndex, inited//标记上次查询到哪,防止重新sortByScore
return function( interacted){
if(!this.currentPano || viewer.mainViewport.view.isFlying() || viewer.lastFrameChanged || viewer.inputHandler.drag /* interacted */){ //拖拽时不更新,否则移动端卡
return lastIndex = 0;
}
let nearPanos = this.tileDownloader.tilePrioritizer.nearPanos;
if(!nearPanos)return;
//let startTime = Date.now()
let panos = [this.currentPano, ...nearPanos ]
this.depthSampler.updateNearPanos(panos)
let maxWaitDur = browser.isMobile() ? 40 : 60
let changeCount = 0, maxChangeTex = browser.isMobile() ? 1 : 3, getCount = 0
let changeTexCount = ()=>{
changeCount ++;
}
let median = Potree.timeCollect.depthSamChangeImg.median
let ifOverTime = ()=>{
let is = changeCount >= maxChangeTex || changeCount * median + getCount * 0.01 > maxWaitDur//不换贴图也要一丢丢计算时间
/* if(is){
console.log('OverTime, changeCount', changeCount)
} */
return is
}
this.depthSampler.addEventListener('changeImg', changeTexCount)
outer: for(let i=lastIndex,j=panos.length; i0)break; //点云的情况下最好不改相机位置,因为其他位置点云还没加载完,所以不判断当前点以外的漫游点
var g = Common.sortByScore(others, [ ], [
Images360.scoreFunctions.distanceSquared(pano.position)
]);
for(let a=0, b=g.length; a{
//console.log('loadedDepthImg',e.pano)
lastIndex = 0 //主要针对刚打开场景第一个点有杂点时单向不成功,要立即进一步双向计算ifShelter
})
}
/* let costTime = Date.now() - startTime
costTime > maxWaitDur && console.log( 'costTime:',costTime) */
}
}()
Images360.filters = {
inPanoDirection : function(pos, dir, i, log) { //pano在mouse的方向上
return function(pano) {
var r = pano.floorPosition.clone().sub(pos).normalize()
var o = pano.position.clone().sub(pos).normalize()
log && console.log('dire',pano.id, r.dot(dir), o.dot(dir) )
return r.dot(dir) > i || o.dot(dir) > i
}
},
inFloorDirection: function(pos, dir, min, log) { //pano在mouse的水平方向上
return function(pano) {
var vec = new THREE.Vector2().subVectors(pano.floorPosition, pos).normalize()
var dir_ = new THREE.Vector2().copy(dir).normalize()
log && console.log('dire', pano.id, vec.dot(dir_) )
return vec.dot(dir_) > min
/* var i = pano.floorPosition.clone().sub(pos).setZ(0).normalize();//改成在xz方向上,否则点击墙面不会移动
return i.dot(dir.clone().setZ(0)) > min */
}
},
isNotBehindNormal: function(e, t) {
var i = new THREE.Vector3;
return t = t.clone(),
function(n) {
var r = i.copy(n.position).sub(e).normalize();
return r.dot(t) > 0
}
},
isCloseEnoughTo: function(e, t) {
return function(i) {//因为marker可能比地面高,所以识别范围要比marker看起来更近一些。(因为投影到地板的位置比marker更近)
return e.distanceTo(i.floorPosition) < t //许钟文
}
},
not: function(e) {
return function(t) {
return t !== e
}
} ,
isEnabled:function() {
return function(t) {
return t.enabled
}
},
isVisible:function() {
return function(t) {
return t.visible
}
}
}
Images360.scoreFunctions = {
direction: function(curPos, dir, ifLog) {
return function(pano) {
var pos1 = /* pano.floorPosition */ pano.position //旧:改为权重放在marker上,这样对有斜坡的更准确,如上楼, 但这样近距离的pano角度就会向下了,以致于走不到
var n = pos1.clone().sub(curPos).normalize();
//ifLog && console.log('direction', pano.id, n.dot(dir) * directionFactor )
return n.dot(dir) * directionFactor
}
},
distance: function(pos1, r=1, ifLog) {
if(pos1.position)pos1 = pos1.position
return function(pano) {//许钟文 改
var pos2 = pano.position.clone()
//ifLog && console.log('distance', pano.id, pos1.distance(pos2) * -1 )
return pos1.distanceTo(pos2) * -1 * r;
}
},
distanceSquared: function(pos1, r=1 ) {
if(pos1.position)pos1 = pos1.position
return function(pano) {//许钟文 改
var pos2 = pano.position.clone()
return pos1.distanceToSquared(pos2) * -1 * r;
}
},
angle: function(e, t) {
return function(i) {
var n = i.position.clone().sub(e).normalize();
return n.angleTo(t) * Potree.config.navigation.angleFactor
}
},
}
Images360.sortFunctions = {//排序函数,涉及到两个item相减
floorDisSquaredToPoint: function(e) {
return function(t, i) {
return t.floorPosition.distanceToSquared(e) - i.floorPosition.distanceToSquared(e)
}
},
disSquaredToPoint: function(e) {
return function(t, i) {
return t.position.distanceToSquared(e) - i.position.distanceToSquared(e)
}
},
}
Images360.prototype.updateCube = (function(){//增加细分的版本,且垂直方向上取中位数 侧边多条
const minDis = 0.2; //pano和墙距离不能小于相机的near
const height = 1 //准确计算的话要分别计算两个pano的地面、天花板之间的俯仰角,和pano之间的还不一样。这里统一假设一个比较小的高度,因高度越大 maxSinAlpha 越大
let minTanBeta = minDis / height /* (pano0.position.z - pano0.floorPosition.z) */
let minBeta = Math.atan(minTanBeta)
const maxSinAlpha = Math.cos(minBeta) // 注:beta = Math/2 - alpha
const skyHeight = 50
return function(pano0, pano1){
if(Potree.settings.displayMode != 'showPanos' || pano0 == pano1
|| this.cubePanos.includes(pano0) && this.cubePanos.includes(pano1)
) return
this.cubePanos = [pano0, pano1]
viewer.addTimeMark('updateCube','start')
//console.log('updateCube',pano0.id, pano1&&pano1.id)
let useBound = (bound, size)=>{
size = size || bound.getSize(new THREE.Vector3)
let center = bound.getCenter(new THREE.Vector3)
size.max(new THREE.Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth))
this.cube.geometry = new THREE.BoxBufferGeometry(1,1,1,1)
this.cube.scale.copy(size)
this.cube.position.copy(center)
if(Potree.settings.testCube){
this.cubeTest.geometry = this.cube.geometry
this.cubeTest.scale.copy(size)
this.cubeTest.position.copy(center)
}
return 'useBound'
}
let getPanoBound = (pano, dis)=>{//因漫游点可能在点云外部,如室外平地,所以需要union进漫游点
let panoBound = new THREE.Box3
panoBound.expandByPoint(pano.position)
let margin = dis ? Math.max(dis * 0.1, 10) : 10
panoBound.expandByVector(new THREE.Vector3(margin,margin,margin)); //give pano a margin 。 随着bound扩大,margin要相应扩大,否则当距离很远时看起来就像没有
return pano.pointcloud.bound.clone().union(panoBound)
}
this.cube.geometry.dispose();
if(pano1){//过渡
let dontAddSides
let dis = pano0.position.distanceTo(pano1.position)
if(dis == 0)return
let sinAlpha = Math.abs(pano0.position.z - pano1.position.z) / dis //俯仰角的sin,随角度增大而增大 0-1
let score = (1+sinAlpha*20) * dis //score越大创建的mesh越不适合
let isNeighbour = this.isNeighbour(pano0, pano1)
//console.log(pano0.id, pano1.id, maxSinAlpha.toFixed(2), sinAlpha.toFixed(2), score.toFixed(2), isNeighbour)
if(sinAlpha>maxSinAlpha || !pano0.pointcloud.hasDepthTex || !pano1.pointcloud.hasDepthTex || (isNeighbour ? score > 100 : score > 50 ) ){
let bound = getPanoBound(pano0, dis).union(getPanoBound(pano1, dis))
let size = bound.getSize(new THREE.Vector3)
let max = Math.max(size.x, size.y, size.z)
size.set(max,max,max) //距离太远的数据集,过渡会畸变。所以扩大skybox,且为立方体
return useBound(bound, size)
}else if( isNeighbour ? score > 70 : score > 15 ){
dontAddSides = true //pano间有阻挡时得到的side点可能使通道变窄,所以去掉。
}
//俯仰角增大时可能不在同一楼层,算出来的mesh不太好,所以更倾向直接使用cube,或去除side。
let half = browser.isMobile() ? 4 : 8 //自行输入 (点云计算的慢,还不准)
let count1 = 2*half//偶数个 每个pano向 外dir 个数
//奇数个的好处:在窄空间内能探测到最远距离,坏处是前方有尖角。偶数个的坏处就是可能检测距离太近。
let getDir = (angle_, vec)=>{ //旋转获得水平向量
let rotMat = new THREE.Matrix4().makeRotationZ(angle_)
return vec.clone().applyMatrix4(rotMat)
}
let getFar = (dir, pano, origin, height)=>{//获取在这个方向上和墙体intersect的距离
//在垂直方向上分出多个方向,取一个最可能的接近真实的距离
let maxH = 40, minH = 2, minR = 0.5, maxR = 2
height = height == void 0 ? Math.min(skyHeight, pano.ceilZ - pano.floorPosition.z) : height
//let r = height (maxH - minH)* 0.14 // 高度越小,角度越小
//let r = minR + ( maxR - minR) * THREE.Math.clamp((height - minH) / (maxH - minH),0,1) //THREE.Math.smoothstep(currentDis, op.nearBound, op.farBound);
let r = math.linearClamp(height, [minH,maxH], [minR, maxR])
let getZ = (deg)=>{
deg *= r
deg = THREE.Math.clamp(deg, 1, 80);
return Math.tan(THREE.Math.degToRad(deg))
}
let dirs_ //注意:角度太大会碰到天花板或地板,越远越容易碰到, 在地下停车场就会伸展不开。 更多取接近0度的,否则围墙矮一点就会取到远处。
dirs_ = [15, 8, 3, -1, -5]
dirs_ = dirs_.map(deg=> dir.clone().setZ(getZ(deg)).normalize() )
let max = 50
let count2 = dirs_.length
let disArr = dirs_.map((dir_, i) =>{
let intersect = this.getIntersect(pano, dir_, origin)
let projectLen = intersect && intersect.distance ? dir_.dot(dir)*intersect.distance : max; //得到project在dir的长度
return projectLen //得水平距离
})
//console.log(pano ? pano.id : 'side','disArr', disArr.slice(0))
disArr.sort((a,b)=>{return b-a}); //从大到小
//console.log(pano ? pano.id : 'side','disArr', disArr)
let dis = disArr[Math.floor(count2/2-0.5)] //对半、取前(中位数)
return dis
}
let sideCount = [0,0]
let addPos = (pano, vec )=>{//添加这个pano这一侧向外半圆的顶点
//添加pano位置对应的最高点最低点:
let minZ, maxZ
minZ = pano.floorPosition.z
maxZ = pano.getCeilHeight()
if(maxZ == Infinity) maxZ = skyHeight + pano.position.z; //maxZ = Math.max(skyHeight, maxZ)
[maxZ, minZ ].forEach(z=>{
posArr.push(pano.position.clone().setZ(z))
})
//在画面上线条从左往右数
const angle = Math.PI/(count1-1)
const dirs = []; //平分这半边180度
for(let i=0;i{
return {
dir,
dis: getFar(dir, pano)
}
})
//剔除那些突然间离相机很近的dir。有可能是拍摄的人、或者杆子、树
/* dirs2.forEach((e,i)=>{
console.log(i, e.dis)
let smallThanBefore = ()=>{
return dirs2[i-1].dis / e.dis > maxRatio
}
let smallThanAfter = ()=>{
return dirs2[i+1].dis / e.dis > maxRatio
}
if(i>0 && i{
start+=1 //不包含start和end
let count = end - start ;
let dis = 0
for(let m=start;m{ //不包含start
start+=1 //不包含start和end
for(let m=start;mstart && dirs2[i].dis / dirs2[j].dis > maxRatio1){
ratios += dirs2[i].dis / dirs2[j].dis
j--
}
let count = i-j-1
ratios /= count
if(count > 0 && computeWidth(j,i)< minWidth * ratios / maxRatio2 ){ //怎么感觉好像改成了视觉宽度小于某个值即可,那直接用count好了?
changeDis(j,i)
start = i //在此之前的修改过,之后不用再判断
}
/* if(count > 0 && (count == 1 || computeWidth(j,i){
let dir = e.dir.clone().multiplyScalar(e.disB || e.dis);
[maxZ,minZ].forEach(z=>{
posArr.push(pano.position.clone().setZ(z).add(dir)) //获取到外墙点
})
});
}
let addSide = ()=>{//两个漫游点间两边各加一些侧线
//中点处的
let top0 = pano0.ceilZ == Infinity ? pano0.position.z+skyHeight : pano0.ceilZ
let top1 = pano1.ceilZ == Infinity ? pano1.position.z+skyHeight : pano1.ceilZ
let midMaxZ = (top0 + top1)/2
let midMinZ = (pano0.floorPosition.z+pano1.floorPosition.z)/2;
let mid = new THREE.Vector3().addVectors(pano0.position, pano1.position).multiplyScalar(0.5)
if(!dontAddSides){
if( pano0.pointcloud.hasDepthTex && pano0.pointcloud.hasDepthTex){
let panos = [pano0,pano1]
let vecs = [vec.clone().negate(), vec]
let axis = [[-1,1],[1,-1]]
let dis2d = new THREE.Vector2().subVectors(pano0.position, pano1.position).length()//水平上的距离
let maxDis = 50, minDis = 0.5, minR = 0.2, maxR = 1.2
//let r = maxR - ( maxR - minR) * THREE.Math.clamp((dis2d - minDis) / (maxDis - minDis),0,1) //dis2d越大,角度要越小 //THREE.Math.smoothstep(currentDis, op.nearBound, op.farBound);
let r = math.linearClamp(dis2d, [minDis,maxDis], [maxR, minR])
//console.log('dis2d',dis2d,'r',r)
let angles = ((browser.isMobile()/* || dis2d<4 */)? [60] : [50,70] /* [35,65] */).map(deg=>{ //正的在左边 尽量能够平分中间这段墙体。 (角度为从中心向外)
let angle = THREE.Math.clamp(deg * r, 5, 80);
//console.log('angle',angle)
return THREE.Math.degToRad(angle)
})
axis.forEach((axis_, index0)=>{
let disToSides = []
let accordingPano = index0 == 0 ? pano0 : pano1; //根据离该点在vec方向上的距离顺序来存顶点
panos.forEach((pano,index)=>{
let dirs = angles.map(angle=>getDir(axis_[index]*angle, vecs[index]))//一侧的若干角度
dirs.forEach((dir_,i)=>{
let dis1 = getFar(dir_, pano);
let disToPano2d = dis1 * Math.cos(angles[i])
if(disToPano2d{return b-a});//从大到小
//由距离accordingPano的近到远:
disToSides.sort((a,b)=>{return a.disToPano2d-b.disToPano2d})
//console.log('disToSides', index0, disToSides)
if(disToSides.length == 1 && disToSides[0].disToSide < 0.5){
disToSides = [] //如果太近直接去除
}
disToSides.forEach(e=>{//求z
let ratio = e.disToPano2d / dis2d
let r = accordingPano == pano0 ? (1-ratio) : ratio
let sideMaxZ_ = top0 * r + top1 * (1-r);
let sideMinZ_ = pano0.floorPosition.z * r + pano1.floorPosition.z * (1-r);
[sideMaxZ_,sideMinZ_].forEach(z=>{
posArr.push(e.pano.position.clone().setZ(z).add(e.dir_)) //是直接使用最长dis的那个intersect点好还是mid
})
})
}
sideCount[index0] = disToSides.length //记录侧边个数
})
}else{
//这段针对点云时,仅测试才会执行到
sideCount = [1,1]
let sideDirs = [getDir(Math.PI/2, vec), getDir(-Math.PI/2, vec)]
sideDirs.forEach((dir_ ,index)=>{
let dis = getFar(dir_, null, mid, midMaxZ-midMinZ); //直接从中点求两侧的距离
dir_.multiplyScalar( /* Math.max( */dis/* , sideDis[index]) */ );
[midMaxZ,midMinZ].forEach(z=>{
posArr.push(mid.clone().setZ(z).add(dir_))
})
})
}
}
//中心:
[midMaxZ,midMinZ].forEach(z=>{
posArr.push(mid.clone().setZ(z))
})
}
//positions存放顺序:pano的每边的 zMax和zMin 、count1个dir的点 ;侧边的点 ;连接处顶底的中点
let addFaces = ()=>{
let getPI = function(index, posType, panoIndex){//获取顶点序号
return 2 + (count1*2 + 2 ) * panoIndex + index*2 + (posType == 'top' ? 0 : 1)
}
let getSidePI = function(index, posType, panoIndex){//获取侧边顶点序号
if(panoIndex == 1) index += sideCount[0]
return getPI(index, posType, 2)-2
}
let getPanoPI = function(posType, panoIndex){//获取pano处对应的点序号
return getPI(-1, posType, panoIndex)
}
let topCenter = posArr.length-2; //最后添加的两个中心点
let btmCenter = posArr.length-1;
for(let i=0;i<2;i++){
for(let index=1; index