001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.imagery.vectortile.mapbox;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.io.ByteArrayOutputStream;
007import java.io.IOException;
008import java.util.ArrayList;
009import java.util.Arrays;
010import java.util.Collection;
011import java.util.Collections;
012import java.util.HashMap;
013import java.util.List;
014import java.util.Map;
015import java.util.Objects;
016import java.util.function.Function;
017import java.util.stream.Collectors;
018
019import org.openstreetmap.josm.data.protobuf.ProtobufParser;
020import org.openstreetmap.josm.data.protobuf.ProtobufRecord;
021import org.openstreetmap.josm.tools.Destroyable;
022
023/**
024 * A Mapbox Vector Tile Layer
025 * @author Taylor Smock
026 * @since 17862
027 */
028public final class Layer implements Destroyable {
029    private static final class ValueFields<T> {
030        static final ValueFields<String> STRING = new ValueFields<>(1, ProtobufRecord::asString);
031        static final ValueFields<Float> FLOAT = new ValueFields<>(2, ProtobufRecord::asFloat);
032        static final ValueFields<Double> DOUBLE = new ValueFields<>(3, ProtobufRecord::asDouble);
033        static final ValueFields<Number> INT64 = new ValueFields<>(4, ProtobufRecord::asUnsignedVarInt);
034        // This may have issues if there are actual uint_values (i.e., more than {@link Long#MAX_VALUE})
035        static final ValueFields<Number> UINT64 = new ValueFields<>(5, ProtobufRecord::asUnsignedVarInt);
036        static final ValueFields<Number> SINT64 = new ValueFields<>(6, ProtobufRecord::asSignedVarInt);
037        static final ValueFields<Boolean> BOOL = new ValueFields<>(7, r -> r.asUnsignedVarInt().longValue() != 0);
038
039        /**
040         * A collection of methods to map a record to a type
041         */
042        public static final Collection<ValueFields<?>> MAPPERS =
043          Collections.unmodifiableList(Arrays.asList(STRING, FLOAT, DOUBLE, INT64, UINT64, SINT64, BOOL));
044
045        private final byte field;
046        private final Function<ProtobufRecord, T> conversion;
047        private ValueFields(int field, Function<ProtobufRecord, T> conversion) {
048            this.field = (byte) field;
049            this.conversion = conversion;
050        }
051
052        /**
053         * Get the field identifier for the value
054         * @return The identifier
055         */
056        public byte getField() {
057            return this.field;
058        }
059
060        /**
061         * Convert a protobuf record to a value
062         * @param protobufRecord The record to convert
063         * @return the converted value
064         */
065        public T convertValue(ProtobufRecord protobufRecord) {
066            return this.conversion.apply(protobufRecord);
067        }
068    }
069
070    /** The field value for a layer (in {@link ProtobufRecord#getField}) */
071    public static final byte LAYER_FIELD = 3;
072    private static final byte VERSION_FIELD = 15;
073    private static final byte NAME_FIELD = 1;
074    private static final byte FEATURE_FIELD = 2;
075    private static final byte KEY_FIELD = 3;
076    private static final byte VALUE_FIELD = 4;
077    private static final byte EXTENT_FIELD = 5;
078    /** The default extent for a vector tile */
079    static final int DEFAULT_EXTENT = 4096;
080    private static final byte DEFAULT_VERSION = 1;
081    /** This is <i>technically</i> an integer, but there are currently only two major versions (1, 2). Required. */
082    private final byte version;
083    /** A unique name for the layer. This <i>must</i> be unique on a per-tile basis. Required. */
084    private final String name;
085
086    /** The extent of the tile, typically 4096. Required. */
087    private final int extent;
088
089    /** A list of unique keys. Order is important. Optional. */
090    private final List<String> keyList = new ArrayList<>();
091    /** A list of unique values. Order is important. Optional. */
092    private final List<Object> valueList = new ArrayList<>();
093    /** The actual features of this layer in this tile */
094    private final List<Feature> featureCollection;
095
096    /**
097     * Create a layer from a collection of records
098     * @param records The records to convert to a layer
099     * @throws IOException - if an IO error occurs
100     */
101    public Layer(Collection<ProtobufRecord> records) throws IOException {
102        // Do the unique required fields first
103        Map<Integer, List<ProtobufRecord>> sorted = new HashMap<>(records.size());
104        byte tVersion = DEFAULT_VERSION;
105        String tName = null;
106        int tExtent = DEFAULT_EXTENT;
107        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(4);
108        for (ProtobufRecord protobufRecord : records) {
109            if (protobufRecord.getField() == VERSION_FIELD) {
110                tVersion = protobufRecord.asUnsignedVarInt().byteValue();
111                // Per spec, we cannot continue past this until we have checked the version number
112                if (tVersion != 1 && tVersion != 2) {
113                    throw new IllegalArgumentException(tr("We do not understand version {0} of the vector tile specification", tVersion));
114                }
115            } else if (protobufRecord.getField() == NAME_FIELD) {
116                tName = protobufRecord.asString();
117            } else if (protobufRecord.getField() == EXTENT_FIELD) {
118                tExtent = protobufRecord.asUnsignedVarInt().intValue();
119            } else if (protobufRecord.getField() == KEY_FIELD) {
120                this.keyList.add(protobufRecord.asString());
121            } else if (protobufRecord.getField() == VALUE_FIELD) {
122                parseValueRecord(byteArrayOutputStream, protobufRecord);
123            } else {
124                sorted.computeIfAbsent(protobufRecord.getField(), i -> new ArrayList<>(records.size())).add(protobufRecord);
125            }
126        }
127        this.version = tVersion;
128        if (tName == null) {
129            throw new IllegalArgumentException(tr("Vector tile layers must have a layer name"));
130        }
131        this.name = tName;
132        this.extent = tExtent;
133
134        this.featureCollection = new ArrayList<>(sorted.getOrDefault((int) FEATURE_FIELD, Collections.emptyList()).size());
135        for (ProtobufRecord protobufRecord : sorted.getOrDefault((int) FEATURE_FIELD, Collections.emptyList())) {
136            this.featureCollection.add(new Feature(this, protobufRecord));
137        }
138        // Cleanup bytes (for memory)
139        for (ProtobufRecord protobufRecord : records) { // NOSONAR -- this shouldn't be combined since this is a cleanup loop.
140            protobufRecord.close();
141        }
142    }
143
144    private void parseValueRecord(ByteArrayOutputStream byteArrayOutputStream, ProtobufRecord protobufRecord)
145            throws IOException {
146        try (ProtobufParser parser = new ProtobufParser(protobufRecord.getBytes())) {
147            ProtobufRecord protobufRecord2 = new ProtobufRecord(byteArrayOutputStream, parser);
148            int field = protobufRecord2.getField();
149            int valueListSize = this.valueList.size();
150            for (Layer.ValueFields<?> mapper : ValueFields.MAPPERS) {
151                if (mapper.getField() == field) {
152                    this.valueList.add(mapper.convertValue(protobufRecord2));
153                    break;
154                }
155            }
156            if (valueListSize == this.valueList.size()) {
157                throw new IllegalArgumentException(tr("Unknown field in vector tile layer value ({0})", field));
158            }
159        }
160    }
161
162    /**
163     * Get all the records from a array of bytes
164     * @param bytes The byte information
165     * @return All the protobuf records
166     * @throws IOException If there was an error reading the bytes (unlikely)
167     */
168    private static Collection<ProtobufRecord> getAllRecords(byte[] bytes) throws IOException {
169        try (ProtobufParser parser = new ProtobufParser(bytes)) {
170            return parser.allRecords();
171        }
172    }
173
174    /**
175     * Create a new layer
176     * @param bytes The bytes that the layer comes from
177     * @throws IOException - if an IO error occurs
178     */
179    public Layer(byte[] bytes) throws IOException {
180        this(getAllRecords(bytes));
181    }
182
183    /**
184     * Get the extent of the tile
185     * @return The layer extent
186     */
187    public int getExtent() {
188        return this.extent;
189    }
190
191    /**
192     * Get the feature on this layer
193     * @return the features
194     */
195    public Collection<Feature> getFeatures() {
196        return Collections.unmodifiableCollection(this.featureCollection);
197    }
198
199    /**
200     * Get the geometry for this layer
201     * @return The geometry
202     */
203    public Collection<Geometry> getGeometry() {
204        return getFeatures().stream().map(Feature::getGeometryObject).collect(Collectors.toList());
205    }
206
207    /**
208     * Get a specified key
209     * @param index The index in the key list
210     * @return The actual key
211     */
212    public String getKey(int index) {
213        return this.keyList.get(index);
214    }
215
216    /**
217     * Get the name of the layer
218     * @return The layer name
219     */
220    public String getName() {
221        return this.name;
222    }
223
224    /**
225     * Get a specified value
226     * @param index The index in the value list
227     * @return The actual value. This can be a {@link String}, {@link Boolean}, {@link Integer}, or {@link Float} value.
228     */
229    public Object getValue(int index) {
230        return this.valueList.get(index);
231    }
232
233    /**
234     * Get the Mapbox Vector Tile version specification for this layer
235     * @return The version of the Mapbox Vector Tile specification
236     */
237    public byte getVersion() {
238        return this.version;
239    }
240
241    @Override
242    public void destroy() {
243        this.featureCollection.clear();
244        this.keyList.clear();
245        this.valueList.clear();
246    }
247
248    @Override
249    public boolean equals(Object other) {
250        if (other instanceof Layer) {
251            Layer o = (Layer) other;
252            return this.extent == o.extent
253              && this.version == o.version
254              && Objects.equals(this.name, o.name)
255              && Objects.equals(this.featureCollection, o.featureCollection)
256              && Objects.equals(this.keyList, o.keyList)
257              && Objects.equals(this.valueList, o.valueList);
258        }
259        return false;
260    }
261
262    @Override
263    public int hashCode() {
264        return Objects.hash(this.name, this.version, this.extent, this.featureCollection, this.keyList, this.valueList);
265    }
266}