index.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. //参考 https://artsandculture.google.com/experiment/TAEPZtXK2s139g
  2. let camera, scene, renderer;
  3. const shadowHasAlpha = false //阴影是否考虑光透过透明材质
  4. const planeGeo = new THREE.PlaneBufferGeometry(1, 1)
  5. const raycaster = new THREE.Raycaster(); raycaster.linePrecision = 0;//不检测boxHelper
  6. const mouse = new THREE.Vector2();
  7. let needUpdateShadow, needsUpdateScene
  8. const Density = 2.5
  9. var BlurShader = {
  10. uniforms: {
  11. "map": { value: null },
  12. "blurRadius": { value: new THREE.Vector2(1.0 / 512.0, 1.0 / 512.0) },
  13. 'opacity': { value: 0 }
  14. },
  15. vertexShader: [
  16. "varying vec2 vUv;",
  17. "void main() {",
  18. " vUv = uv;",
  19. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  20. "}"
  21. ].join("\n"),
  22. fragmentShader: [
  23. "uniform sampler2D map;",
  24. "uniform vec2 resolution;",
  25. "uniform float blurRadius;",
  26. "uniform float opacity;",
  27. "varying vec2 vUv;",
  28. "void main() {",
  29. " vec2 offset = blurRadius / resolution; ",
  30. " vec4 sum = vec4( 0.0 );",
  31. " sum += texture2D( map, vec2( vUv.x - 4.0 * offset.x, vUv.y ) ) * 0.051;",
  32. " sum += texture2D( map, vec2( vUv.x - 3.0 * offset.x, vUv.y ) ) * 0.0918;",
  33. " sum += texture2D( map, vec2( vUv.x - 2.0 * offset.x, vUv.y ) ) * 0.12245;",
  34. " sum += texture2D( map, vec2( vUv.x - 1.0 * offset.x, vUv.y ) ) * 0.1531;",
  35. " sum += texture2D( map, vec2( vUv.x, vUv.y ) ) * 0.1633;",
  36. " sum += texture2D( map, vec2( vUv.x + 1.0 * offset.x, vUv.y ) ) * 0.1531;",
  37. " sum += texture2D( map, vec2( vUv.x + 2.0 * offset.x, vUv.y ) ) * 0.12245;",
  38. " sum += texture2D( map, vec2( vUv.x + 3.0 * offset.x, vUv.y ) ) * 0.0918;",
  39. " sum += texture2D( map, vec2( vUv.x + 4.0 * offset.x, vUv.y ) ) * 0.051;",
  40. " sum += texture2D( map, vec2( vUv.x , vUv.y - 4.0 * offset.y ) ) * 0.051;",
  41. " sum += texture2D( map, vec2( vUv.x , vUv.y - 3.0 * offset.y) ) * 0.0918;",
  42. " sum += texture2D( map, vec2( vUv.x , vUv.y - 2.0 * offset.y) ) * 0.12245;",
  43. " sum += texture2D( map, vec2( vUv.x , vUv.y - 1.0 * offset.y ) ) * 0.1531;",
  44. " sum += texture2D( map, vec2( vUv.x , vUv.y ) ) * 0.1633;",
  45. " sum += texture2D( map, vec2( vUv.x , vUv.y + 1.0 * offset.y ) ) * 0.1531;",
  46. " sum += texture2D( map, vec2( vUv.x , vUv.y + 2.0 * offset.y ) ) * 0.12245;",
  47. " sum += texture2D( map, vec2( vUv.x , vUv.y + 3.0 * offset.y ) ) * 0.0918;",
  48. " sum += texture2D( map, vec2( vUv.x , vUv.y + 4.0 * offset.y ) ) * 0.051;",
  49. " gl_FragColor = sum / 2.0 ;",
  50. " gl_FragColor.a *= opacity;",
  51. "}"
  52. ].join("\n")
  53. };
  54. var isMobile = (function() {
  55. var e = navigator.userAgent || navigator.vendor || window.opera
  56. return (
  57. /(android|bb\d+|meego).+mobile|android|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(
  58. e
  59. ) ||
  60. /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(
  61. e.substr(0, 4)
  62. )
  63. )
  64. })()
  65. var Viewer = function (index, dom) {
  66. this.index = index;
  67. this.dom = dom
  68. this.camera = new THREE.PerspectiveCamera(setting.vfov);
  69. this.camera.position.set(0, 1, -1.5);
  70. this.control = new PanoramaControls(this.camera, this.dom)
  71. this.control.latMin = this.control.latMax = 0
  72. //this.control.target.set(0,-1,0)
  73. this.setRenderer()
  74. this.scene = new THREE.Scene;
  75. this.scene.background = common.loadTexture("background.jpg")
  76. this.pointerDownPos
  77. this.active = false;
  78. this.antialias = true;
  79. this.clickTime = new Date().getTime();
  80. this.updateClock = new THREE.Clock;
  81. this.cardGroup = new THREE.Object3D();
  82. this.scene.add(this.cardGroup);
  83. this.cardGroup.name = "cardGroup";
  84. this.autoMove = true
  85. this.bindEvents()
  86. this.preLoadCards()
  87. this.animate()
  88. }
  89. /*
  90. 同一时间,视线范围不能同时出现两张卡。也就是分布要根据视角范围变化,但是如果浏览器变宽导致的出现两张卡不算。
  91. */
  92. Viewer.prototype.preLoadCards = function () {
  93. let i = 10
  94. while (i-- > 0) {
  95. this.addCard(true)
  96. }
  97. let add = () => {
  98. if (document.hidden) return
  99. let count = this.getCount()
  100. let hopeCount = Density * (this.renderer.domElement.clientWidth * this.renderer.domElement.clientHeight) / 100000
  101. if(count < hopeCount){
  102. let ratio = count / hopeCount
  103. if(Math.random() > ratio){
  104. this.addCard()
  105. }
  106. }
  107. setTimeout(add, 1000/* 40000 * Math.random() * this.getDensity() */) //当前视野中密度越小 添加越频繁
  108. }
  109. add()
  110. document.addEventListener('visibilitychange', (e) => {
  111. if (!document.hidden) add()
  112. console.log('document.hidden', document.hidden)
  113. })
  114. }
  115. Viewer.prototype.getCount = function () {
  116. let frustumMatrix = new THREE.Matrix4
  117. frustumMatrix.multiplyMatrices(this.camera.projectionMatrix, this.camera.matrixWorldInverse)
  118. let frustum = new THREE.Frustum();
  119. frustum.setFromProjectionMatrix(frustumMatrix)
  120. let count = this.cardGroup.children.filter(card => {
  121. return frustum.containsPoint(card.position)
  122. }).length
  123. return count
  124. }
  125. Viewer.prototype.addCard = function (around) {
  126. let cardIndex = Math.floor(cardNames.length * Math.random())
  127. common.loadTexture(cardNames[cardIndex], (map) => {
  128. /* let card = new THREE.Mesh(planeGeo, new THREE.MeshBasicMaterial({
  129. map,
  130. transparent:true, opacity:0,side:2
  131. })) */
  132. let card = new THREE.Mesh(planeGeo, new THREE.ShaderMaterial({
  133. uniforms: {
  134. map: { value: map },
  135. resolution: { value: new THREE.Vector2(this.renderer.domElement.width, this.renderer.domElement.height) },
  136. blurRadius: { value: 0 },//像素
  137. opacity: { value: 0 }
  138. },
  139. vertexShader: BlurShader.vertexShader,
  140. fragmentShader: BlurShader.fragmentShader,
  141. transparent: true, side: 2
  142. }))
  143. Object.defineProperty(card.material, 'opacity', {
  144. get: function () {
  145. return card.material.uniforms.opacity.value
  146. },
  147. set: function (e) {
  148. card.material.uniforms.opacity.value = e
  149. card.material.uniforms.blurRadius.value = math.linearClamp(e, [0, 0.4], [40, 0])
  150. }
  151. })
  152. let direction, far = setting.cards.far
  153. if (around) {//在四周所有方向都可生成,在一开始时需要
  154. let n = 0.6//范围0-1 越大越可能接近相机
  155. far = far * (1 - n * Math.random()) //靠近一点
  156. direction = new THREE.Vector3(0, 0, -1).applyEuler(new THREE.Euler(0, Math.PI * 2 * Math.random(), 0))
  157. } else {//仅在相机前方生成,因为相机往这个方向移动,最前方空缺
  158. direction = new THREE.Vector3(0, 0, -1).applyQuaternion(this.camera.quaternion).applyEuler(new THREE.Euler(0, this.camera.hfov * (Math.random() - 0.5), 0))
  159. }
  160. let h = (Math.random() * 2 - 1) * setting.cards.highest * 0.8 // *0.8是因为靠近后就会飞出视线
  161. card.position.copy(this.camera.position).add(direction.add(new THREE.Vector3(0, h, 0)).multiplyScalar(far))
  162. card.scale.set(map.image.width / 500, map.image.height / 500, 1)
  163. this.cardGroup.add(card)
  164. card.transition = transitions.start(lerp.property(card.material, 'opacity', 1, (e) => {
  165. //console.log(e, card.uuid)
  166. }), setting.cards.fadeInDur);
  167. })
  168. }
  169. Viewer.prototype.removeCards = function () {//移除超过bound的卡
  170. let needRemove = this.cardGroup.children.filter(card => {
  171. if (card.disToCam > setting.cards.far * 1.5) {
  172. card.material.dispose()
  173. transitions.cancel(card.transition)
  174. //console.log('remove一张卡')
  175. return true
  176. }
  177. })
  178. needRemove.forEach(card => card.parent.remove(card))
  179. //needRemove.length>0 && console.log('当前存在卡数', this.cardGroup.children.length)
  180. }
  181. Viewer.prototype.update = function (deltaTime) {//绘制的时候同时更新
  182. this.setSize()
  183. this.control.update(deltaTime)
  184. transitions.update(deltaTime)
  185. if (this.autoMove) {
  186. let direction = new THREE.Vector3(0, 0, -1).applyQuaternion(this.camera.quaternion)
  187. let moveSpeed = 0.8
  188. this.camera.position.add(direction.multiplyScalar(deltaTime * moveSpeed))
  189. }
  190. this.cardGroup.children.forEach(card => {
  191. card.quaternion.copy(this.camera.quaternion)
  192. let dis = card.position.clone().setY(0).distanceTo(this.camera.position.clone().setY(0))
  193. if (!card.transition.running) {
  194. card.material.opacity = math.linearClamp(dis, [setting.cards.near, setting.cards.beginFadeNear], [0, 1])
  195. }
  196. card.disToCam = dis
  197. })
  198. this.removeCards()
  199. var needsUpdate = 1;
  200. if (needsUpdate) {
  201. this.renderer.autoClear = true
  202. this.renderer.render(this.scene, this.camera)
  203. }
  204. }
  205. Viewer.prototype.bindEvents = function () {
  206. this.renderer.domElement.addEventListener('pointermove', this.onPointerMove.bind(this), false);
  207. this.renderer.domElement.addEventListener('pointerdown', this.onPointerDown.bind(this), false);
  208. this.renderer.domElement.addEventListener('pointerup', this.onPointerUp.bind(this), false);
  209. }
  210. Viewer.prototype.setRenderer = function () {
  211. try {
  212. this.renderer = new THREE.WebGLRenderer({ canvas: $(this.dom).find("canvas")[0], antialias: true }),
  213. this.renderer.setPixelRatio(window.devicePixelRatio ? window.devicePixelRatio : 1),
  214. this.renderer.autoClear = false
  215. this.renderer.setClearColor(0xffffff, 1)
  216. console.log("ContextCreated")
  217. //this.emit(Events.ContextCreated)
  218. } catch (e) {
  219. console.error("Unable to create a WebGL rendering context")
  220. }
  221. }
  222. Viewer.prototype.hasChanged = function () {//判断画面是否改变了,改变后需要更新一些东西
  223. var copy = function () {
  224. this.previousState = {
  225. projectionMatrix: this.camera.projectionMatrix.clone(),//worldMatrix在control时归零了所以不用了吧,用position和qua也一样
  226. position: this.camera.position.clone(),
  227. quaternion: this.camera.quaternion.clone(),
  228. //mouse: this.mouse.clone(),
  229. fov: this.camera.fov
  230. };
  231. }.bind(this)
  232. if (!this.previousState) {
  233. copy()
  234. return { cameraChanged: !0, changed: !0 };
  235. }
  236. var cameraChanged =
  237. !this.camera.projectionMatrix.equals(this.previousState.projectionMatrix) ||
  238. !this.camera.position.equals(this.previousState.position) ||
  239. !this.camera.quaternion.equals(this.previousState.quaternion)
  240. var changed = cameraChanged //|| !this.mouse.equals(this.previousState.mouse)
  241. copy()
  242. return { cameraChanged, changed };
  243. }
  244. Viewer.prototype.setSize = function () {
  245. var w, h, pixelRatio;
  246. return function () {
  247. if (w != this.dom.clientWidth || h != this.dom.clientHeight || pixelRatio != window.devicePixelRatio) {
  248. w = this.dom.clientWidth;
  249. h = this.dom.clientHeight;
  250. pixelRatio = window.devicePixelRatio;
  251. this.camera.aspect = w / h;
  252. this.camera.updateProjectionMatrix();
  253. this.renderer.setSize(w, h, false, pixelRatio);
  254. this.camera.hfov = cameraLight.getHFOVForCamera(this.camera, true)
  255. this.cardGroup.children.forEach(card =>
  256. card.material.uniforms.resolution.value.set(w, h)
  257. )
  258. }
  259. }
  260. }()
  261. Viewer.prototype.animate = function () {
  262. var deltaTime = Math.min(1, this.updateClock.getDelta());
  263. this.update(deltaTime)
  264. //bus.emit('player/position/change', {x:this.position.x, y:this.position.z, lon: this.cameraControls.controls.panorama.lon})
  265. window.requestAnimationFrame(this.animate.bind(this));
  266. },
  267. Viewer.prototype.onPointerMove = function (event, force) {
  268. if (event.isPrimary === false) return;
  269. mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  270. mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
  271. if (!this.pointerDownPos || force) this.checkIntersection();
  272. }
  273. Viewer.prototype.onPointerDown = function (event) {
  274. if (event.isPrimary === false) return;
  275. mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  276. mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
  277. this.pointerDownPos = mouse.clone()
  278. this.pointerDownTime = Date.now()
  279. }
  280. Viewer.prototype.onPointerUp = function (event) {
  281. if (event.isPrimary === false) return;
  282. mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  283. mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
  284. let now = Date.now()
  285. if (mouse.distanceTo(this.pointerDownPos) < 0.006 && now - this.pointerDownTime < 1000) {//click
  286. //doubleClick
  287. /* var time = new Date().getTime();
  288. if(time - this.clickTime < 300){
  289. if(this.intersects.length){
  290. console.log('doubleClick');
  291. transitions.cancelById(0)
  292. transitions.start(lerp.vector(this.control.target, this.intersects[0].point), 600, null, 0 , easing.easeInOutQuad, null, Transitions.doubleClick);
  293. }
  294. } */
  295. if(isMobile){
  296. this.onPointerMove(event,true)
  297. }
  298. if (this.hoveredObject) {
  299. this.dispatchEvent({ type: 'clickObject', imgName: this.hoveredObject.material.uniforms.map.value.image.src.split('/').pop() })
  300. }
  301. }
  302. this.pointerDownPos = null
  303. }
  304. Viewer.prototype.checkIntersection = function () {
  305. raycaster.setFromCamera(mouse, this.camera);
  306. raycaster.near = 2
  307. const intersects = raycaster.intersectObject(this.cardGroup, true);
  308. var recover = () => {
  309. if (this.hoveredObject) {
  310. }
  311. }
  312. if (intersects.length > 0) {
  313. const hoveredObject = intersects[0].object;
  314. if (this.hoveredObject != hoveredObject) {
  315. recover()
  316. this.dispatchEvent({ type: "hoverObject", imgName: hoveredObject.material.uniforms.map.value.image.src.split('/').pop() })
  317. this.hoveredObject = hoveredObject;
  318. this.dom.style.cursor = 'pointer'
  319. }
  320. } else {
  321. recover()
  322. this.dispatchEvent({ type: "mouseoutObject" })
  323. this.dom.style.cursor = ''
  324. this.hoveredObject = null
  325. }
  326. this.intersects = intersects;
  327. }
  328. Viewer.prototype.setAutoMove = function (state) {//设置相机飞行状态
  329. this.autoMove = !!state
  330. }
  331. Object.assign(Viewer.prototype, THREE.EventDispatcher.prototype);