overlay.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. var MathLight = {};
  2. MathLight.RADIANS_PER_DEGREE = Math.PI / 180;
  3. MathLight.DEGREES_PER_RADIAN = 180 / Math.PI;
  4. var initOverlay = function(THREE) {
  5. var _planeGeometry = new THREE.PlaneGeometry(settings.overlay.width,settings.overlay.height,1,1)
  6. var _boxGeometry = new THREE.BoxBufferGeometry(settings.overlay.width,settings.overlay.height,settings.overlay.depth)
  7. //ie的mesh 加了polygonOffset也是会重叠。所以去掉前面的face: (但是突然ie又播放不了videoTexture)
  8. var newIndex = [..._boxGeometry.index.array]
  9. newIndex.splice(4 * 6, 6)
  10. _boxGeometry.setIndex(new THREE.BufferAttribute(new Uint16Array(newIndex),1))
  11. var _boxMat = new THREE.MeshBasicMaterial({
  12. //MeshStandardMaterial
  13. color: "#eeeeee",
  14. transparent: !0,
  15. opacity: 0.8
  16. })
  17. var overlayGroup = new THREE.Object3D;
  18. player.model.add(overlayGroup);
  19. overlayGroup.name = "overlayGroup"
  20. player.overlayGroup = overlayGroup;
  21. var Overlay = function(info) {
  22. THREE.Object3D.call(this);
  23. this.sid = info.sid;
  24. if (info.media)
  25. this.preDeal(info)
  26. this.build(info);
  27. this.name = "overlay_" + this.sid;
  28. }
  29. Overlay.prototype = Object.create(THREE.Object3D.prototype);
  30. Overlay.prototype.build = function(info) {
  31. if( info.media.includes('text') && !info.words)return;
  32. var plane = new THREE.Mesh(_planeGeometry,new THREE.MeshBasicMaterial({
  33. //MeshStandardMaterial
  34. color: "#00c8af",
  35. opacity: 0.4,
  36. transparent: !0,
  37. polygonOffset: true,
  38. //是否开启多边形偏移 //ie不开启时blank也不会闪烁
  39. polygonOffsetFactor: -0.9,
  40. //多边形偏移因子
  41. polygonOffsetUnits: -4.0,
  42. //多边形偏移单位
  43. }))
  44. plane.renderOrder = 3
  45. this.add(plane);
  46. this.plane = plane;
  47. if (info.hasBox) {
  48. this.addBox(true)
  49. }
  50. overlayGroup.add(this);
  51. if (info.media) {
  52. if (info.media.includes('video')) {
  53. //var id = "video"+ this.sid id="${ id }"
  54. var video = $(`<video controls="controls" loop autoplay x5-playsinline="" webkit-playsinline="true" playsinline="true" controlslist="nodownload"></video>`)[0]
  55. video.setAttribute("crossOrigin", 'Anonymous')
  56. //要在src设置好前解决跨域
  57. $(video).on('contextmenu', function() {
  58. return false;
  59. });
  60. //禁止右键点击出
  61. video.src = manage.dealURL(info.file);
  62. info.media = video;
  63. info.type = "video"
  64. /* video.addEventListener('loadeddata', ()=>{
  65. console.log(this.sid + " loaded!!!")
  66. }) */
  67. video.oncanplaythrough = function() {
  68. plane.material.map.needsUpdate = !0
  69. if(video.shouldPlay){
  70. video.play()
  71. }
  72. }
  73. video.volume = 0
  74. video.muted = true
  75. }else if(info.media.includes('photo')){
  76. /* var img = new Image();
  77. img.src = manage.dealURL(info.file) //"https://4dkk.4dage.com/images/images"+Config.projectNum+"/overlay"+this.sid+".jpg?m="+new Date().getTime()
  78. info.media = img
  79. */
  80. info.type = "photo"
  81. }else if(info.media.includes('text')){
  82. info.type = "text";
  83. var fontSize = 40;
  84. var lineHeight = fontSize * 2.1;//fontSize + 行间距
  85. var texWidthRitio = 0.86
  86. var canvas = document.createElement('canvas');
  87. var context = canvas.getContext('2d');
  88. canvas.width = 1024;
  89. context.font = `${fontSize}px 微软雅黑`;
  90. var result = []
  91. /* info.words = JSON.parse("[\"测试留言 2021-10-14 20:44:23\",\"“五角星”、“MACAU”、“莲花”、“CPLA”,由81人组成的枪械团体操将花式操枪动作与队形变换结合,不时变换出的图案代表了驻军官兵爱国爱澳的赤诚之心和捍卫国家主权、维护澳门繁荣稳定的坚强决心。💥💥💥💥💥💥💥💥💥💥💥\",\"————————————————\",\"\",\"移动端测试留言功能 2021-10-14 20:42:16\",\"“五角星”、“MACAU”、“莲花”、“CPLA”,由81人组成的枪械团体操将花式操枪动作与队形变换结合,不时变换出的图案代表了驻军官兵爱国爱澳的赤诚之心和捍卫国家主权、维护澳门繁荣稳定的坚强决心。💪💪💪💪💪💪💪💪💪💪💪💪\",\"————————————————\",\"\",\"123 2021-10-14 20:24:39\",\"测试留言\",\"————————————————\",\"\"]"
  92. )
  93. */
  94. info.words.forEach((words)=>{
  95. if(!words){result.push("");return;}
  96. result = result.concat ( breakLinesForCanvas(
  97. words,
  98. //'使用很寻常的二分查找,如果某一个位置之前的文字宽度小于等于设定的宽度,并且它之后一个字之前的文字宽度大于设定的宽度,那么这个位置就是文本的换行点。上面只是找到一个换行点,对于输入的一段文本,需要循环查找,直到不存在这样的换行点为止, 完整的代码如下',
  99. context, canvas.width * texWidthRitio ) )
  100. })
  101. canvas.height = (result.length + 1 ) * lineHeight
  102. var context = canvas.getContext('2d');//不知为什么要再获取一次context才行
  103. context.font = `${fontSize}px 微软雅黑`;
  104. /* context.fillStyle = '#fff';
  105. context.fillRect(0,0,canvas.width,canvas.height); */
  106. context.fillStyle = '#f5c772';
  107. result.forEach(function(line, index) {
  108. context.fillText(line, canvas.width * (1-texWidthRitio)/ 2, lineHeight * (index + 1));
  109. });
  110. var url = canvas.toDataURL()
  111. var img = new Image();
  112. img.src = url;
  113. info.media = img;
  114. info.lineCount = result.length
  115. }
  116. plane.material.opacity = 1;
  117. plane.material.color = new THREE.Color(1,1,1)
  118. }
  119. if (info.width == void 0)
  120. info.width = settings.overlay.width;
  121. if (info.height == void 0)
  122. info.height = settings.overlay.height;
  123. this.setFromInfo(info)
  124. this.fileSrc = info.file
  125. }
  126. Overlay.prototype.computeMapRepeat = function(info){//使得文字不变形
  127. clearInterval(this.mapInterval);
  128. var map = this.plane.material.map;
  129. var tw = map.image.width, th = map.image.height,
  130. w = this.width, h = this.height;
  131. var ratio = (h / w) / (th / tw); //显示的部分占据整个图高度的比例
  132. map.repeat.y = ratio
  133. if(th / tw > h / w){
  134. //如果贴图设置成不repeat(缺点是会有一段白屏期)
  135. /* map.offset.y = 1 - ratio;//向下移动 1-ratio个高度, 使图片的顶部显示在plane的最上方;之后滚动时正常repeat在 1-ratio到0之间变化 , 为了连续变化,改成 1 到 -ratio
  136. this.mapInterval = setInterval(()=>{
  137. map.offset.y -= 0.003;
  138. if(map.offset.y < -ratio )map.offset.y = 1
  139. },20) */
  140. //如果贴图设置成 repeat(缺点是 可能衔接时的缝隙比较窄)
  141. map.wrapS = map.wrapT = THREE.RepeatWrapping;
  142. map.offset.y = 1 - ratio;//向下移动 1-ratio个高度, 使图片的顶部显示在plane的最上方;之后滚动时正常repeat在 1-ratio到0之间变化 , 为了连续变化,改成 1 到 -ratio
  143. this.mapInterval = setInterval(()=>{
  144. map.offset.y -= 0.013 / info.lineCount ;
  145. //if(map.offset.y < -ratio )map.offset.y = 1
  146. },20)
  147. }else{//如果图可以完全展示
  148. map.offset.y = (1 - ratio) / 2;//居中
  149. map.wrapS = map.wrapT = THREE.ClampToEdgeWrapping;
  150. }
  151. map.needsUpdate = true;
  152. }
  153. Overlay.prototype.setFromInfo = function(info) {
  154. //1 恢复到编辑之前 2 初始加载
  155. var plane = this.plane;
  156. var transformAtPanos = {}
  157. for(var i in info.transformAtPanos){
  158. transformAtPanos[i] = {
  159. width : info.transformAtPanos[i].width,
  160. height : info.transformAtPanos[i].height,
  161. pos : info.transformAtPanos[i].pos.clone(),
  162. qua : info.transformAtPanos[i].qua.clone(),
  163. }
  164. }
  165. this.transformAtPanos = transformAtPanos
  166. //在每个漫游点独立设置的position。
  167. //var curPanoTransform = player.currentPano && this.transformAtPanos[player.currentPano.id] || {}
  168. var curPanoTransform = this.transformAtPanos[ getTransformSid()] || {}
  169. info.depth && this.scale.setZ(info.depth / settings.overlay.depth)
  170. this.posCustom = info.pos ? info.pos.clone() : this.position.clone();
  171. //没有单独设置position的漫游点使用的position
  172. this.position.copy(curPanoTransform.pos || this.posCustom)
  173. this.quaCustom = info.qua ? info.qua.clone() : this.quaternion.clone()
  174. this.quaternion.copy(curPanoTransform.qua || this.quaCustom);
  175. this.widthCustom = info.width
  176. this.heightCustom = info.height
  177. this.width = curPanoTransform.width || this.widthCustom
  178. this.height = curPanoTransform.height || this.heightCustom
  179. var a = this.getScaleBySize(this.width, this.height)
  180. this.scale.setX(a.x)
  181. this.scale.setY(a.y)
  182. if (info.type) {
  183. if (!plane.material.map) {
  184. if (info.type == "video") {
  185. plane.material.map = new THREE.VideoTexture(info.media);
  186. this.hasRequestLoad = true
  187. } else if(info.type == "photo"){
  188. this._loadDones = []
  189. }else{
  190. plane.material.map = new THREE.Texture;
  191. plane.material.map.image = info.media;
  192. info.media.onload = ()=>{
  193. plane.material.map.needsUpdate = true
  194. this.computeMapRepeat(info)
  195. }
  196. }
  197. }else{
  198. plane.material.map.image = info.media;
  199. }
  200. if(plane.material.map){
  201. plane.material.map.wrapS = plane.material.map.wrapT = THREE.ClampToEdgeWrapping;
  202. plane.material.map.minFilter = THREE.LinearFilter;
  203. plane.material.map.magFilter = THREE.LinearFilter;
  204. plane.material.map.generateMipmaps = true;
  205. }
  206. this.file = info.file;
  207. }
  208. this.overlayType = info.type;
  209. if (!!this.hasBox != !!info.hasBox) {
  210. this.addBox(!this.hasBox);
  211. }
  212. this.updateMatrixWorld()
  213. this.getVisiblePanos()
  214. {//gif
  215. if(this.animation){
  216. GifTexDeal.remove(this.animation)
  217. }
  218. this.animateInfo = CloneObject(info.animateInfo)
  219. if(this.animateInfo && plane.material.map){
  220. this.animation = GifTexDeal.addAnimation(plane.material.map, this, this.animateInfo, this.sid )
  221. this.visible && this.inSight() && GifTexDeal.start(this.animation)
  222. }
  223. }
  224. }
  225. Overlay.prototype.addBox = function(state) {
  226. if (state == !!this.hasBox) {
  227. return;
  228. }
  229. if (state) {
  230. var box = new THREE.Mesh(_boxGeometry,_boxMat)
  231. box.position.set(0, 0, settings.overlay.depth / 2);
  232. box.renderOrder = 3
  233. this.plane.position.set(0, 0, settings.overlay.depth);
  234. this.add(box);
  235. this.box = box;
  236. } else {
  237. this.plane.position.set(0, 0, 0);
  238. this.remove(this.box);
  239. this.box = null;
  240. }
  241. this.hasBox = state
  242. }
  243. Overlay.prototype.getSizeByScale = function() {
  244. return {
  245. width: settings.overlay.width * this.scale.x,
  246. height: settings.overlay.height * this.scale.y
  247. }
  248. }
  249. Overlay.prototype.getScaleBySize = function(width, height) {
  250. return {
  251. x: width / settings.overlay.width,
  252. y: height / settings.overlay.height,
  253. }
  254. }
  255. Overlay.prototype.preDeal = function(info) {
  256. info.pos = new THREE.Vector3().fromArray(info.pos)
  257. info.qua = new THREE.Quaternion().fromArray(info.qua)
  258. info.width = parseFloat(info.width)
  259. info.height = parseFloat(info.height)
  260. info.depth = parseFloat(info.depth)
  261. info.hasBox = parseInt(info.hasBox)
  262. info.pos.x = parseFloat(info.pos.x)
  263. info.pos.y = parseFloat(info.pos.y)
  264. info.pos.z = parseFloat(info.pos.z)
  265. info.qua.x = parseFloat(info.qua.x)
  266. info.qua.y = parseFloat(info.qua.y)
  267. info.qua.z = parseFloat(info.qua.z)
  268. info.qua.w = parseFloat(info.qua.w)
  269. if (!info.transformAtPanos)
  270. info.transformAtPanos = {}
  271. for (let i in info.transformAtPanos) {
  272. info.transformAtPanos[i].pos = new THREE.Vector3().fromArray(info.transformAtPanos[i].pos)
  273. info.transformAtPanos[i].qua = new THREE.Quaternion().fromArray(info.transformAtPanos[i].qua)
  274. }
  275. if(info.media.includes("text")){
  276. /*
  277. 只有http能加载
  278. */
  279. $.ajax({
  280. url: "/api/web/list",
  281. type: 'POST',
  282. dataType: "json",
  283. cache: false,
  284. contentType: 'application/json;charset=UTF-8',
  285. data : JSON.stringify({"pageNum":1,"pageSize":1000} ),
  286. success: (data)=>{
  287. console.log(data)
  288. var words = [];
  289. data.data.list.forEach((item,index)=>{
  290. /* words += item.nickName; words += " "
  291. words += item.createTime; words += "\n\n"
  292. words += item.msg; words += "\n"
  293. words += "————————\n\n" */
  294. words.push(item.nickName + " " + item.createTime);
  295. //words.push("");
  296. words.push(item.msg);
  297. words.push("————————————————");
  298. words.push("");
  299. })
  300. console.log(words)
  301. info.words = words
  302. this.build(info)
  303. },
  304. error: function (msg) {
  305. console.log(msg)
  306. }
  307. });
  308. }
  309. }
  310. Overlay.prototype.getVisiblePanos = function() {
  311. this.visiblePanos = common.getVisiblePano(this.plane.getWorldPosition(), {
  312. model: null
  313. });
  314. }
  315. Overlay.prototype.updateVisibles = function(panos) {
  316. if(settings.isEdit && EditOverlay.editPlane == this){
  317. return true
  318. }
  319. this.visible = !!panos.find(pano=>this.visiblePanos.includes(pano))
  320. if (!this.visible && this.overlayType == 'video')
  321. this.videoControl('stop')
  322. }
  323. Overlay.updateVisibles = function(panos) {
  324. if (panos === true) {
  325. player.overlayGroup.children.forEach(e=>e.visible = true)
  326. } else {
  327. player.overlayGroup.children.forEach(e=>e.updateVisibles && e.updateVisibles(panos))
  328. }
  329. }
  330. Overlay.prototype.videoControl = function(state){
  331. if(this.overlayType != "video")return
  332. var video = this.plane.material.map.image
  333. if(!state || state == 'stop'){
  334. video.paused || video.pause()
  335. if(state == 'stop'){
  336. video.currentTime = 0;
  337. }
  338. video.shouldPlay = false
  339. //console.log("pause")
  340. }else if(state){
  341. video.paused && video.play()
  342. video.shouldPlay = true
  343. //console.log("play")
  344. }
  345. }
  346. Overlay.prototype.inSight = function(){
  347. if(player.mode == 'panorama'){
  348. var position = this.plane.getWorldPosition()
  349. var pos2d = math.getPos2d(position, player.camera, $("#player")[0])
  350. if(pos2d.trueSide && pos2d.inSight){
  351. return true
  352. }else{
  353. var cornerPoint = [
  354. new THREE.Vector3(-settings.overlay.width/2, settings.overlay.height/2, 0),
  355. new THREE.Vector3(settings.overlay.width/2, settings.overlay.height/2, 0),
  356. new THREE.Vector3(settings.overlay.width/2, -settings.overlay.height/2, 0),
  357. new THREE.Vector3(-settings.overlay.width/2, -settings.overlay.height/2, 0),
  358. ];
  359. for(var i=0;i<4;i++){
  360. cornerPoint[i].applyMatrix4(this.plane.matrixWorld);
  361. var pos2d = math.getPos2d(cornerPoint[i], player.camera, $("#player")[0])
  362. if(pos2d.trueSide && pos2d.inSight){
  363. return true
  364. }
  365. }
  366. }
  367. }else{
  368. return true
  369. }
  370. }
  371. Overlay.prototype.addToLoadQueue = function() {
  372. if (this.overlayType == 'photo') {
  373. Overlay.loadQueue.includes(this) || Overlay.loadQueue.push(this)
  374. }
  375. }
  376. Overlay.prototype.requestDownload = function() {
  377. if (this.hasRequestLoad || this.overlayType != 'photo')
  378. return
  379. console.log('overlay beginDownload : ' + this.sid)
  380. var plane = this.plane;
  381. plane.material.map = Texture.load(this.file, ()=>{
  382. if (this._loadDones) {
  383. this._loadDones.forEach(e=>e())
  384. this._loadDones = null
  385. }
  386. setTimeout(Overlay.loadNext, 50)
  387. plane.material.opacity = 1;
  388. console.log('overlay loaded: ' + this.sid)
  389. if(this.animateInfo){
  390. this.animation = GifTexDeal.addAnimation(plane.material.map, this, this.animateInfo, this.sid )
  391. this.visible && this.inSight() && GifTexDeal.start(this.animation)
  392. }
  393. plane.material.needsUpdate = true
  394. })
  395. plane.material.map.wrapS = plane.material.map.wrapT = THREE.ClampToEdgeWrapping;
  396. plane.material.map.minFilter = THREE.LinearFilter;
  397. plane.material.map.magFilter = THREE.LinearFilter;
  398. plane.material.map.generateMipmaps = true;
  399. this.hasRequestLoad = true
  400. }
  401. Overlay.loadQueue = []; //等待下载的overlay,目前只针对photo
  402. Overlay.maxLoadingCount = 3; //同时正在load图片的数量
  403. Overlay.loadNext = ()=>{//继续requestDownload loadQueue中前排的item
  404. var loadings = player.overlayGroup.children.filter(e=>e.hasRequestLoad && e._loadDones)//开始下载了但是没加载好的
  405. Overlay.loadQueue.slice(0, Overlay.maxLoadingCount - loadings.length).forEach(e=>e.requestDownload())
  406. Overlay.loadQueue.splice(0, Overlay.maxLoadingCount - loadings.length)
  407. }
  408. Overlay.getNeedLoad = function() {//计算获取loadQueue,每次都重新计算,覆盖旧的
  409. if (!player || !player.domElement || !player.mode)
  410. return;
  411. if (player.mode != 'panorama') {
  412. if (!Overlay.loadWhenOutside)
  413. return;
  414. if (Overlay.loadQueue.length == 0) {
  415. Overlay.loadQueue = player.overlayGroup.children.filter(e=>!e.hasRequestLoad).slice(0, 5);
  416. }
  417. return;
  418. }
  419. Overlay.loadWhenOutside = true
  420. var overlays = player.overlayGroup.children.filter(e=>!e.hasRequestLoad && e.visiblePanos.includes(player.currentPano))
  421. //var maxAngle = THREE.Math.degToRad( cameraLight.getHFOVFromVFOV(70, player.domElement.clientWidth, app.player.domElement.clientHeight) / 2);
  422. var cameraDir = player.getDirection()
  423. /* var maxCount = 5;
  424. if(overlays.length>maxCount){
  425. for(var i=0;i<overlays.length;i++){
  426. //角度为可见范围
  427. var v1 = cameraDir.clone().setY(0);
  428. var v2 = overlays[i].plane.getWorldPosition().sub(player.position).setY(0)
  429. if(v1.angleTo(v2) <= maxAngle){
  430. Overlay.loadQueue.push(overlays[i])
  431. if(Overlay.loadQueue.length>=10) break;
  432. }
  433. }
  434. if(Overlay.loadQueue.length<Overlay.maxLoadingCount){
  435. Overlay.loadQueue.push()
  436. }
  437. }else{ */
  438. Overlay.loadQueue = overlays
  439. //}
  440. var request = [(overlay)=>{
  441. return true
  442. }
  443. ];
  444. var rank = [(overlay)=>{
  445. var dis = overlay.plane.getWorldPosition().distanceTo(player.position);
  446. return -dis
  447. }
  448. , (overlay)=>{
  449. var tagDir = overlay.plane.getWorldPosition().sub(player.position)
  450. var angle = tagDir.angleTo(cameraDir)
  451. return -angle * 20
  452. }
  453. ]
  454. var result = common.sortByScore(Overlay.loadQueue, request, rank);
  455. Overlay.loadQueue = result ? result.slice(0, 5).map(e=>e.item) : player.overlayGroup.children.filter(e=>!e.hasRequestLoad).slice(0, 2);
  456. }
  457. Overlay.load = ()=>{//开始下载图片
  458. Overlay.getNeedLoad()
  459. Overlay.loadNext()
  460. var unloads = player.overlayGroup.children.filter(e=>!e.hasRequestLoad)
  461. if (unloads.length) {
  462. setTimeout(Overlay.load, 200)
  463. } else {
  464. Overlay.allRequestLoad = true
  465. console.log('allRequestLoad')
  466. }
  467. }
  468. function findBreakPoint(text, width, context) {
  469. var min = 0;
  470. var max = text.length - 1;
  471. while (min <= max) {
  472. var middle = Math.floor((min + max) / 2);
  473. var middleWidth = context.measureText(text.substr(0, middle)).width;
  474. var oneCharWiderThanMiddleWidth = context.measureText(text.substr(0, middle + 1)).width;
  475. if (middleWidth <= width && oneCharWiderThanMiddleWidth > width) {
  476. return middle;
  477. }
  478. if (middleWidth < width) {
  479. min = middle + 1;
  480. } else {
  481. max = middle - 1;
  482. }
  483. }
  484. return -1;
  485. }
  486. function breakLinesForCanvas(text, context, width, font) {
  487. var result = [];
  488. var breakPoint = 0;
  489. if (font) {
  490. context.font = font;
  491. }
  492. while ((breakPoint = findBreakPoint(text, width, context)) !== -1) {
  493. result.push(text.substr(0, breakPoint));
  494. text = text.substr(breakPoint);
  495. }
  496. if (text) {
  497. result.push(text);
  498. }
  499. return result;
  500. }
  501. window.Overlay = Overlay;
  502. }