//these settings are defined in the firmware (conf_defaults.lua) and will be initialized in loadSettings() var settings = { "network.ap.ssid": "d3d-ap-%%MAC_ADDR_TAIL%%", "network.ap.address": "192.168.10.1", "network.ap.netmask": "255.255.255.0", "printer.temperature": 220, "printer.maxObjectHeight": 150, "printer.layerHeight": 0.2, "printer.wallThickness": 0.7, "printer.screenToMillimeterScale": 0.3, "printer.speed": 50, "printer.travelSpeed": 200, "printer.filamentThickness": 2.85, "printer.enableTraveling": true, "printer.useSubLayers": true, "printer.firstLayerSlow": true, "printer.autoWarmUp": true, "printer.simplify.iterations": 10, "printer.simplify.minNumPoints": 15, "printer.simplify.minDistance": 3, "printer.retraction.enabled": true, "printer.retraction.speed": 50, "printer.retraction.minDistance": 1, "printer.retraction.amount": 5, "printer.autoWarmUpCommand": "M104 S220 (hardcoded temperature)" } function SettingsWindow() { this.wifiboxURL; this.wifiboxCGIBinURL this.window; this.form; this.timeoutTime = 3000; this.retryDelay = 2000; // retry setTimout delay this.retryRetrieveNetworkStatusDelayTime = 1000;// retry setTimout delay this.retryLoadSettingsDelay; // retry setTimout instance this.retrySaveSettingsDelay; // retry setTimout instance this.retryRetrieveNetworkStatusDelay;// retry setTimout instance this.apFieldSet; this.clientFieldSet; this.networks; this.currentNetwork; // the ssid of the network the box is on this.selectedNetwork; // the ssid of the selected network in the client mode settings this.currentLocalIP = ""; this.clientModeState = SettingsWindow.NOT_CONNECTED; this.currentAP; this.apModeState = SettingsWindow.NO_AP; // after switching wifi network or creating a access point we delay the status retrieval // because the webserver needs time to switch this.retrieveNetworkStatusDelay; // setTimout delay this.retrieveNetworkStatusDelayTime = 1000; // Events SettingsWindow.SETTINGS_LOADED = "settingsLoaded"; // network client mode states SettingsWindow.NOT_CONNECTED = "not connected"; // also used as first item in networks list SettingsWindow.CONNECTED = "connected"; SettingsWindow.CONNECTING = "connecting"; SettingsWindow.CONNECTING_FAILED = "connecting failed" // network access point mode states SettingsWindow.NO_AP = "no ap"; SettingsWindow.AP = "ap"; SettingsWindow.CREATING_AP = "creating ap"; SettingsWindow.API_CONNECTING_FAILED = -1 SettingsWindow.API_NOT_CONNECTED = 0 SettingsWindow.API_CONNECTING = 1 SettingsWindow.API_CONNECTED = 2 SettingsWindow.API_CREATING = 3 SettingsWindow.API_CREATED = 4 // network mode SettingsWindow.NETWORK_MODE_NEITHER = "neither"; SettingsWindow.NETWORK_MODE_CLIENT = "clientMode"; SettingsWindow.NETWORK_MODE_ACCESS_POINT = "accessPointMode"; this.networkMode = SettingsWindow.NETWORK_MODE_NEITHER; this.updatePanel = new UpdatePanel(); var self = this; this.init = function(wifiboxURL,wifiboxCGIBinURL) { this.wifiboxURL = wifiboxURL; this.wifiboxCGIBinURL = wifiboxCGIBinURL; this.window = $("#settings"); this.window.find(".btnOK").click(this.submitwindow); this.window.find(".settingsContainer").load("settings.html", function() { console.log("Settings:finished loading settings.html, now loading settings..."); self.form = self.window.find("form"); self.form.submit(function (e) { self.submitwindow(e) }); self.loadSettings(); var btnAP = self.form.find("label[for='ap']"); var btnClient = self.form.find("label[for='client']"); var btnRefresh = self.form.find("#refreshNetworks"); var btnConnect = self.form.find("#connectToNetwork"); var btnCreate = self.form.find("#createAP"); var networkSelector = self.form.find("#network"); self.apFieldSet = self.form.find("#apSettings"); self.clientFieldSet = self.form.find("#clientSettings"); btnAP.on('touchstart mousedown',self.showAPSettings); btnClient.on('touchstart mousedown',self.showClientSettings); btnRefresh.on('touchstart mousedown',self.refreshNetworks); btnConnect.on('touchstart mousedown',self.connectToNetwork); btnCreate.on('touchstart mousedown',self.createAP); networkSelector.change(self.networkSelectorChanged); // update panel var $updatePanelElement = self.form.find("#updatePanel"); self.updatePanel.init(wifiboxURL,$updatePanelElement); }); } this.submitwindow = function(e) { e.preventDefault(); e.stopPropagation(); self.saveSettings(self.readForm(),function(){ self.hideSettings(); }); clearTimeout(self.retryRetrieveNetworkStatusDelay); } this.showSettings = function() { console.log("f:showSettings()"); this.loadSettings(); // reload settings // this.window.css("display","table"); $("#contentOverlay").fadeIn(375, function() { document.body.removeEventListener('touchmove',prevent,false); }); } this.hideSettings = function() { $("#contentOverlay").fadeOut(375, function() { document.body.addEventListener('touchmove',prevent,false); // self.window.css("display","none"); }); } this.loadSettings = function() { if (!communicateWithWifibox) { console.log(" communicateWithWifibox is false: settings aren't being loaded from wifibox...") return; } console.log("Settings:loadSettings() >> getting new data..."); $.ajax({ url: this.wifiboxURL + "/config/all", dataType: 'json', timeout: this.timeoutTime, success: function(response){ console.log("Settings:loadSettings response: ",response); settings = response.data; console.log(" settings: ",settings); self.fillForm(); $(document).trigger(SettingsWindow.SETTINGS_LOADED); } }).fail(function() { console.log("Settings:loadSettings: failed"); clearTimeout(self.retryLoadSettingsDelay); self.retryLoadSettingsDelay = setTimeout(function() { self.loadSettings() },self.retryDelay); // retry after delay }); this.refreshNetworks(); this.retrieveNetworkStatus(false); } this.fillForm = function() { console.log("SettingsWindow:fillForm"); //fill form with loaded settings var selects = this.form.find("select"); selects.each( function(index,element) { var element = $(element); element.val(settings[element.attr('name')]); }); var inputs = this.form.find("input"); inputs.each( function(index,element) { var element = $(element); //console.log("printer setting input: ",index,element.attr("type"),element.attr('name')); //,element); switch(element.attr("type")) { case "text": case "number": element.val(settings[element.attr('name')]); break; case "checkbox": element.prop('checked', settings[element.attr('name')]); break; } }); var textareas = this.form.find("textarea"); textareas.each( function(index,element) { var element = $(element); var value = settings[element.attr('name')]; element.val(value); }); } this.saveSettings = function(newSettings,complete) { settings = newSettings; // store new settings in global settings if (communicateWithWifibox) { $.ajax({ url: this.wifiboxURL + "/config", type: "POST", data: newSettings, dataType: 'json', timeout: this.timeoutTime, success: function(response){ console.log("Settings:saveSettings response: ",response); if(response.status == "error") { clearTimeout(self.retrySaveSettingsDelay); self.retrySaveSettingsDelay = setTimeout(function() { self.saveSettings(settings) },self.retryDelay); // retry after delay } else { var data = response.data; var validation = data.validation; self.clearValidationErrors(); var validated = true; $.each(validation, function(key, val) { if (val != "ok") { console.log("ERROR: setting '" + key + "' not successfully set. Message: " + val); self.displayValidationError(key,val); validated = false; } }); settings.substituted_ssid = data.substituted_ssid; if(complete && validated) complete(); } } }).fail(function() { console.log("Settings:saveSettings: failed"); clearTimeout(self.retrySaveSettingsDelay); self.retrySaveSettingsDelay = setTimeout(function() { self.saveSettings(settings) },self.retryDelay); // retry after delay }); } } this.displayValidationError = function(key,msg) { var formElement = self.form.find("[name|='"+key+"']"); console.log("formElement: ",formElement); formElement.addClass("error"); var errorMsg = "
"+msg+"
" formElement.after(errorMsg); } this.clearValidationErrors = function() { var formElements = self.form.find(".error"); formElements.each( function(index,element) { $(element).removeClass("error"); }); } this.readForm = function() { //console.log("SettingsWindow:readForm"); var settings = {}; var selects = self.form.find("select"); selects.each( function(index,element) { var element = $(element); if(element.attr('name') != "network.client.network") { settings[element.attr('name')] = element.val(); } }); var inputs = self.form.find("input"); inputs.each( function(index,element) { var element = $(element); switch(element.attr("type")) { case "text": case "number": settings[element.attr('name')] = element.val(); break; case "checkbox": settings[element.attr('name')] = element.prop('checked') break; } }); var textareas = self.form.find("textarea"); textareas.each( function(index,element) { var element = $(element); settings[element.attr('name')] = element.val(); }); //console.log(settings); return settings; } /* * Networks ui */ this.showAPSettings = function() { self.apFieldSet.show(); self.clientFieldSet.hide(); } this.showClientSettings = function() { self.clientFieldSet.show(); self.apFieldSet.hide(); } this.refreshNetworks = function() { console.log("Settings:refreshNetworks"); if (communicateWithWifibox) { $.ajax({ url: self.wifiboxURL + "/network/scan", type: "GET", dataType: 'json', timeout: self.timeoutTime, success: function(response){ console.log("Settings:refreshNetworks response: ",response); if(response.status == "error") { //clearTimeout(self.retrySaveSettingsDelay); //self.retrySaveSettingsDelay = setTimeout(function() { self.saveSettings() },self.retryDelay); // retry after delay } else { var networks = response.data.networks self.networks = {}; var foundCurrentNetwork = false; var networkSelector = self.form.find("#network"); networkSelector.empty(); networkSelector.append( $("").val(SettingsWindow.NOT_CONNECTED).html("not connected") ); $.each(networks, function(index,element) { if(element.ssid == self.currentNetwork) { foundCurrentNetwork = true; } networkSelector.append( $("").val(element.ssid).html(element.ssid) ); self.networks[element.ssid] = element; }); if(foundCurrentNetwork) { networkSelector.val(self.currentNetwork); self.selectNetwork(self.currentNetwork); } } } }).fail(function() { }); } } this.retrieveNetworkStatus = function(connecting) { //console.log("Settings:retrieveNetworkStatus"); if (communicateWithWifibox) { $.ajax({ url: self.wifiboxURL + "/network/status", type: "GET", dataType: 'json', timeout: self.timeoutTime, success: function(response){ console.log("Settings:retrieveNetworkStatus response: ",response); if(response.status == "error") { } else { var data = response.data; if(typeof data.status === 'string') { data.status = parseInt(data.status); } //console.log(" data.status: ",data.status,data.statusMessage); // Determine which network settings to show switch(data.status) { case SettingsWindow.API_NOT_CONNECTED: //console.log(" not connected & not a access point"); self.apFieldSet.show(); self.clientFieldSet.show(); self.networkMode = SettingsWindow.NETWORK_MODE_NEITHER; break; case SettingsWindow.API_CONNECTING_FAILED: case SettingsWindow.API_CONNECTING: case SettingsWindow.API_CONNECTED: //console.log(" client mode"); self.form.find("#client").prop('checked',true); self.apFieldSet.hide(); self.clientFieldSet.show(); if(data.status == SettingsWindow.API_CONNECTED) { var networkSelector = self.form.find("#network"); networkSelector.val(data.ssid); self.currentNetwork = data.ssid; self.currentLocalIP = data.localip; self.selectNetwork(data.ssid); } else { self.currentLocalIP = "" } self.networkMode = SettingsWindow.NETWORK_MODE_CLIENT; break; case SettingsWindow.API_CREATING: case SettingsWindow.API_CREATED: //console.log(" access point mode"); self.form.find("#ap").prop('checked',true); self.apFieldSet.show(); self.clientFieldSet.hide(); self.currentNetwork = undefined; self.selectNetwork(SettingsWindow.NOT_CONNECTED); var networkSelector = self.form.find("#network"); networkSelector.val(SettingsWindow.NOT_CONNECTED); if(data.ssid && data.status == SettingsWindow.API_CREATED) { self.currentAP = data.ssid; } self.networkMode = SettingsWindow.NETWORK_MODE_ACCESS_POINT; break; } self.updatePanel.setNetworkMode(self.networkMode); // update status message switch(data.status) { case SettingsWindow.API_CONNECTING_FAILED: self.setClientModeState(SettingsWindow.CONNECTING_FAILED,data.statusMessage); self.setAPModeState(SettingsWindow.NO_AP,""); break; case SettingsWindow.API_NOT_CONNECTED: self.setClientModeState(SettingsWindow.NOT_CONNECTED,""); self.setAPModeState(SettingsWindow.NO_AP,""); break; case SettingsWindow.API_CONNECTING: self.setClientModeState(SettingsWindow.CONNECTING,""); self.setAPModeState(SettingsWindow.NO_AP,""); break; case SettingsWindow.API_CONNECTED: self.setClientModeState(SettingsWindow.CONNECTED,""); self.setAPModeState(SettingsWindow.NO_AP,""); break; case SettingsWindow.API_CREATING: self.setClientModeState(SettingsWindow.NOT_CONNECTED,""); self.setAPModeState(SettingsWindow.CREATING_AP,""); break; case SettingsWindow.API_CREATED: self.setClientModeState(SettingsWindow.NOT_CONNECTED,""); self.setAPModeState(SettingsWindow.AP,""); break; } // Keep checking for updates? if(connecting) { switch(data.status) { case SettingsWindow.API_CONNECTING: case SettingsWindow.API_CREATING: clearTimeout(self.retryRetrieveNetworkStatusDelay); self.retryRetrieveNetworkStatusDelay = setTimeout(function() { self.retrieveNetworkStatus(connecting) },self.retryRetrieveNetworkStatusDelayTime); // retry after delay break; } } } } }).fail(function() { console.log("Settings:retrieveNetworkStatus: failed"); clearTimeout(self.retryRetrieveNetworkStatusDelay); self.retryRetrieveNetworkStatusDelay = setTimeout(function() { self.retrieveNetworkStatus(connecting) },self.retryDelay); // retry after delay }); } } this.networkSelectorChanged = function(e) { var selectedOption = $(this).find("option:selected"); self.selectNetwork(selectedOption.val()); } this.selectNetwork = function(ssid) { console.log("select network: ",ssid); if(ssid == "") return; console.log(" checked"); this.selectedNetwork = ssid; if(this.networks == undefined || ssid == SettingsWindow.NOT_CONNECTED) { this.hideWiFiPassword(); } else { var network = this.networks[ssid]; if(network.encryption == "none") { this.hideWiFiPassword(); } else { this.showWiFiPassword(); } this.form.find("#password").val(""); } } this.showWiFiPassword = function() { this.form.find("#passwordLabel").show(); this.form.find("#password").show(); } this.hideWiFiPassword = function() { this.form.find("#passwordLabel").hide(); this.form.find("#password").hide(); } this.setClientModeState = function(state,msg) { var field = this.form.find("#clientModeState"); var btnConnect = self.form.find("#connectToNetwork"); switch(state) { case SettingsWindow.NOT_CONNECTED: btnConnect.removeAttr("disabled"); field.html("Not connected"); break; case SettingsWindow.CONNECTED: btnConnect.removeAttr("disabled"); var fieldText = "Connected to: "+this.currentNetwork+"."; if(this.currentLocalIP != undefined && this.currentLocalIP != "") { var a = ""+this.currentLocalIP+""; fieldText += " (IP: "+a+")"; } field.html(fieldText); break; case SettingsWindow.CONNECTING: btnConnect.attr("disabled", true); field.html("Connecting... Reconnect by connecting your device to "+this.selectedNetwork+" and going to connect.doodle3d.com"); break; case SettingsWindow.CONNECTING_FAILED: btnConnect.removeAttr("disabled"); field.html(msg); break; } this.clientModeState = state; } this.setAPModeState = function(state,msg) { var field = this.form.find("#apModeState"); var btnCreate = this.form.find("#createAP"); switch(state) { case SettingsWindow.NO_AP: btnCreate.removeAttr("disabled"); field.html("Not currently a access point"); break; case SettingsWindow.AP: btnCreate.removeAttr("disabled"); field.html("Is access point: "+this.currentAP+""); break; case SettingsWindow.CREATING_AP: btnCreate.attr("disabled", true); field.html("Creating access point... Reconnect by connecting your device to "+settings.substituted_ssid+" and going to draw.doodle3d.com"); break; } this.apModeState = state; } this.connectToNetwork = function() { console.log("connectToNetwork"); if(self.selectedNetwork == undefined) return; var postData = { ssid:self.selectedNetwork, phrase:self.form.find("#password").val(), recreate:true } console.log(" postData: ",postData); if (communicateWithWifibox) { // save network related settings and on complete, connect to network self.saveSettings(self.readForm(),function() { $.ajax({ url: self.wifiboxCGIBinURL + "/network/associate", type: "POST", data: postData, dataType: 'json', timeout: self.timeoutTime, success: function(response){ console.log("Settings:connectToNetwork response: ",response); } }).fail(function() { console.log("Settings:connectToNetwork: timeout (normal behavior)"); //clearTimeout(self.retrySaveSettingsDelay); //self.retrySaveSettingsDelay = setTimeout(function() { self.saveSettings() },self.retryDelay); // retry after delay }); }); } self.setClientModeState(SettingsWindow.CONNECTING,""); // after switching wifi network or creating a access point we delay the status retrieval // because the webserver needs time to switch clearTimeout(self.retrieveNetworkStatusDelay); self.retrieveNetworkStatusDelay = setTimeout(function() { self.retrieveNetworkStatus(true) },self.retrieveNetworkStatusDelayTime); } this.createAP = function() { console.log("createAP"); if (communicateWithWifibox) { // save network related settings and on complete, create access point self.saveSettings(self.readForm(),function() { self.setAPModeState(SettingsWindow.CREATING_AP); // get latest substituted ssid $.ajax({ url: self.wifiboxCGIBinURL + "/network/openap", type: "POST", dataType: 'json', timeout: self.timeoutTime, success: function(response){ console.log("Settings:createAP response: ",response); } }).fail(function() { console.log("Settings:createAP: timeout (normal behavior)"); //clearTimeout(self.retrySaveSettingsDelay); //self.retrySaveSettingsDelay = setTimeout(function() { self.saveSettings() },self.retryDelay); // retry after delay }); self.setAPModeState(SettingsWindow.CREATING_AP,""); // after switching wifi network or creating a access point we delay the status retrieval // because the webserver needs time to switch clearTimeout(self.retrieveNetworkStatusDelay); self.retrieveNetworkStatusDelay = setTimeout(function() { self.retrieveNetworkStatus(true) },self.retrieveNetworkStatusDelayTime); }); } } } /************************* * * * FROM DOODLE3D.INI * */ //TODO: find all references to these variables, replace them and finally remove these. var objectHeight = 20; var layerHeight = .2; //var wallThickness = .5; //var hop = 0; //var speed = 70; //var travelSpeed = 200; var enableTraveling = true; //var filamentThickness = 2.89; var minScale = .3; var maxScale = 1; var shape = "%"; var twists = 0; //var useSubLayers = true; //var debug = false; // debug moved to main.js var loglevel = 2; //var zOffset = 0; var serverport = 8888; var autoLoadImage = "hand.txt"; var loadOffset = [0, 0]; // x en y ? var showWarmUp = true; var loopAlways = false; var firstLayerSlow = true; var useSubpathColors = false; var autoWarmUp = true; //var maxObjectHeight = 150; var maxScaleDifference = .1; var frameRate = 60; var quitOnEscape = true; var screenToMillimeterScale = .3; // 0.3 //var targetTemperature = 220; //var simplifyiterations = 10; //var simplifyminNumPoints = 15; //var simplifyminDistance = 3; //var retractionspeed = 50; //var retractionminDistance = 5; //var retractionamount = 3; var sideis3D = true; var sidevisible = true; var sidebounds = [900, 210, 131, 390]; var sideborder = [880, 169, 2, 471]; var windowbounds = [0, 0, 800, 500]; var windowcenter = true; var windowfullscreen = false; var autoWarmUpCommand = "M104 S230"; //var checkTemperatureInterval = 3; var autoWarmUpDelay = 3; function UpdatePanel() { this.wifiboxURL; this.element; this.statusCheckInterval = 1000; this.statusCheckDelayer; // setTimout instance this.installedDelay = 60*1000; // Since we can't retrieve status during installation we show the installed text after a fixed delay this.installedDelayer; // setTimout instance this.retryDelay = 1000; this.retryDelayer; // setTimout instance //this.timeoutTime = 3000; this.canUpdate = false; this.currentVersion = ""; this.newestVersion; this.progress; this.imageSize; // states from api, see Doodle3D firmware src/script/d3d-updater.lua UpdatePanel.NONE = 1; // default state UpdatePanel.DOWNLOADING = 2; UpdatePanel.DOWNLOAD_FAILED = 3; UpdatePanel.IMAGE_READY = 4; // download successfull and checked UpdatePanel.INSTALLING = 5; UpdatePanel.INSTALLED = 6; UpdatePanel.INSTALL_FAILED = 7; this.state; // update state from api this.stateText = ""; // update state text from api this.networkMode; // network modes from SettingsWindow var self = this; this.init = function(wifiboxURL,updatePanelElement) { this.wifiboxURL = wifiboxURL; this.element = updatePanelElement; this.btnUpdate = this.element.find("#update"); this.statusDisplay = this.element.find("#updateState"); this.infoDisplay = this.element.find("#updateInfo"); this.btnUpdate.click(this.update); this.checkStatus(false); } this.update = function() { console.log("UpdatePanel:update"); self.downloadUpdate(); } this.downloadUpdate = function() { console.log("UpdatePanel:downloadUpdate"); $.ajax({ url: self.wifiboxURL + "/update/download", type: "POST", dataType: 'json', success: function(response){ console.log("UpdatePanel:downloadUpdate response: ",response); } }).fail(function() { console.log("UpdatePanel:downloadUpdate: failed"); }); self.setState(UpdatePanel.DOWNLOADING); self.startCheckingStatus(); } this.installUpdate = function() { console.log("UpdatePanel:installUpdate"); self.stopCheckingStatus(); $.ajax({ url: self.wifiboxURL + "/update/install", type: "POST", dataType: 'json', success: function(response){ console.log("UpdatePanel:installUpdate response: ",response); } }).fail(function() { console.log("UpdatePanel:installUpdate: no respons (there shouldn't be)"); }); self.setState(UpdatePanel.INSTALLING); clearTimeout(self.installedDelayer); self.installedDelayer = setTimeout(function() { self.setState(UpdatePanel.INSTALLED) },self.installedDelay); } this.startCheckingStatus = function() { clearTimeout(self.statusCheckDelayer); clearTimeout(self.retryDelayer); self.statusCheckDelayer = setTimeout(function() { self.checkStatus(true) },self.statusCheckInterval); } this.stopCheckingStatus = function() { clearTimeout(self.statusCheckDelayer); clearTimeout(self.retryDelayer); } this.checkStatus = function(keepChecking) { if (!communicateWithWifibox) return; $.ajax({ url: self.wifiboxURL + "/update/status", type: "GET", dataType: 'json', //timeout: self.timeoutTime, success: function(response){ console.log("UpdatePanel:checkStatus response: ",response); // Keep checking ? if(keepChecking) { switch(self.state){ case UpdatePanel.DOWNLOADING: case UpdatePanel.INSTALLING: clearTimeout(self.statusCheckDelayer); self.statusCheckDelayer = setTimeout(function() { self.checkStatus(keepChecking) },self.statusCheckInterval); break; } } if(response.status != "error") { var data = response.data; self.handleStatusData(data); } } }).fail(function() { //console.log("UpdatePanel:checkStatus: failed"); if(keepChecking) { clearTimeout(self.retryDelayer); self.retryDelayer = setTimeout(function() { self.checkStatus(keepChecking) },self.retryDelay); // retry after delay } }); } this.handleStatusData = function(data) { //console.log("UpdatePanel:handleStatusData"); self.canUpdate = data.can_update; if(self.currentVersion != data.current_version || self.newestVersion != data.newest_version) { self.currentVersion = data.current_version; self.newestVersion = data.newest_version; self.updateInfoDisplay(); } self.stateText = data.state_text; self.progress = data.progress; // not always available self.imageSize = data.image_size; // not always available self.setState(data.state_code); switch(this.state){ case UpdatePanel.IMAGE_READY: self.installUpdate(); break; } } this.setState = function(newState) { if(this.state == newState) return; console.log("UpdatePanel:setState: ",this.state," > ",newState,"(",this.stateText,") (networkMode: ",self.networkMode,") (newestVersion: ",self.newestVersion,")"); this.state = newState; // download button // if there isn't newestVersion data something went wrong, // probably accessing the internet if(self.newestVersion != undefined) { switch(this.state){ case UpdatePanel.NONE: case UpdatePanel.DOWNLOAD_FAILED: case UpdatePanel.INSTALL_FAILED: if(self.canUpdate) { self.btnUpdate.removeAttr("disabled"); } else { self.btnUpdate.attr("disabled", true); } break; default: self.btnUpdate.attr("disabled", true); break; } } else { self.btnUpdate.attr("disabled", true); } this.updateStatusDisplay(); } this.updateStatusDisplay = function() { var text = ""; if(self.newestVersion != undefined) { switch(this.state){ case UpdatePanel.NONE: if(self.canUpdate) { text = "Update(s) available."; } else { text = "You're up to date."; } break; case UpdatePanel.DOWNLOADING: text = "Downloading update..."; break; case UpdatePanel.DOWNLOAD_FAILED: text = "Downloading update failed."; break; case UpdatePanel.IMAGE_READY: text = "Update downloaded."; break; case UpdatePanel.INSTALLING: text = "Installing update... (will take a minute)"; break; case UpdatePanel.INSTALLED: text = "Update complete, please refresh Page."; break; case UpdatePanel.INSTALL_FAILED: text = "Installing update failed."; break; } } else { if(self.networkMode == SettingsWindow.NETWORK_MODE_ACCESS_POINT) { text = "Can't access internet in access point mode."; } else { text = "Can't access internet."; } } this.statusDisplay.html(text); } this.updateInfoDisplay = function() { var text = "Current version: "+self.currentVersion+". "; if(self.canUpdate) { text += "Latest version: "+self.newestVersion+"."; } self.infoDisplay.text(text); } this.setNetworkMode = function(networkMode) { self.networkMode = networkMode; } } function setTemperature(callback) { if (callback != undefined) callback(); } function setTemperature(callback) { if (callback != undefined) callback(); } var VERTICALSHAPE; var verticalShapes = { "NONE": 'none', "DIVERGING": 'diverging', "CONVERGING": 'converging', "SINUS": 'sinus' }; function initVerticalShapes() { // TODO give these vertical shapes a better spot VERTICALSHAPE = verticalShapes.NONE; $(".verticalShapes, .straight").on('mouseup touchend', function(e) { e.preventDefault(); console.log("diverging"); VERTICALSHAPE = verticalShapes.NONE; redrawRenderedPreview(); }) $(".verticalShapes, .diverging").on('mouseup touchend', function(e) { e.preventDefault(); console.log("diverging"); VERTICALSHAPE = verticalShapes.DIVERGING; redrawRenderedPreview(); }) $(".verticalShapes, .converging").on('mouseup touchend', function(e) { e.preventDefault(); console.log("converging"); VERTICALSHAPE = verticalShapes.CONVERGING; redrawRenderedPreview(); }) $(".verticalShapes, .sinus").on('mouseup touchend', function(e) { e.preventDefault(); console.log("sinus"); VERTICALSHAPE = verticalShapes.SINUS; redrawRenderedPreview(); }) } function resetVerticalShapes() { VERTICALSHAPE = verticalShapes.NONE; } var btnMoveUpInterval; var btnMoveDownInterval; var btnTwistLeftInterval; var btnTwistRightInterval; var twistIncrement = Math.PI/1800; var btnOopsInterval; var btnNew, btnPrevious, btnNext; var btnOops, btnStop, btnClear; var btnMoveUp, btnMoveDown, btnTwistLeft, btnTwistRight; var btnInfo, btnSettings; //var btnDebug; // debug var state; var prevState; var hasControl; var gcodeGenerateDelayer; var gcodeGenerateDelay = 50; function initButtonBehavior() { console.log("f:initButtonBehavior"); // btnClear= $(".btnClear"); btnOops = $(".btnOops"); btnMoveUp = $("#btnMoveUp"); btnMoveDown = $("#btnMoveDown"); btnTwistLeft = $("#btnTwistLeft"); btnTwistRight = $("#btnTwistRight"); btnInfo = $(".btnInfo"); btnSettings = $(".btnSettings"); btnNew = $(".btnNew"); btnPrint= $(".btnPrint"); btnStop = $(".btnStop"); btnPrevious = $(".btnPrevious"); btnNext = $(".btnNext"); //debug //btnDebug = $(".debugBtn"); btnNew.on('touchstart mousedown', clearDoodle); btnPrint.on('touchstart mousedown', print); // not using these at the moment $("#btnPrevious").css("opacity", "0.3"); btnNext.css("opacity", "0.3"); $("#btnSave").css("opacity", "0.3"); btnInfo.css("opacity", "0.3"); // btnClear.click(function(e) { // e.preventDefault(); // // console.log("clear"); // // clearDoodle(); // }); function startOops(e) { // console.log("btnOops mouse down"); e.preventDefault(); btnOopsInterval = setInterval( function() { oopsUndo(); }, 1000/50); } function stopOops(e) { // console.log("btnOops mouse up"); e.preventDefault(); clearInterval(btnOopsInterval); } btnOops.on('touchstart', function(e) { startOops(e); }); btnOops.on('touchend', function(e) { stopOops(e); }); btnOops.mousedown(function(e) { startOops(e); }); btnOops.mouseup(function(e) { stopOops(e); }); function startMoveUp(e) { e.preventDefault(); // console.log("btnMoveUp mouse down"); previewUp(true); clearInterval(btnMoveUpInterval); btnMoveUpInterval = setInterval( function() { previewUp(true); }, 1000/30); } function stopMoveUp(e) { e.preventDefault(); console.log("btnMoveUp mouse up"); clearInterval(btnMoveUpInterval); previewUp(); } btnMoveUp.mousedown(function(e) { startMoveUp(e) }); btnMoveUp.mouseup(function(e) { stopMoveUp(e) }); btnMoveUp.on('touchstart', function(e) { startMoveUp(e) }); btnMoveUp.on('touchend', function(e) { stopMoveUp(e) }); function startMoveDown(e) { e.preventDefault(); // console.log("btnMoveDown mouse down"); previewDown(true); clearInterval(btnMoveDownInterval); btnMoveDownInterval = setInterval( function() { previewDown(true); }, 1000/30); } function stopMoveDown(e) { e.preventDefault(); console.log("btnMoveDown mouse up"); clearInterval(btnMoveDownInterval); previewDown(); } btnMoveDown.mousedown(function(e) { startMoveDown(e) }); btnMoveDown.mouseup(function(e) { stopMoveDown(e) }); btnMoveDown.on('touchstart', function(e) { startMoveDown(e) }); btnMoveDown.on('touchend', function(e) { stopMoveDown(e) }); function startTwistLeft(e) { e.preventDefault(); // console.log("btnTwistLeft mouse down"); previewTwistLeft(true); clearInterval(btnTwistLeftInterval); btnTwistLeftInterval = setInterval( function() { previewTwistLeft(true); }, 1000/30); } function stopTwistLeft(e) { e.preventDefault(); // console.log("btnTwistLeft mouse up"); clearInterval(btnTwistLeftInterval); previewTwistLeft(); } btnTwistLeft.mousedown(function(e) { startTwistLeft(e) }); btnTwistLeft.mouseup(function(e) { stopTwistLeft(e) }); btnTwistLeft.on('touchstart', function(e) { startTwistLeft(e) }); btnTwistLeft.on('touchend', function(e) { stopTwistLeft(e) }); function startTwistRight(e) { e.preventDefault(); // console.log("btnTwistRight mouse down"); previewTwistRight(true); clearInterval(btnTwistRightInterval); btnTwistRightInterval = setInterval( function() { previewTwistRight(true); }, 1000/30); } function stopTwistRight(e) { e.preventDefault(); // console.log("btnTwistRight mouse up"); clearInterval(btnTwistRightInterval); previewTwistRight(); } btnTwistRight.mousedown(function(e) { startTwistRight(e) }); btnTwistRight.mouseup(function(e) { stopTwistRight(e) }); btnTwistRight.on('touchstart', function(e) { startTwistRight(e) }); btnTwistRight.on('touchend', function(e) { stopTwistRight(e) }); /*function openSettings() { console.log("f:openSettings()"); $("#contentOverlay").fadeIn(1000, function() { loadSettings(); }); }*/ btnSettings.bind('touchstart mousedown',function () { //e.preventDefault(); //console.log("btnSettings clicked"); settingsWindow.showSettings(); }); // btnSettings.on('touchend', function(e) { // e.preventDefault(); // console.log("btnSettings touchend"); // }); btnInfo.mouseup(function(e) { e.preventDefault(); console.log("btnInfo mouse up"); }); // DEBUG /* // $(".agentInfo").css("display", "none"); btnDebug.click(function(e) { console.log("debugClick"); $(".agentInfo").toggleClass("agentInfoToggle"); e.preventDefault(); }) //*/ //btnStop.on('touchstart mousedown',stopPrint); } function stopPrint() { console.log("f:stopPrint() >> sendPrintCommands = " + sendPrintCommands); //if (!confirm("Weet je zeker dat je huidige print wilt stoppen?")) return; if (sendPrintCommands) printer.stop(); //setState(Printer.STOPPING_STATE,printer.hasControl); printer.overruleState(Printer.STOPPING_STATE); } function prevDoodle(e) { console.log("f:prevDoodle()"); console.log("f:prevDoodle()"); } function nextDoodle(e) { console.log("f:nextDoodle()"); } function print(e) { console.log("f:print() >> sendPrintCommands = " + sendPrintCommands); //$(".btnPrint").css("display","none"); if (_points.length > 2) { //setState(Printer.BUFFERING_STATE,printer.hasControl); printer.overruleState(Printer.BUFFERING_STATE); btnStop.css("display","none"); // hack // we put the gcode generation in a little delay // so that for example the print button is disabled right away clearTimeout(gcodeGenerateDelayer); gcodeGenerateDelayer = setTimeout(function() { var gcode = generate_gcode(); if (sendPrintCommands) { if(gcode.length > 0) { printer.print(gcode); } else { printer.overruleState(Printer.IDLE_STATE); printer.startStatusCheckInterval(); } } else { console.log("sendPrintCommands is false: not sending print command to 3dprinter"); } if (debugMode) { $("#textdump").text(""); $("#textdump").text(gcode.join("\n")); } }, gcodeGenerateDelay); } else { console.log("f:print >> not enough points!"); } //alert("Je tekening zal nu geprint worden"); //$(".btnPrint").css("display","block"); // $.post("/doodle3d.of", { data:output }, function(data) { // btnPrint.disabled = false; // }); } function clearMainView() { // console.log("f:clearMainView()"); ctx.save(); ctx.clearRect(0,0,canvas.width, canvas.height); ctx.restore(); } function resetPreview() { // console.log("f:resetPreview()"); // clear preview canvas previewCtx.save(); previewCtx.clearRect(0,0,canvas.width, canvas.height); previewCtx.restore(); // reset height and rotation to default values numLayers = previewDefaults.numLayers; // current number of preview layers rStep = previewDefaults.rotation; // Math.PI/180; //Math.PI/40; // } function oopsUndo() { // console.log("f:oopsUndo()"); _points.pop(); redrawDoodle(); redrawPreview(); } function previewUp(redrawLess) { // console.log("f:previewUp()"); if (numLayers < maxNumLayers) { numLayers++; } // redrawPreview(redrawLess); redrawRenderedPreview(redrawLess); } function previewDown(redrawLess) { // console.log("f:previewDown()"); if (numLayers > minNumLayers) { numLayers--; } // redrawPreview(redrawLess); redrawRenderedPreview(redrawLess); } function previewTwistLeft(redrawLess) { if (redrawLess == undefined) redrawLess = false; // console.log("f:previewTwistLeft()"); if (rStep > -previewRotationLimit) rStep -= twistIncrement; // redrawPreview(redrawLess); redrawRenderedPreview(redrawLess); } function previewTwistRight(redrawLess) { // console.log("f:previewTwistRight()"); if (rStep < previewRotationLimit) rStep += twistIncrement; // redrawPreview(redrawLess); redrawRenderedPreview(redrawLess); } function update() { setState(printer.state,printer.hasControl); thermometer.update(printer.temperature, printer.targetTemperature); progressbar.update(printer.currentLine, printer.totalLines); } function setState(newState,newHasControl) { if(newState == state && newHasControl == hasControl) return; prevState = state; console.log("setState: ",prevState," > ",newState," ( ",newHasControl,")"); setDebugText("State: "+newState); // print button var printEnabled = (newState == Printer.IDLE_STATE && newHasControl); if(printEnabled) { btnPrint.removeClass("disabled"); // enable print button btnPrint.unbind('touchstart mousedown'); btnPrint.bind('touchstart mousedown',print); } else { btnPrint.addClass("disabled"); // disable print button btnPrint.unbind('touchstart mousedown'); } // stop button var stopEnabled = ((newState == Printer.PRINTING_STATE || newState == Printer.BUFFERING_STATE) && newHasControl); if(stopEnabled) { btnStop.removeClass("disabled"); btnStop.unbind('touchstart mousedown'); btnStop.bind('touchstart mousedown',stopPrint); } else { btnStop.addClass("disabled"); btnStop.unbind('touchstart mousedown'); } // thermometer switch(newState) { case Printer.IDLE_STATE: case Printer.BUFFERING_STATE: case Printer.PRINTING_STATE: case Printer.STOPPING_STATE: thermometer.show(); break; default: thermometer.hide(); break; } // progress indicator switch(newState) { case Printer.PRINTING_STATE: progressbar.show(); break; default: progressbar.hide(); break; } if(newState == Printer.WIFIBOX_DISCONNECTED_STATE) { message.set("Lost connection to WiFi box",Message.ERROR); } else if(prevState == Printer.WIFIBOX_DISCONNECTED_STATE) { message.set("Connected to WiFi box",Message.INFO,true); } else if(newState == Printer.DISCONNECTED_STATE) { message.set("Printer disconnected",Message.WARNING,true); } else if(prevState == Printer.DISCONNECTED_STATE && newState == Printer.IDLE_STATE || prevState == Printer.UNKNOWN_STATE && newState == Printer.IDLE_STATE) { message.set("Printer connected",Message.INFO,true); } state = newState; hasControl = newHasControl; } /* * * * * * * * * * * * VARS * * * * * * * * * * */ var preview; var previewCtx; var svgPathRegExp = /[LM]\d* \d*/ig; var svgPathParamsRegExp = /([LM])(\d*) (\d*)/; var dragging = false; var $canvas, canvas, ctx; var canvasWidth, canvasHeight; var drawCanvas; var drawCanvasTopLeftCoords = [0, 0]; var doodleBounds = [-1, -1, -1, -1]; // left, top, right, bottom // var doodleScaleVals = [[0, 0], [1.0, 1.0]]; // [ [x, y], [scaleX, scaleY] ] var doodleTransform = [0, 0, 1.0, 1.0]; // [ x, y, scaleX, scaleY ] var _points = []; var prevCountingTime = 0; var movementCounter = 0; var drawVariableLineWeight = false; // set to true to have the momentum of the mouse/touch movement result in larger/smaller strokes var lineweight = 2; /* * * * * * * * * * * * INIT * * * * * * * * * * */ function initDoodleDrawing() { console.log("f:initDoodleDrawing()"); $canvas = $("#mycanvas"); canvas = $canvas[0]; ctx = canvas.getContext('2d'); canvasWidth = canvas.width; canvasHeight = canvas.height; //* //TODO make these jquery eventhandlers (works for all) if (!canvas.addEventListener) { canvas.attachEvent('onmousedown',onCanvasMouseDown); canvas.attachEvent('onmousemove',onCanvasMouseMove); canvas.attachEvent('onmouseup',onCanvasMouseUp); canvas.attachEvent('ontouchstart',onCanvasTouchDown); canvas.attachEvent('ontouchmove',onCanvasTouchMove); canvas.attachEvent('ontouchend',onCanvasTouchEnd); document.body.attachEvent('ontouchmove',prevent); } else { canvas.addEventListener('mousedown',onCanvasMouseDown,false); canvas.addEventListener('mousemove',onCanvasMouseMove,false); canvas.addEventListener('mouseup',onCanvasMouseUp,false); canvas.addEventListener('touchstart',onCanvasTouchDown,false); canvas.addEventListener('touchmove',onCanvasTouchMove,false); canvas.addEventListener('touchend',onCanvasTouchEnd,false); if (!debugMode) document.body.addEventListener('touchmove',prevent,false); } //*/ // drawCanvas = $(".drawareacontainer"); drawCanvas = $("#mycanvasContainer"); // $("#drawAreaContainer") console.log("drawCanvasTopLeftCoords: " + drawCanvasTopLeftCoords); // drawCanvasTopLeftCoords[0] = drawCanvas.css("left").match(/[0-9]/g).join(""); // drawCanvasTopLeftCoords[1] = drawCanvas.css("top").match(/[0-9]/g).join(""); drawCanvasTopLeftCoords[0] = drawCanvas.offset().left; drawCanvasTopLeftCoords[1] = drawCanvas.offset().top; // drawCanvasTopLeftCoords[0] = drawCanvas[0].offsetParent.offsetLeft; // drawCanvasTopLeftCoords[1] = drawCanvas[0].offsetParent.offsetTop; console.log("f:initDoodleDrawing() >> canvasWidth: " + canvasWidth); console.log("f:initDoodleDrawing() >> canvasHeight: " + canvasHeight); } /* * * * * * * * * * * * CANVAS DRAWING FUNCTION * * * * * * * * * * */ function draw(_x, _y, _width) { // console.log("f:draw() >> _width: " + _width); if (prevX == 0 && prevY ==0) { prevX = _x; prevY = _y; } ctx.beginPath(); ctx.moveTo(prevX, prevY); ctx.lineTo(_x, _y); if (_width != undefined) { ctx.lineWidth = _width; } else { if (drawVariableLineWeight) { var dist = Math.sqrt(Math.pow((prevX - _x), 2) + Math.pow((prevY - _y), 2)); if (dist < 10) { lineweight += .25; } else if (dist < 20) { lineweight += .5; } else if (dist < 30) { lineweight += .75; } else if (dist < 50) { lineweight += 1; } else if (dist < 80) { lineweight += 1.5; } else if (dist < 120) { lineweight += 2.25; } else if (dist < 170) { lineweight += 3.5; } else { lineweight += 2; } lineweight = Math.min(lineweight, 30); lineweight *= 0.90; lineweight = Math.max(lineweight, 1.0); } else { lineweight = 2; } ctx.lineWidth = lineweight; } ctx.lineCap = 'round'; ctx.stroke(); prevX = _x; prevY = _y; } /* * * * * * * * * * * * SUPPORTING FUNCTIONS * * * * * * * * * * */ function clearDoodle() { console.log("f:clearDoodle"); _points = []; prevX = 0; prevY = 0; updatePrevX = -1; updatePrevY = -1; doodleBounds = [-1, -1, -1, -1]; // left, top, right, bottom doodleTransform = [0, 0, 1.0, 1.0]; // [ x, y, scaleX, scaleY ] dragging = false; clearMainView(); resetPreview(); resetVerticalShapes(); } function redrawDoodle() { console.log("f:redrawDoodle()"); clearMainView(); prevX = 0; prevY = 0; for (var i = 0; i < _points.length; i++) { // console.log(" drawing points " + _points[i]); if (_points[i][2] == true) { draw(_points[i][0], _points[i][1], 0.5); } else { draw(_points[i][0], _points[i][1]); } } } function adjustBounds(x, y) { var newPointsOutsideOfCurrentBounds = false; console.log("f:adjustBounds("+x+","+y+")"); if (doodleBounds[0] == -1) { // if doodleBounds[0] is -1 then it isn't initted yet, so x and y are both the min and max vals doodleBounds[0] = x; doodleBounds[1] = y; doodleBounds[2] = x; doodleBounds[3] = y; return; } if (x < doodleBounds[0]) { doodleBounds[0] = x; newPointsOutsideOfCurrentBounds = true; } if (x > doodleBounds[2]) { doodleBounds[2] = x; newPointsOutsideOfCurrentBounds = true; } if (y < doodleBounds[1]) { doodleBounds[1] = y; newPointsOutsideOfCurrentBounds = true; } if (y > doodleBounds[3]) { doodleBounds[3] = y; newPointsOutsideOfCurrentBounds = true; } // doodleBounds[0] = Math.min(doodleBounds[0], x); // left // doodleBounds[2] = Math.max(doodleBounds[2], x); // right // // doodleBounds[1] = Math.min(doodleBounds[1], y); // top // doodleBounds[3] = Math.max(doodleBounds[3], y); // bottom // draw the bounding rect (DEBUG) /* ctx.beginPath(); ctx.rect(doodleBounds[0],doodleBounds[1], doodleBounds[2] - doodleBounds[0], doodleBounds[3] - doodleBounds[1]); ctx.lineWidth = .2; ctx.strokeStyle = "#333" ctx.stroke(); ctx.closePath(); //*/ // console.log(" new bounds: " + doodleBounds); return newPointsOutsideOfCurrentBounds; } // does what exactly? function adjustPreviewTransformation() { // console.log("f:adjustPreviewTransformation()"); // doodleTransform[0] = doodleBounds[0] - (doodleBounds[2] - doodleBounds[0]) / 2; // doodleTransform[1] = doodleBounds[1] - (doodleBounds[3] - doodleBounds[1]) / 2; // doodleTransform[0] = doodleBounds[0] - ((doodleBounds[2] - doodleBounds[0]) / 2); // doodleTransform[1] = doodleBounds[1] - ((doodleBounds[3] - doodleBounds[1]) / 2); doodleTransform[0] = doodleBounds[0]; doodleTransform[1] = doodleBounds[1]; var sclX, sclY, finalScl; if (_points.length < 2) { // console.log(_points); sclX = 1.0; sclY = 1.0; finalScl = Math.min(sclX, sclY); } else { sclX = canvasWidth / (doodleBounds[2] - doodleBounds[0]); sclY = canvasHeight / (doodleBounds[3] - doodleBounds[1]); // TODO this shouldn't be a matter if choosing the smallest but should probably involve maintaining aspect ratio?? finalScl = Math.min(sclX, sclY); } doodleTransform[2] = finalScl; doodleTransform[3] = finalScl; } /* * * * * * * * * * * * MOUSE/TOUCH EVENTHANDLERS * * * * * * * * * * */ function onCanvasMouseDown(e) { // console.log("onmousedown >> e.offsetX,e.offsetY = " + e.offsetX+","+e.offsetY); // console.log("onmousedown >> e.layerX,e.layerY= " + e.layerX+","+e.layerY); // console.log("onmousedown >> e: " + e); // console.log(e); // console.log("f:onCanvasMouseDown()"); dragging = true; prevCountingTime = new Date().getTime(); movementCounter = 0 // _points.push([e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop, true]); // adjustBounds(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop); // adjustPreviewTransformation(); // draw(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop, 0.5); var x, y; if (e.offsetX != undefined) { x = e.offsetX; y = e.offsetY; } else { x = e.layerX; y = e.layerY; } // console.log(" x: " + x + ", y: " + y); _points.push([x, y, true]); adjustBounds(x, y); adjustPreviewTransformation(); draw(x, y, 0.5); } var prevPoint = {x:-1, y:-1}; function onCanvasMouseMove(e) { // console.log("f:onCanvasMouseMove()"); if (!dragging) return; // console.log("onmousemove"); var x, y; if (e.offsetX != undefined) { x = e.offsetX; y = e.offsetY; } else { x = e.layerX; y = e.layerY; } if (prevPoint.x != -1 || prevPoint.y != -1) { var dist = Math.sqrt(Math.pow((prevPoint.x - x), 2) + Math.pow((prevPoint.y - y), 2)); if (dist > 5) { // replace by setting: doodle3d.simplify.minDistance _points.push([x, y, false]); adjustBounds(x, y) adjustPreviewTransformation(); draw(x, y); prevPoint.x = x; prevPoint.y = y; } } else { _points.push([x, y, false]); adjustBounds(x, y) adjustPreviewTransformation(); draw(x, y); prevPoint.x = x; prevPoint.y = y; } // DEBUG // $("#textdump").text(""); // $("#textdump").append("doodlebounds:" + doodleBounds + "\n"); // $("#textdump").append("doodletransform:" + doodleTransform + "\n"); if (new Date().getTime() - prevRedrawTime > redrawInterval) { // redrawing the whole preview the first X points ensures that the doodleBounds is set well prevRedrawTime = new Date().getTime(); if (_points.length < 50) { redrawPreview(); } else { updatePreview(x, y, true); /* if (_points.length - prevUpdateFullPreview > prevUpdateFullPreviewInterval) { console.log("f:onTouchMove >> passed prevUpdateFullPreviewInterval, updating full preview"); redrawPreview(); prevUpdateFullPreview = _points.length; } else { updatePreview(x, y, true); } //*/ // redrawPreview(); } } } prevUpdateFullPreview = 0; // 0 is not a timeframe but refers to the _points array prevUpdateFullPreviewInterval = 25; // refers to number of points, not a timeframe function onCanvasMouseUp(e) { // console.log("f:onCanvasMouseUp()"); // console.log("onmouseup"); dragging = false; console.log("doodleBounds: " + doodleBounds); console.log("doodleTransform: " + doodleTransform); // ctx.stroke(); console.log("_points.length :" + _points.length); // console.log(_points); // DEBUG // $("#textdump").text(""); // $("#textdump").append("doodlebounds:" + doodleBounds + "\n"); // $("#textdump").append("doodletransform:" + doodleTransform + "\n"); // redrawPreview(); renderToImageDataPreview(); } function onCanvasTouchDown(e) { e.preventDefault(); console.log("f:onCanvasTouchDown >> e: " , e); // var x = e.touches[0].pageX - e.touches[0].target.offsetLeft; // var y = e.touches[0].pageY - e.touches[0].target.offsetTop; var x = e.touches[0].pageX - drawCanvasTopLeftCoords[0]; var y = e.touches[0].pageY - drawCanvasTopLeftCoords[1]; // var x = e.touches[0].pageX; // var y = e.touches[0].pageY; // var x = e.touches[0].layerX; // var y = e.touches[0].layerY; _points.push([x, y, true]); adjustBounds(x, y); adjustPreviewTransformation(); draw(x, y, .5); movementCounter = 0; prevRedrawTime = new Date().getTime(); } function onCanvasTouchMove(e) { e.preventDefault(); // var x = e.touches[0].pageX - e.touches[0].target.offsetLeft; // var y = e.touches[0].pageY - e.touches[0].target.offsetTop; var x = e.touches[0].pageX - drawCanvasTopLeftCoords[0]; var y = e.touches[0].pageY - drawCanvasTopLeftCoords[1]; // var x = e.touches[0].layerX; // var y = e.touches[0].layerY; // var x = e.touches[0].layerX; // var y = e.touches[0].layerY; console.log("f:onCanvasTouchMove >> x,y = "+x+","+y+" , e: " , e); if (prevPoint.x != -1 || prevPoint.y != -1) { var dist = Math.sqrt(Math.pow((prevPoint.x - x), 2) + Math.pow((prevPoint.y - y), 2)); if (dist > 5) { _points.push([x, y, false]); adjustBounds(x, y) adjustPreviewTransformation(); draw(x, y); prevPoint.x = x; prevPoint.y = y; } } else { _points.push([x, y, false]); adjustBounds(x, y) adjustPreviewTransformation(); draw(x, y); prevPoint.x = x; prevPoint.y = y; } // update counter -> this was for getting a handle on how often the Canvas fires a move-event /* movementCounter++; if (new Date().getTime() - prevCountingTime > 1000) { // console.log("number of moves in 1sec: " + movementCounter) prevCountingTime= new Date().getTime(); $("#numtimes").text(movementCounter + " times"); movementCounter = 0; } //*/ if (new Date().getTime() - prevRedrawTime > redrawInterval) { // redrawing the whole preview the first X points ensures that the doodleBounds is set well if (_points.length < 50) { redrawPreview(); } else { updatePreview(x, y, true); /* if (_points.length - prevUpdateFullPreview > prevUpdateFullPreviewInterval) { console.log("f:onTouchMove >> passed prevUpdateFullPreviewInterval, updating full preview"); redrawPreview(); prevUpdateFullPreview = _points.length; } else { updatePreview(x, y, true); } //*/ } prevRedrawTime = new Date().getTime(); } } function onCanvasTouchEnd(e) { console.log("f:onCanvasTouchEnd()"); console.log("doodleBounds: " + doodleBounds); console.log("doodleTransform: " + doodleTransform); // ctx.stroke(); console.log("_points.length :" + _points.length); // redrawPreview(); renderToImageDataPreview(); } function prevent(e) { e.preventDefault(); } //* var $preview; var preview; var previewCtx; var preview_tmp; var previewCtx_tmp; var previewDefaults = { rotation: Math.PI/90, numLayers: 10 } var svgPathRegExp = /[LM]\d* \d*/ig; var svgPathParamsRegExp = /([LM])(\d*) (\d*)/; var prevRedrawTime = new Date().getTime(); var redrawInterval = 1000 / 30; // ms function initPreviewRendering() { console.log("f:initPreviewRendering()"); $preview = $("#preview"); preview = $preview[0]; previewCtx = preview.getContext('2d'); // DEBUG --> mbt preview_tmp (voor de toImageData truc) var _ratio = preview.width / canvas.width; preview_tmp = document.getElementById('preview_tmp'); preview_tmp.width = preview.width; preview_tmp.height = canvas.height * _ratio; $("#preview_tmp").css("top", -preview_tmp.height); previewCtx_tmp = preview_tmp.getContext('2d'); calcPreviewCanvasProperties(); redrawPreview(); } function calcPreviewCanvasProperties() { console.log("f:calcPreviewCanvasProperties()"); globalScale = preview.width / canvasWidth; layerCX = (canvasWidth / 2) * globalScale; // defined in canvasDrawing_v01.js layerCY = (canvasHeight / 2) * globalScale; // defined in canvasDrawing_v01.js // layerOffsetY = preview.height - 1.75 * layerCY; layerOffsetY = preview.height * (1 - previewVerticalPadding.bottom); yStep = (preview.height - (preview.height * (previewVerticalPadding.top + previewVerticalPadding.bottom))) / maxNumLayers; } // TODO (perhaps) : make the twist limit dynamic, depending on what's printable (w.r.t. overlapping) var previewRotationLimit = Math.PI / 30; // rough estimate var numLayers = previewDefaults.numLayers; // current number of preview layers var maxNumLayers= 100; // maximum number of preview layers var minNumLayers= 2; // minimum number of preview layers var globalScale = 0.3; // global scale of preview (width preview / width canvas) var globalAlpha = 0.20; // global alpha of preview var scaleY = 0.4; // additional vertical scale per path for 3d effect var viewerScale = 0.65; // additional scale to fit into preview nicely (otherwise is fills out totally) var previewVerticalPadding = { "top" : .15, "bottom" : 0.12 }; // % var strokeWidth = 2; //4; //var rStep = Math.PI/40; //Math.PI/40; // var rStep = previewDefaults.rotation; // Math.PI/180; //Math.PI/40; // var yStep;// = preview.height / 150; // 3; //6; //var svgWidth = 500; // 650 //parseInt($(svg).css("width")); //var svgHeight = 450; //450; //parseInt($(svg).css("height")); var layerCX, layerCY; //var layerCX = (canvasWidth / 2) * globalScale; // defined in canvasDrawing_v01.js //var layerCY = (canvasHeight / 2) * globalScale; // defined in canvasDrawing_v01.js var layerOffsetY; //= preview.height - 1.75 * layerCY; // 330; // previewHeight - 120 var prevX = 0; var prevY = 0; var highlight = true; //highlight bottom, middle and top layers var linesRaw = ""; var debug_redrawSimplification = 6; function redrawPreview(redrawLess) { if (redrawLess == undefined) redrawLess = false; if (_points.length < 2) return; if (!redrawLess) { //debug_redrawSimplification = Math.round(_points.length / 65); //* if (_points.length < 100) { debug_redrawSimplification = 6; } else if (_points.length < 250) { debug_redrawSimplification = 7; } else if (_points.length < 400) { debug_redrawSimplification = 8; } else if (_points.length < 550) { debug_redrawSimplification = 9; } else if (_points.length < 700) { debug_redrawSimplification = 10; } else { debug_redrawSimplification = 11; } //*/ // console.log("debug_redrawSimplification: " + debug_redrawSimplification); } var y = 0; var r = 0; //preview.width = preview.width; previewCtx.clearRect(0, 0, preview.width, preview.height); previewCtx.lineWidth = strokeWidth; previewCtx.strokeStyle = '#f00'; //"rgba(255,255,0,0)"; for(var i = 0; i < numLayers; i++) { var verticalScaleFactor = scaleFunction(i / maxNumLayers); if(i == 0 || i == Math.floor(numLayers/2) || i == numLayers-1) { previewCtx.globalAlpha = 1; } else { previewCtx.globalAlpha = globalAlpha; } if (redrawLess && i%debug_redrawSimplification != 0 && !(i == 0 || i == Math.floor(numLayers/2) || i == numLayers-1) ) { y -= yStep; r += rStep; continue; } previewCtx.save(); // previewCtx.translate(layerCX, layerOffsetY + layerCY + y); previewCtx.translate(layerCX, layerOffsetY + y); // previewCtx.setTransform(1, 0, 0, scaleY, layerCX, layerOffsetY+layerCY+y); previewCtx.scale(viewerScale * verticalScaleFactor, scaleY * viewerScale * verticalScaleFactor); previewCtx.rotate(r); previewCtx.translate((-doodleTransform[0]) * (globalScale * doodleTransform[2]), (-doodleTransform[1]) * (globalScale * doodleTransform[3])); var adjustedDoodlePoint = centeredAndScaledDoodlePoint(_points[0]); previewCtx.beginPath(); previewCtx.moveTo(adjustedDoodlePoint.x, adjustedDoodlePoint.y); for(var j = 1; j < _points.length; j++) { adjustedDoodlePoint = centeredAndScaledDoodlePoint(_points[j]) if (redrawLess && j%debug_redrawSimplification != 0 ) continue; previewCtx.lineTo(adjustedDoodlePoint.x, adjustedDoodlePoint.y); } previewCtx.stroke(); y -= yStep; r += rStep; previewCtx.restore(); } previewCtx.globalAlpha = globalAlpha; } function renderToImageDataPreview() { console.log("f:renderToImageDataPreview()"); if (_points.length < 2) return; //* // the first step previewCtx_tmp.clearRect(0, 0, preview.width, preview.height); previewCtx_tmp.lineWidth = strokeWidth; previewCtx_tmp.strokeStyle = '#f00'; //"rgba(255,255,0,0)"; previewCtx_tmp.save(); previewCtx_tmp.translate(layerCX, layerCY); previewCtx_tmp.scale(viewerScale, viewerScale); previewCtx_tmp.translate((-doodleTransform[0]) * (globalScale * doodleTransform[2]), (-doodleTransform[1]) * (globalScale * doodleTransform[3])); var adjustedDoodlePt = centeredAndScaledDoodlePoint(_points[0]); previewCtx_tmp.beginPath(); previewCtx_tmp.moveTo(adjustedDoodlePt.x, adjustedDoodlePt.y); for(var j = 1; j < _points.length; j++) { adjustedDoodlePt = centeredAndScaledDoodlePoint(_points[j]) previewCtx_tmp.lineTo(adjustedDoodlePt.x, adjustedDoodlePt.y); } previewCtx_tmp.stroke(); previewCtx_tmp.closePath(); previewCtx_tmp.restore(); //*/ // var saved_rect = previewCtx_tmp.getImageData(0, 0, layerCX*2, layerCY*2); var saved_rect_todataurl = preview_tmp.toDataURL(); doodleImageCapture = new Image(); doodleImageCapture.onload = function() { previewCtx.clearRect(0, 0, preview.width, preview.height); previewCtx.lineWidth = strokeWidth; previewCtx.strokeStyle = '#f00'; //"rgba(255,255,0,0)"; var y = 0; var r = 0; for(var i=0;i