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. info.words.forEach((words)=>{
  94. if(!words){result.push("");return;}
  95. result = result.concat ( breakLinesForCanvas(
  96. words,
  97. //'使用很寻常的二分查找,如果某一个位置之前的文字宽度小于等于设定的宽度,并且它之后一个字之前的文字宽度大于设定的宽度,那么这个位置就是文本的换行点。上面只是找到一个换行点,对于输入的一段文本,需要循环查找,直到不存在这样的换行点为止, 完整的代码如下',
  98. context, canvas.width * texWidthRitio ) )
  99. })
  100. canvas.height = (result.length + 1 ) * lineHeight
  101. var context = canvas.getContext('2d');//不知为什么要再获取一次context才行
  102. context.font = `${fontSize}px 微软雅黑`;
  103. /* context.fillStyle = '#fff';
  104. context.fillRect(0,0,canvas.width,canvas.height); */
  105. context.fillStyle = '#f5c772';
  106. result.forEach(function(line, index) {
  107. context.fillText(line, canvas.width * (1-texWidthRitio)/ 2, lineHeight * (index + 1));
  108. });
  109. var url = canvas.toDataURL()
  110. var img = new Image();
  111. img.src = url;
  112. info.media = img;
  113. info.lineCount = result.length
  114. }
  115. plane.material.opacity = 1;
  116. plane.material.color = new THREE.Color(1,1,1)
  117. }
  118. if (info.width == void 0)
  119. info.width = settings.overlay.width;
  120. if (info.height == void 0)
  121. info.height = settings.overlay.height;
  122. this.setFromInfo(info)
  123. this.fileSrc = info.file
  124. }
  125. Overlay.prototype.computeMapRepeat = function(info){//使得文字不变形
  126. clearInterval(this.mapInterval);
  127. var map = this.plane.material.map;
  128. var tw = map.image.width, th = map.image.height,
  129. w = this.width, h = this.height;
  130. var ratio = (h / w) / (th / tw); //显示的部分占据整个图高度的比例
  131. map.repeat.y = ratio
  132. if(th / tw > h / w){
  133. //如果贴图设置成不repeat(缺点是会有一段白屏期)
  134. /* map.offset.y = 1 - ratio;//向下移动 1-ratio个高度, 使图片的顶部显示在plane的最上方;之后滚动时正常repeat在 1-ratio到0之间变化 , 为了连续变化,改成 1 到 -ratio
  135. this.mapInterval = setInterval(()=>{
  136. map.offset.y -= 0.003;
  137. if(map.offset.y < -ratio )map.offset.y = 1
  138. },20) */
  139. //如果贴图设置成 repeat(缺点是 可能衔接时的缝隙比较窄)
  140. map.wrapS = map.wrapT = THREE.RepeatWrapping;
  141. map.offset.y = 1 - ratio;//向下移动 1-ratio个高度, 使图片的顶部显示在plane的最上方;之后滚动时正常repeat在 1-ratio到0之间变化 , 为了连续变化,改成 1 到 -ratio
  142. this.mapInterval = setInterval(()=>{
  143. map.offset.y -= 0.013 / info.lineCount ;
  144. //if(map.offset.y < -ratio )map.offset.y = 1
  145. },20)
  146. }else{//如果图可以完全展示
  147. map.offset.y = (1 - ratio) / 2;//居中
  148. map.wrapS = map.wrapT = THREE.ClampToEdgeWrapping;
  149. }
  150. map.needsUpdate = true;
  151. }
  152. Overlay.prototype.setFromInfo = function(info) {
  153. //1 恢复到编辑之前 2 初始加载
  154. var plane = this.plane;
  155. var transformAtPanos = {}
  156. for(var i in info.transformAtPanos){
  157. transformAtPanos[i] = {
  158. width : info.transformAtPanos[i].width,
  159. height : info.transformAtPanos[i].height,
  160. pos : info.transformAtPanos[i].pos.clone(),
  161. qua : info.transformAtPanos[i].qua.clone(),
  162. }
  163. }
  164. this.transformAtPanos = transformAtPanos
  165. //在每个漫游点独立设置的position。
  166. //var curPanoTransform = player.currentPano && this.transformAtPanos[player.currentPano.id] || {}
  167. var curPanoTransform = this.transformAtPanos[ getTransformSid()] || {}
  168. info.depth && this.scale.setZ(info.depth / settings.overlay.depth)
  169. this.posCustom = info.pos ? info.pos.clone() : this.position.clone();
  170. //没有单独设置position的漫游点使用的position
  171. this.position.copy(curPanoTransform.pos || this.posCustom)
  172. this.quaCustom = info.qua ? info.qua.clone() : this.quaternion.clone()
  173. this.quaternion.copy(curPanoTransform.qua || this.quaCustom);
  174. this.widthCustom = info.width
  175. this.heightCustom = info.height
  176. this.width = curPanoTransform.width || this.widthCustom
  177. this.height = curPanoTransform.height || this.heightCustom
  178. var a = this.getScaleBySize(this.width, this.height)
  179. this.scale.setX(a.x)
  180. this.scale.setY(a.y)
  181. if (info.type) {
  182. if (!plane.material.map) {
  183. if (info.type == "video") {
  184. plane.material.map = new THREE.VideoTexture(info.media);
  185. this.hasRequestLoad = true
  186. } else if(info.type == "photo"){
  187. this._loadDones = []
  188. }else{
  189. plane.material.map = new THREE.Texture;
  190. plane.material.map.image = info.media;
  191. info.media.onload = ()=>{
  192. plane.material.map.needsUpdate = true
  193. this.computeMapRepeat(info)
  194. }
  195. }
  196. }else{
  197. plane.material.map.image = info.media;
  198. }
  199. if(plane.material.map){
  200. plane.material.map.wrapS = plane.material.map.wrapT = THREE.ClampToEdgeWrapping;
  201. plane.material.map.minFilter = THREE.LinearFilter;
  202. plane.material.map.magFilter = THREE.LinearFilter;
  203. plane.material.map.generateMipmaps = true;
  204. }
  205. this.file = info.file;
  206. }
  207. this.overlayType = info.type;
  208. if (!!this.hasBox != !!info.hasBox) {
  209. this.addBox(!this.hasBox);
  210. }
  211. this.updateMatrixWorld()
  212. this.getVisiblePanos()
  213. {//gif
  214. if(this.animation){
  215. GifTexDeal.remove(this.animation)
  216. }
  217. this.animateInfo = CloneObject(info.animateInfo)
  218. if(this.animateInfo && plane.material.map){
  219. this.animation = GifTexDeal.addAnimation(plane.material.map, this, this.animateInfo, this.sid )
  220. this.visible && this.inSight() && GifTexDeal.start(this.animation)
  221. }
  222. }
  223. }
  224. Overlay.prototype.addBox = function(state) {
  225. if (state == !!this.hasBox) {
  226. return;
  227. }
  228. if (state) {
  229. var box = new THREE.Mesh(_boxGeometry,_boxMat)
  230. box.position.set(0, 0, settings.overlay.depth / 2);
  231. box.renderOrder = 3
  232. this.plane.position.set(0, 0, settings.overlay.depth);
  233. this.add(box);
  234. this.box = box;
  235. } else {
  236. this.plane.position.set(0, 0, 0);
  237. this.remove(this.box);
  238. this.box = null;
  239. }
  240. this.hasBox = state
  241. }
  242. Overlay.prototype.getSizeByScale = function() {
  243. return {
  244. width: settings.overlay.width * this.scale.x,
  245. height: settings.overlay.height * this.scale.y
  246. }
  247. }
  248. Overlay.prototype.getScaleBySize = function(width, height) {
  249. return {
  250. x: width / settings.overlay.width,
  251. y: height / settings.overlay.height,
  252. }
  253. }
  254. Overlay.prototype.preDeal = function(info) {
  255. info.pos = new THREE.Vector3().fromArray(info.pos)
  256. info.qua = new THREE.Quaternion().fromArray(info.qua)
  257. info.width = parseFloat(info.width)
  258. info.height = parseFloat(info.height)
  259. info.depth = parseFloat(info.depth)
  260. info.hasBox = parseInt(info.hasBox)
  261. info.pos.x = parseFloat(info.pos.x)
  262. info.pos.y = parseFloat(info.pos.y)
  263. info.pos.z = parseFloat(info.pos.z)
  264. info.qua.x = parseFloat(info.qua.x)
  265. info.qua.y = parseFloat(info.qua.y)
  266. info.qua.z = parseFloat(info.qua.z)
  267. info.qua.w = parseFloat(info.qua.w)
  268. if (!info.transformAtPanos)
  269. info.transformAtPanos = {}
  270. for (let i in info.transformAtPanos) {
  271. info.transformAtPanos[i].pos = new THREE.Vector3().fromArray(info.transformAtPanos[i].pos)
  272. info.transformAtPanos[i].qua = new THREE.Quaternion().fromArray(info.transformAtPanos[i].qua)
  273. }
  274. if(info.media.includes("text")){
  275. /*
  276. 只有http能加载
  277. */
  278. $.ajax({
  279. url: "/api/web/list",
  280. type: 'POST',
  281. dataType: "json",
  282. cache: false,
  283. contentType: 'application/json;charset=UTF-8',
  284. data : JSON.stringify({"pageNum":1,"pageSize":1000} ),
  285. success: (data)=>{
  286. console.log(data)
  287. var words = [];
  288. data.data.list.forEach((item,index)=>{
  289. /* words += item.nickName; words += " "
  290. words += item.createTime; words += "\n\n"
  291. words += item.msg; words += "\n"
  292. words += "————————\n\n" */
  293. words.push(item.nickName + " " + item.createTime);
  294. //words.push("");
  295. words.push(item.msg);
  296. words.push("————————————————");
  297. words.push("");
  298. })
  299. console.log(words)
  300. info.words = words
  301. this.build(info)
  302. },
  303. error: function (msg) {
  304. console.log(msg)
  305. }
  306. });
  307. }
  308. }
  309. Overlay.prototype.getVisiblePanos = function() {
  310. this.visiblePanos = common.getVisiblePano(this.plane.getWorldPosition(), {
  311. model: null
  312. });
  313. }
  314. Overlay.prototype.updateVisibles = function(panos) {
  315. if(settings.isEdit && EditOverlay.editPlane == this){
  316. return true
  317. }
  318. this.visible = !!panos.find(pano=>this.visiblePanos.includes(pano))
  319. if (!this.visible && this.overlayType == 'video')
  320. this.videoControl('stop')
  321. }
  322. Overlay.updateVisibles = function(panos) {
  323. if (panos === true) {
  324. player.overlayGroup.children.forEach(e=>e.visible = true)
  325. } else {
  326. player.overlayGroup.children.forEach(e=>e.updateVisibles && e.updateVisibles(panos))
  327. }
  328. }
  329. Overlay.prototype.videoControl = function(state){
  330. if(this.overlayType != "video")return
  331. var video = this.plane.material.map.image
  332. if(!state || state == 'stop'){
  333. video.paused || video.pause()
  334. if(state == 'stop'){
  335. video.currentTime = 0;
  336. }
  337. video.shouldPlay = false
  338. //console.log("pause")
  339. }else if(state){
  340. video.paused && video.play()
  341. video.shouldPlay = true
  342. //console.log("play")
  343. }
  344. }
  345. Overlay.prototype.inSight = function(){
  346. if(player.mode == 'panorama'){
  347. var position = this.plane.getWorldPosition()
  348. var pos2d = math.getPos2d(position, player.camera, $("#player")[0])
  349. if(pos2d.trueSide && pos2d.inSight){
  350. return true
  351. }else{
  352. var cornerPoint = [
  353. new THREE.Vector3(-settings.overlay.width/2, settings.overlay.height/2, 0),
  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. ];
  358. for(var i=0;i<4;i++){
  359. cornerPoint[i].applyMatrix4(this.plane.matrixWorld);
  360. var pos2d = math.getPos2d(cornerPoint[i], player.camera, $("#player")[0])
  361. if(pos2d.trueSide && pos2d.inSight){
  362. return true
  363. }
  364. }
  365. }
  366. }else{
  367. return true
  368. }
  369. }
  370. Overlay.prototype.addToLoadQueue = function() {
  371. if (this.overlayType == 'photo') {
  372. Overlay.loadQueue.includes(this) || Overlay.loadQueue.push(this)
  373. }
  374. }
  375. Overlay.prototype.requestDownload = function() {
  376. if (this.hasRequestLoad || this.overlayType != 'photo')
  377. return
  378. console.log('overlay beginDownload : ' + this.sid)
  379. var plane = this.plane;
  380. plane.material.map = Texture.load(this.file, ()=>{
  381. if (this._loadDones) {
  382. this._loadDones.forEach(e=>e())
  383. this._loadDones = null
  384. }
  385. setTimeout(Overlay.loadNext, 50)
  386. plane.material.opacity = 1;
  387. console.log('overlay loaded: ' + this.sid)
  388. if(this.animateInfo){
  389. this.animation = GifTexDeal.addAnimation(plane.material.map, this, this.animateInfo, this.sid )
  390. this.visible && this.inSight() && GifTexDeal.start(this.animation)
  391. }
  392. plane.material.needsUpdate = true
  393. })
  394. plane.material.map.wrapS = plane.material.map.wrapT = THREE.ClampToEdgeWrapping;
  395. plane.material.map.minFilter = THREE.LinearFilter;
  396. plane.material.map.magFilter = THREE.LinearFilter;
  397. plane.material.map.generateMipmaps = true;
  398. this.hasRequestLoad = true
  399. }
  400. Overlay.loadQueue = []; //等待下载的overlay,目前只针对photo
  401. Overlay.maxLoadingCount = 3; //同时正在load图片的数量
  402. Overlay.loadNext = ()=>{//继续requestDownload loadQueue中前排的item
  403. var loadings = player.overlayGroup.children.filter(e=>e.hasRequestLoad && e._loadDones)//开始下载了但是没加载好的
  404. Overlay.loadQueue.slice(0, Overlay.maxLoadingCount - loadings.length).forEach(e=>e.requestDownload())
  405. Overlay.loadQueue.splice(0, Overlay.maxLoadingCount - loadings.length)
  406. }
  407. Overlay.getNeedLoad = function() {//计算获取loadQueue,每次都重新计算,覆盖旧的
  408. if (!player || !player.domElement || !player.mode)
  409. return;
  410. if (player.mode != 'panorama') {
  411. if (!Overlay.loadWhenOutside)
  412. return;
  413. if (Overlay.loadQueue.length == 0) {
  414. Overlay.loadQueue = player.overlayGroup.children.filter(e=>!e.hasRequestLoad).slice(0, 5);
  415. }
  416. return;
  417. }
  418. Overlay.loadWhenOutside = true
  419. var overlays = player.overlayGroup.children.filter(e=>!e.hasRequestLoad && e.visiblePanos.includes(player.currentPano))
  420. //var maxAngle = THREE.Math.degToRad( cameraLight.getHFOVFromVFOV(70, player.domElement.clientWidth, app.player.domElement.clientHeight) / 2);
  421. var cameraDir = player.getDirection()
  422. /* var maxCount = 5;
  423. if(overlays.length>maxCount){
  424. for(var i=0;i<overlays.length;i++){
  425. //角度为可见范围
  426. var v1 = cameraDir.clone().setY(0);
  427. var v2 = overlays[i].plane.getWorldPosition().sub(player.position).setY(0)
  428. if(v1.angleTo(v2) <= maxAngle){
  429. Overlay.loadQueue.push(overlays[i])
  430. if(Overlay.loadQueue.length>=10) break;
  431. }
  432. }
  433. if(Overlay.loadQueue.length<Overlay.maxLoadingCount){
  434. Overlay.loadQueue.push()
  435. }
  436. }else{ */
  437. Overlay.loadQueue = overlays
  438. //}
  439. var request = [(overlay)=>{
  440. return true
  441. }
  442. ];
  443. var rank = [(overlay)=>{
  444. var dis = overlay.plane.getWorldPosition().distanceTo(player.position);
  445. return -dis
  446. }
  447. , (overlay)=>{
  448. var tagDir = overlay.plane.getWorldPosition().sub(player.position)
  449. var angle = tagDir.angleTo(cameraDir)
  450. return -angle * 20
  451. }
  452. ]
  453. var result = common.sortByScore(Overlay.loadQueue, request, rank);
  454. Overlay.loadQueue = result ? result.slice(0, 5).map(e=>e.item) : player.overlayGroup.children.filter(e=>!e.hasRequestLoad).slice(0, 2);
  455. }
  456. Overlay.load = ()=>{//开始下载图片
  457. Overlay.getNeedLoad()
  458. Overlay.loadNext()
  459. var unloads = player.overlayGroup.children.filter(e=>!e.hasRequestLoad)
  460. if (unloads.length) {
  461. setTimeout(Overlay.load, 200)
  462. } else {
  463. Overlay.allRequestLoad = true
  464. console.log('allRequestLoad')
  465. }
  466. }
  467. function findBreakPoint(text, width, context) {
  468. var min = 0;
  469. var max = text.length - 1;
  470. while (min <= max) {
  471. var middle = Math.floor((min + max) / 2);
  472. var middleWidth = context.measureText(text.substr(0, middle)).width;
  473. var oneCharWiderThanMiddleWidth = context.measureText(text.substr(0, middle + 1)).width;
  474. if (middleWidth <= width && oneCharWiderThanMiddleWidth > width) {
  475. return middle;
  476. }
  477. if (middleWidth < width) {
  478. min = middle + 1;
  479. } else {
  480. max = middle - 1;
  481. }
  482. }
  483. return -1;
  484. }
  485. function breakLinesForCanvas(text, context, width, font) {
  486. var result = [];
  487. var breakPoint = 0;
  488. if (font) {
  489. context.font = font;
  490. }
  491. while ((breakPoint = findBreakPoint(text, width, context)) !== -1) {
  492. result.push(text.substr(0, breakPoint));
  493. text = text.substr(breakPoint);
  494. }
  495. if (text) {
  496. result.push(text);
  497. }
  498. return result;
  499. }
  500. window.Overlay = Overlay;
  501. }