less copy protection, more size visualization
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

2142 lines
65 KiB

  1. let selected = null;
  2. let selectedEntity = null;
  3. let entityIndex = 0;
  4. let clicked = null;
  5. let dragging = false;
  6. let clickTimeout = null;
  7. let dragOffsetX = null;
  8. let dragOffsetY = null;
  9. let shiftHeld = false;
  10. let altHeld = false;
  11. let entityX;
  12. let canvasWidth;
  13. let canvasHeight;
  14. let dragScale = 1;
  15. let dragScaleHandle = null;
  16. let dragEntityScale = 1;
  17. let dragEntityScaleHandle = null;
  18. let scrollDirection = 0;
  19. let scrollHandle = null;
  20. let zoomDirection = 0;
  21. let zoomHandle = null;
  22. let sizeDirection = 0;
  23. let sizeHandle = null;
  24. let worldSizeDirty = false;
  25. math.createUnit("humans", {
  26. definition: "5.75 feet"
  27. });
  28. math.createUnit("story", {
  29. definition: "12 feet",
  30. prefixes: "long"
  31. });
  32. math.createUnit("stories", {
  33. definition: "12 feet",
  34. prefixes: "long"
  35. });
  36. math.createUnit("parsec", {
  37. definition: "3.086e16 meters",
  38. prefixes: "long"
  39. })
  40. math.createUnit("parsecs", {
  41. definition: "3.086e16 meters",
  42. prefixes: "long"
  43. })
  44. math.createUnit("lightyears", {
  45. definition: "9.461e15 meters",
  46. prefixes: "long"
  47. })
  48. math.createUnit("AU", {
  49. definition: "149597870700 meters"
  50. })
  51. math.createUnit("AUs", {
  52. definition: "149597870700 meters"
  53. })
  54. math.createUnit("dalton", {
  55. definition: "1.66e-27 kg",
  56. prefixes: "long"
  57. });
  58. math.createUnit("daltons", {
  59. definition: "1.66e-27 kg",
  60. prefixes: "long"
  61. });
  62. math.createUnit("solarradii", {
  63. definition: "695990 km",
  64. prefixes: "long"
  65. });
  66. math.createUnit("solarmasses", {
  67. definition: "2e30 kg",
  68. prefixes: "long"
  69. });
  70. math.createUnit("galaxy", {
  71. definition: "105700 lightyears",
  72. prefixes: "long"
  73. });
  74. math.createUnit("galaxies", {
  75. definition: "105700 lightyears",
  76. prefixes: "long"
  77. });
  78. math.createUnit("universe", {
  79. definition: "93.016e9 lightyears",
  80. prefixes: "long"
  81. });
  82. math.createUnit("universes", {
  83. definition: "93.016e9 lightyears",
  84. prefixes: "long"
  85. });
  86. const unitChoices = {
  87. length: [
  88. "meters",
  89. "angstroms",
  90. "millimeters",
  91. "centimeters",
  92. "kilometers",
  93. "inches",
  94. "feet",
  95. "humans",
  96. "stories",
  97. "miles",
  98. "solarradii",
  99. "AUs",
  100. "lightyears",
  101. "parsecs",
  102. "galaxies",
  103. "universes"
  104. ],
  105. area: [
  106. "meters^2",
  107. "cm^2",
  108. "kilometers^2",
  109. "acres",
  110. "miles^2"
  111. ],
  112. mass: [
  113. "kilograms",
  114. "milligrams",
  115. "grams",
  116. "tonnes",
  117. "lbs",
  118. "ounces",
  119. "tons"
  120. ]
  121. }
  122. const config = {
  123. height: math.unit(1500, "meters"),
  124. minLineSize: 100,
  125. maxLineSize: 150,
  126. autoFit: false,
  127. autoFitMode: "max"
  128. }
  129. const availableEntities = {
  130. }
  131. const availableEntitiesByName = {
  132. }
  133. const entities = {
  134. }
  135. function constrainRel(coords) {
  136. if (altHeld) {
  137. return coords;
  138. }
  139. return {
  140. x: Math.min(Math.max(coords.x, 0), 1),
  141. y: Math.min(Math.max(coords.y, 0), 1)
  142. }
  143. }
  144. function snapRel(coords) {
  145. return constrainRel({
  146. x: coords.x,
  147. y: altHeld ? coords.y : (Math.abs(coords.y - 1) < 0.05 ? 1 : coords.y)
  148. });
  149. }
  150. function adjustAbs(coords, oldHeight, newHeight) {
  151. const ratio = math.divide(oldHeight, newHeight);
  152. return { x: 0.5 + (coords.x - 0.5) * math.divide(oldHeight, newHeight), y: 1 + (coords.y - 1) * math.divide(oldHeight, newHeight) };
  153. }
  154. function rel2abs(coords) {
  155. return { x: coords.x * canvasWidth + 50, y: coords.y * canvasHeight };
  156. }
  157. function abs2rel(coords) {
  158. return { x: (coords.x - 50) / canvasWidth, y: coords.y / canvasHeight };
  159. }
  160. function updateEntityElement(entity, element) {
  161. const position = rel2abs({ x: element.dataset.x, y: element.dataset.y });
  162. const view = entity.view;
  163. element.style.left = position.x + "px";
  164. element.style.top = position.y + "px";
  165. element.style.setProperty("--xpos", position.x + "px");
  166. element.style.setProperty("--entity-height", "'" + entity.views[view].height.to(config.height.units[0].unit.name).format({precision: 2}) + "'");
  167. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 50);
  168. const extra = entity.views[view].image.extra;
  169. const bottom = entity.views[view].image.bottom;
  170. const bonus = (extra ? extra : 1) * (1 / (1 - (bottom ? bottom : 0)));
  171. element.style.setProperty("--height", pixels * bonus + "px");
  172. element.style.setProperty("--extra", pixels * bonus - pixels + "px");
  173. if (entity.views[view].rename)
  174. element.querySelector(".entity-name").innerText = entity.name == "" ? "" : entity.views[view].name;
  175. else
  176. element.querySelector(".entity-name").innerText = entity.name;
  177. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  178. bottomName.style.left = position.x + entityX + "px";
  179. bottomName.style.bottom = "0vh";
  180. bottomName.innerText = entity.name;
  181. const topName = document.querySelector("#top-name-" + element.dataset.key);
  182. topName.style.left = position.x + entityX + "px";
  183. topName.style.top = "20vh";
  184. topName.innerText = entity.name;
  185. if (entity.views[view].height.toNumber("meters") / 10 > config.height.toNumber("meters")) {
  186. topName.classList.add("top-name-needed");
  187. } else {
  188. topName.classList.remove("top-name-needed");
  189. }
  190. }
  191. function updateSizes(dirtyOnly = false) {
  192. drawScale(dirtyOnly);
  193. let ordered = Object.entries(entities);
  194. ordered.sort((e1, e2) => {
  195. if (e1[1].priority != e2[1].priority) {
  196. return e2[1].priority - e1[1].priority;
  197. } else {
  198. return e1[1].views[e1[1].view].height.value - e2[1].views[e2[1].view].height.value
  199. }
  200. });
  201. let zIndex = ordered.length;
  202. ordered.forEach(entity => {
  203. const element = document.querySelector("#entity-" + entity[0]);
  204. element.style.zIndex = zIndex;
  205. if (!dirtyOnly || entity[1].dirty) {
  206. updateEntityElement(entity[1], element, zIndex);
  207. entity[1].dirty = false;
  208. }
  209. zIndex -= 1;
  210. });
  211. }
  212. function drawScale(ifDirty=false) {
  213. if (ifDirty && !worldSizeDirty)
  214. return;
  215. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  216. let total = heightPer.clone();
  217. total.value = 0;
  218. for (let y = ctx.canvas.clientHeight - 50; y >= 50; y -= pixelsPer) {
  219. drawTick(ctx, 50, y, total);
  220. total = math.add(total, heightPer);
  221. }
  222. }
  223. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, value) {
  224. const oldStroke = ctx.strokeStyle;
  225. const oldFill = ctx.fillStyle;
  226. ctx.beginPath();
  227. ctx.moveTo(x, y);
  228. ctx.lineTo(x + 20, y);
  229. ctx.strokeStyle = "#000000";
  230. ctx.stroke();
  231. ctx.beginPath();
  232. ctx.moveTo(x + 20, y);
  233. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  234. ctx.strokeStyle = "#aaaaaa";
  235. ctx.stroke();
  236. ctx.beginPath();
  237. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  238. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  239. ctx.strokeStyle = "#000000";
  240. ctx.stroke();
  241. const oldFont = ctx.font;
  242. ctx.font = 'normal 24pt coda';
  243. ctx.fillStyle = "#dddddd";
  244. ctx.beginPath();
  245. ctx.fillText(value.format({ precision: 3 }), x + 20, y + 35);
  246. ctx.font = oldFont;
  247. ctx.strokeStyle = oldStroke;
  248. ctx.fillStyle = oldFill;
  249. }
  250. const canvas = document.querySelector("#display");
  251. /** @type {CanvasRenderingContext2D} */
  252. const ctx = canvas.getContext("2d");
  253. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.toNumber();
  254. heightPer = 1;
  255. if (pixelsPer < config.minLineSize) {
  256. const factor = math.ceil(config.minLineSize / pixelsPer);
  257. heightPer *= factor;
  258. pixelsPer *= factor;
  259. }
  260. if (pixelsPer > config.maxLineSize) {
  261. const factor = math.ceil(pixelsPer / config.maxLineSize);
  262. heightPer /= factor;
  263. pixelsPer /= factor;
  264. }
  265. heightPer = math.unit(heightPer, config.height.units[0].unit.name)
  266. ctx.clearRect(0, 0, canvas.width, canvas.height);
  267. ctx.scale(1, 1);
  268. ctx.canvas.width = canvas.clientWidth;
  269. ctx.canvas.height = canvas.clientHeight;
  270. ctx.beginPath();
  271. ctx.moveTo(50, 50);
  272. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  273. ctx.stroke();
  274. ctx.beginPath();
  275. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  276. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  277. ctx.stroke();
  278. drawTicks(ctx, pixelsPer, heightPer);
  279. }
  280. // Entities are generated as needed, and we make a copy
  281. // every time - the resulting objects get mutated, after all.
  282. // But we also want to be able to read some information without
  283. // calling the constructor -- e.g. making a list of authors and
  284. // owners. So, this function is used to generate that information.
  285. // It is invoked like makeEntity so that it can be dropped in easily,
  286. // but returns an object that lets you construct many copies of an entity,
  287. // rather than creating a new entity.
  288. function createEntityMaker(info, views, sizes) {
  289. const maker = {};
  290. maker.name = info.name;
  291. maker.constructor = () => makeEntity(info, views, sizes);
  292. maker.authors = [];
  293. maker.owners = [];
  294. Object.values(views).forEach(view => {
  295. const authors = authorsOf(view.image.source);
  296. if (authors) {
  297. authors.forEach(author => {
  298. if (maker.authors.indexOf(author) == -1) {
  299. maker.authors.push(author);
  300. }
  301. });
  302. }
  303. const owners = ownersOf(view.image.source);
  304. if (owners) {
  305. owners.forEach(owner => {
  306. if (maker.owners.indexOf(owner) == -1) {
  307. maker.owners.push(owner);
  308. }
  309. });
  310. }
  311. });
  312. return maker;
  313. }
  314. // This function serializes and parses its arguments to avoid sharing
  315. // references to a common object. This allows for the objects to be
  316. // safely mutated.
  317. function makeEntity(info, views, sizes) {
  318. const entityTemplate = {
  319. name: info.name,
  320. identifier: info.name,
  321. scale: 1,
  322. info: JSON.parse(JSON.stringify(info)),
  323. views: JSON.parse(JSON.stringify(views), math.reviver),
  324. sizes: sizes === undefined ? [] : JSON.parse(JSON.stringify(sizes), math.reviver),
  325. init: function () {
  326. const entity = this;
  327. Object.entries(this.views).forEach(([viewKey, view]) => {
  328. view.parent = this;
  329. if (this.defaultView === undefined) {
  330. this.defaultView = viewKey;
  331. this.view = viewKey;
  332. }
  333. Object.entries(view.attributes).forEach(([key, val]) => {
  334. Object.defineProperty(
  335. view,
  336. key,
  337. {
  338. get: function () {
  339. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  340. },
  341. set: function (value) {
  342. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  343. this.parent.scale = newScale;
  344. }
  345. }
  346. )
  347. });
  348. });
  349. this.sizes.forEach(size => {
  350. if (size.default === true) {
  351. this.views[this.defaultView].height = size.height;
  352. this.size = size;
  353. }
  354. });
  355. if (this.size === undefined && this.sizes.length > 0) {
  356. this.views[this.defaultView].height = this.sizes[0].height;
  357. this.size = this.sizes[0];
  358. console.warn("No default size set for " + info.name);
  359. } else if (this.sizes.length == 0) {
  360. this.sizes = [
  361. {
  362. name: "Normal",
  363. height: this.views[this.defaultView].height
  364. }
  365. ];
  366. this.size = this.sizes[0];
  367. }
  368. this.desc = {};
  369. Object.entries(this.info).forEach(([key, value]) => {
  370. Object.defineProperty(
  371. this.desc,
  372. key,
  373. {
  374. get: function () {
  375. let text = value.text;
  376. if (entity.views[entity.view].info) {
  377. if (entity.views[entity.view].info[key]) {
  378. text = combineInfo(text, entity.views[entity.view].info[key]);
  379. }
  380. }
  381. if (entity.size.info) {
  382. if (entity.size.info[key]) {
  383. text = combineInfo(text, entity.size.info[key]);
  384. }
  385. }
  386. return { title: value.title, text: text };
  387. }
  388. }
  389. )
  390. });
  391. delete this.init;
  392. return this;
  393. }
  394. }.init();
  395. return entityTemplate;
  396. }
  397. function combineInfo(existing, next) {
  398. switch (next.mode) {
  399. case "replace":
  400. return next.text;
  401. case "prepend":
  402. return next.text + existing;
  403. case "append":
  404. return existing + next.text;
  405. }
  406. return existing;
  407. }
  408. function clickDown(target, x, y) {
  409. clicked = target;
  410. const rect = target.getBoundingClientRect();
  411. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  412. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  413. dragOffsetX = x - rect.left + entX;
  414. dragOffsetY = y - rect.top + entY;
  415. clickTimeout = setTimeout(() => { dragging = true }, 200)
  416. target.classList.add("no-transition");
  417. }
  418. // could we make this actually detect the menu area?
  419. function hoveringInDeleteArea(e) {
  420. return e.clientY < document.body.clientHeight / 10;
  421. }
  422. function clickUp(e) {
  423. clearTimeout(clickTimeout);
  424. if (clicked) {
  425. if (dragging) {
  426. dragging = false;
  427. if (hoveringInDeleteArea(e)) {
  428. removeEntity(clicked);
  429. document.querySelector("#menubar").classList.remove("hover-delete");
  430. }
  431. } else {
  432. select(clicked);
  433. }
  434. clicked.classList.remove("no-transition");
  435. clicked = null;
  436. }
  437. }
  438. function deselect() {
  439. if (selected) {
  440. selected.classList.remove("selected");
  441. }
  442. document.getElementById("options-selected-entity-none").selected = "selected";
  443. clearAttribution();
  444. selected = null;
  445. clearViewList();
  446. clearEntityOptions();
  447. clearViewOptions();
  448. document.querySelector("#delete-entity").disabled = true;
  449. document.querySelector("#grow").disabled = true;
  450. document.querySelector("#shrink").disabled = true;
  451. document.querySelector("#fit").disabled = true;
  452. }
  453. function select(target) {
  454. deselect();
  455. selected = target;
  456. selectedEntity = entities[target.dataset.key];
  457. document.getElementById("options-selected-entity-" + target.dataset.key).selected = "selected";
  458. selected.classList.add("selected");
  459. displayAttribution(selectedEntity.views[selectedEntity.view].image.source);
  460. configViewList(selectedEntity, selectedEntity.view);
  461. configEntityOptions(selectedEntity, selectedEntity.view);
  462. configViewOptions(selectedEntity, selectedEntity.view);
  463. document.querySelector("#delete-entity").disabled = false;
  464. document.querySelector("#grow").disabled = false;
  465. document.querySelector("#shrink").disabled = false;
  466. document.querySelector("#fit").disabled = false;
  467. }
  468. function configViewList(entity, selectedView) {
  469. const list = document.querySelector("#entity-view");
  470. list.innerHTML = "";
  471. list.style.display = "block";
  472. Object.keys(entity.views).forEach(view => {
  473. const option = document.createElement("option");
  474. option.innerText = entity.views[view].name;
  475. option.value = view;
  476. if (view === selectedView) {
  477. option.selected = true;
  478. }
  479. list.appendChild(option);
  480. });
  481. }
  482. function clearViewList() {
  483. const list = document.querySelector("#entity-view");
  484. list.innerHTML = "";
  485. list.style.display = "none";
  486. }
  487. function updateWorldOptions(entity, view) {
  488. const heightInput = document.querySelector("#options-height-value");
  489. const heightSelect = document.querySelector("#options-height-unit");
  490. const converted = config.height.toNumber(heightSelect.value);
  491. setNumericInput(heightInput, converted);
  492. }
  493. function configEntityOptions(entity, view) {
  494. const holder = document.querySelector("#options-entity");
  495. document.querySelector("#entity-category-header").style.display = "block";
  496. document.querySelector("#entity-category").style.display = "block";
  497. holder.innerHTML = "";
  498. const scaleLabel = document.createElement("div");
  499. scaleLabel.classList.add("options-label");
  500. scaleLabel.innerText = "Scale";
  501. const scaleRow = document.createElement("div");
  502. scaleRow.classList.add("options-row");
  503. const scaleInput = document.createElement("input");
  504. scaleInput.classList.add("options-field-numeric");
  505. scaleInput.id = "options-entity-scale";
  506. scaleInput.addEventListener("change", e => {
  507. entity.scale = e.target.value == 0 ? 1 : e.target.value;
  508. entity.dirty = true;
  509. if (config.autoFit) {
  510. fitWorld();
  511. } else {
  512. updateSizes(true);
  513. }
  514. updateEntityOptions(entity, view);
  515. updateViewOptions(entity, view);
  516. });
  517. scaleInput.addEventListener("keydown", e => {
  518. e.stopPropagation();
  519. })
  520. scaleInput.setAttribute("min", 1);
  521. scaleInput.setAttribute("type", "number");
  522. setNumericInput(scaleInput, entity.scale);
  523. scaleRow.appendChild(scaleInput);
  524. holder.appendChild(scaleLabel);
  525. holder.appendChild(scaleRow);
  526. const nameLabel = document.createElement("div");
  527. nameLabel.classList.add("options-label");
  528. nameLabel.innerText = "Name";
  529. const nameRow = document.createElement("div");
  530. nameRow.classList.add("options-row");
  531. const nameInput = document.createElement("input");
  532. nameInput.classList.add("options-field-text");
  533. nameInput.value = entity.name;
  534. nameInput.addEventListener("input", e => {
  535. entity.name = e.target.value;
  536. entity.dirty = true;
  537. updateSizes(true);
  538. })
  539. nameInput.addEventListener("keydown", e => {
  540. e.stopPropagation();
  541. })
  542. nameRow.appendChild(nameInput);
  543. holder.appendChild(nameLabel);
  544. holder.appendChild(nameRow);
  545. const defaultHolder = document.querySelector("#options-entity-defaults");
  546. defaultHolder.innerHTML = "";
  547. entity.sizes.forEach(defaultInfo => {
  548. const button = document.createElement("button");
  549. button.classList.add("options-button");
  550. button.innerText = defaultInfo.name;
  551. button.addEventListener("click", e => {
  552. entity.views[entity.defaultView].height = defaultInfo.height;
  553. entity.dirty = true;
  554. updateEntityOptions(entity, entity.view);
  555. updateViewOptions(entity, entity.view);
  556. if (!checkFitWorld()){
  557. updateSizes(true);
  558. }
  559. });
  560. defaultHolder.appendChild(button);
  561. });
  562. document.querySelector("#options-order-display").innerText = entity.priority;
  563. document.querySelector("#options-ordering").style.display = "flex";
  564. }
  565. function updateEntityOptions(entity, view) {
  566. const scaleInput = document.querySelector("#options-entity-scale");
  567. setNumericInput(scaleInput, entity.scale);
  568. document.querySelector("#options-order-display").innerText = entity.priority;
  569. }
  570. function clearEntityOptions() {
  571. document.querySelector("#entity-category-header").style.display = "none";
  572. document.querySelector("#entity-category").style.display = "none";
  573. /*
  574. const holder = document.querySelector("#options-entity");
  575. holder.innerHTML = "";
  576. document.querySelector("#options-entity-defaults").innerHTML = "";
  577. document.querySelector("#options-ordering").style.display = "none";
  578. document.querySelector("#options-ordering").style.display = "none";*/
  579. }
  580. function configViewOptions(entity, view) {
  581. const holder = document.querySelector("#options-view");
  582. document.querySelector("#view-category-header").style.display = "block";
  583. document.querySelector("#view-category").style.display = "block";
  584. holder.innerHTML = "";
  585. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  586. const label = document.createElement("div");
  587. label.classList.add("options-label");
  588. label.innerText = val.name;
  589. holder.appendChild(label);
  590. const row = document.createElement("div");
  591. row.classList.add("options-row");
  592. holder.appendChild(row);
  593. const input = document.createElement("input");
  594. input.classList.add("options-field-numeric");
  595. input.id = "options-view-" + key + "-input";
  596. input.setAttribute("type", "number");
  597. input.setAttribute("min", 1);
  598. setNumericInput(input, entity.views[view][key].value);
  599. const select = document.createElement("select");
  600. select.classList.add("options-field-unit");
  601. select.id = "options-view-" + key + "-select"
  602. unitChoices[val.type].forEach(name => {
  603. const option = document.createElement("option");
  604. option.innerText = name;
  605. select.appendChild(option);
  606. });
  607. input.addEventListener("change", e => {
  608. const value = input.value == 0 ? 1 : input.value;
  609. entity.views[view][key] = math.unit(value, select.value);
  610. entity.dirty = true;
  611. if (config.autoFit) {
  612. fitWorld();
  613. } else {
  614. updateSizes(true);
  615. }
  616. updateEntityOptions(entity, view);
  617. updateViewOptions(entity, view, key);
  618. });
  619. input.addEventListener("keydown", e => {
  620. e.stopPropagation();
  621. })
  622. select.setAttribute("oldUnit", select.value);
  623. // TODO does this ever cause a change in the world?
  624. select.addEventListener("input", e => {
  625. const value = input.value == 0 ? 1 : input.value;
  626. const oldUnit = select.getAttribute("oldUnit");
  627. entity.views[entity.view][key] = math.unit(value, oldUnit).to(select.value);
  628. entity.dirty = true;
  629. setNumericInput(input, entity.views[entity.view][key].toNumber(select.value));
  630. select.setAttribute("oldUnit", select.value);
  631. if (config.autoFit) {
  632. fitWorld();
  633. } else {
  634. updateSizes(true);
  635. }
  636. updateEntityOptions(entity, view);
  637. updateViewOptions(entity, view, key);
  638. });
  639. row.appendChild(input);
  640. row.appendChild(select);
  641. });
  642. }
  643. function updateViewOptions(entity, view, changed) {
  644. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  645. if (key != changed) {
  646. const input = document.querySelector("#options-view-" + key + "-input");
  647. const select = document.querySelector("#options-view-" + key + "-select");
  648. const currentUnit = select.value;
  649. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  650. setNumericInput(input, convertedAmount);
  651. }
  652. });
  653. }
  654. function setNumericInput(input, value, round=3) {
  655. input.value = math.round(value, round);
  656. }
  657. function getSortedEntities() {
  658. return Object.keys(entities).sort((a, b) => {
  659. const entA = entities[a];
  660. const entB = entities[b];
  661. const viewA = entA.view;
  662. const viewB = entB.view;
  663. const heightA = entA.views[viewA].height.to("meter").value;
  664. const heightB = entB.views[viewB].height.to("meter").value;
  665. return heightA - heightB;
  666. });
  667. }
  668. function clearViewOptions() {
  669. document.querySelector("#view-category-header").style.display = "none";
  670. document.querySelector("#view-category").style.display = "none";
  671. }
  672. // this is a crime against humanity, and also stolen from
  673. // stack overflow
  674. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  675. const testCanvas = document.createElement("canvas");
  676. testCanvas.id = "test-canvas";
  677. const testCtx = testCanvas.getContext("2d");
  678. function testClick(event) {
  679. // oh my god I can't believe I'm doing this
  680. const target = event.target;
  681. if (navigator.userAgent.indexOf("Firefox") != -1) {
  682. clickDown(target.parentElement, event.clientX, event.clientY);
  683. return;
  684. }
  685. // Get click coordinates
  686. let w = target.width;
  687. let h = target.height;
  688. let ratioW = 1, ratioH = 1;
  689. // Limit the size of the canvas so that very large images don't cause problems)
  690. if (w > 1000) {
  691. ratioW = w / 1000;
  692. w /= ratioW;
  693. h /= ratioW;
  694. }
  695. if (h > 1000) {
  696. ratioH = h / 1000;
  697. w /= ratioH;
  698. h /= ratioH;
  699. }
  700. const ratio = ratioW * ratioH;
  701. var x = event.clientX - target.getBoundingClientRect().x,
  702. y = event.clientY - target.getBoundingClientRect().y,
  703. alpha;
  704. testCtx.canvas.width = w;
  705. testCtx.canvas.height = h;
  706. // Draw image to canvas
  707. // and read Alpha channel value
  708. testCtx.drawImage(target, 0, 0, w, h);
  709. alpha = testCtx.getImageData(Math.floor(x / ratio), Math.floor(y / ratio), 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  710. // If pixel is transparent,
  711. // retrieve the element underneath and trigger its click event
  712. if (alpha === 0) {
  713. const oldDisplay = target.style.display;
  714. target.style.display = "none";
  715. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  716. newTarget.dispatchEvent(new MouseEvent(event.type, {
  717. "clientX": event.clientX,
  718. "clientY": event.clientY
  719. }));
  720. target.style.display = oldDisplay;
  721. } else {
  722. clickDown(target.parentElement, event.clientX, event.clientY);
  723. }
  724. }
  725. function arrangeEntities(order) {
  726. let x = 0.1;
  727. order.forEach(key => {
  728. document.querySelector("#entity-" + key).dataset.x = x;
  729. x += 0.8 / (order.length - 1);
  730. });
  731. updateSizes();
  732. }
  733. function removeAllEntities() {
  734. Object.keys(entities).forEach(key => {
  735. removeEntity(document.querySelector("#entity-" + key));
  736. });
  737. }
  738. function clearAttribution() {
  739. document.querySelector("#attribution-category-header").style.display = "none";
  740. document.querySelector("#options-attribution").style.display = "none";
  741. }
  742. function displayAttribution(file) {
  743. document.querySelector("#attribution-category-header").style.display = "block";
  744. document.querySelector("#options-attribution").style.display = "inline";
  745. const authors = authorsOfFull(file);
  746. const owners = ownersOfFull(file);
  747. const source = sourceOf(file);
  748. const authorHolder = document.querySelector("#options-attribution-authors");
  749. const ownerHolder = document.querySelector("#options-attribution-owners");
  750. const sourceHolder = document.querySelector("#options-attribution-source");
  751. if (authors === []) {
  752. const div = document.createElement("div");
  753. div.innerText = "Unknown";
  754. authorHolder.innerHTML = "";
  755. authorHolder.appendChild(div);
  756. } else if (authors === undefined) {
  757. const div = document.createElement("div");
  758. div.innerText = "Not yet entered";
  759. authorHolder.innerHTML = "";
  760. authorHolder.appendChild(div);
  761. } else {
  762. authorHolder.innerHTML = "";
  763. const list = document.createElement("ul");
  764. authorHolder.appendChild(list);
  765. authors.forEach(author => {
  766. const authorEntry = document.createElement("li");
  767. if (author.url) {
  768. const link = document.createElement("a");
  769. link.href = author.url;
  770. link.innerText = author.name;
  771. authorEntry.appendChild(link);
  772. } else {
  773. const div = document.createElement("div");
  774. div.innerText = author.name;
  775. authorEntry.appendChild(div);
  776. }
  777. list.appendChild(authorEntry);
  778. });
  779. }
  780. if (owners === []) {
  781. const div = document.createElement("div");
  782. div.innerText = "Unknown";
  783. ownerHolder.innerHTML = "";
  784. ownerHolder.appendChild(div);
  785. } else if (owners === undefined) {
  786. const div = document.createElement("div");
  787. div.innerText = "Not yet entered";
  788. ownerHolder.innerHTML = "";
  789. ownerHolder.appendChild(div);
  790. } else {
  791. ownerHolder.innerHTML = "";
  792. const list = document.createElement("ul");
  793. ownerHolder.appendChild(list);
  794. owners.forEach(owner => {
  795. const ownerEntry = document.createElement("li");
  796. if (owner.url) {
  797. const link = document.createElement("a");
  798. link.href = owner.url;
  799. link.innerText = owner.name;
  800. ownerEntry.appendChild(link);
  801. } else {
  802. const div = document.createElement("div");
  803. div.innerText = owner.name;
  804. ownerEntry.appendChild(div);
  805. }
  806. list.appendChild(ownerEntry);
  807. });
  808. }
  809. if (source === null) {
  810. const div = document.createElement("div");
  811. div.innerText = "No link";
  812. sourceHolder.innerHTML = "";
  813. sourceHolder.appendChild(div);
  814. } else if (source === undefined) {
  815. const div = document.createElement("div");
  816. div.innerText = "Not yet entered";
  817. sourceHolder.innerHTML = "";
  818. sourceHolder.appendChild(div);
  819. } else {
  820. sourceHolder.innerHTML = "";
  821. const link = document.createElement("a");
  822. link.style.display = "block";
  823. link.href = source;
  824. link.innerText = new URL(source).host;
  825. sourceHolder.appendChild(link);
  826. }
  827. }
  828. function removeEntity(element) {
  829. if (selected == element) {
  830. deselect();
  831. }
  832. const option = document.querySelector("#options-selected-entity-" + element.dataset.key);
  833. option.parentElement.removeChild(option);
  834. delete entities[element.dataset.key];
  835. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  836. const topName = document.querySelector("#top-name-" + element.dataset.key);
  837. bottomName.parentElement.removeChild(bottomName);
  838. topName.parentElement.removeChild(topName);
  839. element.parentElement.removeChild(element);
  840. }
  841. function checkEntity(entity) {
  842. Object.values(entity.views).forEach(view => {
  843. if (authorsOf(view.image.source) === undefined) {
  844. console.warn("No authors: " + view.image.source);
  845. }
  846. });
  847. }
  848. function displayEntity(entity, view, x, y, selectEntity=false, refresh=false) {
  849. checkEntity(entity);
  850. const box = document.createElement("div");
  851. box.classList.add("entity-box");
  852. const img = document.createElement("img");
  853. img.classList.add("entity-image");
  854. img.addEventListener("dragstart", e => {
  855. e.preventDefault();
  856. });
  857. const nameTag = document.createElement("div");
  858. nameTag.classList.add("entity-name");
  859. nameTag.innerText = entity.name;
  860. box.appendChild(img);
  861. box.appendChild(nameTag);
  862. const image = entity.views[view].image;
  863. img.src = image.source;
  864. if (image.bottom !== undefined) {
  865. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  866. } else {
  867. img.style.setProperty("--offset", ((-1) * 100) + "%")
  868. }
  869. box.dataset.x = x;
  870. box.dataset.y = y;
  871. img.addEventListener("mousedown", e => { testClick(e); e.stopPropagation() });
  872. img.addEventListener("touchstart", e => {
  873. const fakeEvent = {
  874. target: e.target,
  875. clientX: e.touches[0].clientX,
  876. clientY: e.touches[0].clientY
  877. };
  878. testClick(fakeEvent);
  879. });
  880. const heightBar = document.createElement("div");
  881. heightBar.classList.add("height-bar");
  882. box.appendChild(heightBar);
  883. box.id = "entity-" + entityIndex;
  884. box.dataset.key = entityIndex;
  885. entity.view = view;
  886. entity.priority = 0;
  887. entities[entityIndex] = entity;
  888. entity.index = entityIndex;
  889. const world = document.querySelector("#entities");
  890. world.appendChild(box);
  891. const bottomName = document.createElement("div");
  892. bottomName.classList.add("bottom-name");
  893. bottomName.id = "bottom-name-" + entityIndex;
  894. bottomName.innerText = entity.name;
  895. bottomName.addEventListener("click", () => select(box));
  896. world.appendChild(bottomName);
  897. const topName = document.createElement("div");
  898. topName.classList.add("top-name");
  899. topName.id = "top-name-" + entityIndex;
  900. topName.innerText = entity.name;
  901. topName.addEventListener("click", () => select(box));
  902. world.appendChild(topName);
  903. const entityOption = document.createElement("option");
  904. entityOption.id = "options-selected-entity-" + entityIndex;
  905. entityOption.value = entityIndex;
  906. entityOption.innerText = entity.name;
  907. document.getElementById("options-selected-entity").appendChild(entityOption);
  908. entityIndex += 1;
  909. if (config.autoFit) {
  910. fitWorld();
  911. }
  912. if (selectEntity)
  913. select(box);
  914. entity.dirty = true;
  915. if (refresh)
  916. updateSizes(true);
  917. }
  918. window.onblur = function () {
  919. altHeld = false;
  920. shiftHeld = false;
  921. }
  922. window.onfocus = function () {
  923. window.dispatchEvent(new Event("keydown"));
  924. }
  925. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  926. function toggleFullScreen() {
  927. var doc = window.document;
  928. var docEl = doc.documentElement;
  929. var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  930. var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
  931. if(!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
  932. requestFullScreen.call(docEl);
  933. }
  934. else {
  935. cancelFullScreen.call(doc);
  936. }
  937. }
  938. function handleResize() {
  939. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  940. canvasWidth = document.querySelector("#display").clientWidth - 100;
  941. canvasHeight = document.querySelector("#display").clientHeight - 50;
  942. updateSizes();
  943. }
  944. function prepareMenu() {
  945. const menubar = document.querySelector("#popout-menu");
  946. [
  947. [
  948. {
  949. name: "Show/hide sidebar",
  950. id: "menu-toggle-sidebar",
  951. icon: "fas fa-chevron-circle-down",
  952. rotates: true
  953. },
  954. {
  955. name: "Fullscreen",
  956. id: "menu-fullscreen",
  957. icon: "fas fa-compress"
  958. }
  959. ],
  960. [
  961. {
  962. name: "Clear",
  963. id: "menu-clear",
  964. icon: "fas fa-file"
  965. }
  966. ],
  967. [
  968. {
  969. name: "Sort by height",
  970. id: "menu-order-height",
  971. icon: "fas fa-sort-numeric-up"
  972. }
  973. ],
  974. [
  975. {
  976. name: "Permalink",
  977. id: "menu-permalink",
  978. icon: "fas fa-link"
  979. },
  980. {
  981. name: "Export",
  982. id: "menu-export",
  983. icon: "fas fa-share"
  984. },
  985. {
  986. name: "Save",
  987. id: "menu-save",
  988. icon: "fas fa-download"
  989. },
  990. {
  991. name: "Load",
  992. id: "menu-load",
  993. icon: "fas fa-upload"
  994. },
  995. {
  996. name: "Load Autosave",
  997. id: "menu-load-autosave",
  998. icon: "fas fa-redo"
  999. }
  1000. ]
  1001. ].forEach(group => {
  1002. const span = document.createElement("span");
  1003. span.classList.add("popout-group");
  1004. group.forEach(entry => {
  1005. const buttonHolder = document.createElement("div");
  1006. const button = document.createElement("button");
  1007. button.id = entry.id;
  1008. button.classList.add("menu-button");
  1009. const icon = document.createElement("i");
  1010. icon.classList.add(...entry.icon.split(" "));
  1011. if (entry.rotates) {
  1012. icon.classList.add("rotate-backward", "transitions");
  1013. }
  1014. const actionText = document.createElement("span");
  1015. actionText.innerText = entry.name;
  1016. actionText.classList.add("menu-text");
  1017. const srText = document.createElement("span");
  1018. srText.classList.add("sr-only");
  1019. srText.innerText = entry.name;
  1020. button.appendChild(icon);
  1021. button.appendChild(srText);
  1022. buttonHolder.appendChild(button);
  1023. buttonHolder.appendChild(actionText);
  1024. span.appendChild(buttonHolder);
  1025. });
  1026. menubar.appendChild(span);
  1027. });
  1028. if (checkHelpDate()) {
  1029. document.querySelector("#open-help").classList.add("highlighted");
  1030. }
  1031. }
  1032. const lastHelpChange = 1585487259753;
  1033. function checkHelpDate() {
  1034. try {
  1035. const old = localStorage.getItem("help-viewed");
  1036. if (old === null || old < lastHelpChange) {
  1037. return true;
  1038. }
  1039. return false;
  1040. } catch {
  1041. console.warn("Could not set the help-viewed date");
  1042. return false;
  1043. }
  1044. }
  1045. function setHelpDate() {
  1046. try {
  1047. localStorage.setItem("help-viewed", Date.now());
  1048. } catch {
  1049. console.warn("Could not set the help-viewed date");
  1050. }
  1051. }
  1052. function doScroll() {
  1053. document.querySelectorAll(".entity-box").forEach(element => {
  1054. element.dataset.x = parseFloat(element.dataset.x) + scrollDirection/180;
  1055. });
  1056. updateSizes();
  1057. scrollDirection *= 1.05;
  1058. }
  1059. function doZoom() {
  1060. const oldHeight = config.height;
  1061. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  1062. zoomDirection *= 1.05;
  1063. }
  1064. function doSize() {
  1065. if (selected) {
  1066. const entity = entities[selected.dataset.key];
  1067. const oldHeight = entity.views[entity.view].height;
  1068. entity.views[entity.view].height = math.multiply(oldHeight, 1 + sizeDirection/20);
  1069. entity.dirty = true;
  1070. updateEntityOptions(entity, entity.view);
  1071. updateViewOptions(entity, entity.view);
  1072. updateSizes(true);
  1073. sizeDirection *= 1.05;
  1074. }
  1075. }
  1076. document.addEventListener("DOMContentLoaded", () => {
  1077. prepareMenu();
  1078. prepareEntities();
  1079. document.querySelector("#toggle-menu").addEventListener("click", e => {
  1080. const popoutMenu = document.querySelector("#popout-menu");
  1081. console.log("hi")
  1082. if (popoutMenu.classList.contains("visible")) {
  1083. popoutMenu.classList.remove("visible");
  1084. } else {
  1085. const rect = e.target.getBoundingClientRect();
  1086. popoutMenu.classList.add("visible");
  1087. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  1088. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  1089. }
  1090. e.stopPropagation();
  1091. });
  1092. document.querySelector("#popout-menu").addEventListener("click", e => {
  1093. e.stopPropagation();
  1094. });
  1095. document.addEventListener("click", e => {
  1096. console.log("hiii")
  1097. document.querySelector("#popout-menu").classList.remove("visible");
  1098. });
  1099. window.addEventListener("unload", () => saveScene("autosave"));
  1100. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  1101. if (e.target.value == "none") {
  1102. deselect()
  1103. } else {
  1104. select(document.querySelector("#entity-" + e.target.value));
  1105. }
  1106. });
  1107. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  1108. const sidebar = document.querySelector("#options");
  1109. if (sidebar.classList.contains("hidden")) {
  1110. sidebar.classList.remove("hidden");
  1111. e.target.classList.remove("rotate-forward");
  1112. e.target.classList.add("rotate-backward");
  1113. } else {
  1114. sidebar.classList.add("hidden");
  1115. e.target.classList.add("rotate-forward");
  1116. e.target.classList.remove("rotate-backward");
  1117. }
  1118. handleResize();
  1119. });
  1120. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  1121. document.querySelector("#options-show-extra").addEventListener("input", e => {
  1122. document.body.classList[e.target.checked ? "add" : "remove"]("show-extra-options");
  1123. });
  1124. document.querySelector("#options-world-show-names").addEventListener("input", e => {
  1125. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-entity-name");
  1126. });
  1127. document.querySelector("#options-world-show-bottom-names").addEventListener("input", e => {
  1128. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-bottom-name");
  1129. });
  1130. document.querySelector("#options-world-show-top-names").addEventListener("input", e => {
  1131. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-top-name");
  1132. });
  1133. document.querySelector("#options-world-show-height-bars").addEventListener("input", e => {
  1134. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-height-bars");
  1135. });
  1136. document.querySelector("#options-world-show-entity-glow").addEventListener("input", e => {
  1137. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-entity-glow");
  1138. });
  1139. document.querySelector("#options-world-show-bottom-cover").addEventListener("input", e => {
  1140. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-bottom-cover");
  1141. });
  1142. document.querySelector("#options-world-show-scale").addEventListener("input", e => {
  1143. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-scale");
  1144. });
  1145. document.querySelector("#options-order-forward").addEventListener("click", e => {
  1146. if (selected) {
  1147. entities[selected.dataset.key].priority += 1;
  1148. }
  1149. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1150. updateSizes();
  1151. });
  1152. document.querySelector("#options-order-back").addEventListener("click", e => {
  1153. if (selected) {
  1154. entities[selected.dataset.key].priority -= 1;
  1155. }
  1156. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1157. updateSizes();
  1158. });
  1159. const sceneChoices = document.querySelector("#scene-choices");
  1160. Object.entries(scenes).forEach(([id, scene]) => {
  1161. const option = document.createElement("option");
  1162. option.innerText = id;
  1163. option.value = id;
  1164. sceneChoices.appendChild(option);
  1165. });
  1166. document.querySelector("#load-scene").addEventListener("click", e => {
  1167. const chosen = sceneChoices.value;
  1168. removeAllEntities();
  1169. scenes[chosen]();
  1170. });
  1171. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1172. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1173. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1174. document.querySelector("#open-help").addEventListener("click", e => {
  1175. setHelpDate();
  1176. document.querySelector("#open-help").classList.remove("highlighted");
  1177. document.querySelector("#help").classList.add("visible");
  1178. });
  1179. document.querySelector("#close-help").addEventListener("click", e => {
  1180. document.querySelector("#help").classList.remove("visible");
  1181. });
  1182. document.querySelector("#options-height-value").addEventListener("change", e => {
  1183. updateWorldHeight();
  1184. })
  1185. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  1186. e.stopPropagation();
  1187. })
  1188. const unitSelector = document.querySelector("#options-height-unit");
  1189. unitChoices.length.forEach(lengthOption => {
  1190. const option = document.createElement("option");
  1191. option.innerText = lengthOption;
  1192. option.value = lengthOption;
  1193. if (lengthOption === "meters") {
  1194. option.selected = true;
  1195. }
  1196. unitSelector.appendChild(option);
  1197. });
  1198. unitSelector.setAttribute("oldUnit", "meters");
  1199. unitSelector.addEventListener("input", e => {
  1200. checkFitWorld();
  1201. const scaleInput = document.querySelector("#options-height-value");
  1202. const newVal = math.unit(scaleInput.value, unitSelector.getAttribute("oldUnit")).toNumber(e.target.value);
  1203. setNumericInput(scaleInput, newVal);
  1204. updateWorldHeight();
  1205. unitSelector.setAttribute("oldUnit", unitSelector.value);
  1206. });
  1207. param = new URL(window.location.href).searchParams.get("scene");
  1208. if (param === null) {
  1209. scenes["Default"]();
  1210. }
  1211. else {
  1212. try {
  1213. const data = JSON.parse(b64DecodeUnicode(param));
  1214. if (data.entities === undefined) {
  1215. return;
  1216. }
  1217. if (data.world === undefined) {
  1218. return;
  1219. }
  1220. importScene(data);
  1221. } catch (err) {
  1222. console.error(err);
  1223. scenes["Default"]();
  1224. // probably wasn't valid data
  1225. }
  1226. }
  1227. document.querySelector("#world").addEventListener("wheel", e => {
  1228. if (shiftHeld) {
  1229. if (selected) {
  1230. const dir = e.deltaY > 0 ? 10/11 : 11/10;
  1231. const entity = entities[selected.dataset.key];
  1232. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  1233. entity.dirty = true;
  1234. updateEntityOptions(entity, entity.view);
  1235. updateViewOptions(entity, entity.view);
  1236. updateSizes(true);
  1237. } else {
  1238. document.querySelectorAll(".entity-box").forEach(element => {
  1239. element.dataset.x = parseFloat(element.dataset.x) + (e.deltaY < 0 ? 0.1 : -0.1);
  1240. });
  1241. updateSizes();
  1242. }
  1243. } else {
  1244. const dir = e.deltaY < 0 ? 10/11 : 11/10;
  1245. setWorldHeight(config.height, math.multiply(config.height, dir));
  1246. updateWorldOptions();
  1247. }
  1248. checkFitWorld();
  1249. })
  1250. document.querySelector("body").appendChild(testCtx.canvas);
  1251. updateSizes();
  1252. world.addEventListener("mousedown", e => deselect());
  1253. document.querySelector("#entities").addEventListener("mousedown", deselect);
  1254. document.querySelector("#display").addEventListener("mousedown", deselect);
  1255. document.addEventListener("mouseup", e => clickUp(e));
  1256. document.addEventListener("touchend", e => {
  1257. const fakeEvent = {
  1258. target: e.target,
  1259. clientX: e.changedTouches[0].clientX,
  1260. clientY: e.changedTouches[0].clientY
  1261. };
  1262. clickUp(fakeEvent);
  1263. });
  1264. document.querySelector("#entity-view").addEventListener("input", e => {
  1265. const entity = entities[selected.dataset.key];
  1266. entity.view = e.target.value;
  1267. const image = entities[selected.dataset.key].views[e.target.value].image;
  1268. selected.querySelector(".entity-image").src = image.source;
  1269. displayAttribution(image.source);
  1270. if (image.bottom !== undefined) {
  1271. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  1272. } else {
  1273. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  1274. }
  1275. updateSizes();
  1276. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  1277. updateViewOptions(entities[selected.dataset.key], e.target.value);
  1278. });
  1279. clearViewList();
  1280. document.querySelector("#menu-clear").addEventListener("click", e => {
  1281. removeAllEntities();
  1282. });
  1283. document.querySelector("#delete-entity").disabled = true;
  1284. document.querySelector("#delete-entity").addEventListener("click", e => {
  1285. if (selected) {
  1286. removeEntity(selected);
  1287. selected = null;
  1288. }
  1289. });
  1290. document.querySelector("#menu-order-height").addEventListener("click", e => {
  1291. const order = Object.keys(entities).sort((a, b) => {
  1292. const entA = entities[a];
  1293. const entB = entities[b];
  1294. const viewA = entA.view;
  1295. const viewB = entB.view;
  1296. const heightA = entA.views[viewA].height.to("meter").value;
  1297. const heightB = entB.views[viewB].height.to("meter").value;
  1298. return heightA - heightB;
  1299. });
  1300. arrangeEntities(order);
  1301. });
  1302. // TODO: write some generic logic for this lol
  1303. document.querySelector("#scroll-left").addEventListener("mousedown", e => {
  1304. scrollDirection = 1;
  1305. clearInterval(scrollHandle);
  1306. scrollHandle = setInterval(doScroll, 1000/20);
  1307. e.stopPropagation();
  1308. });
  1309. document.querySelector("#scroll-right").addEventListener("mousedown", e => {
  1310. scrollDirection = -1;
  1311. clearInterval(scrollHandle);
  1312. scrollHandle = setInterval(doScroll, 1000/20);
  1313. e.stopPropagation();
  1314. });
  1315. document.querySelector("#scroll-left").addEventListener("touchstart", e => {
  1316. scrollDirection = 1;
  1317. clearInterval(scrollHandle);
  1318. scrollHandle = setInterval(doScroll, 1000/20);
  1319. e.stopPropagation();
  1320. });
  1321. document.querySelector("#scroll-right").addEventListener("touchstart", e => {
  1322. scrollDirection = -1;
  1323. clearInterval(scrollHandle);
  1324. scrollHandle = setInterval(doScroll, 1000/20);
  1325. e.stopPropagation();
  1326. });
  1327. document.addEventListener("mouseup", e => {
  1328. clearInterval(scrollHandle);
  1329. scrollHandle = null;
  1330. });
  1331. document.addEventListener("touchend", e => {
  1332. clearInterval(scrollHandle);
  1333. scrollHandle = null;
  1334. });
  1335. document.querySelector("#zoom-in").addEventListener("mousedown", e => {
  1336. zoomDirection = -1;
  1337. clearInterval(zoomHandle);
  1338. zoomHandle = setInterval(doZoom, 1000/20);
  1339. e.stopPropagation();
  1340. });
  1341. document.querySelector("#zoom-out").addEventListener("mousedown", e => {
  1342. zoomDirection = 1;
  1343. clearInterval(zoomHandle);
  1344. zoomHandle = setInterval(doZoom, 1000/20);
  1345. e.stopPropagation();
  1346. });
  1347. document.querySelector("#zoom-in").addEventListener("touchstart", e => {
  1348. zoomDirection = -1;
  1349. clearInterval(zoomHandle);
  1350. zoomHandle = setInterval(doZoom, 1000/20);
  1351. e.stopPropagation();
  1352. });
  1353. document.querySelector("#zoom-out").addEventListener("touchstart", e => {
  1354. zoomDirection = 1;
  1355. clearInterval(zoomHandle);
  1356. zoomHandle = setInterval(doZoom, 1000/20);
  1357. e.stopPropagation();
  1358. });
  1359. document.addEventListener("mouseup", e => {
  1360. clearInterval(zoomHandle);
  1361. zoomHandle = null;
  1362. });
  1363. document.addEventListener("touchend", e => {
  1364. clearInterval(zoomHandle);
  1365. zoomHandle = null;
  1366. });
  1367. document.querySelector("#shrink").addEventListener("mousedown", e => {
  1368. sizeDirection = -1;
  1369. clearInterval(sizeHandle);
  1370. sizeHandle = setInterval(doSize, 1000/20);
  1371. e.stopPropagation();
  1372. });
  1373. document.querySelector("#grow").addEventListener("mousedown", e => {
  1374. sizeDirection = 1;
  1375. clearInterval(sizeHandle);
  1376. sizeHandle = setInterval(doSize, 1000/20);
  1377. e.stopPropagation();
  1378. });
  1379. document.querySelector("#shrink").addEventListener("touchstart", e => {
  1380. sizeDirection = -1;
  1381. clearInterval(sizeHandle);
  1382. sizeHandle = setInterval(doSize, 1000/20);
  1383. e.stopPropagation();
  1384. });
  1385. document.querySelector("#grow").addEventListener("touchstart", e => {
  1386. sizeDirection = 1;
  1387. clearInterval(sizeHandle);
  1388. sizeHandle = setInterval(doSize, 1000/20);
  1389. e.stopPropagation();
  1390. });
  1391. document.addEventListener("mouseup", e => {
  1392. clearInterval(sizeHandle);
  1393. sizeHandle = null;
  1394. });
  1395. document.addEventListener("touchend", e => {
  1396. clearInterval(sizeHandle);
  1397. sizeHandle = null;
  1398. });
  1399. document.querySelector("#fit").addEventListener("click", e => {
  1400. const x = parseFloat(selected.dataset.x);
  1401. Object.keys(entities).forEach(id => {
  1402. const element = document.querySelector("#entity-" + id);
  1403. const newX = parseFloat(element.dataset.x) - x + 0.5;
  1404. element.dataset.x = newX;
  1405. });
  1406. const entity = entities[selected.dataset.key];
  1407. const height = math.multiply(entity.views[entity.view].height, 1.1);
  1408. setWorldHeight(config.height, height);
  1409. });
  1410. document.querySelector("#fit").addEventListener("mousedown", e => {
  1411. e.stopPropagation();
  1412. });
  1413. document.querySelector("#fit").addEventListener("touchstart", e => {
  1414. e.stopPropagation();
  1415. });
  1416. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  1417. document.querySelector("#options-world-autofit").addEventListener("input", e => {
  1418. config.autoFit = e.target.checked;
  1419. if (config.autoFit) {
  1420. fitWorld();
  1421. }
  1422. });
  1423. document.addEventListener("keydown", e => {
  1424. if (e.key == "Delete") {
  1425. if (selected) {
  1426. removeEntity(selected);
  1427. selected = null;
  1428. }
  1429. }
  1430. })
  1431. document.addEventListener("keydown", e => {
  1432. if (e.key == "Shift") {
  1433. shiftHeld = true;
  1434. e.preventDefault();
  1435. } else if (e.key == "Alt") {
  1436. altHeld = true;
  1437. e.preventDefault();
  1438. }
  1439. });
  1440. document.addEventListener("keyup", e => {
  1441. if (e.key == "Shift") {
  1442. shiftHeld = false;
  1443. e.preventDefault();
  1444. } else if (e.key == "Alt") {
  1445. altHeld = false;
  1446. e.preventDefault();
  1447. }
  1448. });
  1449. document.addEventListener("paste", e => {
  1450. try {
  1451. const data = JSON.parse(e.clipboardData.getData("text"));
  1452. if (data.entities === undefined) {
  1453. return;
  1454. }
  1455. if (data.world === undefined) {
  1456. return;
  1457. }
  1458. importScene(data);
  1459. } catch (err) {
  1460. console.error(err);
  1461. // probably wasn't valid data
  1462. }
  1463. });
  1464. window.addEventListener("resize", handleResize);
  1465. // TODO: further investigate why the tool initially starts out with wrong
  1466. // values under certain circumstances (seems to be narrow aspect ratios -
  1467. // maybe the menu bar is animating when it shouldn't)
  1468. setTimeout(handleResize, 250);
  1469. setTimeout(handleResize, 500);
  1470. setTimeout(handleResize, 750);
  1471. setTimeout(handleResize, 1000);
  1472. document.querySelector("#menu-permalink").addEventListener("click", e => {
  1473. linkScene();
  1474. });
  1475. document.querySelector("#menu-export").addEventListener("click", e => {
  1476. copyScene();
  1477. });
  1478. document.querySelector("#menu-save").addEventListener("click", e => {
  1479. saveScene();
  1480. });
  1481. document.querySelector("#menu-load").addEventListener("click", e => {
  1482. loadScene();
  1483. });
  1484. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  1485. loadScene("autosave");
  1486. });
  1487. clearEntityOptions();
  1488. clearViewOptions();
  1489. clearAttribution();
  1490. });
  1491. function prepareEntities() {
  1492. availableEntities["buildings"] = makeBuildings();
  1493. availableEntities["characters"] = makeCharacters();
  1494. availableEntities["cities"] = makeCities();
  1495. availableEntities["fiction"] = makeFiction();
  1496. availableEntities["food"] = makeFood();
  1497. availableEntities["landmarks"] = makeLandmarks();
  1498. availableEntities["naturals"] = makeNaturals();
  1499. availableEntities["objects"] = makeObjects();
  1500. availableEntities["pokemon"] = makePokemon();
  1501. availableEntities["species"] = makeSpecies();
  1502. availableEntities["vehicles"] = makeVehicles();
  1503. availableEntities["characters"].sort((x, y) => {
  1504. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  1505. });
  1506. const holder = document.querySelector("#spawners");
  1507. const categorySelect = document.createElement("select");
  1508. categorySelect.id = "category-picker";
  1509. holder.appendChild(categorySelect);
  1510. Object.entries(availableEntities).forEach(([category, entityList]) => {
  1511. const select = document.createElement("select");
  1512. select.id = "create-entity-" + category;
  1513. for (let i = 0; i < entityList.length; i++) {
  1514. const entity = entityList[i];
  1515. const option = document.createElement("option");
  1516. option.value = i;
  1517. option.innerText = entity.name;
  1518. select.appendChild(option);
  1519. availableEntitiesByName[entity.name] = entity;
  1520. };
  1521. const button = document.createElement("button");
  1522. button.id = "create-entity-" + category + "-button";
  1523. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  1524. button.addEventListener("click", e => {
  1525. const newEntity = entityList[select.value].constructor()
  1526. displayEntity(newEntity, newEntity.defaultView, 0.5, 1, true, true);
  1527. });
  1528. const categoryOption = document.createElement("option");
  1529. categoryOption.value = category
  1530. categoryOption.innerText = category;
  1531. if (category == "characters") {
  1532. categoryOption.selected = true;
  1533. select.classList.add("category-visible");
  1534. button.classList.add("category-visible");
  1535. }
  1536. categorySelect.appendChild(categoryOption);
  1537. holder.appendChild(select);
  1538. holder.appendChild(button);
  1539. });
  1540. categorySelect.addEventListener("input", e => {
  1541. const oldSelect = document.querySelector("select.category-visible");
  1542. oldSelect.classList.remove("category-visible");
  1543. const oldButton = document.querySelector("button.category-visible");
  1544. oldButton.classList.remove("category-visible");
  1545. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  1546. newSelect.classList.add("category-visible");
  1547. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  1548. newButton.classList.add("category-visible");
  1549. });
  1550. }
  1551. document.addEventListener("mousemove", (e) => {
  1552. if (clicked) {
  1553. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  1554. clicked.dataset.x = position.x;
  1555. clicked.dataset.y = position.y;
  1556. updateEntityElement(entities[clicked.dataset.key], clicked);
  1557. if (hoveringInDeleteArea(e)) {
  1558. document.querySelector("#menubar").classList.add("hover-delete");
  1559. } else {
  1560. document.querySelector("#menubar").classList.remove("hover-delete");
  1561. }
  1562. }
  1563. });
  1564. document.addEventListener("touchmove", (e) => {
  1565. if (clicked) {
  1566. e.preventDefault();
  1567. let x = e.touches[0].clientX;
  1568. let y = e.touches[0].clientY;
  1569. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  1570. clicked.dataset.x = position.x;
  1571. clicked.dataset.y = position.y;
  1572. updateEntityElement(entities[clicked.dataset.key], clicked);
  1573. // what a hack
  1574. // I should centralize this 'fake event' creation...
  1575. if (hoveringInDeleteArea({ clientY: y })) {
  1576. document.querySelector("#menubar").classList.add("hover-delete");
  1577. } else {
  1578. document.querySelector("#menubar").classList.remove("hover-delete");
  1579. }
  1580. }
  1581. }, { passive: false });
  1582. function checkFitWorld() {
  1583. if (config.autoFit) {
  1584. fitWorld();
  1585. return true;
  1586. }
  1587. return false;
  1588. }
  1589. const fitModes = {
  1590. "max": {
  1591. start: 0,
  1592. binop: Math.max,
  1593. final: (total, count) => total
  1594. },
  1595. "arithmetic mean": {
  1596. start: 0,
  1597. binop: math.add,
  1598. final: (total, count) => total / count
  1599. },
  1600. "geometric mean": {
  1601. start: 1,
  1602. binop: math.multiply,
  1603. final: (total, count) => math.pow(total, 1 / count)
  1604. }
  1605. }
  1606. function fitWorld(manual=false, factor=1.1) {
  1607. const fitMode = fitModes[config.autoFitMode]
  1608. let max = fitMode.start
  1609. let count = 0;
  1610. Object.entries(entities).forEach(([key, entity]) => {
  1611. const view = entity.view;
  1612. let extra = entity.views[view].image.extra;
  1613. extra = extra === undefined ? 1 : extra;
  1614. max = fitMode.binop(max, math.multiply(extra, entity.views[view].height.toNumber("meter")));
  1615. count += 1;
  1616. });
  1617. max = fitMode.final(max, count)
  1618. max = math.unit(max, "meter")
  1619. if (manual)
  1620. altHeld = true;
  1621. setWorldHeight(config.height, math.multiply(max, factor));
  1622. if (manual)
  1623. altHeld = false;
  1624. }
  1625. function updateWorldHeight() {
  1626. const unit = document.querySelector("#options-height-unit").value;
  1627. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  1628. const oldHeight = config.height;
  1629. setWorldHeight(oldHeight, math.unit(value, unit));
  1630. }
  1631. function setWorldHeight(oldHeight, newHeight) {
  1632. worldSizeDirty = true;
  1633. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  1634. const unit = document.querySelector("#options-height-unit").value;
  1635. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  1636. Object.entries(entities).forEach(([key, entity]) => {
  1637. const element = document.querySelector("#entity-" + key);
  1638. let newPosition;
  1639. if (!altHeld) {
  1640. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  1641. } else {
  1642. newPosition = { x: element.dataset.x, y: element.dataset.y };
  1643. }
  1644. element.dataset.x = newPosition.x;
  1645. element.dataset.y = newPosition.y;
  1646. });
  1647. updateSizes();
  1648. }
  1649. function loadScene(name="default") {
  1650. try {
  1651. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  1652. if (data === null) {
  1653. return false;
  1654. }
  1655. importScene(data);
  1656. return true;
  1657. } catch (err) {
  1658. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  1659. console.error(err);
  1660. return false;
  1661. }
  1662. }
  1663. function saveScene(name="default") {
  1664. try {
  1665. const string = JSON.stringify(exportScene());
  1666. localStorage.setItem("macrovision-save-" + name, string);
  1667. } catch (err) {
  1668. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  1669. console.error(err);
  1670. }
  1671. }
  1672. function deleteScene(name="default") {
  1673. try {
  1674. localStorage.removeItem("macrovision-save-" + name)
  1675. } catch(err) {
  1676. console.error(err);
  1677. }
  1678. }
  1679. function exportScene() {
  1680. const results = {};
  1681. results.entities = [];
  1682. Object.entries(entities).forEach(([key, entity]) => {
  1683. const element = document.querySelector("#entity-" + key);
  1684. results.entities.push({
  1685. name: entity.identifier,
  1686. scale: entity.scale,
  1687. view: entity.view,
  1688. x: element.dataset.x,
  1689. y: element.dataset.y
  1690. });
  1691. });
  1692. const unit = document.querySelector("#options-height-unit").value;
  1693. results.world = {
  1694. height: config.height.toNumber(unit),
  1695. unit: unit
  1696. }
  1697. return results;
  1698. }
  1699. // btoa doesn't like anything that isn't ASCII
  1700. // great
  1701. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  1702. // for providing an alternative
  1703. function b64EncodeUnicode(str) {
  1704. // first we use encodeURIComponent to get percent-encoded UTF-8,
  1705. // then we convert the percent encodings into raw bytes which
  1706. // can be fed into btoa.
  1707. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  1708. function toSolidBytes(match, p1) {
  1709. return String.fromCharCode('0x' + p1);
  1710. }));
  1711. }
  1712. function b64DecodeUnicode(str) {
  1713. // Going backwards: from bytestream, to percent-encoding, to original string.
  1714. return decodeURIComponent(atob(str).split('').map(function(c) {
  1715. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  1716. }).join(''));
  1717. }
  1718. function linkScene() {
  1719. loc = new URL(window.location);
  1720. window.location = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  1721. }
  1722. function copyScene() {
  1723. const results = exportScene();
  1724. navigator.clipboard.writeText(JSON.stringify(results))
  1725. alert("Scene copied to clipboard. Paste text into the page to load the scene.");
  1726. }
  1727. // TODO - don't just search through every single entity
  1728. // probably just have a way to do lookups directly
  1729. function findEntity(name) {
  1730. return availableEntitiesByName[name];
  1731. }
  1732. function importScene(data) {
  1733. removeAllEntities();
  1734. data.entities.forEach(entityInfo => {
  1735. const entity = findEntity(entityInfo.name).constructor();
  1736. entity.scale = entityInfo.scale
  1737. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  1738. });
  1739. config.height = math.unit(data.world.height, data.world.unit);
  1740. document.querySelector("#options-height-unit").value = data.world.unit;
  1741. updateSizes();
  1742. }