// ==UserScript== // @name Blue Marble // @namespace https://github.com/SwingTheVine/ // @version 0.86.5 // @description A userscript to automate and/or enhance the user experience on Wplace.live. Make sure to comply with the site's Terms of Service, and rules! This script is not affiliated with Wplace.live in any way, use at your own risk. This script is not affiliated with TamperMonkey. The author of this userscript is not responsible for any damages, issues, loss of data, or punishment that may occur as a result of using this script. This script is provided "as is" under the MPL-2.0 license. The "Blue Marble" icon is licensed under CC0 1.0 Universal (CC0 1.0) Public Domain Dedication. The image is owned by NASA. // @author SwingTheVine // @author TWY // @license MPL-2.0 // @supportURL https://discord.gg/tpeBPy46hf // @homepageURL https://bluemarble.camilledaguin.fr/ // @icon https://raw.githubusercontent.com/t-wy/Wplace-BlueMarble-Userscripts/2cb96308ea5bf462b18679629d9455baa517eb5b/dist/assets/Favicon.png // @updateURL https://raw.githubusercontent.com/t-wy/Wplace-BlueMarble-Userscripts/custom-improve/dist/BlueMarble.user.js // @downloadURL https://raw.githubusercontent.com/t-wy/Wplace-BlueMarble-Userscripts/custom-improve/dist/BlueMarble.user.js // @match https://wplace.live/* // @run-at document-start // @grant GM.addStyle // @grant GM.setValue // @grant GM.getValue // ==/UserScript== // Wplace --> https://wplace.live // License --> https://www.mozilla.org/en-US/MPL/2.0/ (()=>{var t,e,n=t=>{throw TypeError(t)},i=(t,e,i)=>e.has(t)?n("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),o=(t,e,i)=>(((t,e)=>{e.has(t)||n("Cannot access private method")})(t,e),i);function s(...t){(0,console.log)(...t)}function r(t){let e="";for(let n=0;n{n.toBlob(t=>{t?i(t):o(new Error("toBlob() returned null"))},t,e)})},n}),Array.prototype.extend||(Array.prototype.extend=function(t){t.forEach(t=>this.push(t))}),t=new WeakSet,e=function(t,e={},n={}){const i=document.createElement(t);this.o?(this.u?.appendChild(i),this.h.push(this.u),this.u=i):(this.o=i,this.u=i);for(const[t,n]of Object.entries(e))i[t]=n;for(const[t,e]of Object.entries(n))i[t]=e;return i};var c=[{id:0,premium:!1,name:"Transparent",rgb:[0,0,0]},{id:1,premium:!1,name:"Black",rgb:[0,0,0]},{id:2,premium:!1,name:"Dark Gray",rgb:[60,60,60]},{id:3,premium:!1,name:"Gray",rgb:[120,120,120]},{id:4,premium:!1,name:"Light Gray",rgb:[210,210,210]},{id:5,premium:!1,name:"White",rgb:[255,255,255]},{id:6,premium:!1,name:"Deep Red",rgb:[96,0,24]},{id:7,premium:!1,name:"Red",rgb:[237,28,36]},{id:8,premium:!1,name:"Orange",rgb:[255,127,39]},{id:9,premium:!1,name:"Gold",rgb:[246,170,9]},{id:10,premium:!1,name:"Yellow",rgb:[249,221,59]},{id:11,premium:!1,name:"Light Yellow",rgb:[255,250,188]},{id:12,premium:!1,name:"Dark Green",rgb:[14,185,104]},{id:13,premium:!1,name:"Green",rgb:[19,230,123]},{id:14,premium:!1,name:"Light Green",rgb:[135,255,94]},{id:15,premium:!1,name:"Dark Teal",rgb:[12,129,110]},{id:16,premium:!1,name:"Teal",rgb:[16,174,166]},{id:17,premium:!1,name:"Light Teal",rgb:[19,225,190]},{id:18,premium:!1,name:"Dark Blue",rgb:[40,80,158]},{id:19,premium:!1,name:"Blue",rgb:[64,147,228]},{id:20,premium:!1,name:"Cyan",rgb:[96,247,242]},{id:21,premium:!1,name:"Indigo",rgb:[107,80,246]},{id:22,premium:!1,name:"Light Indigo",rgb:[153,177,251]},{id:23,premium:!1,name:"Dark Purple",rgb:[120,12,153]},{id:24,premium:!1,name:"Purple",rgb:[170,56,185]},{id:25,premium:!1,name:"Light Purple",rgb:[224,159,249]},{id:26,premium:!1,name:"Dark Pink",rgb:[203,0,122]},{id:27,premium:!1,name:"Pink",rgb:[236,31,128]},{id:28,premium:!1,name:"Light Pink",rgb:[243,141,169]},{id:29,premium:!1,name:"Dark Brown",rgb:[104,70,52]},{id:30,premium:!1,name:"Brown",rgb:[149,104,42]},{id:31,premium:!1,name:"Beige",rgb:[248,178,119]},{id:32,premium:!0,name:"Medium Gray",rgb:[170,170,170]},{id:33,premium:!0,name:"Dark Red",rgb:[165,14,30]},{id:34,premium:!0,name:"Light Red",rgb:[250,128,114]},{id:35,premium:!0,name:"Dark Orange",rgb:[228,92,26]},{id:36,premium:!0,name:"Light Tan",rgb:[214,181,148]},{id:37,premium:!0,name:"Dark Goldenrod",rgb:[156,132,49]},{id:38,premium:!0,name:"Goldenrod",rgb:[197,173,49]},{id:39,premium:!0,name:"Light Goldenrod",rgb:[232,212,95]},{id:40,premium:!0,name:"Dark Olive",rgb:[74,107,58]},{id:41,premium:!0,name:"Olive",rgb:[90,148,74]},{id:42,premium:!0,name:"Light Olive",rgb:[132,197,115]},{id:43,premium:!0,name:"Dark Cyan",rgb:[15,121,159]},{id:44,premium:!0,name:"Light Cyan",rgb:[187,250,242]},{id:45,premium:!0,name:"Light Blue",rgb:[125,199,255]},{id:46,premium:!0,name:"Dark Indigo",rgb:[77,49,184]},{id:47,premium:!0,name:"Dark Slate Blue",rgb:[74,66,132]},{id:48,premium:!0,name:"Slate Blue",rgb:[122,113,196]},{id:49,premium:!0,name:"Light Slate Blue",rgb:[181,174,241]},{id:50,premium:!0,name:"Light Brown",rgb:[219,164,99]},{id:51,premium:!0,name:"Dark Beige",rgb:[209,128,81]},{id:52,premium:!0,name:"Light Beige",rgb:[255,197,165]},{id:53,premium:!0,name:"Dark Peach",rgb:[155,82,73]},{id:54,premium:!0,name:"Peach",rgb:[209,128,120]},{id:55,premium:!0,name:"Light Peach",rgb:[250,182,164]},{id:56,premium:!0,name:"Dark Tan",rgb:[123,99,82]},{id:57,premium:!0,name:"Tan",rgb:[156,132,107]},{id:58,premium:!0,name:"Dark Slate",rgb:[51,57,65]},{id:59,premium:!0,name:"Slate",rgb:[109,117,141]},{id:60,premium:!0,name:"Light Slate",rgb:[179,185,209]},{id:61,premium:!0,name:"Dark Stone",rgb:[109,100,63]},{id:62,premium:!0,name:"Stone",rgb:[148,140,107]},{id:63,premium:!0,name:"Light Stone",rgb:[205,197,158]}],l=new Map(c.filter(t=>Array.isArray(t?.rgb)).map(t=>[`${t.rgb[0]},${t.rgb[1]},${t.rgb[2]}`,{id:t.id,premium:!!t.premium,name:t.name}]));try{const t=c.find(t=>"transparent"===(t?.name||"").toLowerCase());t&&Array.isArray(t.rgb)&&l.set("222,250,206",{id:t.id,premium:!!t.premium,name:t.name})}catch(t){}try{l.set("other",{id:"other",premium:!1,name:"Other"})}catch(t){}function d(t){t.width=0,t.height=0,t.constructor===HTMLCanvasElement&&t.remove(),t=null}function m(){return[[document.querySelector("#bm-11")?.value||"",document.querySelector("#bm-12")?.value||""],[document.querySelector("#bm-13")?.value||"",document.querySelector("#bm-14")?.value||""]]}function u(){const t=m();return[[Number(t[0][0]),Number(t[0][1])],[Number(t[1][0]),Number(t[1][1])]]}function h(){const t=m(),e=u();return!(t.some(t=>t.some(t=>""===t))||e.some(t=>t.some(t=>isNaN(t)||t<0))||e[0][0]>2048||e[0][1]>2048||e[1][0]>1e3||e[1][1]>1e3)}var p={total:([t,e,n])=>n,painted:([t,e,n])=>e,remaining:([t,e,n])=>n-e,"painted%":([t,e,n])=>e/(0===n?1:n),hue:([t,e,n])=>{if("other"===t)return 361;if("#deface"===t)return-1;const[i,o,s]=t.split(",").map(Number),r=Math.max(i,o,s),a=r-Math.min(i,o,s);return 0===a?361+i:r===i?((o-s)/a+6)%6*60:r===o?60*((s-i)/a+2):60*((i-o)/a+4)},luminance:([t,e,n])=>{if("other"===t)return 2;if("#deface"===t)return 0;const[i,o,s]=t.split(",").map(Number);return(.2126*i+.7152*o+.0722*s)/255}};function b(t){if(navigator.clipboard&&"function"==typeof navigator.clipboard.writeText)navigator.clipboard.writeText(t);else{var e=document.createElement("textArea");e.innerHTML=t,document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e)}}function f(t,e){const n=[t[0][0]%2048*1e3+t[1][0]%1e3,e[0][0]%2048*1e3+e[1][0]%1e3],i=[t[0][1]%2048*1e3+t[1][1]%1e3,e[0][1]%2048*1e3+e[1][1]%1e3],o=Math.min(i[0],i[1]),s=Math.abs(i[0]-i[1])+1,r=Math.abs(n[0]-n[1])+1,a=2*r>2048e3;return[[a?Math.max(n[0],n[1]):Math.min(n[0],n[1]),o],[a?2048e3-r+2:r,s]]}function g(t,e){let n=new OffscreenCanvas(t,e);const i=n.getContext("2d");i.fillRect(t-1,e-1,1,1);const o=0!==i.getImageData(t-1,e-1,1,1).data[3];return d(n),n=null,o}function v(t,e){const n="https://backend.wplace.live/files/s0/tiles/"+t%2048+"/"+e+".png";return new Promise((t,e)=>{const i=new Image;i.crossOrigin="anonymous",i.onload=function(){t(i)},i.onerror=function(t){e(t)},i.src=n})}function w(){const t=Number(localStorage.getItem("selected-color"))??0;return isNaN(t)||!isFinite(t)||t<0||t>=64?0:t}var y=class{constructor({displayName:t="My template",p:e=0,C:n="",url:i="",file:o=null,coords:s=null,$:r=null,M:a=null,tileSize:c=1e3}={}){this.displayName=t,this.p=e,this.C=n,this.url=i,this.file=o,this.coords=s,this.$=r,this.M=a,this.tileSize=c,this.enabled=!0,this.k=0,this.S=0,this.T=0,this.O={},this.D=new Set,this.L=null,this.A=Date.now().toString(),this.shreadSize=null}N(t,e,n){const i=n-1>>1;return(t%n==i||e%n==i)&&t%n>=i-1&&t%n<=i+1&&e%n>=i-1&&e%n<=i+1}B(t){const e=[];for(let n=0;nbutton");if(null===t)return!1;if(void 0!==t.__click)H="object"==typeof t.__click&&void 0!==t.__click[3]&&void 0!==t.__click[3].v&&void 0!==t.__click[3].v.addSource||void 0!==document.head.__bmmap;else{const t=()=>{const t=document.currentScript;if(document.head.__bmmap)t.setAttribute("bm-17","true");else try{void 0!==document.querySelector(".right-3>button").__click[3].v.addSource?t.setAttribute("bm-17","true"):t.setAttribute("bm-17","false")}catch(e){e instanceof TypeError&&t.setAttribute("bm-17","false")}},e=document.createElement("script");e.textContent=`(${t})();`,document.documentElement?.appendChild(e);const n="true"===e.getAttribute("bm-17");e.remove(),H=n}return H&&q.forEach(t=>t()),H}function C(t,...e){if(!x())return void z(()=>C(t,...e));const n=document.querySelector(".right-3>button");if(document.head.__bmmap){const n=document.head.__bmmap;return t(n,...e)}if(null!==n){if(n.__click){const i=n.__click[3].v;return t(i,...e)}{const n=()=>document.head.__bmmap||document.querySelector(".right-3>button").__click[3].v,i=t=>{document.currentScript.setAttribute("bm-17",JSON.stringify(t??null))},o=e.map(t=>JSON.stringify(t)).join(","),s=document.createElement("script");s.textContent=`(${i})((${t})((${n})(), ${o}));`,document.documentElement?.appendChild(s);const r=JSON.parse(s.getAttribute("bm-17"));return s.remove(),r}}throw new Error('Could not find the "My location" button.')}var $={};function M(t,e,n,i,o){const s=e.split(",").map(Number),[r,a]=n,c=A([s[0],s[1]],[s[2],s[3]],!1),l=A([s[0],s[1]],[s[2]+r,s[3]+a],!1);$[o]||($[o]={});const d=`bm-${o}-${e}-${t}`;return $[o][d]=[c,l],C(async(t,e,n,i,o,s,r,a,c)=>{document.head.__bmCanvas=c;const l=document.createElement("img");l.src=o,await new Promise(t=>l.addEventListener("load",()=>t(l)));const d=document.getElementById(e);d&&(d.width=0,d.height=0,d.remove());const m=document.createElement("canvas");m.id=e,m.style.display="none",document.body.appendChild(m),m.width=l.naturalWidth,m.height=l.naturalHeight,m.getContext("2d").drawImage(l,0,0),URL.revokeObjectURL(o),t.getLayer(e)&&t.removeLayer(e),t.getSource(e)&&t.removeSource(e),t.addSource(e,{type:"canvas",canvas:e,coordinates:[[s[1],s[0]],[r[1],s[0]],[r[1],r[0]],[s[1],r[0]]]}),t.addLayer({id:e,source:e,type:"raster",paint:{"raster-resampling":"nearest","raster-opacity":1}});const u=t.getLayersOrder(),h="pixel-hover",p=u.find(t=>"overlay"===a&&t.startsWith("bm-18")||t===h+"-ghost");if(t.moveLayer(e,p),t.getLayer(h+"-ghost")){const e=t.getLayersOrder();e&&e.length&&e[e.length-1]!==h+"-ghost"&&t.moveLayer(h+"-ghost")}else t.addLayer({id:h+"-ghost",type:"raster",source:h,paint:{"raster-resampling":"nearest","raster-opacity":.4}})},d,e,n,URL.createObjectURL(i),c,l,o,$)}function k(t=null,e=null){const n=e?"-"+e:"",i=[];return(t?[t]:["overlay","error"]).forEach(t=>{Object.keys($[t]??{}).forEach(e=>{e.endsWith(n)&&(delete $[t][e],i.push(e))})}),C((t,e,n)=>{document.head.__bmCanvas=n,e.forEach(e=>{t.getLayer(e)&&t.removeLayer(e),t.getSource(e)&&t.removeSource(e);const n=document.getElementById(e);n&&(n.width=0,n.height=0,n.remove())})},i,$)}function S(){try{return C(t=>t.refreshTiles("pixel-art-layer"))}catch(t){}}var T={liberty:["Liberty (Default)",!1],bright:["Bright",!1],positron:["Positron",!1],dark:["Dark",!0],fiord:["Fiord (Halloween)",!0]};function O(t){if(!T[t])return;const e=T[t][1];return document.documentElement.dataset.theme=e?"dark":"",C((t,e,n)=>{document.head.__bmCanvas=n;const i="pixel-art-layer",o="pixel-hover";let s=t.getSource(o);const r=async()=>{if(t.getSource(i)||t.addSource(i,{type:"raster",tiles:["https://backend.wplace.live/files/s0/tiles/{x}/{y}.png"],minzoom:11,maxzoom:11,tileSize:window.innerWidth>640?550:400}),t.getLayer(i)||t.addLayer({id:i,type:"raster",source:i,paint:{"raster-resampling":"nearest","raster-opacity":1}}),!t.getSource(o))if(s)t.addSource(o,{type:"canvas",canvas:s.canvas,coordinates:s.coordinates});else{const e=document.createElement("canvas"),n=document.createElement("img");n.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAAAAACoWZBhAAAAAXNSR0IArs4c6QAAACpJREFUeNpj+AsEZ86ASIa/DAwMZ84ACRDzDBigMs/AARITq1oUwxBWAADaREUdDMswKwAAAABJRU5ErkJggg==",await new Promise(t=>n.addEventListener("load",()=>t(n))),e.width=n.naturalWidth,e.height=n.naturalHeight,e.getContext("2d").drawImage(n,0,0);const i=1e-5;s={type:"canvas",canvas:e,coordinates:[[0,0],[i,0],[i,-i],[0,-i]]},t.addSource(o,s)}if(t.getLayer(o)){let e="bm";const n=t.getLayersOrder(),i=n.find(t=>t.startsWith(e+"-overlay-")||t.startsWith(e+"-error-")||t===o+"-ghost");n.indexOf(o)+1!==(void 0===i?n.length:n.indexOf(i))&&t.moveLayer(o,i)}else t.addLayer({id:o,type:"raster",source:o,paint:{"raster-resampling":"nearest","raster-opacity":.4}});if(t.getLayer(o+"-ghost")){const e=t.getLayersOrder();e&&e.length&&e[e.length-1]!==o+"-ghost"&&t.moveLayer(o+"-ghost")}else t.addLayer({id:o+"-ghost",type:"raster",source:o,paint:{"raster-resampling":"nearest","raster-opacity":.4}});const e=document.head.__bmCanvas;e&&["overlay","error"].forEach(n=>{if(e[n]){let i="bm";const s=t.getLayersOrder().find(t=>"overlay"===n&&t.startsWith(i+"-error-")||t===o+"-ghost");Object.entries(e[n]).forEach(([e,[n,i]])=>{t.getSource(e)||t.addSource(e,{type:"canvas",canvas:e,coordinates:[[n[1],n[0]],[i[1],n[0]],[i[1],i[0]],[n[1],i[0]]]}),t.getLayer(e)||(t.addLayer({id:e,type:"raster",source:e,paint:{"raster-resampling":"nearest","raster-opacity":1}}),t.moveLayer(e,s))})}})},a="restoreLayers";if((t._listeners.styledata??[]).find(t=>t.name===a)||(r.name=a,t.on("styledata",r)),!document.querySelector(".flex>.btn.btn-square.relative.shadow-md")){const t=document.querySelector(".gap-1+.btn-circle");t&&t.click()}return t.setStyle("https://maps.wplace.live/styles/"+e,{}),null},t,$)}var D={data:null};async function L(t,e){if(x()){if(C((t,e,n,i)=>{t[i]({center:[n,e],zoom:16})},t,e,"jumpTo"),document.querySelector(".flex>.btn.btn-square.relative.shadow-md")){const t=document.querySelector("canvas.maplibregl-canvas"),e=new MouseEvent("click",{bubbles:!0,cancelable:!0,clientX:t.offsetWidth/2,clientY:t.offsetHeight/2,button:0});t.dispatchEvent(e)}}else{const n=document.querySelector(".mb-2>.btn-ghost");if(void 0!==n)D.data=N(t,e,!1),n.click();else{const n=`https://wplace.live/?lat=${t}&lng=${e}&zoom=16`;window.location.href=n}}}async function E(t,e){const n=A(t,e);await L(n[0],n[1])}function A(t,e,n=!0){const i=n?.5:0,o=(1e3*t[0]+e[0]+i)/2048e3,s=1-(1e3*t[1]+e[1]+i)/2048e3;return[360*Math.atan(Math.exp((2*s-1)*Math.PI))/Math.PI-90,360*o-180]}function N(t,e,n=!0){const i=(e+180)/360*2048*1e3,o=2048*(1-(Math.log(Math.tan((90+t)*Math.PI/360))/Math.PI+1)/2)*1e3,s=n?[Math.floor(i%1e3),Math.floor(o%1e3)]:[i%1e3,o%1e3];return[[Math.floor(i/1e3),Math.floor(o/1e3)],s]}var B,I,j,P,R,F,U,H=!1,q=[];function z(t){if(H)return t();q.push(t)}B=new WeakSet,I=async function(t){const e=t.templates,n=this.F();if(Object.keys(e).length>0){for(const t in e){const i=t,o=e[t],s=o.coords.split(",").map(Number);if(e.hasOwnProperty(t)){const t=i.split(" "),r=Number(t?.[0]),c=t?.[1]||"0",l=o.name||`Template ${r||""}`,m=o.tiles,u={},h={};let p=0;const b=new Map;for(const t in m)if(m.hasOwnProperty(t)){const o=a(m[t]),s=new Blob([o],{type:"image/png"}),r=await createImageBitmap(s);u[t]=n?null:r,h[t]=o;try{const t=r.width,n=r.height;let o=new OffscreenCanvas(t,n);const s=o.getContext("2d",{willReadFrequently:!0});s.imageSmoothingEnabled=!1,s.clearRect(0,0,t,n),s.drawImage(r,0,0);const a=s.getImageData(0,0,t,n).data;d(o),o=null;for(let o=this.U;othis.q&&(this.q=f.p),f.shreadSize=o.shreadSize??this.H,f.$=u,f.M=h,f.S=p,f.enabled=o.enabled??!0;const g={};for(const[t,e]of b.entries())g[t]={count:e,enabled:!0};f.O=g;try{Object.keys(u).forEach(t=>{f.D?.add(t.split(",").slice(0,2).join(","))})}catch(t){}try{const t=e?.[i]?.palette;if(t)for(const[e,n]of Object.entries(t))f.O[e]?f.O[e].enabled=!!n?.enabled:f.O[e]={count:n?.count||0,enabled:!!n?.enabled}}catch(t){}f.L=i,this.G.push(f)}}try{window.postMessage({source:"blue-marble",J:"bm-o"},"*")}catch(t){}try{window.postMessage({source:"blue-marble",J:"bm-d"},"*")}catch(t){}this.Y()}},j=new WeakSet,P=function(){o(this,j,R).call(this),this.X=setInterval(()=>{o(this,j,R).call(this)},1e3)},R=function(){if(null===this.charges)return void o(this,j,F).call(this);const t=Math.floor(this.W()),e=this.charges.max,n=(new Intl.NumberFormat).format(t),i=(new Intl.NumberFormat).format(e),s=document.getElementById("bm-V"),r=s?.querySelector('[data-role="countdown"]'),a=s?.querySelector('[data-role="charge-count"]');s&&r&&a&&(r.textContent=this._(),a.textContent=`(${n} / ${i})`)},F=function(){const t=document.querySelector(".flex>.btn.btn-square.relative.shadow-md"),e=document.querySelector(".relative>.dropdown>.dropdown-content>section>button.btn");if(void 0!==t&&void 0!==e){const t=Date.now();(null===this.V||t-this.V>1e4)&&(fetch("https://backend.wplace.live/me",{credentials:"include"}),this.V=t)}},U=function(t,e){if(null===t)return;const n=Math.ceil(Math.pow(Math.floor(t.level)*Math.pow(30,.65),1/.65)-t.pixelsPainted);t.id||t.id,this.Z.K=t.id,this.charges=t.charges,this.tt=e,this.Z.et(t.extraColorsBitmap??0);const i=document.getElementById("bm-10");i&&(i.textContent=t.name);const o=document.getElementById("bm-N");o&&(o.textContent=(new Intl.NumberFormat).format(t.droplets));const s=document.getElementById("bm-E"),r=document.getElementById("bm-e");s&&r&&(s.textContent=(new Intl.NumberFormat).format(n),r.textContent=1==n?"":"s");const a=document.getElementById("bm-F");a&&(a.textContent=Math.floor(t.level)+1)};var G=GM_info.script.name.toString(),J=GM_info.script.version.toString();!function(t){const e=document.createElement("script");e.setAttribute("bm-1d",G),e.setAttribute("bm-19","color: cornflowerblue;"),e.textContent=`(${t})();`,document.documentElement?.appendChild(e),e.remove()}(()=>{const t=document.currentScript,e=t?.getAttribute("bm-1d")||"Blue Marble",n=t?.getAttribute("bm-19")||"",i=new Map;window.addEventListener("message",t=>{const{source:o,endpoint:s,blobID:r,blobData:a,blink:c}=t.data;if(Date.now(),"blue-marble"==o&&r&&a&&!s){const t=i.get(r);"function"==typeof t?t(a):function(...t){(0,console.warn)(...t)}(`%c${e}%c: Attempted to retrieve a blob (%s) from queue, but the blobID was not a function! Skipping...`,n,"",r),i.delete(r)}});const o=window.fetch;window.fetch=async function(...t){const e=Date.now(),n=await o.apply(this,t),s=n.clone(),r=(t[0]instanceof Request?t[0]?.url:t[0])||"ignore",a=s.headers.get("content-type")||"";if(a.includes("application/json")){if(r.endsWith("/tile/random"))return new Promise(t=>{const n=crypto.randomUUID();i.set(n,e=>{t(new Response(e,{headers:s.headers,status:s.status,statusText:s.statusText}))}),s.json().then(t=>{window.postMessage({source:"blue-marble",endpoint:r,blobID:n,jsonData:t,blink:e},"*")}).catch(t=>{})});s.json().then(t=>{window.postMessage({source:"blue-marble",endpoint:r,jsonData:t,blink:e},"*")}).catch(t=>{})}else if(a.includes("image/")&&!r.includes("openfreemap")&&!r.includes("maps")){const t=await s.blob();window.postMessage({source:"blue-marble",endpoint:r,lastModified:s.headers.get("Last-Modified"),blobData:t,blink:e})}return n};const s={values:Map.prototype.values};Map.prototype.values=function(){const t=s.values.call(this);return Array.from(t).forEach(t=>{t&&t.maps instanceof Set&&Array.from(t.maps).forEach(t=>{t&&t.flyTo&&(document.head.__bmmap=t,function(){for(const t in s)Map.prototype[t]=s[t]}())})}),t}}),GM.addStyle("#bm-16{position:fixed;background-color:#153063cc;color:#fff;padding:10px;border-radius:8px;z-index:9000;transition:all .3s ease,transform 0s;max-width:300px;width:auto;will-change:transform;backface-visibility:hidden;-webkit-backface-visibility:hidden;transform-style:preserve-3d;-webkit-transform-style:preserve-3d}#bm-w,#bm-16 hr,#bm-q,#bm-9{transition:opacity .2s ease,height .2s ease}div#bm-16{font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Monaco,DejaVu Sans,sans-serif;letter-spacing:.05em}#bm-15{margin-bottom:.5em;background:url('data:image/svg+xml;utf8,') repeat;cursor:grab;width:100%;height:1em}#bm-15.dragging{cursor:grabbing}#bm-16:has(#bm-15.dragging){pointer-events:none;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none}#bm-15.dragging{pointer-events:auto}#bm-G{margin-bottom:.5em}#bm-G[style*=\"text-align: center\"]{display:flex;flex-direction:column;align-items:center;justify-content:center}#bm-16[style*=\"padding: 5px\"]{width:auto!important;max-width:300px;min-width:200px}#bm-16 img{display:inline-block;height:2.5em;margin-right:1ch;vertical-align:middle;transition:opacity .2s ease}#bm-G[style*=\"text-align: center\"] img{display:block;margin:0 auto}#bm-15{transition:margin-bottom .2s ease}#bm-16 h1{display:inline-block;font-size:x-large;font-weight:700;vertical-align:middle}#bm-q input[type=checkbox]{vertical-align:middle;flex:0 0 auto}#bm-q label>input[type=checkbox]{margin-right:.5ch}#bm-q label{margin-right:.5ch}.bm-1e{border:white 1px solid;height:1.5em;width:1.5em;margin-top:2px;text-align:center;line-height:1em;padding:0!important}#bm-P{vertical-align:middle}#bm-P svg{width:50%;margin:0 auto;fill:#111}div:has(>#bm-C){display:flex;gap:.5ch}#bm-button-favorite svg,#bm-button-template svg{height:1em;margin:2px auto 0;text-align:center;line-height:1em;vertical-align:bottom}#bm-H input[type=number]{appearance:auto;-moz-appearance:textfield;width:5.5ch;margin-left:1ch;background-color:#0003;padding:0 .5ch;font-size:small}#bm-H input[type=number]::-webkit-outer-spin-button,#bm-H input[type=number]::-webkit-inner-spin-button{-webkit-appearance:none;margin:0}#bm-5{white-space:nowrap;text-align:center}#bm-7{display:flex;flex-direction:row;flex-wrap:wrap;align-content:center;justify-content:center;align-items:center;gap:1ch}div:has(>#bm-m)>button{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}#bm-m,input[type=file][id*=template]{display:none!important;visibility:hidden!important;position:absolute!important;left:-9999px!important;top:-9999px!important;width:0!important;height:0!important;opacity:0!important;z-index:-9999!important;pointer-events:none!important}#bm-O{font-size:small;background-color:#0003;padding:0 .5ch;height:3.75em;width:100%}#bm-9{display:flex;justify-content:space-between}#bm-16 small{font-size:x-small;color:#d3d3d3}#bm-w,#bm-q,#bm-H,#bm-7,#bm-O{margin-top:.5em}#bm-V{display:flex;align-items:baseline;gap:.5ch;white-space:nowrap;min-height:1.4em}#bm-V .bm-x{color:orange;font-weight:700;font-variant-numeric:tabular-nums;font-feature-settings:\"tnum\"}#bm-V .bm-W{color:#d3d3d3;font-size:.8em}#bm-16 button{background-color:#144eb9;border-radius:1em;padding:0 .75ch;font-size:small}#bm-16 span:has(>input[type=file]+button){font-size:small}#bm-16 select{border-width:1px;border-radius:1em;padding:0 .75ch;font-size:small}#bm-16 select option{background-color:#153063cc}#bm-16 button:hover,#bm-16 button:focus-visible{background-color:#1061e5}#bm-16 button:active #bm-16 button:disabled{background-color:#2e97ff}#bm-16 button:disabled{text-decoration:line-through}#bm-16 details>summary{font-size:small}#bm-r label{font-size:small}#bm-n span{word-break:break-word}span.bm-Y:hover,a.bm-Y:focus{text-decoration:underline}\n");var Y=new class{constructor(e,n){i(this,t),this.name=e,this.version=n,this.nt=null,this.it="bm-O",this.o=null,this.u=null,this.h=[]}ot(t){this.nt=t}st(){return this.h.length>0&&(this.u=this.h.pop()),this}ct(t){t?.appendChild(this.o),this.o=null,this.u=null,this.h=[]}dt(n={},i=()=>{}){return i(this,o(this,t,e).call(this,"div",{},n)),this}ut(n={},i=()=>{}){return i(this,o(this,t,e).call(this,"p",{},n)),this}ht(n={},i=()=>{}){return i(this,o(this,t,e).call(this,"span",{},n)),this}bt(n={},i=()=>{}){return i(this,o(this,t,e).call(this,"b",{},n)),this}ft(t){if(!this.o)return this;const e=document.createTextNode(t);return this.u?.appendChild(e),this}gt(n={},i=()=>{}){return i(this,o(this,t,e).call(this,"small",{},n)),this}vt(n={},i=()=>{}){return i(this,o(this,t,e).call(this,"img",{},n)),this}wt(n,i={},s=()=>{}){return s(this,o(this,t,e).call(this,"h"+n,{},i)),this}yt(n={},i=()=>{}){return i(this,o(this,t,e).call(this,"hr",{},n)),this}xt(n={},i=()=>{}){return i(this,o(this,t,e).call(this,"br",{},n)),this}Ct(n={},i=()=>{}){const s=o(this,t,e).call(this,"label",{textContent:n.textContent??""});delete n.textContent;const r=o(this,t,e).call(this,"input",{type:"checkbox"},n);return s.insertBefore(r,s.firstChild),this.st(),i(this,s,r),this}$t(n={},i=()=>{}){const s=n.textContent;delete n.textContent;const r=o(this,t,e).call(this,"details",{type:"details"},n),a=o(this,t,e).call(this,"summary",{textContent:s??""});return r.appendChild(a),this.st(),i(this,a,r),this}Mt(n={},i=()=>{}){return i(this,o(this,t,e).call(this,"button",{},n)),this}kt(n={},i=()=>{}){const s=n.title??n.textContent??"Help: No info";delete n.textContent,n.title=`Help: ${s}`;const r={textContent:"?",className:"bm-1e",onclick:()=>{this.St(this.it,s)}};return i(this,o(this,t,e).call(this,"button",r,n)),this}Tt(n={},i=()=>{}){return i(this,o(this,t,e).call(this,"select",{},n)),this}Ot(n={},i=()=>{}){return i(this,o(this,t,e).call(this,"input",{},n)),this}Dt(n={},i=()=>{}){const s=n.textContent??"";delete n.textContent;const r=o(this,t,e).call(this,"span"),a=o(this,t,e).call(this,"input",{type:"file",style:"display: none !important; visibility: hidden !important; position: absolute !important; left: -9999px !important; width: 0 !important; height: 0 !important; opacity: 0 !important;"},n);this.st();const c=o(this,t,e).call(this,"button",{textContent:s});return this.st(),this.st(),a.setAttribute("tabindex","-1"),a.setAttribute("aria-hidden","true"),c.addEventListener("click",()=>{a.click()}),a.addEventListener("change",()=>{c.style.maxWidth=`${c.offsetWidth}px`,a.files.length>0?c.textContent=a.files[0].name:c.textContent=s}),i(this,r,a,c),this}Lt(n={},i=()=>{}){return i(this,o(this,t,e).call(this,"textarea",{},n)),this}St(t,e,n=!1){const i=document.getElementById(t.replace(/^#/,""));i&&(i instanceof HTMLInputElement?i.value=e:n?i.textContent=e:i.innerHTML=e)}Et(t,e){let n,i=!1,o=0,s=null,r=0,a=0,c=0,l=0;if(t=document.querySelector("#"==t?.[0]?t:"#"+t),e=document.querySelector("#"==e?.[0]?e:"#"+e),!t||!e)return void this.At(`Can not drag! ${t?"":"moveMe"} ${t||e?"":"and "}${e?"":"iMoveThings "}was not found!`);const d=()=>{if(i){const e=Math.abs(r-c),n=Math.abs(a-l);(e>.5||n>.5)&&(r=c,a=l,t.style.transform=`translate(${r}px, ${a}px)`,t.style.left="0px",t.style.top="0px",t.style.right=""),s=requestAnimationFrame(d)}};let m=null;const u=(u,h)=>{i=!0,m=t.getBoundingClientRect(),n=u-m.left,o=h-m.top;const p=window.getComputedStyle(t).transform;if(p&&"none"!==p){const t=new DOMMatrix(p);r=t.m41,a=t.m42}else r=m.left,a=m.top;c=r,l=a,document.body.style.userSelect="none",e.classList.add("dragging"),s&&cancelAnimationFrame(s),d()},h=()=>{i=!1,s&&(cancelAnimationFrame(s),s=null),document.body.style.userSelect="",e.classList.remove("dragging")};e.addEventListener("mousedown",function(t){t.preventDefault(),u(t.clientX,t.clientY)}),e.addEventListener("touchstart",function(t){const e=t?.touches?.[0];e&&(u(e.clientX,e.clientY),t.preventDefault())},{passive:!1}),document.addEventListener("mousemove",function(t){i&&m&&(c=t.clientX-n,l=t.clientY-o)},{passive:!0}),document.addEventListener("touchmove",function(t){if(i&&m){const e=t?.touches?.[0];if(!e)return;c=e.clientX-n,l=e.clientY-o,t.preventDefault()}},{passive:!1}),document.addEventListener("mouseup",h),document.addEventListener("touchend",h),document.addEventListener("touchcancel",h)}Nt(t){(0,console.info)(`${this.name}: ${t}`),this.St(this.it,"Status: "+t,!0)}At(t){(0,console.error)(`${this.name}: ${t}`),this.St(this.it,"Error: "+t,!0)}}(G,J),X=new class{constructor(t,e,n){i(this,B),this.name=t,this.version=e,this.o=n,this.Bt="1.0.0",this.K=null,this.It="!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~",this.tileSize=1e3,this.H=g(5e3,5e3)?5:4,this.U=this.H-1>>1,this.jt=null,this.Pt=null,this.Rt="bm-1a",this.Ft="div#map canvas.maplibregl-canvas",this.Ut=null,this.G=[],this.Ht=null,this.qt=new Map,this.extraColorsBitmap=0,this.zt=0,this.Gt=0,this.Jt={},this.hideLockedColors=!1,this.q=0}Yt(){if(document.body.contains(this.jt))return this.jt;document.getElementById(this.Rt)?.remove();const t=document.querySelector(this.Ft),e=document.createElement("canvas");return e.id=this.Rt,e.className="maplibregl-canvas",e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.height=t?.clientHeight*(window.devicePixelRatio||1)+"px",e.style.width=t?.clientWidth*(window.devicePixelRatio||1)+"px",e.height=t?.clientHeight*(window.devicePixelRatio||1),e.width=t?.clientWidth*(window.devicePixelRatio||1),e.style.zIndex="8999",e.style.pointerEvents="none",t?.parentElement?.appendChild(e),this.jt=e,window.addEventListener("move",this.Xt),window.addEventListener("zoom",this.Wt),window.addEventListener("resize",this._t),this.jt}async Vt(){return{whoami:this.name.replace(" ",""),scriptVersion:this.version,schemaVersion:this.Bt,templates:{}}}async Kt(t,e,n){this.Ht||(this.Ht=await this.Vt()),this.o.Nt(`Creating template at ${n.join(", ")}...`);const i=function(t,e){if(0===t)return e[0];let n="";const i=e.length;for(;t>0;)n=e[t%i]+n,t=Math.floor(t/i);return n}(this.K||0,this.It),o=new y({displayName:e,p:this.q+1,C:i,file:t,coords:n,tileSize:this.tileSize});this.q++,o.shreadSize=this.H;const{j:s,P:r}=await o.I(this.Zt()),c=this.Qt();for(const t of Object.keys(o.O))void 0!==c[t]&&(o.O[t].enabled=c[t]);this.F()?(o.$={},Object.entries(s).forEach(([t,e])=>{o.$[t]=null,e.close()})):o.$=s,o.M=Object.fromEntries(Object.entries(r).map(([t,e])=>[t,a(e)]));const l=`${o.p} ${o.C}`;o.L=l,this.Ht.templates[l]={name:o.displayName,coords:n.join(", "),enabled:!0,tiles:r,palette:o.O,shreadSize:o.shreadSize},this.G.push(o),this.te(o);const d=(new Intl.NumberFormat).format(o.k);this.o.Nt(`Template created at ${n.join(", ")}! Total pixels: ${d}`),this.ee(),await this.ne()}ee(){try{window.postMessage({source:"blue-marble",J:"bm-o"},"*")}catch(t){}try{window.postMessage({source:"blue-marble",J:"bm-d"},"*")}catch(t){}}ie(){if(this.oe())try{const t=document.querySelector("#bm-t");t&&(t.style.display=""),window.postMessage({source:"blue-marble",J:"bm-p"},"*")}catch(t){}}async ne(){await GM.setValue("bmTemplates",JSON.stringify(this.Ht))}async se(t){const e=this.G.find(e=>e.L===t);if(void 0===e)return;const n=this.G.indexOf(e);this.G.splice(n,1);const i=this.Ht?.templates;i&&i?.[t]&&delete i[t],this.te(e),this.o.Nt(`Template ${e.displayName} is deleted!`),await this.ne(),this.ee()}async re(){this.Ht||(this.Ht=await this.Vt())}async ae(t,e){performance.now();const n=e[0].toString().padStart(4,"0")+","+e[1].toString().padStart(4,"0"),i=this.ce(e);if(0===i.length)return;const o=this.F(),s=i.map(t=>{const e=Object.keys(t.$).filter(t=>t.startsWith(n));if(0===e.length)return null;const i=e[0],o=i.split(",");return{Ut:t,le:i,de:[+o[0],+o[1]],me:[+o[2],+o[3]]}}).filter(Boolean),r=s?.length||0,a=this.G.filter(t=>t.enabled).length;let c=0,m=0,u=0,h={},p={};const b=await createImageBitmap(t),f=this.ue(),g=this.H,v=this.U,w=this.tileSize;let y=new OffscreenCanvas(w,w);const x=y.getContext("2d");x.imageSmoothingEnabled=!1,x.beginPath(),x.rect(0,0,w,w),x.clip(),x.clearRect(0,0,w,w),x.drawImage(b,0,0,w,w),b.close();const C=x.getImageData(0,0,w,w).data;for(const t of s){const n=t.Ut,i=n.L,s=await n.R(t.le,o),r=s.width,a=s.height;let b=new OffscreenCanvas(r,a);const y=b.getContext("2d",{willReadFrequently:!0});y.imageSmoothingEnabled=!1,y.clearRect(0,0,r,a),y.drawImage(s,0,0);const x=y.getImageData(0,0,r,a).data,$=r/g,k=a/g;let S=null,T=null,O=null,D=null;const L=t.Ut.enabled??!0;f&&L&&(S=new OffscreenCanvas($,k),T=S.getContext("2d",{willReadFrequently:!0}),T.clearRect(0,0,$,k),O=T.getImageData(0,0,$,k),D=O.data);const E=t.me[0],A=t.me[1];try{for(let t=v,n=A,o=0;t=w||n>=w)continue;const b=4*(t*r+s),g=x[b],v=x[b+1],y=x[b+2],M=x[b+3],k=4*(n*w+a),S=C[k],T=C[k+1],O=C[k+2],E=C[k+3];let A=!1;const N=4*(o*$+d);if(M<64)try{const t=l.has(`${S},${T},${O}`)?`${S},${T},${O}`:"other";E>=64&&"other"!==t&&m++}catch(t){}else{if(u++,E<64)0!==M&&f&&L&&(D[N]=255,D[N+1]=255,D[N+2]=0,D[N+3]=16);else if(S===g&&T===v&&O===y){c++,A=!0;let t=`${g},${v},${y}`;l.has(t)||(t="other"),void 0===h[t]?h[t]={painted:1,he:+L,pe:0,be:[]}:(h[t].painted++,L&&h[t].he++),void 0===p[i]?p[i]={painted:1}:p[i].painted++,f&&L&&(D[N]=0,D[N+1]=128,D[N+2]=0,D[N+3]=160)}else m++,f&&L&&(D[N]=255,D[N+1]=0,D[N+2]=0,D[N+3]=224);if(!A){let t=`${g},${v},${y}`;l.has(t)||(t="other");const i=[e,[a,n]];if(void 0===h[t])h[t]={painted:0,he:0,pe:1,be:[]},L&&h[t].be.push(i);else{const e=this.Jt?.smartPlace?1<<20:1e4;if(h[t].pe++,L)if(h[t].be.length[t.L,t.enabled]));for(const t of this.qt.values())Object.entries(t.Ut).forEach(([t,e])=>{k[t]&&($+=e.painted||0)});const S=this.G.reduce((t,e)=>t+(e.enabled&&(e.S||e.k)||0),0),T=(new Intl.NumberFormat).format($),O=(new Intl.NumberFormat).format(S),D=(new Intl.NumberFormat).format(S-$);return this.o.Nt(`Displaying ${a} template${1==a?"":"s"}.\nPainted ${T} / ${O} • Wrong ${D}`),d(y),window.buildColorFilterList(),window.buildTemplateFilterList(),t}async Y(t=null){performance.now();const e=this.F(),n=(this.G??[]).filter(e=>e.enabled&&(null===t||e.p==t));for(const t of n){if(!t.enabled)return;const n=this.ge(),i=new Set(n),o=n.length!==Object.keys(this.Qt()).length,s=0===n.length;if(s){k("overlay",t.p);continue}const r=this.isLegacyDisplay();for(const n of Object.keys(t.$)){n.split(",");const a=t.shreadSize,c=t.shreadSize-1>>1,m=r?3:this.H,u=await t.R(n,e),h=u.width/t.shreadSize,p=u.height/t.shreadSize,b=h*m,f=p*m;let g=new OffscreenCanvas(b,f);const v=g.getContext("2d");v.imageSmoothingEnabled=!1,v.beginPath(),v.rect(0,0,b,f),v.clip(),v.clearRect(0,0,b,f);try{if(o||a!==m){if(!s){const e=u.width,n=u.height,o=new OffscreenCanvas(e,n).getContext("2d",{willReadFrequently:!0});o.imageSmoothingEnabled=!1,o.clearRect(0,0,e,n),o.drawImage(u,0,0);const s=o.getImageData(0,0,e,n).data,d=v.getImageData(0,0,b,f),h=d.data,p=r?[[1,1]]:t.B(m);for(const[t,o]of p)for(let r=c,d=o;rM(t.p,n,[h,p],w,"overlay")),d(g),g=null,e&&u.close()}}}ve(t){"BlueMarble"==t?.whoami&&(this.Ht=t,o(this,B,I).call(this,t))}Qt(){const t={};for(const e of this.G)for(const[n,i]of Object.entries(e.O))t[n]||(t[n]=i.enabled);return t}ge(){const t=this.we(),e=this.ye(),n=this.Qt(),i=this.xe(),o=[];if(t){const t=w();Object.entries(n).forEach(([n,s])=>{const r=l.get(n).id;r===t&&(e&&!this.Ce(r)||i&&this.$e(r)||o.push(n))})}else Object.entries(n).forEach(([t,n])=>{const s=l.get(t).id;n&&(e&&!this.Ce(s)||i&&this.$e(s)||o.push(t))});return o.sort()}Me(){this.ke();const t=new Set;for(let e=0,n=1;e<64;e++,n<<=1)this.Se&n&&t.add(e);return t}ce(t){const e=t[0].toString().padStart(4,"0")+","+t[1].toString().padStart(4,"0");return this.G.filter(t=>!!t?.$&&(t.D&&t.D.size>0?t.D.has(e):Object.keys(t.$).some(t=>t.startsWith(e)))).sort((t,e)=>t.p-e.p)}Te(t){const e=this.ge(),n=this.ce(t);return this.Oe(e,n)}Oe(t,e){return t.join(";")+"||"+e.map(t=>t.L+","+t.A+","+ +(t.enabled??!0)).join(";")}ke(){const t={};(this.G??[]).forEach(e=>{if(e.enabled&&e?.O)for(const[n,i]of Object.entries(e.O))t[n]=(t[n]??0)+i.count});const e={};for(const t of this.qt.values())Object.entries(t.palette).forEach(([t,n])=>{void 0===e[t]?(e[t]=Object.fromEntries(Object.entries(n)),e[t].be=n.be.slice()):(e[t].painted+=n.painted,e[t].he+=n.he,e[t].pe+=n.pe,e[t].be.extend(n.be))});var n=0,i=0;return Object.entries(t).forEach(([t,o])=>{if((e[t]?.he??0)>=o){const e=l.get(t)?.id??0;e<32?n|=1<{if(!t?.$)return;const e=t.$,n={};Object.entries(e).forEach(([t,e])=>{n[t]=null,null!==e&&e.close()}),t.$=n})}Zt(){const t=this.Jt?.anchor??"lt";return this.He(t)?t.toLowerCase():"lt"}He(t){return 2===t.length&&(t=t.toLowerCase(),"lmr".includes(t[0])&&"tmb".includes(t[1]))}async qe(t){return!!this.He(t)&&(this.Jt.anchor=t.toLowerCase(),await this.Ee(),!0)}oe(){return this.Jt?.eventEnabled??!1}async ze(t){this.Jt.eventEnabled=t,await this.Ee()}Ge(){return this.Jt?.eventClaimedShown??!0}async Je(t){this.Jt.eventClaimedShown=t,await this.Ee()}Ye(){return this.Jt?.eventUnavailableShown??!0}async Xe(t){this.Jt.eventUnavailableShown=t,await this.Ee()}We(){return this.Jt?.eventProvider??""}async _e(t){this.Jt.eventProvider=t,await this.Ee()}we(){return this.Jt?.onlyCurrentColorShown??!1}async Ve(t){this.Jt.onlyCurrentColorShown=t,await this.Ee()}Ke(){return this.Jt?.themeOverridden??!1}async Ze(t){this.Jt.themeOverridden=t,await this.Ee()}Qe(){const t=(this.Jt?.currentTheme??Object.keys(T)[0]).toLowerCase();return T[t]?t:Object.keys(T)[0]}async tn(t){return t=t.toLowerCase(),!!T[t]&&(this.Jt.currentTheme=t,await this.Ee(),!0)}en(){return this.Jt?.hideStatus??!1}async nn(t){this.Jt.hideStatus=t,await this.Ee()}isLegacyDisplay(){return this.Jt?.sn??!1}async rn(t){this.Jt.sn=t,await this.Ee()}ue(){return this.Jt?.showErrorMap??!1}async an(t){this.Jt.showErrorMap=t,await this.Ee()}et(t){this.extraColorsBitmap!==t&&(this.extraColorsBitmap=t,window.buildColorFilterList(),this.Y())}Ce(t){if(t<32)return!0;const e=1<{this.qt.delete(t)})}}(G,J,Y),W=new class{constructor(t){i(this,j),this.Z=t,this.cn=!1,this.ln=[],this.dn=[],this.charges=null,this.tt=null,this.X=null,this.mn={},this.un=null,this.V=null}W(){if(null===this.charges)return o(this,j,F).call(this),0;const t=(Date.now()-this.tt)/this.charges.cooldownMs,e=this.charges.count+t,n=this.charges.count>this.charges.max?this.charges.count:this.charges.max;return e>n?n:e}hn(){const t=this.W();return t>=this.charges.max?0:(this.charges.max-t)*this.charges.cooldownMs}_(){const t=this.hn();if(0===t)return"00:00";const e=Math.floor(t/1e3),n=Math.floor(e/3600),i=Math.floor(e%3600/60).toString().padStart(2,"0"),o=(e%60).toString().padStart(2,"0");return n>0?`${n}:${i}:${o}`:`${i}:${o}`}pn(){const t=[this.ln[0],this.ln[1]],e=[this.ln[2],this.ln[3]],n=(i=t,o=e,[parseInt(i[0])%4*1e3+parseInt(o[0]),parseInt(i[1])%4*1e3+parseInt(o[1])]);var i,o;const s=document.querySelectorAll("span");for(const i of s)if(i.textContent.trim().includes(`${n[0]}, ${n[1]}`)){let n=document.getElementById("bm-z"),o=document.getElementById("bm-A"),s=document.getElementById("bm-g"),r=document.getElementById("bm-h");const a=A(t,e),c=`(Tl X: ${t[0]}, Tl Y: ${t[1]}, Px X: ${e[0]}, Px Y: ${e[1]})`,l=`(${a[0].toFixed(5)}, ${a[1].toFixed(5)})`;if(n)n.textContent=c,o.textContent=l;else{n=document.createElement("span"),n.id="bm-z",n.textContent=c,n.style="margin-left: calc(var(--spacing)*3); font-size: small;",i.parentNode.parentNode.parentNode.insertAdjacentElement("afterend",n);const t=function(){const t=this.dataset.text;b(t),alert("Copied to clipboard: "+t)};s=document.createElement("a"),s.href="#",s.id="bm-g",s.textContent="Copy",s.style="font-size: small; text-decoration: underline;",s.className="text-nowrap",s.addEventListener("click",t),n.insertAdjacentElement("afterend",s),n.insertAdjacentText("afterend"," ");const e=document.createElement("br");s.insertAdjacentElement("afterend",e),o=document.createElement("span"),o.id="bm-A",o.textContent=l,o.style="margin-left: calc(var(--spacing)*3); font-size: small;",e.insertAdjacentElement("afterend",o),r=document.createElement("a"),r.href="#",r.id="bm-h",r.textContent="Copy",r.style="font-size: small; text-decoration: underline;",r.className="text-nowrap",r.addEventListener("click",t),o.insertAdjacentElement("afterend",r),o.insertAdjacentText("afterend"," ")}s.dataset.text=c,r.dataset.text=l}}bn(){if(4!==this.ln.length)return;const t=[this.ln[0],this.ln[1]],e=[this.ln[2],this.ln[3]],n=document.querySelectorAll("dialog.modal > div");for(const i of n){if(null===i.querySelector("input[readonly]"))continue;let n=document.querySelector("#bm-B"),o=document.querySelector("#bm-k"),s=document.querySelector("#bm-u"),r=document.querySelector("#bm-8");if(!n){const t=document.createElement("div");i.appendChild(t);const e=document.createElement("h3");e.innerText="Download as Template",e.className="mb-1 mt-5 flex items-center gap-1 text-xl font-semibold",t.appendChild(e);const a=document.createElement("div");a.className="bg-base-200 border-base-content/10 rounded-xl border-2 p-3",a.style.fontSize="small",a.innerText=["Instruction to mark the rectangular range for downloading:",'1. Pick the first reference point (e.g. the Top Left Corner) and use the "Pin" icon to record the coordinates.','2. Pick the second reference point, i.e. the opposite corner (e.g. the Bottom Right Corner), and click the "Share" button.'].join("\n"),t.appendChild(a),o=document.createElement("span"),o.id="bm-k",o.style.fontSize="small",t.appendChild(o),t.appendChild(document.createElement("br"));const c=document.createElement("div");c.className="mt-3 flex items-end justify-end gap-2",s=document.createElement("progress"),s.id="bm-u",s.max="100",s.value="0",s.hidden=!0,c.appendChild(s),r=document.createElement("span"),r.id="bm-8",r.hidden=!0,r.textContent="0 / 0",c.appendChild(r),n=document.createElement("button"),n.id="bm-B",n.className="btn btn-primary";const l=document.createElementNS("http://www.w3.org/2000/svg","svg");l.setAttribute("xmlns","http://www.w3.org/2000/svg"),l.setAttribute("viewBox","0 -960 960 960"),l.setAttribute("fill","currentColor"),l.setAttribute("class","size-5");const d=document.createElementNS("http://www.w3.org/2000/svg","path");d.setAttribute("d","M480-320 280-520l56-58 104 104v-326h80v326l104-104 56 58-200 200ZM240-160q-33 0-56.5-23.5T160-240v-120h80v120h480v-120h80v120q0 33-23.5 56.5T720-160H240Z"),l.appendChild(d),n.appendChild(l),n.appendChild(document.createTextNode(" Download"));const m=this;n.addEventListener("click",async function(){this.disabled=!0;const t=[m.ln[0],m.ln[1]],e=[m.ln[2],m.ln[3]];if(!h())return void alert("Some coordinates textboxes are empty or invalid!");const n=u(),[[i,o],[a,c]]=f([t,e],n),l=Math.floor(i/1e3),d=Math.floor(o/1e3),p=i%1e3,b=o%1e3,g=Math.floor((i+a-1)/1e3),w=Math.floor((o+c-1)/1e3),y=g-l+1,x=w-d+1;s.max=y*x,s.value=0,s.hidden=!1,r.textContent=`0 / ${s.max}`,r.hidden=!1;try{const t=new OffscreenCanvas(a,c),e=t.getContext("2d");e.clearRect(0,0,a,c);for(let t=d;t<=w;t++)for(let n=l;n<=g;n++){const a=await v(n%2048,t);e.drawImage(a,1e3*n-i,1e3*t-o),s.value++,r.textContent=`${s.value} / ${s.max}`}const n=await t.convertToBlob({type:"image/png"});var C=document.createElement("a");C.href=URL.createObjectURL(n,{type:"image/png"}),C.setAttribute("download",`template_${l}_${d}_${p}_${b}_${(new Date).toISOString()}.png`),C.click(),URL.revokeObjectURL(C.href)}catch(t){throw alert("Download Failed!"),t}finally{s.hidden=!0,r.hidden=!0,this.disabled=!1}}),c.appendChild(n),t.appendChild(c)}const a=[];if(h()){const i=u(),[[o,s],[r,c]]=f([t,e],i),l=Math.floor(o/1e3),d=Math.floor(s/1e3),m=o%1e3,h=s%1e3,p=(o+r-1)%2048e3,b=s+c-1,v=Math.floor(p/1e3),w=Math.floor(b/1e3),y=p%1e3,x=b%1e3;a.push(`Top Left: (Tl X: ${l}, Tl Y: ${d}, Px X: ${m}, Px Y: ${h})`),a.push(`Bottom Right: (Tl X: ${v}, Tl Y: ${w}, Px X: ${y}, Px Y: ${x})`),a.push(`Image Size: ${r}×${c}`),g(r,c)?n.disabled=!1:(n.disabled=!0,a.push("Too large for the browser to export."))}else a.push("Some coordinates textboxes are empty or invalid."),n.disabled=!0;o.innerText=a.join("\n")}}fn(t){o(this,j,P).call(this),window.addEventListener("message",async e=>{const n=e.data,i=n.jsonData;if(!n||"blue-marble"!==n.source)return;if(!n.endpoint)return;const s=n.endpoint?.split("?")[0].split("/").filter(t=>t&&isNaN(Number(t))).filter(t=>t&&!t.includes(".")).pop();switch(s){case"me":if(i.status&&"2"!=i.status?.toString()[0])return void(i.fallback||t.At("You are not logged in!\nCould not fetch userdata."));o(this,j,U).call(this,i,Date.now());break;case"pixel":const e=n.endpoint.split("?")[0].split("/").filter(t=>t&&!isNaN(Number(t))).map(t=>Number(t));if(void 0!==(n.jsonData??{}).painted){if(!e.length)return;const t=e[0].toString().padStart(4,"0")+","+e[1].toString().padStart(4,"0");this.mn[t]&&delete this.mn[t];break}const s=new URLSearchParams(n.endpoint.split("?")[1]),r=[+s.get("x"),+s.get("y")];if(this.ln.length&&(!e.length||!r.length))return void t.At("Coordinates are malformed!\nDid you try clicking the canvas first?");this.ln=[...e,...r],this.pn(),this.bn();break;case"tiles":let a=n.endpoint.split("/");a=[parseInt(a[a.length-2]),parseInt(a[a.length-1].replace(".png",""))];const c=n.blobData,l=a[0].toString().padStart(4,"0")+","+a[1].toString().padStart(4,"0"),d=n.lastModified,m=this.Z.Te(a),u=+this.Z.ue(),h=!this.mn[l]||this.mn[l].fullKey!==m,p=!this.mn[l]||this.mn[l].lastModified!==d,b=!this.mn[l]||this.mn[l].errorMap!==u;(h||p||b)&&(this.Z.ce(a).length>0&&(h||p||b&&u)&&await this.Z.ae(c,a),this.mn[l]={lastModified:d,fullKey:m,errorMap:u});break;case"random":const f=n.blobID,g=D.data,v=null===g?i:{pixel:{x:g[1][0],y:g[1][1]},tile:{x:g[0][0],y:g[0][1]}};D.data=null,window.postMessage({source:"blue-marble",blobID:f,blobData:JSON.stringify(v),blink:n.blink});break;case"claimed":this.un=i.claimed??[],this.Z.ie();break;case"robots":this.cn="false"==i.userscript?.toString().toLowerCase()}})}}(X);Y.ot(W),GM.getValue("bmTemplates","{}").then(async t=>{const e=await GM.getValue("bmUserSettings","{}");let n,i;try{n=JSON.parse(e)}catch{n={}}if(0==Object.keys(n).length){const t=crypto.randomUUID();X.Ae({uuid:t,hideLockedColors:!1,progressBarEnabled:!0,hideCompletedColors:!1,sortBy:"total-desc",anchor:"lt",smartPlace:!1,memorySavingMode:!1,eventEnabled:!1,eventProvider:"",eventClaimedShown:!0,eventUnavailableShown:!0,onlyCurrentColorShown:!1,themeOverridden:!1,currentTheme:"",hideStatus:!1,isLegacyDisplay:!1,showErrorMap:!1}),X.Ee()}else X.Ae(n);try{i=JSON.parse(t)}catch{i={}}X.ve(i),await async function(){let t=!1,e={};const n=await GM.getValue("bmCoords","{}");try{e=JSON.parse(n)||{}}catch{e={}}Y.dt({id:"bm-16",style:"top: 10px; right: 75px;"}).dt({id:"bm-G"}).dt({id:"bm-15"}).st().vt({alt:"Blue Marble Icon - Click to minimize/maximize",src:"https://raw.githubusercontent.com/SwingTheVine/Wplace-BlueMarble/main/dist/assets/Favicon.png",style:"cursor: pointer;"},(e,n)=>{n.addEventListener("click",()=>{t=!t;const i=document.querySelector("#bm-16"),o=document.querySelector("#bm-G"),s=document.querySelector("#bm-15"),r=document.querySelector("#bm-H"),a=document.querySelector("#bm-P"),c=document.querySelector("#bm-Q"),l=document.querySelector("#bm-R"),d=document.querySelector("#bm-I"),m=document.querySelector("#bm-v"),u=document.querySelectorAll("#bm-H input"),h=document.getElementById(e.it);t||(i.style.width="auto",i.style.maxWidth="300px",i.style.minWidth="200px",i.style.padding="10px"),["#bm-16 h1","#bm-w","#bm-16 hr","#bm-q > *:not(#bm-H)","#bm-9"].forEach(e=>{document.querySelectorAll(e).forEach(e=>{e.style.display=t?"none":""})}),t?(r&&(r.style.display="none"),a&&(a.style.display="none"),c&&(c.style.display="none"),l&&(l.style.display="none"),d&&(d.style.display="none"),X.oe()&&(m.style.display="none"),X.en()||(h.style.display="none"),u.forEach(t=>{t.style.display="none"}),i.style.width="60px",i.style.height="76px",i.style.maxWidth="60px",i.style.minWidth="60px",i.style.padding="8px",n.style.marginLeft="3px",o.style.textAlign="center",o.style.margin="0",o.style.marginBottom="0",s&&(s.style.display="",s.style.marginBottom="0.25em")):(r&&(r.style.display="",r.style.flexDirection="",r.style.justifyContent="",r.style.alignItems="",r.style.gap="",r.style.textAlign="",r.style.margin=""),a&&(a.style.display=""),c&&(c.style.display="",c.style.marginTop=""),l&&(l.style.display="",l.style.marginTop=""),d&&(d.style.display="",d.style.marginTop=""),X.oe()?m.style.display="":m.style.display="none",X.en()?h.style.display="none":h.style.display="",u.forEach(t=>{t.style.display=""}),n.style.marginLeft="",i.style.padding="10px",o.style.textAlign="",o.style.margin="",o.style.marginBottom="",s&&(s.style.marginBottom="0.5em"),i.style.width="",i.style.height=""),n.alt=t?"Blue Marble Icon - Minimized (Click to maximize)":"Blue Marble Icon - Maximized (Click to minimize)"})}).st().wt(1,{textContent:G}).gt({textContent:` v${J}`}).st().st().st().yt().st().dt({id:"bm-w"}).ut({textContent:"Username: "}).bt({id:"bm-10"}).st().st().ut({id:"bm-V"},(t,e)=>{e.setAttribute("aria-live","polite")}).ft("Full Charges in ").ht({className:"bm-x",textContent:"--:--"},(t,e)=>{e.dataset.role="countdown"}).st().ft(" ").ht({className:"bm-W",textContent:"(0 / 0)"},(t,e)=>{e.dataset.role="charge-count"}).st().st().ut({textContent:"Droplets: "}).bt({id:"bm-N"}).st().st().ut().bt({id:"bm-E",textContent:"--"}).st().ft(" more pixel").ht({id:"bm-e",textContent:"s"}).st().ft(" to Lv. ").bt({id:"bm-F",textContent:"--"}).st().st().st().yt().st().dt({id:"bm-q"}).dt({id:"bm-H"}).Mt({id:"bm-P",className:"bm-1e",style:"margin-top: 0;",innerHTML:''},(t,e)=>{e.onclick=()=>{const e=t.nt?.ln;e?.[0]?(t.St("bm-11",e?.[0]||""),t.St("bm-12",e?.[1]||""),t.St("bm-13",e?.[2]||""),t.St("bm-14",e?.[3]||""),W.bn(),_()):t.At("Coordinates are malformed! Did you try clicking on the canvas first?")}}).st().Ot({type:"number",id:"bm-11",placeholder:"Tl X",min:0,max:2047,step:1,required:!0,value:e.tx??""},(t,e)=>{e.addEventListener("paste",t=>{const e=(t.clipboardData||window.clipboardData).getData("text"),n=[/^\s*([012]?\d{1,3}),\s*([012]?\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\s*$/,/^\s*([012]?\d{1,3})\s+([012]?\d{1,3})\s+(\d{1,3})\s+(\d{1,3})\s*$/,/^\s*\(?Tl X: ([012]?\d{1,3}), Tl Y: ([012]?\d{1,3}), Px X: (\d{1,3}), Px Y: (\d{1,3})\)?\s*$/].map(t=>t.exec(e)).filter(t=>t).pop();if(void 0===n)return;let i=n.slice(1).map(Number),o=(s=document,coords=[],coords.push(s.querySelector("#bm-11")),coords.push(s.querySelector("#bm-12")),coords.push(s.querySelector("#bm-13")),coords.push(s.querySelector("#bm-14")),coords);var s;for(let t=0;t(W.bn(),_());e.addEventListener("input",n),e.addEventListener("change",n)}).st().Ot({type:"number",id:"bm-12",placeholder:"Tl Y",min:0,max:2047,step:1,required:!0,value:e.ty??""},(t,e)=>{const n=()=>(W.bn(),_());e.addEventListener("input",n),e.addEventListener("change",n)}).st().Ot({type:"number",id:"bm-13",placeholder:"Px X",min:0,max:2047,step:1,required:!0,value:e.px??""},(t,e)=>{const n=()=>(W.bn(),_());e.addEventListener("input",n),e.addEventListener("change",n)}).st().Ot({type:"number",id:"bm-14",placeholder:"Px Y",min:0,max:2047,step:1,required:!0,value:e.py??""},(t,e)=>{const n=()=>(W.bn(),_());e.addEventListener("input",n),e.addEventListener("change",n)}).st().Mt({id:"bm-C",className:"bm-1e",style:"margin-top: 0;",innerHTML:"✈️",title:"Teleport"},(t,e)=>{e.onclick=()=>{V()}}).st().st().$t({id:"bm-r",textContent:"User Settings",style:"max-width: 100%; white-space: nowrap; border: 1px solid rgba(255,255,255,0.1); padding: 4px; border-radius: 4px; margin-top: 4px;"}).dt({style:"display: flex; flex-direction: column; gap: 4px;"}).Ct({id:"bm-3",textContent:"Hide Locked Colors",checked:X.ye()},(t,e,n)=>{n.addEventListener("change",()=>{X.Ne(n.checked),buildColorFilterList(),X.Y(),n.checked?t.Nt("Hidden all locked colors."):t.Nt("Restored all colors.")})}).st().Ct({id:"bm-1",textContent:"Hide Completed Colors",checked:X.xe()},(t,e,n)=>{n.addEventListener("change",()=>{X.Fe(n.checked),buildColorFilterList(),X.Y(),n.checked?t.Nt("Hidden all completed colors."):t.Nt("Restored all colors.")})}).st().Ct({id:"bm-i",textContent:"Show Progress Bar",checked:X.Pe()},(t,e,n)=>{n.addEventListener("change",()=>{X.Re(n.checked),buildColorFilterList(),n.checked?t.Nt("Progress Bar Enabled."):t.Nt("Progress Bar Disabled.")})}).st().Ct({id:"bm-f",textContent:"Memory-Saving Mode",checked:X.F()},(t,e,n)=>{n.addEventListener("change",()=>{X.Ue(n.checked),buildColorFilterList(),n.checked?t.Nt("Memory Saving Mode Enabled. The Effect will be Fully Active After a Page Refresh."):t.Nt("Memory Saving Mode Disabled. The Effect will be Fully Active After a Page Refresh.")})}).st().Ct({id:"bm-S",textContent:"Enable Event",checked:X.oe()},(t,e,n)=>{n.addEventListener("change",()=>{X.ze(n.checked),n.checked?(t.Nt("Event Mode Enabled."),document.getElementById("bm-v").style.display="",document.getElementById("bm-s").parentElement.style.display="",document.getElementById("bm-a").parentElement.style.display="",buildEventList()):(t.Nt("Event Mode Disabled."),document.getElementById("bm-v").style.display="none",document.getElementById("bm-s").parentElement.style.display="none",document.getElementById("bm-a").parentElement.style.display="none")})}).st().Ct({id:"bm-s",textContent:"Hide Claimed Event Items",checked:!X.Ge()},(t,e,n)=>{X.oe()?e.style.display="":e.style.display="none",n.addEventListener("change",()=>{X.Je(!n.checked),n.checked?t.Nt("Hidden All Event Claimed Items."):t.Nt("Restored All Event Claimed Items."),buildEventList()})}).st().Ct({id:"bm-a",textContent:"Hide Unavailable Event Items",checked:!X.Ye()},(t,e,n)=>{X.oe()?e.style.display="":e.style.display="none",n.addEventListener("change",()=>{X.Xe(!n.checked),n.checked?t.Nt("Hidden All Unavailable Event Items."):t.Nt("Restored All Unavailable Event Items."),buildEventList()})}).st().Ct({id:"bm-0",textContent:"Show Current Color Only",checked:X.we()},(t,e,n)=>{n.addEventListener("change",()=>{X.Ve(n.checked),n.checked?(t.Nt("Only the currently selected color will be shown."),buildColorFilterList()):(t.Nt("Color filter is restored."),buildColorFilterList()),X.Y(),buildColorFilterList()})}).st().Ct({id:"bm-b",textContent:"Theme Override: ",checked:X.Ke()},(t,e,n)=>{n.addEventListener("change",async()=>{await X.Ze(n.checked),document.getElementById("bm-T").disabled=!n.checked,forceUpdateTheme()})}).Tt({id:"bm-T"},(t,e)=>{const n=X.Qe();Object.entries(T).forEach(([t,[i,o]])=>{const s=document.createElement("option");s.value=t,s.textContent=i,t===n&&(s.selected=!0),e.appendChild(s)}),e.addEventListener("change",async()=>{await X.tn(e.value),t.Nt(`Changed the theme to "${T[e.value][0]}".`),forceUpdateTheme()})}).st().st().Ct({id:"bm-U",textContent:"Hide Status Display",checked:X.en()},(t,e,n)=>{n.addEventListener("change",()=>{X.nn(n.checked),n.checked?(t.Nt("Status Display Hidden."),document.getElementById(Y.it).style.display="none"):(t.Nt("Status Display Restored."),document.getElementById(Y.it).style.display="")})}).st().Ct({id:"bm-X",textContent:"Use Dot Template (Original ver.)",checked:X.isLegacyDisplay()},(t,e,n)=>{n.addEventListener("change",()=>{X.rn(n.checked),n.checked?t.Nt("Switched to the Dot Template Display."):t.Nt("Switched to the Cross Template Display."),X.Y()})}).st().Ct({id:"bm-J",textContent:"Show Error Map (Experimental)",checked:X.ue()},(t,e,n)=>{n.addEventListener("change",()=>{X.an(n.checked),n.checked?(t.Nt("Error Map is now Displayed."),W.mn={},S()):(t.Nt("Error Map is now Hidden."),k("error"))})}).st().st().st().$t({id:"bm-l",textContent:"Colors",style:"border: 1px solid rgba(255,255,255,0.1); padding: 4px; border-radius: 4px; margin-top: 4px;"},(t,e,n)=>{n.open=!0}).ut({textContent:"Sort Colors by ",style:"font-size: small; margin-top: 3px; margin-left: 5px;"}).Tt({id:"bm-_"},(t,e)=>{const n=["Asc","Desc"],i=X.Be();Object.keys(p).forEach(t=>{n.forEach(n=>{const o=document.createElement("option");o.value=`${t.toLowerCase()}-${n.toLowerCase()}`,o.textContent=`${t[0].toUpperCase()+t.slice(1).toLowerCase()} (${n}.)`,o.value===i&&(o.selected=!0),e.appendChild(o)})}),e.addEventListener("change",()=>{X.je(e.value),buildColorFilterList();const n=e.value.split("-");t.Nt(`Changed the sort criteria to "${n[0][0].toUpperCase()+n[0].slice(1).toLowerCase()}" in ${n[1]}ending order.`)})}).st().st().dt({id:"bm-7",style:"display: flex; gap: 6px; margin-top: 3px; margin-bottom: 0px;"}).Mt({id:"bm-4",textContent:"Enable All"},(t,e)=>{e.onclick=()=>{X.G.forEach(t=>{t?.O&&Object.values(t.O).forEach(t=>t.enabled=!0)}),syncToggleList(),X.Y(),buildColorFilterList(),t.Nt("Enabled all colors")}}).st().Mt({id:"bm-2",textContent:"Disable All"},(t,e)=>{e.onclick=()=>{X.G.forEach(t=>{t?.O&&Object.values(t.O).forEach(t=>t.enabled=!1)}),syncToggleList(),k("overlay"),buildColorFilterList(),t.Nt("Disabled all colors")}}).st().st().dt({id:"bm-y",style:"max-height: 125px; overflow: auto; display: flex; flex-direction: column; gap: 4px;"}).st().st().$t({id:"bm-c",textContent:"Templates",style:"border: 1px solid rgba(255,255,255,0.1); padding: 4px; border-radius: 4px; margin-top: 4px;"},(t,e,n)=>{n.open=!0}).dt({id:"bm-5"}).Dt({id:"bm-m",textContent:"Select Image",accept:"image/png, image/jpeg, image/webp, image/bmp, image/gif"}).Mt({id:"bm-Q",textContent:"Create Template",style:"margin: 0 1ch;"},(t,e)=>{e.onclick=async()=>{const e=document.querySelector("#bm-m"),n=document.querySelector("#bm-11");if(!n.checkValidity())return n.reportValidity(),void t.At("Coordinates are malformed! Did you try clicking on the canvas first?");const i=document.querySelector("#bm-12");if(!i.checkValidity())return i.reportValidity(),void t.At("Coordinates are malformed! Did you try clicking on the canvas first?");const o=document.querySelector("#bm-13");if(!o.checkValidity())return o.reportValidity(),void t.At("Coordinates are malformed! Did you try clicking on the canvas first?");const s=document.querySelector("#bm-14");if(!s.checkValidity())return s.reportValidity(),void t.At("Coordinates are malformed! Did you try clicking on the canvas first?");e?.files[0]?(await X.Kt(e.files[0],e.files[0]?.name.replace(/\.[^/.]+$/,""),[Number(n.value),Number(i.value),Number(o.value),Number(s.value)]),t.Nt("Drew to canvas!")):t.At("No file selected!")}}).st().Tt({id:"bm-D"},(t,e)=>{const n={l:"Left",m:"Center",r:"Right"},i={t:"Top",m:"Middle",b:"Bottom"},o=X.Zt();Object.entries({lt:"⟔",mt:"⨪",rt:"ᒬ",lm:"꜏",mm:"⊡",rm:"꜊",lb:"Ŀ",mb:"∸",rb:"⟓"}).forEach(([t,n])=>{const i=document.createElement("option");i.value=t,i.textContent=n,t===o&&(i.selected=!0),e.appendChild(i)}),e.addEventListener("change",()=>{X.qe(e.value),t.Nt(`Changed the default template anchor to "${i[e.value[1]]} ${n[e.value[0]]}".`)})}).st().st().dt({id:"bm-n",style:"max-height: 125px; overflow: auto; display: flex; flex-direction: column; gap: 4px;"}).st().st().$t({id:"bm-v",textContent:"Event",style:"border: 1px solid rgba(255,255,255,0.1); padding: 4px; border-radius: 4px; display: none; margin-top: 4px;"},(t,e,n)=>{X.oe()&&(n.style.display=""),n.open=!0}).Mt({id:"bm-6",textContent:"Set Data Provider",style:"margin: 0 1ch;"},(t,e)=>{e.onclick=()=>{const t=X.We(),e=prompt("Enter the event data provider JSON URL:",""===t?"https://wplace.samuelscheit.com/tiles/pumpkin.json":t);e&&((t=>{try{return Boolean(new URL(t))}catch(t){return!1}})(e)?(X._e(e),buildEventList()):alert("The URL you entered is not valid!"))}}).st().Mt({id:"bm-j",textContent:"Refresh Data",style:"margin: 0 1ch;"},(t,e)=>{e.onclick=()=>buildEventList()}).st().dt({id:"bm-K",style:"max-height: 125px; overflow: auto; display: flex; flex-direction: column; gap: 4px;"}).st().st().Lt({id:Y.it,placeholder:`Status: Sleeping...\nVersion: ${J}`,readOnly:!0},(t,e)=>{X.en()&&(e.style.display="none")}).st().dt({id:"bm-9"}).dt().Mt({id:"bm-L",className:"bm-1e",innerHTML:"🎨",title:"Template Color Converter"},(t,e)=>{e.addEventListener("click",()=>{window.open("https://pepoafonso.github.io/color_converter_wplace/","_blank","noopener noreferrer")})}).st().Mt({id:"bm-M",className:"bm-1e",innerHTML:"🌐",title:"Official Blue Marble Website"},(t,e)=>{e.addEventListener("click",()=>{window.open("https://bluemarble.lol/","_blank","noopener noreferrer")})}).st().st().dt({id:"bm-1b"}).gt({textContent:"by SwingTheVine | Forked by TWY",style:"margin-top: auto;"}).st().st().st().st().ct(document.body),window.syncToggleList=function(){try{(X.G??[]).forEach(t=>{const e=t.L;if(e&&X.Ht?.templates?.[e]){const n=X.Ht.templates[e];n.enabled=t.enabled,n.palette=t.O}}),X.ne()}catch(t){}},window.buildColorFilterList=function(){const t=document.querySelector("#bm-y"),e=X.Qt(),n=X.xe(),i=X.ye();t.innerHTML="";const{De:o,Le:s}=X.ke();if(!t||!Object.keys(o).length)return void(t&&(t.innerHTML="No template colors to display."));const r=X.Be().split("-"),a=p[r[0]],c="asc"===r[1]?(t,e)=>a(t)-a(e):(t,e)=>a(e)-a(t),d=Object.entries(o).map(([t,e])=>[t,s[t]?.he??0,e]).sort(c);let m=!1;for(const[o,a,c]of d){if(i&&"other"===o)continue;if(n&&a===c)continue;let d=document.createElement("div");d.style.display="flex",d.style.alignItems="center",d.style.gap="6px";let u=document.createElement("div");u.style.width="14px",u.style.height="14px",u.style.border="1px solid rgba(255,255,255,0.5)";let h="",p="";const b=l.get(o);if("other"===o)u.style.background="#888",h="Other",p="other";else if("#deface"===o)u.style.background="#deface",h="Transparent",p="transparent";else{const[t,e,n]=o.split(",").map(Number);u.style.background=`rgb(${t},${e},${n})`;try{if(b&&"number"==typeof b.id){if(i&&!X.Ce(b.id))continue;const o=b?.name||`rgb(${t},${e},${n})`;b.premium&&(u.style.borderColor="gold",u.style.boxShadow="0 0 2px yellow"),h=`#${b.id} ${o}`,p=`${t},${e},${n}`}}catch(t){}}let f=document.createElement("span");if(f.style.fontSize="12px","remaining"===r[0]||n&&"painted"!==r[0]){const t=(c-a).toLocaleString();f.textContent=`${h} • ${t} Left`}else{const t=c.toLocaleString(),e=a.toLocaleString();f.textContent=`${h} • ${e} / ${t}`}if(X.Pe()){const t=a/(0===c?1:c)*100;d.style.background=`linear-gradient(to right, rgb(0, 128, 0, 0.8) 0%, rgb(0, 128, 0, 0.8) ${t}%, transparent ${t}%, transparent 100%)`}const g=s[p];let v=0;u.addEventListener("click",()=>{if((g?.be?.length??0)>0){const t=g.be,e=v%t.length;E(t[e][0],t[e][1]),++v}}),(g?.be?.length??0)>0&&(u.style.cursor="pointer");const y=document.createElement("input");y.type="checkbox",X.we()?(y.checked=b?.id===w(),y.disabled=!0):y.checked=e[o]??!0,y.addEventListener("change",()=>{(X.G??[]).forEach(t=>{t?.O&&void 0!==t.O[o]&&(t.O[o].enabled=y.checked)}),Y.Nt(`${y.checked?"Enabled":"Disabled"} ${o}`),syncToggleList(),X.Y()}),d.appendChild(y),d.appendChild(u),d.appendChild(f),t.appendChild(d),m=!0}!m&&t&&(t.innerHTML=i?n?"All owned colors have been completed.":"Remaining colors are all locked.":"All colors have been completed.")},window.buildTemplateFilterList=function t(){const e=document.querySelector("#bm-n");if(s(X),0===X.G?.length)return void(e&&(e.innerHTML="No templates to display."));e.innerHTML="";const n=X.G,i={};for(const t of X.qt.values())Object.entries(t.Ut).forEach(([t,e])=>{void 0===i[t]?i[t]=Object.fromEntries(Object.entries(e)):i[t].painted+=e.painted});for(const o of n){let n=document.createElement("div");n.style.display="flex",n.style.alignItems="center",n.style.gap="6px";let s=document.createElement("a");s.title="Remove template",s.textContent="🗑️",s.style.fontSize="12px",s.onclick=()=>{confirm(`Remove template ${o?.displayName}?`)&&X.se(o?.L)};let r=document.createElement("a");r.title="Teleport to template",r.textContent="✈️",r.style.fontSize="12px",r.onclick=()=>{E(o.coords.slice(0,2),o.coords.slice(2,4))};let a=document.createElement("span");a.style.fontSize="12px";const c=`${o.S.toLocaleString()}`,l=o.displayName,d=`${(i[o.L]?.painted??0).toLocaleString()}`,m=document.createElement("span");m.textContent=l,m.addEventListener("click",()=>{const e=o.displayName,n=prompt("Rename template",e);if(n){if(n.trim()===e)return;o.displayName=n.trim();try{const t=X.Ht?.templates?.[o.L];t&&(t.name=n.trim(),X.ne())}catch(t){}t()}}),m.className="bm-Y",a.appendChild(m),a.appendChild(document.createTextNode(` • ${d} / ${c}`));const u=document.createElement("input");u.type="checkbox",u.checked=o.enabled,u.addEventListener("change",()=>{o.enabled=u.checked,Y.Nt(`${u.checked?"Enabled":"Disabled"} ${l}`),u.checked?X.Y(o.p):(X.te(o),k(null,o.p)),syncToggleList(),buildColorFilterList(),S()}),n.appendChild(u),n.appendChild(s),n.appendChild(r),n.appendChild(a),e.appendChild(n)}},window.buildEventList=function(){const t=document.querySelector("#bm-K"),e=X.Ge(),n=X.Ye(),i=X.We();if(null===i||""==i)return void(t.innerHTML="Event data provider is not set.");if(null===W.un)return void(t.innerHTML="The event claimed items list is not loaded. Make sure you have clicked the ongoing Event button from the top left corner.");const o=new Set(W.un);s("eventClaimedList",o),fetch(i).then(t=>t.json()).then(i=>{if(s("event Location data",i),"object"!=typeof i)return void(t.innerHTML="The event data provider does not provide a known format.");t.textContent="";let r=!1;Object.entries(i).forEach(([i,s])=>{if(i=Number(i),o.has(i)&&!e)return;const a=document.createElement("div");a.style.display="flex",a.style.alignItems="center",a.style.gap="6px";let c=null,l="";if("object"==typeof s&&(void 0!==s.lat&&void 0!==s.lng?c=[s.lat,s.lng]:void 0!==s.tileX&&void 0!==s.offsetX&&void 0!==s.tileY&&void 0!==s.offsetY&&(c=A([s.tileX,s.tileY],[s.offsetX,s.offsetY])),void 0!==s.foundAt)){const t=Date.now(),e=t-t%36e5,i=new Date(s.foundAt).getTime();if(e!==i-i%36e5&&(l="Expired • ",!n))return}if(null!==c){let t=document.createElement("a");t.title="Teleport to template",t.textContent="✈️",t.style.fontSize="12px",t.onclick=()=>{L(c[0],c[1])},a.appendChild(t)}else l="Unknown Coordinate Format • ";let d=document.createElement("span");d.style.fontSize="12px",d.textContent=`#${i} • ${l}${o.has(i)?"Claimed":"Unclaimed"}`,a.appendChild(d),t.appendChild(a),r=!0}),!r&&t&&(t.innerHTML=`No ${e?"":"unclaimed "}items have ${n?"":"recent "}data available.`)}).catch(e=>{t.innerHTML="Failed fetching the event item info from the event data provider. Make sure the provider URL is a valid JSON resource and can be accessed with appropriate CORS."})},window.forceUpdateTheme=function(){X.Ke()?O(X.Qe()):O(Object.keys(T)[0])},window.forceClickCenter=function t(){if(!x()){if(t.clickCount||(t.clickCount=0),t.clickCount<10&&document.querySelector(".flex>.btn.btn-square.relative.shadow-md")){const e=document.querySelector("canvas.maplibregl-canvas");if(e){const n=new MouseEvent("click",{bubbles:!0,cancelable:!0,clientX:e.offsetWidth/2,clientY:e.offsetHeight/2,button:0});e.dispatchEvent(n),++t.clickCount}}setTimeout(t,100)}},window.addEventListener("message",t=>{if("bm-o"===t?.data?.J)try{buildColorFilterList()}catch(t){}else if("bm-d"===t?.data?.J)try{buildTemplateFilterList()}catch(t){}else if("bm-p"===t?.data?.J)try{buildEventList()}catch(t){}}),setTimeout(()=>{try{X.G?.length>0&&buildColorFilterList(),X.G?.length>0&&buildTemplateFilterList()}catch(t){}try{X.oe()&&buildEventList()}catch(t){}try{X.Ke()&&z(forceUpdateTheme)}catch(t){}try{forceClickCenter()}catch(t){}},0)}(),Y.Et("#bm-16","#bm-15");const o=new Set;let r=null;function a(){if(0===o.size)return void(r=null);let t=0,e=0;if((o.has("w")||o.has("arrowup"))&&(e-=1),(o.has("s")||o.has("arrowdown"))&&(e+=1),(o.has("a")||o.has("arrowleft"))&&(t-=1),(o.has("d")||o.has("arrowright"))&&(t+=1),0!==t||0!==e){if(0!==t&&0!==e){const n=Math.sqrt(t*t+e*e);t/=n,e/=n}C((t,e)=>{t.panBy(e,{duration:0})},[25*t,25*e])}r=requestAnimationFrame(a)}document.addEventListener("keydown",t=>{if("INPUT"===document.activeElement.tagName||"TEXTAREA"===document.activeElement.tagName)return;const e=t.key.toLowerCase();["w","a","s","d","arrowup","arrowdown","arrowleft","arrowright"].includes(e)&&!o.has(e)&&(o.add(e),r||(r=requestAnimationFrame(a)))}),document.addEventListener("keyup",t=>{const e=t.key.toLowerCase();o.delete(e)}),W.fn(Y),new MutationObserver((t,e)=>{const n=document.querySelector("#color-1");if(!n)return;let i=document.querySelector("#bm--");if(!i){i=document.createElement("button"),i.id="bm--",i.textContent="Move ↑",i.className="btn btn-soft",i.onclick=function(){const t=this.parentNode.parentNode.parentNode.parentNode,e="Move ↑"==this.textContent;t.parentNode.className=t.parentNode.className.replace(e?"bottom":"top",e?"top":"bottom"),t.style.borderTopLeftRadius=e?"0px":"var(--radius-box)",t.style.borderTopRightRadius=e?"0px":"var(--radius-box)",t.style.borderBottomLeftRadius=e?"var(--radius-box)":"0px",t.style.borderBottomRightRadius=e?"var(--radius-box)":"0px",this.textContent=e?"Move ↓":"Move ↑"};const t=n.parentNode.parentNode.parentNode.parentNode.querySelector("h2");t.parentNode?.appendChild(i)}if(X.Jt?.smartPlace){let t=document.querySelector("#bm-Z");if(!t){t=document.createElement("button"),t.id="bm-Z",t.textContent="Paint",t.className="btn btn-soft",t.onclick=function(){const t=Math.floor(W.W());let e=[];const n=new Set(X.ge());for(const t of X.qt.values())Object.entries(t.palette).forEach(([t,i])=>{if(!n.has(t))return;const o=l.get(t).id;X.Ce(o)&&e.extend(i.be.map(t=>[o,t]))});let i;if(0===e.length)return;try{const t=C(t=>{const e=t.transform.center;return[e.lat,e.lng]}),e=N(t[0],t[1]);i=[e[0][0]*X.tileSize+e[1][0],e[0][1]*X.tileSize+e[1][1]]}catch{const t=e[Math.floor(Math.random()*e.length)][1];i=[t[0][0]*X.tileSize+t[1][0],t[0][1]*X.tileSize+t[1][1]]}if(e.length<=t);else if(e.length<5e3)e=e.sort(([t,e],[n,o])=>{const s=[e[0][0]*X.tileSize+e[1][0],e[0][1]*X.tileSize+e[1][1]],r=[o[0][0]*X.tileSize+o[1][0],o[0][1]*X.tileSize+o[1][1]];return Math.sqrt(Math.pow(s[0]-i[0],2)+Math.pow(s[1]-i[1],2))*(1+.2*Math.random())-Math.sqrt(Math.pow(r[0]-i[0],2)+Math.pow(r[1]-i[1],2))*(1+.2*Math.random())}).slice(0,t);else{const n={},o=[];e.forEach(([t,e])=>{const o=[e[0][0]*X.tileSize+e[1][0],e[0][1]*X.tileSize+e[1][1]],s=Math.floor(Math.sqrt(Math.pow(o[0]-i[0],2)+Math.pow(o[1]-i[1],2))*(1+.2*Math.random()));void 0===n[s]?n[s]=[[t,e]]:n[s].push([t,e])});const s=Object.keys(n).sort((t,e)=>t-e);for(const e of s)if(o.extend(n[e]),o.length>=t)break;e=o.slice(0,t)}const o=document.querySelector("canvas.maplibregl-canvas");E(e[0][1][0],e[0][1][1]);const s=!x();setTimeout(()=>{let t=e[0][0];document.getElementById("color-"+t).click();const n=[e[0][1][0][0]*X.tileSize+e[0][1][1][0],e[0][1][0][1]*X.tileSize+e[0][1][1][1]],i=[o.offsetWidth/2,o.offsetHeight/2],r=s?2.048:C(t=>t.transform.tileSize*t.transform.scale/2048e3);for(let s=0;s{t.parentElement.classList.contains("bm-1c")||(t.addEventListener("click",function(){X.we()&&setTimeout(()=>{X.Y(),buildColorFilterList()},0)}),t.parentElement.classList.add("bm-1c"))})}).observe(document.body,{childList:!0,subtree:!0}),s(`%c${G}%c (${J}) userscript has loaded!`,"color: cornflowerblue;","")});var _=()=>{try{const[[t,e],[n,i]]=u(),o={tx:t,ty:e,px:n,py:i};GM.setValue("bmCoords",JSON.stringify(o))}catch(t){}},V=()=>{try{const[[t,e],[n,i]]=u();E([t,e],[n,i])}catch(t){}}})();