webgl_rxdz_roam.vue 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  1. <template src="./webgl_rxdz_roam.html">
  2. </template>
  3. <script>
  4. import * as THREE from 'three';
  5. import Stats from 'three/addons/libs/stats.module.js';
  6. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  7. import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  8. import TWEEN from 'three/addons/libs/tween.module.js';
  9. import {getStorage} from '@/utils/localStorage';
  10. var requestId = "";
  11. const util = require('@/utils/util.js').default;
  12. // import util from '@/utils/util.js';
  13. // const config = require('@/services/urlConfig.js');
  14. // import requestConfig from '@/static/lib/requestConfig.js';
  15. import viewShell from'@/components/newBottomCom/viewShell/viewShell.vue';
  16. import viewMask from'@/components/newBottomCom/viewMask/viewMask.vue';
  17. // import { RGBELoader } from '@/webgl/jsm/loaders/RGBELoader.js';
  18. import screenshot from '@/mixins/screenshot.js';
  19. import floorMethod from '@/mixins/floorMethod.js';
  20. import loadModel from '@/mixins/loadModel.js';
  21. import wallMethod from '@/mixins/wallMethod.js';
  22. import commonPageMethod from '@/mixins/commonPageMethod.js';
  23. // import commonPageMethod from '@/common/commonPageMethod.js';
  24. // const app = getApp(); //获取应用实例
  25. export default {
  26. components:{viewShell,viewMask},
  27. mixins:[screenshot,loadModel,floorMethod,wallMethod,commonPageMethod],
  28. /**
  29. * 页面的初始数据
  30. */
  31. data() {
  32. return {
  33. pvCurPageName: "room_show",
  34. locusBehaviorName: "房间展示",
  35. pvCurPageParams: null,
  36. houseId: "",
  37. pvId: 'p_2cmina_23080402',
  38. canvas:null,
  39. navbar: {
  40. showCapsule: 1,
  41. title: '客厅',
  42. titleColor: '#000',
  43. navPadding: 0,
  44. navPaddingBg:'transparent',
  45. navBarColor: 'transparent',
  46. navBackColor: 'transparent',
  47. haveCallback: true, // 如果是 true 会接手 navbarBackClk
  48. fromShare: false,
  49. fromProject: 0,
  50. shareToken: "",
  51. pageName: this.pvCurPageName,
  52. },
  53. id:'',// 户型编号
  54. spaceList:[], // 空间列表
  55. gltfSpaces:[], // 场景中地板模型数组
  56. gltfSpaceRoofs:[],
  57. curSpaceObj:null, // 当前选中的空间
  58. // curSpaceIndex:-1, // 当前选中的空间索引
  59. spaceId:null,
  60. wallIds:[], // 空间墙体id
  61. // wallList:[], // 墙体数据
  62. gltfWalls:[], // 场景中墙体模型数组
  63. loader:null,
  64. scene:null,
  65. // sky:null,
  66. camera:null,
  67. controlStarPosition : { x:0, y:0, z:0}, //控制器初始位置
  68. cameraStarPosition : { x:0, y:20, z:0} ,//摄像头初始位置
  69. cameraLastPosition: null, //摄像头上一次移动到的位置
  70. controlLastPosition: null, //观察点上一次移动到的位置
  71. canvasHeight:408, //canvas视图的高度-计算得出
  72. chooseMesh:null,//标记鼠标拾取到的mesh
  73. shottingImg: [],
  74. progress:1, //进度条
  75. myLoadingStatus:false,
  76. // textGeoList:[],
  77. repeatFlag:false, //重复点击
  78. // skyPlan: null, // 天空盒子
  79. instancedMeshList: [],
  80. screenshotResolve:null,
  81. actors:[],
  82. showDownView:true,//默认显示下载按钮
  83. currentActor:null,
  84. circleGroup:null,//圆形地标
  85. isIOS:false,
  86. defaulIndex:null, //默认视角的序号
  87. // aiImagesList:[
  88. // // "https://dm.static.elab-plus.com/miniProgram/plus_IM01.png",
  89. // // "https://dm.static.elab-plus.com/miniProgram/plus_IM02.png",
  90. // // "https://dm.static.elab-plus.com/miniProgram/plus_IM03.png",
  91. // // "https://dm.static.elab-plus.com/miniProgram/plus_IM04.png",
  92. // ]
  93. }
  94. },
  95. beforeDestroy() {
  96. cancelAnimationFrame(requestId, this.canvas)
  97. this.worker && this.worker.terminate()
  98. if (this.renderer instanceof THREE.WebGLRenderer) {
  99. // 遍历场景中的所有子对象,找到类型为Mesh的对象并移除
  100. let deleList = this.scene.children.filter(object=>{
  101. if (object instanceof THREE.Mesh) {
  102. return object
  103. }
  104. })
  105. if(deleList && deleList.length>0){
  106. this.scene.remove(...deleList);
  107. }
  108. this.scene.traverse(function(object) {
  109. if (object instanceof THREE.Mesh) {
  110. if(object.geometry && typeof(object.geometry.dispose)=='function'){
  111. object.geometry.dispose();
  112. }
  113. if(object.material && typeof(object.material.dispose)=='function'){
  114. object.material.dispose();
  115. }
  116. if(object.texture && typeof(object.texture.dispose)=='function'){
  117. object.texture.dispose();
  118. }
  119. }
  120. });
  121. this.renderer.clear();
  122. this.renderer.dispose();
  123. this.renderer.forceContextLoss();
  124. this.renderer.context = null;
  125. this.renderer.domElement = null;
  126. this.renderer = null;;
  127. this.clearHandle()
  128. }
  129. TWEEN && TWEEN.removeAll();//清除所有的tween;
  130. console.warn("***beforeDestroy-webgl_rxdz_roam***");
  131. },
  132. mounted(options) {
  133. var that = this;
  134. // alert("JavaScript 堆大小限制: "+performance.memory.jsHeapSizeLimit
  135. // +"\n已使用的 JavaScript 堆大小: "+performance.memory.usedJSHeapSize
  136. // +"\nJavaScript 堆的总大小: "+performance.memory.totalJSHeapSize);
  137. console.warn("***webgl_rxdz_roam-options***",this.$route.query)
  138. this.isIOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
  139. if(this.isIOS){
  140. this.curHouseObj = JSON.parse(getStorage('curHouseObj'));
  141. this.wallList = JSON.parse(getStorage('wallList'));
  142. }else{
  143. this.curHouseObj = this.$store.state.curHouseObj;
  144. this.wallList = this.$store.state.wallList;
  145. }
  146. // alert("***mounted-webgl_rxdz_roam***"+this.isIOS + this.curHouseObj)
  147. let screenWidth = window.screen.width;
  148. let screenHeight = window.screen.height;
  149. if(window.innerWidth && window.screen.width){
  150. screenWidth = Math.min(window.innerWidth,window.screen.width)
  151. }
  152. if(window.innerHeight && window.screen.height){
  153. screenHeight = Math.min(window.innerHeight,window.screen.height)
  154. }
  155. let unit = screenWidth / 750;//单位rpm 对应 px 的值
  156. this.canvasHeight = screenHeight - (600 * unit) + (40 * unit);
  157. this.houseId = this.$route.query.houseId?this.$route.query.houseId:'';
  158. this.spaceId = this.$route.query.spaceId?this.$route.query.spaceId:'';
  159. let container = this.$refs.webgl;
  160. let canvas3d = this.canvas = this.$refs.glcanvas;
  161. //uniapp 兼容写法,因为uni的页面对象的Vue 实例是$vm
  162. let camera = null, renderer = null;
  163. let needRender = false; //是否需要渲染 false表示不需要渲染;true 表示需要渲染
  164. let loader = this.loader = new GLTFLoader();
  165. let scene = this.scene = new THREE.Scene();
  166. let raycaster = null;
  167. let mouse = new THREE.Vector2();
  168. let chooseMesh = this.chooseMesh;//标记鼠标拾取到的mesh
  169. let isUserContorl = true;//是否进入漫游状态-默认是
  170. //漫游时变量
  171. let onPointerDownMouseX = 0, onPointerDownMouseY = 0,
  172. lon = 0;
  173. let fingerCount = 0; //触摸时的手指数目
  174. let startTime = 0; //非漫游时的移动变量
  175. let tweenCameraAnma = false; //表示当前是否处在动画过程中
  176. let controls = null,boundary=null;
  177. let stats;
  178. init();
  179. // this.$refs.myLoading.showLoading("加载中...1%")
  180. this.$store.state.loadingMsg="加载中...1%";
  181. // this.myLoadingStatus = true;
  182. this.progress = 1;
  183. this.clearEvent = clearEvent;
  184. this.attendEvent = attendEvent;
  185. // this.meshRoam = meshRoam;
  186. this.tweenCameraAnmaChange = tweenCameraAnmaChange;
  187. this.switchActor = switchActor;
  188. this.starRender = starRender;//对外暴露启动渲染的方法
  189. this.stopRender = stopRender;//对外暴露停止渲染的方法
  190. this.positionCamer = positionCamer;
  191. if(this.curHouseObj && this.curHouseObj.id){
  192. this.setHouseDetail(this.curHouseObj);
  193. }
  194. function init() {
  195. scene.background = new THREE.Color("#FFFFFF");
  196. // scene.environment = new THREE.Color("#F2F2F2");
  197. // 创建一个HDR贴图加载器
  198. // const rgbeloader = new RGBELoader();
  199. // // 加载HDR贴图
  200. // rgbeloader.load('https://dm.static.elab-plus.com/miniProgram/environment.hdr', (texture) => {
  201. // // 将HDR贴图设置为场景的环境贴图
  202. // texture.mapping = THREE.EquirectangularReflectionMapping;
  203. // scene.environment = texture;
  204. // })
  205. // 创建相机位置
  206. camera = new THREE.PerspectiveCamera(90, screenWidth / that.canvasHeight, 0.1, 10000 );
  207. // camera.up.set(0, 1, 0);//俯视状态,将相机的up向量设置为z轴负方向 {x:0,y:1,z:0}
  208. // camera.position.set(that.cameraStarPosition.x, that.cameraStarPosition.y, that.cameraStarPosition.z);
  209. scene.add(camera);
  210. that.camera = camera;
  211. // 环境光会均匀的照亮场景中的所有物体
  212. const ambientLight = new THREE.AmbientLight(0xFFEFE0, 3.5);
  213. scene.add(ambientLight);
  214. //平行光
  215. const light = new THREE.DirectionalLight(0xFFF8E5, 2.5);
  216. light.position.set(5, 7, 3); //default; light shining from top
  217. if(!that.isIOS){
  218. light.castShadow = true; // default false
  219. // 默认情况下光投影相机区域是一个长宽高为10x10x500的长方体区域,光源投射方向为通过坐标原点
  220. light.shadow.camera.left = -100; // 这个区域内产生阴影
  221. light.shadow.camera.right = 100; // 这个区域内产生阴影
  222. light.shadow.camera.top = 100; // 这个区域内产生阴影
  223. light.shadow.camera.bottom = -100; // 这个区域内产生阴影
  224. light.shadow.mapSize.width = 1024; // 影响阴影的清晰度
  225. light.shadow.mapSize.height = 1024; // 影响阴影的清晰度
  226. }
  227. scene.add(light);
  228. //antialias 这个值得设置为false,不然IOS上截图会失效
  229. renderer = that.renderer = new THREE.WebGLRenderer( {
  230. canvas:canvas3d,
  231. alpha: true,
  232. antialias:true,
  233. preserveDrawingBuffer: true,
  234. });
  235. if(!that.isIOS){
  236. renderer.shadowMap.enabled = true;//产生阴影
  237. renderer.shadowMap.type = THREE.PCFSoftShadowMap; // 阴影属性
  238. }
  239. renderer.outputEncoding = THREE.sRGBEncoding;
  240. renderer.outputColorSpace = THREE.SRGBColorSpace;
  241. // renderer.toneMappingExposure = 0.1;//色调映射的曝光级别。默认是1
  242. renderer.toneMapping = THREE.NoToneMapping;//色调映射
  243. renderer.physicallyCorrectLights = true;//关键参数,模拟物理光照影响,必须设置为true
  244. renderer.setPixelRatio(window.devicePixelRatio);
  245. renderer.setSize(screenWidth, that.canvasHeight);
  246. container.appendChild( renderer.domElement );
  247. controls = new OrbitControls( camera, renderer.domElement );
  248. controls.enableDamping = true;//启动缓动
  249. controls.minDistance = 0.0001;
  250. controls.maxDistance = 10;
  251. controls.minPolarAngle = 0;// 默认0
  252. controls.maxPolarAngle = Math.PI / 2; // 默认Math.PI,即可以向下旋转到的视角。
  253. // controls.target.set( that.controlStarPosition.x, that.controlStarPosition.y, that.controlStarPosition.z);
  254. controls.enableZoom = true;//启用摄像机的缩放
  255. controls.enablePan = true;//禁用摄像机平移
  256. controls.enableRotate = true;//启用摄像机水平或垂直旋转
  257. // controls.zoomToCursor = true;
  258. // controls.target.copy(camera.position);
  259. // controls.update();
  260. // 监听相机移动事件-限制只能在当前空间范围内移动
  261. controls.addEventListener('change', () => {
  262. // 检查相机位置是否超出边界框
  263. if (boundary && !boundary.containsPoint(camera.position)) {
  264. let clampedPosition = new THREE.Vector3( );
  265. boundary.clampPoint(camera.position,clampedPosition);
  266. if(clampedPosition){
  267. camera.position.copy(clampedPosition);
  268. // controls.target.copy(clampedPosition);
  269. }
  270. }
  271. });
  272. // controls.target = new THREE.Vector3( );;
  273. // camera.lookAt(that.controlStarPosition.x,that.controlStarPosition.y,that.controlStarPosition.z);
  274. raycaster = new THREE.Raycaster();
  275. // stats = new Stats();
  276. // container.appendChild(stats.dom);
  277. // stats.domElement.style.top = '100px';
  278. attendEvent();//注册监听事件
  279. starRender(); //启动渲染
  280. }
  281. function tweenCameraAnmaChange (value) {
  282. tweenCameraAnma = value
  283. }
  284. function attendEvent () {
  285. renderer && renderer.domElement && renderer.domElement.addEventListener('touchstart', onPointerStart, false);
  286. renderer && renderer.domElement && renderer.domElement.addEventListener('touchmove', onPointerMove, false);
  287. renderer && renderer.domElement && renderer.domElement.addEventListener('touchend', onPointerUp, false);
  288. }
  289. //取消事件监听-避免二次进入时触发多次事件
  290. function clearEvent(){
  291. console.warn("**clearEvent****")
  292. renderer && renderer.domElement && renderer.domElement.removeEventListener('touchstart', onPointerStart);
  293. renderer && renderer.domElement && renderer.domElement.removeEventListener('touchmove', onPointerMove );
  294. renderer && renderer.domElement && renderer.domElement.removeEventListener('touchend', onPointerUp );
  295. }
  296. // 手指移动开始
  297. function onPointerStart(event){
  298. startTime = (new Date()).getTime();
  299. fingerCount = event.touches.length;//手指个数
  300. console.log('开始触摸事件:',lon,fingerCount,camera.position.y)
  301. if (fingerCount === 1) {
  302. // 只有一个手指时记录当前点的坐标作为平移起始点
  303. onPointerDownMouseX = event.changedTouches[0].clientX;
  304. onPointerDownMouseY = event.changedTouches[0].clientY;
  305. }
  306. }
  307. //持续触摸中
  308. function onPointerMove( event ) {
  309. fingerCount = event.touches.length;//手指个数
  310. }
  311. //触摸结束
  312. function onPointerUp(event) {
  313. fingerCount = event.touches.length;//手指个数
  314. console.warn("***触摸结束***",fingerCount,startTime)
  315. if(fingerCount==0){
  316. let now = new Date().getTime()
  317. if (Math.abs(event.changedTouches[0].clientX - onPointerDownMouseX) < 10
  318. && Math.abs(event.changedTouches[0].clientY - onPointerDownMouseY) < 10
  319. && (now - startTime) < 300 ){
  320. checkIntersection(event);
  321. }
  322. }
  323. }
  324. //射线检测handle
  325. function checkIntersection(event) {
  326. let x = (event.changedTouches[0].clientX / screenWidth) * 2 - 1;
  327. let y = -(event.changedTouches[0].clientY / that.canvasHeight) * 2 + 1;
  328. mouse.x = x;
  329. mouse.y = y;
  330. //更新射线
  331. raycaster.setFromCamera(mouse, camera);
  332. let intersects = raycaster.intersectObjects(scene.children,true);
  333. console.warn("***checkIntersection***",intersects.length)
  334. if (intersects.length > 0) {
  335. //找到最近的那个网格模型物体
  336. let mesh = intersects.find((it) => {
  337. if(it.object && it.object.isMesh == true
  338. && it.object.parent && it.object.parent.name == 'actor'
  339. && it.object.parent.visible == true){
  340. return true;
  341. }
  342. });
  343. //拾取到了视角,就不继续拾取了
  344. if(mesh){
  345. moveActor(mesh.object.parent);
  346. return false;
  347. }
  348. mesh = intersects.find((it) => {
  349. if(it.object && it.object.isInstancedMesh
  350. && (it.object.name == '地板' || it.object.name == '花园') && it.object.visible == true){
  351. return true;
  352. }
  353. });
  354. //拾取到了地板
  355. if(mesh){
  356. let floor = mesh.object;
  357. let index = mesh.instanceId;//射线相交是的实例序号
  358. let spaceId = that.gltfSpaces[index].spaceId;//获取选中实例的空间id
  359. if(floor.name == "花园"){//花园
  360. return false;
  361. let selectMesh = that.gltfSpaces.find(it=>{return it.spaceType==14 && it.instancedMeshIndexList[0].instancedAtIndex==index})
  362. spaceId = selectMesh.spaceId;
  363. }else{//室内
  364. // floor.name = "地板";
  365. let selectMesh = that.gltfSpaces.find(it=>{return it.spaceType!=14 && it.instancedMeshIndexList[0].instancedAtIndex==index})
  366. spaceId = selectMesh.spaceId;
  367. }
  368. // let spaceId = that.gltfSpaces[index].spaceId;//获取选中实例的空间id
  369. console.warn("***checkIntersection-地板***",floor,index,spaceId,that.spaceId)
  370. //当前拾取到的是本空间的底部-意味着用户点击了地板
  371. if(floor && spaceId == that.spaceId){
  372. moveCarmer(mesh.point);
  373. return false;
  374. }
  375. }
  376. }
  377. }
  378. //自动切换视角
  379. function switchActor (toIndex=null) {
  380. if(!that.currentActor){
  381. this.$message.warning("没有当前视角!");
  382. return false;
  383. }
  384. if(!that.actors || that.actors.length==0){
  385. this.$message.warning("没有视角!");
  386. return false;
  387. }
  388. if(toIndex!=null){//存在要去往的视角
  389. moveActor(that.actors[toIndex]);
  390. }else{
  391. let index = that.currentActor.userIndex;//当前视角的序号
  392. let nextIndex = (index + 1) % that.actors.length;
  393. //移动到对应的视角去
  394. moveActor(that.actors[nextIndex]);
  395. that.defaulIndex = nextIndex;//更新下默认视角
  396. }
  397. }
  398. //移动到选中的位置-地板
  399. function moveCarmer (point) {
  400. //还在动画中,不能点击切换
  401. if(tweenCameraAnma == true){
  402. return false;
  403. }
  404. let _x = point.x - camera.position.x;//x轴移动的距离
  405. let _z = point.z - camera.position.z;//z轴移动的距离
  406. let cameraNewPosition = {x:camera.position.x + _x,y:1.5,z:camera.position.z + _z};
  407. let targetNewPosition = {x:controls.target.x + _x,y:1.5,z:controls.target.z + _z};
  408. let oldUp = {x:0,y:1,z:0};
  409. let newUp = {x:0,y:1,z:0};
  410. moveTip(cameraNewPosition)
  411. // console.warn("**moveCarmer***",lon,JSON.stringify(cameraNewPosition),JSON.stringify(targetNewPosition))
  412. tweenCamera(camera.position,controls.target,cameraNewPosition,targetNewPosition,oldUp,newUp,2000);
  413. setTimeout(()=> {
  414. that.circleGroup.visible = false;
  415. }, 2000);
  416. }
  417. //创建地标
  418. function creatMoveTip(position){
  419. if(!that.circleGroup){
  420. that.circleGroup = new THREE.Group();
  421. let geometry = new THREE.CircleGeometry( 0.2, 32 );
  422. let material = new THREE.MeshBasicMaterial( { transparent: true } );
  423. let circle = new THREE.Mesh( geometry, material );
  424. circle.position.set(position.x,0.01,position.z);
  425. circle.rotation.x = -Math.PI / 2;
  426. // let geometry1 = new THREE.CircleGeometry( 0.4, 32 );
  427. // let circle2 = new THREE.Mesh( geometry1, material );
  428. // circle2.position.set(position.x,0.01,position.z);
  429. // 使用贴图
  430. const textureLoader = new THREE.TextureLoader();
  431. textureLoader.load('https://dm.static.elab-plus.com/miniProgram/circlemap1.png', function(texture) {
  432. material.map = texture; // 将贴图应用于材质的map属性
  433. material.needsUpdate = true; // 更新材质
  434. });
  435. that.circleGroup.add(circle);
  436. scene.add(that.circleGroup);
  437. that.circleGroup.visible = false;
  438. }
  439. }
  440. //移动地标
  441. function moveTip(position){
  442. if(!that.circleGroup){
  443. that.circleGroup = new THREE.Group();
  444. let geometry = new THREE.CircleGeometry( 0.2, 32 );
  445. let material = new THREE.MeshBasicMaterial( { color: 0xffffff } );
  446. let circle = new THREE.Mesh( geometry, material );
  447. circle.position.set(position.x,0.01,position.z);
  448. circle.rotation.x = -Math.PI / 2;
  449. // let geometry1 = new THREE.CircleGeometry( 0.4, 32 );
  450. // let circle2 = new THREE.Mesh( geometry1, material );
  451. // circle2.position.set(position.x,0.01,position.z);
  452. that.circleGroup.add(circle);
  453. scene.add(that.circleGroup);
  454. }else{
  455. that.circleGroup.visible = true;
  456. that.circleGroup.children[0].position.set(position.x,0.01,position.z);
  457. }
  458. }
  459. //移动视角点位
  460. function moveActor (obj) {
  461. clearEvent();//注销事件监听
  462. // console.warn("***moveActor***",obj)
  463. that.currentActor = obj;//记录下当前的视角对象 mesh网格模型
  464. let cameraNewPosition = obj.position;
  465. let targetNewPosition = obj.targetNewPosition;
  466. let oldUp = {x:0,y:1,z:0}; //俯视
  467. let newUp = {x:0,y:1,z:0}; //正视
  468. // moveTip(cameraNewPosition);
  469. // console.warn("**moveActor***",JSON.stringify(cameraNewPosition),JSON.stringify(targetNewPosition))
  470. tweenCamera(camera.position,controls.target,cameraNewPosition,targetNewPosition,oldUp,newUp,2000);
  471. lon = 0;
  472. setTimeout(()=> {
  473. attendEvent()
  474. // that.circleGroup.visible = false;
  475. }, 2000);
  476. }
  477. //初始化点位视角
  478. function initActor(){
  479. if(!chooseMesh){
  480. console.error("[drawActor],没有选中的空间数据")
  481. return false;
  482. }
  483. let spaceObj = chooseMesh;//获取选中的空间模型的相关数据
  484. if(!spaceObj.actors){
  485. return false;
  486. }
  487. let defaulIndex = spaceObj.actors.findIndex(it=>it.isSelected==true);
  488. if(defaulIndex == -1){
  489. defaulIndex = 0;
  490. }
  491. that.defaulIndex = defaulIndex;//记录下默认视角
  492. that.actors = [];
  493. spaceObj.actors.forEach((actor,index)=>{
  494. // let model = gltf.scene; // 获取模型
  495. // let cloneModel = model.clone(true);//赋值模型,准备复用
  496. // cloneModel.children.map((v,i)=>{
  497. // if(v.material){
  498. // v.material = model.children[i].material.clone()
  499. // }
  500. // })
  501. // let cube = cloneModel;
  502. let cube = {};
  503. cube.name = "actor";
  504. cube.userType = "mesh";
  505. //新的摄像机的位置-新的摄像机角度是倾斜角度,所以z值需要计算,高度设置为模型高度的2倍
  506. let _actorLoaction = actor.actorLocation.split(',');//x y z
  507. let _actorTransform = actor.actorTransform.split(',');//旋转角度,取第三个值
  508. let _hd = THREE.MathUtils.degToRad(parseInt(_actorTransform[2]));//将度转化为弧度。
  509. let _hdY = THREE.MathUtils.degToRad(parseInt(_actorTransform[1]));//Y轴方向上将度转化为弧度。
  510. // if(parseInt(_actorLoaction[1])==0){//X轴
  511. // _actorLoaction[1] = spaceObj.centerX;
  512. // }
  513. // if(parseInt(_actorLoaction[0])==0){//Y轴
  514. // _actorLoaction[0] = spaceObj.centerY;
  515. // }
  516. let X_C = parseInt(_actorLoaction[0]);//X轴偏移量
  517. let Y_C = -parseInt(_actorLoaction[1]);//Y轴偏移量-取反,UE里面的Y轴方向跟Three.js相反
  518. let px = spaceObj.centerX + X_C;
  519. let py = -spaceObj.centerY + Y_C;//UE里面的centerY值跟Three.js Y轴相反;获得真实的坐标值
  520. let position = {
  521. x:(parseInt(px))/100,
  522. y:1.5,
  523. z:(parseInt(py))/100,//模型Y轴坐标系正负值跟webglZ轴是相反的
  524. }
  525. //新的观察点的位置-取模型的中心点坐标,加上高度,由于模型都是贴地的,所以高度设置为1.5
  526. let targetNewPosition = {
  527. x:position.x + Math.sin(_hd),
  528. y:1.5 + Math.tan(_hdY),
  529. z:(position.z - Math.cos(_hd)),
  530. }
  531. cube.position = position;
  532. cube.userIndex = index;
  533. cube.actorEum = index;
  534. cube.targetNewPosition = targetNewPosition;
  535. // console.warn("*actors*",cube,defaulIndex)
  536. that.actors.push(cube);//添加视角
  537. if(index == defaulIndex){//隐藏当前视角
  538. that.currentActor = cube;//记录下当前的视角对象 mesh网格模型
  539. let param = {
  540. type: 'CLK', //埋点类型
  541. clkId: 'clk_2cmina_23080411', //点击ID
  542. clkName: 'visualangle_clk', //点击前往的页面名称
  543. clkParams: {
  544. locusName: "预制视角",
  545. type:that.actors[index].actorEum
  546. }
  547. };
  548. util.trackRequest(param);
  549. }
  550. })
  551. }
  552. //计算当前选中空间的平视时的观察点和摄像机的放置点位
  553. function roamPositionHandle(lon=''){
  554. if(!chooseMesh){
  555. console.error("[roamPositionHandle],没有选中的空间数据")
  556. return false;
  557. }
  558. let spaceObj = chooseMesh;//获取选中的空间模型的相关数据
  559. //获取视角
  560. let defaultActor = null;
  561. if(spaceObj.actors && spaceObj.actors.length>0){
  562. defaultActor = spaceObj.actors.find(it=>it.isSelected==true);
  563. if(!defaultActor){
  564. defaultActor = spaceObj.actors[0];
  565. }
  566. }
  567. let _actorLoaction = defaultActor.actorLocation.split(',');//x y z
  568. let _actorTransform = defaultActor.actorTransform.split(',');//旋转角度,取第三个值
  569. let _hd = THREE.MathUtils.degToRad(parseInt(_actorTransform[2]) + lon);//将度转化为弧度。
  570. let _hdY = THREE.MathUtils.degToRad(parseInt(_actorTransform[1]));//Y轴方向上将度转化为弧度。
  571. // if(parseInt(_actorLoaction[1])==0){//X轴
  572. // _actorLoaction[1] = spaceObj.centerX;
  573. // }
  574. // if(parseInt(_actorLoaction[0])==0){//Y轴
  575. // _actorLoaction[0] = spaceObj.centerY;
  576. // }
  577. let X_C = parseInt(_actorLoaction[0]);//X轴偏移量-UE原因
  578. let Y_C = -parseInt(_actorLoaction[1]);//Y轴偏移量-取反,UE里面的Y轴方向跟Three.js相反
  579. let px = spaceObj.centerX + X_C;
  580. let py = -spaceObj.centerY + Y_C;
  581. //新的摄像机的位置-新的摄像机角度是倾斜角度,所以z值需要计算,高度设置为模型高度的2倍
  582. let cameraNewPosition = {
  583. x:(parseInt(px))/100,
  584. y:1.5,
  585. z:(parseInt(py))/100,//模型Y轴坐标系正负值跟webglZ轴是相反的
  586. }
  587. if(cameraNewPosition){
  588. let minX = 0,maxX = 0,minY = 0,maxY = 0;//0.1 是模型墙壁厚度
  589. minX = (spaceObj.centerX - (spaceObj.spaceWidth/2))/100 + 0.1;
  590. maxX = (spaceObj.centerX + (spaceObj.spaceWidth/2))/100 - 0.1;
  591. maxY = ((-spaceObj.centerY + (spaceObj.spaceHeight/2))/100 - 0.1);
  592. minY = ((-spaceObj.centerY - (spaceObj.spaceHeight/2))/100 + 0.1);
  593. //新的坐标轴不在房间范围内,则不能移动
  594. if(cameraNewPosition.x<minX || cameraNewPosition.x>maxX
  595. ||cameraNewPosition.z<minY || cameraNewPosition.z>maxY){//不在房间范围
  596. let _x = ((spaceObj.spaceWidth/2) - 15)*defaultActor.presentX + spaceObj.centerX;
  597. let _z = ((spaceObj.spaceHeight/2) - 15)*defaultActor.presentY + (-spaceObj.centerY);
  598. cameraNewPosition.x = _x/100;
  599. cameraNewPosition.z = _z/100;
  600. console.warn("**roamPositionHandle-观察点不在空间范围-强制修正观察点位置****",JSON.stringify(cameraNewPosition))
  601. }
  602. }
  603. //新的观察点的位置-取模型的中心点坐标,加上高度,由于模型都是贴地的,所以高度设置为1.5
  604. let targetNewPosition = {
  605. x:cameraNewPosition.x + Math.sin(_hd),
  606. y:1.5 + Math.tan(_hdY),
  607. z:(cameraNewPosition.z - Math.cos(_hd)),
  608. }
  609. let lookPosition = {
  610. x:cameraNewPosition.x + (Math.sin(_hd)*0.01),
  611. y:1.5 + Math.tan(_hdY),
  612. z:(cameraNewPosition.z - (Math.cos(_hd))*0.01),
  613. }
  614. return {cameraNewPosition,targetNewPosition,lookPosition}
  615. }
  616. //直接定位到摄像头位置
  617. function positionCamer(mesh=null){
  618. if(mesh){//如果传入了模型,则取模型
  619. chooseMesh = mesh;
  620. }
  621. if(!chooseMesh){
  622. console.error("[positionCamer],没有选中的空间数据")
  623. return false;
  624. }
  625. if(!chooseMesh.actors || chooseMesh.actors.length==0){
  626. chooseMesh.actors = [{
  627. actorLocation:chooseMesh.actorLocation,
  628. actorTransform:chooseMesh.actorTransform,
  629. isSelected:true,
  630. presentX:chooseMesh.presentX,
  631. presentY:chooseMesh.presentY,
  632. }]
  633. }
  634. boundary = new THREE.Box3(
  635. new THREE.Vector3(chooseMesh.centerX/100 - chooseMesh.spaceWidth/100/2 + 0.1, 0, -chooseMesh.centerY/100 - chooseMesh.spaceHeight/100/2 + 0.1), // 边界框的最小点
  636. new THREE.Vector3(chooseMesh.centerX/100 + chooseMesh.spaceWidth/100/2 - 0.1, 2.7, -chooseMesh.centerY/100 + chooseMesh.spaceHeight/100/2 - 0.1) // 边界框的最大点
  637. );
  638. initActor();//初始化视角
  639. let data = roamPositionHandle();
  640. let cameraNewPosition = data.cameraNewPosition;
  641. let targetNewPosition = data.targetNewPosition;
  642. let lookPosition = data.lookPosition;
  643. creatMoveTip(cameraNewPosition);//创建移动的地标
  644. camera.position.set(cameraNewPosition.x, cameraNewPosition.y, cameraNewPosition.z);
  645. controls.target.set(lookPosition.x,lookPosition.y,lookPosition.z);
  646. // controls.target.set(cameraNewPosition.x,cameraNewPosition.y,cameraNewPosition.z);
  647. // controls.target.copy(camera.position);
  648. camera.lookAt(targetNewPosition.x,targetNewPosition.y,targetNewPosition.z);
  649. }
  650. // oldP 相机原来的位置
  651. // oldT target原来的位置
  652. // newP 相机新的位置
  653. // newT target新的位置
  654. function tweenCamera(oldP, oldT, newP, newT, oldUp, newUp, time=1000) {
  655. if(JSON.stringify(oldP) == JSON.stringify(newP) && JSON.stringify(oldT) == JSON.stringify(newT)){
  656. that.repeatFlag = false;//放开限制,可以再次点击
  657. return false;
  658. }
  659. if (!chooseMesh) {
  660. that.repeatFlag = false;//放开限制,可以再次点击
  661. return false;
  662. }
  663. tweenCameraAnma = true;
  664. var tween = new TWEEN.Tween({
  665. x1: oldP.x, // 相机x
  666. y1: oldP.y, // 相机y
  667. z1: oldP.z, // 相机z
  668. x2: oldT.x, // 控制点的中心点x
  669. y2: oldT.y, // 控制点的中心点y
  670. z2: oldT.z, // 控制点的中心点z
  671. x3: oldUp.x, // 控制点的中心点x
  672. y3: oldUp.y, // 控制点的中心点y
  673. z3: oldUp.z // 控制点的中心点z
  674. })
  675. .to({
  676. x1: newP.x,
  677. y1: newP.y,
  678. z1: newP.z,
  679. x2: newT.x,
  680. y2: newT.y,
  681. z2: newT.z,
  682. x3: newUp.x, // up向量
  683. y3: newUp.y, // 控制点的中心点y
  684. z3: newUp.z // 控制点的中心点z
  685. }, time)
  686. .easing(TWEEN.Easing.Quadratic.InOut)
  687. .onUpdate((object)=> {
  688. camera.position.x = object.x1;
  689. camera.position.y = object.y1;
  690. camera.position.z = object.z1;
  691. // let newTarget = new THREE.Vector3(object.x3,object.y3,object.z3);
  692. // camera.up.copy(newTarget);
  693. camera.lookAt(object.x2,object.y2,object.z2);
  694. // controls.target.x = object.x2;
  695. // controls.target.y = object.y2;
  696. // controls.target.z = object.z2;
  697. // controls.update();
  698. }).onComplete(()=>{
  699. controls.target.x = newT.x;
  700. controls.target.y = newT.y;
  701. controls.target.z = newT.z;
  702. //修正最后的视角
  703. // let up = new THREE.Vector3(newUp.x,newUp.y,newUp.z);
  704. // camera.up.copy(up);
  705. camera.lookAt(newT.x,newT.y,newT.z);
  706. tweenCameraAnma = false;
  707. that.repeatFlag = false;//放开限制,可以再次点击
  708. })
  709. // 开始动画
  710. tween.start();
  711. }
  712. function stopRender () {
  713. needRender = false;
  714. }
  715. function starRender () {
  716. if(needRender==true){//如果已经在渲染中了,则不能再次开启,避免渲染过多
  717. false;
  718. }
  719. needRender = true;
  720. render();//开始渲染
  721. }
  722. function render() {
  723. if(needRender==false){
  724. return false;
  725. }
  726. TWEEN && TWEEN.update();
  727. // stats.update();
  728. renderer.render(scene, camera);//单次渲染
  729. requestId = requestAnimationFrame(render, canvas3d);
  730. if (that.screenshotResolve) {
  731. stopRender();
  732. that.screenshotResolve()
  733. that.screenshotResolve = null;//释放Promise
  734. }
  735. }
  736. },
  737. // computed: {
  738. // curHouseObj() {
  739. // return this.$store.state.curHouseObj;
  740. // },
  741. // wallList() {
  742. // return this.$store.state.wallList;
  743. // },
  744. // },
  745. methods: {
  746. navbarBackClk() {
  747. if(!this.$refs.viewMask){
  748. this.$router.go(-1);
  749. return false
  750. }
  751. if (this.$refs.viewMask.showAIImage) {
  752. this.$refs.viewMask.showOrHideWebGl();//隐藏显示的AI生图
  753. // if(this.currentActor.userIndex!=this.defaulIndex){//当前不是默认视角了
  754. this.switchActor(this.defaulIndex);//切换到默认视角
  755. // }
  756. } else {
  757. this.$router.go(-1);
  758. }
  759. },
  760. switchActor(){},
  761. positionCamer(){},
  762. clearHandle(){
  763. this.clearEvent();
  764. },
  765. save(){
  766. this.$refs.viewMask.save();//下载
  767. },
  768. /**
  769. * 设置户型详情信息
  770. * @param {Object} data 户型详情
  771. */
  772. setHouseDetail(data){
  773. if(data){
  774. this.id = data.id;
  775. this.spaceId = this.$route.query.spaceId?this.$route.query.spaceId:'';
  776. console.warn("***curHouseObj***",data)
  777. // 加载户型
  778. this.loadSpace();
  779. }else{
  780. this.curHouseObj = {}
  781. }
  782. },
  783. // 绘制空间-即地板
  784. async loadSpace(){
  785. this.spaceList = [];
  786. this.wallIds = [];
  787. if(!this.curHouseObj || !this.spaceId){//减少重复请求
  788. alert("数据错误")
  789. console.warn("***数据错误***")
  790. return false
  791. }
  792. if(this.curHouseObj){
  793. const spaceDetail = this.curHouseObj;
  794. const spaceList = JSON.parse(spaceDetail.houseJson);
  795. // 交换centerX, centerY;上一页面已经处理过了,这里不在需要处理
  796. for (let index = 0; index < spaceList.length; index++) {
  797. var element = spaceList[index];
  798. // const centerX = JSON.parse(JSON.stringify(element.centerX))
  799. if(!element.actors || element.actors.length==0){
  800. element.actors = [{
  801. actorLocation:element.actorLocation,
  802. actorTransform:element.actorTransform,
  803. isSelected:true,
  804. }]
  805. }
  806. element.actors.forEach(actor=>{
  807. let _actorLoaction = actor.actorLocation.split(',');//x y z
  808. let X_C = parseInt(_actorLoaction[0]);//X轴偏移量-UE原因
  809. let Y_C = -parseInt(_actorLoaction[1]);//Y轴偏移量-取反,UE里面的Y轴方向跟Three.js相反
  810. let _x = element.centerX + X_C;
  811. let _z = -element.centerY + Y_C;//centerY 要取反,因为UE里面是反向的
  812. // let _x = parseInt(_actorLoaction[1]) || element.centerX;//观察点 X轴坐标
  813. // let _z = parseInt(_actorLoaction[0]) || element.centerY;//观察点 Z轴坐标
  814. let _presentX = (_x - element.centerX)/((element.spaceWidth/2) - 10);//10是墙壁厚度-单位cm
  815. let _presentY = (_z + element.centerY)/((element.spaceHeight/2) - 10);
  816. //注意如果一开始就设置大超过空间大小,则处理成贴近空间边界
  817. actor.presentX = Math.abs(_presentX)>1 ? (_presentX>1?1:-1) : _presentX;//观察点跟空间中心原点的距离比例
  818. actor.presentY = Math.abs(_presentY)>1 ? (_presentY>1?1:-1) : _presentY;
  819. })
  820. element.wallMoveValue = "[0,0,0,0]"
  821. this.spaceList.push(element);
  822. this.wallIds.push(element.wallId);
  823. if(element.spaceId == this.spaceId){ // 默认选中空间
  824. this.curSpaceObj = element;
  825. }
  826. }
  827. if(!this.curSpaceObj && this.spaceList.length > 0){
  828. this.curSpaceObj = this.spaceList[0];
  829. }
  830. }
  831. let curSpaceArea = parseFloat((this.curSpaceObj.spaceWidth * this.curSpaceObj.spaceHeight) / 10000).toFixed(1);
  832. this.navbar.title = this.curSpaceObj.spaceName + " " + curSpaceArea + "㎡"
  833. console.log("该户型空间数据:", this.spaceList);
  834. console.log("当前选中的空间:", this.curSpaceObj);
  835. this.positionCamer(this.curSpaceObj);
  836. this.loaderSpaceArr(this.spaceList);//绘制地板
  837. // 获取墙体数据并且绘制墙体
  838. this.getHouseTypeSpaceWalls();
  839. },
  840. // 获取墙体数据
  841. async getHouseTypeSpaceWalls(){
  842. let wallList = [];
  843. if(this.wallList){
  844. wallList = this.wallList;
  845. }else{
  846. let data = {id:this.wallIds}
  847. const res = await requestConfig('getHouseTypeSpaceWalls', data, true);
  848. // console.log("墙体数据:", res.list)
  849. if(res.success){
  850. wallList = this.wallList = res.list;
  851. }
  852. }
  853. let wallArr = []
  854. for (let index = 0; index < wallList.length; index++) {//每个空间对应一个数据
  855. let element = JSON.parse(wallList[index].wallJson);
  856. let space = this.spaceList.find(space=>space.spaceId==element.spaceId);
  857. this.computeWallHandleOld(space,element);//提前计算
  858. for (let i = 0; i < element.wallData.length; i ++) {//对应空间里面的4个方向的墙壁数据
  859. let wallData = element.wallData[i];
  860. //对应方向的墙壁的墙体模型数据列表,每一面墙可能有多个模型
  861. for (let j = 0; j < wallData.wallModelData.length; j ++) {
  862. let wallModelData = wallData.wallModelData[j];
  863. wallArr.push({spaceId:element.spaceId, wallModelData:wallModelData, wallDirection:wallData.wallDirection})
  864. // console.log("wallModelData", element,wallData.wallDirection, wallModelData.wallType );
  865. }
  866. }
  867. }
  868. this.loadSpaceObjWalls(wallArr, wallList);
  869. this.getOverallArrangementDetailsList();//
  870. },
  871. // 加载单个空间墙体资源
  872. async loadSpaceObjWalls(wallArr, wallList){
  873. // 加载远程墙体模型资源
  874. let startTime = new Date().getTime();
  875. // console.log("wallArr:", wallArr)
  876. let promise_list = [];
  877. let realWallArr = this.preWallData(wallArr);
  878. let arrLength = realWallArr.length;
  879. realWallArr && realWallArr.forEach((item,index) => {
  880. promise_list.push(
  881. new Promise((resolve, reject) => {
  882. this.loadWallModels(item, wallList, arrLength , resolve);
  883. })
  884. )
  885. });
  886. Promise.all(promise_list).then(()=>{
  887. let endTime = new Date().getTime();
  888. console.log("墙体模型全部加载完成,时间:",endTime - startTime);
  889. // 设置空间数组的墙体信息
  890. // this.setSpaceListWallInfo();
  891. this.$nextTick(()=>{
  892. // this.moveMeshCenter(this.curSpaceObj);
  893. this.progress = 100;
  894. // this.$refs.myLoading.showLoading("加载中..." + this.progress + '%')
  895. this.$nextTick(()=>{
  896. this.myLoadingStatus = false;
  897. // this.$refs.myLoading.hideLoading();
  898. // this.meshRoam(this.curSpaceObj);//开始漫游,必须先选中模型
  899. })
  900. })
  901. })
  902. },
  903. }
  904. }
  905. </script>
  906. <style lang="scss" scoped>
  907. @import "./webgl_rxdz_roam.scss";
  908. /* @import "@/common/css/common.css"; */
  909. </style>