Annotation.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. import * as THREE from "../libs/three.js/build/three.module.js";
  2. import {Action} from "./Actions.js";
  3. import {Utils} from "./utils.js";
  4. export class Annotation extends THREE.EventDispatcher {
  5. constructor (args = {}) {
  6. super();
  7. this.scene = null;
  8. this._title = args.title || 'No Title';
  9. this._description = args.description || '';
  10. this.offset = new THREE.Vector3();
  11. this.uuid = THREE.Math.generateUUID();
  12. if (!args.position) {
  13. this.position = null;
  14. } else if (args.position.x != null) {
  15. this.position = args.position;
  16. } else {
  17. this.position = new THREE.Vector3(...args.position);
  18. }
  19. this.cameraPosition = (args.cameraPosition instanceof Array)
  20. ? new THREE.Vector3().fromArray(args.cameraPosition) : args.cameraPosition;
  21. this.cameraTarget = (args.cameraTarget instanceof Array)
  22. ? new THREE.Vector3().fromArray(args.cameraTarget) : args.cameraTarget;
  23. if(!this.cameraTarget && this.position){//add
  24. this.cameraTarget = this.position.clone()
  25. }
  26. this.radius = args.radius;
  27. this.view = args.view || null;
  28. this.keepOpen = false;
  29. this.descriptionVisible = false;
  30. this.showDescription = true;
  31. this.actions = args.actions || [];
  32. this.isHighlighted = false;
  33. this._visible = true;
  34. this.__visible = true;
  35. this._display = true;
  36. this._expand = false;
  37. this.collapseThreshold = [args.collapseThreshold, 100].find(e => e !== undefined);
  38. this.children = [];
  39. this.parent = null;
  40. this.boundingBox = new THREE.Box3();
  41. let iconClose = exports.resourcePath + '/icons/close.svg';
  42. this.domElement = $(`
  43. <div class="annotation" oncontextmenu="return false;">
  44. <div class="annotation-titlebar">
  45. <span class="annotation-label"></span>
  46. </div>
  47. <div class="annotation-description">
  48. <span class="annotation-description-close">
  49. <img src="${iconClose}" width="16px">
  50. </span>
  51. <span class="annotation-description-content">${this._description}</span>
  52. </div>
  53. </div>
  54. `);
  55. this.elTitlebar = this.domElement.find('.annotation-titlebar');
  56. this.elTitle = this.elTitlebar.find('.annotation-label');
  57. this.elTitle.append(this._title);
  58. this.elDescription = this.domElement.find('.annotation-description');
  59. this.elDescriptionClose = this.elDescription.find('.annotation-description-close');
  60. // this.elDescriptionContent = this.elDescription.find(".annotation-description-content");
  61. this.clickTitle = () => {
  62. //if(this.hasView()){
  63. this.moveHere(this.scene.getActiveCamera());
  64. //}
  65. this.dispatchEvent({type: 'click', target: this});
  66. viewer.renderer.domElement.focus()//add 使得方向键可用
  67. };
  68. this.elTitle.click(this.clickTitle);
  69. this.actions = this.actions.map(a => {
  70. if (a instanceof Action) {
  71. return a;
  72. } else {
  73. return new Action(a);
  74. }
  75. });
  76. for (let action of this.actions) {
  77. action.pairWith(this);
  78. }
  79. let actions = this.actions.filter(
  80. a => a.showIn === undefined || a.showIn.includes('scene'));
  81. for (let action of actions) {
  82. let elButton = $(`<img src="${action.icon}" class="annotation-action-icon">`);
  83. this.elTitlebar.append(elButton);
  84. elButton.click(() => action.onclick({annotation: this}));
  85. }
  86. this.elDescriptionClose.hover(
  87. e => this.elDescriptionClose.css('opacity', '1'),
  88. e => this.elDescriptionClose.css('opacity', '0.5')
  89. );
  90. this.elDescriptionClose.click(e => this.setHighlighted(false));
  91. // this.elDescriptionContent.html(this._description);
  92. this.domElement.mouseenter(e => this.setHighlighted(true));
  93. this.domElement.mouseleave(e => this.setHighlighted(false));
  94. this.domElement.on('touchstart', e => {
  95. this.setHighlighted(!this.isHighlighted);
  96. });
  97. this.display = false;
  98. //this.display = true;
  99. }
  100. installHandles(viewer){
  101. if(this.handles !== undefined){
  102. return;
  103. }
  104. let domElement = $(`
  105. <div style="position: absolute; left: 300; top: 200; pointer-events: none">
  106. <svg width="300" height="600">
  107. <line x1="0" y1="0" x2="1200" y2="200" style="stroke: black; stroke-width:2" />
  108. <circle cx="50" cy="50" r="4" stroke="black" stroke-width="2" fill="gray" />
  109. <circle cx="150" cy="50" r="4" stroke="black" stroke-width="2" fill="gray" />
  110. </svg>
  111. </div>
  112. `);
  113. let svg = domElement.find("svg")[0];
  114. let elLine = domElement.find("line")[0];
  115. let elStart = domElement.find("circle")[0];
  116. let elEnd = domElement.find("circle")[1];
  117. let setCoordinates = (start, end) => {
  118. elStart.setAttribute("cx", `${start.x}`);
  119. elStart.setAttribute("cy", `${start.y}`);
  120. elEnd.setAttribute("cx", `${end.x}`);
  121. elEnd.setAttribute("cy", `${end.y}`);
  122. elLine.setAttribute("x1", start.x);
  123. elLine.setAttribute("y1", start.y);
  124. elLine.setAttribute("x2", end.x);
  125. elLine.setAttribute("y2", end.y);
  126. let box = svg.getBBox();
  127. svg.setAttribute("width", `${box.width}`);
  128. svg.setAttribute("height", `${box.height}`);
  129. svg.setAttribute("viewBox", `${box.x} ${box.y} ${box.width} ${box.height}`);
  130. let ya = start.y - end.y;
  131. let xa = start.x - end.x;
  132. if(ya > 0){
  133. start.y = start.y - ya;
  134. }
  135. if(xa > 0){
  136. start.x = start.x - xa;
  137. }
  138. domElement.css("left", `${start.x}px`);
  139. domElement.css("top", `${start.y}px`);
  140. };
  141. $(viewer.renderArea).append(domElement);
  142. let annotationStartPos = this.position.clone();
  143. let annotationStartOffset = this.offset.clone();
  144. $(this.domElement).draggable({
  145. start: (event, ui) => {
  146. annotationStartPos = this.position.clone();
  147. annotationStartOffset = this.offset.clone();
  148. $(this.domElement).find(".annotation-titlebar").css("pointer-events", "none");
  149. console.log($(this.domElement).find(".annotation-titlebar"));
  150. },
  151. stop: () => {
  152. $(this.domElement).find(".annotation-titlebar").css("pointer-events", "");
  153. },
  154. drag: (event, ui ) => {
  155. let renderAreaWidth = viewer.renderer.getSize(new THREE.Vector2()).width;
  156. //let renderAreaHeight = viewer.renderer.getSize().height;
  157. let diff = {
  158. x: ui.originalPosition.left - ui.position.left,
  159. y: ui.originalPosition.top - ui.position.top
  160. };
  161. let nDiff = {
  162. x: -(diff.x / renderAreaWidth) * 2,
  163. y: (diff.y / renderAreaWidth) * 2
  164. };
  165. let camera = viewer.scene.getActiveCamera();
  166. let oldScreenPos = new THREE.Vector3()
  167. .addVectors(annotationStartPos, annotationStartOffset)
  168. .project(camera);
  169. let newScreenPos = oldScreenPos.clone();
  170. newScreenPos.x += nDiff.x;
  171. newScreenPos.y += nDiff.y;
  172. let newPos = newScreenPos.clone();
  173. newPos.unproject(camera);
  174. let newOffset = new THREE.Vector3().subVectors(newPos, this.position);
  175. this.offset.copy(newOffset);
  176. }
  177. });
  178. let updateCallback = () => {
  179. let position = this.position;
  180. let scene = viewer.scene;
  181. const renderAreaSize = viewer.renderer.getSize(new THREE.Vector2());
  182. let renderAreaWidth = renderAreaSize.width;
  183. let renderAreaHeight = renderAreaSize.height;
  184. let start = this.position.clone();
  185. let end = new THREE.Vector3().addVectors(this.position, this.offset);
  186. let toScreen = (position) => {
  187. let camera = scene.getActiveCamera();
  188. let screenPos = new THREE.Vector3();
  189. let worldView = new THREE.Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  190. let ndc = new THREE.Vector4(position.x, position.y, position.z, 1.0).applyMatrix4(worldView);
  191. // limit w to small positive value, in case position is behind the camera
  192. ndc.w = Math.max(ndc.w, 0.1);
  193. ndc.divideScalar(ndc.w);
  194. screenPos.copy(ndc);
  195. screenPos.x = renderAreaWidth * (screenPos.x + 1) / 2;
  196. screenPos.y = renderAreaHeight * (1 - (screenPos.y + 1) / 2);
  197. return screenPos;
  198. };
  199. start = toScreen(start);
  200. end = toScreen(end);
  201. setCoordinates(start, end);
  202. };
  203. viewer.addEventListener("update", updateCallback);
  204. this.handles = {
  205. domElement: domElement,
  206. setCoordinates: setCoordinates,
  207. updateCallback: updateCallback
  208. };
  209. }
  210. removeHandles(viewer){
  211. if(this.handles === undefined){
  212. return;
  213. }
  214. //$(viewer.renderArea).remove(this.handles.domElement);
  215. this.handles.domElement.remove();
  216. viewer.removeEventListener("update", this.handles.updateCallback);
  217. delete this.handles;
  218. }
  219. get visible () {
  220. return this._visible;
  221. }
  222. set visible (value) {
  223. if (this._visible === value) {
  224. return;
  225. }
  226. this._visible = value;
  227. //this.traverse(node => {
  228. // node.display = value;
  229. //});
  230. this.dispatchEvent({
  231. type: 'visibility_changed',
  232. annotation: this
  233. });
  234. }
  235. get display () {
  236. return this._display;
  237. }
  238. set display (display) {
  239. if (this._display === display) {
  240. return;
  241. }
  242. this._display = display;
  243. if (display) {
  244. // this.domElement.fadeIn(200);
  245. this.domElement.show();
  246. } else {
  247. // this.domElement.fadeOut(200);
  248. this.domElement.hide();
  249. }
  250. }
  251. get expand () {
  252. return this._expand;
  253. }
  254. set expand (expand) {
  255. if (this._expand === expand) {
  256. return;
  257. }
  258. if (expand) {
  259. this.display = false;
  260. } else {
  261. this.display = true;
  262. this.traverseDescendants(node => {
  263. node.display = false;
  264. });
  265. }
  266. this._expand = expand;
  267. }
  268. get title () {
  269. return this._title;
  270. }
  271. set title (title) {
  272. if (this._title === title) {
  273. return;
  274. }
  275. this._title = title;
  276. this.elTitle.empty();
  277. this.elTitle.append(this._title);
  278. this.dispatchEvent({
  279. type: "annotation_changed",
  280. annotation: this,
  281. });
  282. }
  283. get description () {
  284. return this._description;
  285. }
  286. set description (description) {
  287. if (this._description === description) {
  288. return;
  289. }
  290. this._description = description;
  291. const elDescriptionContent = this.elDescription.find(".annotation-description-content");
  292. elDescriptionContent.empty();
  293. elDescriptionContent.append(this._description);
  294. this.dispatchEvent({
  295. type: "annotation_changed",
  296. annotation: this,
  297. });
  298. }
  299. add (annotation) {
  300. if (!this.children.includes(annotation)) {
  301. this.children.push(annotation);
  302. annotation.parent = this;
  303. let descendants = [];
  304. annotation.traverse(a => { descendants.push(a); });
  305. for (let descendant of descendants) {
  306. let c = this;
  307. while (c !== null) {
  308. c.dispatchEvent({
  309. 'type': 'annotation_added',
  310. 'annotation': descendant
  311. });
  312. c = c.parent;
  313. }
  314. }
  315. }
  316. }
  317. level () {
  318. if (this.parent === null) {
  319. return 0;
  320. } else {
  321. return this.parent.level() + 1;
  322. }
  323. }
  324. hasChild(annotation) {
  325. return this.children.includes(annotation);
  326. }
  327. remove (annotation) {
  328. if (this.hasChild(annotation)) {
  329. annotation.removeAllChildren();
  330. annotation.dispose();
  331. this.children = this.children.filter(e => e !== annotation);
  332. annotation.parent = null;
  333. }
  334. }
  335. removeAllChildren() {
  336. this.children.forEach((child) => {
  337. if (child.children.length > 0) {
  338. child.removeAllChildren();
  339. }
  340. this.remove(child);
  341. });
  342. }
  343. updateBounds () {
  344. let box = new THREE.Box3();
  345. if (this.position) {
  346. box.expandByPoint(this.position);
  347. }
  348. for (let child of this.children) {
  349. child.updateBounds();
  350. box.union(child.boundingBox);
  351. }
  352. this.boundingBox.copy(box);
  353. }
  354. traverse (handler) {
  355. let expand = handler(this);
  356. if (expand === undefined || expand === true) {
  357. for (let child of this.children) {
  358. child.traverse(handler);
  359. }
  360. }
  361. }
  362. traverseDescendants (handler) {
  363. for (let child of this.children) {
  364. child.traverse(handler);
  365. }
  366. }
  367. flatten () {
  368. let annotations = [];
  369. this.traverse(annotation => {
  370. annotations.push(annotation);
  371. });
  372. return annotations;
  373. }
  374. descendants () {
  375. let annotations = [];
  376. this.traverse(annotation => {
  377. if (annotation !== this) {
  378. annotations.push(annotation);
  379. }
  380. });
  381. return annotations;
  382. }
  383. setHighlighted (highlighted) {
  384. if (highlighted) {
  385. this.domElement.css('opacity', '0.8');
  386. this.elTitlebar.css('box-shadow', '0 0 5px #fff');
  387. this.domElement.css('z-index', '1000');
  388. if (this._description) {
  389. this.descriptionVisible = true;
  390. this.elDescription.fadeIn(200);
  391. this.elDescription.css('position', 'relative');
  392. }
  393. } else {
  394. this.domElement.css('opacity', '0.5');
  395. this.elTitlebar.css('box-shadow', '');
  396. this.domElement.css('z-index', '100');
  397. this.descriptionVisible = false;
  398. this.elDescription.css('display', 'none');
  399. }
  400. this.isHighlighted = highlighted;
  401. }
  402. hasView () {
  403. let hasPosTargetView = this.cameraTarget.x != null;
  404. hasPosTargetView = hasPosTargetView && this.cameraPosition.x != null;
  405. let hasRadiusView = this.radius !== undefined;
  406. let hasView = hasPosTargetView || hasRadiusView;
  407. return hasView;
  408. };
  409. moveHere (camera) {
  410. if (!this.hasView()) {
  411. return;
  412. }
  413. let view = this.scene.view;
  414. let animationDuration = 500;
  415. let easing = TWEEN.Easing.Quartic.Out;
  416. let endTarget;
  417. if (this.cameraTarget) {
  418. endTarget = this.cameraTarget;
  419. } else if (this.position) {
  420. endTarget = this.position;
  421. } else {
  422. endTarget = this.boundingBox.getCenter(new THREE.Vector3());
  423. }
  424. if (this.cameraPosition) {
  425. let endPosition = this.cameraPosition;
  426. Utils.moveTo(this.scene, endPosition, endTarget);
  427. } else if (this.radius) {
  428. let direction = view.direction;
  429. let endPosition = endTarget.clone().add(direction.multiplyScalar(-this.radius));
  430. let startRadius = view.radius;
  431. let endRadius = this.radius;
  432. { // animate camera position
  433. let tween = new TWEEN.Tween(view.position).to(endPosition, animationDuration);
  434. tween.easing(easing);
  435. tween.start();
  436. }
  437. { // animate radius
  438. let t = {x: 0};
  439. let tween = new TWEEN.Tween(t)
  440. .to({x: 1}, animationDuration)
  441. .onUpdate(function () {
  442. view.radius = this.x * endRadius + (1 - this.x) * startRadius;
  443. });
  444. tween.easing(easing);
  445. tween.start();
  446. }
  447. }
  448. };
  449. dispose () {
  450. if (this.domElement.parentElement) {
  451. this.domElement.parentElement.removeChild(this.domElement);
  452. }
  453. };
  454. toString () {
  455. return 'Annotation: ' + this._title;
  456. }
  457. };