/* Copyright (C) 2016 - 2017 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /** @namespace GnuBoat JavaScript namespace */ var GnuBoat = GnuBoat || {}; /** * @brief Sets the webservice base url, used by any other functions */ GnuBoat.setServer = function(baseUrl) { if(baseUrl.slice(-1) != "/") baseUrl += "/"; GnuBoat.private.serverBaseUrl = baseUrl; var link = document.createElement("a"); link.setAttribute("href", baseUrl); $("#opencpnHint").empty(); $("

To connect OpenCPN with the GPSD running on this webservice, use "+ link.hostname +":2947 and "+ link.hostname +":2597 for the messages recieved on NMEA2000 bus.

").appendTo("#opencpnHint"); } /** * @brief Used to display user messages */ GnuBoat.displayMessage = function(text) { $("#message").empty(); $(text).appendTo("#message"); location.hash = "#messages"; } /** * @brief Fetches the data shown in the display area from the webservice */ GnuBoat.displayDataGet = function() { if(GnuBoat.private.serverBaseUrl == null){ GnuBoat.displayMessage("No server set/found"); return; } var gnuboatApi = GnuBoat.private.serverBaseUrl; $.getJSON(gnuboatApi, GnuBoat.private.displayDataSet); }; /** * @brief Gets the metadata of all maps, provided by the tileserver */ GnuBoat.getMapInfos = function() { if(GnuBoat.private.serverBaseUrl == null){ GnuBoat.displayMessage("No server set/found"); return; } $.getJSON(GnuBoat.private.serverBaseUrl +"tileserver.php?/index.json", GnuBoat.private.mapInfos); }; /** * @brief Fetches the list of available logfiles and adds them to the log file download form */ GnuBoat.logfilesLoad = function() { if(GnuBoat.private.serverBaseUrl == null){ GnuBoat.displayMessage("No server set/found"); return; } $("#logfilesForm").empty(); $.getJSON(GnuBoat.private.serverBaseUrl +"?request=logfiles", function(data){ if(!Array.isArray(data) || data.length < 1){ $("

No Logfiles found!

").appendTo("#logfilesForm"); console.log(data); return; } if(("error" in data) && data["error"] == 1){ alert("Failed to upload map: "+ data["errormessage"]); $("#mapTileUploadProgress").hide(); $("#mapFileInput").show(); return; } $("").appendTo("#logfilesForm"); $("").appendTo("#logfilesForm"); data.forEach(function(value, index){ $("").appendTo("#logfilesSelect"); }); }); }; /** * @brief Sends a shutdown request to the webservice */ GnuBoat.shutdown = function() { if(GnuBoat.private.serverBaseUrl == null){ GnuBoat.displayMessage("No server set/found"); return; } $.getJSON(GnuBoat.private.serverBaseUrl +"?request=shutdown", function(data){ var shutdownTime = data["shutdownstart"]; var shutdownDate = Date.parse(shutdownTime); var currentDate = new Date(); var shutdownHint = 'Shutting down in '+ Math.floor((shutdownDate - currentDate)/1000) +"s at "+ shutdownTime.toLocaleString() +""; if(shutdownTime == -1){ shutdownHint = 'Failed to initiate shutdown: '+ data["errormessage"] +""; } GnuBoat.displayMessage(shutdownHint); }); }; /** * @brief Uploads a map and refreshes the maps metadata on success */ GnuBoat.uploadMap = function(form) { if(GnuBoat.private.serverBaseUrl == null){ displayMessage("No server set/found"); return; } $("#mapFileInput").hide(); $("#mapTileUploadProgress").show(); $.ajax({ type: 'POST', url: GnuBoat.private.serverBaseUrl +'?request=map', data: new FormData($("#mapTileUpload")[0]), contentType: false, processData: false, success: function(data){ if(("error" in data) && data["error"] == 1){ alert("Failed to upload map: "+ data["errormessage"]); $("#mapTileUploadProgress").hide(); $("#mapFileInput").show(); return; } alert("Map upload successfully"); $("#mapTileUploadProgress").hide(); $("#mapFileInput").show(); GnuBoat.getMapInfos(); }, error: function(jqXHR, exception, errorThrown){ alert("Failed to upload map (XHR): "+ exception); $("#mapTileUploadProgress").hide(); $("#mapFileInput").show(); } }).progress(function(e){ $("#mapTileUploadProgress").attr({value: e.oloaded, max: e.total}); }); }; /** * @brief Setups up GnuBoat to be able to start() after configured a server with setServer(). */ GnuBoat.initialize = function() { $("#mapTileUploadProgress").hide(); $("#logfilesReload").click(GnuBoat.logfilesLoad); $("#shutdownButton").click(GnuBoat.shutdown); $("#mapTileUpload").validate({ rules: { mapFile: { required: true }, mapName: { required: true } }, submitHandler: function(form){ GnuBoat.uploadMap(form); } }); $("#logfilesForm").validate({ rules: { logfilesSelect: { required: true }, } }); $("#rendering").empty(); var width = $("#rendering").width(); var height = $("#rendering").height(); var fieldOfView = 75; GnuBoat.private.renderScene = new THREE.Scene(); GnuBoat.private.renderScene.background = new THREE.Color(0xEEEEEE); GnuBoat.private.renderCamera = new THREE.PerspectiveCamera(75, width/height, 0.1, 1000000); GnuBoat.private.renderCamera.up = new THREE.Vector3(0, 0, 1); GnuBoat.private.renderCamera.position.set(-0.01, -0.01, 15000); GnuBoat.private.renderCamera.lookAt(GnuBoat.private.renderScene.position); GnuBoat.private.renderRenderer = new THREE.WebGLRenderer(); GnuBoat.private.renderRenderer.setSize(width, height); GnuBoat.private.renderRenderer.setPixelRatio( window.devicePixelRatio ); document.getElementById("rendering").appendChild(GnuBoat.private.renderRenderer.domElement); GnuBoat.private.renderControls = new THREE.OrbitControls( GnuBoat.private.renderCamera, GnuBoat.private.renderRenderer.domElement ); GnuBoat.private.renderControls.zoomSpeed = 2; var deep = new THREE.Color(0x347C7C); var shallow = new THREE.Color(0xBCD9D9); var size = 5; GnuBoat.private.renderDepthSteps = 50; var deltaR = (Math.max(deep.r, shallow.r) - Math.min(deep.r, shallow.r))/GnuBoat.private.renderDepthSteps; var deltaG = (Math.max(deep.g, shallow.g) - Math.min(deep.g, shallow.g))/GnuBoat.private.renderDepthSteps; var deltaB = (Math.max(deep.b, shallow.b) - Math.min(deep.b, shallow.b))/GnuBoat.private.renderDepthSteps; for(var i = 0; i < GnuBoat.private.renderDepthSteps; i++){ var stepColor = new THREE.Color(Math.max(deep.r, shallow.r) - i * deltaR, Math.max(deep.g, shallow.g) - i * deltaG, Math.max(deep.b, shallow.b) - i * deltaB); GnuBoat.private.renderDepthMaterials.push(stepColor); } GnuBoat.private.renderDepthMaterials.push(shallow); } /** * @brief Starts querying the webservice * * Call initialize() and setServer() before start() */ GnuBoat.start = function() { if(GnuBoat.private.serverBaseUrl == null){ GnuBoat.displayMessage("No server set/found"); return; } GnuBoat.getMapInfos(); GnuBoat.displayDataGet(); if(GnuBoat.private.timerDisplay == null) GnuBoat.private.timerDisplay = setInterval(GnuBoat.displayDataGet, 10000); GnuBoat.logfilesLoad(); GnuBoat.private.animate(); } /** * @brief Stops querying the webservice */ GnuBoat.stop = function() { if(GnuBoat.private.timerDisplay != null){ clearInterval(GnuBoat.private.timerDisplay); GnuBoat.private.timerDisplay = null; } } /** * @brief Private methods and properties of GnuBoat */ GnuBoat.private = { map: null, mapLayerCurrent: null, mapPolylines: [], mapControl: null, mapsMetadata: null, mapBounds: null, dataMappings: { speedthroughwater: {display: true, map: true, mapActive: false, titleLong: "Speed Through Water", titleShort: "STW", unit: "kts"}, speedoverground: {display: true, map: true, mapActive: false, titleLong: "Speed Over Ground", titleShort: "SOG", unit: "kts"}, waterdepth: {display: true, map: true, mapActive: true, titleLong: "Waterdepth", titleShort: "Depth", unit: "m"}, watertemperature: {display: true, map: true, mapActive: false, titleLong: "Watertemperature", titleShort: "Water", unit: "°C"}, gpsfix: {display: true, map: false, mapActive: false, titleLong: "GPS Fix", titleShort: "Fix", unit: ""}, }, serverBaseUrl: null, timerDisplay: null, renderScene: null, renderCamera: null, renderRenderer: null, renderMapBounds: null, renderGrid: null, renderControls: null, renderCloud: null, renderDepthMaterials: [], renderDepthSteps: null, openLink: function(target) { window.location=target; }, displayDataSet: function(data) { var keysDisplay = []; for(var key in GnuBoat.private.dataMappings){ if(GnuBoat.private.dataMappings[key]["display"] === true) keysDisplay.push(key); } if(!Array.isArray(data) && !(data instanceof Object)){ console.log("No data array returned!"); console.log(data); return; } if(!("lastvalid" in data)){ console.log("No last valid values given!"); } else{ var lastValid = data["lastvalid"]; for(var i = 0; i < keysDisplay.length; i++){ var key = keysDisplay[i]; var value = lastValid[key]; if($.isNumeric(value)){ var text = value.toFixed(1); if(key == "watertemperature"){ text = value.toFixed(0); } $("#display #"+ key +" #value").text(text); } else if(key == "gpsfix"){ $("#display #"+ key +" #value").text(value); } } } if(!("track" in data)){ console.log("No track given!"); } else{ if(GnuBoat.private.map == null){ console.log("No map in use"); } else{ var track = data["track"]; var maximas = []; var minimas = []; var points = []; var densityPoints = []; var keysMap = []; for(var key in GnuBoat.private.dataMappings){ if(GnuBoat.private.dataMappings[key]["map"] === true) keysMap.push(key); } for(var i = 0; i < keysMap.length; i++){ if(keysMap[i] == "gpsfix") continue; points[keysMap[i]] = []; } // getting maximas, minimums for normalization and the tracks themselves for(var time in track){ for(var i = 0; i < keysMap.length; i++){ var key = keysMap[i]; if(key == "gpsfix") continue; if(!(key in maximas)) maximas[key] = track[time][key] else if(maximas[key] < track[time][key]) maximas[key] = track[time][key]; if(!(key in minimas)) minimas[key] = track[time][key] else if(minimas[key] > track[time][key]) minimas[key] = track[time][key]; points[key].push(new L.latLng(track[time]["latitude"], track[time]["longitude"], track[time][key])); densityPoints.push({latitude: track[time]["latitude"], longitude: track[time]["longitude"], depth: track[time]["waterdepth"]}); } } for(var i = 0; i < keysMap.length; i++){ var key = keysMap[i]; if(key == "gpsfix") continue; if(points[key].length > 0){ if(key in GnuBoat.private.mapPolylines) GnuBoat.private.mapPolylines[key].setLatLngs(points[key]); else{ GnuBoat.private.mapPolylines[key] = L.hotline(points[key], {weight: 3, outlineWidth: 0, min: minimas[key], max: maximas[key]}); if(GnuBoat.private.mapControl){ var name = GnuBoat.private.dataMappings[key]["titleLong"] +" in "+ GnuBoat.private.dataMappings[key]["unit"] +" ("+ GnuBoat.private.dataMappings[key]["titleShort"] +")"; GnuBoat.private.mapControl.addOverlay(GnuBoat.private.mapPolylines[key], name); } if(GnuBoat.private.dataMappings[key]["mapActive"] === true) GnuBoat.private.mapPolylines[key].addTo(GnuBoat.private.map); } } } GnuBoat.private.drawDensityEstimation(densityPoints, maximas["waterdepth"], minimas["waterdepth"]); } } }, mapSetup: function () { var mapMetadataIndex = $("#mapSelect").val(); if(GnuBoat.private.mapsMetadata == null){ console.log("No mapsMetadata set"); return; } if(mapMetadataIndex < 0 || mapMetadataIndex >= GnuBoat.private.mapsMetadata.length){ console.log("Map metadata is outside of range :"+ mapMetadataIndex.toString()); console.log(mapsMetadata); return; } var mapMetadata = GnuBoat.private.mapsMetadata[mapMetadataIndex]; var latitudeTop = mapMetadata["bounds"][3]; var latitudeBottom = mapMetadata["bounds"][1]; var longitudeLeft = mapMetadata["bounds"][0]; var longitudeRight = mapMetadata["bounds"][2]; var mapZoomMin = mapMetadata["minzoom"]; var mapZoomMax = mapMetadata["maxzoom"]; var latitudeCenter = (latitudeTop - latitudeBottom)/2 + latitudeBottom; var longitudeCenter = (longitudeLeft - longitudeRight)/2 + longitudeRight; var mapZoomStart = (mapZoomMax - mapZoomMin)/2 + mapZoomMin; GnuBoat.private.mapBounds = new L.LatLngBounds( new L.LatLng(latitudeBottom, longitudeLeft), new L.LatLng(latitudeTop, longitudeRight)); if(GnuBoat.private.map == null){ // only initialize the map (viewport) once GnuBoat.private.map = L.map('mapViewport'); } GnuBoat.private.map.setView([latitudeCenter, longitudeCenter], mapZoomStart); if(GnuBoat.private.mapLayerCurrent != null){ GnuBoat.private.map.removeLayer(GnuBoat.private.mapLayerCurrent); if(GnuBoat.private.mapControl) GnuBoat.private.mapControl.removeLayer(GnuBoat.private.mapLayerCurrent); GnuBoat.private.mapLayerCurrent = null; } GnuBoat.private.mapLayerCurrent = L.tileLayer(mapMetadata["tiles"][0], { minZoom: mapZoomMin, maxZoom: mapZoomMax, bounds: GnuBoat.private.mapBounds, attribution: mapMetadata["name"], opacity: 0.85 }).addTo(GnuBoat.private.map); if(GnuBoat.private.mapControl != null) GnuBoat.private.mapControl.addBaseLayer(GnuBoat.private.mapLayerCurrent, "Map"); else{ GnuBoat.private.mapControl = L.control.layers({"Map": GnuBoat.private.mapLayerCurrent}, GnuBoat.private.mapOverlaysToList(), {hideSingleBase: true, sortLayers: true, }).addTo(GnuBoat.private.map); } // configure render scene for new map GnuBoat.private.renderSetupMap(); }, mapInfos: function(data) { GnuBoat.private.mapsMetadata = data; $("#mapSelect").empty(); var selected = "selected"; data.forEach(function(value, index){ $("").appendTo("#mapSelect"); selected = ""; }); GnuBoat.private.mapSetup(); $("#mapSelect").change(function(){ GnuBoat.private.mapSetup(); }); }, mapOverlaysToList: function() { var overlays = {}; for(var key in GnuBoat.private.mapPolylines){ overlays[key] = GnuBoat.private.mapPolylines[key]; } return overlays; }, renderSetupMap: function() { if(GnuBoat.private.mapBounds == null) return; // add map bounds if(GnuBoat.private.renderMapBounds != null) GnuBoat.private.renderScene.remove(GnuBoat.private.renderMapBounds); var m1 = GnuBoat.private.mercator(GnuBoat.private.mapBounds.getSouth(), GnuBoat.private.mapBounds.getWest()); var m2 = GnuBoat.private.mercator(GnuBoat.private.mapBounds.getSouth(), GnuBoat.private.mapBounds.getEast()); var m3 = GnuBoat.private.mercator(GnuBoat.private.mapBounds.getNorth(), GnuBoat.private.mapBounds.getEast()); var m4 = GnuBoat.private.mercator(GnuBoat.private.mapBounds.getNorth(), GnuBoat.private.mapBounds.getWest()); var geometryMapBounds = new THREE.Geometry(); var materialMapBounds = new THREE.LineBasicMaterial({color: 0x66BD66, linewidth: 1}); // z is greator 0, to draw the map boundings over the grid var vertex = new THREE.Vector3(0, 0, 2); geometryMapBounds.vertices.push(vertex); vertex = new THREE.Vector3(m2.x - m1.x, m2.y - m1.y, 2); geometryMapBounds.vertices.push(vertex); vertex = new THREE.Vector3(m3.x - m1.x, m3.y - m1.y, 2); geometryMapBounds.vertices.push(vertex); vertex = new THREE.Vector3(m4.x - m1.x, m4.y - m1.y, 2); geometryMapBounds.vertices.push(vertex); GnuBoat.private.renderMapBounds = new THREE.LineLoop(geometryMapBounds, materialMapBounds); GnuBoat.private.renderScene.add(GnuBoat.private.renderMapBounds); // add 500m grid if(GnuBoat.private.renderGrid != null) GnuBoat.private.renderScene.remove(GnuBoat.private.renderGrid); geometryMapBounds.computeBoundingBox(); var maxLength = Math.max(geometryMapBounds.boundingBox.getSize().x, geometryMapBounds.boundingBox.getSize().y); GnuBoat.private.renderGrid = new THREE.GridHelper(maxLength, Math.round(maxLength / 500.0), 0xCCCCCC, 0xCCCCCC); GnuBoat.private.renderGrid.geometry.rotateX( Math.PI / 2 ); GnuBoat.private.renderGrid.translateX(maxLength / 2.0); GnuBoat.private.renderGrid.translateY(maxLength / 2.0); GnuBoat.private.renderScene.add(GnuBoat.private.renderGrid); var distance = 150; var fieldOfView = 2 * Math.atan(maxLength / (2.0 * distance) ) * 180.0 / Math.PI; GnuBoat.private.renderCamera.position.set(-10, -5, 100); GnuBoat.private.renderCamera.fov = fieldOfView; GnuBoat.private.renderCamera.lookAt(GnuBoat.private.renderScene.position); GnuBoat.private.renderCamera.zoom = 5; GnuBoat.private.renderCamera.updateProjectionMatrix(); }, drawDensityEstimation: function(densityPoints, maximum, minimum) { var material = new THREE.PointsMaterial({vertexColors: THREE.VertexColors, size: 5}); var geometry = new THREE.Geometry(); var mercatorSouthWest = {x: 0, y: 0}; if(GnuBoat.private.mapBounds != null) mercatorSouthWest = GnuBoat.private.mercator(GnuBoat.private.mapBounds.getSouth(), GnuBoat.private.mapBounds.getWest()); for(var i = 0; i < densityPoints.length; i++){ var mercator = GnuBoat.private.mercator(densityPoints[i].latitude, densityPoints[i].longitude); var vertex = new THREE.Vector3(mercator.x - mercatorSouthWest.x, mercator.y - mercatorSouthWest.y, (densityPoints[i].depth * -1) + maximum); var color = new THREE.Color(0x000000); if(GnuBoat.private.renderDepthSteps != null){ var step = Math.floor((densityPoints[i].depth - minimum)/((maximum-minimum)/GnuBoat.private.renderDepthSteps)); if(step >= 0 && step < GnuBoat.private.renderDepthMaterials.length) color = GnuBoat.private.renderDepthMaterials[step]; } geometry.vertices.push(vertex); geometry.colors.push(color); } // point cloud if(GnuBoat.private.renderCloud != null) GnuBoat.private.renderScene.remove(GnuBoat.private.renderCloud); GnuBoat.private.renderCloud = new THREE.Points(geometry, material); GnuBoat.private.renderScene.add(GnuBoat.private.renderCloud); }, animate: function() { requestAnimationFrame(GnuBoat.private.animate); if(GnuBoat.private.renderCloud != null){ var scaleZ = $("#renderScaleZ").val(); if(GnuBoat.private.renderCloud.scale.z != scaleZ) GnuBoat.private.renderCloud.scale.set(1, 1, scaleZ); } GnuBoat.private.renderControls.update(); GnuBoat.private.renderRenderer.render(GnuBoat.private.renderScene, GnuBoat.private.renderCamera); }, mercator: function(latitude, longitude) { var result = {}; var earthRadius = 6378137.0; result["x"] = longitude / 180.0 * Math.PI * earthRadius; result["y"] = Math.log(Math.tan(latitude / 180.0 * Math.PI / 2.0 + Math.PI / 4.0)) * earthRadius; return result; }, };