Interactive interface for browsing global, full-resolution satellite imagery
Add vectorStyle build tasks and vector style rendering
ZachTRice08c7eff912cf
diff --git a/tasks/buildOptions.sh b/tasks/buildOptions.shindex 672aa4838..3bcc92591 100755--- a/tasks/buildOptions.sh+++ b/tasks/buildOptions.sh@@ -56,6 +56,7 @@ fimkdir -p "$DEST_DIR/config"mkdir -p "$BUILD_DIR/colormaps"+mkdir -p "$BUILD_DIR/vectorstyles"if [ -e "$BUILD_DIR/features.json" ] ; thencp "$BUILD_DIR/features.json" "$BUILD_DIR/config/wv.json/_features.json"@@ -67,6 +68,18 @@ if [ -e "$BUILD_DIR/config.json" ] ; then"$BUILD_DIR/config/wv.json/_wmts" "$BUILD_DIR/colormaps"fi+# Run processVectorStyles.py and move colormaps where we want them+if [ -e "$BUILD_DIR/vectorstyles" ] ; then+ mkdir -p "$BUILD_DIR"/config/vectorstyles+ if [ -d "$BUILD_DIR"/gc/vectorstyles ] ; then+ cp -r "$BUILD_DIR"/gc/vectorstyles "$BUILD_DIR"/vectorstyles/gc+ fi+ "$TASKS_DIR/processVectorStyles.py" "$OPT_DIR/$OPT_SUBDIR/config.json" \+ "$BUILD_DIR/vectorstyles" \+ "$BUILD_DIR/config/vectorstyles"+fi++# Run processColormap.py and move colormaps where we want themif [ -e "$BUILD_DIR/colormaps" ] ; thenmkdir -p "$BUILD_DIR"/config/palettesdiff --git a/tasks/extractConfigFromWMTS.py b/tasks/extractConfigFromWMTS.pyindex fa8c70d14..f3ccc833f 100755--- a/tasks/extractConfigFromWMTS.py+++ b/tasks/extractConfigFromWMTS.py@@ -104,6 +104,13 @@ def process_layer(gc_layer, wv_layers, colormaps):wv_layer["palette"] = {"id": colormap_id}+ elif schema_version == "http://earthdata.nasa.gov/gibs/metadata-type/mapbox-gl-style/1.0":+ colormap_link = item["@xlink:href"]+ colormap_file = os.path.basename(colormap_link)+ colormap_id = os.path.splitext(colormap_file)[0]+ wv_layer["vectorStyle"] = {+ "id": colormap_id+ }def process_entry(entry, colormaps):layer_count = 0diff --git a/tasks/getCapabilities.py b/tasks/getCapabilities.pyindex f616b5637..ecb1f5111 100755--- a/tasks/getCapabilities.py+++ b/tasks/getCapabilities.py@@ -30,7 +30,9 @@ if len(args) != 2:config_file = args[0]output_dir = args[1]colormaps = {}+vectorstyles = {}colormaps_dir = os.path.join(output_dir, "colormaps")+vectorstyles_dir = os.path.join(output_dir, "vectorstyles")remote_count = 0error_count = 0warning_count = 0@@ -65,6 +67,12 @@ def process_layer(layer):colormap_id = os.path.splitext(colormap_file)[0]colormaps[colormap_id] = colormap_link+ elif schema_version == "http://earthdata.nasa.gov/gibs/metadata-type/mapbox-gl-style/1.0":+ vector_style_link = item["@xlink:href"]+ vector_style_file = os.path.basename(vector_style_link)+ vector_style_id = os.path.splitext(vector_style_file)[0]+ vectorstyles[vector_style_id] = vector_style_link+def process_remote(entry):url = entry["from"]print "%s: %s" % (prog, url)@@ -77,7 +85,7 @@ def process_remote(entry):fp.write(contents)gc = xmltodict.parse(contents)- # Find all colormaps in GetCapabilities responses and store them in memory+ # Find all colormaps and vectorstyles in GetCapabilities responses and store them in memoryif gc["Capabilities"]["Contents"] is None:print('error: %s: no layers' % url)return@@ -112,6 +120,27 @@ def process_colormaps():global warning_countwarning_count += 1+# Fetch every colormap from the API and write response to file system+def process_vectorstyles():+ print "%s: Fetching %d vectorstyles" % (prog, len(vectorstyles))+ sys.stdout.flush()+ if not os.path.exists(vectorstyles_dir):+ os.makedirs(vectorstyles_dir)+ for link in vectorstyles.values():+ try:+ response = http.request("GET", link)+ contents = response.data+ if link.endswith('.json'):+ output_file = os.path.join(vectorstyles_dir, os.path.basename(link))+ with open(output_file, "w") as fp:+ fp.write(contents)+ except Exception as e:+ sys.stderr.write("%s: WARN: Unable to fetch %s: %s" %+ (prog, link, str(e)))+ global warning_count+ warning_count += 1+ print "%s: Fetching %d vectorstyles" % (prog, len(vectorstyles))+tolerant = config.get("tolerant", False)if "wv-options-fetch" in config:for entry in config["wv-options-fetch"]:@@ -127,6 +156,8 @@ if "wv-options-fetch" in config:sys.stderr.write("%s: ERROR: %s\n" % (prog, str(e)))if colormaps:process_colormaps()+ if vectorstyles:+ process_vectorstyles()print "%s: %d error(s), %d remote(s)" % (prog, error_count, remote_count)diff --git a/tasks/processVectorStyles.py b/tasks/processVectorStyles.pynew file mode 100644index 000000000..4907ee6c5--- /dev/null+++ b/tasks/processVectorStyles.py@@ -0,0 +1,59 @@+#!/usr/bin/env python++from optparse import OptionParser+import os+import sys+import json+import shutil++prog = os.path.basename(__file__)+base_dir = os.path.join(os.path.dirname(__file__), "..")+version = "3.0.0"+help_description = """\+Converts colormaps to JSON files+"""++parser = OptionParser(usage="Usage: %s <config_file> <vectorstyles_input_dir> <output_dir>" % prog,+ version="%s version %s" % (prog, version),+ epilog=help_description)++(options, args) = parser.parse_args()+if len(args) != 3:+ parser.error("Invalid number of arguments")++config_file = args[0]+vectorstyles_input_dir = args[1]+output_dir = args[2]++with open(config_file) as fp:+ config = json.load(fp)+skips = config.get("skipPalettes", [])++def copy_file(file):+ input_file = os.path.join(root, file)+ id = os.path.splitext(os.path.basename(input_file))[0]+ if id in skips:+ sys.stderr.write("%s: WARN: [%s] %s\n" % (prog, input_file,+ "Skipping"))+ return++ if input_file.endswith('.json'):+ shutil.copy(input_file, output_dir)++# Main+file_count = 0+error_count = 0++for root, dirs, files in os.walk(vectorstyles_input_dir):+ for file in files:+ try:+ file_count += 1+ copy_file(file)+ except Exception as e:+ sys.stderr.write("%s: ERROR: [%s] %s\n" % (prog, file, str(e)))+ error_count += 1++print "%s: %d error(s), %d file(s)" % (prog, error_count, file_count)++if error_count > 0:+ sys.exit(1)diff --git a/tasks/validateOptions.py b/tasks/validateOptions.pyindex 3dc433203..e0388462d 100755--- a/tasks/validateOptions.py+++ b/tasks/validateOptions.py@@ -100,6 +100,14 @@ for layer_id in wv["layers"].keys():palette_id + ".json")):error("[%s] Unknown palette: %s" % (layer_id, palette_id))del layer["palette"]+ if "vectorStyle" in layer and "id" not in layer["vectorStyle"]:+ error("[%s] No vectorStyle definition" % (layer_id))+ elif "vectorStyle" in layer:+ vector_style_id = layer["vectorStyle"]["id"]+ if not os.path.exists(os.path.join(config_dir, "vectorstyles",+ vector_style_id + ".json")):+ error("[%s] Unknown vector style: %s" % (layer_id, vector_style_id))+ del layer["vectorStyle"]if "group" not in layer and opt.get("warnOnUnexpectedLayer"):error("[%s] Possible unexpected layer, no group defined" % layer_id)remove_layer(wv, layer_id)diff --git a/web/js/map/layerbuilder.js b/web/js/map/layerbuilder.jsindex 08f9e3872..fca9c8b33 100644--- a/web/js/map/layerbuilder.js+++ b/web/js/map/layerbuilder.js@@ -1,4 +1,5 @@import util from '../util/util';+import palettes from '../palettes/palettes';import OlTileGridWMTS from 'ol/tilegrid/WMTS';import OlSourceWMTS from 'ol/source/WMTS';import OlSourceTileWMS from 'ol/source/TileWMS';@@ -8,9 +9,15 @@ import OlTileGridTileGrid from 'ol/tilegrid/TileGrid';import MVT from 'ol/format/MVT';import LayerVectorTile from 'ol/layer/VectorTile';import SourceVectorTile from 'ol/source/VectorTile';+import Style from 'ol/style/style';+import Circle from 'ol/style/circle';+import Fill from 'ol/style/fill';+import Text from 'ol/style/text';+import Stroke from 'ol/style/stroke';import lodashCloneDeep from 'lodash/cloneDeep';import lodashMerge from 'lodash/merge';import lodashEach from 'lodash/each';+import lodashIsEmpty from 'lodash/isEmpty';import { lookupFactory } from '../ol/lookupimagetile';import {isActive as isPaletteActive,@@ -21,6 +28,7 @@ import {export function mapLayerBuilder(models, config, cache, mapUi, store) {var self = {};self.init = function(Parent) {+ console.log(config);self.extentLayers = [];mapUi.events.on('selecting', hideWrap);mapUi.events.on('selectiondone', showWrap);@@ -385,11 +393,215 @@ export function mapLayerBuilder(models, config, cache, mapUi, store) {})});+ var scaleFeature = function (base, resolution) {+ // var zoom = map.getView()+ // .getZoom();+ // var zoom = resolution;+ // Minimum size of the button is 15 pixels+ base = 5;+ // Double the size for each zoom level+ var add = Math.pow(2, resolution);+ // But 47 pixels is the maximum size+ var size = Math.min(base + add, base + 32);+ return {+ scale: size / 48,+ size: size+ };+ };++ // Create style options and store them in a styleCache Object+ // ref: http://openlayers.org/en/v3.10.1/examples/kml-earthquakes.html+ // ref: http://openlayersbook.github.io/ch06-styling-vector-layers/example-07.html+ var featureStyles = function(feature, resolution) {+ var featureStyle, color, fill, stroke, image, text, label, labelFillColor, labelStrokeColor;+ var fillColor = 'rgba(255,255,255,0.4)';+ var strokeColor = '#3399CC';+ var width = 1.25;+ var radius = 5;++ if (config.vectorStyles.rendered[def.vectorStyle.id]) {+ var layerStyles = config.vectorStyles.rendered[def.vectorStyle.id].styles;+ var styleGroup = Object.keys(layerStyles).map(e => layerStyles[e]);+ }+ var styleGroupCount = 0;+ var matchedPropertyStyles = [];+ var matchedLineStyles = [];++ if (config.vectorStyles.rendered[def.vectorStyle.id]) {+ // Match JSON styles from GC to vector features and add styleValue to arrays+ lodashEach(styleGroup, function(styleValues) {+ let stylePropertyKey = styleValues.property;+ if (stylePropertyKey in feature.properties_) matchedPropertyStyles.push(styleValues);+ if (feature.type_ === 'LineString' && styleValues.lines) matchedLineStyles.push(styleValues);+ });+ }++ if (lodashIsEmpty(matchedPropertyStyles) && lodashIsEmpty(matchedLineStyles)) {+ featureStyle = styleCache['default'];++ let defaultFill = new Fill({+ color: fillColor+ });+ let deafultStroke = new Stroke({+ color: strokeColor,+ width: width+ });++ if (!featureStyle) {+ featureStyle = new Style({+ image: new Circle({+ fill: defaultFill,+ stroke: deafultStroke,+ radius: radius+ }),+ fill: defaultFill,+ stroke: deafultStroke+ });+ styleCache['default'] = featureStyle;+ }+ } else {+ // Style vector points+ lodashEach(matchedPropertyStyles, function(matchedStyle) {+ styleGroupCount++;+ let pointStyle = feature.get(matchedStyle.property) + '_' + styleGroupCount;+ if (pointStyle) {+ featureStyle = styleCache[pointStyle];++ // If there is a range, style properties based on ranges+ if (matchedStyle.range) {+ let ranges = matchedStyle.range.split(',');+ let lowRange = ranges[ranges.length - 2].substring(1).trim();+ let highRange = ranges[ranges.length - 1].slice(0, -1).trim();+ if (matchedStyle.range.startsWith('[') && matchedStyle.range.endsWith(']')) { // greater than or equal to + less than or equal to+ if (feature.properties_[matchedStyle.property] >= lowRange && feature.properties_[matchedStyle.property] <= highRange) {+ color = matchedStyle.points.color;+ }+ } else if (matchedStyle.range.startsWith('[') && matchedStyle.range.endsWith(')')) { // greater than or equal to + less than+ if (feature.properties_[matchedStyle.property] >= lowRange && feature.properties_[matchedStyle.property] < highRange) {+ color = matchedStyle.points.color;+ }+ } else if (matchedStyle.range.startsWith('(') && matchedStyle.range.endsWith(']')) { // greater than + less than or equal to+ if (feature.properties_[matchedStyle.property] > lowRange && feature.properties_[matchedStyle.property] <= highRange) {+ color = matchedStyle.points.color;+ }+ } else if (matchedStyle.range.startsWith('(') && matchedStyle.range.endsWith(')')) { // greater than + less than+ if (feature.properties_[matchedStyle.property] > lowRange && feature.properties_[matchedStyle.property] < highRange) {+ color = matchedStyle.points.color;+ }+ } else {+ color = matchedStyle.points.color;+ }+ // If there is a regexp and time property, style time vector points+ } else if (feature.properties_.time && matchedStyle.property === 'time' && matchedStyle.regex) {+ let time = feature.properties_.time;+ let pattern = new RegExp(matchedStyle.regex);+ let timeTest = pattern.test(time);+ if (timeTest) {+ color = matchedStyle.points.color;+ radius = matchedStyle.points.radius;+ if (matchedStyle.label) {+ label = feature.properties_.time;+ labelFillColor = matchedStyle.label.fill_color;+ labelStrokeColor = matchedStyle.label.stroke_color;+ }+ }+ // Else set default styles+ } else {+ color = matchedStyle.points.color;+ radius = matchedStyle.points.radius;+ width = matchedStyle.points.width;+ }++ if (!featureStyle) {+ fill = new Fill({+ color: color || fillColor+ });++ stroke = new Stroke({+ color: color || strokeColor,+ width: width+ });++ image = new Circle({+ fill: fill,+ stroke: stroke,+ radius: radius+ });++ text = new Text({+ text: label || '',+ fill: new Fill({+ color: labelFillColor || fillColor+ }),+ stroke: new Stroke({+ color: labelStrokeColor || strokeColor+ }),+ font: '9px sans-serif',+ offsetX: 24+ });++ featureStyle = new Style({+ fill: fill,+ stroke: stroke,+ image: image,+ text: text+ });++ var radiusDimensions = scaleFeature(radius, resolution);+ radius = radiusDimensions.size;++ var widthDimensions = scaleFeature(width, resolution);+ width = widthDimensions.size;+ // if ((width / (resolution * 100)) > width) {+ // width = width / (resolution * 100);+ // }++ stroke.setWidth(width);++ styleCache[pointStyle] = featureStyle;+ }+ }+ });++ // Style vector lines+ lodashEach(matchedLineStyles, function(matchedStyle) {+ let lineStyle = feature.type;+ let lineColor = matchedStyle.lines.color;+ let lineWidth = matchedStyle.lines.width;+ let width = lineWidth || 1.25;++ if (!featureStyle) {+ var stroke = new Stroke({+ color: lineColor || '#3399CC',+ width: width+ });++ featureStyle = new Style({+ stroke: stroke+ });++ var widthDimensions = scaleFeature(width, resolution);+ width = widthDimensions.size;+ // if ((width / (resolution * 100)) > width) {+ // width = width / (resolution * 100);+ // }++ stroke.setWidth(width);+ styleCache[lineStyle] = featureStyle;+ }+ });+ }++ // The style for this feature is in the cache. Return it as an array+ return featureStyle;+ };+var layer = new LayerVectorTile({renderMode: 'image',preload: 1,extent: extent,- source: sourceOptions+ source: sourceOptions,+ style: featureStyles});return layer;diff --git a/web/js/palettes/model.js b/web/js/palettes/model.jsnew file mode 100644index 000000000..2a6f5575b--- /dev/null+++ b/web/js/palettes/model.js@@ -0,0 +1,650 @@+import lodashEach from 'lodash/each';+import lodashFind from 'lodash/find';+import lodashCloneDeep from 'lodash/cloneDeep';+import lodashIsNaN from 'lodash/isNaN';+import lodashIsUndefined from 'lodash/isUndefined';+import lodashParseInt from 'lodash/parseInt';+import lodashFindIndex from 'lodash/findIndex';+import util from '../util/util';+import palettes from './palettes';+import Promise from 'bluebird';++export function palettesModel(models, config) {+ config.palettes = config.palettes || {+ rendered: {},+ custom: {}+ };++ config.vectorStyles = config.vectorStyles || {+ rendered: {}+ };++ var self = {};+ self.events = util.events();+ self.active = {};+ self.activeB = {};++ self.getRenderedPalette = function(layerId, index) {+ var name = config.layers[layerId].palette.id;+ var palette = config.palettes.rendered[name];+ if (!lodashIsUndefined(index)) {+ if (palette && palette.maps) {+ palette = palette.maps[index];+ }+ }+ return palette;+ };++ self.getRenderedVectorStyle = function (layerId, index) {+ var name = config.layers[layerId].vectorStyle.id;+ var vectorStyle = config.vectorStyles.rendered[name];+ if (!lodashIsUndefined(index)) {+ if (vectorStyle.styles) {+ vectorStyle = vectorStyle.styles[index];+ }+ }+ return vectorStyle;+ };++ self.getCustomPalette = function(paletteId) {+ var palette = config.palettes.custom[paletteId];+ if (!palette) {+ throw new Error('Invalid palette: ' + paletteId);+ }+ return palette;+ };++ var prepare = function(layerId, groupStr) {+ groupStr = groupStr || models.layers.activeLayers;+ self[groupStr][layerId] = self[groupStr][layerId] || {};+ var active = self[groupStr][layerId];+ active.maps = active.maps || [];+ lodashEach(self.getRenderedPalette(layerId).maps, function(palette, index) {+ if (!active.maps[index]) {+ active.maps[index] = lodashCloneDeep(palette);+ }+ });+ };++ self.allowed = function(layerId) {+ if (!palettes.supported) {+ return false;+ }+ let palette = config.layers[layerId].palette;+ if (!palette || palette.immutable) {+ return false;+ }+ return config.layers[layerId].palette;+ };++ self.setCustom = function(layerId, paletteId, index, groupStr) {+ groupStr = groupStr || models.layers.activeLayers;+ if (!config.layers[layerId]) {+ throw new Error('Invalid layer: ' + layerId);+ }+ prepare(layerId, groupStr);+ index = lodashIsUndefined(index) ? 0 : index;+ var active = self[groupStr][layerId];+ var palette = active.maps[index];+ if (palette.custom === paletteId) {+ return;+ }+ palette.custom = paletteId;+ updateLookup(layerId, groupStr);+ self.events.trigger('set-custom', layerId, active, groupStr);+ self.events.trigger('change');+ const layerIndex = lodashFindIndex(models.layers[groupStr], { id: layerId });+ if (layerIndex >= 0) {+ models.layers[groupStr][layerIndex].custom = self[groupStr][layerId];+ models.layers.events.trigger('change');+ }+ };++ self.clearCustom = function(layerId, index, groupStr) {+ groupStr = groupStr || models.layers.activeLayers;+ index = lodashIsUndefined(index) ? 0 : index;+ var active = self[groupStr][layerId];+ if (!active) {+ return;+ }+ var palette = active.maps[index];+ if (!palette.custom) {+ return;+ }+ delete palette.custom;+ updateLookup(layerId, groupStr);+ self.events.trigger('clear-custom', layerId, groupStr);+ self.events.trigger('change');+ const layerIndex = lodashFindIndex(models.layers[groupStr], { id: layerId });+ if (layerIndex >= 0) {+ models.layers[groupStr][layerIndex].custom = self[groupStr][layerId];+ models.layers.events.trigger('change');+ }+ };++ self.setRange = function(layerId, min, max, squash, index, groupStr) {+ groupStr = groupStr || models.layers.activeLayers;+ prepare(layerId);+ index = lodashIsUndefined(index) ? 0 : index;+ var palette = self[groupStr][layerId].maps[index];+ if (min === 0) {+ min = undefined;+ }+ const legend = self.get(layerId, index, groupStr);+ if (legend.entries && legend.entries.values && max === legend.entries.values.length - 1) {+ max = undefined;+ }+ palette.min = min;+ palette.max = max;+ palette.squash = squash;+ updateLookup(layerId, groupStr);+ self.events.trigger('range', layerId, palette.min, palette.max, groupStr);+ self.events.trigger('change');+ const layerIndex = lodashFindIndex(models.layers[groupStr], { id: layerId });+ if (layerIndex >= 0) {+ models.layers[groupStr][layerIndex].custom = self[groupStr][layerId];+ models.layers.events.trigger('change');+ }+ };++ self.getCount = function(layerId) {+ if (self.getRenderedPalette(layerId).maps) {+ return self.getRenderedPalette(layerId).maps.length;+ } else {+ return 0;+ }+ };+ /**+ * Gets a single colormap (entries / legend combo)+ *+ *+ * @method get+ * @static+ * @param str {string} The ID of the layer+ * @param number {Number} The index of the colormap for this layer, default 0+ * object.+ * @return {object} object including the entries and legend+ */+ self.get = function(layerId, index, groupStr) {+ groupStr = groupStr || models.layers.activeLayers;+ index = lodashIsUndefined(index) ? 0 : index;+ if (self[groupStr][layerId]) {+ return self[groupStr][layerId].maps[index];+ }+ return self.getRenderedPalette(layerId, index);+ };+ /**+ * Gets the legend of a colormap+ *+ *+ * @method getLegend+ * @static+ * @param str {string} The ID of the layer+ * @param number {Number} The index of the colormap for this layer, default 0+ * object.+ * @return {object} object of the legend+ */+ self.getLegend = function(layerId, index, groupStr) {+ groupStr = groupStr || models.layers.activeLayers;+ var value = self.get(layerId, index, groupStr);+ return value.legend || value.entries;+ };+ /**+ * Gets the legend of a colormap+ *+ *+ * @method getDefaultLegend+ * @static+ * @param str {string} The ID of the layer+ * @param number {Number} The index of the colormap for this layer, default 0+ * object.+ * @return {object} object of the legend+ */+ self.getDefaultLegend = function(layerId, index) {+ var palette = self.getRenderedPalette(layerId, index);+ return palette.legend || palette.entries;+ };++ self.getLegends = function(layerId, groupStr) {+ groupStr = groupStr || models.layers.activeLayers;+ var legends = [];+ var count = self.getCount(layerId);+ for (var i = 0; i < count; i++) {+ legends.push(self.getLegend(layerId, i, groupStr));+ }+ return legends;+ };++ // Is a canvas required?+ self.isActive = function(layerId, group) {+ group = group || models.layers.activeLayers;+ return self[group][layerId];+ };++ // Looks up options/colormaps/layer.xml colormap entry+ self.getLookup = function(layerId, groupstr) {+ groupstr = groupstr || models.layers.activeLayers;+ return self[groupstr][layerId].lookup;+ };++ self.clear = function() {+ self.active = {};+ self.events.trigger('update');+ };++ self.restore = function(active) {+ self.active = active;+ self.events.trigger('update');+ };++ var getMinValue = function(v) {+ return v.length ? v[0] : v;+ };++ var getMaxValue = function(v) {+ return v.length ? v[v.length - 1] : v;+ };++ self.save = function(state) {+ var groupArray = [models.layers.activeLayers];+ if (self.inUse() && !state.l) {+ throw new Error('No layers in state');+ }+ if (models.compare && models.compare.active) {+ groupArray = ['active', 'activeB'];+ }+ lodashEach(groupArray, groupStr => {+ lodashEach(self[groupStr], function(def, layerId) {+ if (+ !lodashFind(models.layers.get({}, models.layers[groupStr]), {+ id: layerId+ })+ ) {+ return;+ }+ if (self.getCount(layerId) > 1) {+ self.saveMulti(state, layerId, groupStr);+ } else {+ self.saveSingle(state, layerId, groupStr);+ }+ });+ });+ };+ self.palettePromise = function(layerId, paletteId) {+ return new Promise((resolve, reject) => {+ if (config.palettes.rendered[paletteId]) {+ resolve();+ } else {+ palettes.loadRenderedPalette(config, layerId).done(function(result) {+ resolve(result);+ });+ }+ });+ };+ self.saveSingle = function(state, layerId, groupStr) {+ groupStr = groupStr || models.layers.activeLayers;+ var stateStr = 'l';+ if (groupStr === 'activeB' && models.compare && models.compare.active) stateStr = 'l1';+ var attr = lodashFind(state[stateStr], {+ id: layerId+ }).attributes;+ var def = self.get(layerId, undefined, groupStr);++ if (def.custom) {+ attr.push({+ id: 'palette',+ value: def.custom+ });+ }+ if (def.min) {+ var minValue = def.entries.values[def.min];+ attr.push({+ id: 'min',+ value: minValue+ });+ }+ if (def.max) {+ var maxValue = def.entries.values[def.max];+ attr.push({+ id: 'max',+ value: maxValue+ });+ }+ if (def.squash) {+ attr.push({+ id: 'squash'+ });+ }+ };++ self.saveMulti = function(state, layerId, groupStr) {+ groupStr = groupStr || models.layers.activeLayers;+ var stateStr = 'l';+ var palettes = [];+ var hasPalettes = false;+ var min = [];+ var hasMin = false;+ var max = [];+ var hasMax = false;+ var squash = [];+ var hasSquash = false;+ if (groupStr === 'activeB' && models.compare && models.compare.active) stateStr = 'l1';++ for (var i = 0; i < self.getCount(layerId); i++) {+ var def = self.get(layerId, i, groupStr);+ if (def.custom) {+ palettes.push(def.custom);+ hasPalettes = true;+ } else {+ palettes.push('');+ }++ if (def.min) {+ min.push(getMinValue(def.entries.values[def.min]));+ hasMin = true;+ } else {+ min.push('');+ }++ if (def.max) {+ max.push(getMaxValue(def.entries.values[def.max]));+ hasMax = true;+ } else {+ max.push('');+ }++ if (def.squash) {+ squash.push(def.squash);+ hasSquash = true;+ } else {+ squash.push('');+ }+ }++ var attr = lodashFind(state[stateStr], {+ id: layerId+ }).attributes;+ if (hasPalettes) {+ attr.push({+ id: 'palette',+ value: palettes.join(';')+ });+ }+ if (hasMin) {+ attr.push({+ id: 'min',+ value: min.join(';')+ });+ }+ if (hasMax) {+ attr.push({+ id: 'max',+ value: max.join(';')+ });+ }+ if (hasSquash) {+ attr.push({+ id: 'squash',+ value: squash.join(';')+ });+ }+ };++ self.key = function(layerId, groupStr) {+ groupStr = groupStr || models.layers.activeLayers;+ if (!self.isActive(layerId, groupStr)) {+ return '';+ }+ var def = self.get(layerId, undefined, groupStr);+ var keys = [];+ if (def.custom) {+ keys.push('palette=' + def.custom);+ }+ if (def.min) {+ keys.push('min=' + def.min);+ }+ if (def.max) {+ keys.push('max=' + def.max);+ }+ if (def.squash) {+ keys.push('squash');+ }+ return keys.join(',');+ };++ self.load = function(state, errors) {+ var stateArray = [{ stateStr: 'l', groupStr: 'active' }];+ if (!palettes.supported) {+ return self;+ }+ if (state.l1) {+ stateArray = [+ { stateStr: 'l', groupStr: 'active' },+ { stateStr: 'l1', groupStr: 'activeB' }+ ];+ }+ lodashEach(stateArray, stateObj => {+ lodashEach(state[stateObj.stateStr], function(layerDef) {+ var layerId = layerDef.id;+ var minValue, maxValue;+ var min = [];+ var max = [];+ var squash = [];+ var count = 0;+ lodashEach(layerDef.attributes, function(attr) {+ var values;+ if (attr.id === 'palette') {+ count = self.getCount(layerId);+ values = util.toArray(attr.value.split(';'));+ lodashEach(values, function(value, index) {+ try {+ self.setCustom(layerId, value, index, stateObj.groupStr);+ } catch (error) {+ errors.push('Invalid palette: ' + value);+ }+ });+ }+ if (attr.id === 'min') {+ count = self.getCount(layerId);+ values = util.toArray(attr.value.split(';'));+ lodashEach(values, function(value, index) {+ if (value === '') {+ min.push(undefined);+ return;+ }+ minValue = parseFloat(value);+ if (lodashIsNaN(minValue)) {+ errors.push('Invalid min value: ' + value);+ } else {+ min.push(+ findIndex(layerId, 'min', minValue, index, stateObj.groupStr)+ );+ }+ });+ }+ if (attr.id === 'max') {+ count = self.getCount(layerId);+ values = util.toArray(attr.value.split(';'));+ lodashEach(values, function(value, index) {+ if (value === '') {+ max.push(undefined);+ return;+ }+ maxValue = parseFloat(value);+ if (lodashIsNaN(maxValue)) {+ errors.push('Invalid max value: ' + value);+ } else {+ max.push(+ findIndex(layerId, 'max', maxValue, index, stateObj.groupStr)+ );+ }+ });+ }+ if (attr.id === 'squash') {+ count = self.getCount(layerId);+ if (attr.value === true) {+ squash[0] = true;+ } else {+ values = util.toArray(attr.value.split(';'));+ lodashEach(values, function(value) {+ squash.push(value === 'true');+ });+ }+ }+ });+ if (min.length > 0 || max.length > 0) {+ for (var i = 0; i < count; i++) {+ var vmin = min.length > 0 ? min[i] : undefined;+ var vmax = max.length > 0 ? max[i] : undefined;+ var vsquash = squash.length > 0 ? squash[i] : undefined;+ self.setRange(layerId, vmin, vmax, vsquash, i, stateObj.groupStr);+ }+ }+ });+ });+ self.loaded = true;+ return self;+ };++ var findIndex = function(layerId, type, value, index, groupStr) {+ groupStr = groupStr || models.layers.activeLayers;+ index = index || 0;+ var values = self.get(layerId, index, groupStr).entries.values;+ var result;+ lodashEach(values, function(check, index) {+ var min = getMinValue(check);+ var max = getMaxValue(check);+ if (type === 'min' && value === min) {+ result = index;+ return false;+ }+ if (type === 'max' && value === max) {+ result = index;+ return false;+ }+ });+ return result;+ };++ // If any custom rendering is being used, image download must turn it+ // off+ self.inUse = function(groupStr) {+ groupStr = groupStr || models.layers.activeLayers;+ var layers = models.layers.get({}, models.layers[groupStr]);+ var found = false;+ lodashEach(layers, function(layer) {+ if (self[groupStr][layer.id]) {+ found = true;+ return false;+ }+ });+ return found;+ };++ var useLookup = function(layerId, groupStr) {+ groupStr = groupStr || models.layers.activeLayers;+ var use = false;+ var active = self[groupStr][layerId].maps;++ lodashEach(active, function(palette, index) {+ if (palette.custom) {+ use = true;+ return false;+ }+ var rendered = self.getRenderedPalette(layerId, index);+ if (palette.type !== 'classification') {+ if (palette.min <= 0) {+ delete palette.min;+ }+ if (palette.max >= rendered.entries.values.length) {+ delete palette.max;+ }+ if (+ !lodashIsUndefined(palette.min) ||+ !lodashIsUndefined(palette.max)+ ) {+ use = true;+ return false;+ }+ }+ });+ return use;+ };++ var updateLookup = function(layerId, groupStr) {+ groupStr = groupStr || models.layers.activeLayers;+ if (!useLookup(layerId, groupStr)) {+ delete self[groupStr][layerId];+ return;+ }+ var lookup = {};+ var active = self[groupStr][layerId].maps;+ lodashEach(active, function(palette, index) {+ var oldLegend = palette.legend;+ var entries = palette.entries;+ var legend = {+ colors: [],+ minLabel: oldLegend.minLabel,+ maxLabel: oldLegend.maxLabel,+ tooltips: oldLegend.tooltips,+ units: oldLegend.units,+ type: entries.type,+ title: entries.title,+ id: oldLegend.id+ };+ var source = entries.colors;+ var target = palette.custom+ ? self.getCustomPalette(palette.custom).colors+ : source;++ var min = palette.min || 0;+ var max = palette.max || source.length;++ var sourceCount = source.length;+ var targetCount = target.length;++ lodashEach(source, function(color, index) {+ var targetColor;+ if (index < min || index > max) {+ targetColor = '00000000';+ } else {+ var sourcePercent, targetIndex;+ if (palette.squash) {+ sourcePercent = (index - min) / (max - min);+ if (index === max) {+ sourcePercent = 1.0;+ }+ targetIndex = Math.floor(sourcePercent * targetCount);+ if (targetIndex >= targetCount) {+ targetIndex = targetCount - 1;+ }+ } else {+ sourcePercent = index / sourceCount;+ targetIndex = Math.floor(sourcePercent * targetCount);+ }+ targetColor = target[targetIndex];+ }+ legend.colors.push(targetColor);+ var lookupSource =+ lodashParseInt(color.substring(0, 2), 16) ++ ',' ++ lodashParseInt(color.substring(2, 4), 16) ++ ',' ++ lodashParseInt(color.substring(4, 6), 16) ++ ',' ++ lodashParseInt(color.substring(6, 8), 16);+ var lookupTarget = {+ r: lodashParseInt(targetColor.substring(0, 2), 16),+ g: lodashParseInt(targetColor.substring(2, 4), 16),+ b: lodashParseInt(targetColor.substring(4, 6), 16),+ a: lodashParseInt(targetColor.substring(6, 8), 16)+ };+ lookup[lookupSource] = lookupTarget;+ });+ palette.legend = legend;+ });+ self[groupStr][layerId].lookup = lookup;+ };++ return self;+}diff --git a/web/js/palettes/palettes.js b/web/js/palettes/palettes.jsnew file mode 100644index 000000000..bf92c87b6--- /dev/null+++ b/web/js/palettes/palettes.js@@ -0,0 +1,206 @@+import lodashEach from 'lodash/each';+import lodashFind from 'lodash/find';+import util from '../util/util';+import wvui from '../ui/ui';++export default (function(self) {+ var checkerboard;++ self.supported = true;++ var init = function() {+ var browser = util.browser;+ if (browser.ie || !browser.webWorkers || !browser.cors) {+ self.supported = false;+ } else {+ drawCheckerboard();+ }+ };++ self.colorbar = function(target, colors) {+ var canvas;+ if (target.length) {+ canvas = $(target).get(0);+ } else {+ canvas = target;+ }+ if (!canvas) {+ return;+ }+ var g = canvas.getContext('2d');++ g.fillStyle = checkerboard;+ g.fillRect(0, 0, canvas.width, canvas.height);+ if (colors) {+ var bins = colors.length;+ var binWidth = canvas.width / bins;+ var drawWidth = Math.ceil(binWidth);+ lodashEach(colors, function(color, i) {+ g.fillStyle = util.hexToRGBA(color);+ g.fillRect(Math.floor(binWidth * i), 0, drawWidth, canvas.height);+ });+ }+ };++ var drawCheckerboard = function() {+ var size = 2;+ var canvas = document.createElement('canvas');++ canvas.width = size * 2;+ canvas.height = size * 2;++ var g = canvas.getContext('2d');++ // g.fillStyle = "rgb(102, 102, 102)";+ g.fillStyle = 'rgb(200, 200, 200)';+ g.fillRect(0, 0, size, size);+ g.fillRect(size, size, size, size);++ // g.fillStyle = "rgb(153, 153, 153)";+ g.fillStyle = 'rgb(240, 240, 240)';+ g.fillRect(0, size, size, size);+ g.fillRect(size, 0, size, size);++ checkerboard = g.createPattern(canvas, 'repeat');+ };++ self.translate = function(source, target) {+ var translation = [];+ lodashEach(source, function(color, index) {+ var sourcePercent = index / source.length;+ var targetIndex = Math.floor(sourcePercent * target.length);+ translation.push(target[targetIndex]);+ });+ return translation;+ };++ self.lookup = function(sourcePalette, targetPalette) {+ var lookup = {};+ lodashEach(sourcePalette.colors, function(sourceColor, index) {+ var source =+ parseInt(sourceColor.substring(0, 2), 16) ++ ',' ++ parseInt(sourceColor.substring(2, 4), 16) ++ ',' ++ parseInt(sourceColor.substring(4, 6), 16) ++ ',' ++ '255';+ var targetColor = targetPalette.colors[index];+ var target = {+ r: parseInt(targetColor.substring(0, 2), 16),+ g: parseInt(targetColor.substring(2, 4), 16),+ b: parseInt(targetColor.substring(4, 6), 16),+ a: 255+ };+ lookup[source] = target;+ });+ return lookup;+ };++ self.loadCustom = function(config) {+ return util.load.config(+ config.palettes,+ 'custom',+ 'config/palettes-custom.json'+ );+ };++ self.loadRenderedPalette = function(config, layerId) {+ var layer = config.layers[layerId];+ return util.load.config(+ config.palettes.rendered,+ layer.palette.id,+ 'config/palettes/' + layer.palette.id + '.json'+ );+ };++ self.loadRenderedVectorStyle = function (config, layerId) {+ var layer = config.layers[layerId];+ return util.load.config(config.vectorStyles.rendered,+ layer.vectorStyle.id, 'config/vectorstyles/' + layer.vectorStyle.id + '.json');+ };++ self.requirements = function(state, config, startup) {+ var promises = [];+ if (startup || !state.tr) {+ config.vectorStyles = {+ rendered: {}+ };+ config.palettes = {+ rendered: {},+ custom: {}+ };+ }+ lodashEach(state.l, function(qsLayer) {+ var layerId = qsLayer.id;+ if (config.layers[layerId] && config.layers[layerId].palette) {+ promises.push(self.loadRenderedPalette(config, layerId));+ } else if (config.layers[layerId] && config.layers[layerId].vectorStyle) {+ promises.push(self.loadRenderedVectorStyle(config, layerId));+ }+ var custom = lodashFind(qsLayer.attributes, {+ id: 'palette'+ });+ if (custom) {+ promises.push(self.loadCustom(config));+ }+ });+ if (promises.length > 0) {+ var promise = $.Deferred();+ $.when+ .apply(null, promises)+ .then(promise.resolve)+ .fail(promise.reject);+ return promise;+ }+ };++ // Only for permalink 1.1 support+ self.parse = function(state, errors, config) {+ if (state.palettes) {+ if (!self.supported) {+ // FIXME: This should go in errors+ delete state.palettes;+ wvui.notify(+ 'The custom palette feature is not supported ' ++ 'with your web browser. Upgrade or try again in a ' ++ 'different browser'+ );+ return;+ }+ var parts = state.palettes.split('~');+ lodashEach(parts, function(part) {+ var items = part.split(',');+ var layerId = items[0];+ var paletteId = items[1];+ if (!config.layers[layerId]) {+ errors.push({+ message: 'Invalid layer for palette ' + paletteId + ': ' + layerId+ });+ } else if (!config.layers[layerId].palette) {+ errors.push({+ message: 'Layer ' + layerId + ' does not ' + 'support palettes'+ });+ } else {+ var layer = lodashFind(state.l, {+ id: layerId+ });+ if (layer) {+ layer.attributes.push({+ id: 'palette',+ value: paletteId+ });+ } else {+ errors.push({+ message: 'Layer ' + layerId + ' is not ' + 'active'+ });+ }+ }+ });+ delete state.paletes;+ }+ };++ init();+ return self;+})({});