objViewer.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. let texLoader = new THREE.TextureLoader;
  2. let camera, scene, renderer, stats, gui;
  3. const mouse = new THREE.Vector2();
  4. const raycaster = new THREE.Raycaster(); raycaster.linePrecision = 0;//不检测boxHelper
  5. const Transitions = {
  6. doubleClick: 0,
  7. helperOpa: 1,
  8. }
  9. let labelIndex = 0
  10. var Viewer = function (index, dom) {
  11. THREE.EventDispatcher.call(this)
  12. this.index = index;
  13. this.dom = dom
  14. this.camera = new THREE.PerspectiveCamera();
  15. this.camera.position.set(0, 0, 0.78);
  16. this.control = new THREE.OrbitControls(this.camera, this.dom)
  17. this.control.enableDamping = true;
  18. this.control.dampingFactor = 0.4;
  19. this.control.minDistance = 0.3;
  20. this.control.maxDistance = 2;
  21. this.control.enablePan = false;
  22. this.control.enableZoom = true;
  23. this.setRenderer()
  24. this.scene = new THREE.Scene;
  25. this.pointerDownPos
  26. this.textures = [];
  27. this.labels = []
  28. this.active = false;
  29. this.antialias = true;
  30. this.clickTime = new Date().getTime();
  31. this.updateClock = new THREE.Clock;
  32. this.init()
  33. }
  34. Viewer.prototype = Object.create(THREE.EventDispatcher.prototype)
  35. Viewer.constructor = Viewer
  36. Viewer.prototype.bindEvents = function () {
  37. this.renderer.domElement.addEventListener('pointerdown', this.onPointerDown.bind(this), false);
  38. this.renderer.domElement.addEventListener('pointerup', this.onPointerUp.bind(this), false);
  39. }
  40. Viewer.prototype.setRenderer = function () {
  41. try {
  42. this.renderer = new THREE.WebGLRenderer(
  43. {
  44. canvas: $(this.dom).find("canvas")[0],
  45. antialias: true,
  46. alpha: true
  47. }
  48. ),//许钟文 添加个抗锯齿,否则添加的线条锯齿严重,
  49. this.renderer.setClearAlpha(0);
  50. //this.renderer.autoClear = !0,
  51. this.renderer.setPixelRatio(window.devicePixelRatio ? window.devicePixelRatio : 1)
  52. // this.renderer.autoClear = false
  53. //this.emit(Events.ContextCreated)
  54. } catch (e) {
  55. console.error("Unable to create a WebGL rendering context")
  56. }
  57. }
  58. Viewer.prototype.update = function (deltaTime) {//绘制的时候同时更新
  59. //if(!this.active)return;
  60. this.setSize()
  61. this.control.update(deltaTime)
  62. transitions.update(deltaTime)
  63. var needsUpdate = 1;
  64. if (needsUpdate) {
  65. //this.renderer.autoClear = true
  66. this.renderer.render(this.scene, this.camera)
  67. }
  68. }
  69. Viewer.prototype.hasChanged = function () {//判断画面是否改变了,改变后需要更新一些东西
  70. var copy = function () {
  71. this.previousState = {
  72. projectionMatrix: this.camera.projectionMatrix.clone(),//worldMatrix在control时归零了所以不用了吧,用position和qua也一样
  73. position: this.camera.position.clone(),
  74. quaternion: this.camera.quaternion.clone(),
  75. //mouse: this.mouse.clone(),
  76. fov: this.camera.fov
  77. };
  78. }.bind(this)
  79. if (!this.previousState) {
  80. copy()
  81. return { cameraChanged: !0, changeSlightly: !1 };
  82. }
  83. var cameraChanged =
  84. !this.camera.projectionMatrix.equals(this.previousState.projectionMatrix) ||
  85. !this.camera.position.equals(this.previousState.position) ||
  86. !this.camera.quaternion.equals(this.previousState.quaternion)
  87. //var changed = cameraChanged //|| !this.mouse.equals(this.previousState.mouse)
  88. let changeSlightly
  89. if (cameraChanged) {
  90. changeSlightly = math.closeTo(this.camera.position, this.previousState.position, 1e-2) &&
  91. math.closeTo(this.camera.quaternion, this.previousState.quaternion, 1e-3)
  92. }
  93. copy()
  94. return { cameraChanged, changeSlightly };
  95. }
  96. Viewer.prototype.setSize = function () {
  97. var w, h, pixelRatio;
  98. return function () {
  99. if (w != this.dom.clientWidth || h != this.dom.clientHeight || pixelRatio != window.devicePixelRatio) {
  100. w = this.dom.clientWidth;
  101. h = this.dom.clientHeight;
  102. pixelRatio = window.devicePixelRatio;
  103. this.camera.aspect = w / h;
  104. this.camera.updateProjectionMatrix();
  105. this.renderer.setSize(w, h, false, pixelRatio);
  106. }
  107. }
  108. }()
  109. Viewer.prototype.init = function () {
  110. this.meshGroup = new THREE.Object3D();
  111. this.scene.add(this.meshGroup);
  112. this.meshGroup.name = "viewerMeshGroup";
  113. var buildScene = () => {
  114. this.animate()
  115. }
  116. this.loadOBJ(() => {
  117. this.bindEvents()
  118. //this.loadLabels()
  119. })
  120. buildScene()
  121. }
  122. Viewer.prototype.animate = function () {
  123. var deltaTime = Math.min(1, this.updateClock.getDelta());
  124. this.update(deltaTime)
  125. //bus.emit('player/position/change', {x:this.position.x, y:this.position.z, lon: this.cameraControls.controls.panorama.lon})
  126. let changed = this.hasChanged()
  127. if (changed.cameraChanged) {
  128. this.dispatchEvent({ type: 'view.changed', changeSlightly: changed.changeSlightly })
  129. let label_ = this.labels.filter(e => e.elem[0].style.display == 'block')
  130. label_.sort((a, b) => b.pos2d.z - a.pos2d.z)
  131. label_.forEach((e, index) => e.elem.css('z-index', index + 1000));
  132. }
  133. window.requestAnimationFrame(this.animate.bind(this));
  134. },
  135. Viewer.prototype.loadOBJ = function (done) {
  136. var startTime = new Date().getTime();
  137. window.objs = [];
  138. var group = new THREE.Object3D;
  139. this.meshGroup.add(group);
  140. function onProgress(xhr) {
  141. if (xhr.lengthComputable) {
  142. var percentComplete = xhr.loaded / xhr.total * 100;
  143. console.log('model ' + Math.round(percentComplete, 2) + '% downloaded');
  144. }
  145. }
  146. function onError() { }
  147. var MTLLoader = new THREE.MTLLoader();
  148. var OBJLoader = new THREE.OBJLoader()
  149. var loadModel = () => {
  150. var info = {//凳子
  151. path: 'model/',
  152. mtl: 'wl48-he.mtl',
  153. obj: 'wl48-he.obj',
  154. position: [0, 0],
  155. rotation: 0,
  156. height: 1
  157. };
  158. if (!info) {
  159. console.log("加载持续时间:" + (new Date().getTime() - startTime))
  160. return;
  161. }
  162. MTLLoader.setPath(info.path).load(info.mtl, (materials) => {
  163. materials.preload();
  164. OBJLoader.setMaterials(materials)
  165. .setPath(info.path)
  166. .load(info.obj, (object) => {
  167. group.add(object);
  168. object.traverse(function (child) {
  169. if (child.isMesh) {
  170. console.log(child);
  171. if (child.name == "WL48_ping") {
  172. let textrueLoader = new THREE.TextureLoader();
  173. // var emissiveTexture = textrueLoader.load("model/shadow.jpg");
  174. // emissiveTexture.encoding = THREE.LinearEncoding;
  175. // child.material.emissiveMap = emissiveTexture;
  176. child.material.emissiveIntensity = 0;
  177. let step = 1
  178. setInterval(() => {
  179. if (window.activetab == 'pic') {
  180. if (child.material.emissiveIntensity > 0.3) {
  181. step = -1
  182. }
  183. if (child.material.emissiveIntensity < 0) {
  184. step = 1
  185. }
  186. child.material.emissiveIntensity += 0.01 * step;
  187. }
  188. }, 50);
  189. child.material.emissive = new THREE.Color(0xffffff);
  190. child.material.dispose();
  191. }
  192. /* if(child.geometry){
  193. child.geometry.computeBoundingBox();
  194. bound.union(child.geometry.boundingBox)
  195. } */
  196. }
  197. });
  198. this.model = object
  199. let s = 0.010
  200. object.scale.set(s, s, s)
  201. done && done()
  202. console.log("加载持续时间:" + (new Date().getTime() - startTime))
  203. setTimeout(() => {
  204. this.dispatchEvent({ type: 'hadLoaded' })
  205. });
  206. }, onProgress, onError);
  207. });
  208. }
  209. loadModel()
  210. var light1 = new THREE.AmbientLight(16777215);
  211. light1.intensity = 2.8;
  212. this.scene.add(light1)
  213. var light2 = new THREE.SpotLight(0xffffff, 1);
  214. light2.position.set(0, 0, 3)
  215. light2.intensity = 0.2;
  216. var light3 = new THREE.SpotLight(0xffffff, 1);
  217. light3.position.set(0, 0, -3)
  218. light3.intensity = 0.4;
  219. // let spotLightHelper = new THREE.SpotLightHelper(light2);
  220. // let spotLightHelper3 = new THREE.SpotLightHelper(light3);
  221. this.scene.add(light2)
  222. this.scene.add(light3)
  223. // this.scene.add( spotLightHelper );
  224. // this.scene.add( spotLightHelper3 );
  225. }
  226. Viewer.prototype.onPointerMove = function (event) {
  227. if (event.isPrimary === false) return;
  228. mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  229. mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
  230. if (!this.pointerDownPos) this.checkIntersection();
  231. }
  232. Viewer.prototype.onPointerDown = function (event) {
  233. if (event.isPrimary === false) return;
  234. mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  235. mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
  236. this.pointerDownPos = mouse.clone()
  237. }
  238. Viewer.prototype.onPointerUp = function (event) {
  239. if (event.isPrimary === false) return;
  240. this.dispatchEvent({ type: 'onPointerUp' })
  241. mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  242. mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
  243. if (mouse.distanceTo(this.pointerDownPos) < 0.006) {//click
  244. this.checkIntersection()
  245. // if (this.intersects.length) {
  246. // console.log(this.intersects[0].point);
  247. // this.addLabel({ position: this.intersects[0].point })
  248. // }
  249. // var time = new Date().getTime();
  250. // if (time - this.clickTime < 300) {
  251. // if (this.intersects.length) {
  252. // console.log('doubleClick');
  253. // transitions.cancelById(0)
  254. // transitions.start(lerp.vector(this.control.target, this.intersects[0].point), 600, null, 0/* Delay */, easing.easeInOutQuad, null, Transitions.doubleClick);
  255. // }
  256. // }
  257. // this.clickTime = time;
  258. }
  259. this.pointerDownPos = null
  260. }
  261. Viewer.prototype.checkIntersection = function () {
  262. raycaster.setFromCamera(mouse, this.camera);
  263. const intersects = raycaster.intersectObject(this.model/* this.meshGroup */, true);
  264. this.intersects = intersects;
  265. }
  266. /* Viewer.prototype.adjustModelPos = function(){ //固定地板高度的情况下,调整模型的position.y
  267. this.meshGroup.updateMatrixWorld();
  268. this.model.updateMatrixWorld();
  269. var bound = this.model.bound.clone().applyMatrix4(this.model.matrixWorld)
  270. var center = bound.getCenter()
  271. //为了让最低点在地面上:
  272. this.meshGroup.position.y += floorY - bound.min.y
  273. //居中:
  274. this.meshGroup.position.x += 0 - center.x
  275. this.meshGroup.position.z += 0 - center.z
  276. } */
  277. Viewer.prototype.removeAllLabels = function (data) {
  278. this.labels.forEach(label => {
  279. label.dispose()
  280. label = null
  281. })
  282. this.labels = []
  283. }
  284. Viewer.prototype.loadLabelsFromData = function (data) {
  285. data.forEach(info => {
  286. info.position = new THREE.Vector3().fromArray(info.posInModel).applyMatrix4(this.model.matrixWorld)
  287. this.addLabel(info)
  288. })
  289. }
  290. Viewer.prototype.addLabel = function (o) {
  291. labelIndex++
  292. o.title = o.title || ('default' + labelIndex)
  293. o.shelterByModel = true
  294. let label = new Label2D(o)
  295. this.labels.push(label)
  296. }
  297. Viewer.prototype.removeLabel = function (label) {
  298. label.dispose()
  299. let index = this.labels.indexOf(label)
  300. index > -1 && this.labels.splice(index)
  301. label.li && label.li.remove()
  302. }
  303. Viewer.prototype.setAddLabelState = function (state) {
  304. this.addingLabel = !!state
  305. $('#addLabel').text(state ? '停止加标签' : '添加标签')
  306. }
  307. Viewer.prototype.exportLabelData = function () {
  308. let data = this.labels.map(label => {
  309. let inv = new THREE.Matrix4().getInverse(this.model.matrixWorld)
  310. let posInModel = label.position.clone().applyMatrix4(inv)
  311. let info = {
  312. title: label.title,
  313. posInModel: convertTool.toPrecision(posInModel.toArray(), 4),
  314. }
  315. return info
  316. })
  317. $('textarea').css('display', 'block').text(JSON.stringify(data))
  318. console.log(data)
  319. return data
  320. }
  321. Viewer.prototype.getCLabel = function () { //获取最接近中心的label
  322. let disSquairs = this.labels.filter(e => e.elem[0].style.display == 'block').map((label) => {
  323. return {
  324. label,
  325. disSquair: label.pos2d.x * label.pos2d.x + label.pos2d.y * label.pos2d.y
  326. }
  327. })
  328. disSquairs.sort((e1, e2) => { return e1.disSquair - e2.disSquair })
  329. return disSquairs[0] && disSquairs[0].label
  330. }
  331. //============
  332. var startTime = new Date().getTime();
  333. function dataURLtoBlob(dataurl) {//将base64转换blob
  334. var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
  335. bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  336. while (n--) {
  337. u8arr[n] = bstr.charCodeAt(n);
  338. }
  339. return new Blob([u8arr], { type: mime });
  340. }
  341. /*
  342. MeshStandardMaterial(pbr)代替Phong
  343. 优点 : 能量守恒、更容易调节出真实感。 metalnessMap只用到一个通道,颜色信息整合到albedo贴图里,省数据。
  344. 缺点:可能,mtl里的值只能用到一部分, specular用不到。 (会降低对specular的控制)
  345. 另外不知道大部分模型用的是哪种模式,是否使用metalnessMap。
  346. aoMap r
  347. roughnessMap alphaMap g
  348. metalnessMap b
  349. normalMap ?
  350. bumpMap : 黑白?
  351. 主要是光滑度or粗糙度(可贴图) 还有 金属性(可贴图) 还有颜色(可贴图),透明度(in颜色贴图),法线贴图or凹凸贴图
  352. 贴图的属性 rotation offset repeat (当wrapS = THREE.RepeatWrapping,wrapT = THREE.RepeatWrapping)
  353. */