less copy protection, more size visualization
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 

2881 lines
86 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("earths", {
  37. definition: "12756km",
  38. prefixes: "long"
  39. });
  40. math.createUnit("parsec", {
  41. definition: "3.086e16 meters",
  42. prefixes: "long"
  43. })
  44. math.createUnit("parsecs", {
  45. definition: "3.086e16 meters",
  46. prefixes: "long"
  47. })
  48. math.createUnit("lightyears", {
  49. definition: "9.461e15 meters",
  50. prefixes: "long"
  51. })
  52. math.createUnit("AU", {
  53. definition: "149597870700 meters"
  54. })
  55. math.createUnit("AUs", {
  56. definition: "149597870700 meters"
  57. })
  58. math.createUnit("dalton", {
  59. definition: "1.66e-27 kg",
  60. prefixes: "long"
  61. });
  62. math.createUnit("daltons", {
  63. definition: "1.66e-27 kg",
  64. prefixes: "long"
  65. });
  66. math.createUnit("solarradii", {
  67. definition: "695990 km",
  68. prefixes: "long"
  69. });
  70. math.createUnit("solarmasses", {
  71. definition: "2e30 kg",
  72. prefixes: "long"
  73. });
  74. math.createUnit("galaxy", {
  75. definition: "105700 lightyears",
  76. prefixes: "long"
  77. });
  78. math.createUnit("galaxies", {
  79. definition: "105700 lightyears",
  80. prefixes: "long"
  81. });
  82. math.createUnit("universe", {
  83. definition: "93.016e9 lightyears",
  84. prefixes: "long"
  85. });
  86. math.createUnit("universes", {
  87. definition: "93.016e9 lightyears",
  88. prefixes: "long"
  89. });
  90. math.createUnit("multiverse", {
  91. definition: "1e30 lightyears",
  92. prefixes: "long"
  93. });
  94. math.createUnit("multiverses", {
  95. definition: "1e30 lightyears",
  96. prefixes: "long"
  97. });
  98. const unitChoices = {
  99. length: [
  100. "meters",
  101. "angstroms",
  102. "millimeters",
  103. "centimeters",
  104. "kilometers",
  105. "inches",
  106. "feet",
  107. "humans",
  108. "stories",
  109. "miles",
  110. "earths",
  111. "solarradii",
  112. "AUs",
  113. "lightyears",
  114. "parsecs",
  115. "galaxies",
  116. "universes",
  117. "multiverses"
  118. ],
  119. area: [
  120. "meters^2",
  121. "cm^2",
  122. "kilometers^2",
  123. "acres",
  124. "miles^2"
  125. ],
  126. mass: [
  127. "kilograms",
  128. "milligrams",
  129. "grams",
  130. "tonnes",
  131. "lbs",
  132. "ounces",
  133. "tons"
  134. ]
  135. }
  136. const config = {
  137. height: math.unit(1500, "meters"),
  138. minLineSize: 100,
  139. maxLineSize: 150,
  140. autoFit: false,
  141. autoFitMode: "max"
  142. }
  143. const availableEntities = {
  144. }
  145. const availableEntitiesByName = {
  146. }
  147. const entities = {
  148. }
  149. function constrainRel(coords) {
  150. if (altHeld) {
  151. return coords;
  152. }
  153. return {
  154. x: Math.min(Math.max(coords.x, 0), 1),
  155. y: Math.min(Math.max(coords.y, 0), 1)
  156. }
  157. }
  158. function snapRel(coords) {
  159. return constrainRel({
  160. x: coords.x,
  161. y: altHeld ? coords.y : (Math.abs(coords.y - 1) < 0.05 ? 1 : coords.y)
  162. });
  163. }
  164. function adjustAbs(coords, oldHeight, newHeight) {
  165. const ratio = math.divide(oldHeight, newHeight);
  166. return { x: 0.5 + (coords.x - 0.5) * math.divide(oldHeight, newHeight), y: 1 + (coords.y - 1) * math.divide(oldHeight, newHeight) };
  167. }
  168. function rel2abs(coords) {
  169. return { x: coords.x * canvasWidth + 50, y: coords.y * canvasHeight };
  170. }
  171. function abs2rel(coords) {
  172. return { x: (coords.x - 50) / canvasWidth, y: coords.y / canvasHeight };
  173. }
  174. function updateEntityElement(entity, element) {
  175. const position = rel2abs({ x: element.dataset.x, y: element.dataset.y });
  176. const view = entity.view;
  177. element.style.left = position.x + "px";
  178. element.style.top = position.y + "px";
  179. element.style.setProperty("--xpos", position.x + "px");
  180. element.style.setProperty("--entity-height", "'" + entity.views[view].height.to(config.height.units[0].unit.name).format({ precision: 2 }) + "'");
  181. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 50);
  182. const extra = entity.views[view].image.extra;
  183. const bottom = entity.views[view].image.bottom;
  184. const bonus = (extra ? extra : 1) * (1 / (1 - (bottom ? bottom : 0)));
  185. element.style.setProperty("--height", pixels * bonus + "px");
  186. element.style.setProperty("--extra", pixels * bonus - pixels + "px");
  187. if (entity.views[view].rename)
  188. element.querySelector(".entity-name").innerText = entity.name == "" ? "" : entity.views[view].name;
  189. else
  190. element.querySelector(".entity-name").innerText = entity.name;
  191. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  192. bottomName.style.left = position.x + entityX + "px";
  193. bottomName.style.bottom = "0vh";
  194. bottomName.innerText = entity.name;
  195. const topName = document.querySelector("#top-name-" + element.dataset.key);
  196. topName.style.left = position.x + entityX + "px";
  197. topName.style.top = "20vh";
  198. topName.innerText = entity.name;
  199. if (entity.views[view].height.toNumber("meters") / 10 > config.height.toNumber("meters")) {
  200. topName.classList.add("top-name-needed");
  201. } else {
  202. topName.classList.remove("top-name-needed");
  203. }
  204. }
  205. function updateSizes(dirtyOnly = false) {
  206. drawScale(dirtyOnly);
  207. let ordered = Object.entries(entities);
  208. ordered.sort((e1, e2) => {
  209. if (e1[1].priority != e2[1].priority) {
  210. return e2[1].priority - e1[1].priority;
  211. } else {
  212. return e1[1].views[e1[1].view].height.value - e2[1].views[e2[1].view].height.value
  213. }
  214. });
  215. let zIndex = ordered.length;
  216. ordered.forEach(entity => {
  217. const element = document.querySelector("#entity-" + entity[0]);
  218. element.style.zIndex = zIndex;
  219. if (!dirtyOnly || entity[1].dirty) {
  220. updateEntityElement(entity[1], element, zIndex);
  221. entity[1].dirty = false;
  222. }
  223. zIndex -= 1;
  224. });
  225. }
  226. function drawScale(ifDirty = false) {
  227. if (ifDirty && !worldSizeDirty)
  228. return;
  229. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  230. let total = heightPer.clone();
  231. total.value = 0;
  232. for (let y = ctx.canvas.clientHeight - 50; y >= 50; y -= pixelsPer) {
  233. drawTick(ctx, 50, y, total);
  234. total = math.add(total, heightPer);
  235. }
  236. }
  237. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, value) {
  238. const oldStroke = ctx.strokeStyle;
  239. const oldFill = ctx.fillStyle;
  240. ctx.beginPath();
  241. ctx.moveTo(x, y);
  242. ctx.lineTo(x + 20, y);
  243. ctx.strokeStyle = "#000000";
  244. ctx.stroke();
  245. ctx.beginPath();
  246. ctx.moveTo(x + 20, y);
  247. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  248. ctx.strokeStyle = "#aaaaaa";
  249. ctx.stroke();
  250. ctx.beginPath();
  251. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  252. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  253. ctx.strokeStyle = "#000000";
  254. ctx.stroke();
  255. const oldFont = ctx.font;
  256. ctx.font = 'normal 24pt coda';
  257. ctx.fillStyle = "#dddddd";
  258. ctx.beginPath();
  259. ctx.fillText(value.format({ precision: 3 }), x + 20, y + 35);
  260. ctx.font = oldFont;
  261. ctx.strokeStyle = oldStroke;
  262. ctx.fillStyle = oldFill;
  263. }
  264. const canvas = document.querySelector("#display");
  265. /** @type {CanvasRenderingContext2D} */
  266. const ctx = canvas.getContext("2d");
  267. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.toNumber();
  268. heightPer = 1;
  269. if (pixelsPer < config.minLineSize) {
  270. const factor = math.ceil(config.minLineSize / pixelsPer);
  271. heightPer *= factor;
  272. pixelsPer *= factor;
  273. }
  274. if (pixelsPer > config.maxLineSize) {
  275. const factor = math.ceil(pixelsPer / config.maxLineSize);
  276. heightPer /= factor;
  277. pixelsPer /= factor;
  278. }
  279. heightPer = math.unit(heightPer, config.height.units[0].unit.name)
  280. ctx.scale(1, 1);
  281. ctx.canvas.width = canvas.clientWidth;
  282. ctx.canvas.height = canvas.clientHeight;
  283. ctx.beginPath();
  284. ctx.rect(0, 0, canvas.width, canvas.height);
  285. ctx.fillStyle = "#333";
  286. ctx.fill();
  287. ctx.beginPath();
  288. ctx.moveTo(50, 50);
  289. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  290. ctx.stroke();
  291. ctx.beginPath();
  292. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  293. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  294. ctx.stroke();
  295. drawTicks(ctx, pixelsPer, heightPer);
  296. }
  297. // Entities are generated as needed, and we make a copy
  298. // every time - the resulting objects get mutated, after all.
  299. // But we also want to be able to read some information without
  300. // calling the constructor -- e.g. making a list of authors and
  301. // owners. So, this function is used to generate that information.
  302. // It is invoked like makeEntity so that it can be dropped in easily,
  303. // but returns an object that lets you construct many copies of an entity,
  304. // rather than creating a new entity.
  305. function createEntityMaker(info, views, sizes) {
  306. const maker = {};
  307. maker.name = info.name;
  308. maker.constructor = () => makeEntity(info, views, sizes);
  309. maker.authors = [];
  310. maker.owners = [];
  311. maker.nsfw = false;
  312. Object.values(views).forEach(view => {
  313. const authors = authorsOf(view.image.source);
  314. if (authors) {
  315. authors.forEach(author => {
  316. if (maker.authors.indexOf(author) == -1) {
  317. maker.authors.push(author);
  318. }
  319. });
  320. }
  321. const owners = ownersOf(view.image.source);
  322. if (owners) {
  323. owners.forEach(owner => {
  324. if (maker.owners.indexOf(owner) == -1) {
  325. maker.owners.push(owner);
  326. }
  327. });
  328. }
  329. if (isNsfw(view.image.source)) {
  330. maker.nsfw = true;
  331. }
  332. });
  333. return maker;
  334. }
  335. // This function serializes and parses its arguments to avoid sharing
  336. // references to a common object. This allows for the objects to be
  337. // safely mutated.
  338. function makeEntity(info, views, sizes) {
  339. const entityTemplate = {
  340. name: info.name,
  341. identifier: info.name,
  342. scale: 1,
  343. info: JSON.parse(JSON.stringify(info)),
  344. views: JSON.parse(JSON.stringify(views), math.reviver),
  345. sizes: sizes === undefined ? [] : JSON.parse(JSON.stringify(sizes), math.reviver),
  346. init: function () {
  347. const entity = this;
  348. Object.entries(this.views).forEach(([viewKey, view]) => {
  349. view.parent = this;
  350. if (this.defaultView === undefined) {
  351. this.defaultView = viewKey;
  352. this.view = viewKey;
  353. }
  354. Object.entries(view.attributes).forEach(([key, val]) => {
  355. Object.defineProperty(
  356. view,
  357. key,
  358. {
  359. get: function () {
  360. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  361. },
  362. set: function (value) {
  363. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  364. this.parent.scale = newScale;
  365. }
  366. }
  367. )
  368. });
  369. });
  370. this.sizes.forEach(size => {
  371. if (size.default === true) {
  372. this.views[this.defaultView].height = size.height;
  373. this.size = size;
  374. }
  375. });
  376. if (this.size === undefined && this.sizes.length > 0) {
  377. this.views[this.defaultView].height = this.sizes[0].height;
  378. this.size = this.sizes[0];
  379. console.warn("No default size set for " + info.name);
  380. } else if (this.sizes.length == 0) {
  381. this.sizes = [
  382. {
  383. name: "Normal",
  384. height: this.views[this.defaultView].height
  385. }
  386. ];
  387. this.size = this.sizes[0];
  388. }
  389. this.desc = {};
  390. Object.entries(this.info).forEach(([key, value]) => {
  391. Object.defineProperty(
  392. this.desc,
  393. key,
  394. {
  395. get: function () {
  396. let text = value.text;
  397. if (entity.views[entity.view].info) {
  398. if (entity.views[entity.view].info[key]) {
  399. text = combineInfo(text, entity.views[entity.view].info[key]);
  400. }
  401. }
  402. if (entity.size.info) {
  403. if (entity.size.info[key]) {
  404. text = combineInfo(text, entity.size.info[key]);
  405. }
  406. }
  407. return { title: value.title, text: text };
  408. }
  409. }
  410. )
  411. });
  412. delete this.init;
  413. return this;
  414. }
  415. }.init();
  416. return entityTemplate;
  417. }
  418. function combineInfo(existing, next) {
  419. switch (next.mode) {
  420. case "replace":
  421. return next.text;
  422. case "prepend":
  423. return next.text + existing;
  424. case "append":
  425. return existing + next.text;
  426. }
  427. return existing;
  428. }
  429. function clickDown(target, x, y) {
  430. clicked = target;
  431. const rect = target.getBoundingClientRect();
  432. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  433. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  434. dragOffsetX = x - rect.left + entX;
  435. dragOffsetY = y - rect.top + entY;
  436. clickTimeout = setTimeout(() => { dragging = true }, 200)
  437. target.classList.add("no-transition");
  438. }
  439. // could we make this actually detect the menu area?
  440. function hoveringInDeleteArea(e) {
  441. return e.clientY < document.body.clientHeight / 10;
  442. }
  443. function clickUp(e) {
  444. clearTimeout(clickTimeout);
  445. if (clicked) {
  446. if (dragging) {
  447. dragging = false;
  448. if (hoveringInDeleteArea(e)) {
  449. removeEntity(clicked);
  450. document.querySelector("#menubar").classList.remove("hover-delete");
  451. }
  452. } else {
  453. select(clicked);
  454. }
  455. clicked.classList.remove("no-transition");
  456. clicked = null;
  457. }
  458. }
  459. function deselect() {
  460. if (selected) {
  461. selected.classList.remove("selected");
  462. }
  463. document.getElementById("options-selected-entity-none").selected = "selected";
  464. clearAttribution();
  465. selected = null;
  466. clearViewList();
  467. clearEntityOptions();
  468. clearViewOptions();
  469. document.querySelector("#delete-entity").disabled = true;
  470. document.querySelector("#grow").disabled = true;
  471. document.querySelector("#shrink").disabled = true;
  472. document.querySelector("#fit").disabled = true;
  473. }
  474. function select(target) {
  475. deselect();
  476. selected = target;
  477. selectedEntity = entities[target.dataset.key];
  478. document.getElementById("options-selected-entity-" + target.dataset.key).selected = "selected";
  479. selected.classList.add("selected");
  480. displayAttribution(selectedEntity.views[selectedEntity.view].image.source);
  481. configViewList(selectedEntity, selectedEntity.view);
  482. configEntityOptions(selectedEntity, selectedEntity.view);
  483. configViewOptions(selectedEntity, selectedEntity.view);
  484. document.querySelector("#delete-entity").disabled = false;
  485. document.querySelector("#grow").disabled = false;
  486. document.querySelector("#shrink").disabled = false;
  487. document.querySelector("#fit").disabled = false;
  488. }
  489. function configViewList(entity, selectedView) {
  490. const list = document.querySelector("#entity-view");
  491. list.innerHTML = "";
  492. list.style.display = "block";
  493. Object.keys(entity.views).forEach(view => {
  494. const option = document.createElement("option");
  495. option.innerText = entity.views[view].name;
  496. option.value = view;
  497. if (isNsfw(entity.views[view].image.source)) {
  498. option.classList.add("nsfw")
  499. }
  500. if (view === selectedView) {
  501. option.selected = true;
  502. if (option.classList.contains("nsfw")) {
  503. list.classList.add("nsfw");
  504. } else {
  505. list.classList.remove("nsfw");
  506. }
  507. }
  508. list.appendChild(option);
  509. });
  510. }
  511. function clearViewList() {
  512. const list = document.querySelector("#entity-view");
  513. list.innerHTML = "";
  514. list.style.display = "none";
  515. }
  516. function updateWorldOptions(entity, view) {
  517. const heightInput = document.querySelector("#options-height-value");
  518. const heightSelect = document.querySelector("#options-height-unit");
  519. const converted = config.height.toNumber(heightSelect.value);
  520. setNumericInput(heightInput, converted);
  521. }
  522. function configEntityOptions(entity, view) {
  523. const holder = document.querySelector("#options-entity");
  524. document.querySelector("#entity-category-header").style.display = "block";
  525. document.querySelector("#entity-category").style.display = "block";
  526. holder.innerHTML = "";
  527. const scaleLabel = document.createElement("div");
  528. scaleLabel.classList.add("options-label");
  529. scaleLabel.innerText = "Scale";
  530. const scaleRow = document.createElement("div");
  531. scaleRow.classList.add("options-row");
  532. const scaleInput = document.createElement("input");
  533. scaleInput.classList.add("options-field-numeric");
  534. scaleInput.id = "options-entity-scale";
  535. scaleInput.addEventListener("change", e => {
  536. entity.scale = e.target.value == 0 ? 1 : e.target.value;
  537. entity.dirty = true;
  538. if (config.autoFit) {
  539. fitWorld();
  540. } else {
  541. updateSizes(true);
  542. }
  543. updateEntityOptions(entity, view);
  544. updateViewOptions(entity, view);
  545. });
  546. scaleInput.addEventListener("keydown", e => {
  547. e.stopPropagation();
  548. })
  549. scaleInput.setAttribute("min", 1);
  550. scaleInput.setAttribute("type", "number");
  551. setNumericInput(scaleInput, entity.scale);
  552. scaleRow.appendChild(scaleInput);
  553. holder.appendChild(scaleLabel);
  554. holder.appendChild(scaleRow);
  555. const nameLabel = document.createElement("div");
  556. nameLabel.classList.add("options-label");
  557. nameLabel.innerText = "Name";
  558. const nameRow = document.createElement("div");
  559. nameRow.classList.add("options-row");
  560. const nameInput = document.createElement("input");
  561. nameInput.classList.add("options-field-text");
  562. nameInput.value = entity.name;
  563. nameInput.addEventListener("input", e => {
  564. entity.name = e.target.value;
  565. entity.dirty = true;
  566. updateSizes(true);
  567. })
  568. nameInput.addEventListener("keydown", e => {
  569. e.stopPropagation();
  570. })
  571. nameRow.appendChild(nameInput);
  572. holder.appendChild(nameLabel);
  573. holder.appendChild(nameRow);
  574. const defaultHolder = document.querySelector("#options-entity-defaults");
  575. defaultHolder.innerHTML = "";
  576. entity.sizes.forEach(defaultInfo => {
  577. const button = document.createElement("button");
  578. button.classList.add("options-button");
  579. button.innerText = defaultInfo.name;
  580. button.addEventListener("click", e => {
  581. entity.views[entity.defaultView].height = defaultInfo.height;
  582. entity.dirty = true;
  583. updateEntityOptions(entity, entity.view);
  584. updateViewOptions(entity, entity.view);
  585. if (!checkFitWorld()) {
  586. updateSizes(true);
  587. }
  588. if (config.autoFitSize) {
  589. const x = parseFloat(selected.dataset.x);
  590. Object.keys(entities).forEach(id => {
  591. const element = document.querySelector("#entity-" + id);
  592. const newX = parseFloat(element.dataset.x) - x + 0.5;
  593. element.dataset.x = newX;
  594. });
  595. const entity = entities[selected.dataset.key];
  596. const height = math.multiply(entity.views[entity.view].height, 1.1);
  597. setWorldHeight(config.height, height);
  598. }
  599. });
  600. defaultHolder.appendChild(button);
  601. });
  602. document.querySelector("#options-order-display").innerText = entity.priority;
  603. document.querySelector("#options-ordering").style.display = "flex";
  604. }
  605. function updateEntityOptions(entity, view) {
  606. const scaleInput = document.querySelector("#options-entity-scale");
  607. setNumericInput(scaleInput, entity.scale);
  608. document.querySelector("#options-order-display").innerText = entity.priority;
  609. }
  610. function clearEntityOptions() {
  611. document.querySelector("#entity-category-header").style.display = "none";
  612. document.querySelector("#entity-category").style.display = "none";
  613. /*
  614. const holder = document.querySelector("#options-entity");
  615. holder.innerHTML = "";
  616. document.querySelector("#options-entity-defaults").innerHTML = "";
  617. document.querySelector("#options-ordering").style.display = "none";
  618. document.querySelector("#options-ordering").style.display = "none";*/
  619. }
  620. function configViewOptions(entity, view) {
  621. const holder = document.querySelector("#options-view");
  622. document.querySelector("#view-category-header").style.display = "block";
  623. document.querySelector("#view-category").style.display = "block";
  624. holder.innerHTML = "";
  625. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  626. const label = document.createElement("div");
  627. label.classList.add("options-label");
  628. label.innerText = val.name;
  629. holder.appendChild(label);
  630. const row = document.createElement("div");
  631. row.classList.add("options-row");
  632. holder.appendChild(row);
  633. const input = document.createElement("input");
  634. input.classList.add("options-field-numeric");
  635. input.id = "options-view-" + key + "-input";
  636. input.setAttribute("type", "number");
  637. input.setAttribute("min", 1);
  638. setNumericInput(input, entity.views[view][key].value);
  639. const select = document.createElement("select");
  640. select.classList.add("options-field-unit");
  641. select.id = "options-view-" + key + "-select"
  642. unitChoices[val.type].forEach(name => {
  643. const option = document.createElement("option");
  644. option.innerText = name;
  645. select.appendChild(option);
  646. });
  647. input.addEventListener("change", e => {
  648. const value = input.value == 0 ? 1 : input.value;
  649. entity.views[view][key] = math.unit(value, select.value);
  650. entity.dirty = true;
  651. if (config.autoFit) {
  652. fitWorld();
  653. } else {
  654. updateSizes(true);
  655. }
  656. updateEntityOptions(entity, view);
  657. updateViewOptions(entity, view, key);
  658. });
  659. input.addEventListener("keydown", e => {
  660. e.stopPropagation();
  661. })
  662. select.setAttribute("oldUnit", select.value);
  663. // TODO does this ever cause a change in the world?
  664. select.addEventListener("input", e => {
  665. const value = input.value == 0 ? 1 : input.value;
  666. const oldUnit = select.getAttribute("oldUnit");
  667. entity.views[entity.view][key] = math.unit(value, oldUnit).to(select.value);
  668. entity.dirty = true;
  669. setNumericInput(input, entity.views[entity.view][key].toNumber(select.value));
  670. select.setAttribute("oldUnit", select.value);
  671. if (config.autoFit) {
  672. fitWorld();
  673. } else {
  674. updateSizes(true);
  675. }
  676. updateEntityOptions(entity, view);
  677. updateViewOptions(entity, view, key);
  678. });
  679. row.appendChild(input);
  680. row.appendChild(select);
  681. });
  682. }
  683. function updateViewOptions(entity, view, changed) {
  684. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  685. if (key != changed) {
  686. const input = document.querySelector("#options-view-" + key + "-input");
  687. const select = document.querySelector("#options-view-" + key + "-select");
  688. const currentUnit = select.value;
  689. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  690. setNumericInput(input, convertedAmount);
  691. }
  692. });
  693. }
  694. function setNumericInput(input, value, round = 3) {
  695. input.value = math.round(value, round);
  696. }
  697. function getSortedEntities() {
  698. return Object.keys(entities).sort((a, b) => {
  699. const entA = entities[a];
  700. const entB = entities[b];
  701. const viewA = entA.view;
  702. const viewB = entB.view;
  703. const heightA = entA.views[viewA].height.to("meter").value;
  704. const heightB = entB.views[viewB].height.to("meter").value;
  705. return heightA - heightB;
  706. });
  707. }
  708. function clearViewOptions() {
  709. document.querySelector("#view-category-header").style.display = "none";
  710. document.querySelector("#view-category").style.display = "none";
  711. }
  712. // this is a crime against humanity, and also stolen from
  713. // stack overflow
  714. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  715. const testCanvas = document.createElement("canvas");
  716. testCanvas.id = "test-canvas";
  717. const testCtx = testCanvas.getContext("2d");
  718. function testClick(event) {
  719. // oh my god I can't believe I'm doing this
  720. const target = event.target;
  721. if (navigator.userAgent.indexOf("Firefox") != -1) {
  722. clickDown(target.parentElement, event.clientX, event.clientY);
  723. return;
  724. }
  725. // Get click coordinates
  726. let w = target.width;
  727. let h = target.height;
  728. let ratioW = 1, ratioH = 1;
  729. // Limit the size of the canvas so that very large images don't cause problems)
  730. if (w > 1000) {
  731. ratioW = w / 1000;
  732. w /= ratioW;
  733. h /= ratioW;
  734. }
  735. if (h > 1000) {
  736. ratioH = h / 1000;
  737. w /= ratioH;
  738. h /= ratioH;
  739. }
  740. const ratio = ratioW * ratioH;
  741. var x = event.clientX - target.getBoundingClientRect().x,
  742. y = event.clientY - target.getBoundingClientRect().y,
  743. alpha;
  744. testCtx.canvas.width = w;
  745. testCtx.canvas.height = h;
  746. // Draw image to canvas
  747. // and read Alpha channel value
  748. testCtx.drawImage(target, 0, 0, w, h);
  749. alpha = testCtx.getImageData(Math.floor(x / ratio), Math.floor(y / ratio), 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  750. // If pixel is transparent,
  751. // retrieve the element underneath and trigger its click event
  752. if (alpha === 0) {
  753. const oldDisplay = target.style.display;
  754. target.style.display = "none";
  755. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  756. newTarget.dispatchEvent(new MouseEvent(event.type, {
  757. "clientX": event.clientX,
  758. "clientY": event.clientY
  759. }));
  760. target.style.display = oldDisplay;
  761. } else {
  762. clickDown(target.parentElement, event.clientX, event.clientY);
  763. }
  764. }
  765. function arrangeEntities(order) {
  766. let x = 0.1;
  767. order.forEach(key => {
  768. document.querySelector("#entity-" + key).dataset.x = x;
  769. x += 0.8 / (order.length - 1);
  770. });
  771. updateSizes();
  772. }
  773. function removeAllEntities() {
  774. Object.keys(entities).forEach(key => {
  775. removeEntity(document.querySelector("#entity-" + key));
  776. });
  777. }
  778. function clearAttribution() {
  779. document.querySelector("#attribution-category-header").style.display = "none";
  780. document.querySelector("#options-attribution").style.display = "none";
  781. }
  782. function displayAttribution(file) {
  783. document.querySelector("#attribution-category-header").style.display = "block";
  784. document.querySelector("#options-attribution").style.display = "inline";
  785. const authors = authorsOfFull(file);
  786. const owners = ownersOfFull(file);
  787. const source = sourceOf(file);
  788. const authorHolder = document.querySelector("#options-attribution-authors");
  789. const ownerHolder = document.querySelector("#options-attribution-owners");
  790. const sourceHolder = document.querySelector("#options-attribution-source");
  791. if (authors === []) {
  792. const div = document.createElement("div");
  793. div.innerText = "Unknown";
  794. authorHolder.innerHTML = "";
  795. authorHolder.appendChild(div);
  796. } else if (authors === undefined) {
  797. const div = document.createElement("div");
  798. div.innerText = "Not yet entered";
  799. authorHolder.innerHTML = "";
  800. authorHolder.appendChild(div);
  801. } else {
  802. authorHolder.innerHTML = "";
  803. const list = document.createElement("ul");
  804. authorHolder.appendChild(list);
  805. authors.forEach(author => {
  806. const authorEntry = document.createElement("li");
  807. if (author.url) {
  808. const link = document.createElement("a");
  809. link.href = author.url;
  810. link.innerText = author.name;
  811. authorEntry.appendChild(link);
  812. } else {
  813. const div = document.createElement("div");
  814. div.innerText = author.name;
  815. authorEntry.appendChild(div);
  816. }
  817. list.appendChild(authorEntry);
  818. });
  819. }
  820. if (owners === []) {
  821. const div = document.createElement("div");
  822. div.innerText = "Unknown";
  823. ownerHolder.innerHTML = "";
  824. ownerHolder.appendChild(div);
  825. } else if (owners === undefined) {
  826. const div = document.createElement("div");
  827. div.innerText = "Not yet entered";
  828. ownerHolder.innerHTML = "";
  829. ownerHolder.appendChild(div);
  830. } else {
  831. ownerHolder.innerHTML = "";
  832. const list = document.createElement("ul");
  833. ownerHolder.appendChild(list);
  834. owners.forEach(owner => {
  835. const ownerEntry = document.createElement("li");
  836. if (owner.url) {
  837. const link = document.createElement("a");
  838. link.href = owner.url;
  839. link.innerText = owner.name;
  840. ownerEntry.appendChild(link);
  841. } else {
  842. const div = document.createElement("div");
  843. div.innerText = owner.name;
  844. ownerEntry.appendChild(div);
  845. }
  846. list.appendChild(ownerEntry);
  847. });
  848. }
  849. if (source === null) {
  850. const div = document.createElement("div");
  851. div.innerText = "No link";
  852. sourceHolder.innerHTML = "";
  853. sourceHolder.appendChild(div);
  854. } else if (source === undefined) {
  855. const div = document.createElement("div");
  856. div.innerText = "Not yet entered";
  857. sourceHolder.innerHTML = "";
  858. sourceHolder.appendChild(div);
  859. } else {
  860. sourceHolder.innerHTML = "";
  861. const link = document.createElement("a");
  862. link.style.display = "block";
  863. link.href = source;
  864. link.innerText = new URL(source).host;
  865. sourceHolder.appendChild(link);
  866. }
  867. }
  868. function removeEntity(element) {
  869. if (selected == element) {
  870. deselect();
  871. }
  872. const option = document.querySelector("#options-selected-entity-" + element.dataset.key);
  873. option.parentElement.removeChild(option);
  874. delete entities[element.dataset.key];
  875. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  876. const topName = document.querySelector("#top-name-" + element.dataset.key);
  877. bottomName.parentElement.removeChild(bottomName);
  878. topName.parentElement.removeChild(topName);
  879. element.parentElement.removeChild(element);
  880. }
  881. function checkEntity(entity) {
  882. Object.values(entity.views).forEach(view => {
  883. if (authorsOf(view.image.source) === undefined) {
  884. console.warn("No authors: " + view.image.source);
  885. }
  886. });
  887. }
  888. function displayEntity(entity, view, x, y, selectEntity = false, refresh = false) {
  889. checkEntity(entity);
  890. const box = document.createElement("div");
  891. box.classList.add("entity-box");
  892. const img = document.createElement("img");
  893. img.classList.add("entity-image");
  894. img.addEventListener("dragstart", e => {
  895. e.preventDefault();
  896. });
  897. const nameTag = document.createElement("div");
  898. nameTag.classList.add("entity-name");
  899. nameTag.innerText = entity.name;
  900. box.appendChild(img);
  901. box.appendChild(nameTag);
  902. const image = entity.views[view].image;
  903. img.src = image.source;
  904. if (image.bottom !== undefined) {
  905. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  906. } else {
  907. img.style.setProperty("--offset", ((-1) * 100) + "%")
  908. }
  909. box.dataset.x = x;
  910. box.dataset.y = y;
  911. img.addEventListener("mousedown", e => { testClick(e); e.stopPropagation() });
  912. img.addEventListener("touchstart", e => {
  913. const fakeEvent = {
  914. target: e.target,
  915. clientX: e.touches[0].clientX,
  916. clientY: e.touches[0].clientY
  917. };
  918. testClick(fakeEvent);
  919. });
  920. const heightBar = document.createElement("div");
  921. heightBar.classList.add("height-bar");
  922. box.appendChild(heightBar);
  923. box.id = "entity-" + entityIndex;
  924. box.dataset.key = entityIndex;
  925. entity.view = view;
  926. entity.priority = 0;
  927. entities[entityIndex] = entity;
  928. entity.index = entityIndex;
  929. const world = document.querySelector("#entities");
  930. world.appendChild(box);
  931. const bottomName = document.createElement("div");
  932. bottomName.classList.add("bottom-name");
  933. bottomName.id = "bottom-name-" + entityIndex;
  934. bottomName.innerText = entity.name;
  935. bottomName.addEventListener("click", () => select(box));
  936. world.appendChild(bottomName);
  937. const topName = document.createElement("div");
  938. topName.classList.add("top-name");
  939. topName.id = "top-name-" + entityIndex;
  940. topName.innerText = entity.name;
  941. topName.addEventListener("click", () => select(box));
  942. world.appendChild(topName);
  943. const entityOption = document.createElement("option");
  944. entityOption.id = "options-selected-entity-" + entityIndex;
  945. entityOption.value = entityIndex;
  946. entityOption.innerText = entity.name;
  947. document.getElementById("options-selected-entity").appendChild(entityOption);
  948. entityIndex += 1;
  949. if (config.autoFit) {
  950. fitWorld();
  951. }
  952. if (selectEntity)
  953. select(box);
  954. entity.dirty = true;
  955. if (refresh && config.autoFitAdd) {
  956. const x = parseFloat(selected.dataset.x);
  957. Object.keys(entities).forEach(id => {
  958. const element = document.querySelector("#entity-" + id);
  959. const newX = parseFloat(element.dataset.x) - x + 0.5;
  960. element.dataset.x = newX;
  961. });
  962. const entity = entities[selected.dataset.key];
  963. const height = math.multiply(entity.views[entity.view].height, 1.1);
  964. setWorldHeight(config.height, height);
  965. }
  966. if (refresh)
  967. updateSizes(true);
  968. }
  969. window.onblur = function () {
  970. altHeld = false;
  971. shiftHeld = false;
  972. }
  973. window.onfocus = function () {
  974. window.dispatchEvent(new Event("keydown"));
  975. }
  976. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  977. function toggleFullScreen() {
  978. var doc = window.document;
  979. var docEl = doc.documentElement;
  980. var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  981. var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
  982. if (!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
  983. requestFullScreen.call(docEl);
  984. }
  985. else {
  986. cancelFullScreen.call(doc);
  987. }
  988. }
  989. function handleResize() {
  990. const oldCanvasWidth = canvasWidth;
  991. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  992. canvasWidth = document.querySelector("#display").clientWidth - 100;
  993. canvasHeight = document.querySelector("#display").clientHeight - 50;
  994. const change = oldCanvasWidth / canvasWidth;
  995. doHorizReposition(change);
  996. updateSizes();
  997. }
  998. function doHorizReposition(change) {
  999. Object.keys(entities).forEach(key => {
  1000. const element = document.querySelector("#entity-" + key);
  1001. const x = element.dataset.x;
  1002. element.dataset.x = (x - 0.5) * change + 0.5;
  1003. });
  1004. }
  1005. function prepareSidebar() {
  1006. const menubar = document.querySelector("#sidebar-menu");
  1007. [
  1008. {
  1009. name: "Show/hide sidebar",
  1010. id: "menu-toggle-sidebar",
  1011. icon: "fas fa-chevron-circle-down",
  1012. rotates: true
  1013. },
  1014. {
  1015. name: "Fullscreen",
  1016. id: "menu-fullscreen",
  1017. icon: "fas fa-compress"
  1018. },
  1019. {
  1020. name: "Clear",
  1021. id: "menu-clear",
  1022. icon: "fas fa-file"
  1023. },
  1024. {
  1025. name: "Sort by height",
  1026. id: "menu-order-height",
  1027. icon: "fas fa-sort-numeric-up"
  1028. },
  1029. {
  1030. name: "Permalink",
  1031. id: "menu-permalink",
  1032. icon: "fas fa-link"
  1033. },
  1034. {
  1035. name: "Export to clipboard",
  1036. id: "menu-export",
  1037. icon: "fas fa-share"
  1038. },
  1039. {
  1040. name: "Import from clipboard",
  1041. id: "menu-import",
  1042. icon: "fas fa-share",
  1043. classes: ["flipped"]
  1044. },
  1045. {
  1046. name: "Save",
  1047. id: "menu-save",
  1048. icon: "fas fa-download"
  1049. },
  1050. {
  1051. name: "Load",
  1052. id: "menu-load",
  1053. icon: "fas fa-upload"
  1054. },
  1055. {
  1056. name: "Load Autosave",
  1057. id: "menu-load-autosave",
  1058. icon: "fas fa-redo"
  1059. },
  1060. {
  1061. name: "Add Image",
  1062. id: "menu-add-image",
  1063. icon: "fas fa-camera"
  1064. }
  1065. ].forEach(entry => {
  1066. const buttonHolder = document.createElement("div");
  1067. buttonHolder.classList.add("menu-button-holder");
  1068. const button = document.createElement("button");
  1069. button.id = entry.id;
  1070. button.classList.add("menu-button");
  1071. const icon = document.createElement("i");
  1072. icon.classList.add(...entry.icon.split(" "));
  1073. if (entry.rotates) {
  1074. icon.classList.add("rotate-backward", "transitions");
  1075. }
  1076. if (entry.classes) {
  1077. entry.classes.forEach(cls => icon.classList.add(cls));
  1078. }
  1079. const actionText = document.createElement("span");
  1080. actionText.innerText = entry.name;
  1081. actionText.classList.add("menu-text");
  1082. const srText = document.createElement("span");
  1083. srText.classList.add("sr-only");
  1084. srText.innerText = entry.name;
  1085. button.appendChild(icon);
  1086. button.appendChild(srText);
  1087. buttonHolder.appendChild(button);
  1088. buttonHolder.appendChild(actionText);
  1089. menubar.appendChild(buttonHolder);
  1090. });
  1091. }
  1092. function checkBodyClass(cls) {
  1093. return document.body.classList.contains(cls);
  1094. }
  1095. function toggleBodyClass(cls, setting) {
  1096. if (setting) {
  1097. document.body.classList.add(cls);
  1098. } else {
  1099. document.body.classList.remove(cls);
  1100. }
  1101. }
  1102. const settingsData = {
  1103. "auto-scale": {
  1104. name: "Auto-Size World",
  1105. desc: "Constantly zoom to fit the largest entity",
  1106. type: "toggle",
  1107. default: false,
  1108. get value() {
  1109. return config.autoFit;
  1110. },
  1111. set value(param) {
  1112. config.autoFit = param;
  1113. checkFitWorld();
  1114. }
  1115. },
  1116. "zoom-when-adding": {
  1117. name: "Zoom When Adding",
  1118. desc: "Zoom to fit when you add a new entity",
  1119. type: "toggle",
  1120. default: true,
  1121. get value() {
  1122. return config.autoFitAdd;
  1123. },
  1124. set value(param) {
  1125. config.autoFitAdd = param;
  1126. }
  1127. },
  1128. "zoom-when-sizing": {
  1129. name: "Zoom When Sizing",
  1130. desc: "Zoom to fit when you select an entity's size",
  1131. type: "toggle",
  1132. default: true,
  1133. get value() {
  1134. return config.autoFitSize;
  1135. },
  1136. set value(param) {
  1137. config.autoFitSize = param;
  1138. }
  1139. },
  1140. "names": {
  1141. name: "Show Names",
  1142. desc: "Display names over entities",
  1143. type: "toggle",
  1144. default: true,
  1145. get value() {
  1146. return checkBodyClass("toggle-entity-name");
  1147. },
  1148. set value(param) {
  1149. toggleBodyClass("toggle-entity-name", param);
  1150. }
  1151. },
  1152. "bottom-names": {
  1153. name: "Bottom Names",
  1154. desc: "Display names at the bottom",
  1155. type: "toggle",
  1156. default: false,
  1157. get value() {
  1158. return checkBodyClass("toggle-bottom-name");
  1159. },
  1160. set value(param) {
  1161. toggleBodyClass("toggle-bottom-name", param);
  1162. }
  1163. },
  1164. "top-names": {
  1165. name: "Show Arrows",
  1166. desc: "Point to entities that are much larger than the current view",
  1167. type: "toggle",
  1168. default: false,
  1169. get value() {
  1170. return checkBodyClass("toggle-top-name");
  1171. },
  1172. set value(param) {
  1173. toggleBodyClass("toggle-top-name", param);
  1174. }
  1175. },
  1176. "height-bars": {
  1177. name: "Height Bars",
  1178. desc: "Draw dashed lines to the top of each entity",
  1179. type: "toggle",
  1180. default: false,
  1181. get value() {
  1182. return checkBodyClass("toggle-height-bars");
  1183. },
  1184. set value(param) {
  1185. toggleBodyClass("toggle-height-bars", param);
  1186. }
  1187. },
  1188. "glowing-entities": {
  1189. name: "Glowing Edges",
  1190. desc: "Makes all entities glow",
  1191. type: "toggle",
  1192. default: false,
  1193. get value() {
  1194. return checkBodyClass("toggle-entity-glow");
  1195. },
  1196. set value(param) {
  1197. toggleBodyClass("toggle-entity-glow", param);
  1198. }
  1199. },
  1200. "solid-ground": {
  1201. name: "Solid Ground",
  1202. desc: "Draw solid ground at the y=0 line",
  1203. type: "toggle",
  1204. default: false,
  1205. get value() {
  1206. return checkBodyClass("toggle-bottom-cover");
  1207. },
  1208. set value(param) {
  1209. toggleBodyClass("toggle-bottom-cover", param);
  1210. }
  1211. },
  1212. "show-scale": {
  1213. name: "Show Scale",
  1214. desc: "Show the scale",
  1215. type: "toggle",
  1216. default: true,
  1217. get value() {
  1218. return checkBodyClass("toggle-scale");
  1219. },
  1220. set value(param) {
  1221. toggleBodyClass("toggle-scale", param);
  1222. }
  1223. },
  1224. }
  1225. function prepareSettings(userSettings) {
  1226. const menubar = document.querySelector("#settings-menu");
  1227. Object.entries(settingsData).forEach(([id, entry]) => {
  1228. const holder = document.createElement("label");
  1229. holder.classList.add("settings-holder");
  1230. const input = document.createElement("input");
  1231. input.id = "setting-" + id;
  1232. const name = document.createElement("label");
  1233. name.innerText = entry.name;
  1234. name.classList.add("settings-name");
  1235. name.setAttribute("for", input.id);
  1236. const desc = document.createElement("label");
  1237. desc.innerText = entry.desc;
  1238. desc.classList.add("settings-desc");
  1239. desc.setAttribute("for", input.id);
  1240. if (entry.type == "toggle") {
  1241. input.type = "checkbox";
  1242. input.checked = userSettings[id] === undefined ? entry.default : userSettings[id];
  1243. holder.setAttribute("for", input.id);
  1244. input.appendChild(name);
  1245. input.appendChild(desc);
  1246. holder.appendChild(input);
  1247. holder.appendChild(name);
  1248. holder.appendChild(desc);
  1249. menubar.appendChild(holder);
  1250. const update = () => {
  1251. if (input.checked) {
  1252. holder.classList.add("enabled");
  1253. holder.classList.remove("disabled");
  1254. } else {
  1255. holder.classList.remove("enabled");
  1256. holder.classList.add("disabled");
  1257. }
  1258. entry.value = input.checked;
  1259. }
  1260. update();
  1261. input.addEventListener("change", update);
  1262. }
  1263. })
  1264. }
  1265. function prepareMenu() {
  1266. prepareSidebar();
  1267. if (checkHelpDate()) {
  1268. document.querySelector("#open-help").classList.add("highlighted");
  1269. }
  1270. }
  1271. function getUserSettings() {
  1272. try {
  1273. const settings = JSON.parse(localStorage.getItem("settings"));
  1274. return settings === null ? {} : settings;
  1275. } catch {
  1276. return {};
  1277. }
  1278. }
  1279. function exportUserSettings() {
  1280. const settings = {};
  1281. Object.entries(settingsData).forEach(([id, entry]) => {
  1282. settings[id] = entry.value;
  1283. });
  1284. return settings;
  1285. }
  1286. function setUserSettings(settings) {
  1287. try {
  1288. localStorage.setItem("settings", JSON.stringify(settings));
  1289. } catch {
  1290. // :(
  1291. }
  1292. }
  1293. const lastHelpChange = 1587847743294;
  1294. function checkHelpDate() {
  1295. try {
  1296. const old = localStorage.getItem("help-viewed");
  1297. if (old === null || old < lastHelpChange) {
  1298. return true;
  1299. }
  1300. return false;
  1301. } catch {
  1302. console.warn("Could not set the help-viewed date");
  1303. return false;
  1304. }
  1305. }
  1306. function setHelpDate() {
  1307. try {
  1308. localStorage.setItem("help-viewed", Date.now());
  1309. } catch {
  1310. console.warn("Could not set the help-viewed date");
  1311. }
  1312. }
  1313. function doScroll() {
  1314. document.querySelectorAll(".entity-box").forEach(element => {
  1315. element.dataset.x = parseFloat(element.dataset.x) + scrollDirection / 180;
  1316. });
  1317. updateSizes();
  1318. scrollDirection *= 1.05;
  1319. }
  1320. function doZoom() {
  1321. const oldHeight = config.height;
  1322. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  1323. zoomDirection *= 1.05;
  1324. }
  1325. function doSize() {
  1326. if (selected) {
  1327. const entity = entities[selected.dataset.key];
  1328. const oldHeight = entity.views[entity.view].height;
  1329. entity.views[entity.view].height = math.multiply(oldHeight, 1 + sizeDirection / 20);
  1330. entity.dirty = true;
  1331. updateEntityOptions(entity, entity.view);
  1332. updateViewOptions(entity, entity.view);
  1333. updateSizes(true);
  1334. sizeDirection *= 1.05;
  1335. const ownHeight = entity.views[entity.view].height.toNumber("meters");
  1336. const worldHeight = config.height.toNumber("meters");
  1337. if (ownHeight > worldHeight) {
  1338. setWorldHeight(config.height, entity.views[entity.view].height)
  1339. } else if (ownHeight * 10 < worldHeight) {
  1340. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, 10));
  1341. }
  1342. }
  1343. }
  1344. function prepareHelp() {
  1345. const toc = document.querySelector("#table-of-contents");
  1346. const holder = document.querySelector("#help-contents-holder");
  1347. document.querySelectorAll("#help-contents h2").forEach(header => {
  1348. const li = document.createElement("li");
  1349. li.innerText = header.textContent;
  1350. li.addEventListener("click", e => {
  1351. holder.scrollTop = header.offsetTop;
  1352. });
  1353. toc.appendChild(li);
  1354. });
  1355. }
  1356. document.addEventListener("DOMContentLoaded", () => {
  1357. prepareMenu();
  1358. prepareEntities();
  1359. prepareHelp();
  1360. document.querySelector("#open-help").addEventListener("click", e => {
  1361. setHelpDate();
  1362. document.querySelector("#help-menu").classList.add("visible");
  1363. document.querySelector("#open-help").classList.remove("highlighted");
  1364. });
  1365. document.querySelector("#close-help").addEventListener("click", e => {
  1366. document.querySelector("#help-menu").classList.remove("visible");
  1367. });
  1368. document.querySelector("#copy-screenshot").addEventListener("click", e => {
  1369. copyScreenshot();
  1370. toast("Copied to clipboard!");
  1371. });
  1372. document.querySelector("#save-screenshot").addEventListener("click", e => {
  1373. saveScreenshot();
  1374. });
  1375. document.querySelector("#toggle-menu").addEventListener("click", e => {
  1376. const popoutMenu = document.querySelector("#sidebar-menu");
  1377. if (popoutMenu.classList.contains("visible")) {
  1378. popoutMenu.classList.remove("visible");
  1379. } else {
  1380. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  1381. const rect = e.target.getBoundingClientRect();
  1382. popoutMenu.classList.add("visible");
  1383. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  1384. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  1385. }
  1386. e.stopPropagation();
  1387. });
  1388. document.querySelector("#sidebar-menu").addEventListener("click", e => {
  1389. e.stopPropagation();
  1390. });
  1391. document.addEventListener("click", e => {
  1392. document.querySelector("#sidebar-menu").classList.remove("visible");
  1393. });
  1394. document.querySelector("#toggle-settings").addEventListener("click", e => {
  1395. const popoutMenu = document.querySelector("#settings-menu");
  1396. if (popoutMenu.classList.contains("visible")) {
  1397. popoutMenu.classList.remove("visible");
  1398. } else {
  1399. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  1400. const rect = e.target.getBoundingClientRect();
  1401. popoutMenu.classList.add("visible");
  1402. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  1403. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  1404. }
  1405. e.stopPropagation();
  1406. });
  1407. document.querySelector("#settings-menu").addEventListener("click", e => {
  1408. e.stopPropagation();
  1409. });
  1410. document.addEventListener("click", e => {
  1411. document.querySelector("#settings-menu").classList.remove("visible");
  1412. });
  1413. window.addEventListener("unload", () => {
  1414. saveScene("autosave");
  1415. setUserSettings(exportUserSettings());
  1416. });
  1417. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  1418. if (e.target.value == "None") {
  1419. deselect()
  1420. } else {
  1421. select(document.querySelector("#entity-" + e.target.value));
  1422. }
  1423. });
  1424. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  1425. const sidebar = document.querySelector("#options");
  1426. if (sidebar.classList.contains("hidden")) {
  1427. sidebar.classList.remove("hidden");
  1428. e.target.classList.remove("rotate-forward");
  1429. e.target.classList.add("rotate-backward");
  1430. } else {
  1431. sidebar.classList.add("hidden");
  1432. e.target.classList.add("rotate-forward");
  1433. e.target.classList.remove("rotate-backward");
  1434. }
  1435. handleResize();
  1436. });
  1437. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  1438. document.querySelector("#options-order-forward").addEventListener("click", e => {
  1439. if (selected) {
  1440. entities[selected.dataset.key].priority += 1;
  1441. }
  1442. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1443. updateSizes();
  1444. });
  1445. document.querySelector("#options-order-back").addEventListener("click", e => {
  1446. if (selected) {
  1447. entities[selected.dataset.key].priority -= 1;
  1448. }
  1449. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1450. updateSizes();
  1451. });
  1452. const sceneChoices = document.querySelector("#scene-choices");
  1453. Object.entries(scenes).forEach(([id, scene]) => {
  1454. const option = document.createElement("option");
  1455. option.innerText = id;
  1456. option.value = id;
  1457. sceneChoices.appendChild(option);
  1458. });
  1459. document.querySelector("#load-scene").addEventListener("click", e => {
  1460. const chosen = sceneChoices.value;
  1461. removeAllEntities();
  1462. scenes[chosen]();
  1463. });
  1464. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1465. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1466. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1467. document.querySelector("#options-height-value").addEventListener("change", e => {
  1468. updateWorldHeight();
  1469. })
  1470. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  1471. e.stopPropagation();
  1472. })
  1473. const unitSelector = document.querySelector("#options-height-unit");
  1474. unitChoices.length.forEach(lengthOption => {
  1475. const option = document.createElement("option");
  1476. option.innerText = lengthOption;
  1477. option.value = lengthOption;
  1478. if (lengthOption === "meters") {
  1479. option.selected = true;
  1480. }
  1481. unitSelector.appendChild(option);
  1482. });
  1483. unitSelector.setAttribute("oldUnit", "meters");
  1484. unitSelector.addEventListener("input", e => {
  1485. checkFitWorld();
  1486. const scaleInput = document.querySelector("#options-height-value");
  1487. const newVal = math.unit(scaleInput.value, unitSelector.getAttribute("oldUnit")).toNumber(e.target.value);
  1488. setNumericInput(scaleInput, newVal);
  1489. updateWorldHeight();
  1490. unitSelector.setAttribute("oldUnit", unitSelector.value);
  1491. });
  1492. param = new URL(window.location.href).searchParams.get("scene");
  1493. if (param === null) {
  1494. scenes["Default"]();
  1495. }
  1496. else {
  1497. try {
  1498. const data = JSON.parse(b64DecodeUnicode(param));
  1499. if (data.entities === undefined) {
  1500. return;
  1501. }
  1502. if (data.world === undefined) {
  1503. return;
  1504. }
  1505. importScene(data);
  1506. } catch (err) {
  1507. console.error(err);
  1508. scenes["Default"]();
  1509. // probably wasn't valid data
  1510. }
  1511. }
  1512. document.querySelector("#world").addEventListener("wheel", e => {
  1513. if (shiftHeld) {
  1514. if (selected) {
  1515. const dir = e.deltaY > 0 ? 10 / 11 : 11 / 10;
  1516. const entity = entities[selected.dataset.key];
  1517. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  1518. entity.dirty = true;
  1519. updateEntityOptions(entity, entity.view);
  1520. updateViewOptions(entity, entity.view);
  1521. updateSizes(true);
  1522. } else {
  1523. document.querySelectorAll(".entity-box").forEach(element => {
  1524. element.dataset.x = parseFloat(element.dataset.x) + (e.deltaY < 0 ? 0.1 : -0.1);
  1525. });
  1526. updateSizes();
  1527. }
  1528. } else {
  1529. if (config.autoFit) {
  1530. toastRateLimit("Zoom is locked! Check Settings to disable.", "zoom-lock", 1000);
  1531. } else {
  1532. const dir = e.deltaY < 0 ? 10 / 11 : 11 / 10;
  1533. setWorldHeight(config.height, math.multiply(config.height, dir));
  1534. updateWorldOptions();
  1535. }
  1536. }
  1537. checkFitWorld();
  1538. })
  1539. document.querySelector("body").appendChild(testCtx.canvas);
  1540. updateSizes();
  1541. world.addEventListener("mousedown", e => deselect());
  1542. document.querySelector("#entities").addEventListener("mousedown", deselect);
  1543. document.querySelector("#display").addEventListener("mousedown", deselect);
  1544. document.addEventListener("mouseup", e => clickUp(e));
  1545. document.addEventListener("touchend", e => {
  1546. const fakeEvent = {
  1547. target: e.target,
  1548. clientX: e.changedTouches[0].clientX,
  1549. clientY: e.changedTouches[0].clientY
  1550. };
  1551. clickUp(fakeEvent);
  1552. });
  1553. const viewList = document.querySelector("#entity-view");
  1554. document.querySelector("#entity-view").addEventListener("input", e => {
  1555. const entity = entities[selected.dataset.key];
  1556. entity.view = e.target.value;
  1557. const image = entities[selected.dataset.key].views[e.target.value].image;
  1558. selected.querySelector(".entity-image").src = image.source;
  1559. configViewOptions(entity, entity.view);
  1560. displayAttribution(image.source);
  1561. if (image.bottom !== undefined) {
  1562. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  1563. } else {
  1564. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  1565. }
  1566. updateSizes();
  1567. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  1568. updateViewOptions(entities[selected.dataset.key], e.target.value);
  1569. });
  1570. document.querySelector("#entity-view").addEventListener("input", e => {
  1571. if (viewList.options[viewList.selectedIndex].classList.contains("nsfw")) {
  1572. viewList.classList.add("nsfw");
  1573. } else {
  1574. viewList.classList.remove("nsfw");
  1575. }
  1576. })
  1577. clearViewList();
  1578. document.querySelector("#menu-clear").addEventListener("click", e => {
  1579. removeAllEntities();
  1580. });
  1581. document.querySelector("#delete-entity").disabled = true;
  1582. document.querySelector("#delete-entity").addEventListener("click", e => {
  1583. if (selected) {
  1584. removeEntity(selected);
  1585. selected = null;
  1586. }
  1587. });
  1588. document.querySelector("#menu-order-height").addEventListener("click", e => {
  1589. const order = Object.keys(entities).sort((a, b) => {
  1590. const entA = entities[a];
  1591. const entB = entities[b];
  1592. const viewA = entA.view;
  1593. const viewB = entB.view;
  1594. const heightA = entA.views[viewA].height.to("meter").value;
  1595. const heightB = entB.views[viewB].height.to("meter").value;
  1596. return heightA - heightB;
  1597. });
  1598. arrangeEntities(order);
  1599. });
  1600. // TODO: write some generic logic for this lol
  1601. document.querySelector("#scroll-left").addEventListener("mousedown", e => {
  1602. scrollDirection = 1;
  1603. clearInterval(scrollHandle);
  1604. scrollHandle = setInterval(doScroll, 1000 / 20);
  1605. e.stopPropagation();
  1606. });
  1607. document.querySelector("#scroll-right").addEventListener("mousedown", e => {
  1608. scrollDirection = -1;
  1609. clearInterval(scrollHandle);
  1610. scrollHandle = setInterval(doScroll, 1000 / 20);
  1611. e.stopPropagation();
  1612. });
  1613. document.querySelector("#scroll-left").addEventListener("touchstart", e => {
  1614. scrollDirection = 1;
  1615. clearInterval(scrollHandle);
  1616. scrollHandle = setInterval(doScroll, 1000 / 20);
  1617. e.stopPropagation();
  1618. });
  1619. document.querySelector("#scroll-right").addEventListener("touchstart", e => {
  1620. scrollDirection = -1;
  1621. clearInterval(scrollHandle);
  1622. scrollHandle = setInterval(doScroll, 1000 / 20);
  1623. e.stopPropagation();
  1624. });
  1625. document.addEventListener("mouseup", e => {
  1626. clearInterval(scrollHandle);
  1627. scrollHandle = null;
  1628. });
  1629. document.addEventListener("touchend", e => {
  1630. clearInterval(scrollHandle);
  1631. scrollHandle = null;
  1632. });
  1633. document.querySelector("#zoom-in").addEventListener("mousedown", e => {
  1634. zoomDirection = -1;
  1635. clearInterval(zoomHandle);
  1636. zoomHandle = setInterval(doZoom, 1000 / 20);
  1637. e.stopPropagation();
  1638. });
  1639. document.querySelector("#zoom-out").addEventListener("mousedown", e => {
  1640. zoomDirection = 1;
  1641. clearInterval(zoomHandle);
  1642. zoomHandle = setInterval(doZoom, 1000 / 20);
  1643. e.stopPropagation();
  1644. });
  1645. document.querySelector("#zoom-in").addEventListener("touchstart", e => {
  1646. zoomDirection = -1;
  1647. clearInterval(zoomHandle);
  1648. zoomHandle = setInterval(doZoom, 1000 / 20);
  1649. e.stopPropagation();
  1650. });
  1651. document.querySelector("#zoom-out").addEventListener("touchstart", e => {
  1652. zoomDirection = 1;
  1653. clearInterval(zoomHandle);
  1654. zoomHandle = setInterval(doZoom, 1000 / 20);
  1655. e.stopPropagation();
  1656. });
  1657. document.addEventListener("mouseup", e => {
  1658. clearInterval(zoomHandle);
  1659. zoomHandle = null;
  1660. });
  1661. document.addEventListener("touchend", e => {
  1662. clearInterval(zoomHandle);
  1663. zoomHandle = null;
  1664. });
  1665. document.querySelector("#shrink").addEventListener("mousedown", e => {
  1666. sizeDirection = -1;
  1667. clearInterval(sizeHandle);
  1668. sizeHandle = setInterval(doSize, 1000 / 20);
  1669. e.stopPropagation();
  1670. });
  1671. document.querySelector("#grow").addEventListener("mousedown", e => {
  1672. sizeDirection = 1;
  1673. clearInterval(sizeHandle);
  1674. sizeHandle = setInterval(doSize, 1000 / 20);
  1675. e.stopPropagation();
  1676. });
  1677. document.querySelector("#shrink").addEventListener("touchstart", e => {
  1678. sizeDirection = -1;
  1679. clearInterval(sizeHandle);
  1680. sizeHandle = setInterval(doSize, 1000 / 20);
  1681. e.stopPropagation();
  1682. });
  1683. document.querySelector("#grow").addEventListener("touchstart", e => {
  1684. sizeDirection = 1;
  1685. clearInterval(sizeHandle);
  1686. sizeHandle = setInterval(doSize, 1000 / 20);
  1687. e.stopPropagation();
  1688. });
  1689. document.addEventListener("mouseup", e => {
  1690. clearInterval(sizeHandle);
  1691. sizeHandle = null;
  1692. });
  1693. document.addEventListener("touchend", e => {
  1694. clearInterval(sizeHandle);
  1695. sizeHandle = null;
  1696. });
  1697. document.querySelector("#fit").addEventListener("click", e => {
  1698. const x = parseFloat(selected.dataset.x);
  1699. Object.keys(entities).forEach(id => {
  1700. const element = document.querySelector("#entity-" + id);
  1701. const newX = parseFloat(element.dataset.x) - x + 0.5;
  1702. element.dataset.x = newX;
  1703. });
  1704. const entity = entities[selected.dataset.key];
  1705. const height = math.multiply(entity.views[entity.view].height, 1.1);
  1706. setWorldHeight(config.height, height);
  1707. });
  1708. document.querySelector("#fit").addEventListener("mousedown", e => {
  1709. e.stopPropagation();
  1710. });
  1711. document.querySelector("#fit").addEventListener("touchstart", e => {
  1712. e.stopPropagation();
  1713. });
  1714. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  1715. document.addEventListener("keydown", e => {
  1716. if (e.key == "Delete") {
  1717. if (selected) {
  1718. removeEntity(selected);
  1719. selected = null;
  1720. }
  1721. }
  1722. })
  1723. document.addEventListener("keydown", e => {
  1724. if (e.key == "Shift") {
  1725. shiftHeld = true;
  1726. e.preventDefault();
  1727. } else if (e.key == "Alt") {
  1728. altHeld = true;
  1729. e.preventDefault();
  1730. }
  1731. });
  1732. document.addEventListener("keyup", e => {
  1733. if (e.key == "Shift") {
  1734. shiftHeld = false;
  1735. e.preventDefault();
  1736. } else if (e.key == "Alt") {
  1737. altHeld = false;
  1738. e.preventDefault();
  1739. }
  1740. });
  1741. window.addEventListener("resize", handleResize);
  1742. // TODO: further investigate why the tool initially starts out with wrong
  1743. // values under certain circumstances (seems to be narrow aspect ratios -
  1744. // maybe the menu bar is animating when it shouldn't)
  1745. setTimeout(handleResize, 250);
  1746. setTimeout(handleResize, 500);
  1747. setTimeout(handleResize, 750);
  1748. setTimeout(handleResize, 1000);
  1749. document.querySelector("#menu-permalink").addEventListener("click", e => {
  1750. linkScene();
  1751. });
  1752. document.querySelector("#menu-export").addEventListener("click", e => {
  1753. copyScene();
  1754. });
  1755. document.querySelector("#menu-import").addEventListener("click", e => {
  1756. pasteScene();
  1757. });
  1758. document.querySelector("#menu-save").addEventListener("click", e => {
  1759. saveScene();
  1760. });
  1761. document.querySelector("#menu-load").addEventListener("click", e => {
  1762. loadScene();
  1763. });
  1764. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  1765. loadScene("autosave");
  1766. });
  1767. document.querySelector("#menu-add-image").addEventListener("click", e => {
  1768. document.querySelector("#file-upload-picker").click();
  1769. });
  1770. document.querySelector("#file-upload-picker").addEventListener("change", e => {
  1771. if (e.target.files.length > 0) {
  1772. for (let i=0; i<e.target.files.length; i++) {
  1773. customEntityFromFile(e.target.files[i]);
  1774. }
  1775. }
  1776. })
  1777. document.addEventListener("paste", e => {
  1778. let index = 0;
  1779. let item = null;
  1780. let found = false;
  1781. for (; index < e.clipboardData.items.length; index++) {
  1782. item = e.clipboardData.items[index];
  1783. if (item.type == "image/png") {
  1784. found = true;
  1785. break;
  1786. }
  1787. }
  1788. if (!found) {
  1789. return;
  1790. }
  1791. let url = null;
  1792. const file = item.getAsFile();
  1793. customEntityFromFile(file);
  1794. });
  1795. document.querySelector("#world").addEventListener("dragover", e => {
  1796. e.preventDefault();
  1797. })
  1798. document.querySelector("#world").addEventListener("drop", e => {
  1799. e.preventDefault();
  1800. if (e.dataTransfer.files.length > 0) {
  1801. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  1802. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  1803. let coords = abs2rel({x: e.clientX-entX, y: e.clientY-entY});
  1804. customEntityFromFile(e.dataTransfer.files[0], coords.x, coords.y);
  1805. }
  1806. })
  1807. clearEntityOptions();
  1808. clearViewOptions();
  1809. clearAttribution();
  1810. // we do this last because configuring settings can cause things
  1811. // to happen (e.g. auto-fit)
  1812. prepareSettings(getUserSettings());
  1813. });
  1814. function customEntityFromFile(file, x=0.5, y=0.5) {
  1815. file.arrayBuffer().then(buf => {
  1816. arr = new Uint8Array(buf);
  1817. blob = new Blob([arr], {type: file.type });
  1818. url = window.URL.createObjectURL(blob)
  1819. makeCustomEntity(url, x, y);
  1820. });
  1821. }
  1822. function makeCustomEntity(url, x=0.5, y=0.5) {
  1823. const maker = createEntityMaker(
  1824. {
  1825. name: "Custom Entity"
  1826. },
  1827. {
  1828. custom: {
  1829. attributes: {
  1830. height: {
  1831. name: "Height",
  1832. power: 1,
  1833. type: "length",
  1834. base: math.unit(6, "feet")
  1835. }
  1836. },
  1837. image: {
  1838. source: url
  1839. },
  1840. name: "Image",
  1841. info: {},
  1842. rename: false
  1843. }
  1844. },
  1845. []
  1846. );
  1847. const entity = maker.constructor();
  1848. entity.scale = config.height.toNumber("feet") / 20;
  1849. entity.ephemeral = true;
  1850. displayEntity(entity, "custom", x, y, true, true);
  1851. }
  1852. function prepareEntities() {
  1853. availableEntities["buildings"] = makeBuildings();
  1854. availableEntities["characters"] = makeCharacters();
  1855. availableEntities["cities"] = makeCities();
  1856. availableEntities["fiction"] = makeFiction();
  1857. availableEntities["food"] = makeFood();
  1858. availableEntities["landmarks"] = makeLandmarks();
  1859. availableEntities["naturals"] = makeNaturals();
  1860. availableEntities["objects"] = makeObjects();
  1861. availableEntities["dildos"] = makeDildos();
  1862. availableEntities["pokemon"] = makePokemon();
  1863. availableEntities["species"] = makeSpecies();
  1864. availableEntities["vehicles"] = makeVehicles();
  1865. availableEntities["characters"].sort((x, y) => {
  1866. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  1867. });
  1868. const holder = document.querySelector("#spawners");
  1869. const filterHolder = document.querySelector("#filters");
  1870. const categorySelect = document.createElement("select");
  1871. categorySelect.id = "category-picker";
  1872. const filterSelect = document.createElement("select");
  1873. filterSelect.id = "filter-picker";
  1874. holder.appendChild(categorySelect);
  1875. filterHolder.appendChild(filterSelect);
  1876. const authorSet = new Set();
  1877. const ownerSet = new Set();
  1878. Object.entries(availableEntities).forEach(([category, entityList]) => {
  1879. const select = document.createElement("select");
  1880. select.id = "create-entity-" + category;
  1881. select.classList.add("entity-select");
  1882. for (let i = 0; i < entityList.length; i++) {
  1883. const entity = entityList[i];
  1884. const option = document.createElement("option");
  1885. option.value = i;
  1886. option.innerText = entity.name;
  1887. select.appendChild(option);
  1888. if (entity.nsfw) {
  1889. option.classList.add("nsfw");
  1890. }
  1891. if (entity.authors) {
  1892. entity.authors.forEach(a => {
  1893. authorSet.add(a);
  1894. })
  1895. }
  1896. if (entity.owners) {
  1897. entity.owners.forEach(o => {
  1898. ownerSet.add(o);
  1899. })
  1900. }
  1901. availableEntitiesByName[entity.name] = entity;
  1902. };
  1903. select.addEventListener("change", e => {
  1904. if (select.options[select.selectedIndex].classList.contains("nsfw")) {
  1905. select.classList.add("nsfw");
  1906. } else {
  1907. select.classList.remove("nsfw");
  1908. }
  1909. })
  1910. const button = document.createElement("button");
  1911. button.id = "create-entity-" + category + "-button";
  1912. button.classList.add("entity-button");
  1913. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  1914. button.addEventListener("click", e => {
  1915. const newEntity = entityList[select.value].constructor()
  1916. displayEntity(newEntity, newEntity.defaultView, 0.5, 1, true, true);
  1917. });
  1918. const categoryOption = document.createElement("option");
  1919. categoryOption.value = category
  1920. categoryOption.innerText = category;
  1921. if (category == "characters") {
  1922. categoryOption.selected = true;
  1923. select.classList.add("category-visible");
  1924. button.classList.add("category-visible");
  1925. }
  1926. categorySelect.appendChild(categoryOption);
  1927. holder.appendChild(select);
  1928. holder.appendChild(button);
  1929. });
  1930. const noFilter = document.createElement("option");
  1931. noFilter.innerText = "No Filter";
  1932. noFilter.value = "none";
  1933. const authorFilter = document.createElement("option");
  1934. authorFilter.innerText = "Author";
  1935. authorFilter.value = "author";
  1936. const ownerFilter = document.createElement("option");
  1937. ownerFilter.innerText = "Owner";
  1938. ownerFilter.value = "owner";
  1939. filterSelect.appendChild(noFilter);
  1940. filterSelect.appendChild(authorFilter);
  1941. filterSelect.appendChild(ownerFilter);
  1942. const authorFilterSelect = document.createElement("select");
  1943. authorFilterSelect.classList.add("filter-select");
  1944. authorFilterSelect.id = "filter-author";
  1945. filterHolder.appendChild(authorFilterSelect);
  1946. Array.from(authorSet).map(author => [author, attributionData.people[author].name]).sort((e1, e2) => e1[1].toLowerCase().localeCompare(e2[1].toLowerCase())).forEach(author => {
  1947. const option = document.createElement("option");
  1948. option.innerText = author[1];
  1949. option.value = author[0];
  1950. authorFilterSelect.appendChild(option);
  1951. });
  1952. authorFilterSelect.addEventListener("change", e => {
  1953. updateFilter();
  1954. });
  1955. const ownerFilterSelect = document.createElement("select");
  1956. ownerFilterSelect.classList.add("filter-select");
  1957. ownerFilterSelect.id = "filter-owner";
  1958. filterHolder.appendChild(ownerFilterSelect);
  1959. Array.from(ownerSet).map(owner => [owner, attributionData.people[owner].name]).sort((e1, e2) => e1[1].toLowerCase().localeCompare(e2[1].toLowerCase())).forEach(owner => {
  1960. const option = document.createElement("option");
  1961. option.innerText = owner[1];
  1962. option.value = owner[0];
  1963. ownerFilterSelect.appendChild(option);
  1964. });
  1965. ownerFilterSelect.addEventListener("change", e => {
  1966. updateFilter();
  1967. });
  1968. console.log("Loaded " + Object.keys(availableEntitiesByName).length + " entities");
  1969. categorySelect.addEventListener("input", e => {
  1970. const oldSelect = document.querySelector(".entity-select.category-visible");
  1971. oldSelect.classList.remove("category-visible");
  1972. const oldButton = document.querySelector(".entity-button.category-visible");
  1973. oldButton.classList.remove("category-visible");
  1974. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  1975. newSelect.classList.add("category-visible");
  1976. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  1977. newButton.classList.add("category-visible");
  1978. recomputeFilters();
  1979. updateFilter();
  1980. });
  1981. recomputeFilters();
  1982. filterSelect.addEventListener("input", e => {
  1983. const oldSelect = document.querySelector(".filter-select.category-visible");
  1984. if (oldSelect)
  1985. oldSelect.classList.remove("category-visible");
  1986. const newSelect = document.querySelector("#filter-" + e.target.value);
  1987. if (newSelect)
  1988. newSelect.classList.add("category-visible");
  1989. updateFilter();
  1990. });
  1991. }
  1992. // Only display authors and owners if they appear
  1993. // somewhere in the current entity list
  1994. function recomputeFilters() {
  1995. const category = document.querySelector("#category-picker").value;
  1996. const authorSet = new Set();
  1997. const ownerSet = new Set();
  1998. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  1999. const entity = availableEntities[category][element.value];
  2000. if (entity.authors)
  2001. entity.authors.forEach(author => authorSet.add(author));
  2002. if (entity.owners)
  2003. entity.owners.forEach(owner => ownerSet.add(owner));
  2004. });
  2005. let authorFound = false;
  2006. document.querySelectorAll("#filter-author > option").forEach(element => {
  2007. if (authorSet.has(element.value)) {
  2008. element.classList.remove("filtered");
  2009. authorFound = true;
  2010. } else {
  2011. element.classList.add("filtered");
  2012. }
  2013. })
  2014. let ownerFound = false;
  2015. document.querySelectorAll("#filter-owner > option").forEach(element => {
  2016. if (ownerSet.has(element.value)) {
  2017. element.classList.remove("filtered");
  2018. ownerFound = true;
  2019. } else {
  2020. element.classList.add("filtered");
  2021. }
  2022. })
  2023. if (authorFound) {
  2024. document.querySelector("#filter-picker > option[value='author']").classList.remove("filtered");
  2025. } else {
  2026. document.querySelector("#filter-picker > option[value='author']").classList.add("filtered");
  2027. }
  2028. if (ownerFound) {
  2029. document.querySelector("#filter-picker > option[value='owner']").classList.remove("filtered");
  2030. } else {
  2031. document.querySelector("#filter-picker > option[value='owner']").classList.add("filtered");
  2032. }
  2033. document.querySelector("#filter-picker").value = "none";
  2034. document.querySelector("#filter-picker").dispatchEvent(new Event("input"));
  2035. }
  2036. function updateFilter() {
  2037. const category = document.querySelector("#category-picker").value;
  2038. const type = document.querySelector("#filter-picker").value;
  2039. const filterKeySelect = document.querySelector(".filter-select.category-visible");
  2040. clearFilter();
  2041. if (!filterKeySelect) {
  2042. return;
  2043. }
  2044. const key = filterKeySelect.value;
  2045. let current = document.querySelector(".entity-select.category-visible").value;
  2046. let replace = false;
  2047. let first = null;
  2048. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  2049. let keep = false;
  2050. if (type == "author") {
  2051. const authorList = availableEntities[category][element.value].authors;
  2052. if (authorList && authorList.indexOf(key) >= 0) {
  2053. keep = true;
  2054. }
  2055. }
  2056. if (type == "owner") {
  2057. const ownerList = availableEntities[category][element.value].owners;
  2058. if (ownerList && ownerList.indexOf(key) >= 0) {
  2059. keep = true;
  2060. }
  2061. }
  2062. if (!keep) {
  2063. element.classList.add("filtered");
  2064. if (current == element.value) {
  2065. replace = true;
  2066. }
  2067. } else if (!first) {
  2068. first = element.value;
  2069. }
  2070. });
  2071. if (replace) {
  2072. document.querySelector(".entity-select.category-visible").value = first;
  2073. document.querySelector("#create-entity-" + category).dispatchEvent(new Event("change"));
  2074. }
  2075. }
  2076. function clearFilter() {
  2077. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  2078. element.classList.remove("filtered");
  2079. });
  2080. }
  2081. document.addEventListener("mousemove", (e) => {
  2082. if (clicked) {
  2083. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  2084. clicked.dataset.x = position.x;
  2085. clicked.dataset.y = position.y;
  2086. updateEntityElement(entities[clicked.dataset.key], clicked);
  2087. if (hoveringInDeleteArea(e)) {
  2088. document.querySelector("#menubar").classList.add("hover-delete");
  2089. } else {
  2090. document.querySelector("#menubar").classList.remove("hover-delete");
  2091. }
  2092. }
  2093. });
  2094. document.addEventListener("touchmove", (e) => {
  2095. if (clicked) {
  2096. e.preventDefault();
  2097. let x = e.touches[0].clientX;
  2098. let y = e.touches[0].clientY;
  2099. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  2100. clicked.dataset.x = position.x;
  2101. clicked.dataset.y = position.y;
  2102. updateEntityElement(entities[clicked.dataset.key], clicked);
  2103. // what a hack
  2104. // I should centralize this 'fake event' creation...
  2105. if (hoveringInDeleteArea({ clientY: y })) {
  2106. document.querySelector("#menubar").classList.add("hover-delete");
  2107. } else {
  2108. document.querySelector("#menubar").classList.remove("hover-delete");
  2109. }
  2110. }
  2111. }, { passive: false });
  2112. function checkFitWorld() {
  2113. if (config.autoFit) {
  2114. fitWorld();
  2115. return true;
  2116. }
  2117. return false;
  2118. }
  2119. const fitModes = {
  2120. "max": {
  2121. start: 0,
  2122. binop: Math.max,
  2123. final: (total, count) => total
  2124. },
  2125. "arithmetic mean": {
  2126. start: 0,
  2127. binop: math.add,
  2128. final: (total, count) => total / count
  2129. },
  2130. "geometric mean": {
  2131. start: 1,
  2132. binop: math.multiply,
  2133. final: (total, count) => math.pow(total, 1 / count)
  2134. }
  2135. }
  2136. function fitWorld(manual = false, factor = 1.1) {
  2137. const fitMode = fitModes[config.autoFitMode]
  2138. let max = fitMode.start
  2139. let count = 0;
  2140. Object.entries(entities).forEach(([key, entity]) => {
  2141. const view = entity.view;
  2142. let extra = entity.views[view].image.extra;
  2143. extra = extra === undefined ? 1 : extra;
  2144. max = fitMode.binop(max, math.multiply(extra, entity.views[view].height.toNumber("meter")));
  2145. count += 1;
  2146. });
  2147. max = fitMode.final(max, count)
  2148. max = math.unit(max, "meter")
  2149. if (manual)
  2150. altHeld = true;
  2151. setWorldHeight(config.height, math.multiply(max, factor));
  2152. if (manual)
  2153. altHeld = false;
  2154. }
  2155. // TODO why am I doing this
  2156. function updateWorldHeight() {
  2157. const unit = document.querySelector("#options-height-unit").value;
  2158. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  2159. const oldHeight = config.height;
  2160. setWorldHeight(oldHeight, math.unit(value, unit));
  2161. }
  2162. function setWorldHeight(oldHeight, newHeight) {
  2163. worldSizeDirty = true;
  2164. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  2165. const unit = document.querySelector("#options-height-unit").value;
  2166. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  2167. Object.entries(entities).forEach(([key, entity]) => {
  2168. const element = document.querySelector("#entity-" + key);
  2169. let newPosition;
  2170. if (!altHeld) {
  2171. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  2172. } else {
  2173. newPosition = { x: element.dataset.x, y: element.dataset.y };
  2174. }
  2175. element.dataset.x = newPosition.x;
  2176. element.dataset.y = newPosition.y;
  2177. });
  2178. updateSizes();
  2179. }
  2180. function loadScene(name = "default") {
  2181. try {
  2182. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  2183. if (data === null) {
  2184. return false;
  2185. }
  2186. importScene(data);
  2187. return true;
  2188. } catch (err) {
  2189. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  2190. console.error(err);
  2191. return false;
  2192. }
  2193. }
  2194. function saveScene(name = "default") {
  2195. try {
  2196. const string = JSON.stringify(exportScene());
  2197. localStorage.setItem("macrovision-save-" + name, string);
  2198. } catch (err) {
  2199. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  2200. console.error(err);
  2201. }
  2202. }
  2203. function deleteScene(name = "default") {
  2204. try {
  2205. localStorage.removeItem("macrovision-save-" + name)
  2206. } catch (err) {
  2207. console.error(err);
  2208. }
  2209. }
  2210. function exportScene() {
  2211. const results = {};
  2212. results.entities = [];
  2213. Object.entries(entities).filter(([key, entity]) => entity.ephemeral !== true).forEach(([key, entity]) => {
  2214. const element = document.querySelector("#entity-" + key);
  2215. results.entities.push({
  2216. name: entity.identifier,
  2217. scale: entity.scale,
  2218. view: entity.view,
  2219. x: element.dataset.x,
  2220. y: element.dataset.y
  2221. });
  2222. });
  2223. const unit = document.querySelector("#options-height-unit").value;
  2224. results.world = {
  2225. height: config.height.toNumber(unit),
  2226. unit: unit
  2227. }
  2228. results.canvasWidth = canvasWidth;
  2229. return results;
  2230. }
  2231. // btoa doesn't like anything that isn't ASCII
  2232. // great
  2233. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  2234. // for providing an alternative
  2235. function b64EncodeUnicode(str) {
  2236. // first we use encodeURIComponent to get percent-encoded UTF-8,
  2237. // then we convert the percent encodings into raw bytes which
  2238. // can be fed into btoa.
  2239. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  2240. function toSolidBytes(match, p1) {
  2241. return String.fromCharCode('0x' + p1);
  2242. }));
  2243. }
  2244. function b64DecodeUnicode(str) {
  2245. // Going backwards: from bytestream, to percent-encoding, to original string.
  2246. return decodeURIComponent(atob(str).split('').map(function (c) {
  2247. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  2248. }).join(''));
  2249. }
  2250. function linkScene() {
  2251. loc = new URL(window.location);
  2252. window.location = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  2253. }
  2254. function copyScene() {
  2255. const results = exportScene();
  2256. navigator.clipboard.writeText(JSON.stringify(results));
  2257. }
  2258. function pasteScene() {
  2259. try {
  2260. navigator.clipboard.readText().then(text => {
  2261. const data = JSON.parse(text);
  2262. if (data.entities === undefined) {
  2263. return;
  2264. }
  2265. if (data.world === undefined) {
  2266. return;
  2267. }
  2268. importScene(data);
  2269. }).catch(err => alert(err));
  2270. } catch (err) {
  2271. console.error(err);
  2272. // probably wasn't valid data
  2273. }
  2274. }
  2275. // TODO - don't just search through every single entity
  2276. // probably just have a way to do lookups directly
  2277. function findEntity(name) {
  2278. return availableEntitiesByName[name];
  2279. }
  2280. function importScene(data) {
  2281. removeAllEntities();
  2282. data.entities.forEach(entityInfo => {
  2283. const entity = findEntity(entityInfo.name).constructor();
  2284. entity.scale = entityInfo.scale
  2285. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  2286. });
  2287. config.height = math.unit(data.world.height, data.world.unit);
  2288. document.querySelector("#options-height-unit").value = data.world.unit;
  2289. if (data.canvasWidth) {
  2290. doHorizReposition(data.canvasWidth / canvasWidth);
  2291. }
  2292. updateSizes();
  2293. }
  2294. function renderToCanvas() {
  2295. const ctx = document.querySelector("#display").getContext("2d");
  2296. Object.entries(entities).sort((ent1, ent2) => {
  2297. z1 = document.querySelector("#entity-" + ent1[0]).style.zIndex;
  2298. z2 = document.querySelector("#entity-" + ent2[0]).style.zIndex;
  2299. return z1 - z2;
  2300. }).forEach(([id, entity]) => {
  2301. element = document.querySelector("#entity-" + id);
  2302. img = element.querySelector("img");
  2303. let x = parseFloat(element.dataset.x);
  2304. let y = parseFloat(element.dataset.y);
  2305. let coords = rel2abs({x: x, y: y});
  2306. let offset = img.style.getPropertyValue("--offset");
  2307. offset = parseFloat(offset.substring(0, offset.length-1))
  2308. x = coords.x - img.getBoundingClientRect().width/2;
  2309. y = coords.y - img.getBoundingClientRect().height * (-offset/100);
  2310. let xSize = img.getBoundingClientRect().width;
  2311. let ySize = img.getBoundingClientRect().height;
  2312. ctx.drawImage(img, x, y, xSize, ySize);
  2313. });
  2314. }
  2315. function exportCanvas(callback) {
  2316. /** @type {CanvasRenderingContext2D} */
  2317. const ctx = document.querySelector("#display").getContext("2d");
  2318. const blob = ctx.canvas.toBlob(callback);
  2319. }
  2320. function generateScreenshot(callback) {
  2321. renderToCanvas();
  2322. /** @type {CanvasRenderingContext2D} */
  2323. const ctx = document.querySelector("#display").getContext("2d");
  2324. ctx.fillStyle = "#555";
  2325. ctx.font = "normal normal lighter 16pt coda";
  2326. ctx.fillText("macrovision.crux.sexy", 10, 25);
  2327. exportCanvas(blob => {
  2328. callback(blob);
  2329. });
  2330. }
  2331. function copyScreenshot() {
  2332. generateScreenshot(blob => {
  2333. navigator.clipboard.write([
  2334. new ClipboardItem({
  2335. "image/png": blob
  2336. })
  2337. ]);
  2338. });
  2339. drawScale(false);
  2340. }
  2341. function saveScreenshot() {
  2342. generateScreenshot(blob => {
  2343. const a = document.createElement("a");
  2344. a.href = URL.createObjectURL(blob);
  2345. a.setAttribute("download", "macrovision.png");
  2346. a.click();
  2347. });
  2348. drawScale(false);
  2349. }
  2350. const rateLimits = {};
  2351. function toast(msg) {
  2352. let div = document.createElement("div");
  2353. div.innerHTML = msg;
  2354. div.classList.add("toast");
  2355. document.body.appendChild(div);
  2356. setTimeout(() => {
  2357. document.body.removeChild(div);
  2358. }, 5000)
  2359. }
  2360. function toastRateLimit(msg, key, delay) {
  2361. if (!rateLimits[key]) {
  2362. toast(msg);
  2363. rateLimits[key] = setTimeout(() => {
  2364. delete rateLimits[key]
  2365. }, delay);
  2366. }
  2367. }