diff --git a/.gitignore b/.gitignore index d663d5d3..eb3ea057 100644 --- a/.gitignore +++ b/.gitignore @@ -23,9 +23,9 @@ coverage # Compiled binary addons (http://nodejs.org/api/addons.html) build/Release -# Dependency directory -# https://docs.npmjs.com/misc/faq#should-i-check-my-node-modules-folder-into-git -node_modules +node_modules/* +!node_modules/_app + Factorio* /factorio /instances @@ -34,6 +34,10 @@ Factorio* database/items.db config.json package-lock.json +mod_cache.json +static/pictures/spritesheet.js +static/pictures/spritesheet.png +static/external # weird pattern to ignore sharedPlugins except not ignore some core modules !sharedPlugins/ diff --git a/client.js b/client.js index 7e915c99..8b194ce9 100644 --- a/client.js +++ b/client.js @@ -12,9 +12,11 @@ const _ = require('underscore'); const deepmerge = require("deepmerge"); const getMac = require('getmac').getMac; const rmdirSync = require('rmdir-sync'); +const ioClient = require("socket.io-client"); + // internal libraries const objectOps = require("./lib/objectOps.js"); -const fileOps = require("./lib/fileOps.js"); +const fileOps = require("_app/fileOps"); const stringUtils = require("./lib/stringUtils.js"); const modManager = require("./lib/manager/modManager.js"); const configManager = require("./lib/manager/configManager.js"); @@ -77,7 +79,9 @@ if (!command || command == "help" || command == "--help") { console.error("node client.js list"); console.error("node client.js delete [instance]"); console.error("To download the latest version of the Clusterio lua mod, do"); - console.error("node client.js download"); + console.error("node client.js manage shared mods download clusterio"); + console.error("For more management options, do"); + console.error("node client.js manage"); process.exit(1); } else if (command == "list") { let instanceNames = fileOps.getDirectoriesSync("./instances/"); @@ -128,7 +132,7 @@ if (!command || command == "help" || command == "--help") { //const fullUsage = 'node client.js manage [instance, "shared"] ["mods", "config"] ...'; function usage(instance, tool, action){ if(tool && tool == "mods"){ - console.log('node client.js manage '+instance+' '+tool+' ["list", "search", "update"]'); + console.log('node client.js manage '+instance+' '+tool+' ["list", "search", "add", "remove", "update"]'); } else if(tool && tool == "config") { console.log('node client.js manage '+instance+' '+tool+' ["list", "edit"]'); } else { @@ -144,6 +148,10 @@ if (!command || command == "help" || command == "--help") { modManager.listMods(instance); } else if(action == "search"){ modManager.findMods(process.argv[6]); + } else if(action == "add" || action == "download"){ + modManager.addMod(process.argv[6], instance); + } else if(action == "remove" || action == "rm" || action == "delete"){ + modManager.removeMod(process.argv[6], instance); } else if(action == "update"){ modManager.updateAllMods(); } else { @@ -224,8 +232,8 @@ write-data=__PATH__executable__/../../../instances/" + instance + "\r\n\ // this line is probably not needed anymore but Im not gonna remove it fs.copySync('sharedMods', instancedirectory + "/mods"); let instconf = { - "factorioPort": process.env.FACTORIOPORT | Math.floor(Math.random() * 65535), - "clientPort": process.env.RCONPORT | Math.floor(Math.random() * 65535), + "factorioPort": process.env.FACTORIOPORT || Math.floor(Math.random() * 65535), + "clientPort": process.env.RCONPORT || Math.floor(Math.random() * 65535), "clientPassword": Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 8), } console.log("Clusterio | Created instance with settings:") @@ -409,6 +417,16 @@ write-data=__PATH__executable__/../../../instances/" + instance + "\r\n\ // ensure instancemanagement only ever runs once _.once(instanceManagement); function instanceManagement() { + /* Open websocket connection to master */ + var socket = ioClient("http://"+config.masterIP+":"+config.masterPort); + socket.on("hello", data => { + console.log("SOCKET | registering slave!"); + socket.emit("registerSlave", { + instanceID: instanceconfig.unique, + }); + setInterval(B=> socket.emit("heartbeat"), 10000); + }); + console.log("Started instanceManagement();"); // load plugins and execute onLoad event let pluginDirectories = fileOps.getDirectoriesSync("./sharedPlugins/"); @@ -448,21 +466,27 @@ function instanceManagement() { fs.writeFileSync(instancedirectory + "/script-output/" + pluginConfig.scriptOutputFileSubscription, ""); } global.subscribedFiles[pluginConfig.scriptOutputFileSubscription] = true; + console.log("Clusterio | Registered file subscription on "+instancedirectory + "/script-output/" + pluginConfig.scriptOutputFileSubscription); + fs.watch(instancedirectory + "/script-output/" + pluginConfig.scriptOutputFileSubscription, fileChangeHandler); + // run once in case a plugin wrote out information before the plugin loaded fully + fileChangeHandler(false, pluginConfig.scriptOutputFileSubscription); - fs.watch(instancedirectory + "/script-output/" + pluginConfig.scriptOutputFileSubscription, function (eventType, filename) { - if (filename == null) return; - // get array of lines in file - let stuff = fs.readFileSync(instancedirectory + "/script-output/" + filename, "utf8").split("\n"); - // if you found anything, reset the file - if (stuff[0]) { - fs.writeFileSync(instancedirectory + "/script-output/" + filename, ""); - } - for (let i = 0; i < stuff.length; i++) { - if (stuff[i]) { - plugins[I].scriptOutput(stuff[i]); + // send file contents to plugin for processing + function fileChangeHandler(eventType, filename) { + if(filename != null){ + // get array of lines in file + let stuff = fs.readFileSync(instancedirectory + "/script-output/" + filename, "utf8").split("\n"); + // if you found anything, reset the file + if (stuff[0]) { + fs.writeFileSync(instancedirectory + "/script-output/" + filename, ""); + } + for(let i = 0; i < stuff.length; i++) { + if(stuff[i]) { + plugins[I].scriptOutput(stuff[i]); + } } } - }); + } } console.log("Clusterio | Loaded plugin " + pluginDirectories[i]); } else if(pluginConfig.binary != "nodePackage"){ @@ -565,7 +589,8 @@ function instanceManagement() { playerCount: instanceInfo.playerCount || 0, instanceName: instance, } - getMac(function (err, mac) { + + function callback(err, mac) { if (err) { console.log("##### getMac crashed, but we don't really give a shit because we are probably closing down #####"); } else { @@ -581,7 +606,12 @@ function instanceManagement() { } }); } - }); + } + if(global.mac){ + callback(undefined, global.mac); + } else { + getMac(callback); + } },1000)}); } }); @@ -777,7 +807,7 @@ function instanceManagement() { messageInterface("/silent-command remote.call('clusterio', 'importMany', '" + sadas + "')"); sadas = null; } - }, 3000); + }, 1000); // COMBINATOR SIGNALS --------------------------------------------------------- // get inventory from Master and RCON it to our slave setInterval(function () { @@ -786,6 +816,7 @@ function instanceManagement() { console.log("Unable to get JSON master/api/inventory, master might be unaccessible"); } else if (response && response.body) { // Take the inventory we (hopefully) got and turn it into the format LUA accepts + if(Buffer.isBuffer(response.body)) {console.log(response.body.toString("utf-8")); throw new Error();} // We are probably contacting the wrong webserver try { var inventory = JSON.parse(response.body); } catch (e){ @@ -804,63 +835,67 @@ function instanceManagement() { } }); }, 1000); - // REMOTE SIGNALLING - // send any signals the slave has been told to send - setInterval(function () { - // Fetch combinator signals from the server - needle.post(config.masterIP + ":" + config.masterPort + '/api/readSignal', { - since: lastSignalCheck - }, function (err, response, body) { - if (response && response.body) { - if(typeof response.body == "string") response.body = JSON.parse(response.body); - // Take the new combinator frames and compress them so we can use a single command - let frameset = []; - for (let i = 0; i < response.body.length; i++) { - frameset[i] = response.body[i].frame; - } - // console.log(frameset); - // Send all our compressed frames - messageInterface("/silent-command remote.call('clusterio', 'receiveMany', '" + JSON.stringify(frameset) + "')"); - } - }); - // after fetching all the latest frames, we take a timestamp. During the next iteration, we fetch all frames submitted after this. - lastSignalCheck = Date.now(); - - // get outbound frames from file and send to master - // get array of lines in file, each line should correspond to a JSON encoded frame - let signals = fs.readFileSync(instancedirectory + "/script-output/txbuffer.txt", "utf8").split("\n"); - // if we actually got anything from the file, proceed and reset file - if (signals[0]) { - fs.writeFileSync(instancedirectory + "/script-output/txbuffer.txt", ""); - // loop through all our frames - for (let i = 0; i < signals.length; i++) { - (function (i) { - if (signals[i]) { - // signals[i] is a JSON array called a "frame" of signals. We timestamp it for storage on master - // then we unpack and RCON in this.frame to the game later. - let framepart = JSON.parse(signals[i]); - let doneframe = { - time: Date.now(), - frame: framepart, // thats our array of objects(single signals); - } - // console.log(doneframe); - needle.post(config.masterIP + ":" + config.masterPort + '/api/setSignal', doneframe, function (err, response, body) { - if (response && response.body) { - // In the future we might be interested in whether or not we actually manage to send it, but honestly I don't care. - } - }); - } - })(i); - } + // Make sure world has its worldID + setTimeout(function(){ + messageInterface("/silent-command remote.call('clusterio','setWorldID',"+instanceconfig.unique+")") + }, 20000); + /* REMOTE SIGNALLING + * send any signals the slave has been told to send + * Fetch combinator signals from the server + */ + socket.on("processCombinatorSignal", circuitFrameWithMeta => { + if(circuitFrameWithMeta && typeof circuitFrameWithMeta == "object" && circuitFrameWithMeta.frame && Array.isArray(circuitFrameWithMeta.frame)){ + messageInterface("/silent-command remote.call('clusterio', 'receiveFrame', '"+JSON.stringify(circuitFrameWithMeta.frame)+"')"); } - }, 1000); + }); + // get outbound frames from file and send to master + // get array of lines in file, each line should correspond to a JSON encoded frame + let signals = fs.readFileSync(instancedirectory + "/script-output/txbuffer.txt", "utf8").split("\n"); + // if we actually got anything from the file, proceed and reset file + let readingTxBufferSoon = false; + let txBufferClearCounter = 0; + fs.watch(instancedirectory + "/script-output/txbuffer.txt", "utf-8", (eventType, filename) => { + if(!readingTxBufferSoon){ // use a 100ms delay to avoid messing with rapid sequential writes from factorio (I think that might be a problem maybe?) + readingTxBufferSoon = true; + setTimeout(()=>{ + txBufferClearCounter++; + fs.readFile(instancedirectory + "/script-output/txbuffer.txt", "utf-8", (err, signals) => { + signals = signals.split("\n"); + if (signals[0]) { + //if(txBufferClearCounter > 500){ + fs.writeFileSync(instancedirectory + "/script-output/txbuffer.txt", ""); + // txBufferClearCounter = 0; + //} + + // loop through all our frames + for (let i = 0; i < signals.length; i++) { + if (signals[i] && objectOps.isJSON(signals[i])) { + // signals[i] is a JSON array called a "frame" of signals. We timestamp it for storage on master + // then we unpack and RCON in this.frame to the game later. + let framepart = JSON.parse(signals[i]); + let doneframe = { + time: Date.now(), + frame: framepart, // thats our array of objects(single signals); + } + // send to master using socket.io, opened at the top of instanceManagement() + socket.emit("combinatorSignal", doneframe); + } else { + // console.log("Invalid jsony: "+typeof signals[i]) + } + } + } + }); + readingTxBufferSoon = false; + },100); + } + }); } // END OF INSTANCE START --------------------------------------------------------------------- // string, function // returns [{modName:string,hash:string}, ... ] function hashMods(instanceName, callback) { if(!callback) { - throw "ERROR in function hashMods NO CALLBACK" + throw new Error("ERROR in function hashMods NO CALLBACK"); } function callback2(hash, modName){ hashedMods[hashedMods.length] = { @@ -868,22 +903,23 @@ function hashMods(instanceName, callback) { hash: hash, } // check if this callback has ran once for each mod - if(hashedMods.length == /*mods.length*/ + instanceMods.length) { + if(hashedMods.length == instanceMods.length) { callback(hashedMods); } //console.log(modname); } let hashedMods = []; - var i = 0; /*let mods = fs.readdirSync("./sharedMods/")*/ let instanceMods = fs.readdirSync("./instances/"+instanceName+"/mods/"); - - for(o=0;o{ + it("Creates a folder with a .crt and .key file in it", ()=>{ + let certPath = "lib/certTestPlsDelete"; + assert(!fs.existsSync(certPath)); // if it already exsits, the test might pass because of leftover data (which is bad) + + generateSSLcert({ + // bits:512, // supported, but I just use the default of 2048 for this test + certificatePath:certPath, + doLogging: false, + }); + + assert(fs.existsSync(certPath)); + assert(fs.existsSync(certPath+"/cert.key")); // private key + assert(fs.existsSync(certPath+"/cert.crt")); // certificate file + + // remove certificates and data from the test + fileOps.deleteFolderRecursiveSync(certPath); + }).timeout(10000); +}); \ No newline at end of file diff --git a/lib/getInstances.js b/lib/getInstances.js index 5e1d9449..6aeb540f 100644 --- a/lib/getInstances.js +++ b/lib/getInstances.js @@ -1,4 +1,4 @@ -const fileOps = require("./fileOps.js"); +const fileOps = require("_app/fileOps"); module.exports = { sync: function(){ diff --git a/lib/manager/modManager.js b/lib/manager/modManager.js index 48e6dbc4..1f8d53a8 100644 --- a/lib/manager/modManager.js +++ b/lib/manager/modManager.js @@ -6,12 +6,23 @@ Provides tools to manage mods in a clusterio install const rightpad = require("right-pad"); const asTable = require("as-table").configure({delimiter: ' | '}); const moment = require("moment"); - +const syncRequest = require("sync-request"); +const fs = require("fs"); +const https = require('follow-redirects').https; const factorioAPI = require("node-factorio-api"); -const fileOps = require("./../fileOps.js"); +const sLog = require("single-line-log").stdout; + +const fileOps = require("_app/fileOps"); const config = require("./../../config"); const instances = require("./../getInstances.js").sync(); + +function ellipse(str, max){ + return str.length > (max - 3) ? str.substring(0,max-3) + '...' : str; +} +// https://stackoverflow.com/questions/15900485/correct-way-to-convert-size-in-bytes-to-kb-mb-gb-in-javascript +function formatBytes(a,b){if(0==a)return"0 Bytes";var c=1024,d=b||2,e=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],f=Math.floor(Math.log(a)/Math.log(c));return parseFloat((a/Math.pow(c,f)).toFixed(d))+" "+e[f]}; + /** Lists mods for an instance as a table. Warning, handles printing internally. @param {string} instance - Name of the instance or "shared" @@ -25,14 +36,13 @@ modManager.listMods("shared"); */ module.exports.listMods = function(instance){ if(instance && instances.includes(instance)){ - factorioAPI.init(false, 'instances/'+instance+'/instanceMods', 'instances/'+instance+'/saves', '0.15.37'); - console.log("Authenticating to factorio.com...") + factorioAPI.init(false, 'instances/'+instance+'/instanceMods', 'instances/'+instance+'/saves', '0.16.15'); factorioAPI.authenticate({ username: config.username, token: config.token, require_ownership: false }).then(token => { - console.log("Currently installed:"); + console.log("* Currently installed:"); factorioAPI.readModZips().then(list => { console.log(asTable(list.map(mod => { return { @@ -44,26 +54,25 @@ module.exports.listMods = function(instance){ } }))); }); - // Deactivated due to bug in node-factorio-api, see https://github.com/Danacus/node-factorio-api/issues/2 + // Had issues earlier due to bug in node-factorio-api, see https://github.com/Danacus/node-factorio-api/issues/2 // bug is resolved, thanks to @Danacus and @brotherpot - /*factorioAPI.getModsFromSaves().then(list => { - console.log("Mods used in save:"); - console.log(JSON.stringify(list)) + factorioAPI.getModsFromSaves().then(list => { + console.log("* Mods used in save:"); console.log(asTable(list[0].mods)) - });*/ + }); }).catch(reason => { console.log("Failed to authenticate to factorio.com! Please check your connection and the username+token used for authentication in config.json"); }); } else { // list shared mods in /sharedMods/ - factorioAPI.init(false, 'sharedMods/', '', '0.15.37'); - console.log("Authenticating to factorio.com...") + factorioAPI.init(false, 'sharedMods/', '', '0.16.15'); factorioAPI.authenticate({ username: config.username, token: config.token, require_ownership: false }).then(() => { - console.log("Mods shared by all instances:") + console.log("\r\n") + console.log("* Mods shared by all instances:") factorioAPI.getInstalledMods().then(mods => { console.log(asTable(mods)); }); @@ -85,20 +94,16 @@ the results to console as a neat looking table */ module.exports.findMods = function(searchTerm){ factorioAPI.init(false); - console.log("Authenticating to factorio.com...") factorioAPI.authenticate({ username: config.username, token: config.token, require_ownership: false }).then(token => { - factorioAPI.searchMods( - {q: searchTerm, order: 'top', page_size: 20} - ).then(body => { - let mods = body.results; - console.log(asTable(mods.map(mod => { + factorioAPI.searchMods(searchTerm).then(mods => { + console.log(asTable(mods.reverse().map(mod => { return { - title:mod.title, - name:mod.name, + title:ellipse(mod.title, 50), + name:ellipse(mod.name, 30), downloads:mod.downloads_count, updated: moment(mod.updated_at).format("DD.MM.YY"), owner:mod.owner, @@ -109,9 +114,99 @@ module.exports.findMods = function(searchTerm){ }); } +module.exports.addMod = function(term, instance){ + if(instance == "shared"){ // modDirectory has to end in / + var modDirectory = "sharedMods/"; + } else { + var modDirectory = "instances/"+instance+"/instanceMods/"; + } + if(term && term.length > 0){ + if(term.includes("mods.factorio.com/mods/")){ // https://mods.factorio.com/mods/Danielv123/ChooChoo + // treat it as a link download + factorioAPI.init(false, modDirectory, "", "0.16.15"); + factorioAPI.authenticate({ + username: config.username, + token: config.token, + require_ownership: false + }).then(() => { + factorioAPI.searchMods(term.split("/")[term.split("/").length-1]).then(body => { + console.log("Im gonna download: "+body[0].name); + factorioAPI.downloadMod(body[0]).then(()=>{ + console.log("Mod downloaded"); + }); + }); + }); + } else if(term.includes("github.com")){ // https://github.com/Danielv123/factorioClusterioMod + // treat it as a github releases download + let apiURL = "https://api.github.com/repos/" + term.split("/")[3] + "/" + term.split("/")[4] + "/releases"; // https://api.github.com/repos/Danielv123/factorioClusterioMod/releases + + let res = syncRequest('GET', apiURL, {"headers":{"User-Agent":"Fuck you for requiring user agents!"}}); + let url = JSON.parse(res.getBody())[0].assets[0].browser_download_url; + let name = JSON.parse(res.getBody())[0].assets[0].name; + if(url) { + console.log("Downloading " + url); + let file = fs.createWriteStream(modDirectory + name); + let bytesDownloaded = 0; + let downloadStartTime = Date.now(); + https.get(url, function(response) { + let bytesToDownload = response.headers['content-length']; + response.pipe(file); + response.on("data", chunk => { + bytesDownloaded += chunk.length; + let downloadTimeElapsed = Date.now() - downloadStartTime; + let bytesPerSecond = bytesDownloaded / (downloadTimeElapsed/1000); + let timeToComplete = Math.floor((bytesToDownload - bytesDownloaded)/bytesPerSecond); + sLog("Downloading "+name+" "+(bytesDownloaded/bytesToDownload*100).toPrecision(3)+"% ("+formatBytes(bytesDownloaded)+" / "+formatBytes(bytesToDownload)+")\r\n"+ + "about "+timeToComplete+" seconds remaining ("+formatBytes(bytesPerSecond)+"/s)"); + }).on("end", x => { + sLog.clear(); + console.log(" Downloaded in "+moment.utc(moment.duration(Date.now()-downloadStartTime).as('milliseconds')).format('mm:ss')); // because sLog.clear() doesn't seem to do the job of ending the line properly + }); + }); + } + } else { + // treat it as a search and download the top result + factorioAPI.init(false, modDirectory, "", "0.16.15"); + factorioAPI.authenticate({ + username: config.username, + token: config.token, + require_ownership: false + }).then(() => { + factorioAPI.searchMods(term).then(body => { + console.log("Im gonna download: "+body[0].name); + factorioAPI.downloadMod(body[0]).then(()=>{ + console.log("Mod downloaded"); + }); + }); + }); + } + } +} +module.exports.removeMod = function removeMod(term, instance, force = false){ + if(instance == "shared"){ // modDirectory has to end in / + var modDirectory = "sharedMods/"; + } else { + var modDirectory = "instances/"+instance+"/instanceMods/"; + } + if(term && typeof term == "string" && term.length > 0){ + let mods = fs.readdirSync(modDirectory); + let modsMatchingFilter = mods.filter(mod => mod.toLowerCase().includes(term.toLowerCase())); + if(modsMatchingFilter.length < 1){ + console.log("No mods found matching search"); + } else if(modsMatchingFilter.length == 1){ + console.log("Deleting "+modsMatchingFilter[0]); + fs.unlinkSync(modDirectory+modsMatchingFilter[0]); + console.log("Deleted."); + } else if(modsMatchingFilter.length > 1){ + console.log("Found multiple mods, not doing anything"); + modsMatchingFilter.forEach(mod => console.log(mod)); + } + } +} + // 'https://api.github.com/repos/Danielv123/factorioClusterioMod/releases' /** -Download mod from github repo by looking for the first binary download in +Download mod from github repo by looking for the first binary download in the latest release, saving it to /sharedMods @param {string} url a github repo URL, for example https://api.github.com/repos/Danielv123/factorioClusterioMod/releases. Must link to /releases diff --git a/lib/npmPostinstall.js b/lib/npmPostinstall.js index c0e6beae..8106fad4 100644 --- a/lib/npmPostinstall.js +++ b/lib/npmPostinstall.js @@ -1,18 +1,136 @@ var mkdirp = require("mkdirp"); +var http = require('http'); +var https = require('https'); +var fs = require('fs'); + +var modManager = require("./manager/modManager.js"); + +modManager.addMod("clusterio", "shared"); + +function makeDirectory(path){ + return new Promise((resolve, reject) => { + mkdirp(path, function(err){ + if(err){ + console.error("Unable to mkdirp "+path); + console.error(err); + resolve(false); + } else { + console.log("mkdirp "+path); + resolve(true); + } + }); + }); +} +function download(url, file, callback){ + return new Promise((resolve, reject) => { + let pathArray = file.split("/"); + pathArray.pop(); // remove filename from the end + if(pathArray.length >= 1){ + // this might be an invalid path! + fs.stat(pathArray.join("/"), (err, stat) => { + if(err){ + makeDirectory(pathArray.join("/")).then(()=>{ + doDownload(url, file, callback); + }); + } else { + doDownload(url, file, callback); + } + }); + } else { + doDownload(url, file, callback); + } + function doDownload(url, file, callback){ + var writeStream = fs.createWriteStream(file); + let protocol = http; + if(url.split(":")[0] == "https") protocol = https; + var request = protocol.get(url, function(response) { + response.pipe(writeStream); + response.on("end", () => { + if(callback && typeof callback == "function") callback(file); + console.log("Downloaded "+file+" from "+url); + resolve(); + }); + }); + } + }); +} var directories = [ "database/linvodb", "sharedMods", "instances", ]; +let downloadList = [ + { + url: "http://fbpviewer.trakos.pl/images/spritesheet.json", + file: "static/pictures/spritesheet.js", + callback: function(file){ + fs.writeFileSync("static/pictures/spritesheet.js", "export default\n"+fs.readFileSync("static/pictures/spritesheet.js")); + }, + }, + { + url: "http://fbpviewer.trakos.pl/images/spritesheet.png", + file: "static/pictures/spritesheet.png", + }, + { + url: "https://code.jquery.com/jquery.js", + file: "static/external/jquery.js", + }, + { + url: "https://code.jquery.com/ui/1.12.1/jquery-ui.js", + file: "static/external/jquery-ui.js", + }, + { + url: "https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/canvasjs.js", + file: "static/external/canvasjs.js", + }, + { + url: "https://momentjs.com/downloads/moment.min.js", + file: "static/external/moment.min.js", + }, + { + url: "https://craig.global.ssl.fastly.net/js/mousetrap/mousetrap.min.js", + file: "static/external/mousetrap.min.js", + }, + { + url: "https://fonts.googleapis.com/css?family=Roboto", + file: "static/external/css/Roboto.css", + }, + { + url: "https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js", + file: "static/external/socket.io.js", + }, +] -directories.forEach(path => { - mkdirp("database/linvodb", function(err){ - if(err){ - console.error("Unable to mkdirp "+path); - console.error(err); +// initiate folder creations and downloads +processMkdirRecursive(processDownloadRecursive); +function processMkdirRecursive(callback){ + let item = directories.shift(); + makeDirectory(item).then(()=>{ + if(directories.length == 0){ + if(callback) callback(); } else { - console.log("mkdirp "+path); + processMkdirRecursive(callback); } }); -}) +} +function processDownloadRecursive(callback){ + let item = downloadList.shift(); + download(item.url, item.file, item.callback).then(()=>{ + if(downloadList.length == 0){ + if(callback) callback(); + } else { + processDownloadRecursive(callback); + } + }); +} + +// generate SSL certificates if they are missing +if(!fs.existsSync("database/certificates") || !fs.existsSync("database/certificates/cert.crt") || !fs.existsSync("database/certificates/cert.key")){ + var generateSSLcert = require("./generateSSLcert.js"); + + generateSSLcert({ + certificatePath: "database/certificates", + doLogging: true, + }); +} \ No newline at end of file diff --git a/master.js b/master.js index 83a4278f..9c4e289f 100644 --- a/master.js +++ b/master.js @@ -63,6 +63,49 @@ app.use(express.static('static')); // mod downloads app.use(express.static(masterModFolder)); +// set up logging software +const prometheusPrefix = "clusterio_"; +const Prometheus = require('prom-client'); +Prometheus.collectDefaultMetrics({ timeout: 10000 }); // collects RAM usage etc every 10 s +const httpRequestDurationMilliseconds = new Prometheus.Histogram({ + name: prometheusPrefix+'http_request_duration_ms', + help: 'Duration of HTTP requests in ms', + labelNames: ['route'], + // buckets for response time from 0.1ms to 500ms + buckets: [0.10, 5, 15, 50, 100, 200, 300, 400, 500] +}); +const endpointHitCounter = new Prometheus.Gauge({ + name: prometheusPrefix+'endpoint_hit_gauge', + help: "How many requests a particular endpoint has gotten", + labelNames: ['route'], +}); +const prometheusConnectedInstancesCounter = new Prometheus.Gauge({ + name: prometheusPrefix+'connected_instaces_gauge', + help: "How many instances are currently connected to this master server", +}); +const prometheusWsUsageCounter = new Prometheus.Counter({ + name: prometheusPrefix+'websocket_usage_counter', + help: 'Websocket traffic', + labelNames: ["connectionType"], +}); +setInterval(()=>{ + let numberOfActiveSlaves = 0; + for(let instance in slaves){ + if(Date.now() - Number(slaves[instance].time) < 1000 * 30) numberOfActiveSlaves++; + } + prometheusConnectedInstancesCounter.set(numberOfActiveSlaves); +},10000); +/** +Prometheus metrics endpoint. Returns performance and usage metrics in a prometheus readable format. +*/ +app.get('/metrics', (req, res) => { + endpointHitCounter.labels(req.route.path).inc(); + let reqStartTime = Date.now(); + res.set('Content-Type', Prometheus.register.contentType); + res.end(Prometheus.register.metrics()); + httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime); +}); + // set up database var Datastore = require('nedb'); db = {}; @@ -145,6 +188,8 @@ process.on('SIGINT', function () { // world ID management // slaves post here to tell the server they exist app.post("/api/getID", function(req,res) { + endpointHitCounter.labels(req.route.path).inc(); + let reqStartTime = Date.now(); // request.body should be an object // {rconPort, rconPassword, serverPort, mac, time} // time us a unix timestamp we can use to check for how long the server has been unresponsive @@ -163,9 +208,12 @@ app.post("/api/getID", function(req,res) { } console.log("Slave registered: " + slaves[req.body.unique].mac + " : " + slaves[req.body.unique].serverPort+" at " + slaves[req.body.unique].publicIP + " with name " + slaves[req.body.unique].instanceName); } + httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime); }); app.post("/api/editSlaveMeta", function(req,res) { + endpointHitCounter.labels(req.route.path).inc(); + let reqStartTime = Date.now(); // request.body should be an object // {instanceID, pass, meta:{x,y,z}} @@ -181,6 +229,7 @@ app.post("/api/editSlaveMeta", function(req,res) { res.send("ERROR: Invalid instanceID or password") } } + httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime); }); app.post("/api/getSlaveMeta", function (req, res) { @@ -206,6 +255,8 @@ app.post("/api/getSlavesMeta", function (req, res) { // mod management // should handle uploading and checking if mods are uploaded app.post("/api/checkMod", function(req,res) { + endpointHitCounter.labels(req.route.path).inc(); + let reqStartTime = Date.now(); let files = fs.readdirSync(masterModFolder); let found = false; files.forEach(file => { @@ -220,25 +271,31 @@ app.post("/api/checkMod", function(req,res) { res.send("found"); } res.end(); + httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime); }); app.post("/api/uploadMod", function(req,res) { + endpointHitCounter.labels(req.route.path).inc(); + let reqStartTime = Date.now(); if (!req.files) { res.send('No files were uploaded.'); return; } else { console.log(req.files.file); req.files.file.mv('./database/masterMods/'+req.files.file.name, function(err) { - if (err) { - res.status(500).send(err); - } else { - res.send('File uploaded!'); - console.log("Uploaded mod: " + req.files.file.name); - } - }); + if (err) { + res.status(500).send(err); + } else { + res.send('File uploaded!'); + console.log("Uploaded mod: " + req.files.file.name); + } + httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime); + }); } }); // endpoint for getting information about all our slaves app.get("/api/slaves", function(req, res) { + endpointHitCounter.labels(req.route.path).inc(); + let reqStartTime = Date.now(); res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); let copyOfSlaves = JSON.parse(JSON.stringify(slaves)); @@ -247,6 +304,7 @@ app.get("/api/slaves", function(req, res) { copyOfSlaves[key].rconPassword = "hidden"; } res.send(copyOfSlaves); + httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime); }); var recievedItemStatisticsBySlaveID = {}; var sentItemStatisticsBySlaveID = {}; @@ -268,6 +326,8 @@ POST endpoint for storing items in master's inventory. @returns {string} status either "success" or "failure" */ app.post("/api/place", function(req, res) { + endpointHitCounter.labels(req.route.path).inc(); + let reqStartTime = Date.now(); res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); let x; @@ -318,6 +378,7 @@ app.post("/api/place", function(req, res) { } else { res.send("failure"); } + httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime); }); /** POST endpoint to remove items from DB when client orders items. @@ -332,6 +393,8 @@ POST endpoint to remove items from DB when client orders items. */ _doleDivisionFactor = {}; //If the server regularly can't fulfill requests, this number grows until it can. Then it slowly shrinks back down. app.post("/api/remove", function(req, res) { + endpointHitCounter.labels(req.route.path).inc(); + let reqStartTime = Date.now(); const doleDivisionRetardation = 10; //lower rates will equal more dramatic swings const maxDoleDivision = 250; //a higher cap will divide the store more ways, but will take longer to recover as supplies increase res.header("Access-Control-Allow-Origin", "*"); @@ -382,10 +445,12 @@ app.post("/api/remove", function(req, res) { sentItemStatisticsBySlaveID[object.instanceID] = sentItemStatistics; } res.send({count: object.count, name: object.name}); + httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime); } else { // if we didn't have enough, attempt giving out a smaller amount next time _doleDivisionFactor[object.name] = Math.min(maxDoleDivision, Math.max((_doleDivisionFactor[object.name]||0)||1, 1) * 2); res.send({name:object.name, count:0}); + httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime); //console.log('failure out of ' + object.name + " | " + object.count + " from " + object.instanceID + " ("+object.instanceName+")"); } } @@ -403,8 +468,11 @@ Gives no response @param {number} circuitFrame.time */ app.post("/api/setSignal", function(req,res) { + endpointHitCounter.labels(req.route.path).inc(); + let reqStartTime = Date.now(); if(typeof req.body == "object" && req.body.time){ db.signals.insert(req.body); + httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime); // console.log("signal set"); } }); @@ -417,12 +485,15 @@ POST endpoint to read database of circuit signals sent to master @returns {object} circuitFrame */ app.post("/api/readSignal", function(req,res) { + endpointHitCounter.labels(req.route.path).inc(); + let reqStartTime = Date.now(); // request.body should be an object // {since:UNIXTIMESTAMP,} // we should send an array of all signals since then db.signals.find({time:{$gte: req.body.since}}, function (err, docs) { // $gte means greater than or equal to, meaning we only get entries newer than the timestamp res.send(docs); + httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime); // console.log(docs); }); }); @@ -436,6 +507,8 @@ GET endpoint to read the masters current inventory of items. */ // endpoint for getting an inventory of what we got app.get("/api/inventory", function(req, res) { + endpointHitCounter.labels(req.route.path).inc(); + let reqStartTime = Date.now(); res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); // Check it and send it @@ -446,6 +519,7 @@ app.get("/api/inventory", function(req, res) { } } res.send(JSON.stringify(inventory)); + httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime); }); /** GET endpoint to read the masters inventory as an object with key:value pairs @@ -456,10 +530,13 @@ GET endpoint to read the masters inventory as an object with key:value pairs @returns {object} JSON {"iron-plate":100, "copper-plate":5} */ app.get("/api/inventoryAsObject", function(req, res) { + endpointHitCounter.labels(req.route.path).inc(); + let reqStartTime = Date.now(); res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); // Check it and send it res.send(JSON.stringify(db.items)); + httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime); }); // post flowstats here for production graphs @@ -476,6 +553,8 @@ course the timeSeries data. @returns {string} failure */ app.post("/api/logStats", function(req,res) { + endpointHitCounter.labels(req.route.path).inc(); + let reqStartTime = Date.now(); if(typeof req.body == "object" && req.body.instanceID && req.body.timestamp && req.body.data) { if(Number(req.body.timestamp) != NaN){ req.body.timestamp = Number(req.body.timestamp); @@ -492,6 +571,7 @@ app.post("/api/logStats", function(req,res) { } else { res.send("failure"); } + httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime); }); // {instanceID: string, fromTime: Date, toTime, Date} /** @@ -505,6 +585,8 @@ graphs and other IO statistics. @returns {object} - with statistics */ app.post("/api/getStats", function(req,res) { + endpointHitCounter.labels(req.route.path).inc(); + let reqStartTime = Date.now(); if(typeof req.body == "string"){ req.body = JSON.parse(req.body); } @@ -563,6 +645,7 @@ app.post("/api/getStats", function(req,res) { } } } + httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime); }); /** @@ -578,6 +661,8 @@ making up about 92% of the response body weight.) @returns {object[]} timeseries where each entry is a set point in time. */ app.post("/api/getTimelineStats", function(req,res) { + endpointHitCounter.labels(req.route.path).inc(); + let reqStartTime = Date.now(); console.log(req.body); if(typeof req.body == "object" && req.body.instanceID) { // if not specified, get stats for last 24 hours @@ -616,6 +701,7 @@ app.post("/api/getTimelineStats", function(req,res) { }); res.send(docs); + httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime); }); } }); @@ -628,9 +714,13 @@ GET endpoint. Returns factorio's base locale as a JSON object. @returns {object{}} 2 deep nested object with base game factorio locale as key:value pairs */ app.get("/api/getFactorioLocale", function(req,res){ - getFactorioLocale.asObject(config.factorioDirectory, "en", (err, factorioLocale) => res.send(factorioLocale)); + endpointHitCounter.labels(req.route.path).inc(); + let reqStartTime = Date.now(); + getFactorioLocale.asObject(config.factorioDirectory, "en", (err, factorioLocale) => { + res.send(factorioLocale); + httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime); + }); }); - var server = require("http").Server(app); server.listen(config.masterPort || 8080, function () { console.log("Listening on port %s...", server.address().port); @@ -673,53 +763,100 @@ class mapRequester { this.lastBeat = Date.now(); this.socket.on("heartbeat", () => { + prometheusWsUsageCounter.labels('heartbeat').inc(); // we aren't ready to die yet apparently this.lastBeat = Date.now(); }); this.socket.on("requestChunk", loc => { + prometheusWsUsageCounter.labels('requestChunk').inc(); loc.requesterID = this.requesterID; let instanceID = loc.instanceID || this.instanceID; if(slaveMappers[instanceID] && typeof loc.x == "number" && typeof loc.y == "number"){ - slaveMappers[instanceID].socket.emit("getChunk", loc) + slaveMappers[instanceID].socket.emit("getChunk", loc); } }); this.socket.on("requestEntity", req => { + prometheusWsUsageCounter.labels('requestEntity').inc(); req.requesterID = this.requesterID; let instanceID = req.instanceID || this.instanceID; if(slaveMappers[instanceID] && typeof req.x == "number" && typeof req.y == "number"){ - slaveMappers[instanceID].socket.emit("getEntity", req) + slaveMappers[instanceID].socket.emit("getEntity", req); + } + }); + this.socket.on("placeEntity", req => { + prometheusWsUsageCounter.labels('placeEntity').inc(); + req.requesterID = this.requesterID; + let instanceID = req.instanceID || this.instanceID; + if(slaveMappers[instanceID]){ + slaveMappers[instanceID].socket.emit("placeEntity", req); + } + }); + } +} +/* Websockets for send and recieve combinators */ +var wsSlaves = {}; +class wsSlave { + constructor(instanceID, socket){ + this.instanceID = instanceID; + this.socket = socket; + this.lastBeat = Date.now(); + + this.socket.on("heartbeat", () => { + prometheusWsUsageCounter.labels('heartbeat').inc(); + this.lastBeat = Date.now(); + }); + this.socket.on("combinatorSignal", circuitFrameWithMeta => { + prometheusWsUsageCounter.labels('combinatorSignal').inc(); + if(circuitFrameWithMeta && typeof circuitFrameWithMeta == "object"){ + Object.keys(wsSlaves).forEach(instanceID => { + wsSlaves[instanceID].socket.emit("processCombinatorSignal", circuitFrameWithMeta); + }); } }); } } io.on('connection', function (socket) { // cleanup dead sockets from disconnected people - Object.keys(mapRequesters).forEach(requesterName => { - let requester = mapRequesters[requesterName]; - if(requester.lastBeat < (Date.now() - 30000)){ - console.log("remoteMap | There are currently "+Object.keys(mapRequesters).length+" map requesters, deleting one on timeout"); - delete mapRequesters[requesterName]; // we have to use the full name here or we will only kill the pointer - } - }); - Object.keys(slaveMappers).forEach(mapperName => { - let mapper = slaveMappers[mapperName]; - if(mapper.lastBeat < (Date.now() - 30000)){ - console.log("remoteMap | There are currently "+Object.keys(slaveMappers).length+" mappers, deleting one on timeout"); - delete slaveMappers[mapperName]; // we have to use the full name here or we will only kill the pointer - } + let terminatedConnections = 0; + let currentConnections = Object.keys(mapRequesters).length + Object.keys(slaveMappers).length + Object.keys(wsSlaves).length; + [mapRequesters, slaveMappers, wsSlaves].forEach(list => { + Object.keys(list).forEach(connectionID => { + let connection = list[connectionID]; + if(connection.lastBeat < (Date.now() - 30000)){ + terminatedConnections++; + delete list[connectionID]; + } + }); }); + if(terminatedConnections > 0) console.log("SOCKET | There are currently "+currentConnections+" websocket connections, deleting "+terminatedConnections+" on timeout"); + + // tell our friend that we are listening socket.emit('hello', { hello: 'world' }); + + /* initial processing for remoteMap */ socket.on('registerSlaveMapper', function (data) { + prometheusWsUsageCounter.labels('registerSlaveMapper').inc(); slaveMappers[data.instanceID] = new slaveMapper(data.instanceID, socket); console.log("remoteMap | SOCKET registered map provider for "+data.instanceID); }); socket.on('registerMapRequester', function(data){ // data {instanceID:""} + prometheusWsUsageCounter.labels('registerMapRequester').inc(); let requesterID = Math.random().toString(); mapRequesters[requesterID] = new mapRequester(requesterID, socket, data.instanceID); socket.emit("mapRequesterReady", true); console.log("remoteMap | SOCKET registered map requester for "+data.instanceID); }); + + /* Websockets for send and recieve combinators */ + socket.on("registerSlave", function(data) { + prometheusWsUsageCounter.labels('registerSlave').inc(); + if(data && data.instanceID){ + wsSlaves[data.instanceID] = new wsSlave(data.instanceID, socket); + console.log("SOCKET | Created new wsSlave: "+ data.instanceID); + } + }); + }); module.exports = app; diff --git a/master.spec.js b/master.spec.js index 1b7fff6a..219f5278 100644 --- a/master.spec.js +++ b/master.spec.js @@ -35,6 +35,7 @@ describe('Master server endpoint testing', function() { }); // describe("#GET /api/") parallel("#GET static website data", function() { + this.timeout(6000); it("sends some HTML when accessing /", function(done){ this.timeout(6000); request(app).get("/").end(function(err,res){ @@ -80,7 +81,8 @@ describe('Master server endpoint testing', function() { request(app).get("/remoteMap").end(function(err,res){ assert.equal(res.statusCode, 200); validateHTML(res.text).then(result => { - assert(result.messages.length === 0, "there are HTML errors on the page, please fix: "+JSON.stringify(result.messages)); + // there should be 1 error regarding complaining about me using ES6 modules before they are fully supported + assert(result.messages.length === 1, "there are HTML errors on the page, please fix: "+JSON.stringify(result.messages)); done(); }); }); diff --git a/node_modules/_app/factorioServer/index.js b/node_modules/_app/factorioServer/index.js new file mode 100644 index 00000000..7407866e --- /dev/null +++ b/node_modules/_app/factorioServer/index.js @@ -0,0 +1,168 @@ +/** + +class factorioServer + +This class has the responsiblity of : + +* spawning a factorio server +* Handling input via stdin or RCON + + +*/ + +const fs = require("fs"); +const child_process = require("child_process"); +const path = require("path"); + +const mkdirp = require("mkdirp"); +const appRootPath = require("app-root-path"); + +const fileOps = require("_app/fileOps"); + +module.exports = class factorioServer { + constructor({ + factorioDirectory = "factorio", + instanceDirectory = "instances/data", + instanceName = "Default server name", + factorioPort = Math.floor(Math.random() * 65535), + serversettings = {}, + onProgress = function(type, a, b, c){ + if(type == "progress") console.log("Progress: ",a," of ",b," unit: ",c); + if(type == "log") console.log(a); + }, + } = {}){ + this.factorioDirectory = factorioDirectory; + this.instanceDirectory = instanceDirectory; + this.instanceName = instanceName; + this.factorioPort = factorioPort; + this.serversettings = Object.assign({ + "name": "Clusterio instance: " + this.instanceName, + "description": "Public factorio server running clusterio", + "tags": ["clusterio"], + "max_players": "20", + "visibility": "public", + "username": "", + "token": "", + "game_password": "", + "verify_user_identity": true, + "admins": ["Danielv123"], + "allow_commands": true, + "autosave_interval": 10, + "autosave_slots": 5, + "afk_autokick_interval": 0, + "auto_pause": false, + }, serversettings); + this.onProgress = (type, a, b, c) => { + if(typeof onProgress == "function") onProgress(type, a, b, c); + }; + } + async initialize(){ + if(!await this.isValidInstance()){ + await this.createInstance(); + } + return true; + } + async createInstance(path = this.instanceDirectory){ + if(await this.isValidInstance(path)){ + throw new Error("Instance already exists!"); + } + + // create folders + let folders = [ + "/script-output/", + "/saves/", + "/mods/", + "/instanceMods/", + ]; + mkdirp.sync(path); + folders.forEach(folder => mkdirp.sync(path + folder)); + + // create files + let files = [ + {name: "/script-output/output.txt", content: ""}, + {name: "/script-output/orders.txt", content: ""}, + {name: "/script-output/txbuffer.txt", content: ""}, + {name: "/config.ini", content: "[path]\r\n\ read-data=__PATH__executable__/../../data\r\n\ write-data=__PATH__executable__/../../../" + this.instanceDirectory + "\r\n\ "}, + {name: "/config.json", content: JSON.stringify({ + factorioPort: this.factorioPort, + clientPassword: Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 8), + }, null, 4)}, + {name: "/server-settings.json", content: JSON.stringify(this.serversettings, null, 4)}, + ]; + files.forEach(file => { + fs.writeFile(path + file.name, file.content, doneWritingHandler); + // console.log("Created: ",path+file.name); + }); + + let filesToWrite = files.length; + function doneWritingHandler(){ + if(!--filesToWrite){ + return path; + } + } + } + async deleteInstance(path = this.instanceDirectory){ + if(await this.isValidInstance(path)){ + await fileOps.deleteFolderRecursive(path); + return true; + } else { + return false; + } + } + isValidInstance(path = this.instanceDirectory){ + return new Promise((resolve, reject) => { + fs.stat(path, (err, stat) => { + if(err){ + // console.log(err) + resolve(false); + } else { + // the instance folder exists, do some more checks + fs.readdir(path, (err, files) => { + if(files && Array.isArray(files)){ + let foldersThatShouldBeThere = [ + "script-output", + "saves", + "mods", + "instanceMods", + ]; + let instanceValidity = true; + foldersThatShouldBeThere.forEach(folder => { + if(!files.includes(folder)){ + instanceValidity = false; + } + }); + resolve(instanceValidity); + } + }); + } + }); + }); + } + createMap(name = "map.zip"){ + return new Promise((resolve, reject) => { + this.isValidInstance().then(isValid => { + if(!isValid){ + return createInstance(); + } + }).then(()=>{ + this.onProgress("log", "Starting map creation"); + // console.log(this.factorioDirectory + '/bin/x64/factorio') + let proc = child_process.spawn( + path.join(this.factorioDirectory, 'bin', 'x64', 'factorio'), [ + '-c', path.join(this.instanceDirectory,'config.ini'), + '--create', path.join(this.instanceDirectory, 'saves',name), + '--server-settings', path.join(this.instanceDirectory, 'server-settings.json'), + ],{ + cwd:process.cwd(), + } + ); + // console.log(proc.stdout.toString("utf8")); + proc.stdout.on("data", data => this.onProgress("log", data.toString("utf8"))); + proc.on("close", code => { + this.onProgress("log", "Map created! "+code); + resolve(); + }); + }); + }); + } +} \ No newline at end of file diff --git a/node_modules/_app/factorioServer/index.spec.js b/node_modules/_app/factorioServer/index.spec.js new file mode 100644 index 00000000..0a63fbcb --- /dev/null +++ b/node_modules/_app/factorioServer/index.spec.js @@ -0,0 +1,114 @@ +const assert = require("assert"); +const fs = require("fs"); +const path = require("path"); + +const appRootPath = require("app-root-path"); +const parallel = require("mocha.parallel"); +const mkdirp = require("mkdirp"); + +const factorioServer = require("./index.js"); + +describe("class factorioServer/index.js", ()=>{ + it("is a class (or at least a function)", ()=>{ + assert.equal(typeof factorioServer, "function"); + }); + describe(".deleteInstance(instanceName)", ()=>{ + it("deletes an instance, defaulting to the classes instanceDirectory", async () => { + let server = new factorioServer({ + instanceDirectory: path.resolve(__dirname, "_testData_deleteInstance"), + instanceName: "Unit testing instance", + }); + await server.initialize(); + await server.deleteInstance(); + assert.equal(await server.isValidInstance(), false); + return true; + }); + }); + describe(".isValidInstance(instanceName)", ()=>{ + it("tells us whether an instance exists or not", async () => { + let server = new factorioServer({ + instanceDirectory: path.join(__dirname, "_testData_isValidInstance"), + instanceName: "Unit testing instance", + }); + await server.deleteInstance(); + let status = await server.isValidInstance(); + assert.equal(status, false); + let x = await server.initialize(); // creates our instance + let status2 = await server.isValidInstance(); + assert.equal(status2, true); + + await server.deleteInstance(); // clean up folder + return true; + }); + it("does not get tricked by an empty folder", async () => { + let server = new factorioServer({ + instanceDirectory: path.join(__dirname, "_testData_isValidInstance_2"), + instanceName: "Unit testing instance", + }); + assert.equal(await server.isValidInstance(), false); + + mkdirp.sync(path.join(__dirname, "_testData_isValidInstance_2")); // create empty folder simulating instance + assert.equal(await server.isValidInstance(), false); + + await server.initialize(); // create a proper instance + assert.equal(await server.isValidInstance(), true); + + await server.deleteInstance(); // delete the instance and ensure we see that it is in fact deleted + assert.equal(await server.isValidInstance(), false); + + return true; + }).timeout(5000); + }); + describe(".initialize()", ()=>{ + it("creates an instance", done => { + let server = new factorioServer({ + instanceDirectory: path.resolve(__dirname, "_testData_initialize"), + instanceName: "Unit testing instance", + }); + server.initialize().then(()=>{ + return server.deleteInstance(); + }).then(() => { + done(); + }).catch(e => console.log(e)); + }); + }); + describe(".createMap(mapName.zip)", ()=>{ + it("creates a map file as instanceDirectory/saves/map.zip", async function(){ + this.timeout(20000); // these test often takes a lot of time in the map creation step (4500 ms on i3 dev system) + let relativePath = __dirname.replace(appRootPath, "").substr(1); + let server = new factorioServer({ + instanceDirectory: path.join(relativePath, "_testData_createMap"), + instanceName: "Unit testing instance", + onProgress: false, + }); + await server.initialize(); + let maps = fs.readdirSync(path.join(relativePath, "_testData_createMap", "saves")); + assert.equal(maps.length, 0); + await server.createMap(); + let maps2 = fs.readdirSync(path.join(relativePath, "_testData_createMap", "saves")); + assert(maps2.includes("map.zip")); + + await server.deleteInstance(); + return true; + }); + it("supports custom filenames", async function(){ + this.timeout(20000); + let relativePath = __dirname.replace(appRootPath, "").substr(1); + let server = new factorioServer({ + instanceDirectory: path.join(relativePath, "_testData_createMap_2"), + instanceName: "Unit testing instance", + onProgress: false, + }); + await server.initialize(); + + let maps = fs.readdirSync(path.join(relativePath, "_testData_createMap_2", "saves")); + assert.equal(maps.length, 0); + await server.createMap("mapWithCustomName.zip"); + let maps2 = fs.readdirSync(path.join(relativePath, "_testData_createMap_2", "saves")); + assert(maps2.includes("mapWithCustomName.zip")); + + await server.deleteInstance(); + return true; + }); + }); +}); \ No newline at end of file diff --git a/lib/fileOps.js b/node_modules/_app/fileOps/fileOps.js similarity index 62% rename from lib/fileOps.js rename to node_modules/_app/fileOps/fileOps.js index 65250fcf..014f5577 100644 --- a/lib/fileOps.js +++ b/node_modules/_app/fileOps/fileOps.js @@ -1,5 +1,5 @@ -var fs = require("fs"); -var path = require("path"); +const fs = require("fs"); +const path = require("path"); // gets newest file in a directory // dir is directory @@ -70,10 +70,51 @@ var deleteFolderRecursiveSync = function(path) { return false; } }; +var deleteFolderRecursive = function(path){ + return new Promise((resolve, reject) => { + fs.readdir(path, (err, files) => { + if(err){ + reject(err); + } else { + let thingsToDelete = files.length; + files.forEach(file => { + let curPath = path + "/" + file; + fs.stat(curPath, (err, stat) => { + if(!err){ + if(stat.isDirectory()){ + // recurse + deleteFolderRecursive(curPath).then(() => { + whenFilesDeleted(); + }).catch(e => console.log(e)); + } else { + fs.unlink(curPath, () => { + // console.log("Deleted "+curPath); + whenFilesDeleted(); + }); + } + } else { + resolve(false); + } + }); + }); + whenFilesDeleted(); + function whenFilesDeleted(){ + if(!thingsToDelete--){// var-- instead of --var because we are calling the function once too much and need the delay + fs.rmdir(path, () => { + resolve(); + // console.log("Deleted "+path); + }); + } + } + } + }); + }); +} module.exports = { - getNewestFile:getNewestFile, - getDirectoriesSync:getDirectoriesSync, - deleteFolderRecursiveSync:deleteFolderRecursiveSync, - getFileNamesSync:getFileNamesSync, + getNewestFile, + getDirectoriesSync, + deleteFolderRecursiveSync, + deleteFolderRecursive, + getFileNamesSync, } diff --git a/lib/fileOps.spec.js b/node_modules/_app/fileOps/fileOps.spec.js similarity index 50% rename from lib/fileOps.spec.js rename to node_modules/_app/fileOps/fileOps.spec.js index 83f09277..b3d731dd 100644 --- a/lib/fileOps.spec.js +++ b/node_modules/_app/fileOps/fileOps.spec.js @@ -1,30 +1,32 @@ -var assert = require('assert'); -var fileOps = require('./fileOps'); -var fs = require('fs'); +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); + +const fileOps = require('./fileOps'); // create folders for testing function setupTestingEnv(){ - if (!fs.existsSync("database")){ - fs.mkdirSync("database"); + if (!fs.existsSync(path.resolve(__dirname, "database"))){ + fs.mkdirSync(path.resolve(__dirname, "database")); } - if (!fs.existsSync("lib/test")){ - fs.mkdirSync("lib/test"); + if (!fs.existsSync(path.resolve(__dirname, "test"))){ + fs.mkdirSync(path.resolve(__dirname, "test")); } - if (!fs.existsSync("lib/test/folder")){ - fs.mkdirSync("lib/test/folder"); + if (!fs.existsSync(path.resolve(__dirname, "test/folder"))){ + fs.mkdirSync(path.resolve(__dirname, "test/folder")); } - if (!fs.existsSync("lib/test/another folder")){ - fs.mkdirSync("lib/test/another folder"); + if (!fs.existsSync(path.resolve(__dirname, "test/another folder"))){ + fs.mkdirSync(path.resolve(__dirname, "test/another folder")); } - if (!fs.existsSync("lib/test/file.txt")){ - fs.writeFileSync("lib/test/file.txt", "contents"); + if (!fs.existsSync(path.resolve(__dirname, "test/file.txt"))){ + fs.writeFileSync(path.resolve(__dirname, "test/file.txt"), "contents"); } - if (!fs.existsSync("lib/test/another file.txt")){ - fs.writeFileSync("lib/test/another file.txt", "more contents"); + if (!fs.existsSync(path.resolve(__dirname, "test/another file.txt"))){ + fs.writeFileSync(path.resolve(__dirname, "test/another file.txt"), "more contents"); } // we need this xfile to test a branch in fileOps.getNewestFile()s propagation - if (!fs.existsSync("lib/test/xfile.txt")){ - fs.writeFileSync("lib/test/xfile.txt", "contents"); + if (!fs.existsSync(path.resolve(__dirname, "test/xfile.txt"))){ + fs.writeFileSync(path.resolve(__dirname, "test/xfile.txt"), "contents"); } } setupTestingEnv(); @@ -32,7 +34,7 @@ setupTestingEnv(); // run twice to get branch coverage describe("fileOps.js", function(){ describe("fileOps.getDirectoriesSync()", function(){ it("gets an array of directory names from a path", function(){ - let directories = fileOps.getDirectoriesSync("lib/test"); + let directories = fileOps.getDirectoriesSync(path.resolve(__dirname, "test")); // because there are no arrays for some reason assert(typeof directories == "object"); @@ -41,7 +43,7 @@ describe("fileOps.js", function(){ assert(directories[0] == "another folder" && directories[1] == "folder"); }); it("does not return any filenames", function(){ - let directories = fileOps.getDirectoriesSync("lib/test"); + let directories = fileOps.getDirectoriesSync(path.resolve(__dirname, "test")); // this is a function to return directories, not files. So yeah. assert(!directories.includes("file.txt") && !directories.includes("another file.txt")); @@ -54,7 +56,7 @@ describe("fileOps.js", function(){ }); describe("fileOps.getFileNamesSync(path)", function(){ it("gets names of files in directory", function(){ - let files = fileOps.getFileNamesSync("lib/test"); + let files = fileOps.getFileNamesSync(path.resolve(__dirname, "test")); assert(files.length > 0); assert(files.includes("file.txt") && files.includes("another file.txt")); }); @@ -66,24 +68,24 @@ describe("fileOps.js", function(){ }); describe("fileOps.getNewestFile()", function(){ it("gets the newest file in a directory async", function(done){ - fileOps.getNewestFile("lib/test/", fileOps.getFileNamesSync("lib/test"), function(err, newest){ + fileOps.getNewestFile(path.resolve(__dirname, "test/"), fileOps.getFileNamesSync(path.resolve(__dirname, "test")), function(err, newest){ assert(newest && typeof newest.file == "string"); done(); }); }); it("throws if callback is missing", function(){ assert.throws(function(){ - fileOps.getNewestFile("lib/test", fileOps.getFileNamesSync("lib/test")); + fileOps.getNewestFile("test", fileOps.getFileNamesSync(path.resolve(__dirname, "test"))); }, Error); }); it("executes callback(err) if no files are provided", function(done){ - fileOps.getNewestFile("lib/test", [], function(err, newest){ + fileOps.getNewestFile(path.resolve(__dirname, "test"), [], function(err, newest){ assert(err && typeof err == "object"); done(); }); }); it("executes callback(err) if launched without a directory", function(done){ - fileOps.getNewestFile("", fileOps.getFileNamesSync("lib/test"), function(err, newest){ + fileOps.getNewestFile("", fileOps.getFileNamesSync(path.resolve(__dirname, "test")), function(err, newest){ assert(err); done(); }); @@ -98,9 +100,9 @@ describe("fileOps.js", function(){ }); describe("fileOps.deleteFolderRecursiveSync(path)", function(){ it("deletes a folder and all files and folders in it", function(){ - let x = fileOps.deleteFolderRecursiveSync("lib/test"); + let x = fileOps.deleteFolderRecursiveSync(path.resolve(__dirname, "test")); assert.throws(function(){ - fs.statSync("lib/test"); + fs.statSync(path.resolve(__dirname, "test")); }, Error); assert(x); // give it some extra time because its sometimes very slow @@ -110,4 +112,24 @@ describe("fileOps.js", function(){ assert(!x); }); }); + describe("fileOps.deleteFolderRecursive(path)", function(){ + it("deletes a folder and all files and folders in it, just like sync version", async function(){ + setupTestingEnv(); + assert(fs.statSync(path.resolve(__dirname, "test"))); + let x = await fileOps.deleteFolderRecursive(path.resolve(__dirname, "test")); + assert.throws(function(){ + fs.statSync(path.resolve(__dirname, "test")); + }, Error); + assert(x === undefined, "Promise version of this function does not have a return value upon success"); + return true; + }).timeout(5000); + it("throws like a promise does if you give it an invalid path", async function(){ + let x = await fileOps.deleteFolderRecursive("Look this path is fake!") + .catch(e => { + assert(e); + assert.equal(e.code, "ENOENT"); + return true; + }); + }); + }); }); diff --git a/node_modules/_app/fileOps/index.js b/node_modules/_app/fileOps/index.js new file mode 100644 index 00000000..5df8775d --- /dev/null +++ b/node_modules/_app/fileOps/index.js @@ -0,0 +1,2 @@ +const fileOps = require("./fileOps"); +module.exports = fileOps; \ No newline at end of file diff --git a/package.json b/package.json index c1b78137..9cecbbe9 100644 --- a/package.json +++ b/package.json @@ -5,9 +5,9 @@ "repository": "https://github.com/Danielv123/factorioClusterio", "main": "master.js", "scripts": { - "test": "./node_modules/.bin/istanbul cover ./node_modules/mocha/bin/_mocha -- \"./{,!(node_modules)/**/}*.spec.js\" -R spec || echo .", + "test": "./node_modules/.bin/istanbul cover ./node_modules/mocha/bin/_mocha -- \"./{{,node_modules/_app/**/},!(node_modules)/**/}*.spec.js\" -R spec || echo .", "start": "echo Run node client.js start [instance] to start slaves && node master.js", - "cover": "./node_modules/.bin/istanbul cover ./node_modules/mocha/bin/_mocha -- \"./{,!(node_modules)/**/}*.spec.js\" -R spec || echo . && codecov -t f7b38085-36eb-4d72-84e6-64721910171e", + "cover": "./node_modules/.bin/istanbul cover ./node_modules/mocha/bin/_mocha -- \"./{{,node_modules/_app/**/},!(node_modules)/**/}*.spec.js\" -R spec || echo . && codecov -t f7b38085-36eb-4d72-84e6-64721910171e", "docs": "documentation build index.js --config documentation.yml -f html -o docs", "livedocs": "documentation serve --watch *.js lib/** --config documentation.yml", "install": "node lib/npmPostinstall.js" @@ -18,6 +18,7 @@ "author": "Danielv123", "license": "ISC", "dependencies": { + "app-root-path": "^2.0.1", "as-table": "^1.0.31", "averaged-timeseries": "^1.4.0", "body-parser": "^1.18.2", @@ -26,39 +27,42 @@ "ejs": "^2.5.7", "express": "^4.16.2", "express-fileupload": "0.0.6", - "follow-redirects": "^1.2.5", + "follow-redirects": "^1.4.1", "fs-extra": "^1.0.0", - "getmac": "^1.2.1", + "getmac": "^1.4.0", "hash-files": "^1.1.1", - "html5-validator": "^1.0.6", - "ini": "^1.3.4", + "html5-validator": "^1.0.7", + "ini": "^1.3.5", "leveldown": "^1.9.0", - "linvodb3": "^3.25.0", + "linvodb3": "^3.25.1", "luamin": "^1.0.4", "mkdirp": "^0.5.1", "mkdirp-promise": "^5.0.1", - "moment": "^2.19.1", + "moment": "^2.20.1", "ncp": "^2.0.0", "nedb": "^1.8.0", "needle": "^1.1.0", - "node-factorio-api": "^0.1.28", + "node-factorio-api": "^0.3.1-alpha", + "node-forge": "^0.7.1", + "prom-client": "^10.2.3", "node-lua": "^1.0.4", "request": "^2.83.0", "right-pad": "^1.0.1", "rmdir-sync": "^1.0.1", "simple-rcon": "^0.3.1", + "single-line-log": "^1.1.2", "socket.io": "^2.0.4", "socket.io-client": "^2.0.4", "sync-request": "^4.0.1", "underscore": "^1.8.3" }, "devDependencies": { - "documentation": "^5.3.3", + "documentation": "^5.4.0", "istanbul": "^0.4.5", "mocha": "^3.5.3", "mocha-sinon": "^2.0.0", - "mocha.parallel": "^0.15.3", - "nock": "^9.0.27", + "mocha.parallel": "^0.15.5", + "nock": "^9.1.6", "sinon": "^2.4.1", "supertest": "^3.0.0" } diff --git a/sharedPlugins/remoteMap/chunkStore.spec.js b/sharedPlugins/remoteMap/chunkStore.spec.js index 2460dafe..8ea663ba 100644 --- a/sharedPlugins/remoteMap/chunkStore.spec.js +++ b/sharedPlugins/remoteMap/chunkStore.spec.js @@ -12,7 +12,7 @@ describe("remoteMap/chunkStore.js", () => { it("is a constructor", ()=>{ assert.equal(typeof chunkStore, "function"); // create a new store and elevate it - store = new chunkStore("910239"/* instanceID, use defaults for the rest */); + store = new chunkStore("910239"/* instanceID, use defaults for the rest */, undefined, "./database/unitTests/chunkStore/"); assert.equal(store.name, "910239"); }); it("allows you to store the locations of entities", done => { diff --git a/sharedPlugins/remoteMap/control.lua b/sharedPlugins/remoteMap/control.lua index 18301e45..0ca3b083 100644 --- a/sharedPlugins/remoteMap/control.lua +++ b/sharedPlugins/remoteMap/control.lua @@ -22,22 +22,33 @@ -- DEALINGS IN THE SOFTWARE. function write_file(data) - if must_write_initstuff then - must_write_initstuff = false - writeout_initial_stuff() - end - - game.write_file("remoteMap.txt", data, true) + stringsToWriteNextTick = stringsToWriteNextTick .. data .. '\n' + -- game.write_file("remoteMap.txt", data, true) end + +function dump_cached_writes() + game.write_file("remoteMap.txt", stringsToWriteNextTick, true) +end + function complain(text) - print(text) - game.forces["player"].print(text) + if false then -- only print during development + print(text) + game.forces["player"].print(text) + end end local todo_next_tick = {} +must_write_initstuff = true function on_tick(event) + dump_cached_writes() + stringsToWriteNextTick = '' + if must_write_initstuff then + must_write_initstuff = false + log("I must write init stuff!") + writeout_initial_stuff() + end if #todo_next_tick > 0 then - print("on_tick executing "..#todo_next_tick.." stored callbacks") + complain("on_tick executing "..#todo_next_tick.." stored callbacks") for _,func in ipairs(todo_next_tick) do func() end @@ -45,26 +56,50 @@ function on_tick(event) end end +function writeout_initial_stuff() + log("Writing out initial stuff...") + writeout_objects(game.surfaces['nauvis'], {left_top={x=-64,y=-64},right_bottom={x=64,y=64}}) +end function writeout_objects(surface, area) --if my_client_id ~= 1 then return end - header = "objects "..area.left_top.x..","..area.left_top.y..";"..area.right_bottom.x..","..area.right_bottom.y..": " - line = '' for idx, ent in pairs(surface.find_entities(area)) do if area.left_top.x <= ent.position.x and ent.position.x < area.right_bottom.x and area.left_top.y <= ent.position.y and ent.position.y < area.right_bottom.y then if ent.prototype.collision_mask ~= nil and ent.prototype.collision_mask['player-layer'] then - line = line .. ent.name.." "..ent.position.x.." "..ent.position.y.."\n" + -- line = line .. ent.name.." "..ent.position.x.." "..ent.position.y.."\n" + -- local line = ent.name..","..ent.position.x..","..ent.position.y + -- if ent.supports_direction then + -- line = line .. ",rot="..ent.direction + -- end + -- write_file(line) + on_some_entity_created(nil, ent) end end end - write_file(line) --write_file(header..table.concat(lines,"").."\n") --write_file(table.concat(lines,"").."\n") - line=nil end +function on_chunk_generated(event) + local area = event.area + local surface = event.surface + --print("chunk generated at ("..area.left_top.x..","..area.left_top.y..") -- ("..area.right_bottom.x..","..area.right_bottom.y..")") -function on_some_entity_created(event) - local ent = event.entity or event.created_entity or nil + if surface ~= game.surfaces['nauvis'] then -- we only support one surface + return + end + + -- writeout_resources(surface, area) + writeout_objects(surface, area) + -- writeout_tiles(surface, area) +end +function on_some_entity_created(event, entp) + local ent + if entp then + ent = entp + else + ent = event.entity or event.created_entity or nil + end + if ent == nil then complain("wtf, on_some_entity_created has nil entity") return @@ -73,6 +108,7 @@ function on_some_entity_created(event) if ent.supports_direction then entityData = entityData .. ",rot="..ent.direction end + -- log(entityData) write_file(entityData) --writeout_objects(ent.surface, {left_top={x=math.floor(ent.position.x), y=math.floor(ent.position.y)}, right_bottom={x=math.floor(ent.position.x)+1, y=math.floor(ent.position.y)+1}}) --complain("on_some_entity_created: "..ent.name.." at "..ent.position.x..","..ent.position.y) @@ -95,12 +131,15 @@ function on_some_entity_deleted(event) end script.on_event(defines.events.on_tick, on_tick) +script.on_event(defines.events.on_chunk_generated, on_chunk_generated) script.on_event(defines.events.on_biter_base_built, on_some_entity_created) --entity script.on_event(defines.events.on_built_entity, on_some_entity_created) --created_entity script.on_event(defines.events.on_robot_built_entity, on_some_entity_created) --created_entity +script.on_event(defines.events.on_player_rotated_entity, on_some_entity_created) --created_entity script.on_event(defines.events.on_entity_died, on_some_entity_deleted) --entity script.on_event(defines.events.on_player_mined_entity, on_some_entity_deleted) --entity script.on_event(defines.events.on_robot_mined_entity, on_some_entity_deleted) --entity script.on_event(defines.events.on_resource_depleted, on_some_entity_deleted) --entity + diff --git a/sharedPlugins/remoteMap/destroyEntityCommand.lua b/sharedPlugins/remoteMap/destroyEntityCommand.lua new file mode 100644 index 00000000..bd52ed8a --- /dev/null +++ b/sharedPlugins/remoteMap/destroyEntityCommand.lua @@ -0,0 +1,5 @@ +/c +local toDelete = game.surfaces[1].find_entities({{3,7},{4,8}}) +for i, entity in pairs(toDelete) do + entity.die() +end \ No newline at end of file diff --git a/sharedPlugins/remoteMap/index.js b/sharedPlugins/remoteMap/index.js index 72403789..9c03cc08 100644 --- a/sharedPlugins/remoteMap/index.js +++ b/sharedPlugins/remoteMap/index.js @@ -13,8 +13,8 @@ class remoteMap { // initialize chunk database this.chunkMap = new chunkStore(this.config.unique, 64, "./database/chunkStore/"); this.chunkMap.onEntityChange(entity => { - console.log("Entity changed: ") - console.log(entity); + // this.messageInterface("Entity changed: ") + // this.messageInterface(entity); // check valid coordinates (dunno what could go wrong, but can never be too sure) if(entity && entity.x !== undefined && !isNaN(Number(entity.x)) && entity.y !== undefined && !isNaN(Number(entity.y))){ this.socket.emit("sendEntity", entity); @@ -31,7 +31,7 @@ class remoteMap { },10000); }); this.socket.on("getChunk", req => { - console.log("getChunk is not supported!"); + this.messageInterface("getChunk is not supported!"); /*this.chunkMap.getChunk(req.x, req.y).then(chunk => { chunk.requesterID = req.requesterID; this.socket.emit("sendChunk", chunk); @@ -51,17 +51,54 @@ class remoteMap { this.messageInterface("socket.getEntity triggered called with invalid parameters"); } }); + // both placing and deleting entities via the web interface + this.socket.on("placeEntity", req => { + // game.player.surface.create_entity{name="small-ship-wreck", position={game.player.position.x-2, game.player.position.y+1}, direction=..., force=...} + this.messageInterface("placing "+JSON.stringify(req)); + if(req.name && typeof req.name == "string" && req.position && !isNaN(Number(req.position.x)) && !isNaN(Number(req.position.y))){ + if(req.name == "deleted"){ // {{'+req.position.x+','+req.position.y+'},{'+req.position.x+','+req.position.y+'}} + // delete entity from game world using LUA command + this.messageInterface('/silent-command local toDelete = game.surfaces[1].find_entities({{'+req.position.x+','+req.position.y+'},{'+(req.position.x+1)+','+(req.position.y+1)+'}}) for i, entity in pairs(toDelete) do entity.die() end'); + // this position is now empty, delete whatever was there from DB + this.deleteEntity(req.position.x, req.position.y); + } else { + let command = '/silent-command game.surfaces[1].create_entity{name="'+req.name+'", position={'+Number(req.position.x)+', '+Number(req.position.y)+'}, force="neutral"' + if(req.direction) command += ', direction='+req.direction; + command += '}'; + this.messageInterface(command); // execute command + + // add entity to the chunkStore database because create_entity does not trigger any events + let name = req.name; + let entity = {name}; + if(typeof req.direction == "string"){ + entity.rot = req.direction; + } + this.addEntity(req.position.x, req.position.y, entity); + } + } + }); this.messageInterface("/silent-command game.print('"+moduleConfig.name+" version "+moduleConfig.version+" enabled')"); } + addEntity(x,y,entity){ // add entity to database + this.chunkMap.setEntity(Number(x), Number(y), entity).then(data => { + this.messageInterface("Added "+entity.name+" to data "+Number(x)+", "+Number(y)); + }).catch((err)=>this.messageInterface(err)); + } + deleteEntity(x,y){ // remove entity from database + // this position is now empty, delete whatever was there from DB + this.chunkMap.setEntity(x, y, "delete this entity").then(() => { + this.messageInterface("Deleted entity at "+x+", "+y); + }).catch((err)=>this.messageInterface(err)); + } scriptOutput(data){ if(data){ this.messageInterface(data); // express-transport-belt,-35.5,-14.5,[...] data = data.split(","); if(data && data[0] == undefined){ - console.log("empty: "); - console.log(data); + this.messageInterface("empty: "); + this.messageInterface(data); return } let name = data[0]; @@ -70,9 +107,7 @@ class remoteMap { if(xPos && yPos && name){ if(name == "deleted"){ // this position is now empty, delete whatever was there from DB - this.chunkMap.setEntity(xPos, yPos, "delete this entity").then(() => { - this.messageInterface("Deleted data "+xPos+", "+yPos); - }).catch((err)=>this.messageInterface(err)); + this.deleteEntity(xPos, yPos); } else { let entity = {name}; for(let i = 3; i < data.length; i++){ @@ -82,9 +117,10 @@ class remoteMap { } } // save this entity in the database - this.chunkMap.setEntity(xPos, yPos, entity).then(data => { + this.addEntity(xPos, yPos, entity); + /* this.chunkMap.setEntity(xPos, yPos, entity).then(data => { this.messageInterface("Added "+name+" to data "+xPos+", "+yPos); - }).catch((err)=>this.messageInterface(err)); + }).catch((err)=>this.messageInterface(err)); */ } } diff --git a/sharedPlugins/remoteMap/info.json b/sharedPlugins/remoteMap/info.json index ce55594f..e60aaa47 100644 --- a/sharedPlugins/remoteMap/info.json +++ b/sharedPlugins/remoteMap/info.json @@ -2,10 +2,10 @@ { "name": "remoteMap", "title": "Clusterio remote map", -"version": "2.0.0", +"version": "2.2.0", "date": "18-11-2017", "author": "Danielv123", "dependencies": ["base >= 0.15"], "factorio_version": "0.16", -"description": "Clusterio plugin for external mapping and possibly building?" +"description": "Clusterio plugin for mapping and building through the browser. No more need to start game, download and catching up for every game, also mobile factorio confirmed?" } diff --git a/static/head.html b/static/head.html index c3360c23..c503fe6b 100644 --- a/static/head.html +++ b/static/head.html @@ -1,9 +1,9 @@ Clusterio - - - - - + + + + + - \ No newline at end of file + \ No newline at end of file diff --git a/static/lib/entityDrawRules.js b/static/lib/entityDrawRules.js new file mode 100644 index 00000000..6e6e8e0e --- /dev/null +++ b/static/lib/entityDrawRules.js @@ -0,0 +1,355 @@ + +import spritesheetJson from "./../pictures/spritesheet.js"; + +export var entityDrawRules = { + "big-electric-pole": { + sizeInTiles: { + x:2, + y:2, + }, + positionOffset: { + x:-1, + y:-1, + } + }, + "accumulator": { + spritesheet: spritesheetJson.frames["images/factorio/entity/accumulator/accumulator.png"], + sizeInTiles: { + x:3.5, + y:3.5, + }, + positionOffset: { + x:-1, + y:-2, + } + }, + "centrifuge": { + spritesheet: spritesheetJson.frames["images/factorio/entity/centrifuge/centrifuge-A.png.0"], + sizeInTiles: { + x:4, + y:4, + }, + positionOffset: { + x:-1.5, + y:-1, + }, + }, + "stone-furnace": { + spritesheet: spritesheetJson.frames["images/factorio/entity/stone-furnace/stone-furnace.png"], + sizeInTiles: { + x:3, + y:2.2, + }, + positionOffset: { + x:-0.9, + y:-1, + }, + }, + "steel-furnace": { + spritesheet: spritesheetJson.frames["images/factorio/entity/steel-furnace/steel-furnace.png"], + sizeInTiles: { + x:2.5, + y:2.5, + }, + positionOffset: { + x:-1.2, + y:-1.1, + }, + }, + "roboport": { + spritesheet: spritesheetJson.frames["images/factorio/entity/roboport/roboport-base.png"], + sizeInTiles: { + x:5, + y:4.5, + }, + positionOffset: { + x:-2, + y:-2.2, + }, + }, + "substation": { + spritesheet: spritesheetJson.frames["images/factorio/entity/substation/substation.png.0"], + sizeInTiles: { + x:3, + y:3, + }, + positionOffset: { + x:-1, + y:-1.8, + }, + }, + "big-electric-pole": { + spritesheet: spritesheetJson.frames["images/factorio/entity/big-electric-pole/big-electric-pole.png.0"], + sizeInTiles: { + x:5, + y:5, + }, + positionOffset: { + x:-1, + y:-3.5, + }, + }, + "electric-mining-drill": { + spritesheet: [{ + spritesheet: spritesheetJson.frames["images/factorio/entity/electric-mining-drill/electric-mining-drill-N.png.0"], + },{ + spritesheet: spritesheetJson.frames["images/factorio/entity/electric-mining-drill/electric-mining-drill-E.png.0"], + },{ + spritesheet: spritesheetJson.frames["images/factorio/entity/electric-mining-drill/electric-mining-drill-S.png.0"], + },{ + spritesheet: spritesheetJson.frames["images/factorio/entity/electric-mining-drill/electric-mining-drill-W.png.0"], + }, + ], + sizeInTiles: { + x:3, + y:3, + }, + positionOffset: { + x:-1, + y:-1, + }, + }, + "straight-rail": { + sizeInTiles: { + x:2, + y:2, + }, + positionOffset: { + x:-1, + y:-1, + } + }, +}; +let template3x3entity = { + sizeInTiles: { + x:3, + y:3, + }, + positionOffset: { + x:-1, + y:-1, + }, +}; +for(let i = 1; i <= 3; i++){ + let name = "assembling-machine-"+i; + // entityDrawRules[name] = + entityDrawRules[name] = { + spritesheet: spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png.0"], + sizeInTiles: { + x:3.9, + y:3.9, + }, + positionOffset: { + x:-1.4, + y:-1.2, + }, + } + // template3x3entity; +}; +entityDrawRules["radar"] = { + spritesheet: [], + sizeInTiles: { + x:4, + y:4, + }, + positionOffset: { + x:-0.8, + y:-1.7, + }, +} +for(let i = 0; i < 64; i++){ + // animate the radar + entityDrawRules.radar.spritesheet.push({spritesheet: spritesheetJson.frames["images/factorio/entity/radar/radar.png."+i]}); +} +["beacon", "electric-furnace"].forEach(name => { + entityDrawRules[name] = template3x3entity; +}); +entityDrawRules["lab"] = { + spritesheet: spritesheetJson.frames["images/factorio/entity/lab/lab.png.0"], + sizeInTiles: { + x:3.5, + y:3, + }, + positionOffset: { + x:-1, + y:-0.9, + }, +} +entityDrawRules["chemical-plant"] = { + spritesheet: [{ + spritesheet: spritesheetJson.frames["images/factorio/entity/chemical-plant/chemical-plant.png.0"], + sizeInTiles: { + x:3.5, + y:3.5, + }, + positionOffset: { + x:-1.3, + y:-1, + }, + },{ + spritesheet: spritesheetJson.frames["images/factorio/entity/chemical-plant/chemical-plant.png.1"], + sizeInTiles: { + x:3.7, + y:4, + }, + positionOffset: { + x:-1.3, + y:-1.5, + }, + },{ + spritesheet: spritesheetJson.frames["images/factorio/entity/chemical-plant/chemical-plant.png.2"], + sizeInTiles: { + x:3.5, + y:3.2, + }, + positionOffset: { + x:-1.3, + y:-1, + }, + },{ + spritesheet: spritesheetJson.frames["images/factorio/entity/chemical-plant/chemical-plant.png.3"], + sizeInTiles: { + x:3.7, + y:3.6, + }, + positionOffset: { + x:-1.45, + y:-1.3, + }, + }, + ], +}; +[{name: "solar-panel", ref:"images/factorio/entity/solar-panel/solar-panel.png"}].forEach(ent => { + entityDrawRules[ent.name] = { + spritesheet: spritesheetJson.frames[ent.ref], + sizeInTiles: { + x:3, + y:3, + }, + positionOffset: { + x:-1, + y:-1, + }, + } +}); + +["transport-belt", "fast-transport-belt", "express-transport-belt"].forEach(name => { + entityDrawRules[name] = { + spritesheet: [{ + spritesheet: [ // Up + // spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png.0"], // 0 to 31 + ], + sizeInTiles: { + x:1.2,y:1.4, + }, + positionOffset: { + x:-0.1,y:-0, + } + },{ + spritesheet: [ // Right + // spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png.0"], // 0 to 31 + ], + sizeInTiles: { + x:1.2,y:1.4, + }, + positionOffset: { + x:-0.1,y:-0.2, + } + },{ + spritesheet: [ // Down + // spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png.27"], // 32 to 63 + ], + flip: "y", + sizeInTiles: { + x:1.3,y:1.6, + }, + positionOffset: { + x:-0.15,y:-1.6, + } + },{ + spritesheet: [ // Left + // spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png.27"], // 32 to 63 + ], + flip: "x", + sizeInTiles: { + x:1.3,y:1.6, + }, + positionOffset: { + x:-1.35,y:-0.25, + } + }], + } + for(let i = 0; i < 16; i++){ + if(name == "transport-belt"){ + entityDrawRules[name].spritesheet[3].spritesheet.push(spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png."+i]); + entityDrawRules[name].spritesheet[2].spritesheet.push(spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png."+(i+16)]); + entityDrawRules[name].spritesheet[1].spritesheet.push(spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png."+i]); + entityDrawRules[name].spritesheet[0].spritesheet.push(spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png."+(i+16)]); + + } else { + entityDrawRules[name].spritesheet[3].spritesheet.push(spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png."+i]); + entityDrawRules[name].spritesheet[2].spritesheet.push(spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png."+(i+32)]); + entityDrawRules[name].spritesheet[1].spritesheet.push(spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png."+i]); + entityDrawRules[name].spritesheet[0].spritesheet.push(spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png."+(i+32)]); + } + } +}); +["splitter", "fast-splitter", "express-splitter"].forEach(splitter => { + entityDrawRules[splitter] = { + rotOffset:180, + } +}); +["underground-belt", "fast-underground-belt", "express-underground-belt"].forEach(underneathie => { + entityDrawRules[underneathie] = { + rotOffset: 270, + } +}); +["inserter", "fast-inserter", "stack-inserter", "filter-inserter", "burner-inserter", 'long-handed-inserter', 'stack-filter-inserter'].forEach(inserter => { + entityDrawRules[inserter] = { + rotOffset:90, + } +}); +entityDrawRules["oil-refinery"] = { + spritesheet: [ + { + spritesheet: spritesheetJson.frames["images/factorio/entity/oil-refinery/oil-refinery.png.0"], + }, { + spritesheet: spritesheetJson.frames["images/factorio/entity/oil-refinery/oil-refinery.png.1"], + }, { + spritesheet: spritesheetJson.frames["images/factorio/entity/oil-refinery/oil-refinery.png.2"], + }, { + spritesheet: spritesheetJson.frames["images/factorio/entity/oil-refinery/oil-refinery.png.3"], + }], +} +// correct image size for the oil refinery frames (same for all of them on this one) +entityDrawRules["oil-refinery"].spritesheet.forEach(object => { + object.sizeInTiles = { + x:10, + y:7.5, + } + object.positionOffset = { + x:-2, + y:-2.7, + } +}); +// tree sizes +["tree-02", +"tree-02-red", +"tree-03", +"tree-04", +"tree-05", +"tree-07", +"tree-09", +"tree-09-brown", +"tree-09-red"].forEach(tree => { + entityDrawRules[tree] = { + sizeInTiles: { + x: 3, + y: 4, + }, + positionOffset: { + x: -0.6, + y: -2.6, + } + } +}); diff --git a/static/lib/utility.js b/static/lib/utility.js new file mode 100644 index 00000000..930f9653 --- /dev/null +++ b/static/lib/utility.js @@ -0,0 +1,53 @@ +export function getParameterByName(name, url) { + if(!url) url = window.location.href; + name = name.replace(/[\[\]]/g, "\\$&"); + var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), + results = regex.exec(url); + if(!results) return null; + if(!results[2]) return ''; + return decodeURIComponent(results[2].replace(/\+/g, " ")); +} + +// ctx, entityImages[name].img, xPos, yPos, size.x, size.y, rotation, sprWidth, sprHeight, offLeft, offTop +export function drawImageWithRotation(ctx, image, x, y, w, h, degrees, sprWidth, sprHeight, offLeft, offTop, flipX, flipY){ + ctx.save(); + ctx.translate(x+w/2, y+h/2); + ctx.rotate(degrees*Math.PI/180.0); + ctx.translate(-x-w/2, -y-h/2); + if(flipX) { + x -= x*2+sprWidth; + ctx.scale(-1, 1); + } + if(flipY){ + y -= y*2+sprHeight; + ctx.scale(1, -1); + } + + if(isImageOk(image) && sprWidth != undefined && sprHeight != undefined && offLeft != undefined && offTop != undefined){ + // console.log(sprWidth+" "+sprHeight+" "+offLeft+" "+offTop+" "+w+" "+h) + ctx.drawImage(image, offLeft, offTop, sprWidth, sprHeight, x, y, w, h); + } else if(isImageOk(image)){ + ctx.drawImage(image, x, y, w, h); + } else { + // console.log("Image is not OK! "+image.src); + } + ctx.restore(); +} +export function isImageOk(img) { + // During the onload event, IE correctly identifies any images that + // weren't downloaded as not complete. Others should too. Gecko-based + // browsers act like NS4 in that they report this incorrectly. + if (!img.complete) { + return false; + } + + // However, they do have two very useful properties: naturalWidth and + // naturalHeight. These give the true size of the image. If it failed + // to load, either of these should be zero. + if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) { + return false; + } + + // No other way of checking: assume it's ok. + return true; +} \ No newline at end of file diff --git a/static/main.js b/static/main.js index 633bbb47..a1b805f1 100644 --- a/static/main.js +++ b/static/main.js @@ -169,7 +169,7 @@ $.getJSON("/api/getFactorioLocale", (locale) => { // image data // key is the name of the item in the database, value is the name of the image on wiki.factorio.com/images/* // this list has to include all entities that doesn't just follow the simple capitalize first letter convention -/* Notice: All icon images hosted on this Wiki have been renamed to use their in-game names, with underscores. If your external tool references these icons, please correct your links. */ +/* Notice from bilka: All icon images hosted on this Wiki have been renamed to use their in-game names, with underscores. If your external tool references these icons, please correct your links. */ var imagedata = { "put-combinator": "Decider_combinator", "smart-train-stop": "Train_stop", @@ -177,6 +177,19 @@ var imagedata = { "solar-panel-equipment": "Portable_solar_panel", "diesel-locomotive": "Locomotive", // pre 0.15 loco name "small-lamp": "Lamp", + "tree-02": "Green_tree", + "tree-02-red": "Green_tree", + "tree-03": "Green_tree", + "tree-04": "Green_tree", + "tree-05": "Green_tree", + "tree-07": "Green_tree", + "tree-09": "Green_tree", + "tree-09-brown": "Green_tree", + "tree-09-red": "Green_tree", + "dead-tree-desert": "Dead_tree_desert", + "sand-rock-big": "Rock_big", + // "biter-spawner" missing, but can't find png for it on wiki + // "spitter-spawner" } @@ -199,6 +212,5 @@ var imagelinks = { "piercing-shotgun-shell": "/pictures/piercing_shotgun_shells.png", "energy-shield-mk2-equipment": "/pictures/Energy_shield_MK2.png", "battery-mk2-equipment": "/pictures/Battery_MK2.png", - "personal-roboport-mk2-equipment": "/pictures/Personal_roboport_MK2.png" - + "personal-roboport-mk2-equipment": "/pictures/Personal_roboport_MK2.png", } diff --git a/static/nodeDetails.js b/static/nodeDetails.js index eaa22e8d..69d2efa6 100644 --- a/static/nodeDetails.js +++ b/static/nodeDetails.js @@ -33,6 +33,8 @@ function getParameterByName(name, url) { /// code below here +// declaring globals +var chartsByID = {}; // update the online indicator dot setInterval(function(){ getJSON("/api/slaves", function(err, slaveData){ @@ -201,6 +203,7 @@ function makeTerminal(){ myTerminal.input('',handleTerminalInput); } } +if(localStorage.terminalMinimized == "true")minimizeTerminal(true); function minimizeTerminal(instant){ localStorage.terminalMinimized = true; $('#terminal').draggable('disable'); @@ -239,6 +242,10 @@ function maximizeTerminal(instant){ // ID of slave, ID of canvasjs div without # function makeGraph(instanceID, selector) { + let chartIgnoreList = [ + "water", + "steam" + ] post("api/getStats", {instanceID: instanceID}, function(data){ //console.log("Building chart " + instanceID + " with this data:") //console.log(data) @@ -250,7 +257,7 @@ function makeGraph(instanceID, selector) { } let chartData = []; for(let o = 0; o < itemNames.length; o++) { - if(itemNames[o] != "water"){ + if(!chartIgnoreList.includes(itemNames[o])){ chartData[chartData.length] = generateLineChartArray(data, itemNames[o]); } } @@ -289,7 +296,6 @@ function generateLineChartArray(data, nameKey) { return xyz; } -var chartsByID = {}; function drawChart(selector, chartData, title) { // selector is ID of element, ex "chartContainer" or "-123199123" console.log(chartData) diff --git a/static/pictures/grass-1.png b/static/pictures/grass-1.png new file mode 100644 index 00000000..341168d5 Binary files /dev/null and b/static/pictures/grass-1.png differ diff --git a/static/remoteMap.html b/static/remoteMap.html index a0d1a77a..fbaa2278 100644 --- a/static/remoteMap.html +++ b/static/remoteMap.html @@ -1,16 +1,28 @@ <%- include("head.html") %> - - + + <%- include("sidebar.html") %>

remoteMap

- - - +
+ + + +
+
+ +
+
+

Map size: (default 32)

+

Tile size: (default 8)

+

FPS:

+

Pause when window is deselected (saves CPU)

+

Movement speed: (default 0.2)

+
\ No newline at end of file diff --git a/static/remoteMap.js b/static/remoteMap.js index b0a488fa..5cfe1db3 100644 --- a/static/remoteMap.js +++ b/static/remoteMap.js @@ -1,14 +1,92 @@ -function getParameterByName(name, url) { - if (!url) url = window.location.href; - name = name.replace(/[\[\]]/g, "\\$&"); - var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), - results = regex.exec(url); - if (!results) return null; - if (!results[2]) return ''; - return decodeURIComponent(results[2].replace(/\+/g, " ")); +/** + Javascript to download and render a map of a factorio world from an instance using websockets and canvas + + It is its responsibility to handle: + * Display settings + * Ordering of canvases + * Querying slaves through master for map info + * Drawing of sprites defined in external files to canvas + * Handling input for placing/removing items + * Transmitting item placements/removals through master + + That is way too much for one file, so to anyone reading this: + This file is horribly written and documented. + I am sorry. Drawing code is at the bottom, good luck. + + If you have questions and wish to contact me, my name + is Danielv123 on Github, Discord and esperNet #factorio +*/ +console.log(":)") +/// ES6 imports +// rules for how entities are drawn (sizes, offset etc) +import {entityDrawRules} from "./lib/entityDrawRules.js"; +import {getParameterByName, drawImageWithRotation, isImageOk} from "./lib/utility.js"; +import spritesheetJson from "./pictures/spritesheet.js"; +import {itemSelector} from "./remoteMap/itemSelection.js"; +var global = {}; + +var itemSelectorGUI = new itemSelector("#remoteMapItemSelector", [ + {name:"stone-furnace"}, + {name:"accumulator"}, + {name:"electric-furnace"}, + {name:"inserter"}, + {name:"express-transport-belt"}, +]); + +if(!localStorage.remoteMapConfig || localStorage.remoteMapConfig == "[object Object]"){ + localStorage.remoteMapConfig = JSON.stringify({ + mapSize: 32, + tileSize: 8, + movementSpeed: 0.2, + }); } -var socket = io.connect('http://localhost:8080'); +var remoteMapConfig = JSON.parse(localStorage.remoteMapConfig); + +// Handle config changes through UI buttons +(function(){ + let selectMapSize = document.querySelector("#mapSize"); + let selectTileSize = document.querySelector("#tileSize"); + if(selectMapSize && selectTileSize){ + selectMapSize.value = Number(remoteMapConfig.mapSize) || 32; + selectTileSize.value = Number(remoteMapConfig.tileSize) || 8; + + selectMapSize.onchange = function(){ + let config = JSON.parse(localStorage.remoteMapConfig); + config.mapSize = Number(selectMapSize.value); + localStorage.remoteMapConfig = JSON.stringify(config); + console.log("Config updated: "+localStorage.remoteMapConfig); + } + selectTileSize.onchange = function(){ + let config = JSON.parse(localStorage.remoteMapConfig); + config.tileSize = Number(selectTileSize.value); + localStorage.remoteMapConfig = JSON.stringify(config); + console.log("Config updated: "+localStorage.remoteMapConfig); + } + } + let pauseOnBlur = document.querySelector("#pauseOnBlur"); + if(pauseOnBlur){ + pauseOnBlur.checked = localStorage.remoteMapPauseOnBlur || true; + pauseOnBlur.onchange = function(){ + localStorage.remoteMapPauseOnBlur = pauseOnBlur.checked; + } + } + let movementSpeed = document.querySelector("#movementSpeed"); + if(movementSpeed){ + movementSpeed.value = Number(remoteMapConfig.movementSpeed) || 0.2; + movementSpeed.onchange = function(){ + let config = JSON.parse(localStorage.remoteMapConfig); + config.movementSpeed = Number(movementSpeed.value); + localStorage.remoteMapConfig = JSON.stringify(config); + console.log("Config updated: "+localStorage.remoteMapConfig); + + // also update config live + remoteMapConfig.movementSpeed = config.movementSpeed; + } + } +})(); + +var socket = io.connect(document.location.origin); socket.on('hello', function (data) { console.log(data); socket.emit("registerMapRequester", {instanceID: getParameterByName("instanceID")}); @@ -16,15 +94,23 @@ socket.on('hello', function (data) { setInterval(()=>{ socket.emit("heartbeat"); // send our heartbeat to prevent being assumed dead },10000); - requestMapDraw(); + // load important images then proceed with rendering (and loading more images) + global.spritesheet = new Image(); + global.spritesheet.onload = function(){ + global.grassBackground = new Image(); + global.grassBackground.onload = function(){ + requestMapDraw(); + } + global.grassBackground.src = "/pictures/grass-1.png"; + } + global.spritesheet.src = "/pictures/spritesheet.png"; }); socket.on("displayChunk", function(chunk){ - console.log(chunk); - drawChunk(chunk, ctx); + console.log("displayChunk triggered but I can't draw chunks"); }); socket.on("displayEntity", function(entity){ - console.log("Displaying entity "+JSON.stringify(entity)); + // console.log("Displaying entity "+JSON.stringify(entity)); drawEntity(entity); }); }); @@ -32,128 +118,144 @@ socket.on('hello', function (data) { function requestChunk(x,y){ socket.emit('requestChunk', {x:x, y:y, instanceID: getParameterByName("instanceID")}); } -setTimeout(function(){ - canvas = document.getElementById("remoteMap"); - ctx = canvas.getContext("2d"); - ctx.font = "30px Arial"; - ctx.fillText("Hello World",10,50); - - var img = new Image(); - img.onload = function() { - ctx.drawImage(img, 0, 0, 32, 32); - }; - img.src = 'https://wiki.factorio.com/images/Lab.png'; - -}, 1); -entityImages = {}; -/* -entityImages["express-transport-belt"] = new Image(); -entityImages["express-transport-belt"].src = 'https://wiki.factorio.com/images/Express_transport_belt.png'; -*/ +(function(){ + let remoteMapLayers = document.querySelectorAll(".remoteMap"); + remoteMapLayers.forEach(layer => { + layer.addEventListener('contextmenu', event => event.preventDefault()); + layer.width = remoteMapConfig.tileSize * remoteMapConfig.mapSize; + layer.height = remoteMapConfig.tileSize * remoteMapConfig.mapSize; + }); + ["width", "height"].forEach(style => document.querySelector("#remoteMapContainer").style[style] = remoteMapConfig.tileSize * remoteMapConfig.mapSize + "px"); +})(); +const canvas = document.querySelector("#remoteMap"); +const ctx = canvas.getContext("2d"); +ctx.font = "30px Arial"; +ctx.fillText("Use WASD to navigate.",10,50); +const selectionCanvas = document.querySelector("#remoteMapSelection"); +const selectionCtx = selectionCanvas.getContext("2d"); +selectionCtx.font = "30px Arial"; +selectionCtx.fillText("Selection layer",10,50); + +const backgroundCanvas = document.querySelector("#remoteMapBackground"); +const backgroundCtx = backgroundCanvas.getContext("2d"); // map view position, top left corner (or another corner?) -playerPosition = { +window.playerPosition = { x:0, y:0, } +window.cachePosition = { + x:0, + y:0, +}; function requestMapDraw(){ - let xLow = Math.floor(playerPosition.x % 16); - let yLow = Math.floor(playerPosition.y % 16); + let xLow = Math.floor(cachePosition.x % remoteMapConfig.tileSize); + let yLow = Math.floor(cachePosition.y % remoteMapConfig.tileSize); - let xHigh = xLow+64; - let yHigh = yLow+64; + let xHigh = xLow+remoteMapConfig.mapSize; + let yHigh = yLow+remoteMapConfig.mapSize; for(let x = xLow; x < xHigh; x++){ for(let y = yLow; y < yHigh; y++){ socket.emit("requestEntity", {x, y, instanceID: getParameterByName("instanceID")}); } } } -function drawImageWithRotation(ctx, image, x, y, w, h, degrees){ - ctx.save(); - ctx.translate(x+w/2, y+h/2); - ctx.rotate(degrees*Math.PI/180.0); - ctx.translate(-x-w/2, -y-h/2); - ctx.drawImage(image, x, y, w, h); - ctx.restore(); + +document.addEventListener('keydown', keyDownHandler, false); +document.addEventListener('keyup', keyUpHandler, false); +var rightPressed = false; +var leftPressed = false; +var upPressed = false; +var downPressed = false; +function keyDownHandler(event) { + if(event.keyCode == 39 || event.keyCode == 68) { + rightPressed = true; + } + else if(event.keyCode == 37 || event.keyCode == 65) { + leftPressed = true; + } + if(event.keyCode == 40 || event.keyCode == 83) { + downPressed = true; + } + else if(event.keyCode == 38 || event.keyCode == 87) { + upPressed = true; + } +} +function keyUpHandler(event) { + if(event.keyCode == 39 || event.keyCode == 68) { + rightPressed = false; + } + else if(event.keyCode == 37 || event.keyCode == 65) { + leftPressed = false; + } + if(event.keyCode == 40 || event.keyCode == 83) { + downPressed = false; + } + else if(event.keyCode == 38 || event.keyCode == 87) { + upPressed = false; + } } -Mousetrap.bind("s", e => { - console.log("s"); - cache.walkUp(); - playerPosition.y += 16; - clear();drawFromCache(); -}); -Mousetrap.bind("d", e => { - console.log("d"); - cache.walkLeft(); - playerPosition.x += 16; - clear();drawFromCache(); -}); -Mousetrap.bind("w", e => { - console.log("w"); - cache.walkDown(); - playerPosition.y -= 16; - clear();drawFromCache(); -}); -Mousetrap.bind("a", e => { - console.log("a"); - cache.walkRight(); - playerPosition.x -= 16; - clear();drawFromCache(); -}); -entityCache = new Array(64); +var entityCache = new Array(remoteMapConfig.mapSize); // populate cache with arrays of arrays -for(let i = 0; i < 64; i++){ - entityCache[i] = new Array(64); - for(let o = 0; o < 64; o++){ +for(let i = 0; i < remoteMapConfig.mapSize; i++){ + entityCache[i] = new Array(remoteMapConfig.mapSize); + for(let o = 0; o < remoteMapConfig.mapSize; o++){ entityCache[i][o] = " "; } } -cache = { - walkUp: function walkUp(){ - for(let i = 0; i < 64; i++){ +// cache navigation functions, for panning (walking, if you will) +const cache = { + walkDown: function walkUp(){ + cachePosition.y += remoteMapConfig.tileSize; + for(let i = 0; i < remoteMapConfig.mapSize; i++){ entityCache[i].shift(); // remove leftmost entry entityCache[i].push(" "); // add new entry on the right // get data from slaveMapper - let x = playerPosition.x/16 + i; - let y = playerPosition.y/16+64; + let x = cachePosition.x/remoteMapConfig.tileSize + i; + let y = cachePosition.y/remoteMapConfig.tileSize+remoteMapConfig.mapSize-1; socket.emit("requestEntity", {x, y, instanceID: getParameterByName("instanceID")}); } }, - walkDown: function walkDown(){ - for(let i = 0; i < 64; i++){ + walkUp: function walkDown(){ + cachePosition.y -= remoteMapConfig.tileSize; + for(let i = 0; i < remoteMapConfig.mapSize; i++){ entityCache[i].pop(); // remove rightmost entry entityCache[i].unshift(" "); // add new entry on the left // get data from slaveMapper - let x = playerPosition.x/16 + i; - let y = playerPosition.y/16; + let x = cachePosition.x/remoteMapConfig.tileSize + i; + let y = cachePosition.y/remoteMapConfig.tileSize; socket.emit("requestEntity", {x, y, instanceID: getParameterByName("instanceID")}); } }, walkLeft: function walkLeft(){ + cachePosition.x += remoteMapConfig.tileSize; entityCache.shift(); - entityCache.push(new Array(64)); + entityCache.push(new Array(remoteMapConfig.mapSize)); // get data from slaveMapper // fill in a row on the right side of the screen, that is the bottom of the 1st level array - for(let i = 0; i < 64; i++){ - let x = playerPosition.x/16 + 64; - let y = playerPosition.y/16 + i; + for(let i = 0; i < remoteMapConfig.mapSize; i++){ + let x = cachePosition.x/remoteMapConfig.tileSize + remoteMapConfig.mapSize - 1; + let y = cachePosition.y/remoteMapConfig.tileSize + i; socket.emit("requestEntity", {x, y, instanceID: getParameterByName("instanceID")}); } }, walkRight: function walkRight(){ + cachePosition.x -= remoteMapConfig.tileSize; entityCache.pop(); - entityCache.unshift(new Array(64)); + entityCache.unshift(new Array(remoteMapConfig.mapSize)); // get data from slaveMapper // fill a row on the left side of the screen, that is the top column - for(let i = 0; i < 64; i++){ - let x = playerPosition.x/16; - let y = playerPosition.y/16 + i; + for(let i = 0; i < remoteMapConfig.mapSize; i++){ + let x = cachePosition.x/remoteMapConfig.tileSize; + let y = cachePosition.y/remoteMapConfig.tileSize + i; socket.emit("requestEntity", {x, y, instanceID: getParameterByName("instanceID")}); } } } function drawFromCache(){ + clear(); + let startTime = Date.now() entityCache.forEach(row => { row.forEach(doc => { if(doc && typeof doc == "object"){ @@ -162,29 +264,314 @@ function drawFromCache(){ }); }); } +window.requestAnimationFrame(renderLoop); +var fpsTimings = { + lastFrame: Date.now(), + averageLength: 60, + sum:0, + counter: document.querySelector("#fpsCounter"), +} +var isPaused = false; +window.onblur = function() { + if(localStorage.remoteMapPauseOnBlur == "true"){ + isPaused = true; + console.log("paused"); + } +} +window.onfocus = function() { + if(isPaused){ + isPaused = false; + console.log("unpaused"); + window.requestAnimationFrame(renderLoop); + } +} +function getMousePos(canvas, evt) { + var rect = canvas.getBoundingClientRect(); + return { + x: evt.clientX - rect.left, + y: evt.clientY - rect.top + }; +} +window.mousePos = {}; +selectionCanvas.addEventListener('mousemove', function(evt) { + var mousePos = getMousePos(selectionCanvas, evt); + var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y; + window.mousePos.x = mousePos.x; + window.mousePos.y = mousePos.y; +}, false); +selectionCanvas.addEventListener("mousedown", function(evt) { + if(evt.which === 1) window.mousePos.clicked = true; + if(evt.which === 3) window.mousePos.rightClicked = true; + + // place item in world by sending it with websockets and shit + let tileSize = remoteMapConfig.tileSize; + let entity = { + name: itemSelectorGUI.getItem().name, + position:{ + x: Math.floor((playerPosition.x + window.mousePos.x) / tileSize), + y: Math.floor((playerPosition.y + window.mousePos.y) / tileSize), + }, + direction: itemSelectorGUI.getItem().direction.toString(), + }; + if(evt.which === 1){ // left click to place + console.log(JSON.stringify(entity)); + socket.emit("placeEntity", entity); + } else if(evt.which === 3){ // right click to delete + entity.name = "deleted"; + socket.emit("placeEntity", entity) + } + // console.log(entity); +}); +selectionCanvas.addEventListener("mouseup", function(evt) { + if(evt.which === 1) window.mousePos.clicked = false; + if(evt.which === 3) window.mousePos.rightClicked = false; +}); +function renderLoop(){ + // render game canvas + let newTimestamp = Date.now(); + fpsTimings.sum = fpsTimings.sum / fpsTimings.averageLength * (fpsTimings.averageLength - 1); + let timeSinceLastFrame; + fpsTimings.sum += timeSinceLastFrame = newTimestamp - fpsTimings.lastFrame; + fpsTimings.counter.value = (1000 / (fpsTimings.sum / fpsTimings.averageLength)).toPrecision(4); + fpsTimings.lastFrame = newTimestamp; + if(!isPaused){ + let moveSpeed = Number(remoteMapConfig.movementSpeed); + let movement = moveSpeed * timeSinceLastFrame; + // handle movement and requesting new entities + if(upPressed){ + console.log("w"); + playerPosition.y -= movement; + if(Math.abs((playerPosition.y-cachePosition.y)/remoteMapConfig.tileSize) > 1){ + for(let i = 0; i < Math.floor(Math.abs((playerPosition.y-cachePosition.y)/remoteMapConfig.tileSize)); i++){ + cache.walkUp(); + } + } + } + if(leftPressed){ + console.log("a"); + playerPosition.x -= movement; + if(Math.abs((playerPosition.x-cachePosition.x)/remoteMapConfig.tileSize) > 1){ + for(let i = 0; i < Math.floor(Math.abs((playerPosition.x-cachePosition.x)/remoteMapConfig.tileSize)); i++){ + cache.walkRight(); + }} + } + if(downPressed){ + console.log("s"); + playerPosition.y += movement; + if(Math.abs((playerPosition.y-cachePosition.y)/remoteMapConfig.tileSize) > 1){ + for(let i = 0; i < Math.floor(Math.abs((playerPosition.y-cachePosition.y)/remoteMapConfig.tileSize)); i++){ + cache.walkDown(); + }} + } + if(rightPressed){ + console.log("d"); + let oldPos = playerPosition.x; + playerPosition.x += movement; + if(Math.abs((playerPosition.x-cachePosition.x)/remoteMapConfig.tileSize) > 1){ + for(let i = 0; i < Math.floor(Math.abs((playerPosition.x-cachePosition.x)/remoteMapConfig.tileSize)); i++){ + cache.walkLeft(); + }} + } + // draw map + drawFromCache(); + // queue next tick + window.requestAnimationFrame(renderLoop); + } + + // render selection canvas + let mousePosition = window.mousePos; + if(mousePosition && mousePosition.x){ + // make a box around the mouse cursor + selectionCtx.beginPath(); + selectionCtx.lineWidth = remoteMapConfig.tileSize / 16; + selectionCtx.strokeStyle="yellow"; + if(mousePosition.clicked) selectionCtx.strokeStyle = "red"; + if(mousePosition.rightClicked) selectionCtx.strokeStyle = "blue"; + let tileSize = remoteMapConfig.tileSize + let halfTile = tileSize / 2; + let tilePosition = { // position in world coordinates (same as used by factorio) + x: Math.floor((playerPosition.x + mousePosition.x) / tileSize), + y: Math.floor((playerPosition.y + mousePosition.y) / tileSize), + } + // Long thing to correct for offset between playerPosition, cachePosition (tile grid) and mouse position and draw the box so it aligns with tiles. + selectionCtx.rect(tilePosition.x * tileSize - playerPosition.x, tilePosition.y * tileSize - playerPosition.y, tileSize, tileSize); + selectionCtx.stroke(); + } + + // render background canvas + let dw = 1024 / 32 * remoteMapConfig.tileSize; + let dh = 64 / 32 * remoteMapConfig.tileSize; + + // 0-dw and x < ?? + dw is to make sure we draw well outside the canvas on both sides to avoid ugly gfx + for(let x = 0-dw; x < remoteMapConfig.tileSize * remoteMapConfig.mapSize + dw; x += dw){ + for(let y = 0-dh; y < remoteMapConfig.tileSize * remoteMapConfig.mapSize + dh; y += dh){ + let dx = x - playerPosition.x % dw; + let dy = y - playerPosition.y % dh; + if(global.grassBackground && isImageOk(global.grassBackground)) backgroundCtx.drawImage(global.grassBackground, 0, 64, 1024, 64, dx, dy, dw, dh); + } + } +} +var entityImages = {}; // cache to store images and details about entities, populated by drawEntity(); +window.logEntCache = function(){console.log(entityCache)} function drawEntity(entity, dontCache){ - if(entity.x && entity.y){ + if(entity.x !== undefined && entity.y !== undefined){ if(!dontCache){ // cache entity for later draws (like panning) - if(entity.x - playerPosition.x/16 >= 0 && entity.x - playerPosition.x/16 < 64 && entity.y - playerPosition.y/16 >= 0 && entity.y - playerPosition.y/16 < 64){ + if(entity.x - cachePosition.x/remoteMapConfig.tileSize >= 0 && entity.x - cachePosition.x/remoteMapConfig.tileSize < remoteMapConfig.mapSize && entity.y - cachePosition.y/remoteMapConfig.tileSize >= 0 && entity.y - cachePosition.y/remoteMapConfig.tileSize < remoteMapConfig.mapSize){ if(entity.entity){ - entityCache[entity.x - playerPosition.x/16][entity.y - playerPosition.y/16] = entity; + entityCache[entity.x - cachePosition.x/remoteMapConfig.tileSize][entity.y - cachePosition.y/remoteMapConfig.tileSize] = entity; } else { // delete this entity because we just heard the tile is empty and stuff - entityCache[entity.x - playerPosition.x/16][entity.y - playerPosition.y/16] = " "; + entityCache[entity.x - cachePosition.x/remoteMapConfig.tileSize][entity.y - cachePosition.y/remoteMapConfig.tileSize] = " "; } } } if(entity.entity && entity.entity.name && typeof entity.entity.name == "string"){ let name = entity.entity.name; if(!entityImages[name]){ + console.log("Downloading image "+name); // download the entityImages and add stuff to queue - entityImages[name] = {}; - entityImages[name].img = new Image(); - entityImages[name].queue = []; - entityImages[name].queue.push(entity); - entityImages[name].loaded = false; - entityImages[name].img.onload = function(){ + entityImages[name] = { + img: new Image(), + queue: [], + loaded: false, + }; + entityImages[name].draw = function(entity){ + if(this.loaded){ + let name = entity.entity.name; + let image, sprWidth, sprHeight, offLeft, offTop, size, offsetX, offsetY; + let flipX = false, flipY = false; + let rotation = 0; + // check hardcoded entity draw rules for specifics (otherwise draw icon as 1x1 entity with rotation if specified) + if(entityDrawRules[name] && (entityDrawRules[name].positionOffset || entityDrawRules[name].spritesheet)){ + let rules = entityDrawRules[name] + if(rules.positionOffset){ + offsetX = rules.positionOffset.x; + offsetY = rules.positionOffset.y; + } + if(rules.sizeInTiles){ + size = { + x: remoteMapConfig.tileSize * rules.sizeInTiles.x, + y: remoteMapConfig.tileSize * rules.sizeInTiles.y, + }; + } + if(rules.spritesheet && Array.isArray(rules.spritesheet)){ + let dir = Number(entity.entity.rot || 0); + // 2 animated sprites, we will need to flip it for rotations. + if(rules.spritesheet.length == 2){ + let spritesheetAnim = dir / 2 % 2; + let animationStage = Math.floor(Date.now()/16) % rules.spritesheet[spritesheetAnim].spritesheet.length; + + try{ + sprWidth = rules.spritesheet[spritesheetAnim].spritesheet[animationStage].frame.w; + sprHeight = rules.spritesheet[spritesheetAnim].spritesheet[animationStage].frame.h; + offLeft = rules.spritesheet[spritesheetAnim].spritesheet[animationStage].frame.x; + offTop = rules.spritesheet[spritesheetAnim].spritesheet[animationStage].frame.y; + } catch(e){ + // console.log(name) + // console.log(rules.spritesheet[spritesheetAnim].spritesheet) + } + image = global.spritesheet; + + // handle rotation (not handled by generic handler because we have to do flips and special stuff) + if(dir == 4){ + // rotation = (dir/2)*90 + // console.log("rotating") + flipY = true; + } else if(dir == 6){ + flipX = true; + // rotation = ((dir+2)/2)*90+180 // this formula is terrible, don't try to repair, there is no sense to it + } + + if(rules.spritesheet[spritesheetAnim].positionOffset){ + offsetX = rules.spritesheet[spritesheetAnim].positionOffset.x; + offsetY = rules.spritesheet[spritesheetAnim].positionOffset.y; + } + if(rules.spritesheet[spritesheetAnim].sizeInTiles){ + size = { + x: remoteMapConfig.tileSize * rules.spritesheet[spritesheetAnim].sizeInTiles.x, + y: remoteMapConfig.tileSize * rules.spritesheet[spritesheetAnim].sizeInTiles.y, + }; + } + } else { + // correct for whether we have 1, 4 or 8 directions + let spriteSheetRotIndex = dir / (8 / rules.spritesheet.length); + if(rules.spritesheet.length > 8) { + // apparently this entity has more than 8 directions. That isn't supported. + // therefore we can conclude that they are instead intended as animation frames. + // That is why we treat them as animation frames. + spriteSheetRotIndex = Math.floor(Date.now()/32) % rules.spritesheet.length; + } else if(rules.spritesheet[spriteSheetRotIndex].spritesheet.length){ + var animationStage = Math.floor(Date.now()/16) % rules.spritesheet[spriteSheetRotIndex].spritesheet.length; + var usesAnimation = true; + } else { + var usesAnimation = false; + } + + if(usesAnimation){ + try{ + sprWidth = rules.spritesheet[spriteSheetRotIndex].spritesheet[animationStage].frame.w; + sprHeight = rules.spritesheet[spriteSheetRotIndex].spritesheet[animationStage].frame.h; + offLeft = rules.spritesheet[spriteSheetRotIndex].spritesheet[animationStage].frame.x; + offTop = rules.spritesheet[spriteSheetRotIndex].spritesheet[animationStage].frame.y; + }catch(e){} // TODO throws error due to yellow belt rendering + } else { + sprWidth = rules.spritesheet[spriteSheetRotIndex].spritesheet.frame.w; + sprHeight = rules.spritesheet[spriteSheetRotIndex].spritesheet.frame.h; + offLeft = rules.spritesheet[spriteSheetRotIndex].spritesheet.frame.x; + offTop = rules.spritesheet[spriteSheetRotIndex].spritesheet.frame.y; + } + image = global.spritesheet; + + if(rules.spritesheet[spriteSheetRotIndex].positionOffset){ + offsetX = rules.spritesheet[spriteSheetRotIndex].positionOffset.x; + offsetY = rules.spritesheet[spriteSheetRotIndex].positionOffset.y; + } + if(rules.spritesheet[spriteSheetRotIndex].sizeInTiles){ + size = { + x: remoteMapConfig.tileSize * rules.spritesheet[spriteSheetRotIndex].sizeInTiles.x, + y: remoteMapConfig.tileSize * rules.spritesheet[spriteSheetRotIndex].sizeInTiles.y, + }; + } + if(rules.spritesheet[spriteSheetRotIndex].flip){ + let flip = rules.spritesheet[spriteSheetRotIndex].flip; + if(flip == "x") flipX = true; + if(flip == "y") flipY = true; + } + } + } else if(rules.spritesheet){ + sprWidth = rules.spritesheet.frame.w; + sprHeight = rules.spritesheet.frame.h; + offLeft = rules.spritesheet.frame.x; + offTop = rules.spritesheet.frame.y; + image = global.spritesheet; + } + } else { + offsetX = 0, offsetY = 0; + size = { + x:remoteMapConfig.tileSize, y: remoteMapConfig.tileSize, + }; + } + let xPos = ((entity.x + offsetX) * remoteMapConfig.tileSize) - playerPosition.x; + let yPos = ((entity.y + offsetY) * remoteMapConfig.tileSize) - playerPosition.y; + if(entity.entity.rot && !isNaN(Number(entity.entity.rot)) && !(entityDrawRules[name] && Array.isArray(entityDrawRules[name].spritesheet))){ + let rules = entityDrawRules[name]; + if(rules && rules.rotOffset){ + rotation = ((entity.entity.rot * 45) + entityDrawRules[name].rotOffset); + } else { + rotation = entity.entity.rot * 45; + } + } + if(!image) image = entityImages[name].img; + // if(name == "oil-refinery") console.log(offsetX) + drawImageWithRotation(ctx, image, xPos, yPos, size.x, size.y, rotation%360, sprWidth, sprHeight, offLeft, offTop, flipX, flipY); + //console.log("Drawing "+name+" at X: "+xPos+", Y: "+yPos+" with with rotation "+rotation); + } else { + // we are waiting for the image to load, push the task to our queue. It will be processed once the image loads. + this.queue.push(entity); + } + } + let imageLoaded = function(){ // process queue and display console.log("Image loaded!"); entityImages[name].loaded = true; @@ -193,82 +580,29 @@ function drawEntity(entity, dontCache){ }); entityImages[name].queue = []; } - entityImages[name].draw = function(entity){ - if(this.loaded){ - let name = entity.entity.name; - let xPos = (entity.x * 16) - playerPosition.x; - let yPos = (entity.y * 16) - playerPosition.y; - let rotation = 0; - if(entity.entity.rot && !isNaN(Number(entity.entity.rot))){ - rotation = entity.entity.rot * 45; - } - - drawImageWithRotation(ctx, entityImages[name].img, xPos, yPos, 16, 16, rotation); - //console.log("Drawing "+name+" at X: "+xPos+", Y: "+yPos); - } else { - this.queue.push(entity); - } - } - entityImages[name].img.src = getImageFromName(name); + entityImages[name].queue.push(entity); + entityImages[name].img.onload = imageLoaded() + + if(entityDrawRules[name] && entityDrawRules[name].spritesheet){ + // imageLoaded(); + } else entityImages[name].img.src = getImageFromName(name); } else { + // console.log("Already got image, drawing") entityImages[name].draw(entity); } } else { // we got an empty coordinate pair, that usually means this tile was occupied before but is empty now console.log("Clearing at X: "+entity.x+", Y: "+entity.y); - ctx.clearRect(entity.x * 16, entity.y * 16, 16, 16); + ctx.clearRect((entity.x + playerPosition.x/remoteMapConfig.tileSize) * remoteMapConfig.tileSize, (entity.y + playerPosition.y/remoteMapConfig.tileSize) * remoteMapConfig.tileSize, remoteMapConfig.tileSize, remoteMapConfig.tileSize); } } else { - throw new Error("drawEntity on entity without x and y coordinates") + console.log(entity); + throw new Error("drawEntity on entity without x and y coordinates"); } } -function drawChunk(chunk, ctx){ - Object.keys(chunk.dataObject).forEach(xValue => { - let xRow = chunk.dataObject[xValue]; - Object.keys(xRow).forEach(yValue => { - let yCell = xRow[yValue]; - if(yCell && yCell.name && yCell.name){ - let img = new Image(); - let xPos = (xValue*16)+(chunk.position.x*64*16)+(64*16*3); - let yPos = (yValue*16)+(chunk.position.y*64*16)+(64*16); - img.onload = function() { - ctx.drawImage(img, xPos, yPos, 16, 16); - console.log("X: "+xPos+", Y: "+yPos); - }; - img.src = getImageFromName(yCell.name); - //img.src = entityImages[yCell.name].src; - } - }); - }); -} function clear(){ ctx.clearRect(0, 0, canvas.width, canvas.height); + selectionCtx.clearRect(0, 0, selectionCanvas.width, selectionCanvas.height); + backgroundCtx.clearRect(0, 0, backgroundCanvas.width, backgroundCanvas.height); } - -/* -/// ZOOMING AND PANNING COPY PASTA =============================================== -// View parameters -var xleftView = 0; -var ytopView = 0; -var widthViewOriginal = 1.0; //actual width and height of zoomed and panned display -var heightViewOriginal = 1.0; -var widthView = widthViewOriginal; //actual width and height of zoomed and panned display -var heightView = heightViewOriginal; - -window.addEventListener("load",setup,false); -function setup() { - canvas = document.getElementById("canvas"); - ctx = canvas.getContext("2d"); - - widthCanvas = canvas.width; - heightCanvas = canvas.height; - - canvas.addEventListener("dblclick", handleDblClick, false); // dblclick to zoom in at point, shift dblclick to zoom out. - canvas.addEventListener("mousedown", handleMouseDown, false); // click and hold to pan - canvas.addEventListener("mousemove", handleMouseMove, false); - canvas.addEventListener("mouseup", handleMouseUp, false); - canvas.addEventListener("mousewheel", handleMouseWheel, false); // mousewheel duplicates dblclick function - canvas.addEventListener("DOMMouseScroll", handleMouseWheel, false); // for Firefox - - draw(); -}*/ +// setInterval(()=>console.log(entityDrawRules),5000); diff --git a/static/remoteMap/itemSelection.js b/static/remoteMap/itemSelection.js new file mode 100644 index 00000000..f01a9adb --- /dev/null +++ b/static/remoteMap/itemSelection.js @@ -0,0 +1,85 @@ +export class itemSelector { + constructor(containerSelector, entities){ + this.containerSelector = containerSelector; + this.container = document.querySelector(containerSelector); + if(!this.container) throw new Error("Could not find container "+container); + this.entities = entities; + this.direction = 0; + + // populate container + let cont = this.container; + let HTML = ""; + HTML += "
"; + HTML += "

Item selection

"; + HTML += "
"; + HTML += "
"; + HTML += "Name: "; + HTML += ""; + HTML += "
"; + // direction selector + HTML += "
"; + HTML += "

Direction:

"; + HTML += "

"+this.directionToCardinal(0)+"

" + HTML += "

Press R to rotate

"; + HTML += "
"; + + // write styles + let styles = { + ".header > h2":{ + color:"white", + }, + ".blackText":{ + color:"black", + }, + ".blackText > option":{ + color:"black", + } + } + + // turn style object into style tag + HTML += ""; + + // handle direction keyboard event + Mousetrap.bind('r', ()=>this.rotate()); + } + directionToCardinal(dir){ + if(dir == 0){ + return "north"; + } else if(dir == 1){ + return "north-east"; + } else if(dir == 2){ + return "east"; + } else if(dir == 3){ + return "south-east"; + } else if(dir == 4){ + return "south"; + } else if(dir == 5){ + return "south-west"; + } else if(dir == 6){ + return "west"; + } else if(dir == 7){ + return "north-west"; + } + } + rotate(){ + this.direction = (this.direction + 2) % 8; + // update display + document.querySelector("#directionDisplay").innerHTML = this.directionToCardinal(this.direction); + } + getItem(){ + let name = document.querySelector(this.containerSelector+" > .itemSelector > select").value; + let direction = this.direction; + return {name, direction}; + } +} \ No newline at end of file diff --git a/static/slaveDisplay.js b/static/slaveDisplay.js index e5858729..f3015540 100644 --- a/static/slaveDisplay.js +++ b/static/slaveDisplay.js @@ -19,12 +19,14 @@ setTimeout(function() { // detect if remoteMap mod is installed, if it is we want to show the link for it let hasRemoteMap = false; - slaveData[key].mods.forEach(mod => { - console.log(mod.modName); - if(mod.modName.includes("remoteMap")){ - hasRemoteMap = true; // we are still doing the logic on the outside, in case there are multiple instances of remoteMap installed.... - } - }); + if(slaveData[key].mods){ // not all instances have mods apparently + slaveData[key].mods.forEach(mod => { + console.log(mod.modName); + if(mod.modName.includes("remoteMap")){ + hasRemoteMap = true; // we are still doing the logic on the outside, in case there are multiple instances of remoteMap installed.... + } + }); + } if(hasRemoteMap){ HTML += "Remote map" } diff --git a/static/style.css b/static/style.css index 2b026e69..4ac61394 100644 --- a/static/style.css +++ b/static/style.css @@ -271,4 +271,7 @@ input:checked + .slider:before { -webkit-transform: translateX(26px); -ms-transform: translateX(26px); transform: translateX(26px); +} +canvas { + -webkit-transform:translateZ(0) } \ No newline at end of file