From d593e4d564fef8a5fd56a7dc7ccb104a9ba245e3 Mon Sep 17 00:00:00 2001 From: thinkinggis Date: Wed, 7 Aug 2019 15:40:42 +0800 Subject: [PATCH] fix lint err --- .gitignore | 1 - lib/attr/base.js | 257 ++++ lib/attr/color-util.js | 282 +++++ lib/attr/color.js | 84 ++ lib/attr/colorscales.js | 107 ++ lib/attr/filter.js | 51 + lib/attr/index.js | 37 + lib/attr/opacity.js | 51 + lib/attr/pattern.js | 51 + lib/attr/position.js | 140 +++ lib/attr/shape.js | 89 ++ lib/attr/size.js | 107 ++ lib/attr/symbol.js | 51 + lib/component/control/legend/color.js | 1 + lib/component/control/legend/shape.js | 1 + lib/component/control/legend/size.js | 1 + lib/component/index.js | 14 + lib/component/tooltip/index.js | 693 +++++++++++ lib/core/atlas/font-manager.js | 326 ++++++ lib/core/atlas/icon-manager.js | 102 ++ lib/core/base.js | 86 ++ lib/core/controller/buffer.js | 97 ++ lib/core/controller/event.js | 76 ++ lib/core/controller/geom.js | 56 + lib/core/controller/index.js | 30 + lib/core/controller/interaction.js | 83 ++ lib/core/controller/layer.js | 14 + lib/core/controller/map.js | 70 ++ lib/core/controller/mapping.js | 279 +++++ lib/core/controller/pick.js | 105 ++ lib/core/controller/scale.js | 163 +++ lib/core/controller/tile_mapping.js | 292 +++++ lib/core/engine/camera.js | 43 + lib/core/engine/composer.js | 117 ++ lib/core/engine/copy-shader.js | 36 + lib/core/engine/effect-composer.js | 27 + lib/core/engine/index.js | 110 ++ lib/core/engine/mask-pass.js | 74 ++ lib/core/engine/picking/picking.js | 250 ++++ lib/core/engine/picking/pickingMaterial.js | 30 + lib/core/engine/picking/pickingScene.js | 19 + lib/core/engine/render-pass.js | 52 + lib/core/engine/renderer.js | 56 + lib/core/engine/renderpass.js | 107 ++ lib/core/engine/scene.js | 17 + lib/core/engine/shader-pass.js | 64 + lib/core/engine/shaderPass.js | 79 ++ .../extend/windframebuffer/drawMaterial.js | 50 + .../extend/windframebuffer/draw_geometry.js | 85 ++ lib/core/image.js | 137 +++ lib/core/layer.js | 1010 ++++++++++++++++ lib/core/scene.js | 279 +++++ lib/core/source.js | 274 +++++ lib/core/style.js | 154 +++ lib/core/three.js | 362 ++++++ lib/core/worker.js | 94 ++ lib/geo/bound.js | 1 + lib/geo/buffer.js | 1 + lib/geo/featureIndex.js | 92 ++ lib/geo/lngLat.js | 1 + lib/geo/point.js | 1 + lib/geo/project.js | 55 + lib/geom/base.js | 35 + lib/geom/buffer/buffer.js | 241 ++++ lib/geom/buffer/bufferBase.js | 431 +++++++ lib/geom/buffer/factory.js | 26 + lib/geom/buffer/heatmap/grid.js | 70 ++ lib/geom/buffer/heatmap/grid_3d.js | 177 +++ lib/geom/buffer/heatmap/heatmap.js | 169 +++ lib/geom/buffer/heatmap/hexagon.js | 44 + lib/geom/buffer/heatmap/hexagon_3d.js | 96 ++ lib/geom/buffer/image.js | 104 ++ lib/geom/buffer/index.js | 54 + lib/geom/buffer/line.js | 182 +++ lib/geom/buffer/line/arcline.js | 110 ++ lib/geom/buffer/line/meshline.js | 142 +++ lib/geom/buffer/point.js | 243 ++++ lib/geom/buffer/point/circleBuffer.js | 66 ++ lib/geom/buffer/point/extrude_buffer.js | 174 +++ lib/geom/buffer/point/fillBuffer.js | 127 ++ lib/geom/buffer/point/fill_buffer.js | 74 ++ lib/geom/buffer/point/fill_buffer2.js | 168 +++ lib/geom/buffer/point/imageBuffer.js | 48 + lib/geom/buffer/point/image_buffer.js | 48 + lib/geom/buffer/point/index.js | 47 + lib/geom/buffer/point/normalBuffer.js | 39 + lib/geom/buffer/point/sdfCommonWords.js | 178 +++ lib/geom/buffer/point/strokeBuffer.js | 103 ++ lib/geom/buffer/point/text.js | 86 ++ lib/geom/buffer/point/text/font-manager.js | 326 ++++++ lib/geom/buffer/point/text/lru-cache.js | 110 ++ lib/geom/buffer/point/textBuffer.js | 172 +++ lib/geom/buffer/polygon-line.js | 91 ++ lib/geom/buffer/polygon.js | 112 ++ lib/geom/buffer/polygon/extrude_buffer.js | 121 ++ lib/geom/buffer/polygon/fill_buffer.js | 116 ++ lib/geom/buffer/polygon/line_buffer.js | 141 +++ lib/geom/buffer/raster.js | 201 ++++ lib/geom/buffer/text.js | 316 +++++ lib/geom/extrude.js | 229 ++++ lib/geom/geom.js | 68 ++ lib/geom/index.js | 20 + lib/geom/material/arcline.js | 71 ++ lib/geom/material/circleMaterial.js | 63 + lib/geom/material/grid.js | 98 ++ lib/geom/material/heatmapMateial.js | 155 +++ lib/geom/material/heatmapMaterial.js | 155 +++ lib/geom/material/hexagon.js | 98 ++ lib/geom/material/imageMaterial.js | 34 + lib/geom/material/index.js | 37 + lib/geom/material/lineMaterial.js | 111 ++ lib/geom/material/material.js | 97 ++ lib/geom/material/normal_point.js | 95 ++ lib/geom/material/pointLineMaterial.js | 90 ++ lib/geom/material/pointMaterial.js | 103 ++ lib/geom/material/polygonMaterial.js | 59 + lib/geom/material/rainPass.js | 145 +++ lib/geom/material/rasterMaterial.js | 51 + lib/geom/material/text.js | 189 +++ lib/geom/material/textMaterial.js | 60 + lib/geom/material/tile/maskMaterial.js | 74 ++ lib/geom/material/tile/polygon.js | 87 ++ lib/geom/normals.js | 135 +++ lib/geom/shader/index.js | 208 ++++ lib/geom/shape/index.js | 20 + lib/geom/shape/line.js | 158 +++ lib/geom/shape/path.js | 51 + lib/geom/shape/point.js | 63 + lib/geom/shape/polygon.js | 90 ++ lib/global.js | 52 + lib/index.js | 37 + lib/interaction/active.js | 65 ++ lib/interaction/base.js | 149 +++ lib/interaction/factory.js | 26 + lib/interaction/hash.js | 120 ++ lib/interaction/index.js | 39 + lib/interaction/select.js | 59 + lib/layer/factory.js | 25 + lib/layer/heatmap.js | 124 ++ lib/layer/heatmapLayer.js | 60 + lib/layer/heatmap_layer.js | 62 + lib/layer/imageLayer.js | 91 ++ lib/layer/image_layer.js | 91 ++ lib/layer/index.js | 55 + lib/layer/lineLayer.js | 70 ++ lib/layer/line_layer.js | 71 ++ lib/layer/pointLayer.js | 143 +++ lib/layer/point_layer.js | 150 +++ lib/layer/polygonLayer.js | 72 ++ lib/layer/polygon_layer.js | 81 ++ lib/layer/rasterLayer.js | 111 ++ lib/layer/raster_layer.js | 111 ++ lib/layer/render/factory.js | 26 + lib/layer/render/heatmap/gird.js | 63 + lib/layer/render/heatmap/heatmap.js | 97 ++ lib/layer/render/heatmap/hexagon.js | 69 ++ lib/layer/render/image/drawImage.js | 26 + lib/layer/render/index.js | 72 ++ lib/layer/render/line/drawArc.js | 48 + lib/layer/render/line/drawDashLine.js | 1 + lib/layer/render/line/drawLine.js | 43 + lib/layer/render/line/drawMeshLine.js | 89 ++ lib/layer/render/point/drawCircle.js | 63 + lib/layer/render/point/drawFill.js | 60 + lib/layer/render/point/drawImage.js | 45 + lib/layer/render/point/drawNormal.js | 37 + lib/layer/render/point/drawStroke.js | 49 + lib/layer/render/point/drawText.js | 51 + lib/layer/render/point/draw_3d_shape.js | 56 + lib/layer/render/point/index.js | 39 + lib/layer/render/polygon/drawAnimate.js | 86 ++ lib/layer/render/polygon/drawFill.js | 71 ++ lib/layer/render/polygon/drawLine.js | 58 + lib/layer/render/polygon/index.js | 34 + lib/layer/tile/VectorTileLayer.js | 53 + lib/layer/tile/imageTile.js | 167 +++ lib/layer/tile/imageTileLayer.js | 57 + lib/layer/tile/image_tile.js | 167 +++ lib/layer/tile/image_tile_layer.js | 57 + lib/layer/tile/tile-cache.js | 58 + lib/layer/tile/tile.js | 244 ++++ lib/layer/tile/tileCache.js | 61 + lib/layer/tile/tileLayer.js | 701 +++++++++++ lib/layer/tile/tile_cache.js | 61 + lib/layer/tile/tile_layer.js | 706 +++++++++++ lib/layer/tile/vectorTile.js | 228 ++++ lib/layer/tile/vector_tile.js | 182 +++ lib/layer/tile/vector_tile_layer.js | 53 + lib/layer/tile/vector_tile_mesh.js | 202 ++++ lib/map/AMap.js | 296 +++++ lib/map/baseMap.js | 1 + lib/map/gaodeMap.js | 129 ++ lib/map/index.js | 47 + lib/map/mapbox.js | 224 ++++ lib/map/provider.js | 160 +++ lib/scale/auto/cat.js | 94 ++ lib/scale/auto/number.js | 151 +++ lib/scale/auto/time.js | 187 +++ lib/scale/auto/util.js | 212 ++++ lib/scale/base.js | 244 ++++ lib/scale/category.js | 199 ++++ lib/scale/identity.js | 109 ++ lib/scale/index.js | 61 + lib/scale/linear.js | 263 +++++ lib/scale/log.js | 237 ++++ lib/scale/pow.js | 172 +++ lib/scale/time-cat.js | 238 ++++ lib/scale/time-util.js | 33 + lib/scale/time.js | 199 ++++ lib/source/csvSource.js | 144 +++ lib/source/factory.js | 32 + lib/source/geojsonSource.js | 108 ++ lib/source/imageSource.js | 97 ++ lib/source/index.js | 66 ++ lib/source/parser/csv.js | 47 + lib/source/parser/geojson.js | 61 + lib/source/parser/image.js | 56 + lib/source/parser/json.js | 66 ++ lib/source/parser/mvt.js | 39 + lib/source/parser/raster.js | 26 + lib/source/parser/vector.js | 104 ++ lib/source/rainSource.js | 88 ++ lib/source/rasterSource.js | 66 ++ lib/source/source_cache.js | 450 +++++++ lib/source/tileDataCache.js | 55 + lib/source/tileSource.js | 179 +++ lib/source/tile_data_cache.js | 55 + lib/source/tile_source.js | 187 +++ lib/source/transform/cluster.js | 85 ++ lib/source/transform/grid.js | 135 +++ lib/source/transform/hexagon.js | 68 ++ lib/source/transform/map.js | 16 + lib/source/transform/statistics.js | 82 ++ lib/source/vector_tile_source.js | 118 ++ lib/source/vector_tile_worker_source.js | 165 +++ lib/theme/dark.js | 11 + lib/theme/index.js | 23 + lib/theme/light.js | 11 + lib/track.js | 26 + lib/util.js | 34 + lib/util/ajax.js | 197 ++++ lib/util/bkdr-hash.js | 42 + lib/util/common.js | 134 +++ lib/util/diff.js | 64 + lib/util/dom.js | 194 +++ lib/util/font-util.js | 129 ++ lib/util/format.js | 233 ++++ lib/util/geo.js | 50 + lib/util/index.js | 38 + lib/util/loadCSS.js | 29 + lib/util/loadScript.js | 26 + lib/util/lru-cache.js | 121 ++ lib/util/matrix.js | 128 ++ lib/util/object3d-util.js | 83 ++ lib/util/path.js | 1036 +++++++++++++++++ lib/util/polyline-normals copy.js | 153 +++ lib/util/polyline-normals.js | 159 +++ lib/util/shaderModule.js | 275 +++++ lib/util/throttle.js | 31 + lib/util/version.js | 14 + lib/util/vertex-compress.js | 22 + lib/worker/actor.js | 120 ++ lib/worker/geojsonSourceWorker.js | 1 + lib/worker/main.worker.js | 24 + lib/worker/web_worker.js | 14 + lib/worker/worker.js | 117 ++ lib/worker/workerTile.js | 152 +++ lib/worker/worker_controller.js | 96 ++ lib/worker/worker_pool.js | 65 ++ lib/worker/worker_transform.js | 87 ++ rollup.config.js | 11 +- src/component/control/layer.js | 2 +- src/core/scene.js | 6 +- src/worker/workerTile.js | 1 - 274 files changed, 31223 insertions(+), 7 deletions(-) create mode 100644 lib/attr/base.js create mode 100644 lib/attr/color-util.js create mode 100644 lib/attr/color.js create mode 100644 lib/attr/colorscales.js create mode 100644 lib/attr/filter.js create mode 100644 lib/attr/index.js create mode 100644 lib/attr/opacity.js create mode 100644 lib/attr/pattern.js create mode 100644 lib/attr/position.js create mode 100644 lib/attr/shape.js create mode 100644 lib/attr/size.js create mode 100644 lib/attr/symbol.js create mode 100644 lib/component/control/legend/color.js create mode 100644 lib/component/control/legend/shape.js create mode 100644 lib/component/control/legend/size.js create mode 100644 lib/component/index.js create mode 100644 lib/component/tooltip/index.js create mode 100644 lib/core/atlas/font-manager.js create mode 100644 lib/core/atlas/icon-manager.js create mode 100644 lib/core/base.js create mode 100644 lib/core/controller/buffer.js create mode 100644 lib/core/controller/event.js create mode 100644 lib/core/controller/geom.js create mode 100644 lib/core/controller/index.js create mode 100644 lib/core/controller/interaction.js create mode 100644 lib/core/controller/layer.js create mode 100644 lib/core/controller/map.js create mode 100644 lib/core/controller/mapping.js create mode 100644 lib/core/controller/pick.js create mode 100644 lib/core/controller/scale.js create mode 100644 lib/core/controller/tile_mapping.js create mode 100644 lib/core/engine/camera.js create mode 100755 lib/core/engine/composer.js create mode 100755 lib/core/engine/copy-shader.js create mode 100755 lib/core/engine/effect-composer.js create mode 100644 lib/core/engine/index.js create mode 100755 lib/core/engine/mask-pass.js create mode 100755 lib/core/engine/picking/picking.js create mode 100755 lib/core/engine/picking/pickingMaterial.js create mode 100755 lib/core/engine/picking/pickingScene.js create mode 100644 lib/core/engine/render-pass.js create mode 100644 lib/core/engine/renderer.js create mode 100644 lib/core/engine/renderpass.js create mode 100644 lib/core/engine/scene.js create mode 100644 lib/core/engine/shader-pass.js create mode 100644 lib/core/engine/shaderPass.js create mode 100644 lib/core/extend/windframebuffer/drawMaterial.js create mode 100644 lib/core/extend/windframebuffer/draw_geometry.js create mode 100644 lib/core/image.js create mode 100644 lib/core/layer.js create mode 100644 lib/core/scene.js create mode 100644 lib/core/source.js create mode 100644 lib/core/style.js create mode 100644 lib/core/three.js create mode 100644 lib/core/worker.js create mode 100644 lib/geo/bound.js create mode 100644 lib/geo/buffer.js create mode 100644 lib/geo/featureIndex.js create mode 100644 lib/geo/lngLat.js create mode 100644 lib/geo/point.js create mode 100644 lib/geo/project.js create mode 100644 lib/geom/base.js create mode 100644 lib/geom/buffer/buffer.js create mode 100644 lib/geom/buffer/bufferBase.js create mode 100644 lib/geom/buffer/factory.js create mode 100644 lib/geom/buffer/heatmap/grid.js create mode 100644 lib/geom/buffer/heatmap/grid_3d.js create mode 100644 lib/geom/buffer/heatmap/heatmap.js create mode 100644 lib/geom/buffer/heatmap/hexagon.js create mode 100644 lib/geom/buffer/heatmap/hexagon_3d.js create mode 100644 lib/geom/buffer/image.js create mode 100644 lib/geom/buffer/index.js create mode 100644 lib/geom/buffer/line.js create mode 100644 lib/geom/buffer/line/arcline.js create mode 100644 lib/geom/buffer/line/meshline.js create mode 100644 lib/geom/buffer/point.js create mode 100644 lib/geom/buffer/point/circleBuffer.js create mode 100644 lib/geom/buffer/point/extrude_buffer.js create mode 100644 lib/geom/buffer/point/fillBuffer.js create mode 100644 lib/geom/buffer/point/fill_buffer.js create mode 100644 lib/geom/buffer/point/fill_buffer2.js create mode 100644 lib/geom/buffer/point/imageBuffer.js create mode 100644 lib/geom/buffer/point/image_buffer.js create mode 100644 lib/geom/buffer/point/index.js create mode 100644 lib/geom/buffer/point/normalBuffer.js create mode 100644 lib/geom/buffer/point/sdfCommonWords.js create mode 100644 lib/geom/buffer/point/strokeBuffer.js create mode 100644 lib/geom/buffer/point/text.js create mode 100644 lib/geom/buffer/point/text/font-manager.js create mode 100644 lib/geom/buffer/point/text/lru-cache.js create mode 100644 lib/geom/buffer/point/textBuffer.js create mode 100644 lib/geom/buffer/polygon-line.js create mode 100644 lib/geom/buffer/polygon.js create mode 100644 lib/geom/buffer/polygon/extrude_buffer.js create mode 100644 lib/geom/buffer/polygon/fill_buffer.js create mode 100644 lib/geom/buffer/polygon/line_buffer.js create mode 100644 lib/geom/buffer/raster.js create mode 100644 lib/geom/buffer/text.js create mode 100644 lib/geom/extrude.js create mode 100644 lib/geom/geom.js create mode 100644 lib/geom/index.js create mode 100644 lib/geom/material/arcline.js create mode 100644 lib/geom/material/circleMaterial.js create mode 100644 lib/geom/material/grid.js create mode 100644 lib/geom/material/heatmapMateial.js create mode 100644 lib/geom/material/heatmapMaterial.js create mode 100644 lib/geom/material/hexagon.js create mode 100644 lib/geom/material/imageMaterial.js create mode 100644 lib/geom/material/index.js create mode 100644 lib/geom/material/lineMaterial.js create mode 100644 lib/geom/material/material.js create mode 100644 lib/geom/material/normal_point.js create mode 100644 lib/geom/material/pointLineMaterial.js create mode 100644 lib/geom/material/pointMaterial.js create mode 100644 lib/geom/material/polygonMaterial.js create mode 100644 lib/geom/material/rainPass.js create mode 100644 lib/geom/material/rasterMaterial.js create mode 100644 lib/geom/material/text.js create mode 100644 lib/geom/material/textMaterial.js create mode 100644 lib/geom/material/tile/maskMaterial.js create mode 100644 lib/geom/material/tile/polygon.js create mode 100644 lib/geom/normals.js create mode 100644 lib/geom/shader/index.js create mode 100644 lib/geom/shape/index.js create mode 100644 lib/geom/shape/line.js create mode 100644 lib/geom/shape/path.js create mode 100644 lib/geom/shape/point.js create mode 100644 lib/geom/shape/polygon.js create mode 100644 lib/global.js create mode 100755 lib/index.js create mode 100644 lib/interaction/active.js create mode 100644 lib/interaction/base.js create mode 100644 lib/interaction/factory.js create mode 100644 lib/interaction/hash.js create mode 100644 lib/interaction/index.js create mode 100644 lib/interaction/select.js create mode 100644 lib/layer/factory.js create mode 100644 lib/layer/heatmap.js create mode 100644 lib/layer/heatmapLayer.js create mode 100644 lib/layer/heatmap_layer.js create mode 100644 lib/layer/imageLayer.js create mode 100644 lib/layer/image_layer.js create mode 100644 lib/layer/index.js create mode 100644 lib/layer/lineLayer.js create mode 100644 lib/layer/line_layer.js create mode 100644 lib/layer/pointLayer.js create mode 100644 lib/layer/point_layer.js create mode 100644 lib/layer/polygonLayer.js create mode 100644 lib/layer/polygon_layer.js create mode 100644 lib/layer/rasterLayer.js create mode 100644 lib/layer/raster_layer.js create mode 100644 lib/layer/render/factory.js create mode 100644 lib/layer/render/heatmap/gird.js create mode 100644 lib/layer/render/heatmap/heatmap.js create mode 100644 lib/layer/render/heatmap/hexagon.js create mode 100644 lib/layer/render/image/drawImage.js create mode 100644 lib/layer/render/index.js create mode 100644 lib/layer/render/line/drawArc.js create mode 100644 lib/layer/render/line/drawDashLine.js create mode 100644 lib/layer/render/line/drawLine.js create mode 100644 lib/layer/render/line/drawMeshLine.js create mode 100644 lib/layer/render/point/drawCircle.js create mode 100644 lib/layer/render/point/drawFill.js create mode 100644 lib/layer/render/point/drawImage.js create mode 100644 lib/layer/render/point/drawNormal.js create mode 100644 lib/layer/render/point/drawStroke.js create mode 100644 lib/layer/render/point/drawText.js create mode 100644 lib/layer/render/point/draw_3d_shape.js create mode 100644 lib/layer/render/point/index.js create mode 100644 lib/layer/render/polygon/drawAnimate.js create mode 100644 lib/layer/render/polygon/drawFill.js create mode 100644 lib/layer/render/polygon/drawLine.js create mode 100644 lib/layer/render/polygon/index.js create mode 100644 lib/layer/tile/VectorTileLayer.js create mode 100644 lib/layer/tile/imageTile.js create mode 100644 lib/layer/tile/imageTileLayer.js create mode 100644 lib/layer/tile/image_tile.js create mode 100644 lib/layer/tile/image_tile_layer.js create mode 100644 lib/layer/tile/tile-cache.js create mode 100644 lib/layer/tile/tile.js create mode 100644 lib/layer/tile/tileCache.js create mode 100644 lib/layer/tile/tileLayer.js create mode 100644 lib/layer/tile/tile_cache.js create mode 100644 lib/layer/tile/tile_layer.js create mode 100644 lib/layer/tile/vectorTile.js create mode 100644 lib/layer/tile/vector_tile.js create mode 100644 lib/layer/tile/vector_tile_layer.js create mode 100644 lib/layer/tile/vector_tile_mesh.js create mode 100644 lib/map/AMap.js create mode 100644 lib/map/baseMap.js create mode 100644 lib/map/gaodeMap.js create mode 100644 lib/map/index.js create mode 100644 lib/map/mapbox.js create mode 100644 lib/map/provider.js create mode 100644 lib/scale/auto/cat.js create mode 100644 lib/scale/auto/number.js create mode 100644 lib/scale/auto/time.js create mode 100644 lib/scale/auto/util.js create mode 100644 lib/scale/base.js create mode 100644 lib/scale/category.js create mode 100644 lib/scale/identity.js create mode 100644 lib/scale/index.js create mode 100644 lib/scale/linear.js create mode 100644 lib/scale/log.js create mode 100644 lib/scale/pow.js create mode 100644 lib/scale/time-cat.js create mode 100644 lib/scale/time-util.js create mode 100644 lib/scale/time.js create mode 100644 lib/source/csvSource.js create mode 100644 lib/source/factory.js create mode 100644 lib/source/geojsonSource.js create mode 100644 lib/source/imageSource.js create mode 100644 lib/source/index.js create mode 100644 lib/source/parser/csv.js create mode 100644 lib/source/parser/geojson.js create mode 100644 lib/source/parser/image.js create mode 100644 lib/source/parser/json.js create mode 100644 lib/source/parser/mvt.js create mode 100644 lib/source/parser/raster.js create mode 100644 lib/source/parser/vector.js create mode 100644 lib/source/rainSource.js create mode 100644 lib/source/rasterSource.js create mode 100644 lib/source/source_cache.js create mode 100644 lib/source/tileDataCache.js create mode 100644 lib/source/tileSource.js create mode 100644 lib/source/tile_data_cache.js create mode 100644 lib/source/tile_source.js create mode 100644 lib/source/transform/cluster.js create mode 100644 lib/source/transform/grid.js create mode 100644 lib/source/transform/hexagon.js create mode 100644 lib/source/transform/map.js create mode 100644 lib/source/transform/statistics.js create mode 100644 lib/source/vector_tile_source.js create mode 100644 lib/source/vector_tile_worker_source.js create mode 100644 lib/theme/dark.js create mode 100644 lib/theme/index.js create mode 100644 lib/theme/light.js create mode 100644 lib/track.js create mode 100644 lib/util.js create mode 100644 lib/util/ajax.js create mode 100644 lib/util/bkdr-hash.js create mode 100644 lib/util/common.js create mode 100644 lib/util/diff.js create mode 100644 lib/util/dom.js create mode 100644 lib/util/font-util.js create mode 100644 lib/util/format.js create mode 100644 lib/util/geo.js create mode 100644 lib/util/index.js create mode 100644 lib/util/loadCSS.js create mode 100644 lib/util/loadScript.js create mode 100644 lib/util/lru-cache.js create mode 100644 lib/util/matrix.js create mode 100644 lib/util/object3d-util.js create mode 100644 lib/util/path.js create mode 100644 lib/util/polyline-normals copy.js create mode 100644 lib/util/polyline-normals.js create mode 100644 lib/util/shaderModule.js create mode 100644 lib/util/throttle.js create mode 100644 lib/util/version.js create mode 100644 lib/util/vertex-compress.js create mode 100644 lib/worker/actor.js create mode 100644 lib/worker/geojsonSourceWorker.js create mode 100644 lib/worker/main.worker.js create mode 100644 lib/worker/web_worker.js create mode 100644 lib/worker/worker.js create mode 100644 lib/worker/workerTile.js create mode 100644 lib/worker/worker_controller.js create mode 100644 lib/worker/worker_pool.js create mode 100644 lib/worker/worker_transform.js diff --git a/.gitignore b/.gitignore index 986a9bce36..59f663df1c 100755 --- a/.gitignore +++ b/.gitignore @@ -65,7 +65,6 @@ dist temp .DS_Store .idea -lib *.sw* *.un~ diff --git a/lib/attr/base.js b/lib/attr/base.js new file mode 100644 index 0000000000..33d73eeb10 --- /dev/null +++ b/lib/attr/base.js @@ -0,0 +1,257 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _colorUtil = _interopRequireDefault(require("./color-util")); + +var _util = _interopRequireDefault(require("../util")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function toScaleString(scale, value) { + if (_util["default"].isString(value)) { + return value; + } + + return scale.invert(scale.scale(value)); +} +/** + * 所有视觉通道属性的基类 + * @class Attr + */ + + +var AttributeBase = +/*#__PURE__*/ +function () { + function AttributeBase(cfg) { + _classCallCheck(this, AttributeBase); + + /** + * 属性的类型 + * @type {String} + */ + this.type = 'base'; + /** + * 属性的名称 + * @type {String} + */ + + this.name = null; + /** + * 回调函数 + * @type {Function} + */ + + this.method = null; + /** + * 备选的值数组 + * @type {Array} + */ + + this.values = []; + /** + * 属性内部的度量 + * @type {Array} + */ + + this.scales = []; + /** + * 是否通过线性取值, 如果未指定,则根据数值的类型判定 + * @type {Boolean} + */ + + this.linear = null; + + _util["default"].mix(this, cfg); + } + + _createClass(AttributeBase, [{ + key: "get", + value: function get(name) { + return this[name]; + } + }, { + key: "set", + value: function set(name, value) { + this[name] = value; + } // 获取属性值,将值映射到视觉通道 + + }, { + key: "_getAttrValue", + value: function _getAttrValue(scale, value) { + var values = this.values; + + if (scale.isCategory && !this.linear) { + var index = scale.translate(value); + return values[index % values.length]; + } + + var percent = scale.scale(value); + return this.getLinearValue(percent); + } + /** + * 如果进行线性映射,返回对应的映射值 + * @protected + * @param {Number} percent 百分比 + * @return {*} 颜色值、形状、大小等 + */ + + }, { + key: "getLinearValue", + value: function getLinearValue(percent) { + var values = this.values; + var steps = values.length - 1; + var step = Math.floor(steps * percent); + var leftPercent = steps * percent - step; + var start = values[step]; + var end = step === steps ? start : values[step + 1]; + var rstValue = start + (end - start) * leftPercent; + return rstValue; + } + /** + * 默认的回调函数 + * @param {*} value 回调函数的值 + * @type {Function} + * @return {Array} 返回映射后的值 + */ + + }, { + key: "callback", + value: function callback(value) { + var self = this; + var scale = self.scales[0]; + var rstValue = null; + + if (scale.type === 'identity') { + rstValue = scale.value; + } else { + rstValue = self._getAttrValue(scale, value); + } + + return rstValue; + } + /** + * 根据度量获取属性名 + * @return {Array} dims of this Attribute + */ + + }, { + key: "getNames", + value: function getNames() { + var scales = this.scales; + var names = this.names; + var length = Math.min(scales.length, names.length); + var rst = []; + + for (var i = 0; i < length; i++) { + rst.push(names[i]); + } + + return rst; + } + /** + * 根据度量获取维度名 + * @return {Array} dims of this Attribute + */ + + }, { + key: "getFields", + value: function getFields() { + var scales = this.scales; + var rst = []; + + _util["default"].each(scales, function (scale) { + rst.push(scale.field); + }); + + return rst; + } + /** + * 根据名称获取度量 + * @param {String} name the name of scale + * @return {Scale} scale + */ + + }, { + key: "getScale", + value: function getScale(name) { + var scales = this.scales; + var names = this.names; + var index = names.indexOf(name); + return scales[index]; + } + /** + * 映射数据 + * @param {*} param1...paramn 多个数值 + * @return {Array} 映射的值组成的数组 + */ + + }, { + key: "mapping", + value: function mapping() { + var scales = this.scales; + var callback = this.callback; + + for (var _len = arguments.length, params = new Array(_len), _key = 0; _key < _len; _key++) { + params[_key] = arguments[_key]; + } + + var values = params; + + if (callback) { + for (var i = 0; i < params.length; i++) { + params[i] = this._toOriginParam(params[i], scales[i]); + } + + values = callback.apply(this, params); + } + + if (this.type === 'color' && !_util["default"].isArray(values)) { + values = _colorUtil["default"].toRGB(values).map(function (e) { + return e / 255; + }); // values[3] = values[3] * 255; + } + + if (!_util["default"].isArray(values)) { + values = [values]; + } + + return values; + } // 原始的参数 + + }, { + key: "_toOriginParam", + value: function _toOriginParam(param, scale) { + var rst = param; + + if (!scale.isLinear) { + if (_util["default"].isArray(param)) { + rst = []; + + for (var i = 0; i < param.length; i++) { + rst.push(toScaleString(scale, param[i])); + } + } else { + rst = toScaleString(scale, param); + } + } + + return rst; + } + }]); + + return AttributeBase; +}(); + +var _default = AttributeBase; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/attr/color-util.js b/lib/attr/color-util.js new file mode 100644 index 0000000000..f8923889d0 --- /dev/null +++ b/lib/attr/color-util.js @@ -0,0 +1,282 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _util = _interopRequireDefault(require("../util")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +/** + * @fileOverview 颜色计算的辅助方法 + * @author dxq613@gmail.com + */ +var RGB_REG = /rgba?\(([\s.,0-9]+)\)/; +var ColorKeywords = { + aliceblue: '#F0F8FF', + antiquewhite: '#FAEBD7', + aqua: '#00FFFF', + aquamarine: '#7FFFD4', + azure: '#F0FFFF', + beige: '#F5F5DC', + bisque: '#FFE4C4', + black: '#000000', + blanchedalmond: '#FFEBCD', + blue: '#0000FF', + blueviolet: '#8A2BE2', + brown: '#A52A2A', + burlywood: '#DEB887', + cadetblue: '#5F9EA0', + chartreuse: '#7FFF00', + chocolate: '#D2691E', + coral: '#FF7F50', + cornflowerblue: '#6495ED', + cornsilk: '#FFF8DC', + crimson: '#DC143C', + cyan: '#00FFFF', + darkblue: '#00008B', + darkcyan: '#008B8B', + darkgoldenrod: '#B8860B', + darkgray: '#A9A9A9', + darkgreen: '#006400', + darkgrey: '#A9A9A9', + darkkhaki: '#BDB76B', + darkmagenta: '#8B008B', + darkolivegreen: '#556B2F', + darkorange: '#FF8C00', + darkorchid: '#9932CC', + darkred: '#8B0000', + darksalmon: '#E9967A', + darkseagreen: '#8FBC8F', + darkslateblue: '#483D8B', + darkslategray: '#2F4F4F', + darkslategrey: '#2F4F4F', + darkturquoise: '#00CED1', + darkviolet: '#9400D3', + deeppink: '#FF1493', + deepskyblue: '#00BFFF', + dimgray: '#696969', + dimgrey: '#696969', + dodgerblue: '#1E90FF', + firebrick: '#B22222', + floralwhite: '#FFFAF0', + forestgreen: '#228B22', + fuchsia: '#FF00FF', + gainsboro: '#DCDCDC', + ghostwhite: '#F8F8FF', + gold: '#FFD700', + goldenrod: '#DAA520', + gray: '#808080', + green: '#008000', + greenyellow: '#ADFF2F', + grey: '#808080', + honeydew: '#F0FFF0', + hotpink: '#FF69B4', + indianred: '#CD5C5C', + indigo: '#4B0082', + ivory: '#FFFFF0', + khaki: '#F0E68C', + lavender: '#E6E6FA', + lavenderblush: '#FFF0F5', + lawngreen: '#7CFC00', + lemonchiffon: '#FFFACD', + lightblue: '#ADD8E6', + lightcoral: '#F08080', + lightcyan: '#E0FFFF', + lightgoldenrodyellow: '#FAFAD2', + lightgray: '#D3D3D3', + lightgreen: '#90EE90', + lightgrey: '#D3D3D3', + lightpink: '#FFB6C1', + lightsalmon: '#FFA07A', + lightseagreen: '#20B2AA', + lightskyblue: '#87CEFA', + lightslategray: '#778899', + lightslategrey: '#778899', + lightsteelblue: '#B0C4DE', + lightyellow: '#FFFFE0', + lime: '#00FF00', + limegreen: '#32CD32', + linen: '#FAF0E6', + magenta: '#FF00FF', + maroon: '#800000', + mediumaquamarine: '#66CDAA', + mediumblue: '#0000CD', + mediumorchid: '#BA55D3', + mediumpurple: '#9370DB', + mediumseagreen: '#3CB371', + mediumslateblue: '#7B68EE', + mediumspringgreen: '#00FA9A', + mediumturquoise: '#48D1CC', + mediumvioletred: '#C71585', + midnightblue: '#191970', + mintcream: '#F5FFFA', + mistyrose: '#FFE4E1', + moccasin: '#FFE4B5', + navajowhite: '#FFDEAD', + navy: '#000080', + oldlace: '#FDF5E6', + olive: '#808000', + olivedrab: '#6B8E23', + orange: '#FFA500', + orangered: '#FF4500', + orchid: '#DA70D6', + palegoldenrod: '#EEE8AA', + palegreen: '#98FB98', + paleturquoise: '#AFEEEE', + palevioletred: '#DB7093', + papayawhip: '#FFEFD5', + peachpuff: '#FFDAB9', + peru: '#CD853F', + pink: '#FFC0CB', + plum: '#DDA0DD', + powderblue: '#B0E0E6', + purple: '#800080', + rebeccapurple: '#663399', + red: '#FF0000', + rosybrown: '#BC8F8F', + royalblue: '#4169E1', + saddlebrown: '#8B4513', + salmon: '#FA8072', + sandybrown: '#F4A460', + seagreen: '#2E8B57', + seashell: '#FFF5EE', + sienna: '#A0522D', + silver: '#C0C0C0', + skyblue: '#87CEEB', + slateblue: '#6A5ACD', + slategray: '#708090', + slategrey: '#708090', + snow: '#FFFAFA', + springgreen: '#00FF7F', + steelblue: '#4682B4', + tan: '#D2B48C', + teal: '#008080', + thistle: '#D8BFD8', + tomato: '#FF6347', + turquoise: '#40E0D0', + violet: '#EE82EE', + wheat: '#F5DEB3', + white: '#FFFFFF', + whitesmoke: '#F5F5F5', + yellow: '#FFFF00', + yellowgreen: '#9ACD32' +}; // 获取颜色之间的插值 + +function getValue(start, end, percent, index) { + var value = start[index] + (end[index] - start[index]) * percent; + return value; +} + +function calColor(colors, percent) { + if (_util["default"].isNaN(percent) || !_util["default"].isNumber(percent)) { + percent = 0; + } + + var steps = colors.length - 1; + var step = Math.floor(steps * percent); + var left = steps * percent - step; + var start = colors[step]; + var end = step === steps ? start : colors[step + 1]; + return [getValue(start, end, left, 0), getValue(start, end, left, 1), getValue(start, end, left, 2), getValue(start, end, left, 3)]; +} // rgb 颜色转换成数组 + + +function rgb2arr(str) { + var arr = []; + + if (str.length === 4) { + str = "#".concat(str[1]).concat(str[1]).concat(str[2]).concat(str[2]).concat(str[3]).concat(str[3]); + } + + arr.push(parseInt(str.substr(1, 2), 16)); + arr.push(parseInt(str.substr(3, 2), 16)); + arr.push(parseInt(str.substr(5, 2), 16)); + return arr; +} + +var colorCache = {}; +var ColorUtil = { + /** + * 将颜色转换到 rgb 的格式 + * @param {String} color 颜色 + * @return {String} 将颜色转换到 '#ffffff' 的格式 + */ + toRGB: function toRGB(color) { + // 如果已经是 rgb的格式 + var colorArray = [255, 255, 255, 255]; + + if (ColorKeywords[color]) { + // color name 2 hex + var hexColor = ColorKeywords[color]; + colorArray = rgb2arr(hexColor); + colorArray.push(255.0); + } + + if (color[0] === '#' && (color.length === 7 || color.length === 4)) { + // hex2array + colorArray = rgb2arr(color); + colorArray.push(255.0); + return colorArray; + } + + if (RGB_REG.test(color)) { + var matchs = RGB_REG.exec(color); + colorArray = matchs[1].split(/\s*,\s*/); + + if (colorArray.length === 4) { + colorArray[3] *= 255; + } + + if (colorArray.length === 3) { + colorArray.push(255.0); + } + } + + colorCache[color] = colorArray; + return colorArray; + }, + // 转成 WebGl color buffer + color2Arr: function color2Arr(str) { + var rgba = this.toRGB(str); + return rgba.map(function (v) { + return v / 255; + }); + }, + colorArray2RGBA: function colorArray2RGBA(arr) { + return "rgba(".concat(arr[0] * 255, ",").concat(arr[1] * 255, ",").concat(arr[2] * 255, ",").concat(arr[3], ")"); + }, + color2RGBA: function color2RGBA(str) { + return this.color2Arr(str); + }, + rgb2arr: rgb2arr, + + /** + * 获取渐变函数 + * @param {Array} colors 多个颜色 + * @return {String} 颜色值 + */ + gradient: function gradient(colors) { + var points = []; + + if (_util["default"].isString(colors)) { + colors = colors.split('-'); + } + + _util["default"].each(colors, function (color) { + var colorArray = ColorUtil.toRGB(color).map(function (e) { + return e / 255; + }); // colorArray[3] = colorArray[3] * 255; + + points.push(colorArray); + }); + + return function (percent) { + return calColor(points, percent); + }; + } +}; +var _default = ColorUtil; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/attr/color.js b/lib/attr/color.js new file mode 100644 index 0000000000..199ca1f879 --- /dev/null +++ b/lib/attr/color.js @@ -0,0 +1,84 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _colorUtil = _interopRequireDefault(require("./color-util")); + +var _base = _interopRequireDefault(require("./base")); + +var _util = _interopRequireDefault(require("../util")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +/** + * 视觉通道 color + * @class Attr.Color + */ +var Color = +/*#__PURE__*/ +function (_Base) { + _inherits(Color, _Base); + + function Color(cfg) { + var _this; + + _classCallCheck(this, Color); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(Color).call(this, cfg)); + _this.names = ['color']; + _this.type = 'color'; + _this.gradient = null; + + if (_util["default"].isString(_this.values)) { + _this.linear = true; + } + + return _this; + } + /** + * @override + */ + + + _createClass(Color, [{ + key: "getLinearValue", + value: function getLinearValue(percent) { + var gradient = this.gradient; + + if (!gradient) { + var values = this.values; + gradient = _colorUtil["default"].gradient(values); + this.gradient = gradient; + } + + var color = gradient(percent); + return color; + } + }]); + + return Color; +}(_base["default"]); + +var _default = Color; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/attr/colorscales.js b/lib/attr/colorscales.js new file mode 100644 index 0000000000..1a21c2106b --- /dev/null +++ b/lib/attr/colorscales.js @@ -0,0 +1,107 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.colorScales = void 0; +// code from https://github.com/santilland/plotty/blob/master/src/colorscales.js +var colorScales = { + viridis: new Uint8Array([68, 1, 84, 255, 68, 2, 86, 255, 69, 4, 87, 255, 69, 5, 89, 255, 70, 7, 90, 255, 70, 8, 92, 255, 70, 10, 93, 255, 70, 11, 94, 255, 71, 13, 96, 255, 71, 14, 97, 255, 71, 16, 99, 255, 71, 17, 100, 255, 71, 19, 101, 255, 72, 20, 103, 255, 72, 22, 104, 255, 72, 23, 105, 255, 72, 24, 106, 255, 72, 26, 108, 255, 72, 27, 109, 255, 72, 28, 110, 255, 72, 29, 111, 255, 72, 31, 112, 255, 72, 32, 113, 255, 72, 33, 115, 255, 72, 35, 116, 255, 72, 36, 117, 255, 72, 37, 118, 255, 72, 38, 119, 255, 72, 40, 120, 255, 72, 41, 121, 255, 71, 42, 122, 255, 71, 44, 122, 255, 71, 45, 123, 255, 71, 46, 124, 255, 71, 47, 125, 255, 70, 48, 126, 255, 70, 50, 126, 255, 70, 51, 127, 255, 70, 52, 128, 255, 69, 53, 129, 255, 69, 55, 129, 255, 69, 56, 130, 255, 68, 57, 131, 255, 68, 58, 131, 255, 68, 59, 132, 255, 67, 61, 132, 255, 67, 62, 133, 255, 66, 63, 133, 255, 66, 64, 134, 255, 66, 65, 134, 255, 65, 66, 135, 255, 65, 68, 135, 255, 64, 69, 136, 255, 64, 70, 136, 255, 63, 71, 136, 255, 63, 72, 137, 255, 62, 73, 137, 255, 62, 74, 137, 255, 62, 76, 138, 255, 61, 77, 138, 255, 61, 78, 138, 255, 60, 79, 138, 255, 60, 80, 139, 255, 59, 81, 139, 255, 59, 82, 139, 255, 58, 83, 139, 255, 58, 84, 140, 255, 57, 85, 140, 255, 57, 86, 140, 255, 56, 88, 140, 255, 56, 89, 140, 255, 55, 90, 140, 255, 55, 91, 141, 255, 54, 92, 141, 255, 54, 93, 141, 255, 53, 94, 141, 255, 53, 95, 141, 255, 52, 96, 141, 255, 52, 97, 141, 255, 51, 98, 141, 255, 51, 99, 141, 255, 50, 100, 142, 255, 50, 101, 142, 255, 49, 102, 142, 255, 49, 103, 142, 255, 49, 104, 142, 255, 48, 105, 142, 255, 48, 106, 142, 255, 47, 107, 142, 255, 47, 108, 142, 255, 46, 109, 142, 255, 46, 110, 142, 255, 46, 111, 142, 255, 45, 112, 142, 255, 45, 113, 142, 255, 44, 113, 142, 255, 44, 114, 142, 255, 44, 115, 142, 255, 43, 116, 142, 255, 43, 117, 142, 255, 42, 118, 142, 255, 42, 119, 142, 255, 42, 120, 142, 255, 41, 121, 142, 255, 41, 122, 142, 255, 41, 123, 142, 255, 40, 124, 142, 255, 40, 125, 142, 255, 39, 126, 142, 255, 39, 127, 142, 255, 39, 128, 142, 255, 38, 129, 142, 255, 38, 130, 142, 255, 38, 130, 142, 255, 37, 131, 142, 255, 37, 132, 142, 255, 37, 133, 142, 255, 36, 134, 142, 255, 36, 135, 142, 255, 35, 136, 142, 255, 35, 137, 142, 255, 35, 138, 141, 255, 34, 139, 141, 255, 34, 140, 141, 255, 34, 141, 141, 255, 33, 142, 141, 255, 33, 143, 141, 255, 33, 144, 141, 255, 33, 145, 140, 255, 32, 146, 140, 255, 32, 146, 140, 255, 32, 147, 140, 255, 31, 148, 140, 255, 31, 149, 139, 255, 31, 150, 139, 255, 31, 151, 139, 255, 31, 152, 139, 255, 31, 153, 138, 255, 31, 154, 138, 255, 30, 155, 138, 255, 30, 156, 137, 255, 30, 157, 137, 255, 31, 158, 137, 255, 31, 159, 136, 255, 31, 160, 136, 255, 31, 161, 136, 255, 31, 161, 135, 255, 31, 162, 135, 255, 32, 163, 134, 255, 32, 164, 134, 255, 33, 165, 133, 255, 33, 166, 133, 255, 34, 167, 133, 255, 34, 168, 132, 255, 35, 169, 131, 255, 36, 170, 131, 255, 37, 171, 130, 255, 37, 172, 130, 255, 38, 173, 129, 255, 39, 173, 129, 255, 40, 174, 128, 255, 41, 175, 127, 255, 42, 176, 127, 255, 44, 177, 126, 255, 45, 178, 125, 255, 46, 179, 124, 255, 47, 180, 124, 255, 49, 181, 123, 255, 50, 182, 122, 255, 52, 182, 121, 255, 53, 183, 121, 255, 55, 184, 120, 255, 56, 185, 119, 255, 58, 186, 118, 255, 59, 187, 117, 255, 61, 188, 116, 255, 63, 188, 115, 255, 64, 189, 114, 255, 66, 190, 113, 255, 68, 191, 112, 255, 70, 192, 111, 255, 72, 193, 110, 255, 74, 193, 109, 255, 76, 194, 108, 255, 78, 195, 107, 255, 80, 196, 106, 255, 82, 197, 105, 255, 84, 197, 104, 255, 86, 198, 103, 255, 88, 199, 101, 255, 90, 200, 100, 255, 92, 200, 99, 255, 94, 201, 98, 255, 96, 202, 96, 255, 99, 203, 95, 255, 101, 203, 94, 255, 103, 204, 92, 255, 105, 205, 91, 255, 108, 205, 90, 255, 110, 206, 88, 255, 112, 207, 87, 255, 115, 208, 86, 255, 117, 208, 84, 255, 119, 209, 83, 255, 122, 209, 81, 255, 124, 210, 80, 255, 127, 211, 78, 255, 129, 211, 77, 255, 132, 212, 75, 255, 134, 213, 73, 255, 137, 213, 72, 255, 139, 214, 70, 255, 142, 214, 69, 255, 144, 215, 67, 255, 147, 215, 65, 255, 149, 216, 64, 255, 152, 216, 62, 255, 155, 217, 60, 255, 157, 217, 59, 255, 160, 218, 57, 255, 162, 218, 55, 255, 165, 219, 54, 255, 168, 219, 52, 255, 170, 220, 50, 255, 173, 220, 48, 255, 176, 221, 47, 255, 178, 221, 45, 255, 181, 222, 43, 255, 184, 222, 41, 255, 186, 222, 40, 255, 189, 223, 38, 255, 192, 223, 37, 255, 194, 223, 35, 255, 197, 224, 33, 255, 200, 224, 32, 255, 202, 225, 31, 255, 205, 225, 29, 255, 208, 225, 28, 255, 210, 226, 27, 255, 213, 226, 26, 255, 216, 226, 25, 255, 218, 227, 25, 255, 221, 227, 24, 255, 223, 227, 24, 255, 226, 228, 24, 255, 229, 228, 25, 255, 231, 228, 25, 255, 234, 229, 26, 255, 236, 229, 27, 255, 239, 229, 28, 255, 241, 229, 29, 255, 244, 230, 30, 255, 246, 230, 32, 255, 248, 230, 33, 255, 251, 231, 35, 255, 253, 231, 37, 255]), + inferno: new Uint8Array([0, 0, 4, 255, 1, 0, 5, 255, 1, 1, 6, 255, 1, 1, 8, 255, 2, 1, 10, 255, 2, 2, 12, 255, 2, 2, 14, 255, 3, 2, 16, 255, 4, 3, 18, 255, 4, 3, 20, 255, 5, 4, 23, 255, 6, 4, 25, 255, 7, 5, 27, 255, 8, 5, 29, 255, 9, 6, 31, 255, 10, 7, 34, 255, 11, 7, 36, 255, 12, 8, 38, 255, 13, 8, 41, 255, 14, 9, 43, 255, 16, 9, 45, 255, 17, 10, 48, 255, 18, 10, 50, 255, 20, 11, 52, 255, 21, 11, 55, 255, 22, 11, 57, 255, 24, 12, 60, 255, 25, 12, 62, 255, 27, 12, 65, 255, 28, 12, 67, 255, 30, 12, 69, 255, 31, 12, 72, 255, 33, 12, 74, 255, 35, 12, 76, 255, 36, 12, 79, 255, 38, 12, 81, 255, 40, 11, 83, 255, 41, 11, 85, 255, 43, 11, 87, 255, 45, 11, 89, 255, 47, 10, 91, 255, 49, 10, 92, 255, 50, 10, 94, 255, 52, 10, 95, 255, 54, 9, 97, 255, 56, 9, 98, 255, 57, 9, 99, 255, 59, 9, 100, 255, 61, 9, 101, 255, 62, 9, 102, 255, 64, 10, 103, 255, 66, 10, 104, 255, 68, 10, 104, 255, 69, 10, 105, 255, 71, 11, 106, 255, 73, 11, 106, 255, 74, 12, 107, 255, 76, 12, 107, 255, 77, 13, 108, 255, 79, 13, 108, 255, 81, 14, 108, 255, 82, 14, 109, 255, 84, 15, 109, 255, 85, 15, 109, 255, 87, 16, 110, 255, 89, 16, 110, 255, 90, 17, 110, 255, 92, 18, 110, 255, 93, 18, 110, 255, 95, 19, 110, 255, 97, 19, 110, 255, 98, 20, 110, 255, 100, 21, 110, 255, 101, 21, 110, 255, 103, 22, 110, 255, 105, 22, 110, 255, 106, 23, 110, 255, 108, 24, 110, 255, 109, 24, 110, 255, 111, 25, 110, 255, 113, 25, 110, 255, 114, 26, 110, 255, 116, 26, 110, 255, 117, 27, 110, 255, 119, 28, 109, 255, 120, 28, 109, 255, 122, 29, 109, 255, 124, 29, 109, 255, 125, 30, 109, 255, 127, 30, 108, 255, 128, 31, 108, 255, 130, 32, 108, 255, 132, 32, 107, 255, 133, 33, 107, 255, 135, 33, 107, 255, 136, 34, 106, 255, 138, 34, 106, 255, 140, 35, 105, 255, 141, 35, 105, 255, 143, 36, 105, 255, 144, 37, 104, 255, 146, 37, 104, 255, 147, 38, 103, 255, 149, 38, 103, 255, 151, 39, 102, 255, 152, 39, 102, 255, 154, 40, 101, 255, 155, 41, 100, 255, 157, 41, 100, 255, 159, 42, 99, 255, 160, 42, 99, 255, 162, 43, 98, 255, 163, 44, 97, 255, 165, 44, 96, 255, 166, 45, 96, 255, 168, 46, 95, 255, 169, 46, 94, 255, 171, 47, 94, 255, 173, 48, 93, 255, 174, 48, 92, 255, 176, 49, 91, 255, 177, 50, 90, 255, 179, 50, 90, 255, 180, 51, 89, 255, 182, 52, 88, 255, 183, 53, 87, 255, 185, 53, 86, 255, 186, 54, 85, 255, 188, 55, 84, 255, 189, 56, 83, 255, 191, 57, 82, 255, 192, 58, 81, 255, 193, 58, 80, 255, 195, 59, 79, 255, 196, 60, 78, 255, 198, 61, 77, 255, 199, 62, 76, 255, 200, 63, 75, 255, 202, 64, 74, 255, 203, 65, 73, 255, 204, 66, 72, 255, 206, 67, 71, 255, 207, 68, 70, 255, 208, 69, 69, 255, 210, 70, 68, 255, 211, 71, 67, 255, 212, 72, 66, 255, 213, 74, 65, 255, 215, 75, 63, 255, 216, 76, 62, 255, 217, 77, 61, 255, 218, 78, 60, 255, 219, 80, 59, 255, 221, 81, 58, 255, 222, 82, 56, 255, 223, 83, 55, 255, 224, 85, 54, 255, 225, 86, 53, 255, 226, 87, 52, 255, 227, 89, 51, 255, 228, 90, 49, 255, 229, 92, 48, 255, 230, 93, 47, 255, 231, 94, 46, 255, 232, 96, 45, 255, 233, 97, 43, 255, 234, 99, 42, 255, 235, 100, 41, 255, 235, 102, 40, 255, 236, 103, 38, 255, 237, 105, 37, 255, 238, 106, 36, 255, 239, 108, 35, 255, 239, 110, 33, 255, 240, 111, 32, 255, 241, 113, 31, 255, 241, 115, 29, 255, 242, 116, 28, 255, 243, 118, 27, 255, 243, 120, 25, 255, 244, 121, 24, 255, 245, 123, 23, 255, 245, 125, 21, 255, 246, 126, 20, 255, 246, 128, 19, 255, 247, 130, 18, 255, 247, 132, 16, 255, 248, 133, 15, 255, 248, 135, 14, 255, 248, 137, 12, 255, 249, 139, 11, 255, 249, 140, 10, 255, 249, 142, 9, 255, 250, 144, 8, 255, 250, 146, 7, 255, 250, 148, 7, 255, 251, 150, 6, 255, 251, 151, 6, 255, 251, 153, 6, 255, 251, 155, 6, 255, 251, 157, 7, 255, 252, 159, 7, 255, 252, 161, 8, 255, 252, 163, 9, 255, 252, 165, 10, 255, 252, 166, 12, 255, 252, 168, 13, 255, 252, 170, 15, 255, 252, 172, 17, 255, 252, 174, 18, 255, 252, 176, 20, 255, 252, 178, 22, 255, 252, 180, 24, 255, 251, 182, 26, 255, 251, 184, 29, 255, 251, 186, 31, 255, 251, 188, 33, 255, 251, 190, 35, 255, 250, 192, 38, 255, 250, 194, 40, 255, 250, 196, 42, 255, 250, 198, 45, 255, 249, 199, 47, 255, 249, 201, 50, 255, 249, 203, 53, 255, 248, 205, 55, 255, 248, 207, 58, 255, 247, 209, 61, 255, 247, 211, 64, 255, 246, 213, 67, 255, 246, 215, 70, 255, 245, 217, 73, 255, 245, 219, 76, 255, 244, 221, 79, 255, 244, 223, 83, 255, 244, 225, 86, 255, 243, 227, 90, 255, 243, 229, 93, 255, 242, 230, 97, 255, 242, 232, 101, 255, 242, 234, 105, 255, 241, 236, 109, 255, 241, 237, 113, 255, 241, 239, 117, 255, 241, 241, 121, 255, 242, 242, 125, 255, 242, 244, 130, 255, 243, 245, 134, 255, 243, 246, 138, 255, 244, 248, 142, 255, 245, 249, 146, 255, 246, 250, 150, 255, 248, 251, 154, 255, 249, 252, 157, 255, 250, 253, 161, 255, 252, 255, 164, 255]), + rainbow: { + colors: ['#96005A', '#0000C8', '#0019FF', '#0098FF', '#2CFF96', '#97FF00', '#FFEA00', '#FF6F00', '#FF0000'], + positions: [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1] + }, + jet: { + colors: ['#000083', '#003CAA', '#05FFFF', '#FFFF00', '#FA0000', '#800000'], + positions: [0, 0.125, 0.375, 0.625, 0.875, 1] + }, + hsv: { + colors: ['#ff0000', '#fdff02', '#f7ff02', '#00fc04', '#00fc0a', '#01f9ff', '#0200fd', '#0800fd', '#ff00fb', '#ff00f5', '#ff0006'], + positions: [0, 0.169, 0.173, 0.337, 0.341, 0.506, 0.671, 0.675, 0.839, 0.843, 1] + }, + hot: { + colors: ['#000000', '#e60000', '#ffd200', '#ffffff'], + positions: [0, 0.3, 0.6, 1] + }, + cool: { + colors: ['#00ffff', '#ff00ff'], + positions: [0, 1] + }, + spring: { + colors: ['#ff00ff', '#ffff00'], + positions: [0, 1] + }, + summer: { + colors: ['#008066', '#ffff66'], + positions: [0, 1] + }, + autumn: { + colors: ['#ff0000', '#ffff00'], + positions: [0, 1] + }, + winter: { + colors: ['#0000ff', '#00ff80'], + positions: [0, 1] + }, + bone: { + colors: ['#000000', '#545474', '#a9c8c8', '#ffffff'], + positions: [0, 0.376, 0.753, 1] + }, + copper: { + colors: ['#000000', '#ffa066', '#ffc77f'], + positions: [0, 0.804, 1] + }, + greys: { + colors: ['#000000', '#ffffff'], + positions: [0, 1] + }, + yignbu: { + colors: ['#081d58', '#253494', '#225ea8', '#1d91c0', '#41b6c4', '#7fcdbb', '#c7e9b4', '#edf8d9', '#ffffd9'], + positions: [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1] + }, + greens: { + colors: ['#00441b', '#006d2c', '#238b45', '#41ab5d', '#74c476', '#a1d99b', '#c7e9c0', '#e5f5e0', '#f7fcf5'], + positions: [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1] + }, + wind: { + colors: ['#3288bd', '#66c2a5', '#abdda4', '#e6f598', '#fee08b', '#fdae61', '#f46d43', '#d53e4f'], + positions: [0, 0.1, 0.2, 0.6, 0.7, 0.8, 0.9, 1] + }, + yiorrd: { + colors: ['#800026', '#bd0026', '#e31a1c', '#fc4e2a', '#fd8d3c', '#feb24c', '#fed976', '#ffeda0', '#ffffcc'], + positions: [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1] + }, + bluered: { + colors: ['#0000ff', '#ff0000'], + positions: [0, 1] + }, + rdbu: { + colors: ['#050aac', '#6a89f7', '#bebebe', '#dcaa84', '#e6915a', '#b20a1c'], + positions: [0, 0.35, 0.5, 0.6, 0.7, 1] + }, + picnic: { + colors: ['#0000ff', '#3399ff', '#66ccff', '#99ccff', '#ccccff', '#ffffff', '#ffccff', '#ff99ff', '#ff66cc', '#ff6666', '#ff0000'], + positions: [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1] + }, + portland: { + colors: ['#0c3383', '#0a88ba', '#f2d338', '#f28f38', '#d91e1e'], + positions: [0, 0.25, 0.5, 0.75, 1] + }, + blackbody: { + colors: ['#000000', '#e60000', '#e6d200', '#ffffff', '#a0c8ff'], + positions: [0, 0.2, 0.4, 0.7, 1] + }, + earth: { + colors: ['#000082', '#00b4b4', '#28d228', '#e6e632', '#784614', '#ffffff'], + positions: [0, 0.1, 0.2, 0.4, 0.6, 1] + }, + electric: { + colors: ['#000000', '#1e0064', '#780064', '#a05a00', '#e6c800', '#fffadc'], + positions: [0, 0.15, 0.4, 0.6, 0.8, 1] + }, + magma: new Uint8Array([0, 0, 4, 255, 1, 0, 5, 255, 1, 1, 6, 255, 1, 1, 8, 255, 2, 1, 9, 255, 2, 2, 11, 255, 2, 2, 13, 255, 3, 3, 15, 255, 3, 3, 18, 255, 4, 4, 20, 255, 5, 4, 22, 255, 6, 5, 24, 255, 6, 5, 26, 255, 7, 6, 28, 255, 8, 7, 30, 255, 9, 7, 32, 255, 10, 8, 34, 255, 11, 9, 36, 255, 12, 9, 38, 255, 13, 10, 41, 255, 14, 11, 43, 255, 16, 11, 45, 255, 17, 12, 47, 255, 18, 13, 49, 255, 19, 13, 52, 255, 20, 14, 54, 255, 21, 14, 56, 255, 22, 15, 59, 255, 24, 15, 61, 255, 25, 16, 63, 255, 26, 16, 66, 255, 28, 16, 68, 255, 29, 17, 71, 255, 30, 17, 73, 255, 32, 17, 75, 255, 33, 17, 78, 255, 34, 17, 80, 255, 36, 18, 83, 255, 37, 18, 85, 255, 39, 18, 88, 255, 41, 17, 90, 255, 42, 17, 92, 255, 44, 17, 95, 255, 45, 17, 97, 255, 47, 17, 99, 255, 49, 17, 101, 255, 51, 16, 103, 255, 52, 16, 105, 255, 54, 16, 107, 255, 56, 16, 108, 255, 57, 15, 110, 255, 59, 15, 112, 255, 61, 15, 113, 255, 63, 15, 114, 255, 64, 15, 116, 255, 66, 15, 117, 255, 68, 15, 118, 255, 69, 16, 119, 255, 71, 16, 120, 255, 73, 16, 120, 255, 74, 16, 121, 255, 76, 17, 122, 255, 78, 17, 123, 255, 79, 18, 123, 255, 81, 18, 124, 255, 82, 19, 124, 255, 84, 19, 125, 255, 86, 20, 125, 255, 87, 21, 126, 255, 89, 21, 126, 255, 90, 22, 126, 255, 92, 22, 127, 255, 93, 23, 127, 255, 95, 24, 127, 255, 96, 24, 128, 255, 98, 25, 128, 255, 100, 26, 128, 255, 101, 26, 128, 255, 103, 27, 128, 255, 104, 28, 129, 255, 106, 28, 129, 255, 107, 29, 129, 255, 109, 29, 129, 255, 110, 30, 129, 255, 112, 31, 129, 255, 114, 31, 129, 255, 115, 32, 129, 255, 117, 33, 129, 255, 118, 33, 129, 255, 120, 34, 129, 255, 121, 34, 130, 255, 123, 35, 130, 255, 124, 35, 130, 255, 126, 36, 130, 255, 128, 37, 130, 255, 129, 37, 129, 255, 131, 38, 129, 255, 132, 38, 129, 255, 134, 39, 129, 255, 136, 39, 129, 255, 137, 40, 129, 255, 139, 41, 129, 255, 140, 41, 129, 255, 142, 42, 129, 255, 144, 42, 129, 255, 145, 43, 129, 255, 147, 43, 128, 255, 148, 44, 128, 255, 150, 44, 128, 255, 152, 45, 128, 255, 153, 45, 128, 255, 155, 46, 127, 255, 156, 46, 127, 255, 158, 47, 127, 255, 160, 47, 127, 255, 161, 48, 126, 255, 163, 48, 126, 255, 165, 49, 126, 255, 166, 49, 125, 255, 168, 50, 125, 255, 170, 51, 125, 255, 171, 51, 124, 255, 173, 52, 124, 255, 174, 52, 123, 255, 176, 53, 123, 255, 178, 53, 123, 255, 179, 54, 122, 255, 181, 54, 122, 255, 183, 55, 121, 255, 184, 55, 121, 255, 186, 56, 120, 255, 188, 57, 120, 255, 189, 57, 119, 255, 191, 58, 119, 255, 192, 58, 118, 255, 194, 59, 117, 255, 196, 60, 117, 255, 197, 60, 116, 255, 199, 61, 115, 255, 200, 62, 115, 255, 202, 62, 114, 255, 204, 63, 113, 255, 205, 64, 113, 255, 207, 64, 112, 255, 208, 65, 111, 255, 210, 66, 111, 255, 211, 67, 110, 255, 213, 68, 109, 255, 214, 69, 108, 255, 216, 69, 108, 255, 217, 70, 107, 255, 219, 71, 106, 255, 220, 72, 105, 255, 222, 73, 104, 255, 223, 74, 104, 255, 224, 76, 103, 255, 226, 77, 102, 255, 227, 78, 101, 255, 228, 79, 100, 255, 229, 80, 100, 255, 231, 82, 99, 255, 232, 83, 98, 255, 233, 84, 98, 255, 234, 86, 97, 255, 235, 87, 96, 255, 236, 88, 96, 255, 237, 90, 95, 255, 238, 91, 94, 255, 239, 93, 94, 255, 240, 95, 94, 255, 241, 96, 93, 255, 242, 98, 93, 255, 242, 100, 92, 255, 243, 101, 92, 255, 244, 103, 92, 255, 244, 105, 92, 255, 245, 107, 92, 255, 246, 108, 92, 255, 246, 110, 92, 255, 247, 112, 92, 255, 247, 114, 92, 255, 248, 116, 92, 255, 248, 118, 92, 255, 249, 120, 93, 255, 249, 121, 93, 255, 249, 123, 93, 255, 250, 125, 94, 255, 250, 127, 94, 255, 250, 129, 95, 255, 251, 131, 95, 255, 251, 133, 96, 255, 251, 135, 97, 255, 252, 137, 97, 255, 252, 138, 98, 255, 252, 140, 99, 255, 252, 142, 100, 255, 252, 144, 101, 255, 253, 146, 102, 255, 253, 148, 103, 255, 253, 150, 104, 255, 253, 152, 105, 255, 253, 154, 106, 255, 253, 155, 107, 255, 254, 157, 108, 255, 254, 159, 109, 255, 254, 161, 110, 255, 254, 163, 111, 255, 254, 165, 113, 255, 254, 167, 114, 255, 254, 169, 115, 255, 254, 170, 116, 255, 254, 172, 118, 255, 254, 174, 119, 255, 254, 176, 120, 255, 254, 178, 122, 255, 254, 180, 123, 255, 254, 182, 124, 255, 254, 183, 126, 255, 254, 185, 127, 255, 254, 187, 129, 255, 254, 189, 130, 255, 254, 191, 132, 255, 254, 193, 133, 255, 254, 194, 135, 255, 254, 196, 136, 255, 254, 198, 138, 255, 254, 200, 140, 255, 254, 202, 141, 255, 254, 204, 143, 255, 254, 205, 144, 255, 254, 207, 146, 255, 254, 209, 148, 255, 254, 211, 149, 255, 254, 213, 151, 255, 254, 215, 153, 255, 254, 216, 154, 255, 253, 218, 156, 255, 253, 220, 158, 255, 253, 222, 160, 255, 253, 224, 161, 255, 253, 226, 163, 255, 253, 227, 165, 255, 253, 229, 167, 255, 253, 231, 169, 255, 253, 233, 170, 255, 253, 235, 172, 255, 252, 236, 174, 255, 252, 238, 176, 255, 252, 240, 178, 255, 252, 242, 180, 255, 252, 244, 182, 255, 252, 246, 184, 255, 252, 247, 185, 255, 252, 249, 187, 255, 252, 251, 189, 255, 252, 253, 191, 255]), + plasma: new Uint8Array([13, 8, 135, 255, 16, 7, 136, 255, 19, 7, 137, 255, 22, 7, 138, 255, 25, 6, 140, 255, 27, 6, 141, 255, 29, 6, 142, 255, 32, 6, 143, 255, 34, 6, 144, 255, 36, 6, 145, 255, 38, 5, 145, 255, 40, 5, 146, 255, 42, 5, 147, 255, 44, 5, 148, 255, 46, 5, 149, 255, 47, 5, 150, 255, 49, 5, 151, 255, 51, 5, 151, 255, 53, 4, 152, 255, 55, 4, 153, 255, 56, 4, 154, 255, 58, 4, 154, 255, 60, 4, 155, 255, 62, 4, 156, 255, 63, 4, 156, 255, 65, 4, 157, 255, 67, 3, 158, 255, 68, 3, 158, 255, 70, 3, 159, 255, 72, 3, 159, 255, 73, 3, 160, 255, 75, 3, 161, 255, 76, 2, 161, 255, 78, 2, 162, 255, 80, 2, 162, 255, 81, 2, 163, 255, 83, 2, 163, 255, 85, 2, 164, 255, 86, 1, 164, 255, 88, 1, 164, 255, 89, 1, 165, 255, 91, 1, 165, 255, 92, 1, 166, 255, 94, 1, 166, 255, 96, 1, 166, 255, 97, 0, 167, 255, 99, 0, 167, 255, 100, 0, 167, 255, 102, 0, 167, 255, 103, 0, 168, 255, 105, 0, 168, 255, 106, 0, 168, 255, 108, 0, 168, 255, 110, 0, 168, 255, 111, 0, 168, 255, 113, 0, 168, 255, 114, 1, 168, 255, 116, 1, 168, 255, 117, 1, 168, 255, 119, 1, 168, 255, 120, 1, 168, 255, 122, 2, 168, 255, 123, 2, 168, 255, 125, 3, 168, 255, 126, 3, 168, 255, 128, 4, 168, 255, 129, 4, 167, 255, 131, 5, 167, 255, 132, 5, 167, 255, 134, 6, 166, 255, 135, 7, 166, 255, 136, 8, 166, 255, 138, 9, 165, 255, 139, 10, 165, 255, 141, 11, 165, 255, 142, 12, 164, 255, 143, 13, 164, 255, 145, 14, 163, 255, 146, 15, 163, 255, 148, 16, 162, 255, 149, 17, 161, 255, 150, 19, 161, 255, 152, 20, 160, 255, 153, 21, 159, 255, 154, 22, 159, 255, 156, 23, 158, 255, 157, 24, 157, 255, 158, 25, 157, 255, 160, 26, 156, 255, 161, 27, 155, 255, 162, 29, 154, 255, 163, 30, 154, 255, 165, 31, 153, 255, 166, 32, 152, 255, 167, 33, 151, 255, 168, 34, 150, 255, 170, 35, 149, 255, 171, 36, 148, 255, 172, 38, 148, 255, 173, 39, 147, 255, 174, 40, 146, 255, 176, 41, 145, 255, 177, 42, 144, 255, 178, 43, 143, 255, 179, 44, 142, 255, 180, 46, 141, 255, 181, 47, 140, 255, 182, 48, 139, 255, 183, 49, 138, 255, 184, 50, 137, 255, 186, 51, 136, 255, 187, 52, 136, 255, 188, 53, 135, 255, 189, 55, 134, 255, 190, 56, 133, 255, 191, 57, 132, 255, 192, 58, 131, 255, 193, 59, 130, 255, 194, 60, 129, 255, 195, 61, 128, 255, 196, 62, 127, 255, 197, 64, 126, 255, 198, 65, 125, 255, 199, 66, 124, 255, 200, 67, 123, 255, 201, 68, 122, 255, 202, 69, 122, 255, 203, 70, 121, 255, 204, 71, 120, 255, 204, 73, 119, 255, 205, 74, 118, 255, 206, 75, 117, 255, 207, 76, 116, 255, 208, 77, 115, 255, 209, 78, 114, 255, 210, 79, 113, 255, 211, 81, 113, 255, 212, 82, 112, 255, 213, 83, 111, 255, 213, 84, 110, 255, 214, 85, 109, 255, 215, 86, 108, 255, 216, 87, 107, 255, 217, 88, 106, 255, 218, 90, 106, 255, 218, 91, 105, 255, 219, 92, 104, 255, 220, 93, 103, 255, 221, 94, 102, 255, 222, 95, 101, 255, 222, 97, 100, 255, 223, 98, 99, 255, 224, 99, 99, 255, 225, 100, 98, 255, 226, 101, 97, 255, 226, 102, 96, 255, 227, 104, 95, 255, 228, 105, 94, 255, 229, 106, 93, 255, 229, 107, 93, 255, 230, 108, 92, 255, 231, 110, 91, 255, 231, 111, 90, 255, 232, 112, 89, 255, 233, 113, 88, 255, 233, 114, 87, 255, 234, 116, 87, 255, 235, 117, 86, 255, 235, 118, 85, 255, 236, 119, 84, 255, 237, 121, 83, 255, 237, 122, 82, 255, 238, 123, 81, 255, 239, 124, 81, 255, 239, 126, 80, 255, 240, 127, 79, 255, 240, 128, 78, 255, 241, 129, 77, 255, 241, 131, 76, 255, 242, 132, 75, 255, 243, 133, 75, 255, 243, 135, 74, 255, 244, 136, 73, 255, 244, 137, 72, 255, 245, 139, 71, 255, 245, 140, 70, 255, 246, 141, 69, 255, 246, 143, 68, 255, 247, 144, 68, 255, 247, 145, 67, 255, 247, 147, 66, 255, 248, 148, 65, 255, 248, 149, 64, 255, 249, 151, 63, 255, 249, 152, 62, 255, 249, 154, 62, 255, 250, 155, 61, 255, 250, 156, 60, 255, 250, 158, 59, 255, 251, 159, 58, 255, 251, 161, 57, 255, 251, 162, 56, 255, 252, 163, 56, 255, 252, 165, 55, 255, 252, 166, 54, 255, 252, 168, 53, 255, 252, 169, 52, 255, 253, 171, 51, 255, 253, 172, 51, 255, 253, 174, 50, 255, 253, 175, 49, 255, 253, 177, 48, 255, 253, 178, 47, 255, 253, 180, 47, 255, 253, 181, 46, 255, 254, 183, 45, 255, 254, 184, 44, 255, 254, 186, 44, 255, 254, 187, 43, 255, 254, 189, 42, 255, 254, 190, 42, 255, 254, 192, 41, 255, 253, 194, 41, 255, 253, 195, 40, 255, 253, 197, 39, 255, 253, 198, 39, 255, 253, 200, 39, 255, 253, 202, 38, 255, 253, 203, 38, 255, 252, 205, 37, 255, 252, 206, 37, 255, 252, 208, 37, 255, 252, 210, 37, 255, 251, 211, 36, 255, 251, 213, 36, 255, 251, 215, 36, 255, 250, 216, 36, 255, 250, 218, 36, 255, 249, 220, 36, 255, 249, 221, 37, 255, 248, 223, 37, 255, 248, 225, 37, 255, 247, 226, 37, 255, 247, 228, 37, 255, 246, 230, 38, 255, 246, 232, 38, 255, 245, 233, 38, 255, 245, 235, 39, 255, 244, 237, 39, 255, 243, 238, 39, 255, 243, 240, 39, 255, 242, 242, 39, 255, 241, 244, 38, 255, 241, 245, 37, 255, 240, 247, 36, 255, 240, 249, 33, 255]) +}; // export default colorScales; + +exports.colorScales = colorScales; \ No newline at end of file diff --git a/lib/attr/filter.js b/lib/attr/filter.js new file mode 100644 index 0000000000..20e3ea893d --- /dev/null +++ b/lib/attr/filter.js @@ -0,0 +1,51 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("./base")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +/** + * 视觉通道 filter + * @class Attr.filter + */ +var Filter = +/*#__PURE__*/ +function (_Base) { + _inherits(Filter, _Base); + + function Filter(cfg) { + var _this; + + _classCallCheck(this, Filter); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(Filter).call(this, cfg)); + _this.names = ['filter']; + _this.type = 'filter'; + _this.gradient = null; + return _this; + } + + return Filter; +}(_base["default"]); + +var _default = Filter; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/attr/index.js b/lib/attr/index.js new file mode 100644 index 0000000000..ff39c8a7fe --- /dev/null +++ b/lib/attr/index.js @@ -0,0 +1,37 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("./base")); + +var _color = _interopRequireDefault(require("./color")); + +var _size = _interopRequireDefault(require("./size")); + +var _opacity = _interopRequireDefault(require("./opacity")); + +var _shape = _interopRequireDefault(require("./shape")); + +var _position = _interopRequireDefault(require("./position")); + +var _symbol = _interopRequireDefault(require("./symbol")); + +var _filter = _interopRequireDefault(require("./filter")); + +var _pattern = _interopRequireDefault(require("./pattern")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +_base["default"].Color = _color["default"]; +_base["default"].Size = _size["default"]; +_base["default"].Opacity = _opacity["default"]; +_base["default"].Shape = _shape["default"]; +_base["default"].Position = _position["default"]; +_base["default"].Symbol = _symbol["default"]; +_base["default"].Filter = _filter["default"]; +_base["default"].Pattern = _pattern["default"]; +var _default = _base["default"]; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/attr/opacity.js b/lib/attr/opacity.js new file mode 100644 index 0000000000..60ca0a8363 --- /dev/null +++ b/lib/attr/opacity.js @@ -0,0 +1,51 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("./base")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +/** + * 视觉通道 Opacity + * @class Attr.Opacity + */ +var Opacity = +/*#__PURE__*/ +function (_Base) { + _inherits(Opacity, _Base); + + function Opacity(cfg) { + var _this; + + _classCallCheck(this, Opacity); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(Opacity).call(this, cfg)); + _this.names = ['opacity']; + _this.type = 'opacity'; + _this.gradient = null; + return _this; + } + + return Opacity; +}(_base["default"]); + +var _default = Opacity; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/attr/pattern.js b/lib/attr/pattern.js new file mode 100644 index 0000000000..bb9bbdaebb --- /dev/null +++ b/lib/attr/pattern.js @@ -0,0 +1,51 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("./base")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +/** + * 视觉通道 pattern + * @class Attr.pattern + */ +var Pattern = +/*#__PURE__*/ +function (_Base) { + _inherits(Pattern, _Base); + + function Pattern(cfg) { + var _this; + + _classCallCheck(this, Pattern); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(Pattern).call(this, cfg)); + _this.names = ['pattern']; + _this.type = 'pattern'; + _this.gradient = null; + return _this; + } + + return Pattern; +}(_base["default"]); + +var _default = Pattern; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/attr/position.js b/lib/attr/position.js new file mode 100644 index 0000000000..19106cf3e8 --- /dev/null +++ b/lib/attr/position.js @@ -0,0 +1,140 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("./base")); + +var _util = _interopRequireDefault(require("../util")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Position = +/*#__PURE__*/ +function (_Base) { + _inherits(Position, _Base); + + function Position(cfg) { + var _this; + + _classCallCheck(this, Position); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(Position).call(this, cfg)); + _this.names = ['x', 'y']; + _this.type = 'position'; + return _this; + } + + _createClass(Position, [{ + key: "mapping", + value: function mapping(x, y) { + var scales = this.scales; + var coord = this.coord; + var scaleX = scales[0]; + var scaleY = scales[1]; + var rstX; + var rstY; + var obj; + + if (_util["default"].isNil(x) || _util["default"].isNil(y)) { + return []; + } + + if (_util["default"].isArray(y) && _util["default"].isArray(x)) { + rstX = []; + rstY = []; + + for (var i = 0, j = 0; i < x.length && j < y.length; i++, j++) { + obj = coord.convertPoint({ + x: scaleX.scale(x[i]), + y: scaleY.scale(y[j]) + }); + rstX.push(obj.x); + rstY.push(obj.y); + } + } else if (_util["default"].isArray(y)) { + x = scaleX.scale(x); + rstY = []; + + _util["default"].each(y, function (yVal) { + yVal = scaleY.scale(yVal); + obj = coord.convertPoint({ + x: x, + y: yVal + }); + + if (rstX && rstX !== obj.x) { + if (!_util["default"].isArray(rstX)) { + rstX = [rstX]; + } + + rstX.push(obj.x); + } else { + rstX = obj.x; + } + + rstY.push(obj.y); + }); + } else if (_util["default"].isArray(x)) { + y = scaleY.scale(y); + rstX = []; + + _util["default"].each(x, function (xVal) { + xVal = scaleX.scale(xVal); + obj = coord.convertPoint({ + x: xVal, + y: y + }); + + if (rstY && rstY !== obj.y) { + if (!_util["default"].isArray(rstY)) { + rstY = [rstY]; + } + + rstY.push(obj.y); + } else { + rstY = obj.y; + } + + rstX.push(obj.x); + }); + } else { + x = scaleX.scale(x); + y = scaleY.scale(y); + var point = coord.convertPoint({ + x: x, + y: y + }); + rstX = point.x; + rstY = point.y; + } + + return [rstX, rstY]; + } + }]); + + return Position; +}(_base["default"]); + +var _default = Position; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/attr/shape.js b/lib/attr/shape.js new file mode 100644 index 0000000000..1c76acb57e --- /dev/null +++ b/lib/attr/shape.js @@ -0,0 +1,89 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("./base")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +/** + * 视觉通道 Shape + * @class Attr.Shape + */ +var Shape = +/*#__PURE__*/ +function (_Base) { + _inherits(Shape, _Base); + + function Shape(cfg) { + var _this; + + _classCallCheck(this, Shape); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(Shape).call(this, cfg)); + _this.names = ['shape']; + _this.type = 'shape'; + _this.gradient = null; + return _this; + } + /** + * @override + */ + + + _createClass(Shape, [{ + key: "getLinearValue", + value: function getLinearValue(percent) { + var values = this.values; + var index = Math.round((values.length - 1) * percent); + return values[index]; + } + /** + * @override + */ + + }, { + key: "_getAttrValue", + value: function _getAttrValue(scale, value) { + if (this.values === 'text') { + return value; + } + + var values = this.values; + + if (scale.isCategory && !this.linear) { + var index = scale.translate(value); + return values[index % values.length]; + } + + var percent = scale.scale(value); + return this.getLinearValue(percent); + } + }]); + + return Shape; +}(_base["default"]); + +var _default = Shape; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/attr/size.js b/lib/attr/size.js new file mode 100644 index 0000000000..2a58f18a71 --- /dev/null +++ b/lib/attr/size.js @@ -0,0 +1,107 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("./base")); + +var _util = _interopRequireDefault(require("../util")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +/** + * 视觉通道 size + * @class Attr.Size + */ +var Size = +/*#__PURE__*/ +function (_Base) { + _inherits(Size, _Base); + + function Size(cfg) { + var _this; + + _classCallCheck(this, Size); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(Size).call(this, cfg)); + _this.names = ['size']; + _this.type = 'size'; + _this.gradient = null; + _this.domainIndex = 0; + return _this; + } + + _createClass(Size, [{ + key: "mapping", + value: function mapping() { + // 重构 + var self = this; + var outputs = []; + var scales = self.scales; + + if (self.values.length === 0) { + var callback = this.callback.bind(this); + outputs.push(callback.apply(void 0, arguments)); + } else { + if (!_util["default"].isArray(self.values[0])) { + self.values = [self.values]; + } + + for (var i = 0; i < scales.length; i++) { + outputs.push(self._scaling(scales[i], arguments[i])); + } + } + + this.domainIndex = 0; + return outputs; + } + }, { + key: "_scaling", + value: function _scaling(scale, v) { + if (scale.type === 'identity') { + return v; + } + + var percent = scale.scale(v); + return this.getLinearValue(percent); // else if (scale.type === 'linear') { + } + }, { + key: "getLinearValue", + value: function getLinearValue(percent) { + var values = this.values[this.domainIndex]; + var steps = values.length - 1; + var step = Math.floor(steps * percent); + var leftPercent = steps * percent - step; + var start = values[step]; + var end = step === steps ? start : values[step + 1]; + var rstValue = start + (end - start) * leftPercent; + this.domainIndex += 1; + return rstValue; + } + }]); + + return Size; +}(_base["default"]); + +var _default = Size; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/attr/symbol.js b/lib/attr/symbol.js new file mode 100644 index 0000000000..aded74da35 --- /dev/null +++ b/lib/attr/symbol.js @@ -0,0 +1,51 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("./base")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +/** + * 视觉通道 symbol + * @class Attr.symbol + */ +var _Symbol = +/*#__PURE__*/ +function (_Base) { + _inherits(_Symbol, _Base); + + function _Symbol(cfg) { + var _this; + + _classCallCheck(this, _Symbol); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(_Symbol).call(this, cfg)); + _this.names = ['symbol']; + _this.type = 'symbol'; + _this.gradient = null; + return _this; + } + + return _Symbol; +}(_base["default"]); + +var _default = _Symbol; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/component/control/legend/color.js b/lib/component/control/legend/color.js new file mode 100644 index 0000000000..9a390c31f7 --- /dev/null +++ b/lib/component/control/legend/color.js @@ -0,0 +1 @@ +"use strict"; \ No newline at end of file diff --git a/lib/component/control/legend/shape.js b/lib/component/control/legend/shape.js new file mode 100644 index 0000000000..9a390c31f7 --- /dev/null +++ b/lib/component/control/legend/shape.js @@ -0,0 +1 @@ +"use strict"; \ No newline at end of file diff --git a/lib/component/control/legend/size.js b/lib/component/control/legend/size.js new file mode 100644 index 0000000000..9a390c31f7 --- /dev/null +++ b/lib/component/control/legend/size.js @@ -0,0 +1 @@ +"use strict"; \ No newline at end of file diff --git a/lib/component/index.js b/lib/component/index.js new file mode 100644 index 0000000000..8ea5add783 --- /dev/null +++ b/lib/component/index.js @@ -0,0 +1,14 @@ +"use strict"; + +/** + * @fileOverview chart component module + * @author sima.zhang1990@gmail.com + */ +module.exports = { + Axis: require('./axis/index'), + Guide: require('./guide/index'), + Label: require('./label/index'), + Legend: require('./legend/index'), + Plot: require('./plot'), + Tooltip: require('./tooltip/index') +}; \ No newline at end of file diff --git a/lib/component/tooltip/index.js b/lib/component/tooltip/index.js new file mode 100644 index 0000000000..e366ce41a6 --- /dev/null +++ b/lib/component/tooltip/index.js @@ -0,0 +1,693 @@ +"use strict"; + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +/** + * @fileOverview The class of tooltip + * @author sima.zhang + */ +var Util = require('../../util'); + +var Base = require('../../base'); + +var Global = require('../../global'); + +var _require = require('@antv/g'), + DomUtil = _require.DomUtil; + +var CONTAINER_CLASS = 'g2-tooltip'; +var TITLE_CLASS = 'g2-tooltip-title'; +var LIST_CLASS = 'g2-tooltip-list'; +var MARKER_CLASS = 'g2-tooltip-marker'; +var LIST_ITEM_CLASS = 'g2-tooltip-list-item'; + +function find(dom, cls) { + return dom.getElementsByClassName(cls)[0]; +} + +function refixTooltipPosition(x, y, el, viewWidth, viewHeight) { + var width = el.clientWidth; + var height = el.clientHeight; + var gap = 20; + + if (x + width + gap > viewWidth) { + x -= width + gap; + x = x < 0 ? 0 : x; + } else { + x += gap; + } + + if (y + height + gap > viewHeight) { + y -= height + gap; + y = x < 0 ? 0 : y; + } else { + y += gap; + } + + return [x, y]; +} + +function calcTooltipPosition(x, y, position, dom, target) { + var domWidth = dom.clientWidth; + var domHeight = dom.clientHeight; + var rectWidth = 0; + var rectHeight = 0; + var gap = 20; + + if (target) { + var rect = target.getBBox(); + rectWidth = rect.width; + rectHeight = rect.height; + x = rect.x; + y = rect.y; + gap = 5; + } + + switch (position) { + case 'inside': + x = x + rectWidth / 2 - domWidth / 2; + y = y + rectHeight / 2 - domHeight / 2; + break; + + case 'top': + x = x + rectWidth / 2 - domWidth / 2; + y = y - domHeight - gap; + break; + + case 'left': + x = x - domWidth - gap; + y = y + rectHeight / 2 - domHeight / 2; + break; + + case 'right': + x = x + rectWidth + gap; + y = y + rectHeight / 2 - domHeight / 2; + break; + + case 'bottom': + default: + x = x + rectWidth / 2 - domWidth / 2; + y = y + rectHeight + gap; + break; + } + + return [x, y]; +} + +function confineTooltipPosition(x, y, el, plotRange) { + var gap = 20; + var width = el.clientWidth; + var height = el.clientHeight; + + if (x + width > plotRange.tr.x) { + x -= width + 2 * gap; + } + + if (x < plotRange.tl.x) { + x = plotRange.tl.x; + } + + if (y + height > plotRange.bl.y) { + y -= height + 2 * gap; + } + + if (y < plotRange.tl.y) { + y = plotRange.tl.y; + } + + return [x, y]; +} + +var Tooltip = +/*#__PURE__*/ +function (_Base) { + _inherits(Tooltip, _Base); + + _createClass(Tooltip, [{ + key: "getDefaultCfg", + value: function getDefaultCfg() { + return { + /** + * 右下角坐标 + * @type {Number} + */ + x: 0, + + /** + * y 右下角坐标 + * @type {Number} + */ + y: 0, + + /** + * tooltip 记录项 + * @type {Array} + */ + items: null, + + /** + * 是否展示 title + * @type {Boolean} + */ + showTitle: true, + + /** + * tooltip 辅助线配置 + * @type {Object} + */ + crosshairs: null, + + /** + * 视图范围 + * @type {Object} + */ + plotRange: null, + + /** + * x轴上,移动到位置的偏移量 + * @type {Number} + */ + offset: 10, + + /** + * 时间戳 + * @type {Number} + */ + timeStamp: 0, + + /** + * tooltip 容器模板 + * @type {String} + */ + containerTpl: '
' + '
' + '' + '
', + + /** + * tooltip 列表项模板 + * @type {String} + */ + itemTpl: '
  • ' + '' + '{name}: {value}
  • ', + + /** + * 将 tooltip 展示在指定区域内 + * @type {Boolean} + */ + inPlot: true, + + /** + * tooltip 内容跟随鼠标移动 + * @type {Boolean} + */ + follow: true, + + /** + * 是否允许鼠标停留在 tooltip 上,默认不允许 + * @type {Boolean} + */ + enterable: false + }; + } + }, { + key: "_initTooltipWrapper", + value: function _initTooltipWrapper() { + var self = this; + var containerTpl = self.get('containerTpl'); + var outterNode = self.get('canvas').get('el').parentNode; + var container; + + if (/^\#/.test(containerTpl)) { + // 如果传入 dom 节点的 id + var id = containerTpl.replace('#', ''); + container = document.getElementById(id); + } else { + container = DomUtil.createDom(containerTpl); + DomUtil.modifyCSS(container, self.get(CONTAINER_CLASS)); + outterNode.appendChild(container); + outterNode.style.position = 'relative'; + } + + self.set('container', container); + } + }, { + key: "_init", + value: function _init() { + var crosshairs = this.get('crosshairs'); + var frontPlot = this.get('frontPlot'); + var backPlot = this.get('backPlot'); + var crosshairsGroup; + + if (crosshairs) { + if (crosshairs.type === 'rect') { + this.set('crosshairs', Util.deepMix({}, Global.tooltipCrosshairsRect, crosshairs)); + crosshairsGroup = backPlot.addGroup({ + zIndex: 0 + }); + } else { + this.set('crosshairs', Util.deepMix({}, Global.tooltipCrosshairsLine, crosshairs)); + crosshairsGroup = frontPlot.addGroup(); + } + } + + this.set('crosshairsGroup', crosshairsGroup); + + this._initTooltipWrapper(); + } + }]); + + function Tooltip(cfg) { + var _this; + + _classCallCheck(this, Tooltip); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(Tooltip).call(this, cfg)); + + _this._init(); // 初始化属性 + + + if (_this.get('items')) { + _this._renderTooltip(); + } + + _this._renderCrosshairs(); + + return _this; + } + + _createClass(Tooltip, [{ + key: "_clearDom", + value: function _clearDom() { + var container = this.get('container'); + var titleDom = find(container, TITLE_CLASS); + var listDom = find(container, LIST_CLASS); + + if (titleDom) { + titleDom.innerHTML = ''; + } + + if (listDom) { + listDom.innerHTML = ''; + } + } + }, { + key: "_addItem", + value: function _addItem(item, index) { + var itemTpl = this.get('itemTpl'); // TODO: 有可能是个回调函数 + + var itemDiv = Util.substitute(itemTpl, Util.mix({ + index: index + }, item)); + var itemDOM = DomUtil.createDom(itemDiv); + DomUtil.modifyCSS(itemDOM, this.get(LIST_ITEM_CLASS)); + var markerDom = find(itemDOM, MARKER_CLASS); + + if (markerDom) { + DomUtil.modifyCSS(markerDom, this.get(MARKER_CLASS)); + } + + return itemDOM; + } + }, { + key: "_renderTooltip", + value: function _renderTooltip() { + var self = this; + var showTitle = self.get('showTitle'); + var titleContent = self.get('titleContent'); + var container = self.get('container'); + var titleDom = find(container, TITLE_CLASS); + var listDom = find(container, LIST_CLASS); + var items = self.get('items'); + + self._clearDom(); + + if (titleDom && showTitle) { + DomUtil.modifyCSS(titleDom, self.get(TITLE_CLASS)); + titleDom.innerHTML = titleContent; + } + + if (listDom) { + DomUtil.modifyCSS(listDom, self.get(LIST_CLASS)); + Util.each(items, function (item, index) { + listDom.appendChild(self._addItem(item, index)); + }); + } + } + }, { + key: "_clearCrosshairsGroup", + value: function _clearCrosshairsGroup() { + var crosshairsGroup = this.get('crosshairsGroup'); + this.set('crossLineShapeX', null); + this.set('crossLineShapeY', null); + this.set('crosshairsRectShape', null); + crosshairsGroup.clear(); + } + }, { + key: "_renderCrosshairs", + value: function _renderCrosshairs() { + var crosshairs = this.get('crosshairs'); + var canvas = this.get('canvas'); + var plotRange = this.get('plotRange'); + var isTransposed = this.get('isTransposed'); + + if (crosshairs) { + this._clearCrosshairsGroup(); + + switch (crosshairs.type) { + case 'x': + this._renderHorizontalLine(canvas, plotRange); + + break; + + case 'y': + this._renderVerticalLine(canvas, plotRange); + + break; + + case 'cross': + this._renderHorizontalLine(canvas, plotRange); + + this._renderVerticalLine(canvas, plotRange); + + break; + + case 'rect': + this._renderBackground(canvas, plotRange); + + break; + + default: + isTransposed ? this._renderHorizontalLine(canvas, plotRange) : this._renderVerticalLine(canvas, plotRange); + } + } + } + }, { + key: "_addCrossLineShape", + value: function _addCrossLineShape(attrs, type) { + var crosshairsGroup = this.get('crosshairsGroup'); + var shape = crosshairsGroup.addShape('line', { + attrs: attrs + }); + shape.hide(); + this.set('crossLineShape' + type, shape); + return shape; + } + }, { + key: "_renderVerticalLine", + value: function _renderVerticalLine(canvas, plotRange) { + var _this$get = this.get('crosshairs'), + style = _this$get.style; + + var attrs = Util.mix({ + x1: 0, + y1: plotRange ? plotRange.bl.y : canvas.get('height'), + x2: 0, + y2: plotRange ? plotRange.tl.y : 0 + }, style); + + this._addCrossLineShape(attrs, 'Y'); + } + }, { + key: "_renderHorizontalLine", + value: function _renderHorizontalLine(canvas, plotRange) { + var _this$get2 = this.get('crosshairs'), + style = _this$get2.style; + + var attrs = Util.mix({ + x1: plotRange ? plotRange.bl.x : canvas.get('width'), + y1: 0, + x2: plotRange ? plotRange.br.x : 0, + y2: 0 + }, style); + + this._addCrossLineShape(attrs, 'X'); + } + }, { + key: "_renderBackground", + value: function _renderBackground(canvas, plotRange) { + var _this$get3 = this.get('crosshairs'), + style = _this$get3.style; + + var crosshairsGroup = this.get('crosshairsGroup'); + var attrs = Util.mix({ + x: plotRange ? plotRange.tl.x : 0, + y: plotRange ? plotRange.tl.y : canvas.get('height'), + width: plotRange ? plotRange.br.x - plotRange.bl.x : canvas.get('width'), + height: plotRange ? Math.abs(plotRange.tl.y - plotRange.bl.y) : canvas.get('height') + }, style); + var shape = crosshairsGroup.addShape('rect', { + attrs: attrs + }); + shape.hide(); + this.set('crosshairsRectShape', shape); + return shape; + } + }, { + key: "isContentChange", + value: function isContentChange(title, items) { + var titleContent = this.get('titleContent'); + var lastItems = this.get('items'); + var isChanged = !(title === titleContent && lastItems.length === items.length); + + if (!isChanged) { + Util.each(items, function (item, index) { + var preItem = lastItems[index]; + isChanged = item.value !== preItem.value || item.color !== preItem.color || item.name !== preItem.name || item.title !== preItem.title; + + if (isChanged) { + return false; + } + }); + } + + return isChanged; + } + }, { + key: "setContent", + value: function setContent(title, items) { + // const isChange = this.isContentChange(title, items); + // if (isChange) { + // 在外面进行判断是否内容发生改变 + var timeStamp = +new Date(); + this.set('items', items); + this.set('titleContent', title); + this.set('timeStamp', timeStamp); + + this._renderTooltip(); // } + + + return this; + } + }, { + key: "setMarkers", + value: function setMarkers(markerItems, markerCfg) { + var self = this; + var markerGroup = self.get('markerGroup'); + var frontPlot = self.get('frontPlot'); + + if (!markerGroup) { + markerGroup = frontPlot.addGroup({ + zIndex: 1, + capture: false // 不进行拾取 + + }); + self.set('markerGroup', markerGroup); + } else { + markerGroup.clear(); + } + + Util.each(markerItems, function (item) { + markerGroup.addShape('marker', { + color: item.color, + attrs: Util.mix({}, markerCfg, { + x: item.x, + y: item.y + }) + }); + }); + this.set('markerItems', markerItems); + } + }, { + key: "clearMarkers", + value: function clearMarkers() { + var markerGroup = this.get('markerGroup'); + markerGroup && markerGroup.clear(); + } + }, { + key: "setPosition", + value: function setPosition(x, y, target) { + var container = this.get('container'); + var crossLineShapeX = this.get('crossLineShapeX'); + var crossLineShapeY = this.get('crossLineShapeY'); + var crosshairsRectShape = this.get('crosshairsRectShape'); + var endx = x; + var endy = y; // const outterNode = this.get('canvas').get('el').parentNode; + + var outterNode = this.get('canvas').get('el'); + var viewWidth = DomUtil.getWidth(outterNode); + var viewHeight = DomUtil.getHeight(outterNode); + var offset = this.get('offset'); + var position; + + if (this.get('position')) { + position = calcTooltipPosition(x, y, this.get('position'), container, target); + x = position[0]; + y = position[1]; + } else if (!this.get('position')) { + position = refixTooltipPosition(x, y, container, viewWidth, viewHeight); + x = position[0]; + y = position[1]; + } + + if (this.get('inPlot')) { + // tooltip 必须限制在绘图区域内 + var plotRange = this.get('plotRange'); + position = confineTooltipPosition(x, y, container, plotRange); + x = position[0]; + y = position[1]; + } + + if (this.get('x') !== x || this.get('y') !== y) { + var markerItems = this.get('markerItems'); + + if (!Util.isEmpty(markerItems)) { + endx = markerItems[0].x; + endy = markerItems[0].y; + } + + if (crossLineShapeY) { + // 第一次进入时,画布需要单独绘制,所以需要先设定corss的位置 + crossLineShapeY.move(endx, 0); + } + + if (crossLineShapeX) { + crossLineShapeX.move(0, endy); + } + + if (crosshairsRectShape) { + // 绘制矩形辅助框,只在直角坐标系下生效 + var isTransposed = this.get('isTransposed'); + var items = this.get('items'); + var firstItem = items[0]; + var lastItem = items[items.length - 1]; + var dim = isTransposed ? 'y' : 'x'; + var attr = isTransposed ? 'height' : 'width'; + var startDim = firstItem[dim]; + + if (items.length > 1 && firstItem[dim] > lastItem[dim]) { + startDim = lastItem[dim]; + } + + if (this.get('crosshairs').width) { + // 用户定义了 width + crosshairsRectShape.attr(dim, startDim - this.get('crosshairs').width / 2); + crosshairsRectShape.attr(attr, this.get('crosshairs').width); + } else { + if (Util.isArray(firstItem.point[dim]) && !firstItem.size) { + // 直方图 + var width = firstItem.point[dim][1] - firstItem.point[dim][0]; + crosshairsRectShape.attr(dim, firstItem.point[dim][0]); + crosshairsRectShape.attr(attr, width); + } else { + offset = 3 * firstItem.size / 4; + crosshairsRectShape.attr(dim, startDim - offset); + + if (items.length === 1) { + crosshairsRectShape.attr(attr, 3 * firstItem.size / 2); + } else { + crosshairsRectShape.attr(attr, Math.abs(lastItem[dim] - firstItem[dim]) + 2 * offset); + } + } + } + } + + var follow = this.get('follow'); + container.style.left = follow ? x + 'px' : 0; + container.style.top = follow ? y + 'px' : 0; + } + } + }, { + key: "show", + value: function show() { + var crossLineShapeX = this.get('crossLineShapeX'); + var crossLineShapeY = this.get('crossLineShapeY'); + var crosshairsRectShape = this.get('crosshairsRectShape'); + var markerGroup = this.get('markerGroup'); + var container = this.get('container'); + var canvas = this.get('canvas'); + crossLineShapeX && crossLineShapeX.show(); + crossLineShapeY && crossLineShapeY.show(); + crosshairsRectShape && crosshairsRectShape.show(); + markerGroup && markerGroup.show(); + + _get(_getPrototypeOf(Tooltip.prototype), "show", this).call(this); + + container.style.visibility = 'visible'; // canvas.sort(); + + canvas.draw(); + } + }, { + key: "hide", + value: function hide() { + var self = this; + var container = self.get('container'); + var crossLineShapeX = self.get('crossLineShapeX'); + var crossLineShapeY = self.get('crossLineShapeY'); + var crosshairsRectShape = this.get('crosshairsRectShape'); + var markerGroup = self.get('markerGroup'); + var canvas = self.get('canvas'); + container.style.visibility = 'hidden'; + crossLineShapeX && crossLineShapeX.hide(); + crossLineShapeY && crossLineShapeY.hide(); + crosshairsRectShape && crosshairsRectShape.hide(); + markerGroup && markerGroup.hide(); + + _get(_getPrototypeOf(Tooltip.prototype), "hide", this).call(this); + + canvas.draw(); + } + }, { + key: "destroy", + value: function destroy() { + var self = this; + var crossLineShapeX = self.get('crossLineShapeX'); + var crossLineShapeY = self.get('crossLineShapeY'); + var markerGroup = self.get('markerGroup'); + var crosshairsRectShape = self.get('crosshairsRectShape'); + var container = self.get('container'); + var containerTpl = self.get('containerTpl'); + + if (container && !/^\#/.test(containerTpl)) { + container.parentNode.removeChild(container); + } + + crossLineShapeX && crossLineShapeX.remove(); + crossLineShapeY && crossLineShapeY.remove(); + markerGroup && markerGroup.remove(); + crosshairsRectShape && crosshairsRectShape.remove(); // super.remove(); + + _get(_getPrototypeOf(Tooltip.prototype), "destroy", this).call(this); + } + }]); + + return Tooltip; +}(Base); + +module.exports = Tooltip; \ No newline at end of file diff --git a/lib/core/atlas/font-manager.js b/lib/core/atlas/font-manager.js new file mode 100644 index 0000000000..3d2eefb2d7 --- /dev/null +++ b/lib/core/atlas/font-manager.js @@ -0,0 +1,326 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = exports.DEFAULT_RADIUS = exports.DEFAULT_CUTOFF = exports.DEFAULT_BUFFER = exports.DEFAULT_FONT_SIZE = exports.DEFAULT_FONT_WEIGHT = exports.DEFAULT_FONT_FAMILY = exports.DEFAULT_CHAR_SET = void 0; + +var _tinySdf = _interopRequireDefault(require("@mapbox/tiny-sdf")); + +var _fontUtil = require("../../util/font-util"); + +var THREE = _interopRequireWildcard(require("../../core/three")); + +var _lruCache = _interopRequireDefault(require("../../util/lru-cache")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var DEFAULT_CHAR_SET = getDefaultCharacterSet(); +exports.DEFAULT_CHAR_SET = DEFAULT_CHAR_SET; +var DEFAULT_FONT_FAMILY = 'sans-serif'; +exports.DEFAULT_FONT_FAMILY = DEFAULT_FONT_FAMILY; +var DEFAULT_FONT_WEIGHT = 'normal'; +exports.DEFAULT_FONT_WEIGHT = DEFAULT_FONT_WEIGHT; +var DEFAULT_FONT_SIZE = 24; +exports.DEFAULT_FONT_SIZE = DEFAULT_FONT_SIZE; +var DEFAULT_BUFFER = 3; +exports.DEFAULT_BUFFER = DEFAULT_BUFFER; +var DEFAULT_CUTOFF = 0.25; +exports.DEFAULT_CUTOFF = DEFAULT_CUTOFF; +var DEFAULT_RADIUS = 8; +exports.DEFAULT_RADIUS = DEFAULT_RADIUS; +var MAX_CANVAS_WIDTH = 1024; +var BASELINE_SCALE = 0.9; +var HEIGHT_SCALE = 1.2; +var CACHE_LIMIT = 3; +var cache = new _lruCache["default"](CACHE_LIMIT); +var VALID_PROPS = ['fontFamily', 'fontWeight', 'characterSet', 'fontSize', 'sdf', 'buffer', 'cutoff', 'radius']; + +function getDefaultCharacterSet() { + var charSet = []; + + for (var i = 32; i < 128; i++) { + charSet.push(String.fromCharCode(i)); + } + + return charSet; +} + +function setTextStyle(ctx, fontFamily, fontSize, fontWeight) { + ctx.font = "".concat(fontWeight, " ").concat(fontSize, "px ").concat(fontFamily); + ctx.fillStyle = '#000'; + ctx.textBaseline = 'baseline'; + ctx.textAlign = 'left'; +} + +function getNewChars(key, characterSet) { + var cachedFontAtlas = cache.get(key); + + if (!cachedFontAtlas) { + return characterSet; + } + + var newChars = []; + var cachedMapping = cachedFontAtlas.mapping; + var cachedCharSet = Object.keys(cachedMapping); + cachedCharSet = new Set(cachedCharSet); + var charSet = characterSet; + + if (charSet instanceof Array) { + charSet = new Set(charSet); + } + + charSet.forEach(function (_char) { + if (!cachedCharSet.has(_char)) { + newChars.push(_char); + } + }); + return newChars; +} + +function populateAlphaChannel(alphaChannel, imageData) { + // populate distance value from tinySDF to image alpha channel + for (var i = 0; i < alphaChannel.length; i++) { + imageData.data[4 * i + 3] = alphaChannel[i]; + } +} + +var FontAtlasManager = +/*#__PURE__*/ +function () { + function FontAtlasManager() { + _classCallCheck(this, FontAtlasManager); + + // font settings + this.props = { + fontFamily: DEFAULT_FONT_FAMILY, + fontWeight: DEFAULT_FONT_WEIGHT, + characterSet: DEFAULT_CHAR_SET, + fontSize: DEFAULT_FONT_SIZE, + buffer: DEFAULT_BUFFER, + // sdf only props + // https://github.com/mapbox/tiny-sdf + sdf: true, + cutoff: DEFAULT_CUTOFF, + radius: DEFAULT_RADIUS + }; // key is used for caching generated fontAtlas + + this._key = null; + this._texture = new THREE.Texture(); + } + + _createClass(FontAtlasManager, [{ + key: "setProps", + value: function setProps() { + var _this = this; + + var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + VALID_PROPS.forEach(function (prop) { + if (prop in props) { + _this.props[prop] = props[prop]; + } + }); // update cache key + + var oldKey = this._key; + this._key = this._getKey(); + var charSet = getNewChars(this._key, this.props.characterSet); + var cachedFontAtlas = cache.get(this._key); // if a fontAtlas associated with the new settings is cached and + // there are no new chars + + if (cachedFontAtlas && charSet.length === 0) { + // update texture with cached fontAtlas + if (this._key !== oldKey) { + this._updateTexture(cachedFontAtlas); + } + + return; + } // update fontAtlas with new settings + + + var fontAtlas = this._generateFontAtlas(this._key, charSet, cachedFontAtlas); + + this._fontAtlas = fontAtlas; + + this._updateTexture(fontAtlas); // update cache + + + cache.set(this._key, fontAtlas); + } + }, { + key: "_updateTexture", + value: function _updateTexture(_ref) { + var canvas = _ref.data; + this._texture = new THREE.CanvasTexture(canvas); + this._texture.wrapS = THREE.ClampToEdgeWrapping; + this._texture.wrapT = THREE.ClampToEdgeWrapping; + this._texture.minFilter = THREE.LinearFilter; + this._texture.flipY = false; + this._texture.needUpdate = true; + } + }, { + key: "_generateFontAtlas", + value: function _generateFontAtlas(key, characterSet, cachedFontAtlas) { + var _this$props = this.props, + fontFamily = _this$props.fontFamily, + fontWeight = _this$props.fontWeight, + fontSize = _this$props.fontSize, + buffer = _this$props.buffer, + sdf = _this$props.sdf, + radius = _this$props.radius, + cutoff = _this$props.cutoff; + var canvas = cachedFontAtlas && cachedFontAtlas.data; + + if (!canvas) { + canvas = document.createElement('canvas'); + canvas.width = MAX_CANVAS_WIDTH; + } + + var ctx = canvas.getContext('2d'); + setTextStyle(ctx, fontFamily, fontSize, fontWeight); // 1. build mapping + + var _buildMapping = (0, _fontUtil.buildMapping)(Object.assign({ + getFontWidth: function getFontWidth(_char2) { + return ctx.measureText(_char2).width; + }, + fontHeight: fontSize * HEIGHT_SCALE, + buffer: buffer, + characterSet: characterSet, + maxCanvasWidth: MAX_CANVAS_WIDTH + }, cachedFontAtlas && { + mapping: cachedFontAtlas.mapping, + xOffset: cachedFontAtlas.xOffset, + yOffset: cachedFontAtlas.yOffset + })), + mapping = _buildMapping.mapping, + canvasHeight = _buildMapping.canvasHeight, + xOffset = _buildMapping.xOffset, + yOffset = _buildMapping.yOffset; // 2. update canvas + // copy old canvas data to new canvas only when height changed + + + if (canvas.height !== canvasHeight) { + var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); + canvas.height = canvasHeight; + ctx.putImageData(imageData, 0, 0); + } + + setTextStyle(ctx, fontFamily, fontSize, fontWeight); // 3. layout characters + + if (sdf) { + var tinySDF = new _tinySdf["default"](fontSize, buffer, radius, cutoff, fontFamily, fontWeight); // used to store distance values from tinySDF + // tinySDF.size equals `fontSize + buffer * 2` + + var _imageData = ctx.getImageData(0, 0, tinySDF.size, tinySDF.size); + + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = characterSet[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _char3 = _step.value; + populateAlphaChannel(tinySDF.draw(_char3), _imageData); + ctx.putImageData(_imageData, mapping[_char3].x - buffer, mapping[_char3].y - buffer); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator["return"] != null) { + _iterator["return"](); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } else { + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = characterSet[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var _char4 = _step2.value; + ctx.fillText(_char4, mapping[_char4].x, mapping[_char4].y + fontSize * BASELINE_SCALE); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) { + _iterator2["return"](); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + + return { + xOffset: xOffset, + yOffset: yOffset, + mapping: mapping, + data: canvas, + width: canvas.width, + height: canvas.height + }; + } + }, { + key: "_getKey", + value: function _getKey() { + var _this$props2 = this.props, + fontFamily = _this$props2.fontFamily, + fontWeight = _this$props2.fontWeight, + fontSize = _this$props2.fontSize, + buffer = _this$props2.buffer, + sdf = _this$props2.sdf, + radius = _this$props2.radius, + cutoff = _this$props2.cutoff; + + if (sdf) { + return "".concat(fontFamily, " ").concat(fontWeight, " ").concat(fontSize, " ").concat(buffer, " ").concat(radius, " ").concat(cutoff); + } + + return "".concat(fontFamily, " ").concat(fontWeight, " ").concat(fontSize, " ").concat(buffer); + } + }, { + key: "texture", + get: function get() { + return this._texture; + } + }, { + key: "mapping", + get: function get() { + var data = cache.get(this._key); + return data && data.mapping; + } + }, { + key: "scale", + get: function get() { + return HEIGHT_SCALE; + } + }, { + key: "fontAtlas", + get: function get() { + return this._fontAtlas; + } + }]); + + return FontAtlasManager; +}(); + +exports["default"] = FontAtlasManager; \ No newline at end of file diff --git a/lib/core/atlas/icon-manager.js b/lib/core/atlas/icon-manager.js new file mode 100644 index 0000000000..17ea8db7dc --- /dev/null +++ b/lib/core/atlas/icon-manager.js @@ -0,0 +1,102 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _fontUtil = require("../../util/font-util"); + +var THREE = _interopRequireWildcard(require("../../../../core/three")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var BUFFER = 3; +var MAX_CANVAS_WIDTH = 1024; + +var IconManager = +/*#__PURE__*/ +function () { + function IconManager() { + _classCallCheck(this, IconManager); + + this._getIcon = null; + this._mapping = {}; + this._autoPacking = false; + this.iconData = {}; + this._canvas = document.createElement('canvas'); + this._texture = new THREE.Texture(this._canvas); + this.ctx = this._canvas.getContext('2d'); + } + + _createClass(IconManager, [{ + key: "getTexture", + value: function getTexture() { + return this._texture; + } + }, { + key: "_updateIconAtlas", + value: function _updateIconAtlas() { + this._canvas.width = MAX_CANVAS_WIDTH; + this._canvas.height = this._canvasHeigth; + + for (var key in this.mapping) { + var icon = this.mapping[key]; + var x = icon.x, + y = icon.y, + image = icon.image; + this.ctx.drawImage(image, x, y, this.imageWidth, this.imageWidth); + } + + this.texture.magFilter = THREE.LinearFilter; + this.texture.minFilter = THREE.LinearFilter; + this.texture.needsUpdate = true; + } + }, { + key: "addImage", + value: function addImage(id, opt) { + var _this = this; + + this._loadImage(opt).then(function (image) { + _this.iconData.push({ + id: id, + image: image + }); + + var _buildIconMaping = (0, _fontUtil.buildIconMaping)(_this.iconData, BUFFER, MAX_CANVAS_WIDTH), + mapping = _buildIconMaping.mapping, + canvasHeight = _buildIconMaping.canvasHeight; + + _this._mapping = mapping; + _this._canvasHeigth = canvasHeight; + }); + } + }, { + key: "_loadImage", + value: function _loadImage(url) { + return new Promise(function (resolve, reject) { + var image = new Image(); + + image.onload = function () { + resolve(image); + }; + + image.onerror = function () { + reject(new Error('Could not load image at ' + url)); + }; + + image.src = url; + }); + } + }]); + + return IconManager; +}(); + +exports["default"] = IconManager; \ No newline at end of file diff --git a/lib/core/base.js b/lib/core/base.js new file mode 100644 index 0000000000..9da84ab0b2 --- /dev/null +++ b/lib/core/base.js @@ -0,0 +1,86 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _wolfy87Eventemitter = _interopRequireDefault(require("wolfy87-eventemitter")); + +var _util = _interopRequireDefault(require("../util")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Base = +/*#__PURE__*/ +function (_EventEmitter) { + _inherits(Base, _EventEmitter); + + _createClass(Base, [{ + key: "getDefaultCfg", + value: function getDefaultCfg() { + return {}; + } + }]); + + function Base(cfg) { + var _this; + + _classCallCheck(this, Base); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(Base).call(this)); + var attrs = { + visible: true + }; + + var defaultCfg = _this.getDefaultCfg(); + + _this._attrs = attrs; + + _util["default"].assign(attrs, defaultCfg, cfg); + + return _this; + } + + _createClass(Base, [{ + key: "get", + value: function get(name) { + return this._attrs[name]; + } + }, { + key: "set", + value: function set(name, value) { + this._attrs[name] = value; + } + }, { + key: "destroy", + value: function destroy() { + this._attrs = {}; + this.removeAllListeners(); + this.destroyed = true; + } + }]); + + return Base; +}(_wolfy87Eventemitter["default"]); + +var _default = Base; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/core/controller/buffer.js b/lib/core/controller/buffer.js new file mode 100644 index 0000000000..d7dcbc4bb7 --- /dev/null +++ b/lib/core/controller/buffer.js @@ -0,0 +1,97 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _util = _interopRequireDefault(require("../../util")); + +var _object3dUtil = require("../../util/object3d-util"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var BufferController = +/*#__PURE__*/ +function () { + function BufferController(cfg) { + _classCallCheck(this, BufferController); + + // defs 列定义 + _util["default"].assign(this, cfg); + + if (!this.mesh) this.mesh = this.layer; + } + + _createClass(BufferController, [{ + key: "_updateColorAttributes", + value: function _updateColorAttributes() { + var _this = this; + + var filterData = this.mesh.layerData; + var colorKey = {}; + + for (var e = 0; e < filterData.length; e++) { + var item = filterData[e]; + colorKey[item.id] = item.color; + } + + this.layer._activeIds = null; // 清空选中元素xwxw + + var colorAttr = this.mesh.mesh.geometry.attributes.a_color; + var pickAttr = this.mesh.mesh.geometry.attributes.pickingId; + pickAttr.array.forEach(function (id, index) { + var newId = Math.abs(id); + var item = null; + var color = null; + + if (_this.mesh.layerSource.data.featureKeys) { + // hash数据映射 + newId = _this.mesh.layerSource.data.featureKeys[newId].index; + item = filterData[newId]; + color = colorKey[item.id]; + } else { + item = filterData[newId - 1]; + color = colorKey[newId]; + } + + if (item.hasOwnProperty('filter') && item.filter === false) { + colorAttr.array[index * 4 + 0] = 0; + colorAttr.array[index * 4 + 1] = 0; + colorAttr.array[index * 4 + 2] = 0; + colorAttr.array[index * 4 + 3] = 0; + pickAttr.array[index] = -id; // 通过Id数据过滤 id<0 不显示 + } else { + colorAttr.array[index * 4 + 0] = color[0]; + colorAttr.array[index * 4 + 1] = color[1]; + colorAttr.array[index * 4 + 2] = color[2]; + colorAttr.array[index * 4 + 3] = color[3]; + pickAttr.array[index] = id; + } + }); + colorAttr.needsUpdate = true; + pickAttr.needsUpdate = true; + } + }, { + key: "_updateStyle", + value: function _updateStyle(option) { + var newOption = {}; + + for (var key in option) { + newOption['u_' + key] = option[key]; + } + + (0, _object3dUtil.updateObjecteUniform)(this.mesh._object3D, newOption); + } + }]); + + return BufferController; +}(); + +exports["default"] = BufferController; \ No newline at end of file diff --git a/lib/core/controller/event.js b/lib/core/controller/event.js new file mode 100644 index 0000000000..195d9e36b5 --- /dev/null +++ b/lib/core/controller/event.js @@ -0,0 +1,76 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _util = _interopRequireDefault(require("../../util")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var EventContoller = +/*#__PURE__*/ +function () { + function EventContoller(cfg) { + _classCallCheck(this, EventContoller); + + _util["default"].assign(this, cfg); + } + + _createClass(EventContoller, [{ + key: "_init", + value: function _init() { + var _this = this; + + this.layer.scene.on('pick-' + this.layer.layerId, function (e) { + var featureId = e.featureId, + point2d = e.point2d, + type = e.type; + + if (featureId < 0 && _this._activeIds !== null) { + type = 'mouseleave'; + } + + _this._activeIds = featureId; // TODO 瓦片图层获取选中数据信息 + + var lnglat = _this.layer.scene.containerToLngLat(point2d); + + var _this$layer$getSelect = _this.layer.getSelectFeature(featureId, lnglat), + feature = _this$layer$getSelect.feature, + style = _this$layer$getSelect.style; // const style = this.layerData[featureId - 1]; + + + var target = { + featureId: featureId, + feature: feature, + style: style, + pixel: point2d, + type: type, + lnglat: { + lng: lnglat.lng, + lat: lnglat.lat + } + }; + + if (featureId >= 0 || _this._activeIds >= 0) { + // 拾取到元素,或者离开元素 + _this.layer.emit(type, target); + } + }); + } + }, { + key: "_initMapEvent", + value: function _initMapEvent() {} + }]); + + return EventContoller; +}(); + +exports["default"] = EventContoller; \ No newline at end of file diff --git a/lib/core/controller/geom.js b/lib/core/controller/geom.js new file mode 100644 index 0000000000..f8fa35525f --- /dev/null +++ b/lib/core/controller/geom.js @@ -0,0 +1,56 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = polygonGeom; +exports.pointGeom = pointGeom; + +var _geom = _interopRequireDefault(require("../../geom/geom")); + +var _index = require("../../geom/index"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// geom shape buffer geometry material +// shape name type() +// buffer 1:n geometry +// geometry +// +function polygonGeom(shape, coordinates, properties, layerid) { + var polygongeom = _geom.default.polygon; + var _polygongeom$shape = polygongeom[shape], + buffer = _polygongeom$shape.buffer, + geometry = _polygongeom$shape.geometry, + material = _polygongeom$shape.material; // polygon 映射表 + + var bufferData = new _index.GeoBuffer[buffer]({ + coordinates: coordinates, + properties: properties, + shape: shape + }); + bufferData.bufferStruct.name = layerid; + var bg = new _index.bufferGeometry[geometry](bufferData.bufferStruct); + + var mtl = _index.Material[material](); + + return { + geometry: bg, + mtl: mtl + }; +} + +function pointGeom(shape, bufferData) { + var pointgeom = _geom.default.point; + var _pointgeom$shape = pointgeom[shape], + geometry = _pointgeom$shape.geometry, + material = _pointgeom$shape.material; + var bg = new _index.bufferGeometry[geometry](bufferData.bufferStruct); + + var mtl = _index.Material[material](); + + return { + geometry: bg, + mtl: mtl + }; +} \ No newline at end of file diff --git a/lib/core/controller/index.js b/lib/core/controller/index.js new file mode 100644 index 0000000000..0b20742e45 --- /dev/null +++ b/lib/core/controller/index.js @@ -0,0 +1,30 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _scale = _interopRequireDefault(require("./scale")); + +var _mapping = _interopRequireDefault(require("./mapping")); + +var _pick = _interopRequireDefault(require("./pick")); + +var _interaction = _interopRequireDefault(require("./interaction")); + +var _event = _interopRequireDefault(require("./event")); + +var _buffer = _interopRequireDefault(require("./buffer")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +var _default = { + Scale: _scale["default"], + Mapping: _mapping["default"], + Picking: _pick["default"], + Interaction: _interaction["default"], + Event: _event["default"], + Buffer: _buffer["default"] +}; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/core/controller/interaction.js b/lib/core/controller/interaction.js new file mode 100644 index 0000000000..6335cb4eb2 --- /dev/null +++ b/lib/core/controller/interaction.js @@ -0,0 +1,83 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _util = _interopRequireDefault(require("../../util")); + +var _index = require("../../interaction/index"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var InteractionController = +/*#__PURE__*/ +function () { + function InteractionController(cfg) { + _classCallCheck(this, InteractionController); + + // defs 列定义 + _util["default"].assign(this, cfg); + } // interaction 方法 + + + _createClass(InteractionController, [{ + key: "clearAllInteractions", + value: function clearAllInteractions() { + var interactions = this.layer.get('interactions'); + + _util["default"].each(interactions, function (interaction, key) { + interaction.destory(); + delete interactions[key]; + }); + + return this; + } + }, { + key: "clearInteraction", + value: function clearInteraction(type) { + var interactions = this.layer.get('interactions'); + + if (interactions[type]) { + interactions[type].destory(); + delete interactions[type]; + } + + return this; + } + }, { + key: "addInteraction", + value: function addInteraction(type) { + var cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + cfg.layer = this.layer; + var Ctor = (0, _index.getInteraction)(type); + var interaction = new Ctor(cfg); + + this._setInteraction(type, interaction); + + return this; + } + }, { + key: "_setInteraction", + value: function _setInteraction(type, interaction) { + var interactions = this.layer.get('interactions'); + + if (interactions[type]) { + interactions[type].destory(); + } + + interactions[type] = interaction; + } + }]); + + return InteractionController; +}(); + +exports["default"] = InteractionController; \ No newline at end of file diff --git a/lib/core/controller/layer.js b/lib/core/controller/layer.js new file mode 100644 index 0000000000..2ecab7383a --- /dev/null +++ b/lib/core/controller/layer.js @@ -0,0 +1,14 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.layerControl = void 0; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var layerControl = function layerControl() { + _classCallCheck(this, layerControl); +}; + +exports.layerControl = layerControl; \ No newline at end of file diff --git a/lib/core/controller/map.js b/lib/core/controller/map.js new file mode 100644 index 0000000000..6e028d6b7c --- /dev/null +++ b/lib/core/controller/map.js @@ -0,0 +1,70 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _map = require("../../map"); + +var _base = _interopRequireDefault(require("../base")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var MapContorller = +/*#__PURE__*/ +function (_Base) { + _inherits(MapContorller, _Base); + + function MapContorller(cfg, engine, scene) { + var _this; + + _classCallCheck(this, MapContorller); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(MapContorller).call(this, cfg)); + _this._engine = engine; + _this.scene = scene; + return _this; + } + + _createClass(MapContorller, [{ + key: "_init", + value: function _init() { + var mapType = this.get('mapType'); + var mapCfg = this.get('mapCfg'); + this.map = new _map.getMap(mapType)(mapCfg); + this.map('mapLoad', this._mapload.bind(this)); + } + }, { + key: "_mapload", + value: function _mapload() { + this.map.asyncCamera(this._engine); + this.emit('loaded'); + } + }, { + key: "_bindMapMethod", + value: function _bindMapMethod() {} + }]); + + return MapContorller; +}(_base.default); + +exports.default = MapContorller; \ No newline at end of file diff --git a/lib/core/controller/mapping.js b/lib/core/controller/mapping.js new file mode 100644 index 0000000000..393d1ef145 --- /dev/null +++ b/lib/core/controller/mapping.js @@ -0,0 +1,279 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _util = _interopRequireDefault(require("../../util")); + +var _global = _interopRequireDefault(require("../../global")); + +var _scale = _interopRequireDefault(require("./scale")); + +var _index = _interopRequireDefault(require("../../attr/index")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var Mapping = +/*#__PURE__*/ +function () { + /** 初始化mapping + * 初始化mapping + * @param {*} cfg 配置 + * @param {*} cfg.layer layer对象 + * @param {*} cfg.mesh mesh对象 + */ + function Mapping(cfg) { + _classCallCheck(this, Mapping); + + _util["default"].assign(this, cfg); + + if (!this.mesh) this.mesh = this.layer; + + this._init(); + } + + _createClass(Mapping, [{ + key: "_init", + value: function _init() { + this._initControllers(); + + this._initTileAttrs(); + + this._mapping(); + } + }, { + key: "update", + value: function update() { + this.mesh.set('scales', {}); + + this._initTileAttrs(); + + this._updateMaping(); + } + }, { + key: "_initControllers", + value: function _initControllers() { + var scalesOption = this.layer.get('scaleOptions'); + var scaleController = new _scale["default"]({ + defs: _objectSpread({}, scalesOption) + }); + this.mesh.set('scaleController', scaleController); + } + }, { + key: "_createScale", + value: function _createScale(field) { + var scales = this.mesh.get('scales'); + + this._initControllers(); // scale更新 + + + var scale = scales[field]; + + if (!scale) { + scale = this.createScale(field); + scales[field] = scale; + } + + return scale; + } + }, { + key: "createScale", + value: function createScale(field) { + var data = this.mesh.layerSource.data.dataArray; + var scales = this.mesh.get('scales'); + var scale = scales[field]; + var scaleController = this.mesh.get('scaleController'); + + if (!scale) { + scale = scaleController.createScale(field, data); + scales[field] = scale; + } + + return scale; + } // 获取属性映射的值 + + }, { + key: "_getAttrValues", + value: function _getAttrValues(attr, record) { + var scales = attr.scales; + var params = []; + + for (var i = 0; i < scales.length; i++) { + var scale = scales[i]; + var field = scale.field; + + if (scale.type === 'identity') { + params.push(scale.value); + } else { + params.push(record[field]); + } + } + + var indexZoom = params.indexOf('zoom'); + indexZoom !== -1 ? params[indexZoom] = attr.zoom : null; + var values = attr.mapping.apply(attr, params); + return values; + } + }, { + key: "_mapping", + value: function _mapping() { + var attrs = this.mesh.get('attrs'); + var mappedData = []; + var data = this.mesh.layerSource.data.dataArray; + + for (var i = 0; i < data.length; i++) { + var record = data[i]; + var newRecord = {}; + newRecord.id = data[i]._id; + + for (var k in attrs) { + if (attrs.hasOwnProperty(k)) { + var attr = attrs[k]; + var names = attr.names; + + var values = this._getAttrValues(attr, record); + + if (names.length > 1) { + // position 之类的生成多个字段的属性 + for (var j = 0; j < values.length; j++) { + var val = values[j]; + var name = names[j]; + newRecord[name] = _util["default"].isArray(val) && val.length === 1 ? val[0] : val; // 只有一个值时返回第一个属性值 + } + } else { + newRecord[names[0]] = values.length === 1 ? values[0] : values; + } + } + } + + newRecord.coordinates = record.coordinates; + mappedData.push(newRecord); + } // 通过透明度过滤数据 + + + if (attrs.hasOwnProperty('filter')) { + mappedData.forEach(function (item) { + if (item.filter === false) { + item.color[3] = 0; + item.id = -item.id; + } + }); + } + + this.mesh.layerData = mappedData; + } + /** + * 更新数据maping + * @param {*} layerSource 数据源 + * @param {*} layer map + */ + + }, { + key: "_updateMaping", + value: function _updateMaping() { + var attrs = this.mesh.get('attrs'); + var data = this.mesh.layerSource.data.dataArray; + var layerData = this.mesh.layerData; + + for (var i = 0; i < data.length; i++) { + var record = data[i]; + + for (var attrName in attrs) { + if (attrs.hasOwnProperty(attrName) && attrs[attrName].neadUpdate) { + var attr = attrs[attrName]; + var names = attr.names; + + var values = this._getAttrValues(attr, record); + + if (names.length > 1) { + // position 之类的生成多个字段的属性 + for (var j = 0; j < values.length; j++) { + var val = values[j]; + var name = names[j]; + layerData[i][name] = _util["default"].isArray(val) && val.length === 1 ? val[0] : val; // 只有一个值时返回第一个属性值 + } + } else { + layerData[i][names[0]] = values.length === 1 ? values[0] : values; + } + + attr.neadUpdate = true; + } + } + } + } + }, { + key: "_initTileAttrs", + value: function _initTileAttrs() { + var attrOptions = this.layer.get('attrOptions'); + + for (var type in attrOptions) { + if (attrOptions.hasOwnProperty(type)) { + this._updateTileAttr(type); + } + } + } + }, { + key: "_updateTileAttr", + value: function _updateTileAttr(type) { + var self = this; + var attrs = this.mesh.get('attrs'); + var attrOptions = this.layer.get('attrOptions'); + var option = attrOptions[type]; + option.neadUpdate = true; + + var className = _util["default"].upperFirst(type); + + var fields = this._parseFields(option.field); + + var scales = []; + + for (var i = 0; i < fields.length; i++) { + var field = fields[i]; + + var scale = self._createScale(field); + + if (type === 'color' && _util["default"].isNil(option.values)) { + // 设置 color 的默认色值 + option.values = _global["default"].colors; + } + + scales.push(scale); + } + + option.scales = scales; + var attr = new _index["default"][className](option); + attrs[type] = attr; + } + }, { + key: "_parseFields", + value: function _parseFields(field) { + if (_util["default"].isArray(field)) { + return field; + } + + if (_util["default"].isString(field)) { + return field.split('*'); + } + + return [field]; + } + }]); + + return Mapping; +}(); + +exports["default"] = Mapping; \ No newline at end of file diff --git a/lib/core/controller/pick.js b/lib/core/controller/pick.js new file mode 100644 index 0000000000..cc08650de4 --- /dev/null +++ b/lib/core/controller/pick.js @@ -0,0 +1,105 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _util = _interopRequireDefault(require("../../util")); + +var THREE = _interopRequireWildcard(require("../three")); + +var _object3dUtil = require("../../util/object3d-util"); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var PickContoller = +/*#__PURE__*/ +function () { + function PickContoller(cfg) { + _classCallCheck(this, PickContoller); + + _util["default"].assign(this, cfg); + + this.pickObject3D = new THREE.Object3D(); + this.addToPicking(this.pickObject3D); + } + + _createClass(PickContoller, [{ + key: "getPickingId", + value: function getPickingId() { + return this.layer.scene._engine._picking.getNextId(); + } + }, { + key: "addToPicking", + value: function addToPicking(object) { + object.name = this.layer.layerId; + + this.layer.scene._engine._picking.add(object); + } + }, { + key: "removePickingObject", + value: function removePickingObject(object) { + this.layer.scene._engine._picking.remove(object); + } + }, { + key: "removePickingMesh", + value: function removePickingMesh(mesh) { + this.pickObject3D.remove(mesh); + (0, _object3dUtil.destoryObject)(mesh); + } + }, { + key: "removePickMeshByName", + value: function removePickMeshByName(name) { + for (var i = 0; i < this.pickObject3D.children.length; i++) { + if (this.pickObject3D.children[i].name === name) { + this.removePickingMesh(this.pickObject3D.children[i]); + } + } + } + }, { + key: "removeAllMesh", + value: function removeAllMesh() { + var _this = this; + + this.pickObject3D.children.forEach(function (element) { + _this.pickObject3D.remove(element); + + (0, _object3dUtil.destoryObject)(element); + }); + } + }, { + key: "addPickMesh", + value: function addPickMesh(mesh) { + var _this2 = this; + + var pickmaterial = mesh.material.clone(); + pickmaterial.defines.PICK = true; // pickmaterial.fragmentShader = pickingFragmentShader; + + var pickingMesh = new THREE[mesh.type](mesh.geometry, pickmaterial); + pickingMesh.name = mesh.name; + + pickingMesh.onBeforeRender = function () { + var zoom = _this2.layer.scene.getZoom(); + + (0, _object3dUtil.updateObjecteUniform)(pickingMesh, { + u_zoom: zoom + }); + }; + + this.pickObject3D.add(pickingMesh); + } + }]); + + return PickContoller; +}(); + +exports["default"] = PickContoller; \ No newline at end of file diff --git a/lib/core/controller/scale.js b/lib/core/controller/scale.js new file mode 100644 index 0000000000..6d5294556e --- /dev/null +++ b/lib/core/controller/scale.js @@ -0,0 +1,163 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _util = _interopRequireDefault(require("../../util")); + +var _global = _interopRequireDefault(require("../../global")); + +var _scale = _interopRequireDefault(require("../../scale/")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var dateRegex = /^(?:(?!0000)[0-9]{4}([-/.]+)(?:(?:0?[1-9]|1[0-2])\1(?:0?[1-9]|1[0-9]|2[0-8])|(?:0?[13-9]|1[0-2])\1(?:29|30)|(?:0?[13578]|1[02])\1(?:31))|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)([-/.]?)0?2\2(?:29))(\s+([01]|([01][0-9]|2[0-3])):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9]))?$/; +var TYPES = { + LINEAR: 'linear', + CAT: 'cat', + TIME: 'time' +}; + +var ScaleController = +/*#__PURE__*/ +function () { + function ScaleController(cfg) { + _classCallCheck(this, ScaleController); + + // defs 列定义 + this.defs = {}; + + _util["default"].assign(this, cfg); + } + + _createClass(ScaleController, [{ + key: "_getDef", + value: function _getDef(field) { + var defs = this.defs; + var def = null; + + if (_global["default"].scales[field] || defs[field]) { + def = _util["default"].mix({}, _global["default"].scales[field]); // 处理覆盖属性的问题 + + _util["default"].each(defs[field], function (v, k) { + if (_util["default"].isNil(v)) { + delete def[k]; + } else { + def[k] = v; + } + }); + } + + return def; + } + }, { + key: "_getDefaultType", + value: function _getDefaultType(field, data) { + var type = TYPES.LINEAR; + + var value = _util["default"].Array.firstValue(data, field); + + if (_util["default"].isArray(value)) { + value = value[0]; + } + + if (dateRegex.test(value)) { + type = TYPES.TIME; + } else if (_util["default"].isString(value)) { + type = TYPES.CAT; + } + + return type; + } + }, { + key: "_getScaleCfg", + value: function _getScaleCfg(type, field, data) { + var cfg = { + field: field + }; + + var values = _util["default"].Array.values(data, field); + + cfg.values = values; + + if (!_scale["default"].isCategory(type) && type !== 'time') { + var range = _util["default"].Array.getRange(values); + + cfg.min = range.min; + cfg.max = range.max; + cfg.nice = true; + } + + if (type === 'time') { + cfg.nice = false; + } + + return cfg; + } + }, { + key: "createScale", + value: function createScale(field, data) { + var self = this; + + var def = self._getDef(field); + + var scale; // 如果数据为空直接返回常量度量 + + if (!data || !data.length) { + if (def && def.type) { + scale = _scale["default"][def.type](def); + } else { + scale = _scale["default"].identity({ + value: field, + field: field.toString(), + values: [field] + }); + } + + return scale; + } + + var firstValue = _util["default"].Array.firstValue(data, field); + + if (_util["default"].isNumber(field) || _util["default"].isNil(firstValue) && !def) { + scale = _scale["default"].identity({ + value: field, + field: field.toString(), + values: [field] + }); + } else { + // 如果已经定义过这个度量 + var type; + + if (def) { + type = def.type; + } + + type = type || self._getDefaultType(field, data); + + var cfg = self._getScaleCfg(type, field, data); + + if (def) { + _util["default"].mix(cfg, def); + } + + scale = _scale["default"][type](cfg); + } + + return scale; + } + }]); + + return ScaleController; +}(); + +var _default = ScaleController; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/core/controller/tile_mapping.js b/lib/core/controller/tile_mapping.js new file mode 100644 index 0000000000..4504b760b8 --- /dev/null +++ b/lib/core/controller/tile_mapping.js @@ -0,0 +1,292 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _util = _interopRequireDefault(require("../../util")); + +var _global = _interopRequireDefault(require("../../global")); + +var _scale = _interopRequireDefault(require("./scale")); + +var _base = _interopRequireDefault(require("../base")); + +var _index = _interopRequireDefault(require("../../attr/index")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var TileMapping = +/*#__PURE__*/ +function (_Base) { + _inherits(TileMapping, _Base); + + function TileMapping(source, cfg) { + var _this; + + _classCallCheck(this, TileMapping); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(TileMapping).call(this, cfg)); + _this.source = source; + + _this._init(); + + return _this; + } + + _createClass(TileMapping, [{ + key: "_init", + value: function _init() { + this._initControllers(); + + this._initTileAttrs(); + + this._mapping(); + } + }, { + key: "update", + value: function update() { + this.set('scales', {}); + + this._initTileAttrs(); + + this._updateMaping(); + } + }, { + key: "_initControllers", + value: function _initControllers() { + var scalesOption = this.get('scaleOptions'); + var scaleController = new _scale["default"]({ + defs: _objectSpread({}, scalesOption) + }); + this.set('scaleController', scaleController); + } + }, { + key: "_createScale", + value: function _createScale(field) { + var scales = this.get('scales'); + + this._initControllers(); // scale更新 + + + var scale = scales[field]; + + if (!scale) { + scale = this.createScale(field); + scales[field] = scale; + } + + return scale; + } + }, { + key: "createScale", + value: function createScale(field) { + var data = this.source.data.dataArray; + var scales = this.get('scales'); + var scale = scales[field]; + var scaleController = this.get('scaleController'); + + if (!scale) { + scale = scaleController.createScale(field, data); + scales[field] = scale; + } + + return scale; + } // 获取属性映射的值 + + }, { + key: "_getAttrValues", + value: function _getAttrValues(attr, record) { + var scales = attr.scales; + var params = []; + + for (var i = 0; i < scales.length; i++) { + var scale = scales[i]; + var field = scale.field; + + if (scale.type === 'identity') { + params.push(scale.value); + } else { + params.push(record[field]); + } + } + + var indexZoom = params.indexOf('zoom'); + indexZoom !== -1 ? params[indexZoom] = attr.zoom : null; + var values = attr.mapping.apply(attr, params); + return values; + } + }, { + key: "_mapping", + value: function _mapping() { + var attrs = this.get('attrs'); + var mappedData = []; + var data = this.source.data.dataArray; + + for (var i = 0; i < data.length; i++) { + var record = data[i]; + var newRecord = {}; + newRecord.id = data[i]._id; + + for (var k in attrs) { + if (attrs.hasOwnProperty(k)) { + var attr = attrs[k]; + var names = attr.names; + + var values = this._getAttrValues(attr, record); + + if (names.length > 1) { + // position 之类的生成多个字段的属性 + for (var j = 0; j < values.length; j++) { + var val = values[j]; + var name = names[j]; + newRecord[name] = _util["default"].isArray(val) && val.length === 1 ? val[0] : val; // 只有一个值时返回第一个属性值 + } + } else { + newRecord[names[0]] = values.length === 1 ? values[0] : values; + } + } + } + + newRecord.coordinates = record.coordinates; + mappedData.push(newRecord); + } // 通过透明度过滤数据 + + + if (attrs.hasOwnProperty('filter')) { + mappedData.forEach(function (item) { + if (item.filter === false) { + item.color[3] = 0; + item.id = -item.id; + } + }); + } + + this.layerData = mappedData; + } + /** + * 更新数据maping + * @param {*} layerSource 数据源 + * @param {*} layer map + */ + + }, { + key: "_updateMaping", + value: function _updateMaping() { + var attrs = this.get('attrs'); + var data = this.source.data.dataArray; + var layerData = this.layerData; + + for (var i = 0; i < data.length; i++) { + var record = data[i]; + + for (var attrName in attrs) { + if (attrs.hasOwnProperty(attrName) && attrs[attrName].neadUpdate) { + var attr = attrs[attrName]; + var names = attr.names; + + var values = this._getAttrValues(attr, record); + + if (names.length > 1) { + // position 之类的生成多个字段的属性 + for (var j = 0; j < values.length; j++) { + var val = values[j]; + var name = names[j]; + layerData[i][name] = _util["default"].isArray(val) && val.length === 1 ? val[0] : val; // 只有一个值时返回第一个属性值 + } + } else { + layerData[i][names[0]] = values.length === 1 ? values[0] : values; + } + + attr.neadUpdate = true; + } + } + } + } + }, { + key: "_initTileAttrs", + value: function _initTileAttrs() { + var attrOptions = this.get('attrOptions'); + + for (var type in attrOptions) { + if (attrOptions.hasOwnProperty(type)) { + this._updateTileAttr(type); + } + } + } + }, { + key: "_updateTileAttr", + value: function _updateTileAttr(type) { + var self = this; + var attrs = this.get('attrs'); + var attrOptions = this.get('attrOptions'); + var option = attrOptions[type]; + option.neadUpdate = true; + + var className = _util["default"].upperFirst(type); + + var fields = this._parseFields(option.field); + + var scales = []; + + for (var i = 0; i < fields.length; i++) { + var field = fields[i]; + + var scale = self._createScale(field); + + if (type === 'color' && _util["default"].isNil(option.values)) { + // 设置 color 的默认色值 + option.values = _global["default"].colors; + } + + scales.push(scale); + } + + option.scales = scales; + var attr = new _index["default"][className](option); + attrs[type] = attr; + } + }, { + key: "_parseFields", + value: function _parseFields(field) { + if (_util["default"].isArray(field)) { + return field; + } + + if (_util["default"].isString(field)) { + return field.split('*'); + } + + return [field]; + } + }]); + + return TileMapping; +}(_base["default"]); + +exports["default"] = TileMapping; \ No newline at end of file diff --git a/lib/core/engine/camera.js b/lib/core/engine/camera.js new file mode 100644 index 0000000000..bea19aa3c3 --- /dev/null +++ b/lib/core/engine/camera.js @@ -0,0 +1,43 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var THREE = _interopRequireWildcard(require("../three")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var Camera = +/*#__PURE__*/ +function () { + function Camera(container) { + _classCallCheck(this, Camera); + + this.container = container; + var camera = new THREE.PerspectiveCamera(45, 1, 1, 2000000); + this.camera = camera; + this.updateSize(); + window.addEventListener('resize', this.updateSize.bind(this)); + } + + _createClass(Camera, [{ + key: "updateSize", + value: function updateSize() { + var container = this.container; + this.camera.aspect = container.clientWidth / container.clientHeight; + this.camera.updateProjectionMatrix(); + } + }]); + + return Camera; +}(); + +exports["default"] = Camera; \ No newline at end of file diff --git a/lib/core/engine/composer.js b/lib/core/engine/composer.js new file mode 100755 index 0000000000..414973653d --- /dev/null +++ b/lib/core/engine/composer.js @@ -0,0 +1,117 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var THREE = _interopRequireWildcard(require("../three")); + +var _copyShader = _interopRequireDefault(require("./copy-shader")); + +var _shaderPass = _interopRequireDefault(require("./shader-pass")); + +var _maskPass = _interopRequireWildcard(require("./mask-pass")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +// jscs:disable + +/* eslint-disable */ + +/** + * @author alteredq / http://alteredqualia.com/ + */ +var EffectComposer = function EffectComposer(renderer, renderTarget) { + this.renderer = renderer; + + if (renderTarget === undefined) { + var pixelRatio = renderer.getPixelRatio(); + var width = Math.floor(renderer.context.canvas.width / pixelRatio) || 1; + var height = Math.floor(renderer.context.canvas.height / pixelRatio) || 1; + var parameters = { + minFilter: THREE.LinearFilter, + magFilter: THREE.LinearFilter, + format: THREE.RGBAFormat, + stencilBuffer: false + }; + renderTarget = new THREE.WebGLRenderTarget(width, height, parameters); + } + + this.renderTarget1 = renderTarget; + this.renderTarget2 = renderTarget.clone(); + this.writeBuffer = this.renderTarget1; + this.readBuffer = this.renderTarget2; + this.passes = []; + if (_copyShader["default"] === undefined) console.error("EffectComposer relies on THREE.CopyShader"); + this.copyPass = new _shaderPass["default"](_copyShader["default"]); +}; + +EffectComposer.prototype = { + swapBuffers: function swapBuffers() { + var tmp = this.readBuffer; + this.readBuffer = this.writeBuffer; + this.writeBuffer = tmp; + }, + visible: true, + type: 'composer', + addPass: function addPass(pass) { + this.passes.push(pass); + }, + insertPass: function insertPass(pass, index) { + this.passes.splice(index, 0, pass); + }, + render: function render(delta) { + this.writeBuffer = this.renderTarget1; + this.readBuffer = this.renderTarget2; + var maskActive = false; + var pass, + i, + il = this.passes.length; + + for (i = 0; i < il; i++) { + pass = this.passes[i]; + if (!pass.enabled) continue; + pass.render(this.renderer, this.writeBuffer, this.readBuffer, delta, maskActive); + + if (pass.needsSwap) { + if (maskActive) { + var context = this.renderer.context; + context.stencilFunc(context.NOTEQUAL, 1, 0xffffffff); + this.copyPass.render(this.renderer, this.writeBuffer, this.readBuffer, delta); + context.stencilFunc(context.EQUAL, 1, 0xffffffff); + } + + this.swapBuffers(); + } + + if (pass instanceof _maskPass["default"]) { + maskActive = true; + } else if (pass instanceof _maskPass.ClearMaskPass) { + maskActive = false; + } + } + }, + reset: function reset(renderTarget) { + if (renderTarget === undefined) { + renderTarget = this.renderTarget1.clone(); + var pixelRatio = this.renderer.getPixelRatio(); + renderTarget.setSize(Math.floor(this.renderer.context.canvas.width / pixelRatio), Math.floor(this.renderer.context.canvas.height / pixelRatio)); + } + + this.renderTarget1.dispose(); + this.renderTarget1 = renderTarget; + this.renderTarget2.dispose(); + this.renderTarget2 = renderTarget.clone(); + this.writeBuffer = this.renderTarget1; + this.readBuffer = this.renderTarget2; + }, + setSize: function setSize(width, height) { + this.renderTarget1.setSize(width, height); + this.renderTarget2.setSize(width, height); + } +}; +var _default = EffectComposer; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/core/engine/copy-shader.js b/lib/core/engine/copy-shader.js new file mode 100755 index 0000000000..473426827b --- /dev/null +++ b/lib/core/engine/copy-shader.js @@ -0,0 +1,36 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var THREE = _interopRequireWildcard(require("../three")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +// jscs:disable + +/* eslint-disable */ + +/** + * @author alteredq / http://alteredqualia.com/ + * + * Full-screen textured quad shader + */ +var CopyShader = { + uniforms: { + "tDiffuse": { + type: "t", + value: null + }, + "opacity": { + type: "f", + value: 1.0 + } + }, + vertexShader: ["varying vec2 vUv;", "void main() {", "vUv = uv;", "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", "}"].join("\n"), + fragmentShader: ["uniform float opacity;", "uniform sampler2D tDiffuse;", "varying vec2 vUv;", "void main() {", "vec4 texel = texture2D( tDiffuse, vUv );", "gl_FragColor = opacity * texel;", "}"].join("\n") +}; +var _default = CopyShader; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/core/engine/effect-composer.js b/lib/core/engine/effect-composer.js new file mode 100755 index 0000000000..b169d69484 --- /dev/null +++ b/lib/core/engine/effect-composer.js @@ -0,0 +1,27 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = _default; + +var _composer = _interopRequireDefault(require("./composer")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _default(renderer, container) { + var composer = new _composer["default"](renderer); + + var updateSize = function updateSize() { + // TODO: Re-enable this when perf issues can be solved + // + // Rendering double the resolution of the screen can be really slow + // var pixelRatio = window.devicePixelRatio; + var pixelRatio = 1; + composer.setSize(container.clientWidth * pixelRatio, container.clientHeight * pixelRatio); + }; + + window.addEventListener('resize', updateSize, false); + updateSize(); + return composer; +} \ No newline at end of file diff --git a/lib/core/engine/index.js b/lib/core/engine/index.js new file mode 100644 index 0000000000..d80ee06b73 --- /dev/null +++ b/lib/core/engine/index.js @@ -0,0 +1,110 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _wolfy87Eventemitter = _interopRequireDefault(require("wolfy87-eventemitter")); + +var THREE = _interopRequireWildcard(require("../three")); + +var _scene = _interopRequireDefault(require("./scene")); + +var _camera = _interopRequireDefault(require("./camera")); + +var _renderer = _interopRequireDefault(require("./renderer")); + +var _picking = _interopRequireDefault(require("./picking/picking")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Engine = +/*#__PURE__*/ +function (_EventEmitter) { + _inherits(Engine, _EventEmitter); + + function Engine(container, world) { + var _this; + + _classCallCheck(this, Engine); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(Engine).call(this)); + _this._scene = _scene["default"]; + _this._camera = new _camera["default"](container).camera; + _this._renderer = new _renderer["default"](container).renderer; + _this._world = world; // 地图场景实例 + // for MapBox + + _this.world = new THREE.Group(); + + _this._scene.add(_this.world); + + _this._picking = (0, _picking["default"])(_this._world, _this._renderer, _this._camera); + _this.clock = new THREE.Clock(); + _this.composerLayers = []; + return _this; + } + + _createClass(Engine, [{ + key: "_initPostProcessing", + value: function _initPostProcessing() { + this.composerLayers.forEach(function (layer) { + layer.visible && layer.render(); + }); + } + }, { + key: "update", + value: function update() { + this._renderer.clear(); + + this._renderer.render(this._scene, this._camera); + + this._initPostProcessing(); + } + }, { + key: "destroy", + value: function destroy() {} // 渲染第三方Scene对象 + + }, { + key: "renderScene", + value: function renderScene(scene) { + this._renderer.render(scene, this._camera); + } + }, { + key: "run", + value: function run() { + this.update(); + this.engineID = requestAnimationFrame(this.run.bind(this)); + } + }, { + key: "stop", + value: function stop() { + cancelAnimationFrame(this.engineID); + } + }]); + + return Engine; +}(_wolfy87Eventemitter["default"]); + +exports["default"] = Engine; \ No newline at end of file diff --git a/lib/core/engine/mask-pass.js b/lib/core/engine/mask-pass.js new file mode 100755 index 0000000000..22a4d2171c --- /dev/null +++ b/lib/core/engine/mask-pass.js @@ -0,0 +1,74 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ClearMaskPass = exports["default"] = void 0; + +var THREE = _interopRequireWildcard(require("../three")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +// jscs:disable + +/* eslint-disable */ + +/** + * @author alteredq / http://alteredqualia.com/ + */ +var MaskPass = function MaskPass(scene, camera) { + this.scene = scene; + this.camera = camera; + this.enabled = true; + this.clear = true; + this.needsSwap = false; + this.inverse = false; +}; + +MaskPass.prototype = { + render: function render(renderer, writeBuffer, readBuffer, delta) { + var context = renderer.context; // don't update color or depth + + context.colorMask(false, false, false, false); + context.depthMask(false); // set up stencil + + var writeValue, clearValue; + + if (this.inverse) { + writeValue = 0; + clearValue = 1; + } else { + writeValue = 1; + clearValue = 0; + } + + context.enable(context.STENCIL_TEST); + context.stencilOp(context.REPLACE, context.REPLACE, context.REPLACE); + context.stencilFunc(context.ALWAYS, writeValue, 0xffffffff); + context.clearStencil(clearValue); // draw into the stencil buffer + + renderer.render(this.scene, this.camera, readBuffer, this.clear); + renderer.render(this.scene, this.camera, writeBuffer, this.clear); // re-enable update of color and depth + + context.colorMask(true, true, true, true); + context.depthMask(true); // only render where stencil is set to 1 + + context.stencilFunc(context.EQUAL, 1, 0xffffffff); // draw if == 1 + + context.stencilOp(context.KEEP, context.KEEP, context.KEEP); + } +}; + +var ClearMaskPass = function ClearMaskPass() { + this.enabled = true; +}; + +exports.ClearMaskPass = ClearMaskPass; +ClearMaskPass.prototype = { + render: function render(renderer, writeBuffer, readBuffer, delta) { + var context = renderer.context; + context.disable(context.STENCIL_TEST); + } +}; +var _default = MaskPass; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/core/engine/picking/picking.js b/lib/core/engine/picking/picking.js new file mode 100755 index 0000000000..5747d3e64e --- /dev/null +++ b/lib/core/engine/picking/picking.js @@ -0,0 +1,250 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = _default; + +var _pickingScene = _interopRequireDefault(require("./pickingScene")); + +var THREE = _interopRequireWildcard(require("../../three")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var nextId = 1; + +var Picking = +/*#__PURE__*/ +function () { + function Picking(world, renderer, camera) { + _classCallCheck(this, Picking); + + this._world = world; + this._renderer = renderer; + this._camera = camera; + this._pickingScene = _pickingScene["default"]; + this.world = new THREE.Group(); + + this._pickingScene.add(this.world); + + var size = this._renderer.getSize(); + + this._width = size.width; + this._height = size.height; + var parameters = { + minFilter: THREE.LinearFilter, + magFilter: THREE.LinearFilter, + format: THREE.RGBAFormat, + stencilBuffer: false, + depthBuffer: true + }; + this._pickingTexture = new THREE.WebGLRenderTarget(this._width, this._height, parameters); + this._nextId = 1; + + this._resizeTexture(); + + this._initEvents(); + } + + _createClass(Picking, [{ + key: "_initEvents", + value: function _initEvents() { + this._resizeHandler = this._resizeTexture.bind(this); + window.addEventListener('resize', this._resizeHandler, false); + } + }, { + key: "pickdata", + value: function pickdata(event) { + var point = { + x: event.offsetX, + y: event.offsetY, + type: event.type + }; + var normalisedPoint = { + x: 0, + y: 0 + }; + normalisedPoint.x = point.x / this._width * 2 - 1; + normalisedPoint.y = -(point.y / this._height) * 2 + 1; + + this._pickAllObject(point, normalisedPoint); + } + }, { + key: "_resizeTexture", + value: function _resizeTexture() { + var size = this._renderer.getSize(); + + this._width = size.width; + this._height = size.height; + + this._pickingTexture.setSize(this._width, this._height); + + this._pixelBuffer = new Uint8Array(4 * this._width * this._height); + this._needUpdate = true; + } + }, { + key: "_update", + value: function _update(point) { + var texture = this._pickingTexture; + + this._renderer.render(this._pickingScene, this._camera, texture); + + this.pixelBuffer = new Uint8Array(4); + + this._renderer.readRenderTargetPixels(texture, point.x, this._height - point.y, 1, 1, this.pixelBuffer); + } + }, { + key: "_filterObject", + value: function _filterObject(id) { + this.world.children.forEach(function (object, index) { + index === id ? object.visible = true : object.visible = false; + }); + } + }, { + key: "_layerIsVisable", + value: function _layerIsVisable(object) { + var layers = this._world.getLayers(); + + var isVisable = false; + + for (var i = 0; i < layers.length; i++) { + var layer = layers[i]; + + if (object.name === layer.layerId) { + isVisable = layer.get('visible'); + break; + } + } + + return isVisable; + } + }, { + key: "_pickAllObject", + value: function _pickAllObject(point, normalisedPoint) { + var _this = this; + + this.world.children.forEach(function (object, index) { + if (!_this._layerIsVisable(object)) { + return; + } + + _this._filterObject(index); + + var item = _this._pick(point, normalisedPoint, object.name); + + item.type = point.type; + + _this._world.emit('pick', item); + + _this._world.emit('pick-' + object.name, item); + }); + } // _updateRender() { + // this._renderer.render(this._pickingScene, this._camera, this._pickingTexture); + // } + + }, { + key: "_pick", + value: function _pick(point, normalisedPoint, layerId) { + this._update(point); + + var id = this.pixelBuffer[2] * 255 * 255 + this.pixelBuffer[1] * 255 + this.pixelBuffer[0]; + + if (id === 16646655 || this.pixelBuffer[3] === 0) { + id = -999; // return; + } + + var _point2d = { + x: point.x, + y: point.y + }; + var item = { + layerId: layerId, + featureId: id, + point2d: _point2d + }; + return item; + } // Add mesh to picking scene + // + // Picking ID should already be added as an attribute + + }, { + key: "add", + value: function add(mesh) { + this.world.add(mesh); + this._needUpdate = true; + } // Remove mesh from picking scene + + }, { + key: "remove", + value: function remove(mesh) { + this.world.remove(mesh); + this._needUpdate = true; + } // Returns next ID to use for picking + + }, { + key: "getNextId", + value: function getNextId() { + return nextId++; + } + }, { + key: "destroy", + value: function destroy() { + var _this2 = this; + + // TODO: Find a way to properly remove these listeners as they stay + // active at the moment + window.removeEventListener('resize', this._resizeHandler, false); + + this._envents.forEach(function (event) { + _this2._world._container.removeEventListener(event[0], event[1], false); + }); + + if (this._pickingScene.children) { + // Remove everything else in the layer + var child; + + for (var i = this._pickingScene.children.length - 1; i >= 0; i--) { + child = this._pickingScene.children[i]; + + if (!child) { + continue; + } + + this._pickingScene.remove(child); + + if (child.material) { + if (child.material.map) { + child.material.map.dispose(); + child.material.map = null; + } + + child.material.dispose(); + child.material = null; + } + } + } + + this._pickingScene = null; + this._pickingTexture = null; + this._pixelBuffer = null; + this._world = null; + this._renderer = null; + this._camera = null; + } + }]); + + return Picking; +}(); // Initialise without requiring new keyword + + +function _default(world, renderer, camera, scene) { + return new Picking(world, renderer, camera, scene); +} \ No newline at end of file diff --git a/lib/core/engine/picking/pickingMaterial.js b/lib/core/engine/picking/pickingMaterial.js new file mode 100755 index 0000000000..4c37aa2fea --- /dev/null +++ b/lib/core/engine/picking/pickingMaterial.js @@ -0,0 +1,30 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = PickingMaterial; + +var _material = _interopRequireDefault(require("../../../geom/material/material")); + +var _picking_frag = _interopRequireDefault(require("./picking_frag.glsl")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +// import picking_vert from './picking_vert.glsl'; +function PickingMaterial(options) { + var material = new _material["default"]({ + uniforms: { + u_zoom: { + value: options.u_zoom || 1 + } + }, + defines: { + PICK: true + }, + vertexShader: options.vs, + fragmentShader: _picking_frag["default"], + transparent: false + }); + return material; +} \ No newline at end of file diff --git a/lib/core/engine/picking/pickingScene.js b/lib/core/engine/picking/pickingScene.js new file mode 100755 index 0000000000..d557a6e100 --- /dev/null +++ b/lib/core/engine/picking/pickingScene.js @@ -0,0 +1,19 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var THREE = _interopRequireWildcard(require("../../three")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +// This can be imported from anywhere and will still reference the same scene, +// though there is a helper reference in Engine.pickingScene +var _default = function () { + var scene = new THREE.Scene(); + return scene; +}(); + +exports["default"] = _default; \ No newline at end of file diff --git a/lib/core/engine/render-pass.js b/lib/core/engine/render-pass.js new file mode 100644 index 0000000000..d59e761727 --- /dev/null +++ b/lib/core/engine/render-pass.js @@ -0,0 +1,52 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var THREE = _interopRequireWildcard(require("../three")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +// jscs:disable + +/* eslint-disable */ + +/** + * @author alteredq / http://alteredqualia.com/ + */ +var RenderPass = function RenderPass(scene, camera, overrideMaterial, clearColor, clearAlpha) { + this.scene = scene; + this.camera = camera; + this.overrideMaterial = overrideMaterial; + this.clearColor = clearColor; + this.clearAlpha = clearAlpha !== undefined ? clearAlpha : 1; + this.oldClearColor = new THREE.Color(); + this.oldClearAlpha = 1; + this.enabled = true; + this.clear = false; + this.needsSwap = false; +}; + +RenderPass.prototype = { + render: function render(renderer, writeBuffer, readBuffer, delta) { + this.scene.overrideMaterial = this.overrideMaterial; + + if (this.clearColor) { + this.oldClearColor.copy(renderer.getClearColor()); + this.oldClearAlpha = renderer.getClearAlpha(); + renderer.setClearColor(this.clearColor, this.clearAlpha); + } + + renderer.render(this.scene, this.camera, readBuffer, this.clear); + + if (this.clearColor) { + renderer.setClearColor(this.oldClearColor, this.oldClearAlpha); + } + + this.scene.overrideMaterial = null; + } +}; +var _default = RenderPass; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/core/engine/renderer.js b/lib/core/engine/renderer.js new file mode 100644 index 0000000000..8143f7b478 --- /dev/null +++ b/lib/core/engine/renderer.js @@ -0,0 +1,56 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var THREE = _interopRequireWildcard(require("../three")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var Renderer = +/*#__PURE__*/ +function () { + function Renderer(container) { + _classCallCheck(this, Renderer); + + this.container = container; + this.initRender(); + this.updateSize(); + window.addEventListener('resize', this.updateSize.bind(this), false); + } + + _createClass(Renderer, [{ + key: "initRender", + value: function initRender() { + this.renderer = new THREE.WebGLRenderer({ + antialias: true, + alpha: true, + autoClear: false + }); + this.renderer.setClearColor(0xff0000, 0.0); + this.pixelRatio = window.devicePixelRatio; + this.renderer.setPixelRatio(this.pixelRatio); + this.renderer.gammaInput = true; + this.renderer.gammaOutput = true; + this.renderer.shadowMap.enabled = false; + this.container.appendChild(this.renderer.domElement); + } + }, { + key: "updateSize", + value: function updateSize() { + this.renderer.setSize(this.container.clientWidth, this.container.clientHeight); + } + }]); + + return Renderer; +}(); + +exports["default"] = Renderer; \ No newline at end of file diff --git a/lib/core/engine/renderpass.js b/lib/core/engine/renderpass.js new file mode 100644 index 0000000000..f1d4f8e59a --- /dev/null +++ b/lib/core/engine/renderpass.js @@ -0,0 +1,107 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var THREE = _interopRequireWildcard(require("../three")); + +var _util = _interopRequireDefault(require("../../util")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var RenderPass = +/*#__PURE__*/ +function () { + function RenderPass(cfg) { + _classCallCheck(this, RenderPass); + + var defaultCfg = this._getDefaultCfg(); + + _util.default.assign(this, defaultCfg, cfg); + + this._init(); + } + + _createClass(RenderPass, [{ + key: "_getDefaultCfg", + value: function _getDefaultCfg() { + var defaultRenderCfg = { + minFilter: THREE.NearestFilter, + magFilter: THREE.NearestFilter, + format: THREE.RGBAFormat, + stencilBuffer: false, + depthBuffer: false + }; + return { + size: null, + renderCfg: defaultRenderCfg, + clearColor: 0x000000, + clearAlpha: 0.0, + renderToScreen: false, + renderTarget: true + }; + } + }, { + key: "_init", + value: function _init() { + this.scene = new THREE.Scene(); + + if (this.renderTarget) { + var size = this.size ? this.size : this.renderer.getSize(); + this.renderTarget = new THREE.WebGLRenderTarget(size.width, size.height, this.renderCfg); + this.texture = this.renderTarget.texture; + } + + this.originClearColor = this.renderer.getClearColor(); + this.originClearAlpha = this.renderer.getClearAlpha(); + } + }, { + key: "setSize", + value: function setSize(width, height) { + this.size = { + width: width, + height: height + }; + this.renderTarget && this.renderTarget.setSize(width, height); + } + }, { + key: "add", + value: function add(mesh) { + this.scene.add(mesh); + } + }, { + key: "remove", + value: function remove(mesh) { + this.scene.remove(mesh); + } + }, { + key: "render", + value: function render() { + this.renderer.setClearColor(this.clearColor, this.clearAlpha); + + if (this.renderToScreen) { + this.renderer.setRenderTarget(null); + this.renderer.render(this.scene, this.camera); + } else { + this.renderTarget && this.renderer.render(this.scene, this.camera, this.renderTarget, true); + this.renderer.setRenderTarget(null); + } + + this.renderer.setClearColor(this.originClearColor, this.originClearAlpha); + } + }]); + + return RenderPass; +}(); + +exports.default = RenderPass; \ No newline at end of file diff --git a/lib/core/engine/scene.js b/lib/core/engine/scene.js new file mode 100644 index 0000000000..ba9cd0b2a0 --- /dev/null +++ b/lib/core/engine/scene.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var THREE = _interopRequireWildcard(require("../three")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +var _default = function () { + var scene = new THREE.Scene(); + return scene; +}(); + +exports["default"] = _default; \ No newline at end of file diff --git a/lib/core/engine/shader-pass.js b/lib/core/engine/shader-pass.js new file mode 100644 index 0000000000..95523cb72b --- /dev/null +++ b/lib/core/engine/shader-pass.js @@ -0,0 +1,64 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var THREE = _interopRequireWildcard(require("../three")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +// jscs:disable + +/* eslint-disable */ + +/** + * @author alteredq / http://alteredqualia.com/ + */ +var ShaderPass = function ShaderPass(shader, textureID) { + this.textureID = textureID !== undefined ? textureID : "tDiffuse"; + + if (shader instanceof THREE.ShaderMaterial) { + this.uniforms = shader.uniforms; + this.material = shader; + } else if (shader) { + this.uniforms = THREE.UniformsUtils.clone(shader.uniforms); + this.material = new THREE.ShaderMaterial({ + defines: shader.defines || {}, + uniforms: this.uniforms, + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader + }); + } + + this.renderToScreen = false; + this.enabled = true; + this.needsSwap = true; + this.clear = true; + this.camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1); + this.scene = new THREE.Scene(); + this.quad = new THREE.Mesh(new THREE.PlaneBufferGeometry(2, 2), null); + this.scene.add(this.quad); +}; + +ShaderPass.prototype = { + render: function render(renderer, writeBuffer, readBuffer, delta) { + if (this.uniforms[this.textureID]) { + this.uniforms[this.textureID].value = readBuffer.texture; + } + + renderer.autoClear = false; + this.quad.material = this.material; + + if (this.renderToScreen) { + renderer.render(this.scene, this.camera); + } else { + renderer.render(this.scene, this.camera, writeBuffer, this.clear); + } + + renderer.autoClear = true; + } +}; +var _default = ShaderPass; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/core/engine/shaderPass.js b/lib/core/engine/shaderPass.js new file mode 100644 index 0000000000..253c386f11 --- /dev/null +++ b/lib/core/engine/shaderPass.js @@ -0,0 +1,79 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var THREE = _interopRequireWildcard(require("../three")); + +var _renderpass = _interopRequireDefault(require("./renderpass")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var ShaderPass = +/*#__PURE__*/ +function (_RenderPass) { + _inherits(ShaderPass, _RenderPass); + + function ShaderPass(cfg) { + _classCallCheck(this, ShaderPass); + + return _possibleConstructorReturn(this, _getPrototypeOf(ShaderPass).call(this, _objectSpread({ + size: { + width: 2, + height: 2 + } + }, cfg))); + } + + _createClass(ShaderPass, [{ + key: "_init", + value: function _init(cfg) { + _get(_getPrototypeOf(ShaderPass.prototype), "_init", this).call(this, cfg); + + this.camera = new THREE.OrthographicCamera(-this.size.width / 2, this.size.width / 2, this.size.height / 2, -this.size.height / 2, 0, 100); + this.material = new THREE.ShaderMaterial(_objectSpread({ + vertexShader: this.vertexShader, + fragmentShader: this.fragmentShader, + uniforms: this.uniforms + }, this.matCfg)); + this.quad = new THREE.Mesh(new THREE.PlaneBufferGeometry(this.size.width, this.size.height), this.material); + this.quad.frustumCulled = false; // Avoid getting clipped + + this.scene.add(this.quad); + } + }]); + + return ShaderPass; +}(_renderpass.default); + +exports.default = ShaderPass; \ No newline at end of file diff --git a/lib/core/extend/windframebuffer/drawMaterial.js b/lib/core/extend/windframebuffer/drawMaterial.js new file mode 100644 index 0000000000..b1cd69f286 --- /dev/null +++ b/lib/core/extend/windframebuffer/drawMaterial.js @@ -0,0 +1,50 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = DrawMaterial; + +var _material = _interopRequireDefault(require("../../../geom/material/material")); + +var _draw_vert = _interopRequireDefault(require("./draw_vert.glsl")); + +var _draw_frag = _interopRequireDefault(require("./draw_frag.glsl")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function DrawMaterial(options) { + var material = new _material.default({ + uniforms: { + u_color_ramp: { + value: options.u_color_ramp + }, + u_wind_max: { + value: options.u_wind_max + }, + u_particles_res: { + value: options.u_particles_res + }, + u_wind_min: { + value: options.u_wind_min + }, + u_opacity: { + value: options.u_opacity + }, + u_wind: { + value: options.u_wind + }, + u_particles: { + value: options.u_particles + }, + u_bbox: { + value: options.u_bbox + } + }, + vertexShader: _draw_vert.default, + fragmentShader: _draw_frag.default, + transparent: true + }); // material.blending = THREE.AdditiveBlending + + return material; +} \ No newline at end of file diff --git a/lib/core/extend/windframebuffer/draw_geometry.js b/lib/core/extend/windframebuffer/draw_geometry.js new file mode 100644 index 0000000000..2775f4800b --- /dev/null +++ b/lib/core/extend/windframebuffer/draw_geometry.js @@ -0,0 +1,85 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _r3Base = require("@ali/r3-base"); + +var _r3Geometry = require("@ali/r3-geometry"); + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +/** + * 创建点图层几何体 + */ +var DrawGeometry = +/*#__PURE__*/ +function (_BufferGeometry) { + _inherits(DrawGeometry, _BufferGeometry); + + function DrawGeometry(opts) { + var _this; + + _classCallCheck(this, DrawGeometry); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(DrawGeometry).call(this, opts.name)); + _this._index = opts.index; + _this.mode = _r3Base.DrawMode.POINTS; + _this.primitive.indexType = _r3Base.DataType.UNSIGNED_INT; + + _this.initialize(); + + return _this; + } + /** + * 构造多边形数据 + * @private + */ + + + _createClass(DrawGeometry, [{ + key: "initialize", + value: function initialize() { + var _this2 = this; + + _get(_getPrototypeOf(DrawGeometry.prototype), "initialize", this).call(this, [{ + semantic: 'INDEX', + size: 1, + type: _r3Base.DataType.FLOAT, + normalized: false + }], this._index.length); + + this._index.forEach(function (vert, j) { + _this2.setVertexValues(j, { + INDEX: [vert] + }); + }); + } + }]); + + return DrawGeometry; +}(_r3Geometry.BufferGeometry); + +exports.default = DrawGeometry; \ No newline at end of file diff --git a/lib/core/image.js b/lib/core/image.js new file mode 100644 index 0000000000..1b93c014f4 --- /dev/null +++ b/lib/core/image.js @@ -0,0 +1,137 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var THREE = _interopRequireWildcard(require("./three")); + +var _wolfy87Eventemitter = _interopRequireDefault(require("wolfy87-eventemitter")); + +var _ajax = require("../util/ajax"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +// 将图片标注绘制在512*512的画布上,每个大小 64*64 支持 64种图片 +var LoadImage = +/*#__PURE__*/ +function (_EventEmitter) { + _inherits(LoadImage, _EventEmitter); + + function LoadImage() { + var _this; + + _classCallCheck(this, LoadImage); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(LoadImage).call(this)); + var pixelRatio = window.devicePixelRatio || 1; + _this.imageWidth = 64 * pixelRatio; + _this.canvas = document.createElement('canvas'); + _this.canvas.style.cssText += 'height: 512px;width: 512px;'; + _this.canvas.width = _this.imageWidth * 8; + _this.canvas.height = _this.imageWidth * 8; + _this.ctx = _this.canvas.getContext('2d'); + _this.images = []; + _this.imagesCount = 0; + _this.imagePos = {}; + _this.imagesIds = []; + return _this; + } + + _createClass(LoadImage, [{ + key: "addImage", + value: function addImage(id, opt) { + var _this2 = this; + + this.imagesCount++; + this.imagesIds.push(id); + var imageCount = this.imagesCount; + var x = imageCount % 8 * this.imageWidth; + var y = parseInt(imageCount / 8) * this.imageWidth; + this.imagePos[id] = { + x: x / this.canvas.width, + y: y / this.canvas.height + }; + this.texture = new THREE.Texture(this.canvas); + + if (typeof opt === 'string') { + (0, _ajax.getImage)({ + url: opt + }, function (err, img) { + img.id = id; + + _this2.images.push(img); + + _this2.ctx.drawImage(img, x, y, _this2.imageWidth, _this2.imageWidth); + + _this2.texture.magFilter = THREE.LinearFilter; + _this2.texture.minFilter = THREE.LinearFilter; + _this2.texture.needsUpdate = true; + + if (_this2.images.length === _this2.imagesCount) { + _this2.emit('imageLoaded'); + } + }); + } else { + var width = opt.width, + height = opt.height, + channels = opt.channels; + var data = new Uint8Array(width * height * channels); + var image = new Image(); + image.width = width; + image.height = height; + image.data = data; + image.id = id; + this.images.push(image); + this.ctx.drawImage(image, x, y, this.imageWidth, this.imageWidth); + this.texture = new THREE.CanvasTexture(this.canvas); + this.imagePos[id] = { + x: x >> 9, + y: y >> 9 + }; + + if (this.images.length === this.imagesCount) { + this.emit('imageLoaded'); + } + } + } + }, { + key: "removeImage", + value: function removeImage() {} // todo + // drawAllImages() { + // this.images.forEach((item, index) => { + // const x = parseInt(index / 8) * 64; + // const y = index % 8 * 64; + // this.ctx.drawImage(item, x, y, 64, 64); + // }); + // this.texture = new CanvasTexture(this.canvas); + // this.texture.needsUpdate=true; + // } + + }]); + + return LoadImage; +}(_wolfy87Eventemitter["default"]); + +exports["default"] = LoadImage; \ No newline at end of file diff --git a/lib/core/layer.js b/lib/core/layer.js new file mode 100644 index 0000000000..f08e713bb4 --- /dev/null +++ b/lib/core/layer.js @@ -0,0 +1,1010 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("./base")); + +var THREE = _interopRequireWildcard(require("./three")); + +var _colorUtil = _interopRequireDefault(require("../attr/color-util")); + +var _index = _interopRequireDefault(require("./controller/index")); + +var _source2 = _interopRequireDefault(require("./source")); + +var _diff = _interopRequireDefault(require("../util/diff")); + +var _object3dUtil = require("../util/object3d-util"); + +var _util = _interopRequireDefault(require("../util")); + +var _global = _interopRequireDefault(require("../global")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var id = 1; + +function parseFields(field) { + if (_util["default"].isArray(field)) { + return field; + } + + if (_util["default"].isString(field)) { + return field.split('*'); + } + + return [field]; +} + +var Layer = +/*#__PURE__*/ +function (_Base) { + _inherits(Layer, _Base); + + _createClass(Layer, [{ + key: "getDefaultCfg", + value: function getDefaultCfg() { + return { + visible: true, + zIndex: 0, + type: '', + minZoom: 0, + maxZoom: 22, + rotation: 0, + option: {}, + attrOptions: {}, + scaleOptions: {}, + preScaleOptions: null, + scales: {}, + attrs: {}, + // 样式配置项 + styleOptions: { + stroke: [1, 1, 1, 1], + strokeWidth: 1.0, + opacity: 1.0, + strokeOpacity: 1.0, + texture: false, + blending: 'normal' + }, + destroyed: false, + // 选中时的配置项 + selectedOptions: null, + // active 时的配置项 + activedOptions: { + fill: [1.0, 0, 0, 1.0] + }, + interactions: {}, + animateOptions: { + enable: false + } + }; + } + }]); + + function Layer(scene, cfg) { + var _this; + + _classCallCheck(this, Layer); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(Layer).call(this, cfg)); + _this.scene = scene; + _this.map = scene.map; + _this._object3D = new THREE.Object3D(); + _this._pickObject3D = new THREE.Object3D(); + _this._object3D.visible = _this.get('visible'); + _this._object3D.renderOrder = _this.get('zIndex') || 0; + _this._mapEventHandlers = []; + + var layerId = _this._getUniqueId(); + + _this.set('layerId', layerId); + + _this.set('mapType', _this.scene.mapType); + + _this.layerId = layerId; + _this._activeIds = null; + var world = scene._engine.world; + world.add(_this._object3D); + _this.layerMesh = null; + _this.layerLineMesh = null; + + _this._initEvents(); + + return _this; + } + /** + * 将图层添加加到 Object + * @param {*} object three 物体 + * @param {*} type mesh类型是区别是填充还是边线 + */ + + + _createClass(Layer, [{ + key: "add", + value: function add(object) { + var _this2 = this; + + var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'fill'; + + // composer合图层绘制 + if (object.type === 'composer') { + this._object3D = object; + + this.scene._engine.composerLayers.push(object); + + setTimeout(function () { + return _this2.scene._engine.update(); + }, 500); + return; + } + + type === 'fill' ? this.layerMesh = object : this.layerLineMesh = object; + + this._visibleWithZoom(); + + object.onBeforeRender = function () { + // 每次渲染前改变状态 + var zoom = _this2.scene.getZoom(); + + (0, _object3dUtil.updateObjecteUniform)(_this2._object3D, { + u_time: _this2.scene._engine.clock.getElapsedTime(), + u_zoom: zoom + }); + + _this2.preRender(); + }; + + object.onAfterRender = function () { + // 每次渲染后改变状态 + _this2.afterRender(); + }; + + this._object3D.add(object); + + if (type === 'fill') { + this.get('pickingController').addPickMesh(object); + } + + this.scene._engine.update(); // setTimeout(() => this.scene._engine.update(), 200); + + } + }, { + key: "remove", + value: function remove(object) { + if (object.type === 'composer') { + this.scene._engine.composerLayers = this.scene._engine.composerLayers.filter(function (layer) { + return layer !== object; + }); + return; + } + + this._object3D.remove(object); + } + }, { + key: "_getUniqueId", + value: function _getUniqueId() { + return id++; + } + }, { + key: "_visible", + value: function _visible(visible) { + this.set('visible', visible); + this._object3D.visible = this.get('visible'); + } // 兼容瓦片source,非瓦片source + + }, { + key: "source", + value: function source(data) { + var cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + // 根据Source类型判断,是不是瓦片图层 + if (this.scene.getTileSource(data)) { + this.set('layerType', 'tile'); + this.set('sourceOption', _objectSpread({ + id: data + }, cfg)); + this.scene.style.addLayer(this); // 初始化tiles + + this.tiles = new THREE.Object3D(); + + this._object3D.add(this.tiles); + + return this; + } + + if (data instanceof _source2["default"]) { + this.layerSource = data; + return this; + } + + cfg.data = data; + cfg.mapType = this.scene.mapType; + cfg.zoom = this.scene.getZoom(); + this.layerSource = new _source2["default"](cfg); + return this; + } + }, { + key: "color", + value: function color(field, values) { + this._createAttrOption('color', field, values, _global["default"].colors); + + return this; + } + }, { + key: "size", + value: function size(field, values) { + var fields = parseFields(field); + + if (fields.indexOf('zoom') !== -1) { + this._zoomScale = true; + } + + if (_util["default"].isArray(fields) && !values) values = fields; + + this._createAttrOption('size', field, values, _global["default"].size); + + return this; + } + }, { + key: "scale", + value: function scale(field, cfg) { + var options = this.get('scaleOptions'); + var scaleDefs = options; + + if (_util["default"].isObject(field)) { + _util["default"].mix(scaleDefs, field); + } else { + scaleDefs[field] = cfg; + } + + return this; + } + }, { + key: "shape", + value: function shape(field, values) { + if (field.split(':').length === 2) { + this.shapeType = field.split(':')[0]; + field = field.split(':')[1]; + } + + values === 'text' ? this.shapeType = values : null; + + this._createAttrOption('shape', field, values, _global["default"].shape); + + return this; + } + }, { + key: "pattern", + value: function pattern(field, values) { + this._createAttrOption('pattern', field, values, _global["default"].pattern); + + return this; + } + /** + * 是否允许使用默认的图形激活交互 + * @param {Boolean} enable 是否允许激活开关 + * @param {Object} cfg 激活的配置项 + * @return {Geom} 返回 geom 自身 + */ + + }, { + key: "active", + value: function active(enable, cfg) { + if (enable === false) { + this.set('allowActive', false); + } else if (_util["default"].isObject(enable) && enable.fill) { + this.set('allowActive', true); + if (enable.fill) enable.fill = _colorUtil["default"].color2RGBA(enable.fill); + this.set('activedOptions', enable); + } else { + this.set('allowActive', true); + this.set('activedOptions', cfg || { + fill: _colorUtil["default"].color2RGBA(_global["default"].activeColor) + }); + } + + return this; + } + }, { + key: "style", + value: function style(field, cfg) { + var colorItem = ['fill', 'stroke', 'color', 'baseColor', 'brightColor', 'windowColor']; + var styleOptions = this.get('styleOptions'); + + if (!styleOptions) { + styleOptions = {}; + this.set('styleOptions', styleOptions); + } + + if (_util["default"].isObject(field)) { + cfg = field; + field = null; + } + + var fields; + + if (field) { + fields = parseFields(field); + } + + styleOptions.fields = fields; + + _util["default"].assign(styleOptions, cfg); + + for (var item in cfg) { + if (colorItem.indexOf(item) !== -1 && styleOptions[item] !== 'none') { + styleOptions[item] = _colorUtil["default"].color2RGBA(styleOptions[item]); + } + } + + this.set('styleOptions', styleOptions); + return this; + } + }, { + key: "filter", + value: function filter(field, values) { + this._createAttrOption('filter', field, values, true); + + return this; + } + }, { + key: "animate", + value: function animate(field, cfg) { + var animateOptions = this.get('animateOptions'); + + if (!animateOptions) { + animateOptions = {}; + this.set('animateOptions', animateOptions); + } + + if (_util["default"].isObject(field)) { + cfg = field; + field = null; + } + + var fields; + + if (field) { + fields = parseFields(field); + } + + animateOptions.fields = fields; + + _util["default"].assign(animateOptions, cfg); + + this.set('animateOptions', animateOptions); + return this; + } + }, { + key: "fitBounds", + value: function fitBounds() { + var extent = this.layerSource.data.extent; + this.scene.fitBounds(extent); + } + }, { + key: "hide", + value: function hide() { + this._visible(false); + + return this; + } + }, { + key: "show", + value: function show() { + this._visible(true); + + return this; + } + }, { + key: "setData", + value: function setData(data, cfg) { + this.layerSource.setData(data, cfg); + this.repaint(); + } + }, { + key: "_createScale", + value: function _createScale(field) { + // TODO scale更新 + var scales = this.get('scales'); + var scale = scales[field]; + + if (!scale) { + scale = this.createScale(field); + scales[field] = scale; + } + + return scale; + } + }, { + key: "_setAttrOptions", + value: function _setAttrOptions(attrName, attrCfg) { + var options = this.get('attrOptions'); + + if (attrName === 'size' && this._zoomScale) { + attrCfg.zoom = this.map.getZoom(); + } + + options[attrName] = attrCfg; + } + }, { + key: "_createAttrOption", + value: function _createAttrOption(attrName, field, cfg, defaultValues) { + var attrCfg = {}; + attrCfg.field = field; + + if (cfg) { + if (_util["default"].isFunction(cfg)) { + attrCfg.callback = cfg; + } else { + attrCfg.values = cfg; + } + } else if (attrName !== 'color') { + attrCfg.values = defaultValues; + } + + this._setAttrOptions(attrName, attrCfg); + } + }, { + key: "_initControllers", + value: function _initControllers() { + var mappingCtr = new _index["default"].Mapping({ + layer: this + }); + var pickCtr = new _index["default"].Picking({ + layer: this + }); + var interactionCtr = new _index["default"].Interaction({ + layer: this + }); + this.set('mappingController', mappingCtr); + this.set('pickingController', pickCtr); + this.set('interacionController', interactionCtr); + } + }, { + key: "render", + value: function render() { + if (this.get('layerType') === 'tile') { + this.scene.style.update(this._attrs); + return this; + } + + this.init(); + + this.scene._engine.update(); + + return this; + } // 重绘 度量, 映射,顶点构建 + + }, { + key: "repaint", + value: function repaint() { + this.set('scales', {}); + var mappingCtr = new _index["default"].Mapping({ + layer: this + }); + this.set('mappingController', mappingCtr); // this._initAttrs(); + // this._mapping(); + + this.redraw(); + } // 初始化图层 + + }, { + key: "init", + value: function init() { + this._initControllers(); // this._initAttrs(); + + + this._updateDraw(); + } + }, { + key: "_initInteraction", + value: function _initInteraction() { + if (this.get('allowActive')) { + this.get('interacionController').addInteraction('active'); + } + } + }, { + key: "_initMapEvent", + value: function _initMapEvent() { + var _this3 = this; + + // zoomchange mapmove resize + var EVENT_TYPES = ['zoomchange', 'dragend']; + + _util["default"].each(EVENT_TYPES, function (type) { + var handler = _util["default"].wrapBehavior(_this3, "".concat(type)); + + _this3.map.on("".concat(type), handler); + + _this3._mapEventHandlers.push({ + type: type, + handler: handler + }); + }); + } + }, { + key: "clearMapEvent", + value: function clearMapEvent() { + var _this4 = this; + + var eventHandlers = this._mapEventHandlers; + + _util["default"].each(eventHandlers, function (eh) { + _this4.map.off(eh.type, eh.handler); + }); + } + }, { + key: "zoomchange", + value: function zoomchange(ev) { + // 地图缩放等级变化 + this._visibleWithZoom(ev); + } + }, { + key: "dragend", + value: function dragend() {} + }, { + key: "resize", + value: function resize() {} + }, { + key: "setActive", + value: function setActive(id, color) { + this._activeIds = id; + + if (!Array.isArray(color)) { + color = _colorUtil["default"].color2RGBA(color); + } + + (0, _object3dUtil.updateObjecteUniform)(this._object3D, { + u_activeColor: color, + u_activeId: id + }); + + this.scene._engine.update(); + } + }, { + key: "_addActiveFeature", + value: function _addActiveFeature(e) { + var featureId = e.featureId; + this._activeIds = featureId; + (0, _object3dUtil.updateObjecteUniform)(this._object3D, { + u_activeId: featureId + }); + } + }, { + key: "_setPreOption", + value: function _setPreOption() { + var nextAttrs = this.get('attrOptions'); + var nextStyle = this.get('styleOptions'); + this.set('preAttrOptions', _util["default"].clone(nextAttrs)); + this.set('preStyleOption', _util["default"].clone(nextStyle)); + } + }, { + key: "_updateDraw", + value: function _updateDraw() { + var preAttrs = this.get('preAttrOptions'); + var nextAttrs = this.get('attrOptions'); + var preStyle = this.get('preStyleOption'); + var nextStyle = this.get('styleOptions'); + + if (preAttrs === undefined && preStyle === undefined) { + // 首次渲染 + // this._mapping(); + // this._scaleByZoom(); + this._setPreOption(); + + this._initInteraction(); + + this._initMapEvent(); + + this.draw(); + return; + } + + if (!_util["default"].isEqual(preAttrs.color, nextAttrs.color)) { + this._updateAttributes(this.layerMesh); + } // 更新数据过滤 filter + + + if (!_util["default"].isEqual(preAttrs.filter, nextAttrs.filter)) { + // 更新color; + this._updateAttributes(this.layerMesh); + } // 更新Size + + + if (!_util["default"].isEqual(preAttrs.size, nextAttrs.size)) { + // 更新color; + this._updateSize(); + } // 更新形状 + + + if (!_util["default"].isEqual(preAttrs.shape, nextAttrs.shape)) { + // 更新color; + this._updateShape(); + } + + if (!_util["default"].isEqual(preStyle, nextStyle)) { + // 判断新增,修改,删除 + var newStyle = {}; + + _util["default"].each((0, _diff["default"])(preStyle, nextStyle), function (_ref) { + var type = _ref.type, + key = _ref.key, + value = _ref.value; + type !== 'remove' && (newStyle[key] = value); // newStyle[key] = type === 'remove' ? null : value; + }); + + this._updateStyle(newStyle); + } + + this._setPreOption(); + } + }, { + key: "_updateSize", + value: function _updateSize(zoom) { + var _this5 = this; + + var sizeOption = this.get('attrOptions').size; + var fields = parseFields(sizeOption.field); + var data = this.layerSource.data.dataArray; + if (!this.zoomSizeCache) this.zoomSizeCache = {}; + + if (!this.zoomSizeCache[zoom]) { + this.zoomSizeCache[zoom] = []; + + var _loop = function _loop(i) { + var params = fields.map(function (field) { + return data[i][field]; + }); + var indexZoom = fields.indexOf('zoom'); + indexZoom !== -1 ? params[indexZoom] = zoom : null; + + _this5.zoomSizeCache[zoom].push(sizeOption.callback.apply(sizeOption, _toConsumableArray(params))); + }; + + for (var i = 0; i < data.length; i++) { + _loop(i); + } + } + + this.emit('sizeUpdated', this.zoomSizeCache[zoom]); + } + }, { + key: "_updateStyle", + value: function _updateStyle(option) { + var newOption = {}; + + for (var key in option) { + newOption['u_' + key] = option[key]; + } + + (0, _object3dUtil.updateObjecteUniform)(this._object3D, newOption); + } + }, { + key: "_scaleByZoom", + value: function _scaleByZoom() { + var _this6 = this; + + if (this._zoomScale) { + this.map.on('zoomend', function () { + var zoom = _this6.map.getZoom(); + + _this6._updateSize(Math.floor(zoom)); + }); + } + } + }, { + key: "_initEvents", + value: function _initEvents() { + var _this7 = this; + + this.scene.on('pick-' + this.layerId, function (e) { + var featureId = e.featureId, + point2d = e.point2d, + type = e.type; // TODO 瓦片图层获取选中数据信息 + + var lnglat = _this7.scene.containerToLngLat(point2d); + + var feature = null; + var style = null; + + if (featureId !== -999) { + var res = _this7.getSelectFeature(featureId, lnglat); + + feature = res.feature; + style = res.style; + } + + var target = { + featureId: featureId, + feature: feature, + style: style, + pixel: point2d, + type: type, + lnglat: { + lng: lnglat.lng, + lat: lnglat.lat + } + }; + + if (featureId >= 0) { + // 拾取到元素,或者离开元素 + _this7.emit(type, target); + } + + if (featureId < 0 && _this7._activeIds >= 0) { + type = 'mouseleave'; + + _this7.emit(type, target); + } + + _this7._activeIds = featureId; + }); + } + }, { + key: "getSelectFeature", + value: function getSelectFeature(featureId) { + var feature = this.layerSource.getSelectFeature(featureId); + var style = this.layerData[featureId - 1]; + return { + feature: feature, + style: style + }; + } + /** + * 用于过滤数据 + * @param {*} object 更新颜色和数据过滤 + */ + + }, { + key: "_updateAttributes", + value: function _updateAttributes(object) { + var _this8 = this; + + this.get('mappingController').update(); + var filterData = this.layerData; + this._activeIds = null; // 清空选中元素 + + var colorAttr = object.geometry.attributes.a_color; + var pickAttr = object.geometry.attributes.pickingId; + pickAttr.array.forEach(function (id, index) { + id = Math.abs(id); + + var color = _toConsumableArray(_this8.layerData[id - 1].color); + + id = Math.abs(id); + var item = filterData[id - 1]; + + if (item.hasOwnProperty('filter') && item.filter === false) { + colorAttr.array[index * 4 + 0] = 0; + colorAttr.array[index * 4 + 1] = 0; + colorAttr.array[index * 4 + 2] = 0; + colorAttr.array[index * 4 + 3] = 0; + pickAttr.array[index] = -id; // 通过Id数据过滤 id<0 不显示 + } else { + colorAttr.array[index * 4 + 0] = color[0]; + colorAttr.array[index * 4 + 1] = color[1]; + colorAttr.array[index * 4 + 2] = color[2]; + colorAttr.array[index * 4 + 3] = color[3]; + pickAttr.array[index] = id; + } + }); + colorAttr.needsUpdate = true; + pickAttr.needsUpdate = true; + } + }, { + key: "_visibleWithZoom", + value: function _visibleWithZoom() { + if (this._object3D === null) return; + var zoom = this.scene.getZoom(); + var minZoom = this.get('minZoom'); + var maxZoom = this.get('maxZoom'); // z-fighting + + var offset = 0; + + if (this.type === 'point') { + offset = 5; + this.shapeType = 'text' && (offset = 10); + } else if (this.type === 'polyline' || this.type === 'line') { + offset = 2; + } else if (this.type === 'polygon') { + offset = 1; + } + + this._object3D.position && (this._object3D.position.z = offset * Math.pow(2, 20 - zoom)); + + if (zoom < minZoom || zoom >= maxZoom) { + this._object3D.visible = false; + } else if (this.get('visible')) { + this._object3D.visible = true; + } + } // 重新构建mesh + + }, { + key: "redraw", + value: function redraw() { + var _this9 = this; + + this._object3D.children.forEach(function (child) { + _this9._object3D.remove(child); + }); + + this.get('pickingController').removeAllMesh(); + this.draw(); + } // 更新mesh + + }, { + key: "updateDraw", + value: function updateDraw() {} + }, { + key: "styleCfg", + value: function styleCfg() {} + /** + * 重置高亮要素 + */ + + }, { + key: "_resetStyle", + value: function _resetStyle() { + this._activeIds = null; + (0, _object3dUtil.updateObjecteUniform)(this._object3D, { + u_activeId: 0 + }); + } + /** + * 销毁Layer对象 + */ + + }, { + key: "destroy", + value: function destroy() { + this.removeAllListeners(); + this.clearAllInteractions(); + this.clearMapEvent(); + + if (this._object3D.type === 'composer') { + this.remove(this._object3D); + return; + } + + if (this._object3D && this._object3D.children) { + var child; + + for (var i = 0; i < this._object3D.children.length; i++) { + child = this._object3D.children[i]; + + if (!child) { + continue; + } + + this.remove(child); + + if (child.geometry) { + // child.geometry.dispose(); + child.geometry = null; + } + + if (child.material) { + if (child.material.map) { + child.material.map.dispose(); + child.material.map = null; + } + + child.material.dispose(); + child.material = null; + } + + child = null; + } + } + + this.layerMesh.geometry = null; + this.layerMesh.material.dispose(); + this.layerMesh.material = null; + + if (this._pickingMesh) { + this._pickingMesh.children[0].geometry = null; + + this._pickingMesh.children[0].material.dispose(); + + this._pickingMesh.children[0].material = null; + } + + this._buffer = null; + this._object3D = null; + + this.scene._engine._scene.remove(this._object3D); + + this.layerData.length = 0; + this.layerSource = null; + + this.scene._engine._picking.remove(this._pickingMesh); + + this.destroyed = true; + } + /** + * 获取图例配置项 + * @param {*} field 字段 + * @param {*} type 图例类型 color, size + * @return {*} 图例配置项 + */ + + }, { + key: "getLegendCfg", + value: function getLegendCfg(field) { + var _this10 = this; + + var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'color'; + + // todo heatmap + if (this.type === 'heatmap' && this.shapeType === 'heatmap') { + return this.get('styleOptions').rampColors; + } + + var scales = this.get('scales'); + var scale = scales[field]; + var colorAttrs = this.get('attrs')[type]; + var lengendCfg = {}; + + if (scale) { + var ticks = scale.ticks; + lengendCfg.value = ticks; + lengendCfg.type = scale.type; + var values = ticks.map(function (value) { + var v = _this10._getAttrValues(colorAttrs, _defineProperty({}, field, value)); + + return type === 'color' ? _colorUtil["default"].colorArray2RGBA(v) : v; + }); + lengendCfg[type] = values; + } + + return lengendCfg; + } + }, { + key: "preRender", + value: function preRender() {} + }, { + key: "afterRender", + value: function afterRender() {} + }]); + + return Layer; +}(_base["default"]); + +exports["default"] = Layer; \ No newline at end of file diff --git a/lib/core/scene.js b/lib/core/scene.js new file mode 100644 index 0000000000..1d2e3a5642 --- /dev/null +++ b/lib/core/scene.js @@ -0,0 +1,279 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _engine = _interopRequireDefault(require("./engine")); + +var _layer = require("../layer"); + +var _base = _interopRequireDefault(require("./base")); + +var _image = _interopRequireDefault(require("./image")); + +var _fontManager = _interopRequireDefault(require("../geom/buffer/point/text/font-manager")); + +var _index = require("../map/index"); + +var _global = _interopRequireDefault(require("../global")); + +var _index2 = require("../interaction/index"); + +var _shader = require("../geom/shader"); + +var _style = _interopRequireDefault(require("./style")); + +var _crsEpsg = require("@antv/geo-coord/lib/geo/crs/crs-epsg3857"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Scene = +/*#__PURE__*/ +function (_Base) { + _inherits(Scene, _Base); + + _createClass(Scene, [{ + key: "getDefaultCfg", + value: function getDefaultCfg() { + return _global["default"].scene; + } + }]); + + function Scene(cfg) { + var _this; + + _classCallCheck(this, Scene); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(Scene).call(this, cfg)); + + _this._initMap(); + + _this.crs = _crsEpsg.epsg3857; // this._initAttribution(); // 暂时取消,后面作为组件去加载 + + _this.addImage(); + + _this.fontAtlasManager = new _fontManager["default"](); + _this._layers = []; + _this.animateCount = 0; + return _this; + } + + _createClass(Scene, [{ + key: "_initEngine", + value: function _initEngine(mapContainer) { + this._engine = new _engine["default"](mapContainer, this); + this.registerMapEvent(); // this._engine.run(); + + (0, _shader.compileBuiltinModules)(); + } // 为pickup场景添加 object 对象 + + }, { + key: "addPickMesh", + value: function addPickMesh(object) { + this._engine._picking.add(object); + } + }, { + key: "_initMap", + value: function _initMap() { + var _this2 = this; + + this.mapContainer = this.get('id'); + this.mapType = this.get('mapType') || 'amap'; + var MapProvider = (0, _index.getMap)(this.mapType); + var Map = new MapProvider(this._attrs); + Map.mixMap(this); + this._container = Map.container; + Map.on('mapLoad', function () { + _this2.map = Map.map; + + _this2._initEngine(Map.renderDom); + + Map.asyncCamera(_this2._engine); + + _this2.initLayer(); + + _this2._registEvents(); + + var hash = _this2.get('hash'); + + if (hash) { + var Ctor = (0, _index2.getInteraction)('hash'); + var interaction = new Ctor({ + layer: _this2 + }); + + interaction._onHashChange(); + } + + _this2.style = new _style["default"](_this2, {}); + + _this2.emit('loaded'); + + _this2._engine.update(); + }); + } + }, { + key: "initLayer", + value: function initLayer() { + var _this3 = this; + + var _loop = function _loop(key) { + Scene.prototype[key] = function (cfg) { + var layer = new _layer.LAYER_MAP[key](_this3, cfg); + + _this3._layers.push(layer); + + return layer; + }; + }; + + for (var key in _layer.LAYER_MAP) { + _loop(key); + } + } // 添加 Tile Source + + }, { + key: "addTileSource", + value: function addTileSource(id, Sourcecfg) { + this.style.addSource(id, Sourcecfg); + } + }, { + key: "getTileSource", + value: function getTileSource(id) { + return this.style.getSource(id); + } + }, { + key: "on", + value: function on(type, hander) { + if (this.map) { + this.map.on(type, hander); + } + + _get(_getPrototypeOf(Scene.prototype), "on", this).call(this, type, hander); + } + }, { + key: "off", + value: function off(type, hander) { + if (this.map) { + this.map.off(type, hander); + } + + _get(_getPrototypeOf(Scene.prototype), "off", this).call(this, type, hander); + } + }, { + key: "addImage", + value: function addImage() { + this.image = new _image["default"](); + } + }, { + key: "_initEvent", + value: function _initEvent() {} + }, { + key: "getLayers", + value: function getLayers() { + return this._layers; + } + }, { + key: "_addLayer", + value: function _addLayer() {} + }, { + key: "_registEvents", + value: function _registEvents() { + var _this4 = this; + + var events = ['mouseout', 'mouseover', 'mousemove', 'mousedown', 'mouseleave', 'mouseup', 'rightclick', 'click', 'dblclick']; + events.forEach(function (event) { + _this4._container.addEventListener(event, function (e) { + // 要素拾取 + e.pixel || (e.pixel = e.point); + requestAnimationFrame(function () { + _this4._engine._picking.pickdata(e); + }); + }, false); + }); + } + }, { + key: "removeLayer", + value: function removeLayer(layer) { + var layerIndex = this._layers.indexOf(layer); + + if (layerIndex > -1) { + this._layers.splice(layerIndex, 1); + } + + layer.destroy(); + layer = null; + } + }, { + key: "startAnimate", + value: function startAnimate() { + if (this.animateCount === 0) { + this.unRegsterMapEvent(); + + this._engine.run(); + } + + this.animateCount++; + } + }, { + key: "stopAnimate", + value: function stopAnimate() { + if (this.animateCount === 1) { + this._engine.stop(); + + this.registerMapEvent(); + } + + this.animateCount++; + } // 地图状态变化时更新可视化渲染 + + }, { + key: "registerMapEvent", + value: function registerMapEvent() { + var _this5 = this; + + this._updateRender = function () { + return _this5._engine.update(); + }; + + this.map.on('mousemove', this._updateRender); + this.map.on('mapmove', this._updateRender); + this.map.on('camerachange', this._updateRender); + } + }, { + key: "unRegsterMapEvent", + value: function unRegsterMapEvent() { + this.map.off('mousemove', this._updateRender); + this.map.off('mapmove', this._updateRender); + this.map.off('camerachange', this._updateRender); + } + }]); + + return Scene; +}(_base["default"]); + +exports["default"] = Scene; \ No newline at end of file diff --git a/lib/core/source.js b/lib/core/source.js new file mode 100644 index 0000000000..68e93c9469 --- /dev/null +++ b/lib/core/source.js @@ -0,0 +1,274 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("./base")); + +var _source = require("../source"); + +var _cluster = require("../source/transform/cluster"); + +var _geo = require("../util/geo"); + +var _util = require("@antv/util"); + +var _index = require("../map/index"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Source = +/*#__PURE__*/ +function (_Base) { + _inherits(Source, _Base); + + _createClass(Source, [{ + key: "getDefaultCfg", + value: function getDefaultCfg() { + return { + data: null, + defs: {}, + parser: {}, + transforms: [], + scaledefs: {}, + scales: {}, + options: {} + }; + } + }]); + + function Source(cfg) { + var _this; + + _classCallCheck(this, Source); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(Source).call(this, cfg)); + + var transform = _this.get('transforms'); + + _this._transforms = transform || []; + var mapType = _this.get('mapType') || 'AMap'; + _this.projectFlat = (0, _index.getMap)(mapType).project; // 数据解析 + + _this._init(); + + return _this; + } + + _createClass(Source, [{ + key: "_init", + value: function _init() { + this._excuteParser(); + + var isCluster = this.get('isCluster') || false; + isCluster && this._executeCluster(); // 数据转换 统计,聚合,分类 + + this._executeTrans(); // 坐标转换 + + + if (!this.get('projected')) { + this._projectCoords(); + } + } + }, { + key: "setData", + value: function setData(data) { + var cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + Object.assign(this._attrs, cfg); + var transform = this.get('transforms'); + this._transforms = transform || []; + this.set('data', data); + + this._init(); + } // 数据更新 + + }, { + key: "updateTransfrom", + value: function updateTransfrom(cfg) { + var transforms = cfg.transforms; + this._transforms = transforms; + this.data = (0, _util.clone)(this.originData); + + this._executeTrans(); + + this._projectCoords(); + } + }, { + key: "_excuteParser", + value: function _excuteParser() { + var parser = this.get('parser'); + var _parser$type = parser.type, + type = _parser$type === void 0 ? 'geojson' : _parser$type; + var data = this.get('data'); + this.originData = (0, _source.getParser)(type)(data, parser); // this.data = { + // dataArray: clone(this.originData.dataArray) + // }; // TODO 关闭数据备份 + + this.data = this.originData; + + if (this.data !== null && !this.get('projected')) { + this.data.extent = (0, _geo.extent)(this.data.dataArray); + } + } + /** + * 数据统计 + */ + + }, { + key: "_executeTrans", + value: function _executeTrans() { + var _this2 = this; + + var trans = this._transforms; + trans.forEach(function (tran) { + var type = tran.type; + var data = (0, _source.getTransform)(type)(_this2.data, tran); + Object.assign(_this2.data, data); + }); + this._transforms = trans; + } + }, { + key: "transform", + value: function transform(option) { + var data = (0, _source.getTransform)(option.type)(this.data, option); + Object.assign(this.data, data); + } + }, { + key: "_executeCluster", + value: function _executeCluster() { + var clusterCfg = this.get('Cluster') || {}; + var zoom = this.get('zoom'); + clusterCfg.zoom = Math.floor(zoom); + this.set('cluster', clusterCfg); + var clusterData = (0, _cluster.cluster)(this.data, clusterCfg); + this.data = clusterData.data; + this.pointIndex = clusterData.pointIndex; + } + }, { + key: "updateCusterData", + value: function updateCusterData(zoom, bbox) { + var clusterPoint = this.pointIndex.getClusters(bbox, zoom); + this.data.dataArray = (0, _cluster.formatData)(clusterPoint); + var clusterCfg = this.get('Cluster') || {}; + clusterCfg.zoom = Math.floor(zoom); + clusterCfg.bbox = bbox; + this.set('cluster', clusterCfg); + + this._projectCoords(); + } + }, { + key: "_projectCoords", + value: function _projectCoords() { + var _this3 = this; + + if (this.data === null) { + return; + } + + this.data.dataArray.forEach(function (data) { + // data.coordinates = this._coordProject(data.coordinates); + data.coordinates = (0, _geo.tranfrormCoord)(data.coordinates, _this3._coorConvert.bind(_this3)); + }); + } + }, { + key: "_getCoord", + value: function _getCoord(geo) { + if (geo.geometry) { + // GeoJSON feature + geo = geo.geometry.coordinates; + } else if (geo.coordinates) { + // GeoJSON geometry + geo = geo.coordinates; + } + + return geo; + } + }, { + key: "_coordProject", + value: function _coordProject(geo) { + var _this4 = this; + + if (Array.isArray(geo[0][0])) { + return geo.map(function (coor) { + return _this4._coordProject(coor); + }); + } + + if (!Array.isArray(geo[0])) { + return this._coorConvert(geo); + } + + return geo.map(function (coor) { + return _this4._coorConvert(coor); + }); + } + }, { + key: "_coorConvert", + value: function _coorConvert(geo) { + var ll = this.projectFlat(geo); + return [ll.x, ll.y, geo[2] || 0]; + } + }, { + key: "getSelectFeature", + value: function getSelectFeature(featureId) { + var data = this.get('data'); // 如果是GeoJSON 数据返回原数 + // 颜色编码从1开始,要素索引从0开始,所以颜色转变要素需要减1 + + var isCluster = this.get('isCluster') || false; + return data.features && !isCluster ? data.features[featureId - 1] : this.data.dataArray[featureId - 1]; + } + }, { + key: "getSeletFeatureIndex", + value: function getSeletFeatureIndex(featureId) { + var data = this.get('data'); + + if (!data.features) { + return featureId - 1; + } + + var featureIndex = 0; + + for (var i = 0; i < this.data.dataArray.length; i++) { + var item = this.data.dataArray[i]; + + if (item._id === featureId) { + break; + } + + featureIndex++; + } + + return featureIndex; + } + }, { + key: "destroy", + value: function destroy() { + this.data = null; + this.originData = null; + } + }]); + + return Source; +}(_base["default"]); + +exports["default"] = Source; \ No newline at end of file diff --git a/lib/core/style.js b/lib/core/style.js new file mode 100644 index 0000000000..d389a21c07 --- /dev/null +++ b/lib/core/style.js @@ -0,0 +1,154 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("../core/base")); + +var _worker_pool = _interopRequireDefault(require("../worker/worker_pool")); + +var _throttle = _interopRequireDefault(require("../util/throttle")); + +var _source_cache = _interopRequireDefault(require("../source/source_cache")); + +var _worker_controller = _interopRequireDefault(require("../worker/worker_controller")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +// 统一管理所有的Source +// 统一管理地图样式 +var Style = +/*#__PURE__*/ +function (_Base) { + _inherits(Style, _Base); + + function Style(scene, cfg) { + var _this; + + _classCallCheck(this, Style); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(Style).call(this, cfg)); + _this.scene = scene; + _this._sourceCaches = {}; + _this.WorkerPool = new _worker_pool["default"](); + _this._tileMap = {}; + _this.WorkerController = new _worker_controller["default"](_this.WorkerPool, _assertThisInitialized(_this)); + _this.layerStyles = {}; + _this.layers = []; + + _this.addMapEvent(); + + return _this; + } + + _createClass(Style, [{ + key: "addSource", + value: function addSource(id, sourceCfg) { + if (this._sourceCaches[id] !== undefined) { + throw new Error('SourceID 已存在'); + } + + sourceCfg.sourceID = id; + this._sourceCaches[id] = new _source_cache["default"](this.scene, sourceCfg); + } + }, { + key: "getSource", + value: function getSource(id) { + return this._sourceCaches[id]; + } + }, { + key: "addLayer", + value: function addLayer(layer) { + var id = layer.layerId; + this.layers[id] = layer; + } // 设置 + + }, { + key: "_addTileStyle", + value: function _addTileStyle(layerCfg) { + var layerid = layerCfg.layerId; + this.layerStyles[layerid] = layerCfg; + + this._layerStyleGroupBySourceID(); + + this.WorkerController.broadcast('setLayers', this.layerStyles); // TODO 更新 style + } + }, { + key: "removeTileStyle", + value: function removeTileStyle(id) { + delete this.layerStyles[id]; + + this._layerStyleGroupBySourceID(); + } + }, { + key: "_layerStyleGroupBySourceID", + value: function _layerStyleGroupBySourceID() { + var sourceStyles = []; // 支持VectorLayer + + for (var layerId in this.layerStyles) { + var sourceID = this.layerStyles[layerId].sourceOption.id; + var sourcelayer = this.layerStyles[layerId].sourceOption.parser.sourceLayer; + if (!sourceStyles[sourceID]) sourceStyles[sourceID] = {}; + if (!sourceStyles[sourceID][sourcelayer]) sourceStyles[sourceID][sourcelayer] = []; + sourceStyles[sourceID][sourcelayer].push(this.layerStyles[layerId]); + } + + this.sourceStyles = sourceStyles; + } + }, { + key: "update", + value: function update(parameters) { + this._addTileStyle(parameters); + + for (var key in this._sourceCaches) { + this._sourceCaches[key].update(this.layers, this.sourceStyles[key]); + } + } + }, { + key: "addMapEvent", + value: function addMapEvent() { + var _this2 = this; + + this.mapEventHander = (0, _throttle["default"])(function () { + requestAnimationFrame(function () { + for (var key in _this2._sourceCaches) { + _this2._sourceCaches[key].update(_this2.layers, _this2.sourceStyles[key]); + } + }); + }, 200); + this.scene.map.on('zoomchange', this.mapEventHander); + this.scene.map.on('dragend', this.mapEventHander); + } + }, { + key: "clearMapEvent", + value: function clearMapEvent() { + this.scene.map.off('zoomchange', this.mapEventHander); + this.scene.map.off('dragend', this.mapEventHander); + } // 计算视野内的瓦片坐标 + + }]); + + return Style; +}(_base["default"]); + +exports["default"] = Style; \ No newline at end of file diff --git a/lib/core/three.js b/lib/core/three.js new file mode 100644 index 0000000000..af43cae443 --- /dev/null +++ b/lib/core/three.js @@ -0,0 +1,362 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + Float32BufferAttribute: true, + Float64BufferAttribute: true, + Uint32BufferAttribute: true, + Int32BufferAttribute: true, + Uint16BufferAttribute: true, + Int16BufferAttribute: true, + Uint8ClampedBufferAttribute: true, + Uint8BufferAttribute: true, + Int8BufferAttribute: true, + BufferAttribute: true, + Scene: true, + WebGLRenderer: true, + CanvasTexture: true, + Object3D: true, + Group: true, + Clock: true, + Points: true, + LineSegments: true, + Mesh: true, + Texture: true, + WebGLRenderTarget: true, + PerspectiveCamera: true, + OrthographicCamera: true, + BufferGeometry: true, + InstancedBufferGeometry: true, + PlaneBufferGeometry: true, + BoxBufferGeometry: true, + Raycaster: true, + UniformsUtils: true, + Matrix4: true, + Matrix3: true, + Line: true, + Vector4: true, + Vector3: true, + Vector2: true, + ShaderMaterial: true, + DataTexture: true, + Color: true, + InstancedBufferAttribute: true +}; +exports.Float32BufferAttribute = Float32BufferAttribute; +Object.defineProperty(exports, "Float64BufferAttribute", { + enumerable: true, + get: function get() { + return _BufferAttribute.Float64BufferAttribute; + } +}); +Object.defineProperty(exports, "Uint32BufferAttribute", { + enumerable: true, + get: function get() { + return _BufferAttribute.Uint32BufferAttribute; + } +}); +Object.defineProperty(exports, "Int32BufferAttribute", { + enumerable: true, + get: function get() { + return _BufferAttribute.Int32BufferAttribute; + } +}); +Object.defineProperty(exports, "Uint16BufferAttribute", { + enumerable: true, + get: function get() { + return _BufferAttribute.Uint16BufferAttribute; + } +}); +Object.defineProperty(exports, "Int16BufferAttribute", { + enumerable: true, + get: function get() { + return _BufferAttribute.Int16BufferAttribute; + } +}); +Object.defineProperty(exports, "Uint8ClampedBufferAttribute", { + enumerable: true, + get: function get() { + return _BufferAttribute.Uint8ClampedBufferAttribute; + } +}); +Object.defineProperty(exports, "Uint8BufferAttribute", { + enumerable: true, + get: function get() { + return _BufferAttribute.Uint8BufferAttribute; + } +}); +Object.defineProperty(exports, "Int8BufferAttribute", { + enumerable: true, + get: function get() { + return _BufferAttribute.Int8BufferAttribute; + } +}); +Object.defineProperty(exports, "BufferAttribute", { + enumerable: true, + get: function get() { + return _BufferAttribute.BufferAttribute; + } +}); +Object.defineProperty(exports, "Scene", { + enumerable: true, + get: function get() { + return _Scene.Scene; + } +}); +Object.defineProperty(exports, "WebGLRenderer", { + enumerable: true, + get: function get() { + return _WebGLRenderer.WebGLRenderer; + } +}); +Object.defineProperty(exports, "CanvasTexture", { + enumerable: true, + get: function get() { + return _CanvasTexture.CanvasTexture; + } +}); +Object.defineProperty(exports, "Object3D", { + enumerable: true, + get: function get() { + return _Object3D.Object3D; + } +}); +Object.defineProperty(exports, "Group", { + enumerable: true, + get: function get() { + return _Group.Group; + } +}); +Object.defineProperty(exports, "Clock", { + enumerable: true, + get: function get() { + return _Clock.Clock; + } +}); +Object.defineProperty(exports, "Points", { + enumerable: true, + get: function get() { + return _Points.Points; + } +}); +Object.defineProperty(exports, "LineSegments", { + enumerable: true, + get: function get() { + return _LineSegments.LineSegments; + } +}); +Object.defineProperty(exports, "Mesh", { + enumerable: true, + get: function get() { + return _Mesh.Mesh; + } +}); +Object.defineProperty(exports, "Texture", { + enumerable: true, + get: function get() { + return _Texture.Texture; + } +}); +Object.defineProperty(exports, "WebGLRenderTarget", { + enumerable: true, + get: function get() { + return _WebGLRenderTarget.WebGLRenderTarget; + } +}); +Object.defineProperty(exports, "PerspectiveCamera", { + enumerable: true, + get: function get() { + return _PerspectiveCamera.PerspectiveCamera; + } +}); +Object.defineProperty(exports, "OrthographicCamera", { + enumerable: true, + get: function get() { + return _OrthographicCamera.OrthographicCamera; + } +}); +Object.defineProperty(exports, "BufferGeometry", { + enumerable: true, + get: function get() { + return _BufferGeometry.BufferGeometry; + } +}); +Object.defineProperty(exports, "InstancedBufferGeometry", { + enumerable: true, + get: function get() { + return _InstancedBufferGeometry.InstancedBufferGeometry; + } +}); +Object.defineProperty(exports, "PlaneBufferGeometry", { + enumerable: true, + get: function get() { + return _PlaneGeometry.PlaneBufferGeometry; + } +}); +Object.defineProperty(exports, "BoxBufferGeometry", { + enumerable: true, + get: function get() { + return _BoxGeometry.BoxBufferGeometry; + } +}); +Object.defineProperty(exports, "Raycaster", { + enumerable: true, + get: function get() { + return _Raycaster.Raycaster; + } +}); +Object.defineProperty(exports, "UniformsUtils", { + enumerable: true, + get: function get() { + return _UniformsUtils.UniformsUtils; + } +}); +Object.defineProperty(exports, "Matrix4", { + enumerable: true, + get: function get() { + return _Matrix.Matrix4; + } +}); +Object.defineProperty(exports, "Matrix3", { + enumerable: true, + get: function get() { + return _Matrix2.Matrix3; + } +}); +Object.defineProperty(exports, "Line", { + enumerable: true, + get: function get() { + return _Line.Line; + } +}); +Object.defineProperty(exports, "Vector4", { + enumerable: true, + get: function get() { + return _Vector.Vector4; + } +}); +Object.defineProperty(exports, "Vector3", { + enumerable: true, + get: function get() { + return _Vector2.Vector3; + } +}); +Object.defineProperty(exports, "Vector2", { + enumerable: true, + get: function get() { + return _Vector3.Vector2; + } +}); +Object.defineProperty(exports, "ShaderMaterial", { + enumerable: true, + get: function get() { + return _ShaderMaterial.ShaderMaterial; + } +}); +Object.defineProperty(exports, "DataTexture", { + enumerable: true, + get: function get() { + return _DataTexture.DataTexture; + } +}); +Object.defineProperty(exports, "Color", { + enumerable: true, + get: function get() { + return _Color.Color; + } +}); +Object.defineProperty(exports, "InstancedBufferAttribute", { + enumerable: true, + get: function get() { + return _InstancedBufferAttribute.InstancedBufferAttribute; + } +}); + +require("three/src/polyfills.js"); + +var _BufferAttribute = require("three/src/core/BufferAttribute.js"); + +var _constants = require("three/src/constants.js"); + +Object.keys(_constants).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _constants[key]; + } + }); +}); + +var _Scene = require("three/src/scenes/Scene.js"); + +var _WebGLRenderer = require("three/src/renderers/WebGLRenderer.js"); + +var _CanvasTexture = require("three/src/textures/CanvasTexture.js"); + +var _Object3D = require("three/src/core/Object3D.js"); + +var _Group = require("three/src/objects/Group"); + +var _Clock = require("three/src/core/Clock"); + +var _Points = require("three/src/objects/Points.js"); + +var _LineSegments = require("three/src/objects/LineSegments.js"); + +var _Mesh = require("three/src/objects/Mesh.js"); + +var _Texture = require("three/src/textures/Texture.js"); + +var _WebGLRenderTarget = require("three/src/renderers/WebGLRenderTarget.js"); + +var _PerspectiveCamera = require("three/src/cameras/PerspectiveCamera.js"); + +var _OrthographicCamera = require("three/src/cameras/OrthographicCamera.js"); + +var _BufferGeometry = require("three/src/core/BufferGeometry.js"); + +var _InstancedBufferGeometry = require("three/src/core/InstancedBufferGeometry"); + +var _PlaneGeometry = require("three/src/geometries/PlaneGeometry.js"); + +var _BoxGeometry = require("three/src/geometries/BoxGeometry.js"); + +var _Raycaster = require("three/src/core/Raycaster.js"); + +var _UniformsUtils = require("three/src/renderers/shaders/UniformsUtils.js"); + +var _Matrix = require("three/src/math/Matrix4.js"); + +var _Matrix2 = require("three/src/math/Matrix3.js"); + +var _Line = require("three/src/objects/Line.js"); + +var _Vector = require("three/src/math/Vector4.js"); + +var _Vector2 = require("three/src/math/Vector3.js"); + +var _Vector3 = require("three/src/math/Vector2.js"); + +var _ShaderMaterial = require("three/src/materials/ShaderMaterial.js"); + +var _DataTexture = require("three/src/textures/DataTexture.js"); + +var _Color = require("three/src/math/Color.js"); + +var _InstancedBufferAttribute = require("three/src/core/InstancedBufferAttribute"); + +// export * from '../../build/three.js'; +function Float32BufferAttribute(array, itemSize, normalized) { + if (Array.isArray(array)) { + array = new Float32Array(array); + } + + _BufferAttribute.BufferAttribute.call(this, array, itemSize, normalized); +} + +Float32BufferAttribute.prototype = Object.create(_BufferAttribute.BufferAttribute.prototype); +Float32BufferAttribute.prototype.constructor = Float32BufferAttribute; \ No newline at end of file diff --git a/lib/core/worker.js b/lib/core/worker.js new file mode 100644 index 0000000000..4d26733142 --- /dev/null +++ b/lib/core/worker.js @@ -0,0 +1,94 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var WorkerPool = +/*#__PURE__*/ +function () { + function WorkerPool(workerCount) { + _classCallCheck(this, WorkerPool); + + this.workerCount = workerCount || Math.max(Math.floor(window.navigator.hardwareConcurrency / 2), 1); + this.workers = []; // worker线程池 + + this.workerQueue = []; // 任务队列 + + this._initWorker(); // 初始化线程池 + + } + + _createClass(WorkerPool, [{ + key: "_initWorker", + value: function _initWorker() { + while (this.workers.length < this.workerCount) { + this.workers.push(new Worker()); + } + } + }, { + key: "runTask", + value: function runTask(payload) { + var _this = this; + + return new Promise(function (resolve, reject) { + if (_this.workers.length > 0) { + var worker = _this.workers.shift(); // 从线程池取出一个worker + + + worker.postMessage(payload); // 向线程发送数据 + + var workerCallback = function workerCallback(e) { + resolve(e.data); // 成功则返回数据 + // 移除事件监听 + + worker.removeEventListener('message', workerCallback); // 重新放回线程池 + + _this.workers.push(worker); // 如果任务队列的数据还有则从任务队列继续取数据执行任务 + + + if (_this.workerQueue.length > 0) { + var queueData = _this.workerQueue.shift(); + + _this.runTask(queueData.payload).then(function (data) { + queueData.resolve(data); + }); + } + }; // 监听worker事件 + + + worker.addEventListener('message', workerCallback); + worker.addEventListener('error', function (e) { + reject('filename:' + e.filename + '\nmessage:' + e.message + '\nlineno:' + e.lineno); + }); + } else { + // 如果线程池都被占用,则将数据丢入任务队列,并保存对应的resolve和reject + _this.workerQueue.push({ + payload: payload, + resolve: resolve, + reject: reject + }); + } + }); + } + }, { + key: "release", + value: function release() { + this.workers.forEach(function (worker) { + worker.terminate(); + }); + } + }]); + + return WorkerPool; +}(); + +var _default = WorkerPool; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/geo/bound.js b/lib/geo/bound.js new file mode 100644 index 0000000000..9a390c31f7 --- /dev/null +++ b/lib/geo/bound.js @@ -0,0 +1 @@ +"use strict"; \ No newline at end of file diff --git a/lib/geo/buffer.js b/lib/geo/buffer.js new file mode 100644 index 0000000000..9a390c31f7 --- /dev/null +++ b/lib/geo/buffer.js @@ -0,0 +1 @@ +"use strict"; \ No newline at end of file diff --git a/lib/geo/featureIndex.js b/lib/geo/featureIndex.js new file mode 100644 index 0000000000..72b230b094 --- /dev/null +++ b/lib/geo/featureIndex.js @@ -0,0 +1,92 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _rbush = _interopRequireDefault(require("rbush")); + +var _bbox = _interopRequireDefault(require("@turf/bbox")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } + +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var FeatureIndex = +/*#__PURE__*/ +function () { + function FeatureIndex(data) { + var _this = this; + + _classCallCheck(this, FeatureIndex); + + this.tree = (0, _rbush["default"])(); + this.rawData = data; + data.features.forEach(function (feature) { + _this.insert(feature); + }); + } + + _createClass(FeatureIndex, [{ + key: "insert", + value: function insert(feature) { + var bbox = this.toBBox(feature); + bbox.feature = feature; + this.tree.insert(bbox); + } + }, { + key: "search", + value: function search(feature) { + return this.tree.search(this.toBBox(feature)); + } + }, { + key: "clear", + value: function clear() { + this.tree.clear(); + } + }, { + key: "all", + value: function all() { + return this.tree.all(); + } + }, { + key: "toBBox", + value: function toBBox(feature) { + var bbox = feature.type === 'Point' ? this.pointBBox(feature) : (0, _bbox["default"])(feature); + return { + minX: bbox[0], + minY: bbox[1], + maxX: bbox[2], + maxY: bbox[3] + }; + } + }, { + key: "pointBBox", + value: function pointBBox(feature) { + var size = 1 / 1000 / 1000; // 1m + + var _feature$geometry$coo = _slicedToArray(feature.geometry.coordinates, 2), + x = _feature$geometry$coo[0], + y = _feature$geometry$coo[1]; + + return [x - size, y - size, x + size, y + size]; + } + }]); + + return FeatureIndex; +}(); + +exports["default"] = FeatureIndex; \ No newline at end of file diff --git a/lib/geo/lngLat.js b/lib/geo/lngLat.js new file mode 100644 index 0000000000..9a390c31f7 --- /dev/null +++ b/lib/geo/lngLat.js @@ -0,0 +1 @@ +"use strict"; \ No newline at end of file diff --git a/lib/geo/point.js b/lib/geo/point.js new file mode 100644 index 0000000000..9a390c31f7 --- /dev/null +++ b/lib/geo/point.js @@ -0,0 +1 @@ +"use strict"; \ No newline at end of file diff --git a/lib/geo/project.js b/lib/geo/project.js new file mode 100644 index 0000000000..352c1dee0e --- /dev/null +++ b/lib/geo/project.js @@ -0,0 +1,55 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.aProjectFlat = aProjectFlat; +exports.unProjectFlat = unProjectFlat; + +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } + +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + +function aProjectFlat(lnglat) { + var maxs = 85.0511287798; + var lat = Math.max(Math.min(maxs, lnglat[1]), -maxs); + var scale = 256 << 20; + var d = Math.PI / 180; + var x = lnglat[0] * d; + var y = lat * d; + y = Math.log(Math.tan(Math.PI / 4 + y / 2)); + var a = 0.5 / Math.PI, + b = 0.5, + c = -0.5 / Math.PI; + d = 0.5; + x = scale * (a * x + b) - 215440491; + y = scale * (c * y + d) - 106744817; + return { + x: parseInt(x), + y: parseInt(y) + }; +} + +function unProjectFlat(px) { + var a = 0.5 / Math.PI, + b = 0.5, + c = -0.5 / Math.PI; + var d = 0.5; + var scale = 256 << 20; + + var _px = _slicedToArray(px, 2), + x = _px[0], + y = _px[1]; + + x = ((x + 215440491) / scale - b) / a; + y = ((y + 106744817) / scale - d) / c; + y = (Math.atan(Math.pow(Math.E, y)) - Math.PI / 4) * 2; + d = Math.PI / 180; + var lat = y / d; + var lng = x / d; + return [lng, lat]; +} \ No newline at end of file diff --git a/lib/geom/base.js b/lib/geom/base.js new file mode 100644 index 0000000000..8a4858b56a --- /dev/null +++ b/lib/geom/base.js @@ -0,0 +1,35 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.shapeBae = exports.GeomBase = void 0; +var GeomBase = { + color: 'updateDraw', + size: 'repaint', + filter: 'updateDraw', + layer: '', + pickable: true, + setLayer: function setLayer(layer) { + this.layer = layer; + this.style = layer.get('styleOption'); + }, + getShape: function getShape(type) { + return type; + }, + draw: function draw() { + var shape = this.getShape(); + this.Mesh = shape.Mesh(); + }, + // 更新geometry buffer; + updateDraw: function updateDraw() {}, + repaint: function repaint() {} +}; +exports.GeomBase = GeomBase; +var shapeBae = { + geometryBuffer: function geometryBuffer() {}, + geometry: function geometry() {}, + material: function material() {}, + mesh: function mesh() {} +}; +exports.shapeBae = shapeBae; \ No newline at end of file diff --git a/lib/geom/buffer/buffer.js b/lib/geom/buffer/buffer.js new file mode 100644 index 0000000000..92d2ce2a37 --- /dev/null +++ b/lib/geom/buffer/buffer.js @@ -0,0 +1,241 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("../../core/base")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var BufferBase = +/*#__PURE__*/ +function (_Base) { + _inherits(BufferBase, _Base); + + function BufferBase(cfg) { + var _this; + + _classCallCheck(this, BufferBase); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(BufferBase).call(this, cfg)); + _this.attributes = {}; + _this.verticesCount = 0; + _this.indexCount = 0; + _this.indexArray = new Int32Array(0); + + _this._init(); + + return _this; + } + + _createClass(BufferBase, [{ + key: "_init", + value: function _init() { + this._calculateFeatures(); + + this._initAttributes(); + + this._buildFeatures(); + } + }, { + key: "_initAttributes", + value: function _initAttributes() { + this.attributes.positions = new Float32Array(this.verticesCount * 3); + this.attributes.colors = new Float32Array(this.verticesCount * 4); + this.attributes.pickingIds = new Float32Array(this.verticesCount); + this.attributes.sizes = new Float32Array(this.verticesCount); + this.attributes.pickingIds = new Float32Array(this.verticesCount); + + if (this.get('uv')) { + this.attributes.uv = new Float32Array(this.verticesCount * 2); + } + + this.indexArray = new Int32Array(this.indexCount); + } + }, { + key: "addFeature", + value: function addFeature() {} // 更新渲染 + + }, { + key: "upload", + value: function upload() {} + }, { + key: "destroy", + value: function destroy() {} + }, { + key: "resize", + value: function resize() {} + }, { + key: "checkIsClosed", + value: function checkIsClosed(points) { + var p1 = points[0][0]; + var p2 = points[0][points[0].length - 1]; + return p1[0] === p2[0] && p1[1] === p2[1]; + } + }, { + key: "concat", + value: function concat(arrayType, arrays) { + var totalLength = 0; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = arrays[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var arr = _step.value; + totalLength += arr.length; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator["return"] != null) { + _iterator["return"](); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var arrayBuffer = new ArrayBuffer(totalLength * arrayType.BYTES_PER_ELEMENT); + var offset = 0; + var result = new arrayType(arrayBuffer); + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = arrays[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var _arr = _step2.value; + result.set(_arr, offset); + offset += _arr.length; + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) { + _iterator2["return"](); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + return result; + } + }, { + key: "_encodeArray", + value: function _encodeArray(feature, num) { + var color = feature.color, + id = feature.id, + pattern = feature.pattern, + size = feature.size; + var verticesOffset = feature.bufferInfo.verticesOffset; + var imagePos = this.get('imagePos'); + var start1 = verticesOffset; + + for (var i = 0; i < num; i++) { + if (feature.hasOwnProperty('color')) { + this.attributes.colors[start1 * 4 + i * 4] = color[0]; + this.attributes.colors[start1 * 4 + i * 4 + 1] = color[1]; + this.attributes.colors[start1 * 4 + i * 4 + 2] = color[2]; + this.attributes.colors[start1 * 4 + i * 4 + 3] = color[3]; + } + + if (feature.hasOwnProperty('id')) { + this.attributes.pickingIds[start1 + i] = id; + } + + if (feature.hasOwnProperty('size')) { + var size2 = size; + + if (Array.isArray(size) && size.length === 2) { + size2 = [size[0]]; + } + + if (!Array.isArray(size)) { + size2 = [size]; + } + + this.attributes.sizes.set(size2, (start1 + i) * size2.length); + } + + if (feature.hasOwnProperty('pattern')) { + var patternPos = imagePos[pattern] || { + x: 0, + y: 0 + }; + this.attributes.patterns[start1 * 2 + i * 2] = patternPos.x; + this.attributes.patterns[start1 * 2 + i * 2 + 1] = patternPos.y; + } + } + } + }, { + key: "_calculateWall", + value: function _calculateWall(feature) { + var size = feature.size; + var _feature$bufferInfo = feature.bufferInfo, + vertices = _feature$bufferInfo.vertices, + indexOffset = _feature$bufferInfo.indexOffset, + verticesOffset = _feature$bufferInfo.verticesOffset, + faceNum = _feature$bufferInfo.faceNum; + + this._encodeArray(feature, faceNum * 4); + + for (var i = 0; i < faceNum; i++) { + var prePoint = vertices.slice(i * 3, i * 3 + 3); + var nextPoint = vertices.slice(i * 3 + 3, i * 3 + 6); + + this._calculateExtrudeFace(prePoint, nextPoint, verticesOffset + i * 4, indexOffset + i * 6, size); + + feature.bufferInfo.verticesOffset += 4; + feature.bufferInfo.indexOffset += 6; + } + } + }, { + key: "_calculateExtrudeFace", + value: function _calculateExtrudeFace(prePoint, nextPoint, positionOffset, indexOffset, size) { + this.attributes.positions.set([prePoint[0], prePoint[1], size, nextPoint[0], nextPoint[1], size, prePoint[0], prePoint[1], 0, nextPoint[0], nextPoint[1], 0], positionOffset * 3); + var indexArray = [1, 2, 0, 3, 2, 1].map(function (v) { + return v + positionOffset; + }); + + if (this.get('uv')) { + this.attributes.uv.set([0.1, 0, 0, 0, 0.1, size / 2000, 0, size / 2000], positionOffset * 2); + } + + this.indexArray.set(indexArray, indexOffset); + } + }]); + + return BufferBase; +}(_base["default"]); + +exports["default"] = BufferBase; \ No newline at end of file diff --git a/lib/geom/buffer/bufferBase.js b/lib/geom/buffer/bufferBase.js new file mode 100644 index 0000000000..c0616b1246 --- /dev/null +++ b/lib/geom/buffer/bufferBase.js @@ -0,0 +1,431 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("../../core/base")); + +var THREE = _interopRequireWildcard(require("../../core/three")); + +var _normals2 = require("../normals"); + +var _extrude2 = _interopRequireDefault(require("../extrude")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var BufferBase = +/*#__PURE__*/ +function (_Base) { + _inherits(BufferBase, _Base); + + function BufferBase(cfg) { + var _this; + + _classCallCheck(this, BufferBase); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(BufferBase).call(this, cfg)); + _this.bufferStruct = {}; + + _this.geometryBuffer(); + + return _this; + } + + _createClass(BufferBase, [{ + key: "geometryBuffer", + value: function geometryBuffer() {} + }, { + key: "_normals", + value: function _normals() { + var _this$bufferStruct = this.bufferStruct, + position = _this$bufferStruct.position, + indices = _this$bufferStruct.indices, + _this$bufferStruct$no = _this$bufferStruct.normals, + normals = _this$bufferStruct$no === void 0 ? [] : _this$bufferStruct$no; + indices.forEach(function (index, i) { + normals.push((0, _normals2.faceNormals)(index, position[i])); + }); + this.bufferStruct.normals = normals; + } + }, { + key: "_extrude", + value: function _extrude(coordinate, heightValue) { + var extrudeData = (0, _extrude2["default"])(coordinate, heightValue); + return extrudeData; + } + }, { + key: "_mergeAttributes", + value: function _mergeAttributes(attributes) { + var lengths = {}; // Find array lengths + + attributes.forEach(function (_attributes) { + for (var k in _attributes) { + if (!lengths[k]) { + lengths[k] = 0; + } + + lengths[k] += _attributes[k].length; + } + }); + var mergedAttributes = {}; // Set up arrays to merge into + + for (var k in lengths) { + mergedAttributes[k] = new Float32Array(lengths[k]); + } + + var lastLengths = {}; + attributes.forEach(function (_attributes) { + for (var _k in _attributes) { + if (!lastLengths[_k]) { + lastLengths[_k] = 0; + } + + mergedAttributes[_k].set(_attributes[_k], lastLengths[_k]); + + lastLengths[_k] += _attributes[_k].length; + } + }); + return mergedAttributes; + } + }, { + key: "_toPolygonAttributes", + value: function _toPolygonAttributes(polygon) { + // Three components per vertex per face (3 x 3 = 9) + var style = polygon.style, + indices = polygon.indices, + position = polygon.position, + indexCount = polygon.indexCount; + var vertices = new Float32Array(indexCount * 3); + var normals = new Float32Array(indexCount * 3); + var colors = new Float32Array(indexCount * 4); + var pickingIds = new Float32Array(indexCount); + var pA = new THREE.Vector3(); + var pB = new THREE.Vector3(); + var pC = new THREE.Vector3(); + var cb = new THREE.Vector3(); + var ab = new THREE.Vector3(); + var lastIndex = 0; + indices.forEach(function (indice, pIndex) { + for (var i = 0; i < indice.length / 3; i++) { + var index = indice[i * 3]; + var color = style[pIndex].color; + var _pickingId = style[pIndex].id; + var ax = position[pIndex][index][0]; + var ay = position[pIndex][index][1]; + var az = position[pIndex][index][2]; + index = indice[i * 3 + 1]; + var bx = position[pIndex][index][0]; + var by = position[pIndex][index][1]; + var bz = position[pIndex][index][2]; + index = indice[i * 3 + 2]; + var cx = position[pIndex][index][0]; + var cy = position[pIndex][index][1]; + var cz = position[pIndex][index][2]; + pA.set(ax, ay, az); + pB.set(bx, by, bz); + pC.set(cx, cy, cz); + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + cb.normalize(); + var nx = cb.x; + var ny = cb.y; + var nz = cb.z; + vertices[lastIndex * 9 + 0] = ax; + vertices[lastIndex * 9 + 1] = ay; + vertices[lastIndex * 9 + 2] = az; + normals[lastIndex * 9 + 0] = nx; + normals[lastIndex * 9 + 1] = ny; + normals[lastIndex * 9 + 2] = nz; + colors[lastIndex * 12 + 0] = color[0]; + colors[lastIndex * 12 + 1] = color[1]; + colors[lastIndex * 12 + 2] = color[2]; + colors[lastIndex * 12 + 3] = color[3]; + vertices[lastIndex * 9 + 3] = bx; + vertices[lastIndex * 9 + 4] = by; + vertices[lastIndex * 9 + 5] = bz; + normals[lastIndex * 9 + 3] = nx; + normals[lastIndex * 9 + 4] = ny; + normals[lastIndex * 9 + 5] = nz; + colors[lastIndex * 12 + 4] = color[0]; + colors[lastIndex * 12 + 5] = color[1]; + colors[lastIndex * 12 + 6] = color[2]; + colors[lastIndex * 12 + 7] = color[3]; + vertices[lastIndex * 9 + 6] = cx; + vertices[lastIndex * 9 + 7] = cy; + vertices[lastIndex * 9 + 8] = cz; + normals[lastIndex * 9 + 6] = nx; + normals[lastIndex * 9 + 7] = ny; + normals[lastIndex * 9 + 8] = nz; + colors[lastIndex * 12 + 8] = color[0]; + colors[lastIndex * 12 + 9] = color[1]; + colors[lastIndex * 12 + 10] = color[2]; + colors[lastIndex * 12 + 11] = color[3]; + pickingIds[lastIndex * 3 + 0] = _pickingId; + pickingIds[lastIndex * 3 + 1] = _pickingId; + pickingIds[lastIndex * 3 + 2] = _pickingId; + lastIndex++; + } + }); + var attributes = { + vertices: vertices, + normals: normals, + colors: colors, + pickingIds: pickingIds, + faceUv: new Float32Array(polygon.faceUv), + sizes: new Float32Array(polygon.sizes) + }; + return attributes; + } + }, { + key: "_toPointShapeAttributes", + value: function _toPointShapeAttributes(polygon) { + // Three components per vertex per face (3 x 3 = 9) + var style = polygon.style, + indices = polygon.indices, + position = polygon.position, + indexCount = polygon.indexCount, + shapes = polygon.shapes, + sizes = polygon.sizes; + var vertices = new Float32Array(indexCount * 3); + var shapePositions = new Float32Array(indexCount * 3); + var a_size = new Float32Array(indexCount * 3); + var normals = new Float32Array(indexCount * 3); + var colors = new Float32Array(indexCount * 4); + var pickingIds = new Float32Array(indexCount); + var pA = new THREE.Vector3(); + var pB = new THREE.Vector3(); + var pC = new THREE.Vector3(); + var cb = new THREE.Vector3(); + var ab = new THREE.Vector3(); + var lastIndex = 0; + indices.forEach(function (indice, pIndex) { + for (var i = 0; i < indice.length / 3; i++) { + var index = indice[i * 3]; + var color = style[pIndex].color; + var coor1 = position[pIndex]; + var size = sizes[pIndex]; + var _pickingId = style[pIndex].id; + var ax = shapes[pIndex][index][0]; + var ay = shapes[pIndex][index][1]; + var az = shapes[pIndex][index][2]; + index = indice[i * 3 + 1]; + var bx = shapes[pIndex][index][0]; + var by = shapes[pIndex][index][1]; + var bz = shapes[pIndex][index][2]; + index = indice[i * 3 + 2]; + var cx = shapes[pIndex][index][0]; + var cy = shapes[pIndex][index][1]; + var cz = shapes[pIndex][index][2]; + pA.set(ax, ay, az); + pB.set(bx, by, bz); + pC.set(cx, cy, cz); + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + cb.normalize(); + var nx = cb.x; + var ny = cb.y; + var nz = cb.z; + vertices[lastIndex * 9 + 0] = coor1[0]; + vertices[lastIndex * 9 + 1] = coor1[1]; + vertices[lastIndex * 9 + 2] = coor1[2]; + shapePositions[lastIndex * 9 + 0] = ax; + shapePositions[lastIndex * 9 + 1] = ay; + shapePositions[lastIndex * 9 + 2] = az; + a_size[lastIndex * 9 + 0] = size[0]; + a_size[lastIndex * 9 + 1] = size[1]; + a_size[lastIndex * 9 + 2] = size[2]; + normals[lastIndex * 9 + 0] = nx; + normals[lastIndex * 9 + 1] = ny; + normals[lastIndex * 9 + 2] = nz; + colors[lastIndex * 12 + 0] = color[0]; + colors[lastIndex * 12 + 1] = color[1]; + colors[lastIndex * 12 + 2] = color[2]; + colors[lastIndex * 12 + 3] = color[3]; + vertices[lastIndex * 9 + 3] = coor1[0]; + vertices[lastIndex * 9 + 4] = coor1[1]; + vertices[lastIndex * 9 + 5] = coor1[2]; + shapePositions[lastIndex * 9 + 3] = bx; + shapePositions[lastIndex * 9 + 4] = by; + shapePositions[lastIndex * 9 + 5] = bz; + a_size[lastIndex * 9 + 3] = size[0]; + a_size[lastIndex * 9 + 4] = size[1]; + a_size[lastIndex * 9 + 5] = size[2]; + normals[lastIndex * 9 + 3] = nx; + normals[lastIndex * 9 + 4] = ny; + normals[lastIndex * 9 + 5] = nz; + colors[lastIndex * 12 + 4] = color[0]; + colors[lastIndex * 12 + 5] = color[1]; + colors[lastIndex * 12 + 6] = color[2]; + colors[lastIndex * 12 + 7] = color[3]; + vertices[lastIndex * 9 + 6] = coor1[0]; + vertices[lastIndex * 9 + 7] = coor1[1]; + vertices[lastIndex * 9 + 8] = coor1[2]; + a_size[lastIndex * 9 + 6] = size[0]; + a_size[lastIndex * 9 + 7] = size[1]; + a_size[lastIndex * 9 + 8] = size[2]; + shapePositions[lastIndex * 9 + 6] = cx; + shapePositions[lastIndex * 9 + 7] = cy; + shapePositions[lastIndex * 9 + 8] = cz; + normals[lastIndex * 9 + 6] = nx; + normals[lastIndex * 9 + 7] = ny; + normals[lastIndex * 9 + 8] = nz; + colors[lastIndex * 12 + 8] = color[0]; + colors[lastIndex * 12 + 9] = color[1]; + colors[lastIndex * 12 + 10] = color[2]; + colors[lastIndex * 12 + 11] = color[3]; + pickingIds[lastIndex * 3 + 0] = _pickingId; + pickingIds[lastIndex * 3 + 1] = _pickingId; + pickingIds[lastIndex * 3 + 2] = _pickingId; + lastIndex++; + } + }); + var attributes = { + vertices: vertices, + normals: normals, + colors: colors, + pickingIds: pickingIds, + shapePositions: shapePositions, + a_size: a_size, + faceUv: new Float32Array(polygon.faceUv) + }; + return attributes; + } + }, { + key: "_toPolygonLineAttributes", + value: function _toPolygonLineAttributes(polygonline) { + var style = polygonline.style, + indices = polygonline.indices, + position = polygonline.position, + indexCount = polygonline.indexCount; + var vertices = new Float32Array(indexCount * 3); + var colors = new Float32Array(indexCount * 4); + var pickingIds = new Float32Array(indexCount); + var lastIndex = 0; + indices.forEach(function (indice, pIndex) { + for (var i = 0; i < indice.length; i++) { + var index = indice[i]; + var color = style[pIndex].color; + var _pickingId = style[pIndex].id; + vertices[lastIndex * 3] = position[pIndex][index][0]; + vertices[lastIndex * 3 + 1] = position[pIndex][index][1]; + vertices[lastIndex * 3 + 2] = position[pIndex][index][2]; + colors[lastIndex * 4] = color[0]; + colors[lastIndex * 4 + 1] = color[1]; + colors[lastIndex * 4 + 2] = color[2]; + colors[lastIndex * 4 + 3] = color[3]; + pickingIds[lastIndex] = _pickingId; + lastIndex++; + } + }); + var attributes = { + vertices: vertices, + colors: colors, + pickingIds: pickingIds + }; + return attributes; + } + }, { + key: "_toPointsAttributes", + value: function _toPointsAttributes(point) { + var style = point.style, + position = point.position; + var count = position.length; + var vertices = new Float32Array(count * 3); + var colors = new Float32Array(count * 4); + var sizes = new Float32Array(count); + var shapes = new Float32Array(count); + var pickingIds = new Float32Array(count); + position.forEach(function (pos, index) { + vertices[index * 3] = pos[0]; + vertices[index * 3 + 1] = pos[1]; + vertices[index * 3 + 2] = pos[2]; + colors[index * 4] = style[index].color[0]; + colors[index * 4 + 1] = style[index].color[1]; + colors[index * 4 + 2] = style[index].color[2]; + colors[index * 4 + 3] = style[index].color[3]; + pickingIds[index] = style[index].id; + sizes[index] = style[index].size * window.devicePixelRatio; + + if (style[index].shape) { + shapes[index] = style[index].shape; + } + }); + var attributes = { + vertices: vertices, + colors: colors, + sizes: sizes, + shapes: shapes, + pickingIds: pickingIds + }; + return attributes; + } + }, { + key: "_generateTexture", + value: function _generateTexture() { + // build a small canvas 32x64 and paint it in white + var canvas = document.createElement('canvas'); + canvas.width = 32; + canvas.height = 64; + var context = canvas.getContext('2d'); // plain it in white + + context.fillStyle = '#ffffff'; + context.fillRect(0, 0, 32, 64); // draw the window rows - with a small noise to simulate light variations in each room + + for (var y = 8; y < 64; y += 8) { + for (var x = 0; x < 32; x += 2) { + var value = Math.floor(Math.random() * 64); + context.fillStyle = 'rgb(' + [value, value, value].join(',') + ')'; + context.fillRect(x, y, 2, 4); + } + } + + context.fillStyle = '#105CB3'; + context.fillRect(0, 60, 32, 64); // build a bigger canvas and copy the small one in it + // This is a trick to upscale the texture without filtering + + var canvas2 = document.createElement('canvas'); + canvas2.width = 512; + canvas2.height = 1024; + var context2 = canvas2.getContext('2d'); // disable smoothing + + context2.imageSmoothingEnabled = false; + context2.webkitImageSmoothingEnabled = false; + context2.mozImageSmoothingEnabled = false; // then draw the image + + context2.drawImage(canvas, 0, 0, canvas2.width, canvas2.height); // return the just built canvas2 + + var texture = new THREE.Texture(canvas2); // texture.anisotropy = renderer.getMaxAnisotropy(); + + texture.needsUpdate = true; + return texture; + } + }]); + + return BufferBase; +}(_base["default"]); + +exports["default"] = BufferBase; \ No newline at end of file diff --git a/lib/geom/buffer/factory.js b/lib/geom/buffer/factory.js new file mode 100644 index 0000000000..0472b2a15e --- /dev/null +++ b/lib/geom/buffer/factory.js @@ -0,0 +1,26 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.registerBuffer = exports.getBuffer = exports.Buffer_MAP = void 0; +var Buffer_MAP = {}; +exports.Buffer_MAP = Buffer_MAP; + +var getBuffer = function getBuffer(bufferType, shapeType) { + return Buffer_MAP[bufferType.toLowerCase()] && Buffer_MAP[bufferType.toLowerCase()][shapeType.toLowerCase()]; +}; + +exports.getBuffer = getBuffer; + +var registerBuffer = function registerBuffer(bufferType, shapeType, render) { + if (getBuffer(bufferType, shapeType)) { + throw new Error("Render shapeType '".concat(shapeType, "' existed.")); + } // 存储到 map 中 + + + if (!Buffer_MAP[bufferType.toLowerCase()]) Buffer_MAP[bufferType.toLowerCase()] = {}; + Buffer_MAP[bufferType.toLowerCase()][shapeType.toLowerCase()] = render; +}; + +exports.registerBuffer = registerBuffer; \ No newline at end of file diff --git a/lib/geom/buffer/heatmap/grid.js b/lib/geom/buffer/heatmap/grid.js new file mode 100644 index 0000000000..e5470a97bb --- /dev/null +++ b/lib/geom/buffer/heatmap/grid.js @@ -0,0 +1,70 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = gridBuffer; + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } + +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + +function gridBuffer(layerData) { + var attribute = { + vertices: [], + miter: [], + colors: [], + pickingIds: [] + }; + layerData.forEach(function (element) { + var _attribute$colors, _attribute$colors2, _attribute$colors3, _attribute$colors4, _attribute$colors5, _attribute$colors6; + + var color = element.color, + id = element.id; + + var _element$coordinates = _slicedToArray(element.coordinates, 3), + x = _element$coordinates[0], + y = _element$coordinates[1], + z = _element$coordinates[2]; + + attribute.vertices.push(x, y, z); + attribute.miter.push(-1, -1); + attribute.vertices.push(x, y, z); + attribute.miter.push(1, 1); + attribute.vertices.push(x, y, z); + attribute.miter.push(-1, 1); + attribute.vertices.push(x, y, z); + attribute.miter.push(-1, -1); + attribute.vertices.push(x, y, z); + attribute.miter.push(1, -1); + attribute.vertices.push(x, y, z); + attribute.miter.push(1, 1); + + (_attribute$colors = attribute.colors).push.apply(_attribute$colors, _toConsumableArray(color)); + + (_attribute$colors2 = attribute.colors).push.apply(_attribute$colors2, _toConsumableArray(color)); + + (_attribute$colors3 = attribute.colors).push.apply(_attribute$colors3, _toConsumableArray(color)); + + (_attribute$colors4 = attribute.colors).push.apply(_attribute$colors4, _toConsumableArray(color)); + + (_attribute$colors5 = attribute.colors).push.apply(_attribute$colors5, _toConsumableArray(color)); + + (_attribute$colors6 = attribute.colors).push.apply(_attribute$colors6, _toConsumableArray(color)); + + attribute.pickingIds.push(id, id, id, id, id, id); + }); + return attribute; +} \ No newline at end of file diff --git a/lib/geom/buffer/heatmap/grid_3d.js b/lib/geom/buffer/heatmap/grid_3d.js new file mode 100644 index 0000000000..64f449b7fa --- /dev/null +++ b/lib/geom/buffer/heatmap/grid_3d.js @@ -0,0 +1,177 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _buffer = _interopRequireDefault(require("../buffer")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } + +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Grid3D = +/*#__PURE__*/ +function (_BufferBase) { + _inherits(Grid3D, _BufferBase); + + function Grid3D() { + _classCallCheck(this, Grid3D); + + return _possibleConstructorReturn(this, _getPrototypeOf(Grid3D).apply(this, arguments)); + } + + _createClass(Grid3D, [{ + key: "_buildFeatures", + value: function _buildFeatures() { + var _this = this; + + var layerData = this.get('layerData'); + this._offset = 0; + var shapeType = this.get('shapeType'); + layerData.forEach(function (feature) { + _this._calculateTop(feature); + + if (shapeType === 'squareColumn') { + _this._calculateWall(feature); + } + + delete feature.bufferInfo; + }); + } + }, { + key: "_initAttributes", + value: function _initAttributes() { + _get(_getPrototypeOf(Grid3D.prototype), "_initAttributes", this).call(this); + + this.attributes.miters = new Float32Array(this.verticesCount * 3); + this.attributes.normals = new Float32Array(this.verticesCount * 3); + } + }, { + key: "_calculateFeatures", + value: function _calculateFeatures() { + var layerData = this.get('layerData'); + var shapeType = this.get('shapeType'); + + if (shapeType === 'squareColumn') { + this.verticesCount = layerData.length * 20; + } else { + this.verticesCount = layerData.length * 4; + } + + this.indexCount = this.verticesCount * 1.5; + } + }, { + key: "_calculateTop", + value: function _calculateTop(feature) { + var _this2 = this; + + var _feature$coordinates = _slicedToArray(feature.coordinates, 2), + x = _feature$coordinates[0], + y = _feature$coordinates[1]; + + var size = feature.size; + feature.bufferInfo = { + verticesOffset: this._offset + }; + var shapeType = this.get('shapeType'); + + if (shapeType !== 'squareColumn') { + size = 0; + } + + this._encodeArray(feature, 4); + + this.attributes.positions.set([x, y, size, x, y, size, x, y, size, x, y, size], this._offset * 3); + this.attributes.miters.set([-1, 1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1], this._offset * 3); + this.attributes.normals.set([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], this._offset * 3); // top normal + + var indexArray = [0, 2, 1, 2, 3, 1].map(function (v) { + return v + _this2._offset; + }); + this.indexArray.set(indexArray, this._offset * 1.5); + this._offset += 4; + } + }, { + key: "_calculateWall", + value: function _calculateWall(feature) { + var size = feature.size; + + var _feature$coordinates2 = _slicedToArray(feature.coordinates, 2), + x = _feature$coordinates2[0], + y = _feature$coordinates2[1]; + + var vertices = [1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, 1, 1, -1, 1]; + feature.bufferInfo = { + verticesOffset: this._offset + }; + + this._encodeArray(feature, 20); // front left, back right + + + this.attributes.normals.set([0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, // bottom + -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, // left + 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, // top + 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0 // right + ], this._offset * 3); // top normal + + for (var i = 0; i < 4; i++) { + this.attributes.positions.set([x, y, 1, x, y, 1, x, y, 1, x, y, 1], this._offset * 3); + var prePoint = vertices.slice(i * 3, i * 3 + 3); + var nextPoint = vertices.slice(i * 3 + 3, i * 3 + 6); + + this._calculateExtrudeFace(prePoint, nextPoint, this._offset, this._offset * 1.5, size); + + this._offset += 4; + } + } + }, { + key: "_calculateExtrudeFace", + value: function _calculateExtrudeFace(prePoint, nextPoint, positionOffset, indexOffset, size) { + this.attributes.miters.set([prePoint[0], prePoint[1], size, nextPoint[0], nextPoint[1], size, prePoint[0], prePoint[1], 0, nextPoint[0], nextPoint[1], 0], positionOffset * 3); + var indexArray = [0, 1, 2, 1, 3, 2].map(function (v) { + return v + positionOffset; + }); + + if (this.get('uv')) { + // temp 点亮城市demo + this.attributes.uv.set([0.1, 0, 0, 0, 0.1, size / 2000, 0, size / 2000], positionOffset * 2); + } + + this.indexArray.set(indexArray, indexOffset); + } + }]); + + return Grid3D; +}(_buffer["default"]); + +exports["default"] = Grid3D; \ No newline at end of file diff --git a/lib/geom/buffer/heatmap/heatmap.js b/lib/geom/buffer/heatmap/heatmap.js new file mode 100644 index 0000000000..1b16bce4ff --- /dev/null +++ b/lib/geom/buffer/heatmap/heatmap.js @@ -0,0 +1,169 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createColorRamp = createColorRamp; +exports["default"] = void 0; + +var _colorscales = require("../../../attr/colorscales"); + +var THREE = _interopRequireWildcard(require("../../../core/three")); + +var _base = _interopRequireDefault(require("../../../core/base")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var HeatmapBuffer = +/*#__PURE__*/ +function (_Base) { + _inherits(HeatmapBuffer, _Base); + + function HeatmapBuffer(cfg) { + var _this; + + _classCallCheck(this, HeatmapBuffer); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(HeatmapBuffer).call(this, cfg)); + + _this.init(); + + return _this; + } + + _createClass(HeatmapBuffer, [{ + key: "init", + value: function init() { + var _this2 = this; + + var data = this.get('data'); + var positions = []; + var dirs = []; + var weights = []; // const indices = []; + // 组织顶点数据 + + data.forEach(function (d) { + // const totalIndex = index * 4; + var coord = d.coordinates; + var weight = d.size; + + var dir = _this2._addDir(-1, 1); + + var dir1 = _this2._addDir(1, 1); + + var dir2 = _this2._addDir(-1, -1); + + var dir3 = _this2._addDir(1, -1); + + positions.push.apply(positions, _toConsumableArray(coord).concat(_toConsumableArray(coord), _toConsumableArray(coord), _toConsumableArray(coord), _toConsumableArray(coord), _toConsumableArray(coord))); + dirs.push.apply(dirs, _toConsumableArray(dir).concat(_toConsumableArray(dir2), _toConsumableArray(dir3), _toConsumableArray(dir1), _toConsumableArray(dir), _toConsumableArray(dir3))); + weights.push(weight, weight, weight, weight, weight, weight); // indices.push(totalIndex, totalIndex + 2, totalIndex + 3, totalIndex, totalIndex + 3, totalIndex + 1); + }); + this.attributes = { + vertices: positions, + // indices, + dirs: dirs, + weights: weights + }; + } + }, { + key: "_addVertex", + value: function _addVertex(position, dirX, dirY) { + var x = position[0] * 2 + (dirX + 1) / 2; + var y = position[1] * 2 + (dirY + 1) / 2; + var z = position[2]; + return [x, y, z]; + } + }, { + key: "_addDir", + value: function _addDir(dirX, dirY) { + var x = (dirX + 1) / 2; + var y = (dirY + 1) / 2; + return [x, y]; + } + }]); + + return HeatmapBuffer; +}(_base["default"]); + +exports["default"] = HeatmapBuffer; + +function createColorRamp(colors) { + var colorImageData = getColorRamp(colors); + var colorTexture = getTexture(colorImageData); + return colorTexture; +} + +function getColorRamp(name) { + var colorscale = name; + var canvas = document.createElement('canvas'); + var ctx = canvas.getContext('2d'); + canvas.width = 1; + canvas.height = 256; + var gradient = ctx.createLinearGradient(0, 0, 0, 256); + var data = null; + + if (typeof colorscale === 'string') { + colorscale = _colorscales.colorScales[name]; + } + + if (Object.prototype.toString.call(colorscale) === '[object Object]') { + var min = colorscale.positions[0]; + var max = colorscale.positions[colorscale.positions.length - 1]; + + for (var i = 0; i < colorscale.colors.length; ++i) { + var value = (colorscale.positions[i] - min) / (max - min); + gradient.addColorStop(value, colorscale.colors[i]); + } + + ctx.fillStyle = gradient; + ctx.fillRect(0, 0, 1, 256); + data = new Uint8ClampedArray(ctx.getImageData(0, 0, 1, 256).data); + } + + if (Object.prototype.toString.call(colorscale) === '[object Uint8Array]') { + data = ctx.createImageData(1, 256); + } + + return new ImageData(data, 1, 256); +} + +function getTexture(image) { + var texture = new THREE.Texture(image); + texture.wrapS = THREE.ClampToEdgeWrapping; + texture.wrapT = THREE.ClampToEdgeWrapping; + texture.magFilter = THREE.NearestFilter; + texture.minFilter = THREE.NearestFilter; + texture.format = THREE.RGBAFormat; + texture.type = THREE.UnsignedByteType; + texture.needsUpdate = true; + return texture; +} \ No newline at end of file diff --git a/lib/geom/buffer/heatmap/hexagon.js b/lib/geom/buffer/heatmap/hexagon.js new file mode 100644 index 0000000000..6882f4b556 --- /dev/null +++ b/lib/geom/buffer/heatmap/hexagon.js @@ -0,0 +1,44 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = hexagonBuffer; + +var _polygon = require("../../shape/polygon"); + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +function hexagonBuffer(layerData) { + var attribute = { + vertices: [], + miter: [], + colors: [], + pickingIds: [] + }; + var a = Math.cos(Math.PI / 6); + var points = [[0, -1, 0], [-a, -0.5, 0], [-a, 0.5, 0], [0, 1, 0], [a, 0.5, 0], [a, -0.5, 0], [0, -1, 0]]; // const hexgonPoints = polygonPath(6); + + var hexgonFill = (0, _polygon.fill)([points]); + var positionsIndex = hexgonFill.positionsIndex, + positions = hexgonFill.positions; + layerData.forEach(function (element) { + positionsIndex.forEach(function (pointIndex) { + var _attribute$vertices, _attribute$colors; + + (_attribute$vertices = attribute.vertices).push.apply(_attribute$vertices, _toConsumableArray(element.coordinates)); + + attribute.miter.push(positions[pointIndex][0], positions[pointIndex][1]); + attribute.pickingIds.push(element.id); + + (_attribute$colors = attribute.colors).push.apply(_attribute$colors, _toConsumableArray(element.color)); + }); + }); + return attribute; +} \ No newline at end of file diff --git a/lib/geom/buffer/heatmap/hexagon_3d.js b/lib/geom/buffer/heatmap/hexagon_3d.js new file mode 100644 index 0000000000..2c4435e7a2 --- /dev/null +++ b/lib/geom/buffer/heatmap/hexagon_3d.js @@ -0,0 +1,96 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _buffer = _interopRequireDefault(require("../buffer")); + +var _extrude = require("../../extrude"); + +var _global = _interopRequireDefault(require("../../../global")); + +var shapePath = _interopRequireWildcard(require("../../shape/path")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Hexagon3D = +/*#__PURE__*/ +function (_BufferBase) { + _inherits(Hexagon3D, _BufferBase); + + function Hexagon3D() { + _classCallCheck(this, Hexagon3D); + + return _possibleConstructorReturn(this, _getPrototypeOf(Hexagon3D).apply(this, arguments)); + } + + _createClass(Hexagon3D, [{ + key: "_buildFeatures", + value: function _buildFeatures() { + var _this = this; + + var layerData = this.get('layerData'); + this._offset = 0; + layerData.forEach(function (feature) { + _this._calculateFill(feature); + }); + } + }, { + key: "_calculateFeatures", + value: function _calculateFeatures() { + var shape = this.get('shapeType'); + var hexgonFill = this.getShape(shape); + var layerData = this.get('layerData'); + this.verticesCount = layerData.length; + this.indexCount = 0; + this.instanceGeometry = hexgonFill; + } + }, { + key: "_calculateFill", + value: function _calculateFill(feature) { + feature.bufferInfo = { + verticesOffset: this._offset + }; + var coordinates = feature.coordinates; + + this._encodeArray(feature, 1); + + this.attributes.positions.set(coordinates, this._offset * 3); + this._offset++; + } + }, { + key: "getShape", + value: function getShape(shape) { + var pointShape = _global["default"].pointShape; + if (pointShape['3d'].indexOf(shape) !== -1) return (0, _extrude.extrude_Polygon)([shapePath[shape]()]); + if (pointShape['2d'].indexOf(shape) !== -1) return (0, _extrude.fillPolygon)([shapePath[shape]()]); + return (0, _extrude.fillPolygon)([shapePath[shape]()]); + } + }]); + + return Hexagon3D; +}(_buffer["default"]); + +exports["default"] = Hexagon3D; \ No newline at end of file diff --git a/lib/geom/buffer/image.js b/lib/geom/buffer/image.js new file mode 100644 index 0000000000..45f130d210 --- /dev/null +++ b/lib/geom/buffer/image.js @@ -0,0 +1,104 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _util = _interopRequireDefault(require("../../util")); + +var THREE = _interopRequireWildcard(require("../../core/three")); + +var _base = _interopRequireDefault(require("../../core/base")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var ImageBuffer = +/*#__PURE__*/ +function (_Base) { + _inherits(ImageBuffer, _Base); + + function ImageBuffer(cfg) { + var _this; + + _classCallCheck(this, ImageBuffer); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(ImageBuffer).call(this, cfg)); + + _this.init(); + + return _this; + } + + _createClass(ImageBuffer, [{ + key: "init", + value: function init() { + var _this2 = this; + + var layerData = this.get('layerData'); + var coordinates = layerData[0].coordinates; + var images = layerData[0].images; + var positions = [].concat(_toConsumableArray(coordinates[0]), [coordinates[1][0], coordinates[0][1], 0], _toConsumableArray(coordinates[1]), _toConsumableArray(coordinates[0]), _toConsumableArray(coordinates[1]), [coordinates[0][0], coordinates[1][1], 0]); + var image = images; + + if (_util["default"].isArray(images)) { + image = images[0]; + var textures = images.map(function (img) { + return _this2._getTexture(img); + }); + this.u_rasters = textures; + } + + var uv = [0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0]; + var texture = new THREE.Texture(image); + texture.magFilter = THREE.LinearFilter; + texture.minFilter = THREE.LinearMipMapLinearFilter; + texture.needsUpdate = true; + var attributes = { + vertices: new Float32Array(positions), + uvs: new Float32Array(uv) + }; + this.attributes = attributes; + this.texture = texture; + } + }, { + key: "_getTexture", + value: function _getTexture(image) { + var texture = new THREE.Texture(image); + texture.magFilter = THREE.LinearFilter; + texture.minFilter = THREE.LinearFilter; + } + }]); + + return ImageBuffer; +}(_base["default"]); + +exports["default"] = ImageBuffer; \ No newline at end of file diff --git a/lib/geom/buffer/index.js b/lib/geom/buffer/index.js new file mode 100644 index 0000000000..8935a8de6f --- /dev/null +++ b/lib/geom/buffer/index.js @@ -0,0 +1,54 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getBuffer", { + enumerable: true, + get: function get() { + return _factory.getBuffer; + } +}); + +var _fill_buffer = _interopRequireDefault(require("./polygon/fill_buffer")); + +var _line_buffer = _interopRequireDefault(require("./polygon/line_buffer")); + +var _extrude_buffer = _interopRequireDefault(require("./polygon/extrude_buffer")); + +var _fill_buffer2 = _interopRequireDefault(require("./point/fill_buffer2")); + +var _meshline = _interopRequireDefault(require("./line/meshline")); + +var _arcline = _interopRequireDefault(require("./line/arcline")); + +var _hexagon_3d = _interopRequireDefault(require("./heatmap/hexagon_3d")); + +var _extrude_buffer2 = _interopRequireDefault(require("./point/extrude_buffer")); + +var _factory = require("./factory"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +// Polygon +// Point +// Line +// heatmap +// 3D Shape +// Point +(0, _factory.registerBuffer)('point', 'fill', _fill_buffer2["default"]); // polygon + +(0, _factory.registerBuffer)('polygon', 'fill', _fill_buffer["default"]); +(0, _factory.registerBuffer)('polygon', 'extrude', _extrude_buffer["default"]); +(0, _factory.registerBuffer)('polygon', 'line', _line_buffer["default"]); // line + +(0, _factory.registerBuffer)('line', 'line', _meshline["default"]); +(0, _factory.registerBuffer)('line', 'arc', _arcline["default"]); +(0, _factory.registerBuffer)('line', 'greatCircle', _arcline["default"]); // heatmap +// registerBuffer('heatmap', 'square', Grid3D); +// registerBuffer('heatmap', 'squareColumn', Grid3D); + +(0, _factory.registerBuffer)('heatmap', 'shape', _hexagon_3d["default"]); +(0, _factory.registerBuffer)('point', 'shape', _hexagon_3d["default"]); // 3D Shape + +(0, _factory.registerBuffer)('shape', 'extrude', _extrude_buffer2["default"]); \ No newline at end of file diff --git a/lib/geom/buffer/line.js b/lib/geom/buffer/line.js new file mode 100644 index 0000000000..e4c1420aa2 --- /dev/null +++ b/lib/geom/buffer/line.js @@ -0,0 +1,182 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _bufferBase = _interopRequireDefault(require("./bufferBase")); + +var _shape = require("../shape"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var LineBuffer = +/*#__PURE__*/ +function (_BufferBase) { + _inherits(LineBuffer, _BufferBase); + + function LineBuffer() { + _classCallCheck(this, LineBuffer); + + return _possibleConstructorReturn(this, _getPrototypeOf(LineBuffer).apply(this, arguments)); + } + + _createClass(LineBuffer, [{ + key: "geometryBuffer", + value: function geometryBuffer() { + var shapeType = this.shapeType = this.get('shapeType'); + + if (shapeType === 'line') { + this.attributes = this._getMeshLineAttributes(); + return; + } else if (shapeType === 'arc') { + this.attributes = this._getArcLineAttributes(); + return; + } + } + }, { + key: "_getShape", + value: function _getShape(geo, props, index) { + if (!this.shapeType) { + return _shape.lineShape.defaultLine(geo, index); + } + + var shape = this.shapeType; + + if (shape === 'meshLine') { + return _shape.lineShape[shape](geo, props, index); + } else if (shape === 'tubeLine') { + return _shape.lineShape[shape](geo, props, index); + } else if (shape === 'arc') { + return _shape.lineShape[shape](geo, props, index); + } + + return _shape.lineShape.Line(geo, props, index); + } + }, { + key: "_getArcLineAttributes", + value: function _getArcLineAttributes() { + var _this = this; + + var layerData = this.get('layerData'); + var positions = []; + var colors = []; + var indexArray = []; + var sizes = []; + var instances = []; + var pickingIds = []; + layerData.forEach(function (item) { + var props = item; + var positionCount = positions.length / 3; + + var attrData = _this._getShape(item.coordinates, props, positionCount); + + positions.push.apply(positions, _toConsumableArray(attrData.positions)); + colors.push.apply(colors, _toConsumableArray(attrData.colors)); + indexArray.push.apply(indexArray, _toConsumableArray(attrData.indexArray)); + instances.push.apply(instances, _toConsumableArray(attrData.instances)); + sizes.push.apply(sizes, _toConsumableArray(attrData.sizes)); + pickingIds.push.apply(pickingIds, _toConsumableArray(attrData.pickingIds)); + }); + return { + pickingIds: pickingIds, + positions: positions, + colors: colors, + indexArray: indexArray, + sizes: sizes, + instances: instances + }; + } + }, { + key: "_getMeshLineAttributes", + value: function _getMeshLineAttributes() { + var layerData = this.get('layerData'); + + var _this$get = this.get('style'), + dashArray = _this$get.dashArray; + + var imagePos = this.get('imagePos'); + var positions = []; + var pickingIds = []; + var normal = []; + var miter = []; + var colors = []; + var indexArray = []; + var sizes = []; + var attrDistance = []; + var attrDashArray = []; + var textureCoord = []; + var totalDistance = []; + layerData.forEach(function (item) { + var props = item; + var positionCount = positions.length / 3; + var patternPos = { + x: 0, + y: 0 + }; + + if (item.pattern && imagePos[item.pattern]) { + patternPos = imagePos[item.pattern]; + } + + var attr = _shape.lineShape.Line(item.coordinates, props, positionCount, dashArray, patternPos); + + positions.push.apply(positions, _toConsumableArray(attr.positions)); + normal.push.apply(normal, _toConsumableArray(attr.normal)); + miter.push.apply(miter, _toConsumableArray(attr.miter)); + colors.push.apply(colors, _toConsumableArray(attr.colors)); + indexArray.push.apply(indexArray, _toConsumableArray(attr.indexArray)); + sizes.push.apply(sizes, _toConsumableArray(attr.sizes)); + attrDistance.push.apply(attrDistance, _toConsumableArray(attr.attrDistance)); + pickingIds.push.apply(pickingIds, _toConsumableArray(attr.pickingIds)); + attrDashArray.push.apply(attrDashArray, _toConsumableArray(attr.dashArray)); + textureCoord.push.apply(textureCoord, _toConsumableArray(attr.textureCoordArray)); + totalDistance.push.apply(totalDistance, _toConsumableArray(attr.totalDistances)); + }); + return { + positions: positions, + normal: normal, + miter: miter, + colors: colors, + indexArray: indexArray, + pickingIds: pickingIds, + sizes: sizes, + attrDistance: attrDistance, + attrDashArray: attrDashArray, + textureCoord: textureCoord, + totalDistance: totalDistance + }; + } + }]); + + return LineBuffer; +}(_bufferBase["default"]); + +exports["default"] = LineBuffer; \ No newline at end of file diff --git a/lib/geom/buffer/line/arcline.js b/lib/geom/buffer/line/arcline.js new file mode 100644 index 0000000000..c9fd250b45 --- /dev/null +++ b/lib/geom/buffer/line/arcline.js @@ -0,0 +1,110 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _buffer = _interopRequireDefault(require("../buffer")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var ArcLineBuffer = +/*#__PURE__*/ +function (_BufferBase) { + _inherits(ArcLineBuffer, _BufferBase); + + function ArcLineBuffer() { + _classCallCheck(this, ArcLineBuffer); + + return _possibleConstructorReturn(this, _getPrototypeOf(ArcLineBuffer).apply(this, arguments)); + } + + _createClass(ArcLineBuffer, [{ + key: "_buildFeatures", + value: function _buildFeatures() { + var _this = this; + + var layerData = this.get('layerData'); + layerData.forEach(function (feature, index) { + _this._calculateArc(feature, index); + }); + } + }, { + key: "_initAttributes", + value: function _initAttributes() { + _get(_getPrototypeOf(ArcLineBuffer.prototype), "_initAttributes", this).call(this); + + this.attributes.instanceArray = new Float32Array(this.verticesCount * 4); + } + }, { + key: "_calculateArc", + value: function _calculateArc(feature, offset) { + var _this2 = this; + + var _this$get = this.get('style'), + _this$get$segNum = _this$get.segNum, + segNum = _this$get$segNum === void 0 ? 30 : _this$get$segNum; + + var coordinates = feature.coordinates; + + var _loop = function _loop(i) { + _this2.attributes.positions.set([i, 1, i, i, -1, i], offset * segNum * 6 + i * 6); + + _this2.attributes.instanceArray.set([coordinates[0][0], coordinates[0][1], coordinates[1][0], coordinates[1][1], coordinates[0][0], coordinates[0][1], coordinates[1][0], coordinates[1][1]], offset * segNum * 8 + i * 8); + + if (i !== segNum - 1) { + var indexArray = [0, 1, 2, 1, 3, 2].map(function (v) { + return offset * segNum * 2 + i * 2 + v; + }); + + _this2.indexArray.set(indexArray, offset * segNum * 6 + i * 6 - offset * 6); + } + }; + + for (var i = 0; i < segNum; i++) { + _loop(i); + } + + feature.bufferInfo = { + verticesOffset: offset * segNum * 2 + }; + + this._encodeArray(feature, segNum * 2); + } + }, { + key: "_calculateFeatures", + value: function _calculateFeatures() { + var layerData = this.get('layerData'); + var segNum = this.get('segNum') || 30; + this.verticesCount = layerData.length * segNum * 2; + this.indexCount = this.verticesCount * 3 - layerData.length * 6; + } + }]); + + return ArcLineBuffer; +}(_buffer["default"]); + +exports["default"] = ArcLineBuffer; \ No newline at end of file diff --git a/lib/geom/buffer/line/meshline.js b/lib/geom/buffer/line/meshline.js new file mode 100644 index 0000000000..a97bd008ad --- /dev/null +++ b/lib/geom/buffer/line/meshline.js @@ -0,0 +1,142 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _buffer = _interopRequireDefault(require("../buffer")); + +var _polylineNormals = _interopRequireDefault(require("../../../util/polyline-normals")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var MeshLineBuffer = +/*#__PURE__*/ +function (_BufferBase) { + _inherits(MeshLineBuffer, _BufferBase); + + function MeshLineBuffer() { + _classCallCheck(this, MeshLineBuffer); + + return _possibleConstructorReturn(this, _getPrototypeOf(MeshLineBuffer).apply(this, arguments)); + } + + _createClass(MeshLineBuffer, [{ + key: "_buildFeatures", + value: function _buildFeatures() { + var _this = this; + + var layerData = this.get('layerData'); + layerData.forEach(function (feature) { + _this._calculateLine(feature); + + delete feature.bufferInfo; + }); + } + }, { + key: "_initAttributes", + value: function _initAttributes() { + _get(_getPrototypeOf(MeshLineBuffer.prototype), "_initAttributes", this).call(this); + + this.attributes.dashArray = new Float32Array(this.verticesCount); + this.attributes.attrDistance = new Float32Array(this.verticesCount); + this.attributes.totalDistances = new Float32Array(this.verticesCount); + this.attributes.patterns = new Float32Array(this.verticesCount * 2); + this.attributes.miters = new Float32Array(this.verticesCount); + this.attributes.normals = new Float32Array(this.verticesCount * 3); + } + }, { + key: "_calculateFeatures", + value: function _calculateFeatures() { + var _this2 = this; + + var layerData = this.get('layerData'); // 计算长 + + layerData.forEach(function (feature) { + var bufferInfo = {}; + var coordinates = feature.coordinates; + + if (Array.isArray(coordinates[0][0])) { + coordinates = coordinates[0]; + } + + var _getNormals = (0, _polylineNormals["default"])(coordinates, false, _this2.verticesCount), + normals = _getNormals.normals, + attrIndex = _getNormals.attrIndex, + attrPos = _getNormals.attrPos, + attrDistance = _getNormals.attrDistance, + miters = _getNormals.miters; + + bufferInfo.normals = normals; + bufferInfo.arrayIndex = attrIndex; + bufferInfo.positions = attrPos; + bufferInfo.attrDistance = attrDistance; + bufferInfo.miters = miters; + bufferInfo.verticesOffset = _this2.verticesCount; + bufferInfo.indexOffset = _this2.indexCount; + _this2.verticesCount += attrPos.length / 3; + _this2.indexCount += attrIndex.length; + feature.bufferInfo = bufferInfo; + }); + } + }, { + key: "_calculateLine", + value: function _calculateLine(feature) { + var _feature$bufferInfo = feature.bufferInfo, + normals = _feature$bufferInfo.normals, + arrayIndex = _feature$bufferInfo.arrayIndex, + positions = _feature$bufferInfo.positions, + attrDistance = _feature$bufferInfo.attrDistance, + miters = _feature$bufferInfo.miters, + verticesOffset = _feature$bufferInfo.verticesOffset, + indexOffset = _feature$bufferInfo.indexOffset; + + var _this$get = this.get('style'), + _this$get$dashArray = _this$get.dashArray, + dashArray = _this$get$dashArray === void 0 ? 200 : _this$get$dashArray; + + this._encodeArray(feature, positions.length / 3); + + var totalLength = attrDistance[attrDistance.length - 1]; // 增加长度 + + var totalDistances = Array(positions.length / 3).fill(totalLength); // 虚线比例 + + var ratio = dashArray / totalLength; + var dashArrays = Array(positions.length / 3).fill(ratio); + this.attributes.positions.set(positions, verticesOffset * 3); + this.indexArray.set(arrayIndex, indexOffset); + this.attributes.miters.set(miters, verticesOffset); + this.attributes.normals.set(normals, verticesOffset * 3); + this.attributes.attrDistance.set(attrDistance, verticesOffset); + this.attributes.totalDistances.set(totalDistances, verticesOffset); + this.attributes.dashArray.set(dashArrays, verticesOffset); + } + }]); + + return MeshLineBuffer; +}(_buffer["default"]); + +exports["default"] = MeshLineBuffer; \ No newline at end of file diff --git a/lib/geom/buffer/point.js b/lib/geom/buffer/point.js new file mode 100644 index 0000000000..a51cfd7d26 --- /dev/null +++ b/lib/geom/buffer/point.js @@ -0,0 +1,243 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _bufferBase = _interopRequireDefault(require("./bufferBase")); + +var _index = require("../shape/index"); + +var polygonPath = _interopRequireWildcard(require("../shape/path")); + +var polygonShape = _interopRequireWildcard(require("../shape/polygon")); + +var lineShape = _interopRequireWildcard(require("../shape/line")); + +var _global = _interopRequireDefault(require("../../global")); + +var _util = _interopRequireDefault(require("../../util")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } + +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var pointShape = _global["default"].pointShape; + +var PointBuffer = +/*#__PURE__*/ +function (_BufferBase) { + _inherits(PointBuffer, _BufferBase); + + function PointBuffer() { + _classCallCheck(this, PointBuffer); + + return _possibleConstructorReturn(this, _getPrototypeOf(PointBuffer).apply(this, arguments)); + } + + _createClass(PointBuffer, [{ + key: "geometryBuffer", + value: function geometryBuffer() { + var type = this.get('type'); + + switch (type) { + case 'image': + this._imageBuffer(); + + break; + + case '2d': + this._3dRegularBuffer(); + + break; + + case '3d': + this._3dRegularBuffer(); + + break; + + case 'Model': + this._ModelBuffer(); + + break; + + default: + this._sdfRegularBuffer(); + + } + } + }, { + key: "_imageBuffer", + value: function _imageBuffer() { + var coordinates = this.get('coordinates'); + var properties = this.get('properties'); + var imagePos = this.get('imagePos'); + var uv = new Float32Array(properties.length * 2); + + for (var i = 0; i < properties.length; i++) { + var _imagePos$properties$ = imagePos[properties[i].shape], + x = _imagePos$properties$.x, + y = _imagePos$properties$.y; + uv[i * 2] = x; + uv[i * 2 + 1] = y; + } + + this.bufferStruct.position = coordinates; + this.bufferStruct.uv = uv; + this.bufferStruct.style = properties; + this.attributes = this._toPointsAttributes(this.bufferStruct); + this.attributes.uvs = uv; + } + }, { + key: "_sdfRegularBuffer", + value: function _sdfRegularBuffer() { + var coordinates = this.get('coordinates'); + var properties = this.get('properties'); + this.bufferStruct.position = coordinates; + this.bufferStruct.style = properties; + this.attributes = this._toPointsAttributes(this.bufferStruct); + } + }, { + key: "_3dRegularBuffer", + value: function _3dRegularBuffer() { + var _this = this; + + var lineAttribute = { + shapes: [], + normal: [], + miter: [], + indexArray: [], + sizes: [], + positions: [] + }; + var coordinates = this.get('coordinates'); + var properties = this.get('properties'); + var style = this.get('style'); + var type = this.get('type'); + var positions = []; + var shapes = []; + var sizes = []; + var uvs = []; + var positionsIndex = []; + var indexCount = 0; + this.bufferStruct.style = properties; + coordinates.forEach(function (geo, index) { + var _lineAttribute$shapes, _lineAttribute$normal, _lineAttribute$miter, _lineAttribute$indexA; + + var _properties$index = properties[index], + size = _properties$index.size, + shape = _properties$index.shape; // let shapeType = ''; + + if (type === '2d' || type === '3d' && size[2] === 0) { + // let shapeType = 'fill'; + _util["default"].isArray(size) || (size = [size, size, 0]); + } else { + _util["default"].isArray(size) || (size = [size, size, size]); + } + + if (_index.regularShape[shape] == null) { + uvs.push(0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0); + shape = 'square'; + } + + properties[index].size = size; + + var _this$_getShape = _this._getShape(properties[index], style, lineAttribute.miter.length), + _this$_getShape2 = _slicedToArray(_this$_getShape, 2), + vert = _this$_getShape2[0], + polygonLine = _this$_getShape2[1]; + + polygonLine.miter.forEach(function () { + var _lineAttribute$positi, _lineAttribute$sizes; + + (_lineAttribute$positi = lineAttribute.positions).push.apply(_lineAttribute$positi, _toConsumableArray(geo)); + + (_lineAttribute$sizes = lineAttribute.sizes).push.apply(_lineAttribute$sizes, _toConsumableArray(size)); + }); + + (_lineAttribute$shapes = lineAttribute.shapes).push.apply(_lineAttribute$shapes, _toConsumableArray(polygonLine.positions)); + + (_lineAttribute$normal = lineAttribute.normal).push.apply(_lineAttribute$normal, _toConsumableArray(polygonLine.normal)); + + (_lineAttribute$miter = lineAttribute.miter).push.apply(_lineAttribute$miter, _toConsumableArray(polygonLine.miter)); + + (_lineAttribute$indexA = lineAttribute.indexArray).push.apply(_lineAttribute$indexA, _toConsumableArray(polygonLine.indexArray)); + + shapes.push(vert.positions); + positions.push(geo); + sizes.push(size); + positionsIndex.push(vert.positionsIndex); + indexCount += vert.positionsIndex.length; + }); + this.bufferStruct.indices = positionsIndex; + this.bufferStruct.position = positions; + this.bufferStruct.indexCount = indexCount; + this.bufferStruct.shapes = shapes; + this.bufferStruct.sizes = sizes; + this.bufferStruct.faceUv = uvs; + this.attributes = this._toPointShapeAttributes(this.bufferStruct); + this.lineAttribute = lineAttribute; + } + }, { + key: "_getShape", + value: function _getShape(props, style, positionsIndex) { + var shape = props.shape; + var stroke = style.stroke, + strokeWidth = style.strokeWidth; + var path = polygonPath[shape](); + var polygon = null; + var polygonLine = null; + + if (pointShape['3d'].indexOf(shape) === -1) { + polygon = polygonShape.fill([path]); + polygonLine = lineShape.Line(path, { + size: [strokeWidth, 0], + color: stroke + }, positionsIndex); + } else { + polygon = polygonShape.extrude([path]); + } + + return [polygon, polygonLine]; + } + }]); + + return PointBuffer; +}(_bufferBase["default"]); + +exports["default"] = PointBuffer; \ No newline at end of file diff --git a/lib/geom/buffer/point/circleBuffer.js b/lib/geom/buffer/point/circleBuffer.js new file mode 100644 index 0000000000..2ed371940e --- /dev/null +++ b/lib/geom/buffer/point/circleBuffer.js @@ -0,0 +1,66 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = circleBuffer; + +var _vertexCompress = require("../../../util/vertex-compress"); + +var _global = _interopRequireDefault(require("../../../global")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +var pointShape = _global["default"].pointShape; +var LEFT_SHIFT17 = 131072.0; // const LEFT_SHIFT18 = 262144.0; +// const LEFT_SHIFT19 = 524288.0; +// const LEFT_SHIFT20 = 1048576.0; + +var LEFT_SHIFT21 = 2097152.0; // const LEFT_SHIFT22 = 4194304.0; + +var LEFT_SHIFT23 = 8388608.0; // const LEFT_SHIFT24 = 16777216.0; + +function circleBuffer(layerData) { + var index = []; + var aPosition = []; + var aPackedData = []; + layerData.forEach(function (_ref, i) { + var _ref$size = _ref.size, + size = _ref$size === void 0 ? 0 : _ref$size, + color = _ref.color, + id = _ref.id, + coordinates = _ref.coordinates, + shape = _ref.shape; + var shapeIndex = pointShape['2d'].indexOf(shape) || 0; + + if (isNaN(size)) { + size = 0; + } // pack color(vec4) into vec2 + + + var packedColor = [(0, _vertexCompress.packUint8ToFloat)(color[0] * 255, color[1] * 255), (0, _vertexCompress.packUint8ToFloat)(color[2] * 255, color[3] * 255)]; // construct point coords + + [[-1, -1], [1, -1], [1, 1], [-1, 1]].forEach(function (extrude) { + // vec4(color, color, (4-bit extrude, 4-bit shape, 16-bit size), id) + aPackedData.push.apply(aPackedData, packedColor.concat([(extrude[0] + 1) * LEFT_SHIFT23 + (extrude[1] + 1) * LEFT_SHIFT21 + shapeIndex * LEFT_SHIFT17 + size, id])); + }); // TODO:如果使用相对瓦片坐标,还可以进一步压缩 + + aPosition.push.apply(aPosition, _toConsumableArray(coordinates).concat(_toConsumableArray(coordinates), _toConsumableArray(coordinates), _toConsumableArray(coordinates))); + index.push.apply(index, _toConsumableArray([0, 1, 2, 0, 2, 3].map(function (n) { + return n + i * 4; + }))); + }); + return { + aPosition: aPosition, + index: index, + aPackedData: aPackedData + }; +} \ No newline at end of file diff --git a/lib/geom/buffer/point/extrude_buffer.js b/lib/geom/buffer/point/extrude_buffer.js new file mode 100644 index 0000000000..4b79229ee3 --- /dev/null +++ b/lib/geom/buffer/point/extrude_buffer.js @@ -0,0 +1,174 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _buffer = _interopRequireDefault(require("../buffer")); + +var _global = _interopRequireDefault(require("../../../global")); + +var _extrude = require("../../extrude"); + +var shapePath = _interopRequireWildcard(require("../../shape/path")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var ExtrudeBuffer = +/*#__PURE__*/ +function (_BufferBase) { + _inherits(ExtrudeBuffer, _BufferBase); + + function ExtrudeBuffer() { + _classCallCheck(this, ExtrudeBuffer); + + return _possibleConstructorReturn(this, _getPrototypeOf(ExtrudeBuffer).apply(this, arguments)); + } + + _createClass(ExtrudeBuffer, [{ + key: "_buildFeatures", + value: function _buildFeatures() { + var _this = this; + + var layerData = this.get('layerData'); + this._offset = 0; + this._indexOffset = 0; + layerData.forEach(function (feature) { + _this._calculateFill(feature); + }); + } + }, { + key: "_initAttributes", + value: function _initAttributes() { + _get(_getPrototypeOf(ExtrudeBuffer.prototype), "_initAttributes", this).call(this); + + this.attributes.miters = new Float32Array(this.verticesCount * 3); + this.attributes.normals = new Float32Array(this.verticesCount * 3); + this.attributes.sizes = new Float32Array(this.verticesCount * 3); + } + }, { + key: "_calculateFeatures", + value: function _calculateFeatures() { + var _this2 = this; + + var layerData = this.get('layerData'); + this.geometryMap = {}; + layerData.forEach(function (feature) { + var shape = feature.shape; + + var _this2$getShape = _this2.getShape(shape), + positions = _this2$getShape.positions, + indexArray = _this2$getShape.indexArray; + + _this2.verticesCount += positions.length / 3; + _this2.indexCount += indexArray.length; + }); + } + }, { + key: "_calcultateGeometry", + value: function _calcultateGeometry() { + var shape = this.get('shapeType'); + var hexgonFill = this.getShapeFunction(shape)([this._getPoints(6)]); + this.instanceGeometry = hexgonFill; + } + }, { + key: "_calculateFill", + value: function _calculateFill(feature) { + var _this3 = this; + + feature.bufferInfo = { + verticesOffset: this._offset + }; + var coordinates = feature.coordinates, + shape = feature.shape; + var instanceGeometry = this.getShape(shape); + var numPoint = instanceGeometry.positions.length / 3; + + this._encodeArray(feature, numPoint); + + this.attributes.miters.set(instanceGeometry.positions, this._offset * 3); + var indexArray = instanceGeometry.indexArray.map(function (v) { + return v + _this3._offset; + }); + this.indexArray.set(indexArray, this._indexOffset); + + if (instanceGeometry.normals) { + this.attributes.normals.set(instanceGeometry.normals, this._offset * 3); + } + + var position = []; + + for (var i = 0; i < numPoint; i++) { + position.push.apply(position, _toConsumableArray(coordinates)); + } + + this.attributes.positions.set(position, this._offset * 3); + this._offset += numPoint; + this._indexOffset += indexArray.length; + } + }, { + key: "_getPoints", + value: function _getPoints(num) { + return (0, shapePath.polygonPath)(num, 1); + } + }, { + key: "getShape", + value: function getShape(shape) { + var pointShape = _global["default"].pointShape; + + if (this.geometryMap[shape]) { + return this.geometryMap[shape]; + } + + var geometry = null; + + if (pointShape['3d'].indexOf(shape) !== -1) { + geometry = (0, _extrude.extrude_Polygon)([shapePath[shape]()]); + } else if (pointShape['2d'].indexOf(shape) !== -1) { + geometry = (0, _extrude.fillPolygon)([shapePath[shape]()]); + } else { + geometry = (0, _extrude.fillPolygon)([shapePath[shape]()]); + } + + this.geometryMap[shape] = geometry; + return geometry; + } + }]); + + return ExtrudeBuffer; +}(_buffer["default"]); + +exports["default"] = ExtrudeBuffer; \ No newline at end of file diff --git a/lib/geom/buffer/point/fillBuffer.js b/lib/geom/buffer/point/fillBuffer.js new file mode 100644 index 0000000000..392dea32a1 --- /dev/null +++ b/lib/geom/buffer/point/fillBuffer.js @@ -0,0 +1,127 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = fillBuffer; + +var _global = _interopRequireDefault(require("../../../global")); + +var THREE = _interopRequireWildcard(require("../../../core/three")); + +var polygonShape = _interopRequireWildcard(require("../../shape/polygon")); + +var polygonPath = _interopRequireWildcard(require("../../shape/path")); + +var _util = _interopRequireDefault(require("../../../util")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +var pointShape = _global["default"].pointShape; + +function fillBuffer(layerData) { + var attribute = { + vertices: [], + normals: [], + colors: [], + pickingIds: [], + shapePositions: [], + a_size: [], + faceUv: [] + }; + layerData.forEach(function (item) { + var size = item.size, + shape = item.shape, + color = item.color, + id = item.id, + coordinates = item.coordinates; + var polygon = null; + var path = polygonPath[shape](); + + if (pointShape['2d'].indexOf(shape) !== -1) { + _util["default"].isArray(size) || (size = [size, size, 0]); + polygon = polygonShape.fill([path]); + } else if (pointShape['3d'].indexOf(shape) !== -1) { + _util["default"].isArray(size) || (size = [size, size, size]); + polygon = polygonShape.extrude([path]); + } else { + throw new Error('Invalid shape type: ' + shape); + } + + toPointShapeAttributes(polygon, coordinates, { + size: size, + shape: shape, + color: color, + id: id + }, attribute); // toPointShapeAttributes(polygon, null, {}, attribute); + // instanced attributes + // attribute.vertices.push(...coordinates); + // attribute.a_size.push(...size); + // attribute.colors.push(...color); + // attribute.pickingIds.push(id); + }); + return attribute; +} + +function toPointShapeAttributes(polygon, geo, style, attribute) { + var positionsIndex = polygon.positionsIndex, + positions = polygon.positions; + var pA = new THREE.Vector3(); + var pB = new THREE.Vector3(); + var pC = new THREE.Vector3(); + var cb = new THREE.Vector3(); + var ab = new THREE.Vector3(); + + for (var i = 0; i < positionsIndex.length / 3; i++) { + var _attribute$vertices, _attribute$a_size, _attribute$colors; + + var index = positionsIndex[i * 3]; + var color = style.color, + size = style.size, + id = style.id; + var ax = positions[index][0]; + var ay = positions[index][1]; + var az = positions[index][2]; + index = positionsIndex[i * 3 + 1]; + var bx = positions[index][0]; + var by = positions[index][1]; + var bz = positions[index][2]; + index = positionsIndex[i * 3 + 2]; + var cx = positions[index][0]; + var cy = positions[index][1]; + var cz = positions[index][2]; + pA.set(ax, ay, az); + pB.set(bx, by, bz); + pC.set(cx, cy, cz); + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + cb.normalize(); + var nx = cb.x; + var ny = cb.y; + var nz = cb.z; + + (_attribute$vertices = attribute.vertices).push.apply(_attribute$vertices, _toConsumableArray(geo).concat(_toConsumableArray(geo), _toConsumableArray(geo))); + + attribute.shapePositions.push(ax, ay, az, bx, by, bz, cx, cy, cz); + + (_attribute$a_size = attribute.a_size).push.apply(_attribute$a_size, _toConsumableArray(size).concat(_toConsumableArray(size), _toConsumableArray(size))); + + attribute.normals.push(nx, ny, nz, nx, ny, nz, nx, ny, nz); + + (_attribute$colors = attribute.colors).push.apply(_attribute$colors, _toConsumableArray(color).concat(_toConsumableArray(color), _toConsumableArray(color))); + + attribute.pickingIds.push(id, id, id); // attribute.shapePositions.push(ax, ay, az, bx, by, bz, cx, cy, cz); + // attribute.normals.push(nx, ny, nz, nx, ny, nz, nx, ny, nz); + } +} \ No newline at end of file diff --git a/lib/geom/buffer/point/fill_buffer.js b/lib/geom/buffer/point/fill_buffer.js new file mode 100644 index 0000000000..f9c99a42b2 --- /dev/null +++ b/lib/geom/buffer/point/fill_buffer.js @@ -0,0 +1,74 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = FillBuffer; + +var _vertexCompress = require("../../../util/vertex-compress"); + +var _global = _interopRequireDefault(require("../../../global")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +var pointShape = _global["default"].pointShape; +var LEFT_SHIFT17 = 131072.0; // const LEFT_SHIFT18 = 262144.0; +// const LEFT_SHIFT19 = 524288.0; +// const LEFT_SHIFT20 = 1048576.0; + +var LEFT_SHIFT21 = 2097152.0; // const LEFT_SHIFT22 = 4194304.0; + +var LEFT_SHIFT23 = 8388608.0; // const LEFT_SHIFT24 = 16777216.0; + +function FillBuffer(data) { + var index = []; + var aPosition = []; + var aPackedData = []; + var layerData = data.layerData; + layerData.forEach(function (_ref, i) { + var _ref$size = _ref.size, + size = _ref$size === void 0 ? 0 : _ref$size, + color = _ref.color, + id = _ref.id, + coordinates = _ref.coordinates, + shape = _ref.shape; + var shapeIndex = pointShape['2d'].indexOf(shape) || 0; + var newCoord = coordinates; + + if (coordinates.length === 1) { + newCoord = coordinates[0][0]; + } + + if (isNaN(size)) { + size = 0; + } // pack color(vec4) into vec2 + + + var packedColor = [(0, _vertexCompress.packUint8ToFloat)(color[0] * 255, color[1] * 255), (0, _vertexCompress.packUint8ToFloat)(color[2] * 255, color[3] * 255)]; // construct point coords + + [[-1, -1], [1, -1], [1, 1], [-1, 1]].forEach(function (extrude) { + // vec4(color, color, (4-bit extrude, 4-bit shape, 16-bit size), id) + aPackedData.push.apply(aPackedData, packedColor.concat([(extrude[0] + 1) * LEFT_SHIFT23 + (extrude[1] + 1) * LEFT_SHIFT21 + shapeIndex * LEFT_SHIFT17 + size, id])); + }); // TODO:如果使用相对瓦片坐标,还可以进一步压缩 + + aPosition.push.apply(aPosition, _toConsumableArray(newCoord).concat(_toConsumableArray(newCoord), _toConsumableArray(newCoord), _toConsumableArray(newCoord))); + index.push.apply(index, _toConsumableArray([0, 1, 2, 0, 2, 3].map(function (n) { + return n + i * 4; + }))); + }); + return { + attributes: { + aPosition: new Float32Array(aPosition), + aPackedData: new Float32Array(aPackedData) + }, + indexArray: new Int32Array(index) + }; +} \ No newline at end of file diff --git a/lib/geom/buffer/point/fill_buffer2.js b/lib/geom/buffer/point/fill_buffer2.js new file mode 100644 index 0000000000..d8616435ff --- /dev/null +++ b/lib/geom/buffer/point/fill_buffer2.js @@ -0,0 +1,168 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _buffer = _interopRequireDefault(require("../buffer")); + +var _global = _interopRequireDefault(require("../../../global")); + +var _extrude = require("../../extrude"); + +var shapePath = _interopRequireWildcard(require("../../shape/path")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var pointShape = _global["default"].pointShape; + +var PointFillBuffer = +/*#__PURE__*/ +function (_BufferBase) { + _inherits(PointFillBuffer, _BufferBase); + + function PointFillBuffer() { + _classCallCheck(this, PointFillBuffer); + + return _possibleConstructorReturn(this, _getPrototypeOf(PointFillBuffer).apply(this, arguments)); + } + + _createClass(PointFillBuffer, [{ + key: "_buildFeatures", + value: function _buildFeatures() { + var _this = this; + + var layerData = this.get('layerData'); + this._offset = 0; + this._indexOffset = 0; + layerData.forEach(function (feature) { + _this._calculateFill(feature); + }); + } + }, { + key: "_initAttributes", + value: function _initAttributes() { + _get(_getPrototypeOf(PointFillBuffer.prototype), "_initAttributes", this).call(this); + + this.attributes.miters = new Float32Array(this.verticesCount * 2); + this.attributes.sizes = new Float32Array(this.verticesCount); + this.attributes.shapes = new Float32Array(this.verticesCount); + } + }, { + key: "_calculateFeatures", + value: function _calculateFeatures() { + var layerData = this.get('layerData'); + this.verticesCount = layerData.length * 4; + this.indexCount = layerData.length * 6; + } + }, { + key: "_calcultateGeometry", + value: function _calcultateGeometry() { + var shape = this.get('shapeType'); + var hexgonFill = this.getShapeFunction(shape)([this._getPoints(6)]); + this.instanceGeometry = hexgonFill; + } + }, { + key: "_calculateFill", + value: function _calculateFill(feature) { + var _this2 = this; + + feature.bufferInfo = { + verticesOffset: this._offset + }; + var coordinates = feature.coordinates, + shape = feature.shape; + var shapeIndex = pointShape['2d'].indexOf(shape) || 0; + var newCoord = coordinates; + + if (coordinates.length === 1) { + newCoord = coordinates[0][0]; + } + + feature.bufferInfo = { + verticesOffset: this._offset + }; + + this._encodeArray(feature, 4); + + this.attributes.shapes.set([shapeIndex, shapeIndex, shapeIndex, shapeIndex], this._offset); + this.attributes.miters.set([-1, -1, 1, -1, 1, 1, -1, 1], this._offset * 2); + var indexArray = [0, 1, 2, 0, 2, 3].map(function (n) { + return n + _this2._offset; + }); + this.indexArray.set(indexArray, this._offset * 1.5); + var position = []; + + for (var i = 0; i < 4; i++) { + position.push.apply(position, _toConsumableArray(newCoord)); + } + + this.attributes.positions.set(position, this._offset * 3); + this._offset += 4; + } + }, { + key: "_getPoints", + value: function _getPoints(num) { + return (0, shapePath.polygonPath)(num, 1); + } + }, { + key: "getShape", + value: function getShape(shape) { + var pointShape = _global["default"].pointShape; + + if (this.geometryMap[shape]) { + return this.geometryMap[shape]; + } + + var geometry = null; + + if (pointShape['3d'].indexOf(shape) !== -1) { + geometry = (0, _extrude.extrude_Polygon)([shapePath[shape]()]); + } else if (pointShape['2d'].indexOf(shape) !== -1) { + geometry = (0, _extrude.fillPolygon)([shapePath[shape]()]); + } else { + geometry = (0, _extrude.fillPolygon)([shapePath[shape]()]); + } + + this.geometryMap[shape] = geometry; + return geometry; + } + }]); + + return PointFillBuffer; +}(_buffer["default"]); + +exports["default"] = PointFillBuffer; \ No newline at end of file diff --git a/lib/geom/buffer/point/imageBuffer.js b/lib/geom/buffer/point/imageBuffer.js new file mode 100644 index 0000000000..97b278e213 --- /dev/null +++ b/lib/geom/buffer/point/imageBuffer.js @@ -0,0 +1,48 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = ImageBuffer; + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +function ImageBuffer(layerData, opt) { + var attributes = { + vertices: [], + colors: [], + sizes: [], + shapes: [], + pickingIds: [], + uv: [] + }; + layerData.forEach(function (item) { + var _attributes$vertices, _attributes$colors; + + var color = item.color, + size = item.size, + id = item.id, + shape = item.shape, + coordinates = item.coordinates; + var _opt$imagePos$shape = opt.imagePos[shape], + x = _opt$imagePos$shape.x, + y = _opt$imagePos$shape.y; + + (_attributes$vertices = attributes.vertices).push.apply(_attributes$vertices, _toConsumableArray(coordinates)); + + (_attributes$colors = attributes.colors).push.apply(_attributes$colors, _toConsumableArray(color)); + + attributes.pickingIds.push(id); + attributes.sizes.push(size * window.devicePixelRatio); // + + attributes.uv.push(x, y); + attributes.shapes.push(shape); + }); + return attributes; +} \ No newline at end of file diff --git a/lib/geom/buffer/point/image_buffer.js b/lib/geom/buffer/point/image_buffer.js new file mode 100644 index 0000000000..97b278e213 --- /dev/null +++ b/lib/geom/buffer/point/image_buffer.js @@ -0,0 +1,48 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = ImageBuffer; + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +function ImageBuffer(layerData, opt) { + var attributes = { + vertices: [], + colors: [], + sizes: [], + shapes: [], + pickingIds: [], + uv: [] + }; + layerData.forEach(function (item) { + var _attributes$vertices, _attributes$colors; + + var color = item.color, + size = item.size, + id = item.id, + shape = item.shape, + coordinates = item.coordinates; + var _opt$imagePos$shape = opt.imagePos[shape], + x = _opt$imagePos$shape.x, + y = _opt$imagePos$shape.y; + + (_attributes$vertices = attributes.vertices).push.apply(_attributes$vertices, _toConsumableArray(coordinates)); + + (_attributes$colors = attributes.colors).push.apply(_attributes$colors, _toConsumableArray(color)); + + attributes.pickingIds.push(id); + attributes.sizes.push(size * window.devicePixelRatio); // + + attributes.uv.push(x, y); + attributes.shapes.push(shape); + }); + return attributes; +} \ No newline at end of file diff --git a/lib/geom/buffer/point/index.js b/lib/geom/buffer/point/index.js new file mode 100644 index 0000000000..df9dbc5a56 --- /dev/null +++ b/lib/geom/buffer/point/index.js @@ -0,0 +1,47 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "FillBuffer", { + enumerable: true, + get: function get() { + return _fillBuffer["default"]; + } +}); +Object.defineProperty(exports, "StrokeBuffer", { + enumerable: true, + get: function get() { + return _strokeBuffer["default"]; + } +}); +Object.defineProperty(exports, "ImageBuffer", { + enumerable: true, + get: function get() { + return _image_buffer["default"]; + } +}); +Object.defineProperty(exports, "NormalBuffer", { + enumerable: true, + get: function get() { + return _normalBuffer["default"]; + } +}); +Object.defineProperty(exports, "CircleBuffer", { + enumerable: true, + get: function get() { + return _fill_buffer["default"]; + } +}); + +var _fillBuffer = _interopRequireDefault(require("./fillBuffer")); + +var _strokeBuffer = _interopRequireDefault(require("./strokeBuffer")); + +var _image_buffer = _interopRequireDefault(require("./image_buffer")); + +var _normalBuffer = _interopRequireDefault(require("./normalBuffer")); + +var _fill_buffer = _interopRequireDefault(require("./fill_buffer")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } \ No newline at end of file diff --git a/lib/geom/buffer/point/normalBuffer.js b/lib/geom/buffer/point/normalBuffer.js new file mode 100644 index 0000000000..2500d04fca --- /dev/null +++ b/lib/geom/buffer/point/normalBuffer.js @@ -0,0 +1,39 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = NormalBuffer; + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +function NormalBuffer(layerData) { + var attributes = { + vertices: [], + colors: [], + sizes: [], + pickingIds: [] + }; + layerData.forEach(function (item) { + var _attributes$vertices, _attributes$colors; + + var color = item.color, + size = item.size, + id = item.id, + coordinates = item.coordinates; + + (_attributes$vertices = attributes.vertices).push.apply(_attributes$vertices, _toConsumableArray(coordinates)); + + (_attributes$colors = attributes.colors).push.apply(_attributes$colors, _toConsumableArray(color)); + + attributes.pickingIds.push(id); + attributes.sizes.push(size); + }); + return attributes; +} \ No newline at end of file diff --git a/lib/geom/buffer/point/sdfCommonWords.js b/lib/geom/buffer/point/sdfCommonWords.js new file mode 100644 index 0000000000..4387347136 --- /dev/null +++ b/lib/geom/buffer/point/sdfCommonWords.js @@ -0,0 +1,178 @@ +// const SDFCommonWordsKey = '_AMap_sdf_com_words'; +// /** +// * SDF 常用字获取/存储/check +// * +// */ +// const SDFCommonWords = { +// store() { +// }, +// /** +// * 检查一个字符是否在常用字中 +// * @param {*} charcode 汉字 +// */ +// check(charcode) { +// const range = this.range || []; +// const info = this.info || {}; +// if (typeof charcode !== 'number') { +// charcode = charcode.substr(0).charCodeAt(0); +// } +// for (let i = 0; i < range.length; i++) { +// const curRange = range[i]; +// const [ rangeStart, rangeEnd ] = curRange.split('-'); +// if (charcode >= rangeStart && charcode <= rangeEnd) { +// const curInfo = info[curRange] && info[curRange].info || {}; +// if (curInfo[charcode]) { +// return true; +// } +// } +// } +// return false; +// }, +// /** +// * 获取纹理和位置信息 +// * @param list +// * @param cb +// */ +// getImagesAndInfo(list, cb) { +// const range = this.range; +// }, +// loadCanvas(url, range, done) { +// try { +// const xhr = new XMLHttpRequest(); +// xhr.open('GET', url); +// // 直接用 blob 格式 load 图片文件,方便直接转换成 base64 +// // 转成 base64 便于存储 +// // 使用 canvas 转换 base64 容易有损 +// xhr.responseType = 'blob'; +// xhr.onerror = function() { +// done({ code: 0 }); +// }; +// xhr.onload = function() { +// if (xhr.status === 200) { +// const reader = new FileReader(); +// reader.onload = () => { +// done(reader.result, range); +// }; +// reader.readAsDataURL(xhr.response); +// } else { +// done({ code: 0 }); +// } +// }; +// xhr.send(); +// } catch (err) { +// done({ code: 0 }); +// } +// }, +// loadImages(urls = []) { +// const deferred = $.Deferred(); +// const totalNumbers = urls.length; +// const localInfo = this.info; +// let loadPicNum = 0; +// for (let i = 0; i < urls.length; i++) { +// const { url, range } = urls[i]; +// this.loadCanvas(url, range, (base64, range) => { +// // image to base64 +// loadPicNum++; +// !localInfo[range] && (localInfo[range] = {}); +// localInfo[range].pic = base64; +// this.info = localInfo; +// // todo: temp 暂时用 localstorage 存储,因为数据比较大,最好使用 indexDB +// localStorage.setItem(SDFCommonWordsKey, JSON.stringify(localInfo)); +// if (loadPicNum === totalNumbers) { +// deferred.resolve(); +// } +// }); +// } +// return deferred; +// }, +// loadInfo(urls) { +// const deferred = $.Deferred(); +// const totalNumbers = urls.length; +// const localInfo = this.info; +// let loadInfoNum = 0; +// for (let i = 0; i < urls.length; i++) { +// const { url, range } = urls[i]; +// $.ajax({ +// url, +// dataType: 'json', +// success: data => { +// loadInfoNum++; +// !localInfo[range] && (localInfo[range] = {}); +// localInfo[range].info = data; +// this.info = localInfo; +// localStorage.setItem(SDFCommonWordsKey, JSON.stringify(localInfo)); +// if (loadInfoNum === totalNumbers) { +// deferred.resolve(); +// } +// }, +// error: () => { +// } +// }); +// } +// return deferred; +// }, +// getTotalAssets(info, cb) { +// const { range = [], urlPrefix } = info; +// const picUrls = []; +// const infoUrls = []; +// this.range = range; +// for (let i = 0; i < range.length; i++) { +// const curRange = range[i]; +// const baseUrl = urlPrefix + curRange; +// const picUrl = baseUrl + '.png'; +// const infoUrl = baseUrl + '.json'; +// picUrls.push({ range: curRange, url: picUrl }); +// infoUrls.push({ range: curRange, url: infoUrl }); +// } +// const imageDeferred = this.loadImages(picUrls); +// const infoDeferred = this.loadInfo(infoUrls); +// $.when(imageDeferred, infoDeferred) +// .then(() => { +// // all info load complete +// // console.log("all info load complete", " -- ", 1); +// cb && cb(this.info); +// }, () => { +// // fail +// }); +// }, +// // 获取数据 +// getData(cb) { +// if (!_.isEmpty(this.info)) { +// cb && cb(this.info); +// } else { +// this.getRemoteData(cb); +// } +// }, +// /** +// * 从服务获取数据,什么时候强制去取一回数据?过期? +// * @param cb +// */ +// getRemoteData(cb) { +// const self = this; +// $.ajax({ +// url: '/getcommonwords', +// dataType: 'json', +// success: data => { +// if (data.code == 1) { +// const info = data.data; +// self.getTotalAssets(info, cb); +// } +// } +// }); +// }, +// destroy() { +// }, +// init() { +// let info = localStorage.getItem(SDFCommonWordsKey); +// this.range = []; +// this.info = {}; +// if (info) { +// info = JSON.parse(info); +// this.range = Object.keys(info); +// this.info = info; +// } +// this.info = info || {}; +// } +// }; +// export default SDFCommonWords; +"use strict"; \ No newline at end of file diff --git a/lib/geom/buffer/point/strokeBuffer.js b/lib/geom/buffer/point/strokeBuffer.js new file mode 100644 index 0000000000..53316efa0a --- /dev/null +++ b/lib/geom/buffer/point/strokeBuffer.js @@ -0,0 +1,103 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = StrokeBuffer; + +var polygonPath = _interopRequireWildcard(require("../../shape/path")); + +var polygonShape = _interopRequireWildcard(require("../../shape/polygon")); + +var lineShape = _interopRequireWildcard(require("../../shape/line")); + +var _global = _interopRequireDefault(require("../../../global")); + +var _util = _interopRequireDefault(require("../../../util")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +var pointShape = _global["default"].pointShape; + +function StrokeBuffer(layerData, style) { + var attribute = { + shapes: [], + normal: [], + miter: [], + indexArray: [], + sizes: [], + positions: [], + pickingIds: [], + colors: [] + }; + var stroke = style.stroke, + strokeWidth = style.strokeWidth; + layerData.forEach(function (item) { + var size = item.size, + shape = item.shape, + id = item.id, + coordinates = item.coordinates; + var path = polygonPath[shape](); + var positionsIndex = attribute.miter.length; + var polygon = null; + + if (pointShape['2d'].indexOf(shape) !== -1) { + _util["default"].isArray(size) || (size = [size, size, 0]); + polygon = lineShape.Line([path], { + size: [strokeWidth, 0], + color: stroke, + id: id + }, positionsIndex); + } else if (pointShape['3d'].indexOf(shape) !== -1) { + _util["default"].isArray(size) || (size = [size, size, size]); + var polygonExtrudePath = polygonShape.extrudeline([path]); // TODO 3d line + + polygon = lineShape.Line([polygonExtrudePath], { + size: [strokeWidth, 0], + color: stroke, + id: id + }, positionsIndex); + } else { + throw new Error('Invalid shape type: ' + shape); + } + + polygonLineBuffer(polygon, coordinates, size, attribute); + }); + return attribute; +} + +function polygonLineBuffer(polygon, geo, size, attribute) { + var _attribute$shapes, _attribute$normal, _attribute$miter, _attribute$pickingIds, _attribute$indexArray, _attribute$colors; + + (_attribute$shapes = attribute.shapes).push.apply(_attribute$shapes, _toConsumableArray(polygon.positions)); + + (_attribute$normal = attribute.normal).push.apply(_attribute$normal, _toConsumableArray(polygon.normal)); + + (_attribute$miter = attribute.miter).push.apply(_attribute$miter, _toConsumableArray(polygon.miter)); + + (_attribute$pickingIds = attribute.pickingIds).push.apply(_attribute$pickingIds, _toConsumableArray(polygon.pickingIds)); + + (_attribute$indexArray = attribute.indexArray).push.apply(_attribute$indexArray, _toConsumableArray(polygon.indexArray)); + + (_attribute$colors = attribute.colors).push.apply(_attribute$colors, _toConsumableArray(polygon.colors)); + + polygon.miter.forEach(function () { + var _attribute$positions, _attribute$sizes; + + (_attribute$positions = attribute.positions).push.apply(_attribute$positions, _toConsumableArray(geo)); // 多边形位置 + + + (_attribute$sizes = attribute.sizes).push.apply(_attribute$sizes, _toConsumableArray(size)); // 多边形大小 + + }); +} \ No newline at end of file diff --git a/lib/geom/buffer/point/text.js b/lib/geom/buffer/point/text.js new file mode 100644 index 0000000000..a2656e8f57 --- /dev/null +++ b/lib/geom/buffer/point/text.js @@ -0,0 +1,86 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = TextBuffer; + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +function TextBuffer(layerData, fontAtlasManager) { + var characterSet = []; + layerData.forEach(function (element) { + var text = element.shape || ''; + text = text.toString(); + + for (var j = 0; j < text.length; j++) { + if (characterSet.indexOf(text[j]) === -1) { + characterSet.push(text[j]); + } + } + }); + fontAtlasManager.setProps({ + characterSet: characterSet + }); + var attr = drawGlyph(layerData, fontAtlasManager); + return attr; +} + +function drawGlyph(layerData, fontAtlasManager) { + var attributes = { + originPoints: [], + textSizes: [], + textOffsets: [], + colors: [], + textureElements: [], + pickingIds: [] + }; + var texture = fontAtlasManager.texture, + fontAtlas = fontAtlasManager.fontAtlas, + mapping = fontAtlasManager.mapping, + scale = fontAtlasManager.scale; + layerData.forEach(function (element) { + var size = element.size; + var pos = element.coordinates; + var text = element.shape || ''; + text = text.toString(); + var pen = { + x: -text.length * size / 2, + y: 0 + }; + + for (var i = 0; i < text.length; i++) { + var _attributes$colors; + + var metric = mapping[text[i]]; + var x = metric.x, + y = metric.y, + width = metric.width, + height = metric.height; + var color = element.color; + var offsetX = pen.x; + var offsetY = pen.y; + attributes.pickingIds.push(element.id, element.id, element.id, element.id, element.id, element.id); + attributes.textOffsets.push( // 文字在词语的偏移量 + offsetX, offsetY, offsetX, offsetY, offsetX, offsetY, offsetX, offsetY, offsetX, offsetY, offsetX, offsetY); + attributes.originPoints.push( // 词语的经纬度坐标 + pos[0], pos[1], 0, pos[0], pos[1], 0, pos[0], pos[1], 0, pos[0], pos[1], 0, pos[0], pos[1], 0, pos[0], pos[1], 0); + attributes.textSizes.push(size, size * scale, 0, size * scale, 0, 0, size, size * scale, 0, 0, size, 0); + + (_attributes$colors = attributes.colors).push.apply(_attributes$colors, _toConsumableArray(color).concat(_toConsumableArray(color), _toConsumableArray(color), _toConsumableArray(color), _toConsumableArray(color), _toConsumableArray(color))); + + attributes.textureElements.push( // 文字纹理坐标 + x + width, y, x, y, x, y + height, x + width, y, x, y + height, x + width, y + height); + pen.x = pen.x + size; + } + }); + attributes.texture = texture; + attributes.fontAtlas = fontAtlas; + return attributes; +} \ No newline at end of file diff --git a/lib/geom/buffer/point/text/font-manager.js b/lib/geom/buffer/point/text/font-manager.js new file mode 100644 index 0000000000..3608161186 --- /dev/null +++ b/lib/geom/buffer/point/text/font-manager.js @@ -0,0 +1,326 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = exports.DEFAULT_RADIUS = exports.DEFAULT_CUTOFF = exports.DEFAULT_BUFFER = exports.DEFAULT_FONT_SIZE = exports.DEFAULT_FONT_WEIGHT = exports.DEFAULT_FONT_FAMILY = exports.DEFAULT_CHAR_SET = void 0; + +var _tinySdf = _interopRequireDefault(require("@mapbox/tiny-sdf")); + +var _fontUtil = require("../../../../util/font-util"); + +var THREE = _interopRequireWildcard(require("../../../../core/three")); + +var _lruCache = _interopRequireDefault(require("./lru-cache")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var DEFAULT_CHAR_SET = getDefaultCharacterSet(); +exports.DEFAULT_CHAR_SET = DEFAULT_CHAR_SET; +var DEFAULT_FONT_FAMILY = 'sans-serif'; +exports.DEFAULT_FONT_FAMILY = DEFAULT_FONT_FAMILY; +var DEFAULT_FONT_WEIGHT = 'normal'; +exports.DEFAULT_FONT_WEIGHT = DEFAULT_FONT_WEIGHT; +var DEFAULT_FONT_SIZE = 24; +exports.DEFAULT_FONT_SIZE = DEFAULT_FONT_SIZE; +var DEFAULT_BUFFER = 3; +exports.DEFAULT_BUFFER = DEFAULT_BUFFER; +var DEFAULT_CUTOFF = 0.25; +exports.DEFAULT_CUTOFF = DEFAULT_CUTOFF; +var DEFAULT_RADIUS = 8; +exports.DEFAULT_RADIUS = DEFAULT_RADIUS; +var MAX_CANVAS_WIDTH = 1024; +var BASELINE_SCALE = 0.9; +var HEIGHT_SCALE = 1.2; +var CACHE_LIMIT = 3; +var cache = new _lruCache["default"](CACHE_LIMIT); +var VALID_PROPS = ['fontFamily', 'fontWeight', 'characterSet', 'fontSize', 'sdf', 'buffer', 'cutoff', 'radius']; + +function getDefaultCharacterSet() { + var charSet = []; + + for (var i = 32; i < 128; i++) { + charSet.push(String.fromCharCode(i)); + } + + return charSet; +} + +function setTextStyle(ctx, fontFamily, fontSize, fontWeight) { + ctx.font = "".concat(fontWeight, " ").concat(fontSize, "px ").concat(fontFamily); + ctx.fillStyle = '#000'; + ctx.textBaseline = 'baseline'; + ctx.textAlign = 'left'; +} + +function getNewChars(key, characterSet) { + var cachedFontAtlas = cache.get(key); + + if (!cachedFontAtlas) { + return characterSet; + } + + var newChars = []; + var cachedMapping = cachedFontAtlas.mapping; + var cachedCharSet = Object.keys(cachedMapping); + cachedCharSet = new Set(cachedCharSet); + var charSet = characterSet; + + if (charSet instanceof Array) { + charSet = new Set(charSet); + } + + charSet.forEach(function (_char) { + if (!cachedCharSet.has(_char)) { + newChars.push(_char); + } + }); + return newChars; +} + +function populateAlphaChannel(alphaChannel, imageData) { + // populate distance value from tinySDF to image alpha channel + for (var i = 0; i < alphaChannel.length; i++) { + imageData.data[4 * i + 3] = alphaChannel[i]; + } +} + +var FontAtlasManager = +/*#__PURE__*/ +function () { + function FontAtlasManager() { + _classCallCheck(this, FontAtlasManager); + + // font settings + this.props = { + fontFamily: DEFAULT_FONT_FAMILY, + fontWeight: DEFAULT_FONT_WEIGHT, + characterSet: DEFAULT_CHAR_SET, + fontSize: DEFAULT_FONT_SIZE, + buffer: DEFAULT_BUFFER, + // sdf only props + // https://github.com/mapbox/tiny-sdf + sdf: true, + cutoff: DEFAULT_CUTOFF, + radius: DEFAULT_RADIUS + }; // key is used for caching generated fontAtlas + + this._key = null; + this._texture = new THREE.Texture(); + } + + _createClass(FontAtlasManager, [{ + key: "setProps", + value: function setProps() { + var _this = this; + + var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + VALID_PROPS.forEach(function (prop) { + if (prop in props) { + _this.props[prop] = props[prop]; + } + }); // update cache key + + var oldKey = this._key; + this._key = this._getKey(); + var charSet = getNewChars(this._key, this.props.characterSet); + var cachedFontAtlas = cache.get(this._key); // if a fontAtlas associated with the new settings is cached and + // there are no new chars + + if (cachedFontAtlas && charSet.length === 0) { + // update texture with cached fontAtlas + if (this._key !== oldKey) { + this._updateTexture(cachedFontAtlas); + } + + return; + } // update fontAtlas with new settings + + + var fontAtlas = this._generateFontAtlas(this._key, charSet, cachedFontAtlas); + + this._fontAtlas = fontAtlas; + + this._updateTexture(fontAtlas); // update cache + + + cache.set(this._key, fontAtlas); + } + }, { + key: "_updateTexture", + value: function _updateTexture(_ref) { + var canvas = _ref.data; + this._texture = new THREE.CanvasTexture(canvas); + this._texture.wrapS = THREE.ClampToEdgeWrapping; + this._texture.wrapT = THREE.ClampToEdgeWrapping; + this._texture.minFilter = THREE.LinearFilter; + this._texture.flipY = false; + this._texture.needUpdate = true; + } + }, { + key: "_generateFontAtlas", + value: function _generateFontAtlas(key, characterSet, cachedFontAtlas) { + var _this$props = this.props, + fontFamily = _this$props.fontFamily, + fontWeight = _this$props.fontWeight, + fontSize = _this$props.fontSize, + buffer = _this$props.buffer, + sdf = _this$props.sdf, + radius = _this$props.radius, + cutoff = _this$props.cutoff; + var canvas = cachedFontAtlas && cachedFontAtlas.data; + + if (!canvas) { + canvas = document.createElement('canvas'); + canvas.width = MAX_CANVAS_WIDTH; + } + + var ctx = canvas.getContext('2d'); + setTextStyle(ctx, fontFamily, fontSize, fontWeight); // 1. build mapping + + var _buildMapping = (0, _fontUtil.buildMapping)(Object.assign({ + getFontWidth: function getFontWidth(_char2) { + return ctx.measureText(_char2).width; + }, + fontHeight: fontSize * HEIGHT_SCALE, + buffer: buffer, + characterSet: characterSet, + maxCanvasWidth: MAX_CANVAS_WIDTH + }, cachedFontAtlas && { + mapping: cachedFontAtlas.mapping, + xOffset: cachedFontAtlas.xOffset, + yOffset: cachedFontAtlas.yOffset + })), + mapping = _buildMapping.mapping, + canvasHeight = _buildMapping.canvasHeight, + xOffset = _buildMapping.xOffset, + yOffset = _buildMapping.yOffset; // 2. update canvas + // copy old canvas data to new canvas only when height changed + + + if (canvas.height !== canvasHeight) { + var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); + canvas.height = canvasHeight; + ctx.putImageData(imageData, 0, 0); + } + + setTextStyle(ctx, fontFamily, fontSize, fontWeight); // 3. layout characters + + if (sdf) { + var tinySDF = new _tinySdf["default"](fontSize, buffer, radius, cutoff, fontFamily, fontWeight); // used to store distance values from tinySDF + // tinySDF.size equals `fontSize + buffer * 2` + + var _imageData = ctx.getImageData(0, 0, tinySDF.size, tinySDF.size); + + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = characterSet[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _char3 = _step.value; + populateAlphaChannel(tinySDF.draw(_char3), _imageData); + ctx.putImageData(_imageData, mapping[_char3].x - buffer, mapping[_char3].y - buffer); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator["return"] != null) { + _iterator["return"](); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } else { + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = characterSet[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var _char4 = _step2.value; + ctx.fillText(_char4, mapping[_char4].x, mapping[_char4].y + fontSize * BASELINE_SCALE); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) { + _iterator2["return"](); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + + return { + xOffset: xOffset, + yOffset: yOffset, + mapping: mapping, + data: canvas, + width: canvas.width, + height: canvas.height + }; + } + }, { + key: "_getKey", + value: function _getKey() { + var _this$props2 = this.props, + fontFamily = _this$props2.fontFamily, + fontWeight = _this$props2.fontWeight, + fontSize = _this$props2.fontSize, + buffer = _this$props2.buffer, + sdf = _this$props2.sdf, + radius = _this$props2.radius, + cutoff = _this$props2.cutoff; + + if (sdf) { + return "".concat(fontFamily, " ").concat(fontWeight, " ").concat(fontSize, " ").concat(buffer, " ").concat(radius, " ").concat(cutoff); + } + + return "".concat(fontFamily, " ").concat(fontWeight, " ").concat(fontSize, " ").concat(buffer); + } + }, { + key: "texture", + get: function get() { + return this._texture; + } + }, { + key: "mapping", + get: function get() { + var data = cache.get(this._key); + return data && data.mapping; + } + }, { + key: "scale", + get: function get() { + return HEIGHT_SCALE; + } + }, { + key: "fontAtlas", + get: function get() { + return this._fontAtlas; + } + }]); + + return FontAtlasManager; +}(); + +exports["default"] = FontAtlasManager; \ No newline at end of file diff --git a/lib/geom/buffer/point/text/lru-cache.js b/lib/geom/buffer/point/text/lru-cache.js new file mode 100644 index 0000000000..980fe4b949 --- /dev/null +++ b/lib/geom/buffer/point/text/lru-cache.js @@ -0,0 +1,110 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +/** + * LRU Cache class with limit + * + * Update order for each get/set operation + * Delete oldest when reach given limit + */ +var LRUCache = +/*#__PURE__*/ +function () { + function LRUCache() { + var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 5; + + _classCallCheck(this, LRUCache); + + this.limit = limit; + this.clear(); + } + + _createClass(LRUCache, [{ + key: "clear", + value: function clear() { + this._cache = {}; // access/update order, first item is oldest, last item is newest + + this._order = []; + } + }, { + key: "get", + value: function get(key) { + var value = this._cache[key]; + + if (value) { + // update order + this._deleteOrder(key); + + this._appendOrder(key); + } + + return value; + } + }, { + key: "set", + value: function set(key, value) { + if (!this._cache[key]) { + // if reach limit, delete the oldest + if (Object.keys(this._cache).length === this.limit) { + this["delete"](this._order[0]); + } + + this._cache[key] = value; + + this._appendOrder(key); + } else { + // if found in cache, delete the old one, insert new one to the first of list + this["delete"](key); + this._cache[key] = value; + + this._appendOrder(key); + } + } + }, { + key: "delete", + value: function _delete(key) { + var value = this._cache[key]; + + if (value) { + this._deleteCache(key); + + this._deleteOrder(key); + } + } + }, { + key: "_deleteCache", + value: function _deleteCache(key) { + delete this._cache[key]; + } + }, { + key: "_deleteOrder", + value: function _deleteOrder(key) { + var index = this._order.findIndex(function (o) { + return o === key; + }); + + if (index >= 0) { + this._order.splice(index, 1); + } + } + }, { + key: "_appendOrder", + value: function _appendOrder(key) { + this._order.push(key); + } + }]); + + return LRUCache; +}(); + +exports["default"] = LRUCache; \ No newline at end of file diff --git a/lib/geom/buffer/point/textBuffer.js b/lib/geom/buffer/point/textBuffer.js new file mode 100644 index 0000000000..856e878031 --- /dev/null +++ b/lib/geom/buffer/point/textBuffer.js @@ -0,0 +1,172 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = TextBuffer; + +var _ajax = require("../../../util/ajax"); + +var _wolfy87Eventemitter = _interopRequireDefault(require("wolfy87-eventemitter")); + +var _global = _interopRequireDefault(require("../../../global")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +// const Space = 1; +var metrics = { + buffer: 3, + family: 'ios9', + size: 24 +}; + +function TextBuffer(layerData, style) { + var _this = this; + + _wolfy87Eventemitter.default.call(this); + + var attributes = { + originPoints: [], + textSizes: [], + textOffsets: [], + colors: [], + textureElements: [] + }; + var _style$textOffset = style.textOffset, + textOffset = _style$textOffset === void 0 ? [0, 0] : _style$textOffset; + var chars = []; + var textChars = {}; + layerData.forEach(function (element) { + var text = element.shape || ''; + text = text.toString(); + + for (var j = 0; j < text.length; j++) { + var code = text.charCodeAt(j); + textChars[text] = 0; + + if (chars.indexOf(code) === -1) { + chars.push(text.charCodeAt(j)); + } + } + }); + loadTextInfo(chars, function (chars, texture) { + layerData.forEach(function (element) { + var size = element.size; + var pos = layerData.coordinates; + var pen = { + x: textOffset[0], + y: textOffset[1] + }; + var text = element.shape || ''; + text = text.toString(); + + for (var i = 0; i < text.length; i++) { + var color = element.color; + drawGlyph(chars, pos, text[i], pen, size, attributes.colors, attributes.textureElements, attributes.originPoints, attributes.textSizes, attributes.textOffsets, color); + } + + _this.emit('completed', { + attributes: attributes, + texture: texture + }); + }); + }); +} + +function loadTextInfo(chars, done) { + (0, _ajax.getJSON)({ + url: "".concat(_global.default.sdfHomeUrl, "/getsdfdata?chars=").concat(chars.join('|')) + }, function (e, info) { + loadTextTexture(info.url, function (texture) { + done(info.info, texture); + }); + }); +} + +function loadTextTexture(url, cb) { + var _this2 = this; + + var img = new Image(); + img.crossOrigin = 'anonymous'; + + img.onload = function () { + var textTexture = _this2._creatTexture(img); + + cb(textTexture); + }; + + img.src = url; +} +/** + * 计算每个标注词语的位置 + * @param {*} chars 文本信息 + * @param {*} pos 文字三维空间坐标 + * @param {*} text 字符 + * @param {*} pen 字符在词语的偏移量 + * @param {*} size 字体大小 + * @param {*} colors 颜色 + * @param {*} textureElements 纹理坐标 + * @param {*} originPoints 初始位置数据 + * @param {*} textSizes 文字大小数组 + * @param {*} textOffsets 字体偏移量数据 + * @param {*} color 文字颜色 + */ + + +function drawGlyph(chars, pos, text, pen, size, colors, textureElements, originPoints, textSizes, textOffsets, color) { + var chr = text.charCodeAt(0); + var metric = chars[chr]; + if (!metric) return; + var scale = size / metrics.size; + var width = metric[0]; + var height = metric[1]; + var posX = metric[5]; + var posY = metric[6]; + var buffer = metrics.buffer; + + if (width > 0 && height > 0) { + width += buffer * 2; + height += buffer * 2; + var originX = 0; + var originY = 0; + var offsetX = pen.x; + var offsetY = pen.y; + originPoints.push(pos[0] + originX, pos[1] + originY, 0, pos[0] + originX, pos[1] + originY, 0, pos[0] + originX, pos[1] + originY, 0, pos[0] + originX, pos[1] + originY, 0, pos[0] + originX, pos[1] + originY, 0, pos[0] + originX, pos[1] + originY, 0); + var bx = 0; + var by = metrics.size / 2 + buffer; + textSizes.push((bx - buffer + width) * scale, (height - by) * scale, (bx - buffer) * scale, (height - by) * scale, (bx - buffer) * scale, -by * scale, (bx - buffer + width) * scale, (height - by) * scale, (bx - buffer) * scale, -by * scale, (bx - buffer + width) * scale, -by * scale); + textOffsets.push(offsetX, offsetY, offsetX, offsetY, offsetX, offsetY, offsetX, offsetY, offsetX, offsetY, offsetX, offsetY); + colors.push.apply(colors, _toConsumableArray(color).concat(_toConsumableArray(color), _toConsumableArray(color), _toConsumableArray(color), _toConsumableArray(color), _toConsumableArray(color))); + textureElements.push(posX + width, posY, posX, posY, posX, posY + height, posX + width, posY, posX, posY + height, posX + width, posY + height); + } + + pen.x = pen.x + size * 1.8; +} // function measureText(text, size) { +// const dimensions = { +// advance: 0 +// }; +// const metrics = this.metrics; +// const scale = size / metrics.size; +// for (let i = 0; i < text.length; i++) { +// const code = text.charCodeAt(i); +// const horiAdvance = metrics.chars[code][4]; +// dimensions.advance += (horiAdvance + Space) * scale; +// } +// return dimensions; +// } +// function creatTexture(image) { +// this.bufferStruct.textSize = [ image.width, image.height ]; +// const texture = new THREE.Texture(image); +// texture.minFilter = THREE.LinearFilter; +// texture.magFilter = THREE.ClampToEdgeWrapping; +// texture.needsUpdate = true; +// return texture; +// } \ No newline at end of file diff --git a/lib/geom/buffer/polygon-line.js b/lib/geom/buffer/polygon-line.js new file mode 100644 index 0000000000..300ea32f97 --- /dev/null +++ b/lib/geom/buffer/polygon-line.js @@ -0,0 +1,91 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _index = require("../shape/index"); + +var _bufferBase = _interopRequireDefault(require("./bufferBase")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var polygonLineBuffer = +/*#__PURE__*/ +function (_BufferBase) { + _inherits(polygonLineBuffer, _BufferBase); + + function polygonLineBuffer() { + _classCallCheck(this, polygonLineBuffer); + + return _possibleConstructorReturn(this, _getPrototypeOf(polygonLineBuffer).apply(this, arguments)); + } + + _createClass(polygonLineBuffer, [{ + key: "geometryBuffer", + value: function geometryBuffer() { + var coordinates = this.get('coordinates'); + var properties = this.get('properties'); + var shape = this.get('shape'); + var positions = []; + var positionsIndex = []; + var vertsCount = 0; + this.bufferStruct.style = properties; + var isExtrude = properties[0].hasOwnProperty('size'); + coordinates.forEach(function (geo, index) { + var heightValue = properties[index].size; + var extrudeData = []; + + if (isExtrude && shape === 'extrudeline') { + extrudeData = _index.polygonShape.extrudeline(geo); + extrudeData.positions = extrudeData.positions.map(function (pos) { + pos[2] *= heightValue; + return pos; + }); + } else { + extrudeData = _index.polygonShape.line(geo); + } + + positions.push(extrudeData.positions); + positionsIndex.push.apply(positionsIndex, _toConsumableArray(extrudeData.positionsIndex.map(function (index) { + return index + vertsCount; + }))); + vertsCount += extrudeData.positions.length; + }); + this.bufferStruct.indexs = positionsIndex; + this.bufferStruct.verts = positions; + this.bufferStruct.vertsCount = vertsCount; + } + }]); + + return polygonLineBuffer; +}(_bufferBase["default"]); + +exports["default"] = polygonLineBuffer; \ No newline at end of file diff --git a/lib/geom/buffer/polygon.js b/lib/geom/buffer/polygon.js new file mode 100644 index 0000000000..54922a2aca --- /dev/null +++ b/lib/geom/buffer/polygon.js @@ -0,0 +1,112 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _shape = require("../shape"); + +var _bufferBase = _interopRequireDefault(require("./bufferBase")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var PolygonBuffer = +/*#__PURE__*/ +function (_BufferBase) { + _inherits(PolygonBuffer, _BufferBase); + + function PolygonBuffer() { + _classCallCheck(this, PolygonBuffer); + + return _possibleConstructorReturn(this, _getPrototypeOf(PolygonBuffer).apply(this, arguments)); + } + + _createClass(PolygonBuffer, [{ + key: "geometryBuffer", + value: function geometryBuffer() { + var layerData = this.get('layerData'); + var shape = this.get('shape'); + var positions = []; + var faceUv = []; + var sizes = []; + var positionsIndex = []; + var indexCount = 0; + this.bufferStruct.style = layerData; + var isExtrude = layerData[0].hasOwnProperty('size'); // indices, normals, colors, UVs + + layerData.forEach(function (item) { + var heightValue = item.size; + + var extrudeData = _shape.polygonShape[shape](item.coordinates); + + if (isExtrude && shape === 'extrude') { + extrudeData = _shape.polygonShape.extrude(item.coordinates); + extrudeData.positions = extrudeData.positions.map(function (pos) { + pos[2] *= heightValue; + return pos; + }); + } + + positions.push(extrudeData.positions); + + if (shape !== 'line') { + // faceUv.push(...extrudeData.faceUv); + var count = extrudeData.faceUv.length / 2; + + for (var i = 0; i < count; i++) { + // uv 系数生成等大小的窗户 + var x = extrudeData.faceUv[i * 2]; + var y = extrudeData.faceUv[i * 2 + 1]; + + if (x !== -1) { + x = x * 0.1; + y = y * heightValue / 2000; + } + + faceUv.push(x, y); + sizes.push((1.0 - extrudeData.faceUv[i * 2 + 1]) * heightValue); + } + } + + indexCount += extrudeData.positionsIndex.length; + positionsIndex.push(extrudeData.positionsIndex); + }); + this.bufferStruct.indices = positionsIndex; + this.bufferStruct.position = positions; + this.bufferStruct.indexCount = indexCount; + this.bufferStruct.style = layerData; + this.bufferStruct.faceUv = faceUv; + this.bufferStruct.sizes = sizes; + + if (shape !== 'line') { + this.attributes = this._toPolygonAttributes(this.bufferStruct); + this.faceTexture = this._generateTexture(); + } else { + this.attributes = this._toPolygonLineAttributes(this.bufferStruct); + } + } + }]); + + return PolygonBuffer; +}(_bufferBase["default"]); + +exports["default"] = PolygonBuffer; \ No newline at end of file diff --git a/lib/geom/buffer/polygon/extrude_buffer.js b/lib/geom/buffer/polygon/extrude_buffer.js new file mode 100644 index 0000000000..5c7ba53772 --- /dev/null +++ b/lib/geom/buffer/polygon/extrude_buffer.js @@ -0,0 +1,121 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _buffer = _interopRequireDefault(require("../buffer")); + +var _earcut = _interopRequireDefault(require("earcut")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var ExtrudeButffer = +/*#__PURE__*/ +function (_BufferBase) { + _inherits(ExtrudeButffer, _BufferBase); + + function ExtrudeButffer() { + _classCallCheck(this, ExtrudeButffer); + + return _possibleConstructorReturn(this, _getPrototypeOf(ExtrudeButffer).apply(this, arguments)); + } + + _createClass(ExtrudeButffer, [{ + key: "_buildFeatures", + value: function _buildFeatures() { + var _this = this; + + var layerData = this.get('layerData'); + layerData.forEach(function (feature) { + _this._calculateTop(feature); + + _this._calculateWall(feature); + + delete feature.bufferInfo; + }); + } + }, { + key: "_calculateFeatures", + value: function _calculateFeatures() { + var _this2 = this; + + var layerData = this.get('layerData'); // 计算长 + + layerData.forEach(function (feature) { + var coordinates = feature.coordinates; + var bufferInfo = {}; + + var flattengeo = _earcut["default"].flatten(coordinates); + + var n = _this2.checkIsClosed(coordinates[0]) ? coordinates[0].length - 1 : coordinates[0].length; + var vertices = flattengeo.vertices, + dimensions = flattengeo.dimensions, + holes = flattengeo.holes; + var indexArray = (0, _earcut["default"])(vertices, holes, dimensions).map(function (v) { + return _this2.verticesCount + v; + }); + bufferInfo.vertices = vertices; + bufferInfo.indexArray = indexArray; + bufferInfo.verticesOffset = _this2.verticesCount + 0; + bufferInfo.indexOffset = _this2.indexCount + 0; + bufferInfo.faceNum = n; + _this2.indexCount += indexArray.length + n * 6; + _this2.verticesCount += vertices.length / 3 + n * 4; + feature.bufferInfo = bufferInfo; + }); + } + }, { + key: "_calculateTop", + value: function _calculateTop(feature) { + var size = feature.size; + var _feature$bufferInfo = feature.bufferInfo, + indexArray = _feature$bufferInfo.indexArray, + vertices = _feature$bufferInfo.vertices, + indexOffset = _feature$bufferInfo.indexOffset, + verticesOffset = _feature$bufferInfo.verticesOffset; + var pointCount = vertices.length / 3; + + this._encodeArray(feature, vertices.length / 3); // 添加顶点 + + + for (var i = 0; i < pointCount; i++) { + this.attributes.positions.set([vertices[i * 3], vertices[i * 3 + 1], size], (verticesOffset + i) * 3); // 顶部文理坐标计算 + + if (this.get('uv')) { + // TODO 用过BBox计算纹理坐标 + this.attributes.uv.set([-1, -1], (verticesOffset + i) * 2); + } + } + + feature.bufferInfo.verticesOffset += pointCount; // 添加顶点索引 + + this.indexArray.set(indexArray, indexOffset); // 顶部坐标 + + feature.bufferInfo.indexOffset += indexArray.length; + } + }]); + + return ExtrudeButffer; +}(_buffer["default"]); + +exports["default"] = ExtrudeButffer; \ No newline at end of file diff --git a/lib/geom/buffer/polygon/fill_buffer.js b/lib/geom/buffer/polygon/fill_buffer.js new file mode 100644 index 0000000000..1f900d113f --- /dev/null +++ b/lib/geom/buffer/polygon/fill_buffer.js @@ -0,0 +1,116 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _buffer = _interopRequireDefault(require("../buffer")); + +var _earcut = _interopRequireDefault(require("earcut")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var FillBuffer = +/*#__PURE__*/ +function (_BufferBase) { + _inherits(FillBuffer, _BufferBase); + + function FillBuffer() { + _classCallCheck(this, FillBuffer); + + return _possibleConstructorReturn(this, _getPrototypeOf(FillBuffer).apply(this, arguments)); + } + + _createClass(FillBuffer, [{ + key: "_buildFeatures", + value: function _buildFeatures() { + var _this = this; + + var layerData = this.get('layerData'); + layerData.forEach(function (feature) { + _this._calculateFill(feature); + + delete feature.bufferInfo; + }); + } + }, { + key: "_calculateFill", + value: function _calculateFill(feature) { + var _feature$bufferInfo = feature.bufferInfo, + indexArray = _feature$bufferInfo.indexArray, + vertices = _feature$bufferInfo.vertices, + indexOffset = _feature$bufferInfo.indexOffset, + verticesOffset = _feature$bufferInfo.verticesOffset; + var pointCount = vertices.length / 3; + + this._encodeArray(feature, vertices.length / 3); // 添加顶点 + + + for (var i = 0; i < pointCount; i++) { + this.attributes.positions.set([vertices[i * 3], vertices[i * 3 + 1], 0], (verticesOffset + i) * 3); + + if (this.get('uv')) { + // TODO 用过BBox计算纹理坐标 + this.attributes.uv.set([0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0], (verticesOffset + i) * 3); + } + } + + feature.bufferInfo.verticesOffset += pointCount; // 添加顶点索引 + + this.indexArray.set(indexArray, indexOffset); // 顶部坐标 + + feature.bufferInfo.indexOffset += indexArray.length; + } + }, { + key: "_calculateFeatures", + value: function _calculateFeatures() { + var _this2 = this; + + var layerData = this.get('layerData'); // 计算长 + + layerData.forEach(function (feature) { + var coordinates = feature.coordinates; + var bufferInfo = {}; + + var flattengeo = _earcut["default"].flatten(coordinates); + + var vertices = flattengeo.vertices, + dimensions = flattengeo.dimensions, + holes = flattengeo.holes; + var indexArray = (0, _earcut["default"])(vertices, holes, dimensions).map(function (v) { + return _this2.verticesCount + v; + }); + bufferInfo.vertices = vertices; + bufferInfo.indexArray = indexArray; + bufferInfo.verticesOffset = _this2.verticesCount + 0; + bufferInfo.indexOffset = _this2.indexCount + 0; + _this2.indexCount += indexArray.length; + _this2.verticesCount += vertices.length / 3; + feature.bufferInfo = bufferInfo; + }); + } + }]); + + return FillBuffer; +}(_buffer["default"]); + +exports["default"] = FillBuffer; \ No newline at end of file diff --git a/lib/geom/buffer/polygon/line_buffer.js b/lib/geom/buffer/polygon/line_buffer.js new file mode 100644 index 0000000000..449ff04828 --- /dev/null +++ b/lib/geom/buffer/polygon/line_buffer.js @@ -0,0 +1,141 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _buffer = _interopRequireDefault(require("../buffer")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var LineBuffer = +/*#__PURE__*/ +function (_BufferBase) { + _inherits(LineBuffer, _BufferBase); + + function LineBuffer() { + _classCallCheck(this, LineBuffer); + + return _possibleConstructorReturn(this, _getPrototypeOf(LineBuffer).apply(this, arguments)); + } + + _createClass(LineBuffer, [{ + key: "_buildFeatures", + value: function _buildFeatures() { + var _this = this; + + var layerData = this.get('layerData'); + var offsetVertices = 0; + var offsetIndex = 0; + var offset = 0; + layerData.forEach(function (feature) { + var coordinates = feature.coordinates; + coordinates.forEach(function (coord) { + var n = coord.length; + feature.bufferInfo = { + verticesOffset: offsetVertices + }; + + _this._encodeArray(feature, n); + + for (var i = 0; i < n; i++) { + _this.attributes.positions[offsetVertices * 3] = coord[i][0]; + _this.attributes.positions[offsetVertices * 3 + 1] = coord[i][1]; + _this.attributes.positions[offsetVertices * 3 + 2] = coord[i][2]; + _this.indexArray[offsetIndex * 2] = i + offset; + _this.indexArray[offsetIndex * 2 + 1] = i + offset + 1; + + if (i === n - 1) { + _this.indexArray[offsetIndex * 2 + 1] = offsetVertices - n + 1; + } + + offsetVertices++; + offsetIndex++; + } + + offset += n; + }); + }); + } + }, { + key: "_calculateBufferLength", + value: function _calculateBufferLength() { + var _this2 = this; + + var layerData = this.get('layerData'); + layerData.forEach(function (feature) { + var coordinates = feature.coordinates; + coordinates.forEach(function (coord) { + _this2.verticesCount += coord.length; + _this2.indexCount += coord.length * 2 - 2; + }); + }); + } + }, { + key: "_calculateFeatures", + value: function _calculateFeatures() { + var _this3 = this; + + var layerData = this.get('layerData'); + layerData.forEach(function (feature) { + var coordinates = feature.coordinates; + coordinates.forEach(function (coord) { + _this3.verticesCount += coord.length; + _this3.indexCount += coord.length * 2; + }); + }); + } + }, { + key: "_calculateLine", + value: function _calculateLine(feature) { + var _this4 = this; + + var _feature$bufferInfo = feature.bufferInfo, + indexOffset = _feature$bufferInfo.indexOffset, + verticesOffset = _feature$bufferInfo.verticesOffset; + feature.coordinates.forEach(function (coord) { + var n = coord.length; + + _this4._encodeArray(feature, n); + + for (var i = 0; i < n; i++) { + _this4.attributes.positions[(verticesOffset + i) * 3] = coord[i][0]; + _this4.attributes.positions[(verticesOffset + i) * 3 + 1] = coord[i][1]; + _this4.attributes.positions[(verticesOffset + i) * 3 + 2] = coord[i][2]; + _this4.indexArray[(indexOffset + i) * 2] = i + verticesOffset * 2; + _this4.indexArray[(indexOffset + i) * 2 + 1] = i + verticesOffset * 2 + 1; + + if (i === n - 1) { + _this4.indexArray[(indexOffset + i) * 2 + 1] = verticesOffset + 1; + } + } + + verticesOffset += n; + indexOffset += n; + }); + } + }]); + + return LineBuffer; +}(_buffer["default"]); + +exports["default"] = LineBuffer; \ No newline at end of file diff --git a/lib/geom/buffer/raster.js b/lib/geom/buffer/raster.js new file mode 100644 index 0000000000..ff3857ee39 --- /dev/null +++ b/lib/geom/buffer/raster.js @@ -0,0 +1,201 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.RasterBuffer = void 0; + +var _colorscales = require("../../attr/colorscales"); + +var THREE = _interopRequireWildcard(require("../../core/three")); + +var _base = _interopRequireDefault(require("../../core/base")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var RasterBuffer = +/*#__PURE__*/ +function (_Base) { + _inherits(RasterBuffer, _Base); + + function RasterBuffer(cfg) { + var _this; + + _classCallCheck(this, RasterBuffer); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(RasterBuffer).call(this, cfg)); + + _this.init(); + + return _this; + } + + _createClass(RasterBuffer, [{ + key: "init", + value: function init() { + var layerData = this.get('layerData'); + var _layerData$dataArray$ = layerData.dataArray[0], + coordinates = _layerData$dataArray$.coordinates, + width = _layerData$dataArray$.width, + data = _layerData$dataArray$.data, + height = _layerData$dataArray$.height; + var positions = [].concat(_toConsumableArray(coordinates[0]), [coordinates[1][0], coordinates[0][1], 0], _toConsumableArray(coordinates[1]), _toConsumableArray(coordinates[0]), _toConsumableArray(coordinates[1]), [coordinates[0][0], coordinates[1][1], 0]); + var imgPosUv = [0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0]; + var size = this.get('size'); + var texture = new THREE.DataTexture(new Float32Array(data), width, height, THREE.LuminanceFormat, THREE.FloatType); + texture.needsUpdate = true; + var colors = this.get('rampColors'); + var colorImageData = this.getColorRamp(colors); + + var colorTexture = this._getTexture(colorImageData); // 颜色纹理 + + + this.position = positions; + this.uv = imgPosUv; + this.u_raster = texture; // + + this.u_extent = [coordinates[0][0], coordinates[0][1], coordinates[1][0], coordinates[1][1]]; + this.u_colorTexture = colorTexture; // 颜色表‘= + + var triangles = this._buildTriangles(width, height, size, this.u_extent); + + var attributes = { + vertices: new Float32Array(triangles.vertices), + uvs: new Float32Array(triangles.uvs), + indices: triangles.indices, + dimension: triangles.dimension + }; + this.attributes = attributes; + } + }, { + key: "getColorRamp", + value: function getColorRamp(name) { + var colorscale = name; + var canvas = document.createElement('canvas'); + var ctx = canvas.getContext('2d'); + canvas.width = 256; + canvas.height = 1; + var gradient = ctx.createLinearGradient(0, 0, 256, 0); + var data = null; + + if (typeof colorscale === 'string') { + colorscale = _colorscales.colorScales[name]; + } + + if (Object.prototype.toString.call(colorscale) === '[object Object]') { + var min = colorscale.positions[0]; + var max = colorscale.positions[colorscale.positions.length - 1]; + + for (var i = 0; i < colorscale.colors.length; ++i) { + var value = (colorscale.positions[i] - min) / (max - min); + gradient.addColorStop(value, colorscale.colors[i]); + } + + ctx.fillStyle = gradient; + ctx.fillRect(0, 0, 256, 1); + data = new Uint8ClampedArray(ctx.getImageData(0, 0, 256, 1).data); + } + + if (Object.prototype.toString.call(colorscale) === '[object Uint8Array]') { + data = ctx.createImageData(256, 1); + } + + return new ImageData(data, 16, 16); + } + /** + * 颜色纹理 + * @param {*} image 颜色图片 + * @return {texture} texture + */ + + }, { + key: "_getTexture", + value: function _getTexture(image) { + var texture1 = new THREE.Texture(image); + texture1.magFilter = THREE.LinearFilter; + texture1.minFilter = THREE.LinearFilter; + texture1.format = THREE.RGBAFormat; + texture1.type = THREE.UnsignedByteType; + texture1.generateMipmaps = true; + texture1.needsUpdate = true; + return texture1; + } + }, { + key: "_buildTriangles", + value: function _buildTriangles(width, height) { + var size = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 2; + var extent = arguments.length > 3 ? arguments[3] : undefined; + // const extent = [ 73.482190241, 3.82501784112, 135.106618732, 57.6300459963 ] + var indices = []; + var vertices = []; + var uvs = []; + var gridX = Math.floor(width / size); + var gridY = Math.floor(height / size); + var gridX1 = gridX + 1; + var gridY1 = gridY + 1; + var stepX = (extent[2] - extent[0]) / gridX1; + var stepY = (extent[3] - extent[1]) / gridY1; + + for (var i = 0; i < gridY1; i++) { + var y = i * size; + + for (var j = 0; j < gridX1; j++) { + var x = j * size; + vertices.push(extent[0] + x * stepX, (height - y) * stepY + extent[1], 0); + uvs.push(j / gridX); + uvs.push(i / gridY); + } + } + + for (var iy = 0; iy < gridY; iy++) { + for (var ix = 0; ix < gridX; ix++) { + var a = ix + gridX1 * iy; + var b = ix + gridX1 * (iy + 1); + var c = ix + 1 + gridX1 * (iy + 1); + var d = ix + 1 + gridX1 * iy; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + + return { + uvs: uvs, + indices: indices, + vertices: vertices, + dimension: [gridX, gridY] + }; + } + }]); + + return RasterBuffer; +}(_base["default"]); + +exports.RasterBuffer = RasterBuffer; \ No newline at end of file diff --git a/lib/geom/buffer/text.js b/lib/geom/buffer/text.js new file mode 100644 index 0000000000..b78c8eabeb --- /dev/null +++ b/lib/geom/buffer/text.js @@ -0,0 +1,316 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _bufferBase = _interopRequireDefault(require("./bufferBase")); + +var _ajax = require("../../util/ajax"); + +var THREE = _interopRequireWildcard(require("../../core/three")); + +var _tinySdf = _interopRequireDefault(require("@mapbox/tiny-sdf")); + +var _global = _interopRequireDefault(require("../../global")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Space = 1; + +var TextBuffer = +/*#__PURE__*/ +function (_BufferBase) { + _inherits(TextBuffer, _BufferBase); + + function TextBuffer() { + _classCallCheck(this, TextBuffer); + + return _possibleConstructorReturn(this, _getPrototypeOf(TextBuffer).apply(this, arguments)); + } + + _createClass(TextBuffer, [{ + key: "geometryBuffer", + value: function geometryBuffer() { + var _this = this; + + this.metrics = { + buffer: 3, + family: 'ios9', + size: 24 + }; + var layerData = this.get('layerData'); + + var _this$get = this.get('style'), + _this$get$textOffset = _this$get.textOffset, + textOffset = _this$get$textOffset === void 0 ? [0, 0] : _this$get$textOffset; + + var chars = []; + var textChars = {}; + layerData.forEach(function (element) { + var text = element.shape || ''; + text = text.toString(); + + for (var j = 0; j < text.length; j++) { + var code = text.charCodeAt(j); + textChars[text] = 0; + + if (chars.indexOf(code) === -1) { + chars.push(text.charCodeAt(j)); + } + } + }); + + var sdfTexture = this._updateSdf(Object.keys(textChars).join('')); + + this.sdfTexture = sdfTexture; + + this._loadTextInfo(chars); + + this.on('SourceLoaded', function () { + var textureElements = []; + var colors = []; + var originPoints = []; + var textSizes = []; + var textOffsets = []; + layerData.forEach(function (element) { + var size = element.size; + var pos = element.coordinates; // const pen = { x: pos[0] - dimensions.advance / 2, y: pos[1] }; + + var pen = { + x: textOffset[0], + y: textOffset[1] + }; + var text = element.shape || ''; + text = text.toString(); + + for (var i = 0; i < text.length; i++) { + var color = element.color; + + _this._drawGlyph(pos, text[i], pen, size, colors, textureElements, originPoints, textSizes, textOffsets, color); + } + }); + _this.bufferStruct.style = layerData; + _this.attributes = { + originPoints: originPoints, + textSizes: textSizes, + textOffsets: textOffsets, + colors: colors, + textureElements: textureElements + }; + + _this.emit('completed'); + }); + } + }, { + key: "_loadTextInfo", + value: function _loadTextInfo(chars) { + var _this2 = this; + + (0, _ajax.getJSON)({ + url: "".concat(_global.default.sdfHomeUrl, "/getsdfdata?chars=").concat(chars.join('|')) + }, function (e, info) { + _this2.metrics.chars = info.info; + + _this2._loadTextTexture(info.url); + }); + } + }, { + key: "_loadTextTexture", + value: function _loadTextTexture(url) { + var _this3 = this; + + var img = new Image(); + img.crossOrigin = 'anonymous'; + + img.onload = function () { + _this3.bufferStruct.textTexture = _this3._creatTexture(_this3.sdfTexture.texure); + + _this3.emit('SourceLoaded'); + }; + + img.src = url; + } + /** + * 计算每个标注词语的位置 + * @param {*} pos 文字三维空间坐标 + * @param {*} text 字符 + * @param {*} pen 字符在词语的偏移量 + * @param {*} size 字体大小 + * @param {*} colors 颜色 + * @param {*} textureElements 纹理坐标 + * @param {*} originPoints 初始位置数据 + * @param {*} textSizes 文字大小数组 + * @param {*} textOffsets 字体偏移量数据 + * @param {*} color 文字颜色 + */ + + }, { + key: "_drawGlyph", + value: function _drawGlyph(pos, text, pen, size, colors, textureElements, originPoints, textSizes, textOffsets, color) { + var metrics = this.metrics; + var chr = text.charCodeAt(0); + var metric = metrics.chars[chr]; + if (!metric) return; + var info = this.sdfTexture.info; + var _info$text = info[text], + x = _info$text.x, + y = _info$text.y; + var scale = size / metrics.size; + var width = 24; // metric[0]; + + var height = 24; // metric[1]; + // const horiBearingX = metric[2]; + // const horiBearingY = metric[3]; + // const horiAdvance = metric[4]; + // const posX = metric[5]; + // const posY = metric[6]; + + var posX = x; + var posY = y; + var buffer = metrics.buffer; + + if (width > 0 && height > 0) { + width += buffer * 2; + height += buffer * 2; // Add a quad (= two triangles) per glyph. + // const originX = (horiBearingX - buffer + width / 2) * scale; + // const originY = -(height - horiBearingY) * scale; + + var originX = 0; + var originY = 0; // const offsetWidth = width / 2 * scale / (1.0 - horiBearingX * 1.5 / horiAdvance); + // const offsetHeight = (horiAdvance / 2) * scale; + // const offsetWidth = width/2 * scale; + // const offsetHeight = height / 2 * scale; + // const offsetHeight = height * scale; + + var offsetX = pen.x; + var offsetY = pen.y; + originPoints.push(pos[0] + originX, pos[1] + originY, 0, pos[0] + originX, pos[1] + originY, 0, pos[0] + originX, pos[1] + originY, 0, pos[0] + originX, pos[1] + originY, 0, pos[0] + originX, pos[1] + originY, 0, pos[0] + originX, pos[1] + originY, 0); // textSizes.push( + // offsetWidth, offsetHeight, + // -offsetWidth, offsetHeight, + // -offsetWidth, -offsetHeight, + // offsetWidth, offsetHeight, + // -offsetWidth, -offsetHeight, + // offsetWidth, -offsetHeight, + // ); + + var bx = 0; + var by = metrics.size / 2 + buffer; + textSizes.push((bx - buffer + width) * scale, (height - by) * scale, (bx - buffer) * scale, (height - by) * scale, (bx - buffer) * scale, -by * scale, (bx - buffer + width) * scale, (height - by) * scale, (bx - buffer) * scale, -by * scale, (bx - buffer + width) * scale, -by * scale); + textOffsets.push(offsetX, offsetY, offsetX, offsetY, offsetX, offsetY, offsetX, offsetY, offsetX, offsetY, offsetX, offsetY); + colors.push.apply(colors, _toConsumableArray(color).concat(_toConsumableArray(color), _toConsumableArray(color), _toConsumableArray(color), _toConsumableArray(color), _toConsumableArray(color))); + textureElements.push(posX + width, posY, posX, posY, posX, posY + height, posX + width, posY, posX, posY + height, posX + width, posY + height); + } // pen.x = pen.x + (horiAdvance + Space) * scale; + + + pen.x = pen.x + size * 1.8; + } + }, { + key: "_measureText", + value: function _measureText(text, size) { + var dimensions = { + advance: 0 + }; + var metrics = this.metrics; + var scale = size / metrics.size; + + for (var i = 0; i < text.length; i++) { + var code = text.charCodeAt(i); + var horiAdvance = metrics.chars[code][4]; + dimensions.advance += (horiAdvance + Space) * scale; + } + + return dimensions; + } + }, { + key: "_creatTexture", + value: function _creatTexture(image) { + this.bufferStruct.textSize = [image.width, image.height]; + var texture = new THREE.Texture(image); + texture.minFilter = THREE.LinearFilter; + texture.magFilter = THREE.ClampToEdgeWrapping; + texture.needsUpdate = true; + return texture; + } + }, { + key: "_updateSdf", + value: function _updateSdf(chars) { + var canvas = document.createElement('canvas'); + var ctx = canvas.getContext('2d'); + var sdfs = {}; + var fontSize = 24; + var fontWeight = 100; + var buffer = fontSize / 8; + var radius = fontSize / 3; + var canvasSize = Math.floor(Math.pow(chars.length, 0.5)) * (fontSize + buffer + radius); + canvas.width = canvasSize; + canvas.height = canvasSize; + ctx.clearRect(0, 0, canvas.width, canvas.height); + var sdf = new _tinySdf.default(fontSize, buffer, radius, null, null, fontWeight); + + for (var y = 0, i = 0; y + sdf.size <= canvas.height && i < chars.length; y += sdf.size) { + for (var x = 0; x + sdf.size <= canvas.width && i < chars.length; x += sdf.size) { + ctx.putImageData(this._makeRGBAImageData(ctx, sdf.draw(chars[i]), sdf.size), x, y); + sdfs[chars[i]] = { + x: x, + y: y + }; + i++; + } + } + + return { + info: sdfs, + texure: canvas + }; + } + }, { + key: "_makeRGBAImageData", + value: function _makeRGBAImageData(ctx, alphaChannel, size) { + var imageData = ctx.createImageData(size, size); + var data = imageData.data; + + for (var i = 0; i < alphaChannel.length; i++) { + data[4 * i + 0] = alphaChannel[i]; + data[4 * i + 1] = alphaChannel[i]; + data[4 * i + 2] = alphaChannel[i]; + data[4 * i + 3] = 255; + } + + return imageData; + } + }]); + + return TextBuffer; +}(_bufferBase.default); + +exports.default = TextBuffer; \ No newline at end of file diff --git a/lib/geom/extrude.js b/lib/geom/extrude.js new file mode 100644 index 0000000000..df4b3067a1 --- /dev/null +++ b/lib/geom/extrude.js @@ -0,0 +1,229 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = extrudePolygon; +exports.extrudePolygonLine = extrudePolygonLine; +exports.fillPolygon = fillPolygon; +exports.extrude_Polygon = extrude_Polygon; + +var _earcut = _interopRequireDefault(require("earcut")); + +var THREE = _interopRequireWildcard(require("../core/three")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +/** + * 计算是否拉伸 + * @param {Array} points 点坐标数组 + * @param {boolean} extrude 是否拉伸 + * @return {object} 顶点坐标顶点索引 + */ +function extrudePolygon(points, extrude) { + // height += Math.random() * 100; // 解决 depth + var p1 = points[0][0]; + var p2 = points[0][points[0].length - 1]; + var faceUv = []; + + if (p1[0] === p2[0] && p1[1] === p2[1]) { + points[0] = points[0].slice(0, points[0].length - 1); + } + + var n = points[0].length; + + var flattengeo = _earcut["default"].flatten(points); + + var positions = []; + var cells = []; + var dimensions = flattengeo.dimensions; + var triangles = (0, _earcut["default"])(flattengeo.vertices, flattengeo.holes, flattengeo.dimensions); + cells = triangles; + var pointCount = flattengeo.vertices.length / dimensions; + var vertices = flattengeo.vertices; + extrude ? full() : flat(); + + function flat() { + for (var i = 0; i < pointCount; i++) { + positions.push([vertices[i * dimensions], vertices[i * dimensions + 1], 0]); + } + } + + function full() { + // 顶部纹理 + triangles.forEach(function () { + faceUv.push(-1, -1); + }); // 顶部坐标 + + for (var i = 0; i < pointCount; i++) { + positions.push([vertices[i * dimensions], vertices[i * dimensions + 1], 1]); + } + + for (var _i = 0; _i < pointCount; _i++) { + positions.push([vertices[_i * dimensions], vertices[_i * dimensions + 1], 0]); + } + + for (var _i2 = 0; _i2 < n; _i2++) { + if (_i2 === n - 1) { + cells.push(_i2, n, _i2 + n); + faceUv.push(1, 0, 0, 1, 1, 1); + cells.push(_i2, 0, n); + faceUv.push(1, 0, 0, 0, 0, 1); + } else { + cells.push(_i2 + n, _i2, _i2 + n + 1); + faceUv.push(1, 1, 1, 0, 0, 1); + cells.push(_i2, _i2 + 1, _i2 + n + 1); + faceUv.push(1, 0, 0, 0, 0, 1); + } + } + } + + points = []; + return { + positions: positions, + faceUv: faceUv, + positionsIndex: cells + }; +} + +function extrudePolygonLine(points, extrude) { + // height += Math.random() * 100; // 解决 depth + var p1 = points[0][0]; + var p2 = points[0][points[0].length - 1]; + + if (p1[0] === p2[0] && p1[1] === p2[1]) { + points[0] = points[0].slice(0, points[0].length - 1); + } + + var n = points[0].length; + + var flattengeo = _earcut["default"].flatten(points); + + var positions = []; + var cells = []; + var triangles = (0, _earcut["default"])(flattengeo.vertices, flattengeo.holes, flattengeo.dimensions); + cells = triangles.map(function (e) { + return e; + }); + extrude === 0 ? flat() : full(); + + function flat() { + points[0].forEach(function (p) { + positions.push([p[0], p[1], 0]); + }); // top + } + + function full() { + points[0].forEach(function (p) { + positions.push([p[0], p[1], 1]); + }); // top + + points[0].forEach(function (p) { + positions.push([p[0], p[1], 0]); + }); // bottom + + for (var i = 0; i < n; i++) { + if (i === n - 1) { + cells.push(i + n, n, i); + cells.push(0, i, n); + } else { + cells.push(i + n, i + n + 1, i); + cells.push(i + 1, i, i + n + 1); + } + } + } + + points = []; + return { + positions: positions, + positionsIndex: cells + }; +} + +function fillPolygon(points) { + var flattengeo = _earcut["default"].flatten(points); + + var triangles = (0, _earcut["default"])(flattengeo.vertices, flattengeo.holes, flattengeo.dimensions); + return { + positions: flattengeo.vertices, + indexArray: triangles + }; +} + +function extrude_Polygon(points) { + var p1 = points[0][0]; + var p2 = points[0][points[0].length - 1]; + + if (p1[0] === p2[0] && p1[1] === p2[1]) { + points[0] = points[0].slice(0, points[0].length - 1); + } + + var n = points[0].length; + + var flattengeo = _earcut["default"].flatten(points); + + var positions = []; + var indexArray = []; + var normals = []; // 设置顶部z值 + + for (var j = 0; j < flattengeo.vertices.length / 3; j++) { + flattengeo.vertices[j * 3 + 2] = 1; + normals.push(0, 0, 1); + } + + positions.push.apply(positions, _toConsumableArray(flattengeo.vertices)); + var triangles = (0, _earcut["default"])(flattengeo.vertices, flattengeo.holes, flattengeo.dimensions); + indexArray.push.apply(indexArray, _toConsumableArray(triangles)); + + var _loop = function _loop(i) { + var prePoint = flattengeo.vertices.slice(i * 3, i * 3 + 3); + var nextPoint = flattengeo.vertices.slice(i * 3 + 3, i * 3 + 6); + nextPoint.length === 0 && (nextPoint = flattengeo.vertices.slice(0, 3)); + var indexOffset = positions.length / 3; + positions.push(prePoint[0], prePoint[1], 1, nextPoint[0], nextPoint[1], 1, prePoint[0], prePoint[1], 0, nextPoint[0], nextPoint[1], 0); + var normal = computeNormal([nextPoint[0], nextPoint[1], 1], [prePoint[0], prePoint[1], 0], [prePoint[0], prePoint[1], 1]); + normals.push.apply(normals, _toConsumableArray(normal).concat(_toConsumableArray(normal), _toConsumableArray(normal), _toConsumableArray(normal))); + indexArray.push.apply(indexArray, _toConsumableArray([1, 2, 0, 3, 2, 1].map(function (v) { + return v + indexOffset; + }))); + }; + + for (var i = 0; i < n; i++) { + _loop(i); + } + + return { + positions: positions, + indexArray: indexArray, + normals: normals + }; +} + +function computeNormal(v1, v2, v3) { + var pA = new THREE.Vector3(); + var pB = new THREE.Vector3(); + var pC = new THREE.Vector3(); + var cb = new THREE.Vector3(); + var ab = new THREE.Vector3(); + pA.set.apply(pA, _toConsumableArray(v1)); + pB.set.apply(pB, _toConsumableArray(v2)); + pC.set.apply(pC, _toConsumableArray(v3)); + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + cb.normalize(); + var x = cb.x, + y = cb.y, + z = cb.z; + return [x, y, z]; +} \ No newline at end of file diff --git a/lib/geom/geom.js b/lib/geom/geom.js new file mode 100644 index 0000000000..90986f0655 --- /dev/null +++ b/lib/geom/geom.js @@ -0,0 +1,68 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var geom = { + point: { + symbol: ['circle', 'hexagon', 'triangle', 'diamond'], + native: { + buffer: '', + geometry: 'PointGeometry', + material: 'PointMaterial' + }, + line: { + buffer: 'PointBuffer', + geometry: 'PolygonLine', + material: 'MeshlineMaterial' + }, + fill: { + buffer: 'PointBuffer', + geometry: 'PolygonGeometry', + material: 'PolygonMaterial' + }, + extrude: { + buffer: 'PointBuffer', + geometry: 'PolygonGeometry', + material: 'PolygonMaterial' + }, + extrudeline: { + buffer: 'PointBuffer', + geometry: 'PolygonLine', + material: 'MeshlineMaterial' + }, + pointGrid: { + buffer: 'pointGrid', + geometry: 'PolygonLine', + material: 'MeshlineMaterial' + } + }, + line: { + shape: ['native'] + }, + polygon: { + line: { + buffer: 'polygonLineBuffer', + geometry: 'PolygonLine', + material: 'MeshlineMaterial' + }, + fill: { + buffer: 'PolygonBuffer', + geometry: 'PolygonGeometry', + material: 'PolygonMaterial' + }, + extrude: { + buffer: 'PolygonBuffer', + geometry: 'PolygonGeometry', + material: 'PolygonMaterial' + }, + extrudeline: { + buffer: 'polygonLineBuffer', + geometry: 'PolygonLine', + material: 'MeshlineMaterial' + } + } +}; +var _default = geom; +exports.default = _default; \ No newline at end of file diff --git a/lib/geom/index.js b/lib/geom/index.js new file mode 100644 index 0000000000..78d97f6254 --- /dev/null +++ b/lib/geom/index.js @@ -0,0 +1,20 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.GeoBuffer = exports.Material = exports.bufferGeometry = void 0; + +var bufferGeometry = _interopRequireWildcard(require("./bufferGeometry/index")); + +exports.bufferGeometry = bufferGeometry; + +var Material = _interopRequireWildcard(require("./material/index")); + +exports.Material = Material; + +var GeoBuffer = _interopRequireWildcard(require("./buffer/index")); + +exports.GeoBuffer = GeoBuffer; + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } \ No newline at end of file diff --git a/lib/geom/material/arcline.js b/lib/geom/material/arcline.js new file mode 100644 index 0000000000..e71abda68b --- /dev/null +++ b/lib/geom/material/arcline.js @@ -0,0 +1,71 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ArclineMaterial = ArclineMaterial; + +var _r3Base = require("@ali/r3-base"); + +var _r3Material = require("@ali/r3-material"); + +function ArclineMaterial() { + var tech = requireGeometryTechnique(); + var newMtl = new _r3Material.Material('MeshlineTech_mtl'); + newMtl.technique = tech; + newMtl.setValue('segmentNumber', 50.0); + return newMtl; +} + +function requireGeometryTechnique() { + // 顶点着色器 + var VERT_SHADER = "\n precision mediump float;\n attribute vec3 a_position;\n attribute vec3 a_color;\n attribute vec4 a_instance;\n uniform mat4 matModelViewProjection;\n uniform float segmentNumber; \n varying vec3 v_color;\n\n float getSegmentRatio(float index) {\n return smoothstep(0.0, 1.0, index / (segmentNumber - 1.0));\n }\n\n float paraboloid(vec2 source, vec2 target, float ratio) {\n vec2 x = mix(source, target, ratio);\n vec2 center = mix(source, target, 0.5);\n float dSourceCenter = distance(source, center);\n float dXCenter = distance(x, center);\n return (dSourceCenter + dXCenter) * (dSourceCenter - dXCenter)*0.6;\n }\n\n vec3 getPos(vec2 source, vec2 target, float height, float segmentRatio) {\n return vec3(\n mix(source, target, segmentRatio),\n sqrt(max(0.0, height))\n );\n }\n\n void main() {\n vec2 source = a_instance.rg;\n vec2 target = a_instance.ba;\n float segmentIndex = a_position.x;\n float segmentRatio = getSegmentRatio(segmentIndex);\n vec3 c1 = vec3(0.929,0.972,0.917);\n vec3 c2 = vec3(0.062,0.325,0.603); \n v_color = mix(c1, c2, segmentRatio);\n float height = paraboloid(source, target, segmentRatio);\n vec3 position = getPos(source,target,height,segmentRatio);\n gl_Position = matModelViewProjection * vec4(position, 1.0);\n }\n "; // 片元着色器 + + var FRAG_SHADER = "\n precision mediump float;\n varying vec3 v_color;\n\n void main() {\n gl_FragColor = vec4(v_color,1.0);\n }\n "; // Technique 配置信息 + + var cfg = { + attributes: { + a_position: { + name: 'a_position', + semantic: 'POSITION', + type: _r3Base.DataType.FLOAT_VEC3 + }, + a_color: { + name: 'a_color', + semantic: 'COLOR', + type: _r3Base.DataType.FLOAT_VEC3 + }, + a_instance: { + name: 'a_instance', + semantic: 'INSPOS', + type: _r3Base.DataType.FLOAT_VEC4 + } + }, + uniforms: { + matModelViewProjection: { + name: 'matModelViewProjection', + semantic: _r3Base.UniformSemantic.MODELVIEWPROJECTION, + type: _r3Base.DataType.FLOAT_MAT4 + }, + segmentNumber: { + name: 'segmentNumber', + type: _r3Base.DataType.FLOAT + } + } + }; // 创建 Technique + + var tech = new _r3Material.RenderTechnique('MeshlineTech'); + tech.states = { + enable: [_r3Base.RenderState.BLEND], + functions: { + blendFunc: [_r3Base.BlendFunc.SRC_ALPHA, _r3Base.BlendFunc.ONE_MINUS_SRC_ALPHA] // + + } + }; + tech.isValid = true; + tech.uniforms = cfg.uniforms; + tech.attributes = cfg.attributes; + tech.vertexShader = VERT_SHADER; + tech.fragmentShader = FRAG_SHADER; + return tech; +} \ No newline at end of file diff --git a/lib/geom/material/circleMaterial.js b/lib/geom/material/circleMaterial.js new file mode 100644 index 0000000000..5e58533d98 --- /dev/null +++ b/lib/geom/material/circleMaterial.js @@ -0,0 +1,63 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _material = _interopRequireDefault(require("./material")); + +var _shaderModule = require("../../util/shaderModule"); + +var _deepMix = _interopRequireDefault(require("@antv/util/lib/deep-mix")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var CircleMaterial = +/*#__PURE__*/ +function (_Material) { + _inherits(CircleMaterial, _Material); + + function CircleMaterial(_uniforms) { + var _this; + + var _defines = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var parameters = arguments.length > 2 ? arguments[2] : undefined; + + _classCallCheck(this, CircleMaterial); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(CircleMaterial).call(this, parameters)); + + var _getModule = (0, _shaderModule.getModule)('circle'), + vs = _getModule.vs, + fs = _getModule.fs, + uniforms = _getModule.uniforms; + + _this.uniforms = (0, _shaderModule.wrapUniforms)((0, _deepMix["default"])(uniforms, _uniforms)); + _this.defines = _defines; + _this.type = 'CircleMaterial'; + _this.vertexShader = vs; + _this.fragmentShader = fs; + _this.transparent = true; + return _this; + } + + return CircleMaterial; +}(_material["default"]); + +exports["default"] = CircleMaterial; \ No newline at end of file diff --git a/lib/geom/material/grid.js b/lib/geom/material/grid.js new file mode 100644 index 0000000000..86d0510918 --- /dev/null +++ b/lib/geom/material/grid.js @@ -0,0 +1,98 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _material = _interopRequireDefault(require("./material")); + +var _shaderModule = require("../../util/shaderModule"); + +var _deepMix = _interopRequireDefault(require("@antv/util/lib/deep-mix")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var GridMaterial = +/*#__PURE__*/ +function (_Material) { + _inherits(GridMaterial, _Material); + + _createClass(GridMaterial, [{ + key: "getDefaultParameters", + value: function getDefaultParameters() { + return { + uniforms: { + u_opacity: { + value: 1.0 + }, + u_time: { + value: 0 + }, + u_xOffset: { + value: 0.01 + }, + u_yOffset: { + value: 0.01 + }, + u_coverage: { + value: 0.8 + }, + u_activeId: { + value: 0 + }, + u_activeColor: { + value: [1.0, 0, 0, 1.0] + } + }, + defines: {} + }; + } + }]); + + function GridMaterial(_uniforms, _defines, parameters) { + var _this; + + _classCallCheck(this, GridMaterial); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(GridMaterial).call(this, parameters)); + + var _this$getDefaultParam = _this.getDefaultParameters(), + defines = _this$getDefaultParam.defines; + + var _getModule = (0, _shaderModule.getModule)('grid'), + vs = _getModule.vs, + fs = _getModule.fs, + uniforms = _getModule.uniforms; + + _this.uniforms = (0, _shaderModule.wrapUniforms)((0, _deepMix["default"])(uniforms, _uniforms)); + _this.type = 'GridMaterial'; + _this.defines = Object.assign(defines, _defines); + _this.vertexShader = vs; + _this.fragmentShader = fs; + _this.transparent = true; + return _this; + } + + return GridMaterial; +}(_material["default"]); + +exports["default"] = GridMaterial; \ No newline at end of file diff --git a/lib/geom/material/heatmapMateial.js b/lib/geom/material/heatmapMateial.js new file mode 100644 index 0000000000..cccfa13889 --- /dev/null +++ b/lib/geom/material/heatmapMateial.js @@ -0,0 +1,155 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.HeatmapIntensityMaterial = exports.HeatmapColorizeMaterial = void 0; + +var THREE = _interopRequireWildcard(require("../../core/three")); + +var _material = _interopRequireDefault(require("./material")); + +var _shaderModule = require("../../util/shaderModule"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var HeatmapColorizeMaterial = +/*#__PURE__*/ +function (_Material) { + _inherits(HeatmapColorizeMaterial, _Material); + + _createClass(HeatmapColorizeMaterial, [{ + key: "getDefaultParameters", + value: function getDefaultParameters() { + return { + uniforms: { + u_intensity: { + value: 1.0 + }, + u_texture: { + value: null + }, + u_rampColors: { + value: 0 + }, + u_opacity: { + value: 1 + } + }, + defines: {} + }; + } + }]); + + function HeatmapColorizeMaterial(_uniforms) { + var _this; + + var _defines = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var parameters = arguments.length > 2 ? arguments[2] : undefined; + + _classCallCheck(this, HeatmapColorizeMaterial); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(HeatmapColorizeMaterial).call(this, parameters)); + + var _this$getDefaultParam = _this.getDefaultParameters(), + uniforms = _this$getDefaultParam.uniforms, + defines = _this$getDefaultParam.defines; + + var _getModule = (0, _shaderModule.getModule)('heatmap_color'), + vs = _getModule.vs, + fs = _getModule.fs; + + _this.uniforms = Object.assign(uniforms, _this.setUniform(_uniforms)); + _this.type = 'HeatmapColorizeMaterial'; + _this.defines = Object.assign(defines, _defines); + _this.vertexShader = vs; + _this.fragmentShader = fs; + _this.transparent = true; + return _this; + } + + return HeatmapColorizeMaterial; +}(_material["default"]); + +exports.HeatmapColorizeMaterial = HeatmapColorizeMaterial; + +var HeatmapIntensityMaterial = +/*#__PURE__*/ +function (_Material2) { + _inherits(HeatmapIntensityMaterial, _Material2); + + _createClass(HeatmapIntensityMaterial, [{ + key: "getDefaultParameters", + value: function getDefaultParameters() { + return { + uniforms: { + u_intensity: { + value: 10.0 + }, + u_zoom: { + value: 4 + }, + u_radius: { + value: 10 + } + }, + defines: {} + }; + } + }]); + + function HeatmapIntensityMaterial(_uniforms) { + var _this2; + + var _defines = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var parameters = arguments.length > 2 ? arguments[2] : undefined; + + _classCallCheck(this, HeatmapIntensityMaterial); + + _this2 = _possibleConstructorReturn(this, _getPrototypeOf(HeatmapIntensityMaterial).call(this, parameters)); + + var _this2$getDefaultPara = _this2.getDefaultParameters(), + uniforms = _this2$getDefaultPara.uniforms, + defines = _this2$getDefaultPara.defines; + + var _getModule2 = (0, _shaderModule.getModule)('heatmap_intensity'), + vs = _getModule2.vs, + fs = _getModule2.fs; + + _this2.uniforms = Object.assign(uniforms, _this2.setUniform(_uniforms)); + _this2.type = 'heatmap_intensity'; + _this2.defines = Object.assign(defines, _defines); + _this2.vertexShader = vs; + _this2.blending = THREE.AdditiveBlending; + _this2.fragmentShader = fs; + _this2.depthTest = false; + _this2.transparent = true; + return _this2; + } + + return HeatmapIntensityMaterial; +}(_material["default"]); + +exports.HeatmapIntensityMaterial = HeatmapIntensityMaterial; \ No newline at end of file diff --git a/lib/geom/material/heatmapMaterial.js b/lib/geom/material/heatmapMaterial.js new file mode 100644 index 0000000000..cccfa13889 --- /dev/null +++ b/lib/geom/material/heatmapMaterial.js @@ -0,0 +1,155 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.HeatmapIntensityMaterial = exports.HeatmapColorizeMaterial = void 0; + +var THREE = _interopRequireWildcard(require("../../core/three")); + +var _material = _interopRequireDefault(require("./material")); + +var _shaderModule = require("../../util/shaderModule"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var HeatmapColorizeMaterial = +/*#__PURE__*/ +function (_Material) { + _inherits(HeatmapColorizeMaterial, _Material); + + _createClass(HeatmapColorizeMaterial, [{ + key: "getDefaultParameters", + value: function getDefaultParameters() { + return { + uniforms: { + u_intensity: { + value: 1.0 + }, + u_texture: { + value: null + }, + u_rampColors: { + value: 0 + }, + u_opacity: { + value: 1 + } + }, + defines: {} + }; + } + }]); + + function HeatmapColorizeMaterial(_uniforms) { + var _this; + + var _defines = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var parameters = arguments.length > 2 ? arguments[2] : undefined; + + _classCallCheck(this, HeatmapColorizeMaterial); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(HeatmapColorizeMaterial).call(this, parameters)); + + var _this$getDefaultParam = _this.getDefaultParameters(), + uniforms = _this$getDefaultParam.uniforms, + defines = _this$getDefaultParam.defines; + + var _getModule = (0, _shaderModule.getModule)('heatmap_color'), + vs = _getModule.vs, + fs = _getModule.fs; + + _this.uniforms = Object.assign(uniforms, _this.setUniform(_uniforms)); + _this.type = 'HeatmapColorizeMaterial'; + _this.defines = Object.assign(defines, _defines); + _this.vertexShader = vs; + _this.fragmentShader = fs; + _this.transparent = true; + return _this; + } + + return HeatmapColorizeMaterial; +}(_material["default"]); + +exports.HeatmapColorizeMaterial = HeatmapColorizeMaterial; + +var HeatmapIntensityMaterial = +/*#__PURE__*/ +function (_Material2) { + _inherits(HeatmapIntensityMaterial, _Material2); + + _createClass(HeatmapIntensityMaterial, [{ + key: "getDefaultParameters", + value: function getDefaultParameters() { + return { + uniforms: { + u_intensity: { + value: 10.0 + }, + u_zoom: { + value: 4 + }, + u_radius: { + value: 10 + } + }, + defines: {} + }; + } + }]); + + function HeatmapIntensityMaterial(_uniforms) { + var _this2; + + var _defines = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var parameters = arguments.length > 2 ? arguments[2] : undefined; + + _classCallCheck(this, HeatmapIntensityMaterial); + + _this2 = _possibleConstructorReturn(this, _getPrototypeOf(HeatmapIntensityMaterial).call(this, parameters)); + + var _this2$getDefaultPara = _this2.getDefaultParameters(), + uniforms = _this2$getDefaultPara.uniforms, + defines = _this2$getDefaultPara.defines; + + var _getModule2 = (0, _shaderModule.getModule)('heatmap_intensity'), + vs = _getModule2.vs, + fs = _getModule2.fs; + + _this2.uniforms = Object.assign(uniforms, _this2.setUniform(_uniforms)); + _this2.type = 'heatmap_intensity'; + _this2.defines = Object.assign(defines, _defines); + _this2.vertexShader = vs; + _this2.blending = THREE.AdditiveBlending; + _this2.fragmentShader = fs; + _this2.depthTest = false; + _this2.transparent = true; + return _this2; + } + + return HeatmapIntensityMaterial; +}(_material["default"]); + +exports.HeatmapIntensityMaterial = HeatmapIntensityMaterial; \ No newline at end of file diff --git a/lib/geom/material/hexagon.js b/lib/geom/material/hexagon.js new file mode 100644 index 0000000000..f00c1d7bf0 --- /dev/null +++ b/lib/geom/material/hexagon.js @@ -0,0 +1,98 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _material = _interopRequireDefault(require("./material")); + +var _shaderModule = require("../../util/shaderModule"); + +var _deepMix = _interopRequireDefault(require("@antv/util/lib/deep-mix")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var hexagonMaterial = +/*#__PURE__*/ +function (_Material) { + _inherits(hexagonMaterial, _Material); + + _createClass(hexagonMaterial, [{ + key: "getDefaultParameters", + value: function getDefaultParameters() { + return { + uniforms: { + u_opacity: { + value: 1.0 + }, + u_time: { + value: 0 + }, + u_radius: { + value: 0.01 + }, + u_angle: { + value: 0.01 + }, + u_coverage: { + value: 0.8 + }, + u_activeId: { + value: 0 + }, + u_activeColor: { + value: [1.0, 0, 0, 1.0] + } + }, + defines: {} + }; + } + }]); + + function hexagonMaterial(_uniforms, _defines, parameters) { + var _this; + + _classCallCheck(this, hexagonMaterial); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(hexagonMaterial).call(this, parameters)); + + var _this$getDefaultParam = _this.getDefaultParameters(), + defines = _this$getDefaultParam.defines; + + var _getModule = (0, _shaderModule.getModule)('hexagon'), + vs = _getModule.vs, + fs = _getModule.fs, + uniforms = _getModule.uniforms; + + _this.uniforms = (0, _shaderModule.wrapUniforms)((0, _deepMix["default"])(uniforms, _uniforms)); + _this.type = 'hexagonMaterial'; + _this.defines = Object.assign(defines, _defines); + _this.vertexShader = vs; + _this.fragmentShader = fs; + _this.transparent = true; + return _this; + } + + return hexagonMaterial; +}(_material["default"]); + +exports["default"] = hexagonMaterial; \ No newline at end of file diff --git a/lib/geom/material/imageMaterial.js b/lib/geom/material/imageMaterial.js new file mode 100644 index 0000000000..5000cb9a7c --- /dev/null +++ b/lib/geom/material/imageMaterial.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = ImageMaterial; + +var _shaderModule = require("../../util/shaderModule"); + +var _material = _interopRequireDefault(require("./material")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function ImageMaterial(options) { + var _getModule = (0, _shaderModule.getModule)('image'), + vs = _getModule.vs, + fs = _getModule.fs; + + var material = new _material["default"]({ + uniforms: { + u_opacity: { + value: options.u_opacity + }, + u_texture: { + value: options.u_texture + } + }, + vertexShader: vs, + fragmentShader: fs, + transparent: true, + depthTest: false + }); + return material; +} \ No newline at end of file diff --git a/lib/geom/material/index.js b/lib/geom/material/index.js new file mode 100644 index 0000000000..75fe920724 --- /dev/null +++ b/lib/geom/material/index.js @@ -0,0 +1,37 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "PointMaterial", { + enumerable: true, + get: function get() { + return _point.PointMaterial; + } +}); +Object.defineProperty(exports, "MeshlineMaterial", { + enumerable: true, + get: function get() { + return _meshline.MeshlineMaterial; + } +}); +Object.defineProperty(exports, "PolygonMaterial", { + enumerable: true, + get: function get() { + return _polygon.PolygonMaterial; + } +}); +Object.defineProperty(exports, "ArclineMaterial", { + enumerable: true, + get: function get() { + return _arcline.ArclineMaterial; + } +}); + +var _point = require("./point"); + +var _meshline = require("./meshline"); + +var _polygon = require("./polygon"); + +var _arcline = require("./arcline"); \ No newline at end of file diff --git a/lib/geom/material/lineMaterial.js b/lib/geom/material/lineMaterial.js new file mode 100644 index 0000000000..1781562bf6 --- /dev/null +++ b/lib/geom/material/lineMaterial.js @@ -0,0 +1,111 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.LineMaterial = LineMaterial; +exports.ArcLineMaterial = ArcLineMaterial; +exports.MeshLineMaterial = MeshLineMaterial; + +var THREE = _interopRequireWildcard(require("../../core/three")); + +var _material = _interopRequireDefault(require("./material")); + +var _shaderModule = require("../../util/shaderModule"); + +var _deepMix = _interopRequireDefault(require("@antv/util/lib/deep-mix")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function LineMaterial(options) { + var _getModule = (0, _shaderModule.getModule)('line'), + vs = _getModule.vs, + fs = _getModule.fs; + + var material = new _material["default"]({ + uniforms: { + u_opacity: { + value: options.u_opacity || 1.0 + }, + u_time: { + value: options.u_time || 0 + }, + u_zoom: { + value: options.u_zoom || 10 + }, + u_activeId: { + value: options.activeId || 0 + }, + u_activeColor: { + value: options.activeColor || [1.0, 0, 0, 1.0] + } + }, + vertexShader: vs, + fragmentShader: fs, + transparent: true // blending: THREE.AdditiveBlending + + }); + return material; +} + +function ArcLineMaterial(options) { + var moduleName = 'arcline'; + + if (options.shapeType === 'greatCircle') { + moduleName = 'greatcircle'; + } + + var _getModule2 = (0, _shaderModule.getModule)(moduleName), + vs = _getModule2.vs, + fs = _getModule2.fs; + + var material = new _material["default"]({ + uniforms: { + u_opacity: { + value: options.u_opacity || 1.0 + }, + segmentNumber: { + value: 29 + }, + u_time: { + value: 0 + }, + u_zoom: { + value: options.u_zoom || 10 + }, + u_activeId: { + value: options.activeId || 0 + }, + u_activeColor: { + value: options.activeColor || [1.0, 0, 0, 1.0] + } + }, + vertexShader: vs, + fragmentShader: fs, + transparent: true, + blending: THREE.AdditiveBlending + }); + return material; +} + +function MeshLineMaterial(options, defines) { + var _getModule3 = (0, _shaderModule.getModule)('meshline'), + vs = _getModule3.vs, + fs = _getModule3.fs, + uniforms = _getModule3.uniforms; + + var material = new _material["default"]({ + uniforms: (0, _shaderModule.wrapUniforms)((0, _deepMix["default"])(uniforms, options, { + u_activeId: options.activeId, + u_activeColor: options.activeColor + })), + defines: defines, + vertexShader: vs, + fragmentShader: fs, + transparent: true // blending: THREE.AdditiveBlending + + }); + return material; +} \ No newline at end of file diff --git a/lib/geom/material/material.js b/lib/geom/material/material.js new file mode 100644 index 0000000000..5b2a9fb7cf --- /dev/null +++ b/lib/geom/material/material.js @@ -0,0 +1,97 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var THREE = _interopRequireWildcard(require("../../core/three")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var blendingEnum = { + normal: 'NormalBlending', + additive: 'AdditiveBlending', + subtractive: 'SubtractiveBlending' +}; + +var Material = +/*#__PURE__*/ +function (_THREE$ShaderMaterial) { + _inherits(Material, _THREE$ShaderMaterial); + + function Material() { + _classCallCheck(this, Material); + + return _possibleConstructorReturn(this, _getPrototypeOf(Material).apply(this, arguments)); + } + + _createClass(Material, [{ + key: "setUniformsValue", + value: function setUniformsValue(name, value) { + if (!this.uniforms[name]) { + return; + } + + this.uniforms[name].value = value; + this.uniforms.needsUpdate = true; + } + }, { + key: "setDefinesvalue", + value: function setDefinesvalue(name, value) { + this.defines[name] = value; + this.needsUpdate = true; + } + }, { + key: "setUniform", + value: function setUniform(option) { + var uniforms = {}; + + for (var key in option) { + if (key.substr(0, 2) === 'u_') { + uniforms[key] = { + value: option[key] + }; + } + } + + return uniforms; + } + }, { + key: "updateUninform", + value: function updateUninform(option) { + for (var key in option) { + if (key.substr(0, 2) === 'u_') { + this.setUniformsValue(key, option[key]); + } + } + } + }, { + key: "setBending", + value: function setBending(type) { + this.blending = THREE[blendingEnum[type]] || THREE.NormalBlending; + } + }]); + + return Material; +}(THREE.ShaderMaterial); + +exports["default"] = Material; \ No newline at end of file diff --git a/lib/geom/material/normal_point.js b/lib/geom/material/normal_point.js new file mode 100644 index 0000000000..4e81f715a3 --- /dev/null +++ b/lib/geom/material/normal_point.js @@ -0,0 +1,95 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _material = _interopRequireDefault(require("./material")); + +var THREE = _interopRequireWildcard(require("../../core/three")); + +var _shaderModule = require("../../util/shaderModule"); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var PointMaterial = +/*#__PURE__*/ +function (_Material) { + _inherits(PointMaterial, _Material); + + _createClass(PointMaterial, [{ + key: "getDefaultParameters", + value: function getDefaultParameters() { + return { + uniforms: { + u_opacity: { + value: 1 + }, + u_stroke: { + value: [1.0, 1.0, 1.0, 1.0] + }, + u_strokeWidth: { + value: 1 + }, + u_activeId: { + value: 0 + } + }, + defines: { + SHAPE: false, + TEXCOORD_0: false + } + }; + } + }]); + + function PointMaterial(_uniforms, _defines, parameters) { + var _this; + + _classCallCheck(this, PointMaterial); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(PointMaterial).call(this, parameters)); + + var _this$getDefaultParam = _this.getDefaultParameters(), + uniforms = _this$getDefaultParam.uniforms, + defines = _this$getDefaultParam.defines; + + var _getModule = (0, _shaderModule.getModule)('pointnormal'), + vs = _getModule.vs, + fs = _getModule.fs; + + _this.uniforms = Object.assign(uniforms, _this.setUniform(_uniforms)); + _this.defines = Object.assign(defines, _defines); + _this.type = 'PointMaterial'; + _this.vertexShader = vs; + _this.fragmentShader = fs; + _this.transparent = true; + _this.blending = THREE.AdditiveBlending; + return _this; + } + + return PointMaterial; +}(_material["default"]); + +exports["default"] = PointMaterial; \ No newline at end of file diff --git a/lib/geom/material/pointLineMaterial.js b/lib/geom/material/pointLineMaterial.js new file mode 100644 index 0000000000..9e884db1d5 --- /dev/null +++ b/lib/geom/material/pointLineMaterial.js @@ -0,0 +1,90 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _material = _interopRequireDefault(require("./material")); + +var _shaderModule = require("../../util/shaderModule"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var PointLineMaterial = +/*#__PURE__*/ +function (_Material) { + _inherits(PointLineMaterial, _Material); + + _createClass(PointLineMaterial, [{ + key: "getDefaultParameters", + value: function getDefaultParameters() { + return { + uniforms: { + u_strokeOpacity: { + value: 1 + }, + u_stroke: { + value: [1.0, 1.0, 1.0, 1.0] + }, + u_strokeWidth: { + value: 1.0 + }, + u_zoom: { + value: 10 + }, + u_activeId: { + value: 0 + }, + u_activeColor: { + value: [1.0, 0, 0, 1.0] + } + } + }; + } + }]); + + function PointLineMaterial(_uniforms, _defines, parameters) { + var _this; + + _classCallCheck(this, PointLineMaterial); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(PointLineMaterial).call(this, parameters)); + + var _this$getDefaultParam = _this.getDefaultParameters(), + uniforms = _this$getDefaultParam.uniforms; + + var _getModule = (0, _shaderModule.getModule)('pointline'), + vs = _getModule.vs, + fs = _getModule.fs; + + _this.uniforms = Object.assign(uniforms, _this.setUniform(_uniforms)); + _this.type = 'PointLineMaterial'; + _this.vertexShader = vs; + _this.fragmentShader = fs; + _this.transparent = true; + return _this; + } + + return PointLineMaterial; +}(_material["default"]); + +exports["default"] = PointLineMaterial; \ No newline at end of file diff --git a/lib/geom/material/pointMaterial.js b/lib/geom/material/pointMaterial.js new file mode 100644 index 0000000000..e80f51791a --- /dev/null +++ b/lib/geom/material/pointMaterial.js @@ -0,0 +1,103 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _material = _interopRequireDefault(require("./material")); + +var THREE = _interopRequireWildcard(require("../../core/three")); + +var _shaderModule = require("../../util/shaderModule"); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var PointMaterial = +/*#__PURE__*/ +function (_Material) { + _inherits(PointMaterial, _Material); + + _createClass(PointMaterial, [{ + key: "getDefaultParameters", + value: function getDefaultParameters() { + return { + uniforms: { + u_opacity: { + value: 1 + }, + u_stroke: { + value: [1.0, 1.0, 1.0, 1.0] + }, + u_strokeWidth: { + value: 1 + }, + u_activeId: { + value: 0 + } + }, + defines: { + SHAPE: false, + TEXCOORD_0: false + } + }; + } + }]); + + function PointMaterial(_uniforms, _defines, parameters) { + var _this; + + _classCallCheck(this, PointMaterial); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(PointMaterial).call(this, parameters)); + + var _this$getDefaultParam = _this.getDefaultParameters(), + uniforms = _this$getDefaultParam.uniforms, + defines = _this$getDefaultParam.defines; + + var _getModule = (0, _shaderModule.getModule)('point'), + vs = _getModule.vs, + fs = _getModule.fs; + + _this.uniforms = Object.assign(uniforms, _this.setUniform(_uniforms)); + _this.defines = Object.assign(defines, _defines); + _this.type = 'PointMaterial'; + _this.vertexShader = vs; + _this.fragmentShader = fs; + _this.transparent = true; + + if (!_this.uniforms.shape) { + _this.blending = THREE.AdditiveBlending; + } + + if (_this.uniforms.u_texture) { + _this.defines.TEXCOORD_0 = true; + } + + return _this; + } + + return PointMaterial; +}(_material["default"]); + +exports["default"] = PointMaterial; \ No newline at end of file diff --git a/lib/geom/material/polygonMaterial.js b/lib/geom/material/polygonMaterial.js new file mode 100644 index 0000000000..0320f51452 --- /dev/null +++ b/lib/geom/material/polygonMaterial.js @@ -0,0 +1,59 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _material = _interopRequireDefault(require("./material")); + +var _shaderModule = require("../../util/shaderModule"); + +var _deepMix = _interopRequireDefault(require("@antv/util/lib/deep-mix")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var PolygonMaterial = +/*#__PURE__*/ +function (_Material) { + _inherits(PolygonMaterial, _Material); + + function PolygonMaterial(_uniforms, _defines, parameters) { + var _this; + + _classCallCheck(this, PolygonMaterial); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(PolygonMaterial).call(this, parameters)); + + var _getModule = (0, _shaderModule.getModule)('polygon'), + vs = _getModule.vs, + fs = _getModule.fs, + uniforms = _getModule.uniforms; + + _this.uniforms = (0, _shaderModule.wrapUniforms)((0, _deepMix["default"])(uniforms, _uniforms)); + _this.type = 'PolygonMaterial'; + _this.defines = _defines; + _this.vertexShader = vs; + _this.fragmentShader = fs; + _this.transparent = true; + return _this; + } + + return PolygonMaterial; +}(_material["default"]); + +exports["default"] = PolygonMaterial; \ No newline at end of file diff --git a/lib/geom/material/rainPass.js b/lib/geom/material/rainPass.js new file mode 100644 index 0000000000..0a8b785cc4 --- /dev/null +++ b/lib/geom/material/rainPass.js @@ -0,0 +1,145 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.RainPassMaterial = void 0; + +var _r3Base = require("@ali/r3-base"); + +var _r3Material = require("@ali/r3-material"); + +var _rainPass_frag = _interopRequireDefault(require("../shader/rainPass_frag.glsl")); + +var _rainPass_vert = _interopRequireDefault(require("../shader/rainPass_vert.glsl")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var RainPassMaterial = +/*#__PURE__*/ +function (_Material) { + _inherits(RainPassMaterial, _Material); + + function RainPassMaterial(opt) { + var _this; + + _classCallCheck(this, RainPassMaterial); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(RainPassMaterial).call(this, opt.name)); // this._generateTechnique(); + + for (var item in opt) { + if (item.substr(0, 2) === 'u_') { + _this.setValue(item, opt[item]); + } + } + + return _this; + } + + _createClass(RainPassMaterial, [{ + key: "_generateTechnique", + value: function _generateTechnique() { + var VERT_SHADER = _rainPass_vert.default; // 片元着色器 + + var FRAG_SHADER = _rainPass_frag.default; // Technique 配置信息 + + var cfg = { + attributes: { + a_position: { + name: 'a_position', + semantic: 'POSITION', + type: _r3Base.DataType.FLOAT_VEC3 + }, + a_uv: { + name: 'a_uv', + semantic: 'TEXCOORD_0', + type: _r3Base.DataType.FLOAT_VEC2 + } + }, + uniforms: { + matModelViewProjection: { + name: 'matModelViewProjection', + semantic: _r3Base.UniformSemantic.MODELVIEWPROJECTION, + type: _r3Base.DataType.FLOAT_MAT4 + }, + u_texture: { + name: 'u_texture', + type: _r3Base.DataType.SAMPLER_2D + }, + u_colorTexture: { + name: 'u_colorTexture', + type: _r3Base.DataType.SAMPLER_2D + } + } + }; // 创建 Technique + + var tech = new _r3Material.RenderTechnique('PointMaterial'); + tech.states = { + disable: [_r3Base.RenderState.CULL_FACE, _r3Base.RenderState.DEPTH_TEST], + enable: [_r3Base.RenderState.BLEND], + functions: { + blendFunc: [_r3Base.BlendFunc.SRC_ALPHA, _r3Base.BlendFunc.ONE_MINUS_SRC_ALPHA] + } + }; + tech.isValid = true; + tech.uniforms = cfg.uniforms; + tech.attributes = cfg.attributes; + tech.vertexShader = VERT_SHADER; + tech.fragmentShader = FRAG_SHADER; + tech.customMacros = this._macros; + this._technique = tech; + } + }, { + key: "prepareDrawing", + value: function prepareDrawing(camera, component, primitive) { + this.getAttributeDefines(camera, component, primitive); + + if (!this._technique) { + this._generateTechnique(); + } + + _get(_getPrototypeOf(RainPassMaterial.prototype), "prepareDrawing", this).call(this, camera, component, primitive); + } + }, { + key: "getAttributeDefines", + value: function getAttributeDefines(camera, component, primitive) { + this._macros = []; + if (!primitive) return this._macros; + var attribNames = Object.keys(primitive.vertexAttributes); + + if (attribNames.indexOf('SHAPE') !== -1) { + this._macros.push('SHAPE'); + } + + if (attribNames.indexOf('TEXCOORD_0') !== -1) { + this._macros.push('TEXCOORD_0'); + } + } + }]); + + return RainPassMaterial; +}(_r3Material.Material); + +exports.RainPassMaterial = RainPassMaterial; \ No newline at end of file diff --git a/lib/geom/material/rasterMaterial.js b/lib/geom/material/rasterMaterial.js new file mode 100644 index 0000000000..c164b10c66 --- /dev/null +++ b/lib/geom/material/rasterMaterial.js @@ -0,0 +1,51 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = ImageMaterial; + +var _material = _interopRequireDefault(require("./material")); + +var _shaderModule = require("../../util/shaderModule"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function ImageMaterial(options) { + var _getModule = (0, _shaderModule.getModule)('raster'), + vs = _getModule.vs, + fs = _getModule.fs; + + var material = new _material["default"]({ + uniforms: { + u_opacity: { + value: options.u_opacity + }, + u_texture: { + value: options.u_texture + }, + u_colorTexture: { + value: options.u_colorTexture + }, + u_min: { + value: options.u_min + }, + u_max: { + value: options.u_max + }, + u_extent: { + value: options.u_extent + }, + u_dimension: { + value: options.u_dimension + } + }, + vertexShader: vs, + fragmentShader: fs, + transparent: false + }); // material.roughness = 1; + // material.metalness = 0.1; + // material.envMapIntensity = 3; + + return material; +} \ No newline at end of file diff --git a/lib/geom/material/text.js b/lib/geom/material/text.js new file mode 100644 index 0000000000..4d1e0db89b --- /dev/null +++ b/lib/geom/material/text.js @@ -0,0 +1,189 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TextMaterial = void 0; + +var _r3Base = require("@ali/r3-base"); + +var _r3Material = require("@ali/r3-material"); + +var _text_frag = _interopRequireDefault(require("../shader/text_frag.glsl")); + +var _text_vert = _interopRequireDefault(require("../shader/text_vert.glsl")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var TextMaterial = +/*#__PURE__*/ +function (_Material) { + _inherits(TextMaterial, _Material); + + function TextMaterial(opt) { + var _this; + + _classCallCheck(this, TextMaterial); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(TextMaterial).call(this, opt.name)); // this._generateTechnique(); + + for (var item in opt) { + if (item.substr(0, 2) === 'u_') { + _this.setValue(item, opt[item]); + } + } + + return _this; + } + + _createClass(TextMaterial, [{ + key: "_generateTechnique", + value: function _generateTechnique() { + var VERT_SHADER = _text_vert.default; // 片元着色器 + + var FRAG_SHADER = _text_frag.default; // Technique 配置信息 + + var cfg = { + attributes: { + a_position: { + name: 'a_position', + semantic: 'POSITION', + type: _r3Base.DataType.FLOAT_VEC4 + }, + a_color: { + name: 'a_color', + semantic: 'COLOR', + type: _r3Base.DataType.FLOAT_VEC4 + }, + a_uv: { + name: 'a_uv', + semantic: 'TEXCOORD_0', + type: _r3Base.DataType.FLOAT_VEC2 + } + }, + uniforms: { + matModelViewProjection: { + name: 'matModelViewProjection', + semantic: _r3Base.UniformSemantic.MODELVIEWPROJECTION, + type: _r3Base.DataType.FLOAT_MAT4 + }, + u_model: { + name: 'u_model', + semantic: _r3Base.UniformSemantic.MODEL, + type: _r3Base.DataType.FLOAT_MAT4 + }, + u_view: { + name: 'u_view', + semantic: _r3Base.UniformSemantic.VIEW, + type: _r3Base.DataType.FLOAT_MAT4 + }, + u_projection: { + name: 'u_projection', + semantic: _r3Base.UniformSemantic.PROJECTION, + type: _r3Base.DataType.FLOAT_MAT4 + }, + u_texture: { + name: 'u_texture', + type: _r3Base.DataType.SAMPLER_2D + }, + u_stroke: { + name: 'u_stroke', + type: _r3Base.DataType.FLOAT_VEC4 + }, + u_strokeWidth: { + name: 'u_strokeWidth', + type: _r3Base.DataType.FLOAT + }, + u_textSize: { + name: 'u_textSize', + type: _r3Base.DataType.FLOAT_VEC2 + }, + u_color: { + name: 'u_color', + type: _r3Base.DataType.FLOAT_VEC4 + }, + u_buffer: { + name: 'u_buffer', + type: _r3Base.DataType.FLOAT + }, + u_scale: { + name: 'u_scale', + type: _r3Base.DataType.FLOAT_MAT4 + }, + u_gamma: { + name: 'u_gamma', + type: _r3Base.DataType.FLOAT + } + } + }; // 创建 Technique + + var tech = new _r3Material.RenderTechnique('TextMaterial'); + tech.states = { + disable: [_r3Base.RenderState.CULL_FACE, _r3Base.RenderState.DEPTH_TEST], + enable: [_r3Base.RenderState.BLEND], + functions: { + blendFunc: [_r3Base.BlendFunc.SRC_ALPHA, _r3Base.BlendFunc.ONE_MINUS_SRC_ALPHA] + } + }; + tech.isValid = true; + tech.uniforms = cfg.uniforms; + tech.attributes = cfg.attributes; + tech.vertexShader = VERT_SHADER; + tech.fragmentShader = FRAG_SHADER; + tech.customMacros = this._macros; + this._technique = tech; + } + }, { + key: "prepareDrawing", + value: function prepareDrawing(camera, component, primitive) { + this.getAttributeDefines(camera, component, primitive); + + if (!this._technique) { + this._generateTechnique(); + } + + _get(_getPrototypeOf(TextMaterial.prototype), "prepareDrawing", this).call(this, camera, component, primitive); + } + }, { + key: "getAttributeDefines", + value: function getAttributeDefines(camera, component, primitive) { + this._macros = []; + if (!primitive) return this._macros; + var attribNames = Object.keys(primitive.vertexAttributes); + + if (attribNames.indexOf('SHAPE') !== -1) { + this._macros.push('SHAPE'); + } + + if (attribNames.indexOf('TEXCOORD_0') !== -1) { + this._macros.push('TEXCOORD_0'); + } + } + }]); + + return TextMaterial; +}(_r3Material.Material); + +exports.TextMaterial = TextMaterial; \ No newline at end of file diff --git a/lib/geom/material/textMaterial.js b/lib/geom/material/textMaterial.js new file mode 100644 index 0000000000..c0f1138c23 --- /dev/null +++ b/lib/geom/material/textMaterial.js @@ -0,0 +1,60 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = TextMaterial; + +var _material = _interopRequireDefault(require("./material")); + +var _shaderModule = require("../../util/shaderModule"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function TextMaterial(options) { + var _getModule = (0, _shaderModule.getModule)('text'), + vs = _getModule.vs, + fs = _getModule.fs; + + var material = new _material["default"]({ + uniforms: { + u_opacity: { + value: options.u_opacity || 1.0 + }, + u_texture: { + value: options.u_texture + }, + u_strokeWidth: { + value: options.u_strokeWidth + }, + u_stroke: { + value: options.u_stroke + }, + u_textTextureSize: { + value: options.u_textTextureSize + }, + u_scale: { + value: options.u_scale + }, + u_gamma: { + value: options.u_gamma + }, + u_buffer: { + value: options.u_buffer + }, + u_glSize: { + value: options.u_glSize + }, + u_activeId: { + value: options.u_activeId || 0 + }, + u_activeColor: { + value: options.u_activeColor + } + }, + vertexShader: vs, + fragmentShader: fs, + transparent: true + }); + return material; +} \ No newline at end of file diff --git a/lib/geom/material/tile/maskMaterial.js b/lib/geom/material/tile/maskMaterial.js new file mode 100644 index 0000000000..98eabd41a8 --- /dev/null +++ b/lib/geom/material/tile/maskMaterial.js @@ -0,0 +1,74 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _material = _interopRequireDefault(require("./../material")); + +var _shaderModule = require("../../../util/shaderModule"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var MaskMaterial = +/*#__PURE__*/ +function (_Material) { + _inherits(MaskMaterial, _Material); + + _createClass(MaskMaterial, [{ + key: "getDefaultParameters", + value: function getDefaultParameters() { + return { + uniforms: {}, + defines: {} + }; + } + }]); + + function MaskMaterial(_uniforms, _defines, parameters) { + var _this; + + _classCallCheck(this, MaskMaterial); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(MaskMaterial).call(this, parameters)); + + var _this$getDefaultParam = _this.getDefaultParameters(), + uniforms = _this$getDefaultParam.uniforms, + defines = _this$getDefaultParam.defines; + + var _getModule = (0, _shaderModule.getModule)('mask_quard'), + vs = _getModule.vs, + fs = _getModule.fs; + + _this.uniforms = Object.assign(uniforms, _this.setUniform(_uniforms)); + _this.type = 'MaskMaterial'; + _this.defines = Object.assign(defines, _defines); + _this.vertexShader = vs; + _this.fragmentShader = fs; + _this.transparent = true; + return _this; + } + + return MaskMaterial; +}(_material["default"]); + +exports["default"] = MaskMaterial; \ No newline at end of file diff --git a/lib/geom/material/tile/polygon.js b/lib/geom/material/tile/polygon.js new file mode 100644 index 0000000000..22b42b2044 --- /dev/null +++ b/lib/geom/material/tile/polygon.js @@ -0,0 +1,87 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _material = _interopRequireDefault(require("../material")); + +var _shaderModule = require("../../../util/shaderModule"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var TileMaterial = +/*#__PURE__*/ +function (_Material) { + _inherits(TileMaterial, _Material); + + _createClass(TileMaterial, [{ + key: "getDefaultParameters", + value: function getDefaultParameters() { + return { + uniforms: { + u_opacity: { + value: 1.0 + }, + u_time: { + value: 0 + }, + u_activeId: { + value: 0 + }, + u_activeColor: { + value: [1.0, 0, 0, 1.0] + } + }, + defines: {} + }; + } + }]); + + function TileMaterial(_uniforms, _defines, parameters) { + var _this; + + _classCallCheck(this, TileMaterial); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(TileMaterial).call(this, parameters)); + + var _this$getDefaultParam = _this.getDefaultParameters(), + uniforms = _this$getDefaultParam.uniforms, + defines = _this$getDefaultParam.defines; + + var _getModule = (0, _shaderModule.getModule)('tilepolygon'), + vs = _getModule.vs, + fs = _getModule.fs; + + _this.uniforms = Object.assign(uniforms, _this.setUniform(_uniforms)); + _this.type = 'tile_polygon_Material'; + _this.defines = Object.assign(defines, _defines); + _this.vertexShader = vs; + _this.fragmentShader = fs; + _this.transparent = true; + return _this; + } + + return TileMaterial; +}(_material["default"]); + +exports["default"] = TileMaterial; \ No newline at end of file diff --git a/lib/geom/normals.js b/lib/geom/normals.js new file mode 100644 index 0000000000..c230fcc416 --- /dev/null +++ b/lib/geom/normals.js @@ -0,0 +1,135 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.vertexNormals = vertexNormals; +exports.faceNormals = faceNormals; +var DEFAULT_NORMALS_EPSILON = 1e-6; +var DEFAULT_FACE_EPSILON = 1e-6; +/** + * Estimate the vertex normals of a mesh + * @param {*} faces 索引坐标 + * @param {*} positions 顶点 + * @param {*} specifiedEpsilon 参数 + * @return {*} normals + */ + +function vertexNormals(faces, positions, specifiedEpsilon) { + var N = positions.length; + var normals = new Array(N); + var epsilon = specifiedEpsilon === void 0 ? DEFAULT_NORMALS_EPSILON : specifiedEpsilon; // Initialize normal array + + for (var i = 0; i < N; ++i) { + normals[i] = [0.0, 0.0, 0.0]; + } // Walk over all the faces and add per-vertex contribution to normal weights + + + for (var _i = 0; _i < faces.length / 3; ++_i) { + var f = [faces[_i * 3], faces[_i * 3 + 1], faces[_i * 3 + 2]]; + var p = 0; + var c = f[f.length - 1]; + var n = f[0]; + + for (var j = 0; j < f.length; ++j) { + // Shift indices back + p = c; + c = n; + n = f[(j + 1) % f.length]; + var v0 = positions[p]; + var v1 = positions[c]; + var v2 = positions[n]; // Compute infineteismal arcs + + var d01 = new Array(3); + var m01 = 0.0; + var d21 = new Array(3); + var m21 = 0.0; + + for (var k = 0; k < 3; ++k) { + d01[k] = v0[k] - v1[k]; + m01 += d01[k] * d01[k]; + d21[k] = v2[k] - v1[k]; + m21 += d21[k] * d21[k]; + } // Accumulate values in normal + + + if (m01 * m21 > epsilon) { + var norm = normals[c]; + var w = 1.0 / Math.sqrt(m01 * m21); + + for (var _k = 0; _k < 3; ++_k) { + var u = (_k + 1) % 3; + var v = (_k + 2) % 3; + norm[_k] += w * (d21[u] * d01[v] - d21[v] * d01[u]); + } + } + } + } // Scale all normals to unit length + + + for (var _i2 = 0; _i2 < N; ++_i2) { + var _norm = normals[_i2]; + var m = 0.0; + + for (var _k2 = 0; _k2 < 3; ++_k2) { + m += _norm[_k2] * _norm[_k2]; + } + + if (m > epsilon) { + var _w = 1.0 / Math.sqrt(m); + + for (var _k3 = 0; _k3 < 3; ++_k3) { + _norm[_k3] *= _w; + } + } else { + for (var _k4 = 0; _k4 < 3; ++_k4) { + _norm[_k4] = 0.0; + } + } + } // Return the resulting set of patches + + + return normals; +} // Compute face normals of a mesh + + +function faceNormals(faces, positions, specifiedEpsilon) { + var N = faces.length / 3; + var normals = new Array(N); + var epsilon = specifiedEpsilon === void 0 ? DEFAULT_FACE_EPSILON : specifiedEpsilon; + + for (var i = 0; i < N; ++i) { + var pos = [positions[faces[i * 3]], positions[faces[i * 3 + 1]], positions[faces[i * 3 + 2]]]; + var d01 = new Array(3); + var d21 = new Array(3); + + for (var j = 0; j < 3; ++j) { + d01[j] = pos[1][j] - pos[0][j]; + d21[j] = pos[2][j] - pos[0][j]; + } + + var n = new Array(3); + var l = 0.0; + + for (var _j = 0; _j < 3; ++_j) { + var u = (_j + 1) % 3; + var v = (_j + 2) % 3; + n[_j] = d01[u] * d21[v] - d01[v] * d21[u]; + l += n[_j] * n[_j]; + } + + if (l > epsilon) { + l = 1.0 / Math.sqrt(l); + } else { + l = 0.0; + } + + for (var _j2 = 0; _j2 < 3; ++_j2) { + n[_j2] *= l; + } + + normals[i] = n; + } + + return normals; +} \ No newline at end of file diff --git a/lib/geom/shader/index.js b/lib/geom/shader/index.js new file mode 100644 index 0000000000..fb7aa5e4a9 --- /dev/null +++ b/lib/geom/shader/index.js @@ -0,0 +1,208 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.compileBuiltinModules = compileBuiltinModules; + +var _point_frag = _interopRequireDefault(require("../shader/point_frag.glsl")); + +var _point_vert = _interopRequireDefault(require("../shader/point_vert.glsl")); + +var _polygon_frag = _interopRequireDefault(require("../shader/polygon_frag.glsl")); + +var _polygon_vert = _interopRequireDefault(require("../shader/polygon_vert.glsl")); + +var _grid_frag = _interopRequireDefault(require("../shader/grid_frag.glsl")); + +var _grid_vert = _interopRequireDefault(require("../shader/grid_vert.glsl")); + +var _hexagon_frag = _interopRequireDefault(require("../shader/hexagon_frag.glsl")); + +var _hexagon_vert = _interopRequireDefault(require("../shader/hexagon_vert.glsl")); + +var _circle_frag = _interopRequireDefault(require("./circle_frag.glsl")); + +var _circle_vert = _interopRequireDefault(require("./circle_vert.glsl")); + +var _point_meshLine_frag = _interopRequireDefault(require("../shader/point_meshLine_frag.glsl")); + +var _point_meshLine_vert = _interopRequireDefault(require("../shader/point_meshLine_vert.glsl")); + +var _normal_point_frag = _interopRequireDefault(require("./normal_point_frag.glsl")); + +var _normal_point_vert = _interopRequireDefault(require("./normal_point_vert.glsl")); + +var _meshline_frag = _interopRequireDefault(require("../shader/meshline_frag.glsl")); + +var _meshline_vert = _interopRequireDefault(require("../shader/meshline_vert.glsl")); + +var _arcline_frag = _interopRequireDefault(require("../shader/arcline_frag.glsl")); + +var _arcline_vert = _interopRequireDefault(require("../shader/arcline_vert.glsl")); + +var _great_circle_line_vert = _interopRequireDefault(require("../shader/great_circle_line_vert.glsl")); + +var _line_frag = _interopRequireDefault(require("../shader/line_frag.glsl")); + +var _line_vert = _interopRequireDefault(require("../shader/line_vert.glsl")); + +var _heatmap_colorize_vert = _interopRequireDefault(require("../shader/heatmap_colorize_vert.glsl")); + +var _heatmap_colorize_frag = _interopRequireDefault(require("../shader/heatmap_colorize_frag.glsl")); + +var _heatmap_intensity_frag = _interopRequireDefault(require("../shader/heatmap_intensity_frag.glsl")); + +var _heatmap_intensity_vert = _interopRequireDefault(require("../shader/heatmap_intensity_vert.glsl")); + +var _text_frag = _interopRequireDefault(require("../shader/text_frag.glsl")); + +var _text_vert = _interopRequireDefault(require("../shader/text_vert.glsl")); + +var _image_vert = _interopRequireDefault(require("../shader/image_vert.glsl")); + +var _image_frag = _interopRequireDefault(require("../shader/image_frag.glsl")); + +var _raster_vert = _interopRequireDefault(require("../shader/raster_vert.glsl")); + +var _raster_frag = _interopRequireDefault(require("../shader/raster_frag.glsl")); + +var _polygon_vert2 = _interopRequireDefault(require("../shader/tile/polygon_vert.glsl")); + +var _polygon_frag2 = _interopRequireDefault(require("../shader/tile/polygon_frag.glsl")); + +var _mask_quard_vert = _interopRequireDefault(require("../shader/tile/mask_quard_vert.glsl")); + +var _mask_quard_frag = _interopRequireDefault(require("../shader/tile/mask_quard_frag.glsl")); + +var _common = _interopRequireDefault(require("./common.glsl")); + +var _shaderModule = require("../../util/shaderModule"); + +var _pick_color = _interopRequireDefault(require("./shaderChunks/pick_color.glsl")); + +var _decode = _interopRequireDefault(require("./shaderChunks/decode.glsl")); + +var _lighting = _interopRequireDefault(require("./shaderChunks/lighting.glsl")); + +var _pick = _interopRequireDefault(require("./shaderChunks/pick.glsl")); + +var _sdf_2d = _interopRequireDefault(require("./shaderChunks/sdf_2d.glsl")); + +var _project = _interopRequireDefault(require("./shaderChunks/project.glsl")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +// 点的边线 +// 原生点 +// 有宽度的线 +// arc line +// 原生线 +// 热力图 +// 文本 +// 图像 +// 栅格 +// tile +// mask +function compileBuiltinModules() { + (0, _shaderModule.registerModule)('point', { + vs: _point_vert["default"], + fs: _point_frag["default"] + }); + (0, _shaderModule.registerModule)('common', { + vs: _common["default"], + fs: _common["default"] + }); + (0, _shaderModule.registerModule)('decode', { + vs: _decode["default"], + fs: '' + }); + (0, _shaderModule.registerModule)('lighting', { + vs: _lighting["default"], + fs: '' + }); + (0, _shaderModule.registerModule)('pick', { + vs: '', + fs: _pick["default"] + }); + (0, _shaderModule.registerModule)('sdf_2d', { + vs: '', + fs: _sdf_2d["default"] + }); + (0, _shaderModule.registerModule)('project', { + vs: _project["default"], + fs: '' + }); + (0, _shaderModule.registerModule)('pick_color', { + vs: _pick_color["default"], + fs: _pick_color["default"] + }); + (0, _shaderModule.registerModule)('circle', { + vs: _circle_vert["default"], + fs: _circle_frag["default"] + }); + (0, _shaderModule.registerModule)('polygon', { + vs: _polygon_vert["default"], + fs: _polygon_frag["default"] + }); + (0, _shaderModule.registerModule)('grid', { + vs: _grid_vert["default"], + fs: _grid_frag["default"] + }); + (0, _shaderModule.registerModule)('hexagon', { + vs: _hexagon_vert["default"], + fs: _hexagon_frag["default"] + }); + (0, _shaderModule.registerModule)('pointline', { + vs: _point_meshLine_vert["default"], + fs: _point_meshLine_frag["default"] + }); + (0, _shaderModule.registerModule)('pointnormal', { + vs: _normal_point_vert["default"], + fs: _normal_point_frag["default"] + }); + (0, _shaderModule.registerModule)('meshline', { + vs: _meshline_vert["default"], + fs: _meshline_frag["default"] + }); + (0, _shaderModule.registerModule)('arcline', { + vs: _arcline_vert["default"], + fs: _arcline_frag["default"] + }); + (0, _shaderModule.registerModule)('greatcircle', { + vs: _great_circle_line_vert["default"], + fs: _arcline_frag["default"] + }); + (0, _shaderModule.registerModule)('line', { + vs: _line_vert["default"], + fs: _line_frag["default"] + }); + (0, _shaderModule.registerModule)('heatmap_color', { + vs: _heatmap_colorize_vert["default"], + fs: _heatmap_colorize_frag["default"] + }); + (0, _shaderModule.registerModule)('heatmap_intensity', { + vs: _heatmap_intensity_vert["default"], + fs: _heatmap_intensity_frag["default"] + }); + (0, _shaderModule.registerModule)('text', { + vs: _text_vert["default"], + fs: _text_frag["default"] + }); + (0, _shaderModule.registerModule)('image', { + vs: _image_vert["default"], + fs: _image_frag["default"] + }); + (0, _shaderModule.registerModule)('raster', { + vs: _raster_vert["default"], + fs: _raster_frag["default"] + }); + (0, _shaderModule.registerModule)('tilepolygon', { + vs: _polygon_vert2["default"], + fs: _polygon_frag2["default"] + }); + (0, _shaderModule.registerModule)('mask_quard', { + vs: _mask_quard_vert["default"], + fs: _mask_quard_frag["default"] + }); +} \ No newline at end of file diff --git a/lib/geom/shape/index.js b/lib/geom/shape/index.js new file mode 100644 index 0000000000..b56a3271ec --- /dev/null +++ b/lib/geom/shape/index.js @@ -0,0 +1,20 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.lineShape = exports.polygonShape = exports.regularShape = void 0; + +var regularShape = _interopRequireWildcard(require("./point")); + +exports.regularShape = regularShape; + +var polygonShape = _interopRequireWildcard(require("./polygon")); + +exports.polygonShape = polygonShape; + +var lineShape = _interopRequireWildcard(require("./line")); + +exports.lineShape = lineShape; + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } \ No newline at end of file diff --git a/lib/geom/shape/line.js b/lib/geom/shape/line.js new file mode 100644 index 0000000000..aca6ae8ef6 --- /dev/null +++ b/lib/geom/shape/line.js @@ -0,0 +1,158 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.arc = arc; +exports.defaultLine = defaultLine; +exports.Line = Line; + +var _polylineNormals = _interopRequireDefault(require("../../util/polyline-normals")); + +var _flatten = _interopRequireDefault(require("@antv/util/lib/flatten")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +/** + * shape arc + * @param {array} geo 坐标点 + * @param {int} index 原始数据index + * @return {object} 顶点坐标,起始点坐标,索引坐标 + */ +function arc(geo, props, positionsIndex) { + var segNum = 30; + var posArray = []; + var instanceArray = []; + var sizes = []; + var colors = []; + var pickingIds = []; + var size = props.size, + color = props.color, + id = props.id; + var defaultInstance = [geo[0][0], geo[0][1], geo[1][0], geo[1][1]]; + var indexArray = []; + var c = 0; + var index = positionsIndex; + + for (var i = 0; i < segNum; i++) { + posArray.push(i, 1, i); + posArray.push(i, -1, i); + instanceArray.push.apply(instanceArray, defaultInstance); + instanceArray.push.apply(instanceArray, defaultInstance); + sizes.push(size, size); + colors.push.apply(colors, _toConsumableArray(color)); + colors.push.apply(colors, _toConsumableArray(color)); + pickingIds.push(id); + pickingIds.push(id); + + if (i !== segNum - 1) { + indexArray[c++] = index + 0; + indexArray[c++] = index + 1; + indexArray[c++] = index + 2; + indexArray[c++] = index + 1; + indexArray[c++] = index + 3; + indexArray[c++] = index + 2; + } + + index += 2; + } + + return { + pickingIds: pickingIds, + positions: posArray, + indexArray: indexArray, + instances: instanceArray, + colors: colors, + sizes: sizes + }; +} +/** + * shape defaultLine + * @param {array} geo 坐标点 + * @param {int} index 原始数据index + * @return {object} 顶点坐标,索引坐标 + */ + + +function defaultLine(geo, index) { + var indexArray = []; + var positions = []; + geo.slice(0, geo.length - 1).forEach(function (coor, i) { + positions.push(coor, geo[i + 1]); + indexArray.push(index, index); + }); + return { + positions: positions, + indexes: indexArray + }; +} // mesh line + + +function Line(path, props, positionsIndex) { + var lengthPerDashSegment = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 200; + var textureCoord = arguments.length > 4 ? arguments[4] : undefined; + + if (Array.isArray(path[0][0])) { + path = path[0]; // 面坐标转线坐标 + } + + var positions = []; + var pickingIds = []; + var normal = []; + var miter = []; + var colors = []; + var dashArray = []; + var textureCoordArray = []; + + var _getNormals = (0, _polylineNormals["default"])(path, false, positionsIndex), + normals = _getNormals.normals, + attrIndex = _getNormals.attrIndex, + attrPos = _getNormals.attrPos, + attrDistance = _getNormals.attrDistance; + + var sizes = []; + var totalDistances = []; + var size = props.size, + color = props.color, + id = props.id; + !Array.isArray(size) && (size = [size]); + var totalLength = attrDistance[attrDistance.length - 1]; + attrPos.forEach(function (point) { + colors.push.apply(colors, _toConsumableArray(color)); + pickingIds.push(id); + sizes.push(size[0]); + point[2] = size[1] || 0; + positions.push.apply(positions, _toConsumableArray(point)); + textureCoordArray.push(textureCoord.x, textureCoord.y); + totalDistances.push(totalLength); + }); + var ratio = lengthPerDashSegment / totalLength; + normals.forEach(function (n) { + var norm = n[0]; + var m = n[1]; + normal.push(norm[0], norm[1], 0); + miter.push(m); + dashArray.push(ratio); + }); + return { + positions: positions, + normal: normal, + indexArray: (0, _flatten["default"])(attrIndex), + miter: miter, + colors: colors, + sizes: sizes, + pickingIds: pickingIds, + attrDistance: attrDistance, + dashArray: dashArray, + textureCoordArray: textureCoordArray, + totalDistances: totalDistances + }; +} \ No newline at end of file diff --git a/lib/geom/shape/path.js b/lib/geom/shape/path.js new file mode 100644 index 0000000000..d673b7621f --- /dev/null +++ b/lib/geom/shape/path.js @@ -0,0 +1,51 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.cylinder = exports.circle = circle; +exports.squareColumn = exports.square = square; +exports.triangleColumn = exports.triangle = triangle; +exports.hexagonColumn = exports.hexagon = hexagon; +exports.polygonPath = polygonPath; + +/** + * @author lzxue + * @email lzx199065@gmail.com + * @create date 2018-11-28 11:01:33 + * @modify date 2018-11-28 11:01:33 + * @desc 点,线,面 coordinates +*/ +function circle() { + return polygonPath(30); +} + +function square() { + return polygonPath(4); +} + +function triangle() { + return polygonPath(3); +} + +function hexagon() { + return polygonPath(6, 1); +} + +function polygonPath(pointCount) { + var start = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var step = Math.PI * 2 / pointCount; + var line = []; + + for (var i = 0; i < pointCount; i++) { + line.push(step * i + start * Math.PI / 12); + } + + var path = line.map(function (t) { + var x = Math.sin(t + Math.PI / 4), + y = Math.cos(t + Math.PI / 4); + return [x, y, 0]; + }); + path.push(path[0]); + return path; +} \ No newline at end of file diff --git a/lib/geom/shape/point.js b/lib/geom/shape/point.js new file mode 100644 index 0000000000..46094faccb --- /dev/null +++ b/lib/geom/shape/point.js @@ -0,0 +1,63 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.circle = circle; +exports.triangle = triangle; +exports.diamond = diamond; +exports.square = square; +exports.hexagon = hexagon; + +var polygonShape = _interopRequireWildcard(require("./polygon")); + +var _path = require("./path"); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +/** + * shape circle + * @param {enum} type 渲染类型 + * @return {object} 顶点坐标和索引坐标 + */ +function circle(type) { + var points = (0, _path.polygonPath)(30); + return polygonShape[type]([points]); +} +/** + * @param {enum} type 渲染类型 + * @param {boolean} extrude 是否进行高度拉伸 + * @return {object} 顶点坐标和索引坐标 + */ + + +function triangle(type) { + var points = (0, _path.polygonPath)(3); + return polygonShape[type]([points]); +} +/** + * @param {enum} type 渲染类型 + * @param {boolean} extrude 是否进行高度拉伸 + * @return {object} 顶点坐标和索引坐标 + */ + + +function diamond(type) { + var points = (0, _path.polygonPath)(4); + return polygonShape[type]([points]); +} + +function square(type) { + return diamond(type); +} +/** + * @param {enum} type 渲染类型 + * @param {boolean} extrude 是否进行高度拉伸 + * @return {object} 顶点坐标和索引坐标 + */ + + +function hexagon(type) { + var points = (0, _path.polygonPath)(6); + return polygonShape[type]([points]); +} \ No newline at end of file diff --git a/lib/geom/shape/polygon.js b/lib/geom/shape/polygon.js new file mode 100644 index 0000000000..11dcc54833 --- /dev/null +++ b/lib/geom/shape/polygon.js @@ -0,0 +1,90 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.fill = fill; +exports.extrude = extrude; +exports.line = line; +exports.extrudeline = extrudeline; + +var _extrude = _interopRequireDefault(require("../extrude")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +/** + * 计算平面的 polygon的顶点坐标和索引 + * @param {Array} points 顶点坐标 + * @param {*} extrude 是否拉伸 + * @return {object} 顶点坐标和顶点索引 + */ +function fill(points) { + return (0, _extrude["default"])(points, false); +} +/** + * 计算 extrude 的 polygon的顶点坐标和索引 + * @param {Array} points 顶点坐标 + * @param {*} extrude 是否拉伸 + * @return {object} 顶点坐标和顶点索引 + */ + + +function extrude(points) { + return (0, _extrude["default"])(points, true); +} +/** + * 绘制多边形轮廓 + * @param {*} points 点数据组 + * @return {object} 顶点坐标和顶点索引 + */ + + +function line(points) { + var vertIndex = []; + var vertCount = points[0].length - 1; + + for (var i = 0; i < vertCount; i++) { + vertIndex.push(i, i + 1); + } + + vertIndex.push(vertCount, 0); + return { + positions: points[0], + positionsIndex: vertIndex + }; +} +/** + * 绘制3D多边形轮廓 + * @param {*} points 点数据组 + * @return {object} 顶点坐标和顶点索引 + */ + + +function extrudeline(points) { + var positions = []; + points[0].forEach(function (p) { + positions.push([p[0], p[1], 0]); + }); + points[0].forEach(function (p) { + positions.push([p[0], p[1], 1]); + }); // top + + var vertIndex = []; + var pointCount = points[0].length; + var vertCount = pointCount - 1; + + for (var i = 0; i < vertCount; i++) { + vertIndex.push(i, i + 1); + vertIndex.push(i + pointCount, i + 1 + pointCount); + vertIndex.push(i, i + pointCount); + } + + vertIndex.push(vertCount, 0); + vertIndex.push(vertCount, vertCount + pointCount); + vertIndex.push(vertCount + pointCount, pointCount); + var newPositions = []; + vertIndex.forEach(function (index) { + newPositions.push(positions[index]); + }); + return newPositions; +} \ No newline at end of file diff --git a/lib/global.js b/lib/global.js new file mode 100644 index 0000000000..810af90b73 --- /dev/null +++ b/lib/global.js @@ -0,0 +1,52 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _version = _interopRequireDefault(require("./util/version")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +/** + * @fileOverview 全局变量 + * @author dxq613 + */ +// const Global = {}; +var FONT_FAMILY = '"-apple-system", BlinkMacSystemFont, "Segoe UI", Roboto,"Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei",SimSun, "sans-serif"'; +var Global = { + version: _version["default"], + scene: { + mapType: 'AMAP', + zoom: 5, + center: [107.622, 39.266], + minZoom: 0, + maxZoom: 22, + pitch: 0, + hash: false + }, + animate: true, + height: 0, + activeColor: '#2f54eb', + colors: ['rgb(103,0,31)', 'rgb(178,24,43)', 'rgb(214,96,77)', 'rgb(244,165,130)', 'rgb(253,219,199)', 'rgb(247,247,247)', 'rgb(209,229,240)', 'rgb(146,197,222)', 'rgb(67,147,195)', 'rgb(33,102,172)', 'rgb(5,48,97)'], + size: 10000, + shape: 'circle', + pattern: '', + snapArray: [0, 1, 2, 4, 5, 10], + pointShape: { + '2d': ['circle', 'triangle', 'square', 'pentagon', 'hexagon', 'octogon', 'hexagram', 'rhombus', 'vesica'], + '3d': ['cylinder', 'triangleColumn', 'hexagonColumn', 'squareColumn'] + }, + sdfHomeUrl: 'https://sdf.amap.com', + scales: {}, + textStyle: { + fontSize: 12, + fill: '#ccc', + textBaseline: 'middle', + fontFamily: FONT_FAMILY, + textAlign: 'center' + } +}; +var _default = Global; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/index.js b/lib/index.js new file mode 100755 index 0000000000..2dbeec7051 --- /dev/null +++ b/lib/index.js @@ -0,0 +1,37 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _scene = _interopRequireDefault(require("./core/scene")); + +var _global = _interopRequireDefault(require("./global")); + +var _source = _interopRequireDefault(require("./core/source")); + +var _tile_source = _interopRequireDefault(require("./source/tile_source")); + +var _source2 = require("./source"); + +var _interaction = require("./interaction"); + +var _layer = require("./layer"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +var version = _global["default"].version; +var exported = { + version: version, + Scene: _scene["default"], + Source: _source["default"], + TileSource: _tile_source["default"], + registerParser: _source2.registerParser, + registerTransform: _source2.registerTransform, + registerLayer: _layer.registerLayer, + registerInteraction: _interaction.registerInteraction, + getInteraction: _interaction.getInteraction +}; +var _default = exported; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/interaction/active.js b/lib/interaction/active.js new file mode 100644 index 0000000000..f7d6f3d42e --- /dev/null +++ b/lib/interaction/active.js @@ -0,0 +1,65 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("./base")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Active = +/*#__PURE__*/ +function (_Interaction) { + _inherits(Active, _Interaction); + + function Active(cfg) { + _classCallCheck(this, Active); + + return _possibleConstructorReturn(this, _getPrototypeOf(Active).call(this, _objectSpread({ + processEvent: 'mousemove', + resetEvent: 'mouseleave' + }, cfg))); + } + + _createClass(Active, [{ + key: "process", + value: function process(ev) { + this.layer._addActiveFeature(ev); + } + }, { + key: "reset", + value: function reset() { + this.layer._resetStyle(); + } + }]); + + return Active; +}(_base["default"]); + +exports["default"] = Active; \ No newline at end of file diff --git a/lib/interaction/base.js b/lib/interaction/base.js new file mode 100644 index 0000000000..0ac1d6b361 --- /dev/null +++ b/lib/interaction/base.js @@ -0,0 +1,149 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _ = _interopRequireWildcard(require("@antv/util")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var EVENT_TYPES = ['start', 'process', 'end', 'reset']; + +var Interaction = +/*#__PURE__*/ +function () { + function Interaction(cfg) { + _classCallCheck(this, Interaction); + + var defaultCfg = this._getDefaultCfg(); + + Object.assign(this, defaultCfg, cfg); + this._eventHandlers = []; + + this._bindEvents(); + } + + _createClass(Interaction, [{ + key: "_getDefaultCfg", + value: function _getDefaultCfg() { + return { + startEvent: 'mousedown', + processEvent: 'mousemove', + endEvent: 'mouseup', + resetEvent: 'dblclick' + }; + } + }, { + key: "_start", + value: function _start(ev) { + this.preStart(ev); + this.start(ev); + this.afterStart(ev); + } + }, { + key: "preStart", + value: function preStart() {} + }, { + key: "start", + value: function start() {} + }, { + key: "afterStart", + value: function afterStart() {} + }, { + key: "_process", + value: function _process(ev) { + this.preProcess(ev); + this.process(ev); + this.afterProcess(ev); + } + }, { + key: "preProcess", + value: function preProcess() {} + }, { + key: "process", + value: function process() {} + }, { + key: "afterProcess", + value: function afterProcess() {} + }, { + key: "_end", + value: function _end(ev) { + this.preEnd(ev); + this.end(ev); + this.afterEnd(ev); + } + }, { + key: "preEnd", + value: function preEnd() {} + }, { + key: "end", + value: function end() {} + }, { + key: "afterEnd", + value: function afterEnd() {} + }, { + key: "_reset", + value: function _reset() { + this.preReset(); + this.reset(); + this.afterReset(); + } + }, { + key: "preReset", + value: function preReset() {} + }, { + key: "reset", + value: function reset() {} + }, { + key: "afterReset", + value: function afterReset() {} + }, { + key: "_bindEvents", + value: function _bindEvents() { + var _this = this; + + _.each(EVENT_TYPES, function (type) { + var eventName = _this["".concat(type, "Event")]; + + var handler = _.wrapBehavior(_this, "_".concat(type)); + + _this.layer.on(eventName, handler); + + _this._eventHandlers.push({ + type: eventName, + handler: handler + }); + }); + } + }, { + key: "_unbindEvents", + value: function _unbindEvents() { + var _this2 = this; + + var eventHandlers = this._eventHandlers; + + _.each(eventHandlers, function (eh) { + _this2.layer.off(eh.type, eh.handler); + }); + } + }, { + key: "destory", + value: function destory() { + this._unbindEvents(); + + this._reset(); + } + }]); + + return Interaction; +}(); + +exports["default"] = Interaction; \ No newline at end of file diff --git a/lib/interaction/factory.js b/lib/interaction/factory.js new file mode 100644 index 0000000000..29db9a78aa --- /dev/null +++ b/lib/interaction/factory.js @@ -0,0 +1,26 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.registerInteraction = exports.getInteraction = exports.INTERACTION_MAP = void 0; +var INTERACTION_MAP = {}; +exports.INTERACTION_MAP = INTERACTION_MAP; + +var getInteraction = function getInteraction(type) { + return INTERACTION_MAP[type]; +}; + +exports.getInteraction = getInteraction; + +var registerInteraction = function registerInteraction(type, ctor) { + // 注册的时候,需要校验 type 重名,不区分大小写 + if (getInteraction(type)) { + throw new Error("Interaction type '".concat(type, "' existed.")); + } // 存储到 map 中 + + + INTERACTION_MAP[type] = ctor; +}; + +exports.registerInteraction = registerInteraction; \ No newline at end of file diff --git a/lib/interaction/hash.js b/lib/interaction/hash.js new file mode 100644 index 0000000000..25337f205c --- /dev/null +++ b/lib/interaction/hash.js @@ -0,0 +1,120 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("./base")); + +var _throttle = _interopRequireDefault(require("../util/throttle")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Hash = +/*#__PURE__*/ +function (_Interaction) { + _inherits(Hash, _Interaction); + + function Hash(cfg) { + var _this; + + _classCallCheck(this, Hash); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(Hash).call(this, _objectSpread({ + endEvent: 'camerachange' + }, cfg))); + window.addEventListener('hashchange', _this._onHashChange.bind(_assertThisInitialized(_this)), false); + _this._updateHash = (0, _throttle["default"])(_this._updateHashUnthrottled.bind(_assertThisInitialized(_this)), 30 * 1000 / 100); + return _this; + } + + _createClass(Hash, [{ + key: "end", + value: function end() { + this._updateHash(); + } + }, { + key: "reset", + value: function reset() {// this.layer._resetStyle(); + } + }, { + key: "_getHashString", + value: function _getHashString() { + var center = this.layer.getCenter(), + zoom = Math.round(this.layer.getZoom() * 100) / 100, + // derived from equation: 512px * 2^z / 360 / 10^d < 0.5px + precision = Math.ceil((zoom * Math.LN2 + Math.log(512 / 360 / 0.5)) / Math.LN10), + m = Math.pow(10, precision), + lng = Math.round(center.lng * m) / m, + lat = Math.round(center.lat * m) / m, + bearing = this.layer.getRotation(), + pitch = this.layer.getPitch(); + var hash = ''; + hash += "#".concat(zoom, "/").concat(lat, "/").concat(lng); + if (bearing || pitch) hash += "/".concat(Math.round(bearing * 10) / 10); + if (pitch) hash += "/".concat(Math.round(pitch)); + return hash; + } + }, { + key: "_onHashChange", + value: function _onHashChange() { + var loc = window.location.hash.replace('#', '').split('/'); + + if (loc.length >= 3) { + this.layer.setStatus({ + center: [+loc[2], +loc[1]], + zoom: +loc[0], + bearing: +(loc[3] || 0), + pitch: +(loc[4] || 0) + }); + return true; + } + + return false; + } + }, { + key: "_updateHashUnthrottled", + value: function _updateHashUnthrottled() { + var hash = this._getHashString(); + + window.history.replaceState(window.history.state, '', hash); + } + }, { + key: "destory", + value: function destory() { + window.removeEventListener('hashchange', this._onHashChange, false); + this.layer.off('camerachange', this._updateHash); + clearTimeout(this._updateHash()); + return this; + } + }]); + + return Hash; +}(_base["default"]); + +exports["default"] = Hash; \ No newline at end of file diff --git a/lib/interaction/index.js b/lib/interaction/index.js new file mode 100644 index 0000000000..71ad3ae4d5 --- /dev/null +++ b/lib/interaction/index.js @@ -0,0 +1,39 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "Interaction", { + enumerable: true, + get: function get() { + return _base["default"]; + } +}); +Object.defineProperty(exports, "getInteraction", { + enumerable: true, + get: function get() { + return _factory.getInteraction; + } +}); +Object.defineProperty(exports, "registerInteraction", { + enumerable: true, + get: function get() { + return _factory.registerInteraction; + } +}); + +var _base = _interopRequireDefault(require("./base")); + +var _active = _interopRequireDefault(require("./active")); + +var _select = _interopRequireDefault(require("./select")); + +var _hash = _interopRequireDefault(require("./hash")); + +var _factory = require("./factory"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +(0, _factory.registerInteraction)('active', _active["default"]); +(0, _factory.registerInteraction)('select', _select["default"]); +(0, _factory.registerInteraction)('hash', _hash["default"]); \ No newline at end of file diff --git a/lib/interaction/select.js b/lib/interaction/select.js new file mode 100644 index 0000000000..7591e8a9a6 --- /dev/null +++ b/lib/interaction/select.js @@ -0,0 +1,59 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("./base")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Select = +/*#__PURE__*/ +function (_Interaction) { + _inherits(Select, _Interaction); + + function Select(cfg) { + _classCallCheck(this, Select); + + return _possibleConstructorReturn(this, _getPrototypeOf(Select).call(this, _objectSpread({ + processEvent: 'click' + }, cfg))); + } + + _createClass(Select, [{ + key: "process", + value: function process(ev) { + this.layer._addActiveFeature(ev); + } + }]); + + return Select; +}(_base["default"]); + +exports["default"] = Select; \ No newline at end of file diff --git a/lib/layer/factory.js b/lib/layer/factory.js new file mode 100644 index 0000000000..fdf209cc6d --- /dev/null +++ b/lib/layer/factory.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.registerLayer = exports.getLayer = exports.LAYER_MAP = void 0; +var LAYER_MAP = {}; +exports.LAYER_MAP = LAYER_MAP; + +var getLayer = function getLayer(type) { + return LAYER_MAP[type.toLowerCase()]; +}; + +exports.getLayer = getLayer; + +var registerLayer = function registerLayer(type, layer) { + if (getLayer(type)) { + throw new Error("Layer type '".concat(type, "' existed.")); + } // 存储到 map 中 + + + LAYER_MAP[type] = layer; +}; + +exports.registerLayer = registerLayer; \ No newline at end of file diff --git a/lib/layer/heatmap.js b/lib/layer/heatmap.js new file mode 100644 index 0000000000..994166f2fb --- /dev/null +++ b/lib/layer/heatmap.js @@ -0,0 +1,124 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _layer = _interopRequireDefault(require("../core/layer")); + +var _grid = _interopRequireDefault(require("../geom/buffer/heatmap/grid")); + +var _gird = _interopRequireDefault(require("./render/heatmap/gird")); + +var _hexagon = _interopRequireDefault(require("./render/heatmap/hexagon")); + +var _hexagon2 = _interopRequireDefault(require("../geom/buffer/heatmap/hexagon")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var HeatMapLayer = +/*#__PURE__*/ +function (_Layer) { + _inherits(HeatMapLayer, _Layer); + + function HeatMapLayer() { + _classCallCheck(this, HeatMapLayer); + + return _possibleConstructorReturn(this, _getPrototypeOf(HeatMapLayer).apply(this, arguments)); + } + + _createClass(HeatMapLayer, [{ + key: "shape", + value: function shape(type) { + this.shapeType = type; + return this; + } + }, { + key: "render", + value: function render() { + this._prepareRender(); + + return this; + } + }, { + key: "_prepareRender", + value: function _prepareRender() { + this.init(); + + switch (this.shapeType) { + case 'grid': + this._drawGrid(); + + break; + + case 'hexagon': + this._drawHexagon(); + + break; + + default: + this._drawGrid(); + + } + } + }, { + key: "_drawHexagon", + value: function _drawHexagon() { + var style = this.get('styleOptions'); + var radius = this.layerSource.data.radius; + this._buffer = new _hexagon2.default(this.layerData); + + var config = _objectSpread({}, style, { + radius: radius + }); + + var Mesh = new _hexagon.default(this._buffer, config); + this.add(Mesh); + } + }, { + key: "_drawGrid", + value: function _drawGrid() { + this.type = 'heatmap'; + var style = this.get('styleOptions'); + var _this$layerSource$dat = this.layerSource.data, + xOffset = _this$layerSource$dat.xOffset, + yOffset = _this$layerSource$dat.yOffset; + this._buffer = new _grid.default(this.layerData); + + var config = _objectSpread({}, style, { + xOffset: xOffset, + yOffset: yOffset + }); + + var girdMesh = new _gird.default(this._buffer, config); + this.add(girdMesh); + } + }]); + + return HeatMapLayer; +}(_layer.default); + +exports.default = HeatMapLayer; \ No newline at end of file diff --git a/lib/layer/heatmapLayer.js b/lib/layer/heatmapLayer.js new file mode 100644 index 0000000000..5f4e5b8e84 --- /dev/null +++ b/lib/layer/heatmapLayer.js @@ -0,0 +1,60 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _layer = _interopRequireDefault(require("../core/layer")); + +var _render = require("./render/"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var HeatMapLayer = +/*#__PURE__*/ +function (_Layer) { + _inherits(HeatMapLayer, _Layer); + + function HeatMapLayer() { + _classCallCheck(this, HeatMapLayer); + + return _possibleConstructorReturn(this, _getPrototypeOf(HeatMapLayer).apply(this, arguments)); + } + + _createClass(HeatMapLayer, [{ + key: "shape", + value: function shape(type) { + this.shapeType = type; + return this; + } + }, { + key: "draw", + value: function draw() { + this.type = 'heatmap'; + this.add((0, _render.getRender)('heatmap', this.shapeType || 'heatmap')(this.layerData, this, this.layerSource)); + } + }]); + + return HeatMapLayer; +}(_layer["default"]); + +exports["default"] = HeatMapLayer; \ No newline at end of file diff --git a/lib/layer/heatmap_layer.js b/lib/layer/heatmap_layer.js new file mode 100644 index 0000000000..5496cd23f4 --- /dev/null +++ b/lib/layer/heatmap_layer.js @@ -0,0 +1,62 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _layer = _interopRequireDefault(require("../core/layer")); + +var _render = require("./render/"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var HeatMapLayer = +/*#__PURE__*/ +function (_Layer) { + _inherits(HeatMapLayer, _Layer); + + function HeatMapLayer() { + _classCallCheck(this, HeatMapLayer); + + return _possibleConstructorReturn(this, _getPrototypeOf(HeatMapLayer).apply(this, arguments)); + } + + _createClass(HeatMapLayer, [{ + key: "shape", + value: function shape(type) { + this.shapeType = type; + return this; + } + }, { + key: "draw", + value: function draw() { + this.type = 'heatmap'; + if (!this.shapeType) this.shapeType = 'heatmap'; + var renderType = this.shapeType === 'heatmap' ? 'heatmap' : 'shape'; + this.add((0, _render.getRender)('heatmap', renderType)(this.layerData, this, this.layerSource)); + } + }]); + + return HeatMapLayer; +}(_layer["default"]); + +exports["default"] = HeatMapLayer; \ No newline at end of file diff --git a/lib/layer/imageLayer.js b/lib/layer/imageLayer.js new file mode 100644 index 0000000000..6b55d20bd9 --- /dev/null +++ b/lib/layer/imageLayer.js @@ -0,0 +1,91 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _layer = _interopRequireDefault(require("../core/layer")); + +var THREE = _interopRequireWildcard(require("../core/three")); + +var _image = _interopRequireDefault(require("../geom/buffer/image")); + +var _imageMaterial = _interopRequireDefault(require("../geom/material/imageMaterial")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var imageLayer = +/*#__PURE__*/ +function (_Layer) { + _inherits(imageLayer, _Layer); + + function imageLayer() { + _classCallCheck(this, imageLayer); + + return _possibleConstructorReturn(this, _getPrototypeOf(imageLayer).apply(this, arguments)); + } + + _createClass(imageLayer, [{ + key: "draw", + value: function draw() { + var _this = this; + + this.type = 'image'; + var source = this.layerSource; + + var _this$get = this.get('styleOptions'), + opacity = _this$get.opacity; // 加载 完成事件 + + + source.originData.images.then(function (images) { + _this.layerData[0].images = images; + var buffer = new _image["default"]({ + layerData: _this.layerData + }); + + _this.initGeometry(buffer.attributes); + + var material = new _imageMaterial["default"]({ + u_texture: buffer.texture, + u_opacity: opacity + }); + var imageMesh = new THREE.Mesh(_this.geometry, material); + + _this.add(imageMesh); + }); + return this; + } + }, { + key: "initGeometry", + value: function initGeometry(attributes) { + this.geometry = new THREE.BufferGeometry(); + this.geometry.addAttribute('position', new THREE.Float32BufferAttribute(attributes.vertices, 3)); + this.geometry.addAttribute('uv', new THREE.Float32BufferAttribute(attributes.uvs, 2)); + } + }]); + + return imageLayer; +}(_layer["default"]); + +exports["default"] = imageLayer; \ No newline at end of file diff --git a/lib/layer/image_layer.js b/lib/layer/image_layer.js new file mode 100644 index 0000000000..6b55d20bd9 --- /dev/null +++ b/lib/layer/image_layer.js @@ -0,0 +1,91 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _layer = _interopRequireDefault(require("../core/layer")); + +var THREE = _interopRequireWildcard(require("../core/three")); + +var _image = _interopRequireDefault(require("../geom/buffer/image")); + +var _imageMaterial = _interopRequireDefault(require("../geom/material/imageMaterial")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var imageLayer = +/*#__PURE__*/ +function (_Layer) { + _inherits(imageLayer, _Layer); + + function imageLayer() { + _classCallCheck(this, imageLayer); + + return _possibleConstructorReturn(this, _getPrototypeOf(imageLayer).apply(this, arguments)); + } + + _createClass(imageLayer, [{ + key: "draw", + value: function draw() { + var _this = this; + + this.type = 'image'; + var source = this.layerSource; + + var _this$get = this.get('styleOptions'), + opacity = _this$get.opacity; // 加载 完成事件 + + + source.originData.images.then(function (images) { + _this.layerData[0].images = images; + var buffer = new _image["default"]({ + layerData: _this.layerData + }); + + _this.initGeometry(buffer.attributes); + + var material = new _imageMaterial["default"]({ + u_texture: buffer.texture, + u_opacity: opacity + }); + var imageMesh = new THREE.Mesh(_this.geometry, material); + + _this.add(imageMesh); + }); + return this; + } + }, { + key: "initGeometry", + value: function initGeometry(attributes) { + this.geometry = new THREE.BufferGeometry(); + this.geometry.addAttribute('position', new THREE.Float32BufferAttribute(attributes.vertices, 3)); + this.geometry.addAttribute('uv', new THREE.Float32BufferAttribute(attributes.uvs, 2)); + } + }]); + + return imageLayer; +}(_layer["default"]); + +exports["default"] = imageLayer; \ No newline at end of file diff --git a/lib/layer/index.js b/lib/layer/index.js new file mode 100644 index 0000000000..c9a45b3068 --- /dev/null +++ b/lib/layer/index.js @@ -0,0 +1,55 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "registerLayer", { + enumerable: true, + get: function get() { + return _factory.registerLayer; + } +}); +Object.defineProperty(exports, "LAYER_MAP", { + enumerable: true, + get: function get() { + return _factory.LAYER_MAP; + } +}); +Object.defineProperty(exports, "getLayer", { + enumerable: true, + get: function get() { + return _factory.getLayer; + } +}); + +var _factory = require("./factory"); + +var _polygon_layer = _interopRequireDefault(require("./polygon_layer")); + +var _point_layer = _interopRequireDefault(require("./point_layer")); + +var _line_layer = _interopRequireDefault(require("./line_layer")); + +var _image_layer = _interopRequireDefault(require("./image_layer")); + +var _raster_layer = _interopRequireDefault(require("./raster_layer")); + +var _heatmap_layer = _interopRequireDefault(require("./heatmap_layer")); + +var _tile_layer = _interopRequireDefault(require("./tile/tile_layer")); + +var _image_tile_layer = _interopRequireDefault(require("./tile/image_tile_layer")); + +var _vector_tile_layer = _interopRequireDefault(require("./tile/vector_tile_layer")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +(0, _factory.registerLayer)('PolygonLayer', _polygon_layer["default"]); +(0, _factory.registerLayer)('PointLayer', _point_layer["default"]); +(0, _factory.registerLayer)('LineLayer', _line_layer["default"]); +(0, _factory.registerLayer)('ImageLayer', _image_layer["default"]); +(0, _factory.registerLayer)('RasterLayer', _raster_layer["default"]); +(0, _factory.registerLayer)('HeatmapLayer', _heatmap_layer["default"]); +(0, _factory.registerLayer)('TileLayer', _tile_layer["default"]); +(0, _factory.registerLayer)('ImageTileLayer', _image_tile_layer["default"]); +(0, _factory.registerLayer)('VectorTileLayer', _vector_tile_layer["default"]); \ No newline at end of file diff --git a/lib/layer/lineLayer.js b/lib/layer/lineLayer.js new file mode 100644 index 0000000000..21abaf6810 --- /dev/null +++ b/lib/layer/lineLayer.js @@ -0,0 +1,70 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _layer = _interopRequireDefault(require("../core/layer")); + +var _render = require("./render/"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var LineLayer = +/*#__PURE__*/ +function (_Layer) { + _inherits(LineLayer, _Layer); + + function LineLayer() { + _classCallCheck(this, LineLayer); + + return _possibleConstructorReturn(this, _getPrototypeOf(LineLayer).apply(this, arguments)); + } + + _createClass(LineLayer, [{ + key: "shape", + value: function shape(type) { + this.shapeType = type; + return this; + } + }, { + key: "preRender", + value: function preRender() { + if (this.animateDuration > 0 && this.animateDuration < this.scene._engine.clock.getElapsedTime()) { + this.layerMesh.material.setDefinesvalue('ANIMATE', false); + this.emit('animateEnd'); + this.scene.stopAnimate(); + this.animateDuration = Infinity; + } + } + }, { + key: "draw", + value: function draw() { + this.type = 'line'; + this.add((0, _render.getRender)('line', this.shapeType || 'line')(this.layerData, this, this.layerSource)); + } + }]); + + return LineLayer; +}(_layer["default"]); + +exports["default"] = LineLayer; \ No newline at end of file diff --git a/lib/layer/line_layer.js b/lib/layer/line_layer.js new file mode 100644 index 0000000000..88dd75c8b8 --- /dev/null +++ b/lib/layer/line_layer.js @@ -0,0 +1,71 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _layer = _interopRequireDefault(require("../core/layer")); + +var _render = require("./render"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var LineLayer = +/*#__PURE__*/ +function (_Layer) { + _inherits(LineLayer, _Layer); + + function LineLayer() { + _classCallCheck(this, LineLayer); + + return _possibleConstructorReturn(this, _getPrototypeOf(LineLayer).apply(this, arguments)); + } + + _createClass(LineLayer, [{ + key: "shape", + value: function shape(type) { + this.shapeType = type; + return this; + } + }, { + key: "preRender", + value: function preRender() { + if (this.animateDuration > 0 && this.animateDuration < this.scene._engine.clock.getElapsedTime()) { + this.layerMesh.material.setDefinesvalue('ANIMATE', false); + this.emit('animateEnd'); + this.scene.stopAnimate(); + this.animateDuration = Infinity; + } + } + }, { + key: "draw", + value: function draw() { + this.type = 'line'; + this.add((0, _render.getRender)('line', this.shapeType || 'line')(this.layerData, this)); + } + }]); + + return LineLayer; +}(_layer["default"]); + +exports["default"] = LineLayer; +LineLayer.type = 'line'; \ No newline at end of file diff --git a/lib/layer/pointLayer.js b/lib/layer/pointLayer.js new file mode 100644 index 0000000000..63ee1607e7 --- /dev/null +++ b/lib/layer/pointLayer.js @@ -0,0 +1,143 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _layer = _interopRequireDefault(require("../core/layer")); + +var _global = _interopRequireDefault(require("../global")); + +var _render = require("./render/"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var pointShape = _global["default"].pointShape; +/** + * point shape 2d circle, traingle text,image + * shape 3d cube,column, sphere + * shape Model ,自定义 + * image + */ + +var PointLayer = +/*#__PURE__*/ +function (_Layer) { + _inherits(PointLayer, _Layer); + + function PointLayer() { + _classCallCheck(this, PointLayer); + + return _possibleConstructorReturn(this, _getPrototypeOf(PointLayer).apply(this, arguments)); + } + + _createClass(PointLayer, [{ + key: "draw", + value: function draw() { + this.type = 'point'; + this.shapeType = this._getShape(); + var mesh = (0, _render.getRender)(this.type, this.shapeType)(this.layerData, this, this.layerSource); + this.add(mesh); + } + }, { + key: "_getShape", + value: function _getShape() { + var shape = null; + + if (!this.layerData[0].hasOwnProperty('shape')) { + return 'normal'; + } + + for (var i = 0; i < this.layerData.length; i++) { + shape = this.layerData[i].shape; + + if (shape !== undefined) { + break; + } + } // 2D circle 特殊处理 + + + if (pointShape['2d'].indexOf(shape) !== -1) { + return 'circle'; + } else if (pointShape['3d'].indexOf(shape) !== -1) { + return 'fill'; + } else if (this.scene.image.imagesIds.indexOf(shape) !== -1) { + return 'image'; + } + + return 'text'; + } + }, { + key: "zoomchange", + value: function zoomchange(ev) { + var _this = this; + + _get(_getPrototypeOf(PointLayer.prototype), "zoomchange", this).call(this, ev); + + requestAnimationFrame(function () { + _this._updateData(); + }); + } + }, { + key: "dragend", + value: function dragend(ev) { + var _this2 = this; + + _get(_getPrototypeOf(PointLayer.prototype), "dragend", this).call(this, ev); + + requestAnimationFrame(function () { + _this2._updateData(); + }); + } + }, { + key: "_updateData", + value: function _updateData() { + if (this.layerSource.get('isCluster')) { + var bounds = this.scene.getBounds().toBounds(); + var SW = bounds.getSouthWest(); + var NE = bounds.getNorthEast(); + var zoom = this.scene.getZoom(); + var step = Math.max(NE.lng - SW.lng, NE.lat - SW.lat) / 2; + var bbox = [SW.lng, SW.lat, NE.lng, NE.lat]; // const bbox = [ SW.lng - step, SW.lat - step, NE.lng + step, NE.lat + step ]; + + var cfg = this.layerSource.get('cluster'); + var preBox = cfg.bbox; + var preZoom = cfg.zoom; + + if (!(preBox && preBox[0] < bbox[0] && preBox[1] < bbox[1] && preBox[2] > bbox[2] && preBox[3] < bbox[3] && // 当前范围在范围内 + Math.abs(zoom - preZoom) < 0.5)) { + var newbbox = [SW.lng - step, SW.lat - step, NE.lng + step, NE.lat + step]; + this.layerSource.updateCusterData(Math.floor(zoom - 1), newbbox); + this.repaint(); + } + } + } + }]); + + return PointLayer; +}(_layer["default"]); + +exports["default"] = PointLayer; \ No newline at end of file diff --git a/lib/layer/point_layer.js b/lib/layer/point_layer.js new file mode 100644 index 0000000000..e47377faf6 --- /dev/null +++ b/lib/layer/point_layer.js @@ -0,0 +1,150 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _layer = _interopRequireDefault(require("../core/layer")); + +var _global = _interopRequireDefault(require("../global")); + +var _render = require("./render"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var pointShape = _global["default"].pointShape; +/** + * point shape 2d circle, traingle text,image + * shape 3d cube,column, sphere + * shape Model ,自定义 + * image + */ + +var PointLayer = +/*#__PURE__*/ +function (_Layer) { + _inherits(PointLayer, _Layer); + + function PointLayer(scene, cfg) { + var _this; + + _classCallCheck(this, PointLayer); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(PointLayer).call(this, scene, cfg)); + + _this.set('type', 'point'); + + return _this; + } + + _createClass(PointLayer, [{ + key: "draw", + value: function draw() { + this.type = 'point'; + this.shapeType = this._getShape(); + var mesh = (0, _render.getRender)(this.type, this.shapeType)(this.layerData, this); + this.add(mesh); + } + }, { + key: "_getShape", + value: function _getShape() { + var shape = null; + + if (!this.layerData[0].hasOwnProperty('shape')) { + return 'normal'; + } + + for (var i = 0; i < this.layerData.length; i++) { + shape = this.layerData[i].shape; + + if (shape !== undefined) { + break; + } + } // 2D circle 特殊处理 + + + if (pointShape['2d'].indexOf(shape) !== -1) { + return 'fill'; + } else if (pointShape['3d'].indexOf(shape) !== -1) { + return 'extrude'; + } else if (this.scene.image.imagesIds.indexOf(shape) !== -1) { + return 'image'; + } + + return 'text'; + } + }, { + key: "zoomchange", + value: function zoomchange(ev) { + var _this2 = this; + + _get(_getPrototypeOf(PointLayer.prototype), "zoomchange", this).call(this, ev); + + requestAnimationFrame(function () { + _this2._updateData(); + }); + } + }, { + key: "dragend", + value: function dragend(ev) { + var _this3 = this; + + _get(_getPrototypeOf(PointLayer.prototype), "dragend", this).call(this, ev); + + requestAnimationFrame(function () { + _this3._updateData(); + }); + } + }, { + key: "_updateData", + value: function _updateData() { + if (this.layerSource.get('isCluster')) { + var bounds = this.scene.getBounds().toBounds(); + var SW = bounds.getSouthWest(); + var NE = bounds.getNorthEast(); + var zoom = this.scene.getZoom(); + var step = Math.max(NE.lng - SW.lng, NE.lat - SW.lat) / 2; + var bbox = [SW.lng, SW.lat, NE.lng, NE.lat]; // const bbox = [ SW.lng - step, SW.lat - step, NE.lng + step, NE.lat + step ]; + + var cfg = this.layerSource.get('cluster'); + var preBox = cfg.bbox; + var preZoom = cfg.zoom; + + if (!(preBox && preBox[0] < bbox[0] && preBox[1] < bbox[1] && preBox[2] > bbox[2] && preBox[3] < bbox[3] && // 当前范围在范围内 + Math.abs(zoom - preZoom) < 0.5)) { + var newbbox = [SW.lng - step, SW.lat - step, NE.lng + step, NE.lat + step]; + this.layerSource.updateCusterData(Math.floor(zoom - 1), newbbox); + this.repaint(); + } + } + } + }]); + + return PointLayer; +}(_layer["default"]); + +exports["default"] = PointLayer; +PointLayer.type = 'point'; \ No newline at end of file diff --git a/lib/layer/polygonLayer.js b/lib/layer/polygonLayer.js new file mode 100644 index 0000000000..a79a8d24a2 --- /dev/null +++ b/lib/layer/polygonLayer.js @@ -0,0 +1,72 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _layer = _interopRequireDefault(require("../core/layer")); + +var _render = require("./render/"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var PolygonLayer = +/*#__PURE__*/ +function (_Layer) { + _inherits(PolygonLayer, _Layer); + + function PolygonLayer() { + _classCallCheck(this, PolygonLayer); + + return _possibleConstructorReturn(this, _getPrototypeOf(PolygonLayer).apply(this, arguments)); + } + + _createClass(PolygonLayer, [{ + key: "shape", + value: function shape(type) { + this.shape = type; + return this; + } + }, { + key: "draw", + value: function draw() { + this.init(); + this.type = 'polygon'; + var animateOptions = this.get('animateOptions'); + + if (animateOptions.enable) { + this.shape = 'animate'; + } + + this.add((0, _render.getRender)(this.type, this.shape)(this.layerData, this)); + } + }, { + key: "update", + value: function update() { + this.updateFilter(this.layerMesh); + } + }]); + + return PolygonLayer; +}(_layer["default"]); + +exports["default"] = PolygonLayer; \ No newline at end of file diff --git a/lib/layer/polygon_layer.js b/lib/layer/polygon_layer.js new file mode 100644 index 0000000000..03b891e6a9 --- /dev/null +++ b/lib/layer/polygon_layer.js @@ -0,0 +1,81 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _layer = _interopRequireDefault(require("../core/layer")); + +var _render = require("./render"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var PolygonLayer = +/*#__PURE__*/ +function (_Layer) { + _inherits(PolygonLayer, _Layer); + + function PolygonLayer(scene, cfg) { + var _this; + + _classCallCheck(this, PolygonLayer); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(PolygonLayer).call(this, scene, cfg)); + + _this.set('type', 'polygon'); + + return _this; + } + + _createClass(PolygonLayer, [{ + key: "shape", + value: function shape(type) { + this.shape = type; + this.set('shape', type); + this.set('shapeType', 'polygon'); + return this; + } + }, { + key: "draw", + value: function draw() { + // this.init(); + this.type = 'polygon'; + var animateOptions = this.get('animateOptions'); + + if (animateOptions.enable) { + this.shape = 'animate'; + } + + this.add((0, _render.getRender)(this.type, this.shape)(this.layerData, this)); + } + }, { + key: "update", + value: function update() { + this.updateFilter(this.layerMesh); + } + }]); + + return PolygonLayer; +}(_layer["default"]); + +exports["default"] = PolygonLayer; +PolygonLayer.type = 'polygon'; \ No newline at end of file diff --git a/lib/layer/rasterLayer.js b/lib/layer/rasterLayer.js new file mode 100644 index 0000000000..19264f45b5 --- /dev/null +++ b/lib/layer/rasterLayer.js @@ -0,0 +1,111 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _layer = _interopRequireDefault(require("../core/layer")); + +var THREE = _interopRequireWildcard(require("../core/three")); + +var _rasterMaterial = _interopRequireDefault(require("../geom/material/rasterMaterial")); + +var _raster = require("../geom/buffer/raster"); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var RasterLayer = +/*#__PURE__*/ +function (_Layer) { + _inherits(RasterLayer, _Layer); + + function RasterLayer() { + _classCallCheck(this, RasterLayer); + + return _possibleConstructorReturn(this, _getPrototypeOf(RasterLayer).apply(this, arguments)); + } + + _createClass(RasterLayer, [{ + key: "draw", + value: function draw() { + this.type = 'raster'; + var source = this.layerSource; // 加载 完成事件 + + var styleOptions = this.get('styleOptions'); + var buffer = new _raster.RasterBuffer({ + layerData: source.data, + rampColors: styleOptions.rampColors + }); + this.initGeometry(buffer.attributes); + var rasterConfig = source.data.dataArray[0]; + var material = new _rasterMaterial["default"]({ + u_texture: buffer.bufferStruct.u_raster, + u_colorTexture: buffer.bufferStruct.u_colorTexture, + u_opacity: 1.0, + u_extent: buffer.bufferStruct.u_extent, + u_min: rasterConfig.min, + u_max: rasterConfig.max, + u_dimension: buffer.attributes.dimension + }); + var rasterMesh = new THREE.Mesh(this.geometry, material); + this.add(rasterMesh); + return this; + } + }, { + key: "animateFunc", + value: function animateFunc() { + var _this = this; + + var animateOptions = this.get('animateOptions'); + this.material.setValue('u_bands', this.animateData.index % 3); + this.material.setValue('u_texture', this.animateData.rasters[Math.floor(this.animateData.index / 3) % 8]); + this.animateData.index++; + + if (animateOptions) { + animateOptions(this.animateData.index); + } + + setTimeout(function () { + _this.animateId = requestAnimationFrame(_this.animateFunc.bind(_this)); + }, 500); + } + }, { + key: "cancelAnimate", + value: function cancelAnimate() { + window.cancelAnimationFrame(this.animateId); + } + }, { + key: "initGeometry", + value: function initGeometry(attributes) { + this.geometry = new THREE.BufferGeometry(); + this.geometry.setIndex(attributes.indices); + this.geometry.addAttribute('position', new THREE.Float32BufferAttribute(attributes.vertices, 3)); + this.geometry.addAttribute('uv', new THREE.Float32BufferAttribute(attributes.uvs, 2)); + } + }]); + + return RasterLayer; +}(_layer["default"]); + +exports["default"] = RasterLayer; \ No newline at end of file diff --git a/lib/layer/raster_layer.js b/lib/layer/raster_layer.js new file mode 100644 index 0000000000..9dfb85170b --- /dev/null +++ b/lib/layer/raster_layer.js @@ -0,0 +1,111 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _layer = _interopRequireDefault(require("../core/layer")); + +var THREE = _interopRequireWildcard(require("../core/three")); + +var _rasterMaterial = _interopRequireDefault(require("../geom/material/rasterMaterial")); + +var _raster = require("../geom/buffer/raster"); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var RasterLayer = +/*#__PURE__*/ +function (_Layer) { + _inherits(RasterLayer, _Layer); + + function RasterLayer() { + _classCallCheck(this, RasterLayer); + + return _possibleConstructorReturn(this, _getPrototypeOf(RasterLayer).apply(this, arguments)); + } + + _createClass(RasterLayer, [{ + key: "draw", + value: function draw() { + this.type = 'raster'; + var source = this.layerSource; // 加载 完成事件 + + var styleOptions = this.get('styleOptions'); + var buffer = new _raster.RasterBuffer({ + layerData: source.data, + rampColors: styleOptions.rampColors + }); + this.initGeometry(buffer.attributes); + var rasterConfig = source.data.dataArray[0]; + var material = new _rasterMaterial["default"]({ + u_texture: buffer.u_raster, + u_colorTexture: buffer.u_colorTexture, + u_opacity: 1.0, + u_extent: buffer.u_extent, + u_min: rasterConfig.min, + u_max: rasterConfig.max, + u_dimension: buffer.attributes.dimension + }); + var rasterMesh = new THREE.Mesh(this.geometry, material); + this.add(rasterMesh); + return this; + } + }, { + key: "animateFunc", + value: function animateFunc() { + var _this = this; + + var animateOptions = this.get('animateOptions'); + this.material.setValue('u_bands', this.animateData.index % 3); + this.material.setValue('u_texture', this.animateData.rasters[Math.floor(this.animateData.index / 3) % 8]); + this.animateData.index++; + + if (animateOptions) { + animateOptions(this.animateData.index); + } + + setTimeout(function () { + _this.animateId = requestAnimationFrame(_this.animateFunc.bind(_this)); + }, 500); + } + }, { + key: "cancelAnimate", + value: function cancelAnimate() { + window.cancelAnimationFrame(this.animateId); + } + }, { + key: "initGeometry", + value: function initGeometry(attributes) { + this.geometry = new THREE.BufferGeometry(); + this.geometry.setIndex(attributes.indices); + this.geometry.addAttribute('position', new THREE.Float32BufferAttribute(attributes.vertices, 3)); + this.geometry.addAttribute('uv', new THREE.Float32BufferAttribute(attributes.uvs, 2)); + } + }]); + + return RasterLayer; +}(_layer["default"]); + +exports["default"] = RasterLayer; \ No newline at end of file diff --git a/lib/layer/render/factory.js b/lib/layer/render/factory.js new file mode 100644 index 0000000000..4e464041f1 --- /dev/null +++ b/lib/layer/render/factory.js @@ -0,0 +1,26 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.registerRender = exports.getRender = exports.Render_MAP = void 0; +var Render_MAP = {}; +exports.Render_MAP = Render_MAP; + +var getRender = function getRender(layerType, shapeType) { + return Render_MAP[layerType.toLowerCase()] && Render_MAP[layerType.toLowerCase()][shapeType.toLowerCase()]; +}; + +exports.getRender = getRender; + +var registerRender = function registerRender(layerType, shapeType, render) { + if (getRender(layerType, shapeType)) { + throw new Error("Render shapeType '".concat(shapeType, "' existed.")); + } // 存储到 map 中 + + + if (!Render_MAP[layerType.toLowerCase()]) Render_MAP[layerType.toLowerCase()] = {}; + Render_MAP[layerType.toLowerCase()][shapeType.toLowerCase()] = render; +}; + +exports.registerRender = registerRender; \ No newline at end of file diff --git a/lib/layer/render/heatmap/gird.js b/lib/layer/render/heatmap/gird.js new file mode 100644 index 0000000000..b7c10635b9 --- /dev/null +++ b/lib/layer/render/heatmap/gird.js @@ -0,0 +1,63 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = DrawGrid; + +var THREE = _interopRequireWildcard(require("../../../core/three")); + +var _grid = _interopRequireDefault(require("../../../geom/material/grid")); + +var _buffer = require("../../../geom/buffer/"); + +var _shaderModule = require("../../../util/shaderModule"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function DrawGrid(layerData, layer, source) { + var _layer$get = layer.get('styleOptions'), + opacity = _layer$get.opacity, + coverage = _layer$get.coverage, + lights = _layer$get.lights; + + var activeOption = layer.get('activedOptions'); + var _source$data = source.data, + xOffset = _source$data.xOffset, + yOffset = _source$data.yOffset; // const attributes = new gridBuffer(layerdata); + + var geometryBuffer = (0, _buffer.getBuffer)(layer.type, layer.shapeType); + var buffer = new geometryBuffer({ + layerData: layerData, + shapeType: layer.shapeType + }); + var attributes = buffer.attributes, + indexArray = buffer.indexArray; + var geometry = new THREE.BufferGeometry(); + geometry.setIndex(new THREE.Uint32BufferAttribute(indexArray, 1)); + geometry.addAttribute('position', new THREE.Float32BufferAttribute(attributes.positions, 3)); + geometry.addAttribute('miter', new THREE.Float32BufferAttribute(attributes.miters, 3)); + geometry.addAttribute('a_color', new THREE.Float32BufferAttribute(attributes.colors, 4)); + geometry.addAttribute('pickingId', new THREE.Float32BufferAttribute(attributes.pickingIds, 1)); + geometry.addAttribute('normal', new THREE.Float32BufferAttribute(attributes.normals, 3)); + var material = new _grid["default"](_objectSpread({ + u_opacity: opacity, + u_xOffset: xOffset, + u_yOffset: yOffset, + u_coverage: coverage, + u_activeColor: activeOption.fill + }, (0, _shaderModule.generateLightingUniforms)(lights)), { + SHAPE: false, + LIGHTING: layer.shapeType !== 'square' + }); + var gridMesh = new THREE.Mesh(geometry, material); + return gridMesh; +} \ No newline at end of file diff --git a/lib/layer/render/heatmap/heatmap.js b/lib/layer/render/heatmap/heatmap.js new file mode 100644 index 0000000000..c8ff73da0f --- /dev/null +++ b/lib/layer/render/heatmap/heatmap.js @@ -0,0 +1,97 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = DrawHeatmap; + +var _heatmap = _interopRequireWildcard(require("../../../geom/buffer/heatmap/heatmap")); + +var _heatmapMaterial = require("../../../geom/material/heatmapMaterial"); + +var _renderPass = _interopRequireDefault(require("../../../core/engine/render-pass")); + +var _shaderPass = _interopRequireDefault(require("../../../core/engine/shader-pass")); + +var _effectComposer = _interopRequireDefault(require("../../../core/engine/effect-composer")); + +var THREE = _interopRequireWildcard(require("../../../core/three")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +// import Renderpass from '../../../core/engine/renderpass.bak'; +function DrawHeatmap(layerdata, layer) { + var colors = layer.get('styleOptions').rampColors; + layer.rampColors = (0, _heatmap.createColorRamp)(colors); + var heatmap = new heatmapPass(layerdata, layer); + var copy = new copyPass(layer); + copy.renderToScreen = true; + var composer = new _effectComposer["default"](layer.scene._engine._renderer, layer.scene._container); + composer.addPass(heatmap); + composer.addPass(copy); + + layer.scene._engine.update(); + + layer._updateStyle = function (style) { + if (style.rampColors) { + style.rampColors = (0, _heatmap.createColorRamp)(style.rampColors); + } + + var newOption = {}; + + for (var key in style) { + newOption['u_' + key] = style[key]; + } + + heatmap.scene.children[0].material.updateUninform(newOption); + copy.scene.children[0].material.updateUninform(newOption); + }; + + return composer; +} + +function heatmapPass(layerdata, layer) { + var scene = new THREE.Scene(); + var style = layer.get('styleOptions'); + var data = layerdata; + var camera = layer.scene._engine._camera; // get attributes data + + var buffer = new _heatmap["default"]({ + data: data + }); + var attributes = buffer.attributes; // create geometery + + var geometry = new THREE.BufferGeometry(); // geometry.setIndex(attributes.indices); + + geometry.addAttribute('position', new THREE.Float32BufferAttribute(attributes.vertices, 3)); + geometry.addAttribute('a_dir', new THREE.Float32BufferAttribute(attributes.dirs, 2)); + geometry.addAttribute('a_weight', new THREE.Float32BufferAttribute(attributes.weights, 1)); + var material = new _heatmapMaterial.HeatmapIntensityMaterial({ + u_intensity: style.intensity, + u_radius: style.radius, + u_zoom: layer.scene.getZoom() + }, {}); + var mesh = new THREE.Mesh(geometry, material); + scene.add(mesh); + + scene.onBeforeRender = function () { + // 每次渲染前改变状态 + var zoom = layer.scene.getZoom(); + mesh.material.setUniformsValue('u_zoom', zoom); + }; + + var pass = new _renderPass["default"](scene, camera); + return pass; +} + +function copyPass(layer) { + var style = layer.get('styleOptions'); + var material = new _heatmapMaterial.HeatmapColorizeMaterial({ + u_rampColors: layer.rampColors, + u_opacity: style.opacity || 1.0 + }, {}); + var copyPass = new _shaderPass["default"](material, 'u_texture'); + return copyPass; +} \ No newline at end of file diff --git a/lib/layer/render/heatmap/hexagon.js b/lib/layer/render/heatmap/hexagon.js new file mode 100644 index 0000000000..05de68ec9c --- /dev/null +++ b/lib/layer/render/heatmap/hexagon.js @@ -0,0 +1,69 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = DrawHexagon; + +var THREE = _interopRequireWildcard(require("../../../core/three")); + +var _hexagon = _interopRequireDefault(require("../../../geom/material/hexagon")); + +var _buffer = require("../../../geom/buffer/"); + +var _shaderModule = require("../../../util/shaderModule"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function DrawHexagon(layerData, layer, source) { + var style = layer.get('styleOptions'); + + var _layer$get = layer.get('activedOptions'), + fill = _layer$get.fill; + + var radius = source.data.radius; + var opacity = style.opacity, + _style$angle = style.angle, + angle = _style$angle === void 0 ? 0 : _style$angle, + coverage = style.coverage, + lights = style.lights; + var geometryBuffer = (0, _buffer.getBuffer)(layer.type, 'shape'); + var buffer = new geometryBuffer({ + layerData: layerData, + shapeType: layer.shapeType + }); + var attributes = buffer.attributes, + instanceGeometry = buffer.instanceGeometry; + var instancedGeometry = new THREE.InstancedBufferGeometry(); + instancedGeometry.setIndex(instanceGeometry.indexArray); + instancedGeometry.addAttribute('miter', new THREE.Float32BufferAttribute(instanceGeometry.positions, 3)); + + if (instanceGeometry.normals) { + instancedGeometry.addAttribute('normal', new THREE.Float32BufferAttribute(instanceGeometry.normals, 3)); + } + + instancedGeometry.addAttribute('position', new THREE.InstancedBufferAttribute(new Float32Array(attributes.positions), 3)); + instancedGeometry.addAttribute('a_color', new THREE.InstancedBufferAttribute(new Float32Array(attributes.colors), 4)); + instancedGeometry.addAttribute('pickingId', new THREE.InstancedBufferAttribute(new Float32Array(attributes.pickingIds), 1)); + instancedGeometry.addAttribute('a_size', new THREE.InstancedBufferAttribute(new Float32Array(attributes.sizes), 1)); + var material = new _hexagon["default"](_objectSpread({ + u_opacity: opacity, + u_radius: radius, + u_angle: angle / 180 * Math.PI, + u_coverage: coverage, + u_activeColor: fill + }, (0, _shaderModule.generateLightingUniforms)(lights)), { + SHAPE: false, + LIGHTING: !!instanceGeometry.normals + }); + var hexgonMesh = new THREE.Mesh(instancedGeometry, material); + return hexgonMesh; +} \ No newline at end of file diff --git a/lib/layer/render/image/drawImage.js b/lib/layer/render/image/drawImage.js new file mode 100644 index 0000000000..1125ec207c --- /dev/null +++ b/lib/layer/render/image/drawImage.js @@ -0,0 +1,26 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = DrawImage; + +var THREE = _interopRequireWildcard(require("../../../core/three")); + +var _imageMaterial = _interopRequireDefault(require("../../../geom/material/imageMaterial")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function DrawImage(attributes, style) { + var geometry = new THREE.BufferGeometry(); + geometry.addAttribute('position', new THREE.Float32BufferAttribute(attributes.vertices, 3)); + geometry.addAttribute('uv', new THREE.Float32BufferAttribute(attributes.uvs, 2)); + var opacity = style.opacity; + var material = new _imageMaterial["default"]({ + u_texture: attributes.texture, + u_opacity: opacity + }); + return new THREE.Mesh(geometry, material); +} \ No newline at end of file diff --git a/lib/layer/render/index.js b/lib/layer/render/index.js new file mode 100644 index 0000000000..2f37f1f7a1 --- /dev/null +++ b/lib/layer/render/index.js @@ -0,0 +1,72 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getRender", { + enumerable: true, + get: function get() { + return _factory.getRender; + } +}); + +var _factory = require("./factory"); + +var _drawFill = _interopRequireDefault(require("./polygon/drawFill")); + +var _drawLine = _interopRequireDefault(require("./polygon/drawLine")); + +var _drawAnimate = _interopRequireDefault(require("./polygon/drawAnimate")); + +var _draw_3d_shape = _interopRequireDefault(require("./point/draw_3d_shape")); + +var _drawMeshLine = _interopRequireDefault(require("./line/drawMeshLine")); + +var _drawArc = _interopRequireDefault(require("./line/drawArc")); + +var _drawImage = _interopRequireDefault(require("./point/drawImage")); + +var _drawNormal = _interopRequireDefault(require("./point/drawNormal")); + +var _drawStroke = _interopRequireDefault(require("./point/drawStroke")); + +var _drawText = _interopRequireDefault(require("./point/drawText")); + +var _drawCircle = _interopRequireDefault(require("./point/drawCircle")); + +var _hexagon = _interopRequireDefault(require("./heatmap/hexagon")); + +var _gird = _interopRequireDefault(require("./heatmap/gird")); + +var _heatmap = _interopRequireDefault(require("./heatmap/heatmap")); + +var _drawImage2 = _interopRequireDefault(require("./image/drawImage")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +// polygon +(0, _factory.registerRender)('polygon', 'fill', _drawFill["default"]); +(0, _factory.registerRender)('polygon', 'extrude', _drawFill["default"]); +(0, _factory.registerRender)('polygon', 'line', _drawLine["default"]); +(0, _factory.registerRender)('polygon', 'animate', _drawAnimate["default"]); // line + +(0, _factory.registerRender)('line', 'line', _drawMeshLine["default"]); +(0, _factory.registerRender)('line', 'arc', _drawArc["default"]); +(0, _factory.registerRender)('line', 'greatCircle', _drawArc["default"]); // point +// import DrawPointFill from './point/drawFill'; + +// registerRender('point', 'fill', DrawPointFill); +(0, _factory.registerRender)('point', 'image', _drawImage["default"]); +(0, _factory.registerRender)('point', 'normal', _drawNormal["default"]); +(0, _factory.registerRender)('point', 'stroke', _drawStroke["default"]); +(0, _factory.registerRender)('point', 'text', _drawText["default"]); +(0, _factory.registerRender)('point', 'fill', _drawCircle["default"]); +(0, _factory.registerRender)('point', 'shape', _draw_3d_shape["default"]); +(0, _factory.registerRender)('point', 'extrude', _draw_3d_shape["default"]); // heatmap + +(0, _factory.registerRender)('heatmap', 'square', _gird["default"]); +(0, _factory.registerRender)('heatmap', 'squareColumn', _gird["default"]); +(0, _factory.registerRender)('heatmap', 'heatmap', _heatmap["default"]); +(0, _factory.registerRender)('heatmap', 'shape', _hexagon["default"]); // image + +(0, _factory.registerRender)('image', 'image', _drawImage2["default"]); \ No newline at end of file diff --git a/lib/layer/render/line/drawArc.js b/lib/layer/render/line/drawArc.js new file mode 100644 index 0000000000..f4be321385 --- /dev/null +++ b/lib/layer/render/line/drawArc.js @@ -0,0 +1,48 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = DrawArcLine; + +var THREE = _interopRequireWildcard(require("../../../core/three")); + +var _lineMaterial = require("../../../geom/material/lineMaterial"); + +var _buffer2 = require("../../../geom/buffer/"); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function DrawArcLine(layerData, layer, buffer) { + var style = layer.get('styleOptions'); + var activeOption = layer.get('activedOptions'); + + if (!buffer) { + var geometryBuffer = (0, _buffer2.getBuffer)(layer.type, layer.shapeType); + buffer = new geometryBuffer({ + layerData: layerData, + shapeType: layer.shapeType, + style: style + }); + } + + var _buffer = buffer, + attributes = _buffer.attributes, + indexArray = _buffer.indexArray; + var geometry = new THREE.BufferGeometry(); + geometry.setIndex(new THREE.Uint32BufferAttribute(indexArray, 1)); + geometry.addAttribute('position', new THREE.Float32BufferAttribute(attributes.positions, 3)); + geometry.addAttribute('a_color', new THREE.Float32BufferAttribute(attributes.colors, 4)); + geometry.addAttribute('a_instance', new THREE.Float32BufferAttribute(attributes.instanceArray, 4)); + geometry.addAttribute('a_size', new THREE.Float32BufferAttribute(attributes.sizes, 1)); + var lineMaterial = new _lineMaterial.ArcLineMaterial({ + u_opacity: style.opacity, + u_zoom: layer.scene.getZoom(), + activeColor: activeOption.fill, + shapeType: layer.shapeType + }, { + SHAPE: false + }); + var arcMesh = new THREE.Mesh(geometry, lineMaterial); + return arcMesh; +} \ No newline at end of file diff --git a/lib/layer/render/line/drawDashLine.js b/lib/layer/render/line/drawDashLine.js new file mode 100644 index 0000000000..9a390c31f7 --- /dev/null +++ b/lib/layer/render/line/drawDashLine.js @@ -0,0 +1 @@ +"use strict"; \ No newline at end of file diff --git a/lib/layer/render/line/drawLine.js b/lib/layer/render/line/drawLine.js new file mode 100644 index 0000000000..bceced392c --- /dev/null +++ b/lib/layer/render/line/drawLine.js @@ -0,0 +1,43 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = DrawLine; + +var THREE = _interopRequireWildcard(require("../../../core/three")); + +var _lineMaterial = require("../../../geom/material/lineMaterial"); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function DrawLine(attributes, style) { + var opacity = style.opacity, + zoom = style.zoom, + animate = style.animate, + duration = style.duration, + interval = style.interval, + trailLength = style.trailLength; + var geometry = new THREE.BufferGeometry(); + geometry.setIndex(attributes.indexArray); + geometry.addAttribute('pickingId', new THREE.Float32BufferAttribute(attributes.pickingIds, 1)); + geometry.addAttribute('position', new THREE.Float32BufferAttribute(attributes.positions, 3)); + geometry.addAttribute('a_color', new THREE.Float32BufferAttribute(attributes.colors, 4)); + geometry.addAttribute('a_size', new THREE.Float32BufferAttribute(attributes.sizes, 1)); + geometry.addAttribute('normal', new THREE.Float32BufferAttribute(attributes.normal, 3)); + geometry.addAttribute('a_miter', new THREE.Float32BufferAttribute(attributes.miter, 1)); + geometry.addAttribute('a_distance', new THREE.Float32BufferAttribute(attributes.attrDistance, 1)); + var lineMaterial = new _lineMaterial.MeshLineMaterial({ + u_opacity: opacity, + u_zoom: zoom, + u_duration: duration, + u_interval: interval, + u_trailLength: trailLength, + u_time: 0 + }, { + SHAPE: false, + ANIMATE: animate + }); + var arcMesh = new THREE.Mesh(geometry, lineMaterial); + return arcMesh; +} \ No newline at end of file diff --git a/lib/layer/render/line/drawMeshLine.js b/lib/layer/render/line/drawMeshLine.js new file mode 100644 index 0000000000..e753c1b2c5 --- /dev/null +++ b/lib/layer/render/line/drawMeshLine.js @@ -0,0 +1,89 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = DrawLine; + +var THREE = _interopRequireWildcard(require("../../../core/three")); + +var _lineMaterial = require("../../../geom/material/lineMaterial"); + +var _buffer2 = require("../../../geom/buffer/"); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function DrawLine(layerData, layer, buffer) { + var style = layer.get('styleOptions'); + var animateOptions = layer.get('animateOptions'); + var activeOption = layer.get('activedOptions'); // const pattern = style.pattern; + // const texture = layer.scene.image.singleImages[pattern]; + + var hasPattern = layerData.some(function (layer) { + return layer.pattern; + }); + + if (!buffer) { + var geometryBuffer = (0, _buffer2.getBuffer)(layer.type, layer.shapeType); + buffer = new geometryBuffer({ + layerData: layerData, + shapeType: 'line', + style: style, + imagePos: layer.scene.image.imagePos + }); + } + + var _buffer = buffer, + attributes = _buffer.attributes, + indexArray = _buffer.indexArray; + var geometry = new THREE.BufferGeometry(); + geometry.setIndex(new THREE.Uint32BufferAttribute(indexArray, 1)); + geometry.addAttribute('pickingId', new THREE.Float32BufferAttribute(attributes.pickingIds, 1)); + geometry.addAttribute('position', new THREE.Float32BufferAttribute(attributes.positions, 3)); + geometry.addAttribute('a_color', new THREE.Float32BufferAttribute(attributes.colors, 4)); + geometry.addAttribute('a_size', new THREE.Float32BufferAttribute(attributes.sizes, 1)); + geometry.addAttribute('normal', new THREE.Float32BufferAttribute(attributes.normals, 3)); + geometry.addAttribute('a_miter', new THREE.Float32BufferAttribute(attributes.miters, 1)); + geometry.addAttribute('a_distance', new THREE.Float32BufferAttribute(attributes.attrDistance, 1)); + geometry.addAttribute('a_dash_array', new THREE.Float32BufferAttribute(attributes.dashArray, 1)); + geometry.addAttribute('a_texture_coord', new THREE.Float32BufferAttribute(attributes.patterns, 2)); + geometry.addAttribute('a_total_distance', new THREE.Float32BufferAttribute(attributes.totalDistances, 1)); + var lineMaterial = new _lineMaterial.MeshLineMaterial({ + u_opacity: style.opacity, + u_zoom: layer.scene.getZoom(), + u_time: 0, + u_dash_offset: style.dashOffset, + u_dash_ratio: style.dashRatio, + activeColor: activeOption.fill, + u_pattern_spacing: style.patternSpacing || 0, + u_texture: hasPattern ? layer.scene.image.texture : null + }, { + SHAPE: false, + ANIMATE: false, + DASHLINE: style.lineType === 'dash', + TEXTURE: hasPattern + }); + lineMaterial.setBending(style.blending); + var lineMesh = new THREE.Mesh(geometry, lineMaterial); + + if (animateOptions.enable) { + layer.scene.startAnimate(); + var _animateOptions$durat = animateOptions.duration, + duration = _animateOptions$durat === void 0 ? 2 : _animateOptions$durat, + _animateOptions$inter = animateOptions.interval, + interval = _animateOptions$inter === void 0 ? 0.5 : _animateOptions$inter, + _animateOptions$trail = animateOptions.trailLength, + trailLength = _animateOptions$trail === void 0 ? 0.5 : _animateOptions$trail, + _animateOptions$repea = animateOptions.repeat, + repeat = _animateOptions$repea === void 0 ? Infinity : _animateOptions$repea; + layer.animateDuration = layer.scene._engine.clock.getElapsedTime() + duration * repeat; + lineMaterial.updateUninform({ + u_duration: duration, + u_interval: interval, + u_trailLength: trailLength + }); + lineMaterial.setDefinesvalue('ANIMATE', true); + } + + return lineMesh; +} \ No newline at end of file diff --git a/lib/layer/render/point/drawCircle.js b/lib/layer/render/point/drawCircle.js new file mode 100644 index 0000000000..f7758f2e43 --- /dev/null +++ b/lib/layer/render/point/drawCircle.js @@ -0,0 +1,63 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = drawCircle; + +var THREE = _interopRequireWildcard(require("../../../core/three")); + +var _circleMaterial = _interopRequireDefault(require("../../../geom/material/circleMaterial")); + +var _buffer2 = require("../../../geom/buffer/"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +/** + * 绘制 SDF,不仅是圆形 + * 手动构建点阵坐标系,便于实现描边、反走样效果 + */ +function drawCircle(layerData, layer, buffer) { + var style = layer.get('styleOptions'); + var activeOption = layer.get('activedOptions'); + + if (!buffer) { + var geometryBuffer = (0, _buffer2.getBuffer)(layer.type, layer.shapeType); + buffer = new geometryBuffer({ + layerData: layerData + }); + } // const { aPosition, aPackedData } = buffer.attributes; + + + var _buffer = buffer, + attributes = _buffer.attributes, + indexArray = _buffer.indexArray; + var geometry = new THREE.BufferGeometry(); + + if (buffer.indexArray) { + geometry.setIndex(new THREE.Uint32BufferAttribute(indexArray, 1)); + } // geometry.addAttribute('position', new THREE.Float32BufferAttribute(aPosition, 3)); + + + geometry.addAttribute('position', new THREE.Float32BufferAttribute(attributes.positions, 3)); + geometry.addAttribute('a_color', new THREE.Float32BufferAttribute(attributes.colors, 4)); + geometry.addAttribute('pickingId', new THREE.Float32BufferAttribute(attributes.pickingIds, 1)); + geometry.addAttribute('miter', new THREE.Float32BufferAttribute(attributes.miters, 2)); + geometry.addAttribute('a_size', new THREE.Float32BufferAttribute(attributes.sizes, 1)); + geometry.addAttribute('a_shape', new THREE.Float32BufferAttribute(attributes.shapes, 1)); // geometry.addAttribute('a_packed_data', new THREE.Float32BufferAttribute(aPackedData, 4)); + + var material = new _circleMaterial["default"]({ + u_opacity: style.opacity, + u_activeColor: activeOption.fill, + u_zoom: layer.scene.getZoom(), + u_stroke_color: style.stroke, + u_stroke_width: style.strokeWidth, + u_stroke_opacity: style.strokeOpacity + }); + material.depthTest = false; + material.setBending(style.blending); + var fillMesh = new THREE.Mesh(geometry, material); + return fillMesh; +} \ No newline at end of file diff --git a/lib/layer/render/point/drawFill.js b/lib/layer/render/point/drawFill.js new file mode 100644 index 0000000000..b0011b649c --- /dev/null +++ b/lib/layer/render/point/drawFill.js @@ -0,0 +1,60 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = DrawFill; + +var THREE = _interopRequireWildcard(require("../../../core/three")); + +var PointBuffer = _interopRequireWildcard(require("../../../geom/buffer/point/index")); + +var _drawStroke = _interopRequireDefault(require("./drawStroke")); + +var _polygonMaterial = _interopRequireDefault(require("../../../geom/material/polygonMaterial")); + +var _shaderModule = require("../../../util/shaderModule"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function DrawFill(layerData, layer) { + var style = layer.get('styleOptions'); + var activeOption = layer.get('activedOptions'); + var attributes = PointBuffer.FillBuffer(layerData, style); + var geometry = new THREE.BufferGeometry(); + geometry.addAttribute('position', new THREE.Float32BufferAttribute(attributes.vertices, 3)); + geometry.addAttribute('a_color', new THREE.Float32BufferAttribute(attributes.colors, 4)); + geometry.addAttribute('pickingId', new THREE.Float32BufferAttribute(attributes.pickingIds, 1)); + geometry.addAttribute('normal', new THREE.Float32BufferAttribute(attributes.normals, 3)); + geometry.addAttribute('a_shape', new THREE.Float32BufferAttribute(attributes.shapePositions, 3)); + geometry.addAttribute('a_size', new THREE.Float32BufferAttribute(attributes.a_size, 3)); + var material = new _polygonMaterial["default"](_objectSpread({ + u_opacity: style.opacity, + u_activeColor: activeOption.fill, + u_zoom: layer.scene.getZoom() + }, (0, _shaderModule.generateLightingUniforms)(style.lights)), { + SHAPE: true, + LIGHTING: true + }); + material.setDefinesvalue('SHAPE', true); + material.depthTest = false; + material.setBending(style.blending); + var fillMesh = new THREE.Mesh(geometry, material); + + if (style.stroke !== 'none') { + // 是否绘制边界 + var meshStroke = (0, _drawStroke["default"])(layerData, layer); + fillMesh.add(meshStroke); + } // const fillMesh = new THREE.Mesh(instancedGeometry, material); + + + return fillMesh; +} \ No newline at end of file diff --git a/lib/layer/render/point/drawImage.js b/lib/layer/render/point/drawImage.js new file mode 100644 index 0000000000..4f58cfb26b --- /dev/null +++ b/lib/layer/render/point/drawImage.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = DrawImage; + +var THREE = _interopRequireWildcard(require("../../../core/three")); + +var PointBuffer = _interopRequireWildcard(require("../../../geom/buffer/point/index")); + +var _pointMaterial = _interopRequireDefault(require("../../../geom/material/pointMaterial")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function DrawImage(layerData, layer) { + var geometry = new THREE.BufferGeometry(); + var style = layer.get('styleOptions'); + var strokeWidth = style.strokeWidth, + stroke = style.stroke, + opacity = style.opacity; + var texture = layer.scene.image.texture; + var attributes = PointBuffer.ImageBuffer(layerData, { + imagePos: layer.scene.image.imagePos + }); + geometry.addAttribute('position', new THREE.Float32BufferAttribute(attributes.vertices, 3)); + geometry.addAttribute('a_color', new THREE.Float32BufferAttribute(attributes.colors, 4)); + geometry.addAttribute('pickingId', new THREE.Float32BufferAttribute(attributes.pickingIds, 1)); + geometry.addAttribute('uv', new THREE.Float32BufferAttribute(attributes.uv, 2)); + geometry.addAttribute('a_size', new THREE.Float32BufferAttribute(attributes.sizes, 1)); + var material = new _pointMaterial["default"]({ + u_opacity: opacity, + u_strokeWidth: strokeWidth, + u_stroke: stroke, + u_texture: texture + }, { + SHAPE: false, + TEXCOORD_0: true + }); + material.depthTest = false; + var strokeMesh = new THREE.Points(geometry, material); + return strokeMesh; +} \ No newline at end of file diff --git a/lib/layer/render/point/drawNormal.js b/lib/layer/render/point/drawNormal.js new file mode 100644 index 0000000000..0bbd229c3b --- /dev/null +++ b/lib/layer/render/point/drawNormal.js @@ -0,0 +1,37 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = DrawNormal; + +var THREE = _interopRequireWildcard(require("../../../core/three")); + +var PointBuffer = _interopRequireWildcard(require("../../../geom/buffer/point/index")); + +var _normal_point = _interopRequireDefault(require("../../../geom/material/normal_point")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +/** + * 原生点绘制 + */ +function DrawNormal(layerData, layer) { + var geometry = new THREE.BufferGeometry(); + var style = layer.get('styleOptions'); + var activeOption = layer.get('activedOptions'); + var opacity = style.opacity; + var attributes = PointBuffer.NormalBuffer(layerData, style); + geometry.addAttribute('position', new THREE.Float32BufferAttribute(attributes.vertices, 3)); + geometry.addAttribute('a_color', new THREE.Float32BufferAttribute(attributes.colors, 4)); + geometry.addAttribute('pickingId', new THREE.Float32BufferAttribute(attributes.pickingIds, 1)); + geometry.addAttribute('a_size', new THREE.Float32BufferAttribute(attributes.sizes, 1)); + var material = new _normal_point["default"]({ + u_opacity: opacity, + u_activeColor: activeOption.fill + }, {}, style); + var strokeMesh = new THREE.Points(geometry, material); + return strokeMesh; +} \ No newline at end of file diff --git a/lib/layer/render/point/drawStroke.js b/lib/layer/render/point/drawStroke.js new file mode 100644 index 0000000000..13892e4933 --- /dev/null +++ b/lib/layer/render/point/drawStroke.js @@ -0,0 +1,49 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = DrawStroke; + +var _pointLineMaterial = _interopRequireDefault(require("../../../geom/material/pointLineMaterial")); + +var PointBuffer = _interopRequireWildcard(require("../../../geom/buffer/point/index")); + +var THREE = _interopRequireWildcard(require("../../../core/three")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +/** + * @author lzxue + * @email lzx199065@gmail.com + * @create date 2018-11-29 16:35:34 + * @modify date 2018-11-29 16:35:34 + * @desc [description] 绘制图形的边框 +*/ +function DrawStroke(layerData, layer) { + var style = layer.get('styleOptions'); + var activeOption = layer.get('activedOptions'); + var strokeWidth = style.strokeWidth, + stroke = style.stroke, + strokeOpacity = style.strokeOpacity; + var attributes = PointBuffer.StrokeBuffer(layerData, style); + var geometry = new THREE.BufferGeometry(); + geometry.setIndex(attributes.indexArray); + geometry.addAttribute('position', new THREE.Float32BufferAttribute(attributes.positions, 3)); + geometry.addAttribute('a_shape', new THREE.Float32BufferAttribute(attributes.shapes, 3)); + geometry.addAttribute('a_size', new THREE.Float32BufferAttribute(attributes.sizes, 3)); + geometry.addAttribute('normal', new THREE.Float32BufferAttribute(attributes.normal, 3)); + geometry.addAttribute('a_miter', new THREE.Float32BufferAttribute(attributes.miter, 1)); + geometry.addAttribute('pickingId', new THREE.Float32BufferAttribute(attributes.pickingIds, 1)); + geometry.addAttribute('a_color', new THREE.Float32BufferAttribute(attributes.colors, 4)); + var material = new _pointLineMaterial["default"]({ + u_strokeOpacity: strokeOpacity, + u_stroke: stroke, + u_strokeWidth: strokeWidth, + u_activeColor: activeOption.fill + }); + var strokeMesh = new THREE.Mesh(geometry, material); + return strokeMesh; +} \ No newline at end of file diff --git a/lib/layer/render/point/drawText.js b/lib/layer/render/point/drawText.js new file mode 100644 index 0000000000..b6cdc16de1 --- /dev/null +++ b/lib/layer/render/point/drawText.js @@ -0,0 +1,51 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = DrawText; + +var THREE = _interopRequireWildcard(require("../../../core/three")); + +var _textMaterial = _interopRequireDefault(require("../../../geom/material/textMaterial")); + +var _text = _interopRequireDefault(require("../../../geom/buffer/point/text")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function DrawText(layerData, layer) { + var style = layer.get('styleOptions'); + var activeOption = layer.get('activedOptions'); + + var _layer$scene$getSize = layer.scene.getSize(), + width = _layer$scene$getSize.width, + height = _layer$scene$getSize.height; + + var attributes = new _text["default"](layerData, layer.scene.fontAtlasManager); + var geometry = new THREE.BufferGeometry(); + geometry.addAttribute('position', new THREE.Float32BufferAttribute(attributes.originPoints, 3)); + geometry.addAttribute('uv', new THREE.Float32BufferAttribute(attributes.textureElements, 2)); + geometry.addAttribute('a_txtsize', new THREE.Float32BufferAttribute(attributes.textSizes, 2)); + geometry.addAttribute('a_txtOffsets', new THREE.Float32BufferAttribute(attributes.textOffsets, 2)); + geometry.addAttribute('a_color', new THREE.Float32BufferAttribute(attributes.colors, 4)); + geometry.addAttribute('pickingId', new THREE.Float32BufferAttribute(attributes.pickingIds, 1)); + var strokeWidth = style.strokeWidth, + stroke = style.stroke, + opacity = style.opacity; + var material = new _textMaterial["default"]({ + name: layer.layerId, + u_texture: attributes.texture, + u_strokeWidth: strokeWidth, + u_stroke: stroke, + u_textTextureSize: [attributes.fontAtlas.width, attributes.fontAtlas.height], + u_gamma: 1.0 / 12.0 * (1.4142135623730951 / 2.0), + u_buffer: 0.75, + u_opacity: opacity, + u_glSize: [width, height], + u_activeColor: activeOption.fill + }); + var mesh = new THREE.Mesh(geometry, material); + return mesh; +} \ No newline at end of file diff --git a/lib/layer/render/point/draw_3d_shape.js b/lib/layer/render/point/draw_3d_shape.js new file mode 100644 index 0000000000..c2b01bccbe --- /dev/null +++ b/lib/layer/render/point/draw_3d_shape.js @@ -0,0 +1,56 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = Draw3DShape; + +var THREE = _interopRequireWildcard(require("../../../core/three")); + +var _buffer = require("../../../geom/buffer/"); + +var _polygonMaterial = _interopRequireDefault(require("../../../geom/material/polygonMaterial")); + +var _shaderModule = require("../../../util/shaderModule"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function Draw3DShape(layerData, layer) { + var style = layer.get('styleOptions'); + var activeOption = layer.get('activedOptions'); + var geometryBuffer = (0, _buffer.getBuffer)('shape', 'extrude'); + var buffer = new geometryBuffer({ + layerData: layerData, + shapeType: layer.shapeType + }); + var attributes = buffer.attributes, + indexArray = buffer.indexArray; + var geometry = new THREE.BufferGeometry(); + geometry.setIndex(new THREE.Uint32BufferAttribute(indexArray, 1)); + geometry.addAttribute('position', new THREE.Float32BufferAttribute(attributes.positions, 3)); + geometry.addAttribute('a_color', new THREE.Float32BufferAttribute(attributes.colors, 4)); + geometry.addAttribute('pickingId', new THREE.Float32BufferAttribute(attributes.pickingIds, 1)); + geometry.addAttribute('normal', new THREE.Float32BufferAttribute(attributes.normals, 3)); + geometry.addAttribute('a_shape', new THREE.Float32BufferAttribute(attributes.miters, 3)); + geometry.addAttribute('a_size', new THREE.Float32BufferAttribute(attributes.sizes, 3)); + var material = new _polygonMaterial["default"](_objectSpread({ + u_opacity: style.opacity, + u_activeColor: activeOption.fill, + u_zoom: layer.scene.getZoom() + }, (0, _shaderModule.generateLightingUniforms)(style.lights)), { + SHAPE: true, + LIGHTING: true + }); + material.setDefinesvalue('SHAPE', true); + material.setBending(style.blending); + var fillMesh = new THREE.Mesh(geometry, material); + return fillMesh; +} \ No newline at end of file diff --git a/lib/layer/render/point/index.js b/lib/layer/render/point/index.js new file mode 100644 index 0000000000..7d75f1061a --- /dev/null +++ b/lib/layer/render/point/index.js @@ -0,0 +1,39 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "DrawFill", { + enumerable: true, + get: function get() { + return _drawFill["default"]; + } +}); +Object.defineProperty(exports, "DrawImage", { + enumerable: true, + get: function get() { + return _drawImage["default"]; + } +}); +Object.defineProperty(exports, "DrawStroke", { + enumerable: true, + get: function get() { + return _drawStroke["default"]; + } +}); +Object.defineProperty(exports, "DrawNormal", { + enumerable: true, + get: function get() { + return _drawNormal["default"]; + } +}); + +var _drawFill = _interopRequireDefault(require("./drawFill")); + +var _drawImage = _interopRequireDefault(require("./drawImage")); + +var _drawStroke = _interopRequireDefault(require("./drawStroke")); + +var _drawNormal = _interopRequireDefault(require("./drawNormal")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } \ No newline at end of file diff --git a/lib/layer/render/polygon/drawAnimate.js b/lib/layer/render/polygon/drawAnimate.js new file mode 100644 index 0000000000..20323d0460 --- /dev/null +++ b/lib/layer/render/polygon/drawAnimate.js @@ -0,0 +1,86 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = DrawAnimate; + +var THREE = _interopRequireWildcard(require("../../../core/three")); + +var _polygonMaterial = _interopRequireDefault(require("../../../geom/material/polygonMaterial")); + +var _buffer2 = require("../../../geom/buffer/"); + +var _shaderModule = require("../../../util/shaderModule"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function DrawAnimate(layerData, layer, buffer) { + var style = layer.get('styleOptions'); + + var _layer$map$getCameraS = layer.map.getCameraState(), + near = _layer$map$getCameraS.near, + far = _layer$map$getCameraS.far; + + layer.scene.startAnimate(); + + if (!buffer) { + var geometryBuffer = (0, _buffer2.getBuffer)(layer.type, 'extrude'); + buffer = new geometryBuffer({ + layerData: layerData, + uv: true + }); + } + + var _buffer = buffer, + attributes = _buffer.attributes, + indexArray = _buffer.indexArray; + var opacity = style.opacity, + baseColor = style.baseColor, + brightColor = style.brightColor, + windowColor = style.windowColor, + lights = style.lights; + var geometry = new THREE.BufferGeometry(); + + if (indexArray) { + geometry.setIndex(new THREE.Uint32BufferAttribute(indexArray, 1)); + } + + geometry.addAttribute('position', new THREE.Float32BufferAttribute(attributes.positions, 3)); + geometry.addAttribute('a_color', new THREE.Float32BufferAttribute(attributes.colors, 4)); + geometry.addAttribute('pickingId', new THREE.Float32BufferAttribute(attributes.pickingIds, 1)); + geometry.addAttribute('faceUv', new THREE.Float32BufferAttribute(attributes.uv, 2)); // geometry.addAttribute('a_size', new THREE.Float32BufferAttribute(attributes.sizes, 1)); + + geometry.computeVertexNormals(); + var material = new _polygonMaterial["default"](_objectSpread({ + u_opacity: opacity, + u_baseColor: baseColor, + u_brightColor: brightColor, + u_windowColor: windowColor, + u_near: near, + u_far: far + }, (0, _shaderModule.generateLightingUniforms)(lights)), { + SHAPE: false, + LIGHTING: true, + ANIMATE: true + }); + var fillPolygonMesh = new THREE.Mesh(geometry, material); + return fillPolygonMesh; +} + +DrawAnimate.prototype.updateStyle = function (style) { + this.fillPolygonMesh.material.updateUninform({ + u_opacity: style.opacity, + u_baseColor: style.baseColor, + u_brightColor: style.brightColor, + u_windowColor: style.windowColor + }); +}; \ No newline at end of file diff --git a/lib/layer/render/polygon/drawFill.js b/lib/layer/render/polygon/drawFill.js new file mode 100644 index 0000000000..f76d0f5ed4 --- /dev/null +++ b/lib/layer/render/polygon/drawFill.js @@ -0,0 +1,71 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = DrawPolygonFill; + +var THREE = _interopRequireWildcard(require("../../../core/three")); + +var _polygonMaterial = _interopRequireDefault(require("../../../geom/material/polygonMaterial")); + +var _shaderModule = require("../../../util/shaderModule"); + +var _buffer2 = require("../../../geom/buffer/"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function DrawPolygonFill(layerData, layer, buffer) { + var style = layer.get('styleOptions'); + var activeOption = layer.get('activedOptions'); + + var config = _objectSpread({}, style, { + activeColor: activeOption.fill + }); + + var opacity = config.opacity, + activeColor = config.activeColor, + lights = config.lights; + + if (!buffer) { + var geometryBuffer = (0, _buffer2.getBuffer)(layer.type, layer.shape); + buffer = new geometryBuffer({ + layerData: layerData + }); + } + + var _buffer = buffer, + attributes = _buffer.attributes, + indexArray = _buffer.indexArray; + var geometry = new THREE.BufferGeometry(); + + if (indexArray) { + geometry.setIndex(new THREE.Uint32BufferAttribute(indexArray, 1)); + } + + geometry.addAttribute('position', new THREE.Float32BufferAttribute(attributes.positions, 3)); + geometry.addAttribute('a_color', new THREE.Float32BufferAttribute(attributes.colors, 4)); + geometry.addAttribute('pickingId', new THREE.Float32BufferAttribute(attributes.pickingIds, 1)); + geometry.computeVertexNormals(); + var material = new _polygonMaterial["default"](_objectSpread({ + u_opacity: opacity, + u_activeColor: activeColor + }, (0, _shaderModule.generateLightingUniforms)(lights)), { + SHAPE: false, + LIGHTING: true + }); + var fillPolygonMesh = new THREE.Mesh(geometry, material); + delete attributes.vertices; + delete attributes.colors; + delete attributes.pickingIds; + delete attributes.normals; + return fillPolygonMesh; +} \ No newline at end of file diff --git a/lib/layer/render/polygon/drawLine.js b/lib/layer/render/polygon/drawLine.js new file mode 100644 index 0000000000..d2b7d64fe6 --- /dev/null +++ b/lib/layer/render/polygon/drawLine.js @@ -0,0 +1,58 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = DrawPolygonLine; + +var THREE = _interopRequireWildcard(require("../../../core/three")); + +var _buffer2 = require("../../../geom/buffer/"); + +var _lineMaterial = require("../../../geom/material/lineMaterial"); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function DrawPolygonLine(layerData, layer, buffer) { + var style = layer.get('styleOptions'); + var activeOption = layer.get('activedOptions'); + + var config = _objectSpread({}, style, { + activeColor: activeOption.fill + }); + + var opacity = config.opacity; + + if (!buffer) { + var geometryBuffer = (0, _buffer2.getBuffer)(layer.type, layer.shape); + buffer = new geometryBuffer({ + layerData: layerData + }); + } + + var _buffer = buffer, + attributes = _buffer.attributes, + indexArray = _buffer.indexArray; + var geometry = new THREE.BufferGeometry(); + + if (indexArray) { + geometry.setIndex(new THREE.Uint32BufferAttribute(indexArray, 1)); + } + + geometry.addAttribute('position', new THREE.Float32BufferAttribute(attributes.positions, 3)); + geometry.addAttribute('a_color', new THREE.Float32BufferAttribute(attributes.colors, 4)); + geometry.addAttribute('pickingId', new THREE.Float32BufferAttribute(attributes.pickingIds, 1)); + var lineMaterial = new _lineMaterial.LineMaterial({ + u_opacity: opacity + }, { + SHAPE: false + }); + var polygonLineMesh = new THREE.LineSegments(geometry, lineMaterial); + return polygonLineMesh; +} \ No newline at end of file diff --git a/lib/layer/render/polygon/index.js b/lib/layer/render/polygon/index.js new file mode 100644 index 0000000000..0d846ec611 --- /dev/null +++ b/lib/layer/render/polygon/index.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.polygonMesh = polygonMesh; +Object.defineProperty(exports, "DrawAnimate", { + enumerable: true, + get: function get() { + return _drawAnimate["default"]; + } +}); +Object.defineProperty(exports, "DrawFill", { + enumerable: true, + get: function get() { + return _drawFill["default"]; + } +}); +Object.defineProperty(exports, "DrawLine", { + enumerable: true, + get: function get() { + return _drawLine["default"]; + } +}); + +var _drawAnimate = _interopRequireDefault(require("./drawAnimate")); + +var _drawFill = _interopRequireDefault(require("./drawFill")); + +var _drawLine = _interopRequireDefault(require("./drawLine")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function polygonMesh() {} \ No newline at end of file diff --git a/lib/layer/tile/VectorTileLayer.js b/lib/layer/tile/VectorTileLayer.js new file mode 100644 index 0000000000..c0ca537b8f --- /dev/null +++ b/lib/layer/tile/VectorTileLayer.js @@ -0,0 +1,53 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _tileLayer = _interopRequireDefault(require("./tileLayer")); + +var _vectorTile = _interopRequireDefault(require("./vectorTile")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var VectorTileLayer = +/*#__PURE__*/ +function (_TileLayer) { + _inherits(VectorTileLayer, _TileLayer); + + function VectorTileLayer() { + _classCallCheck(this, VectorTileLayer); + + return _possibleConstructorReturn(this, _getPrototypeOf(VectorTileLayer).apply(this, arguments)); + } + + _createClass(VectorTileLayer, [{ + key: "_createTile", + value: function _createTile(key, layer) { + return new _vectorTile["default"](key, this.url, layer); + } + }]); + + return VectorTileLayer; +}(_tileLayer["default"]); + +exports["default"] = VectorTileLayer; \ No newline at end of file diff --git a/lib/layer/tile/imageTile.js b/lib/layer/tile/imageTile.js new file mode 100644 index 0000000000..41b5a3217a --- /dev/null +++ b/lib/layer/tile/imageTile.js @@ -0,0 +1,167 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _tile = _interopRequireDefault(require("./tile")); + +var _image = _interopRequireDefault(require("../../geom/buffer/image")); + +var _drawImage = _interopRequireDefault(require("../render/image/drawImage")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var ImageTile = +/*#__PURE__*/ +function (_Tile) { + _inherits(ImageTile, _Tile); + + function ImageTile() { + _classCallCheck(this, ImageTile); + + return _possibleConstructorReturn(this, _getPrototypeOf(ImageTile).apply(this, arguments)); + } + + _createClass(ImageTile, [{ + key: "requestTileAsync", + value: function requestTileAsync() { + var _this = this; + + // Making this asynchronous really speeds up the LOD framerate + setTimeout(function () { + if (!_this._mesh) { + // this._mesh = this._createMesh(); + _this._requestTile(); + } + }, 0); + } + }, { + key: "_requestTile", + value: function _requestTile() { + var image = this._createDebugMesh(); + + this._createMesh(image); + + this.emit('tileLoaded'); // const urlParams = { + // x: this._tile[0], + // y: this._tile[1], + // z: this._tile[2] + // }; + // const url = this._getTileURL(urlParams); + // const image = document.createElement('img'); + // image.addEventListener('load', () => { + // this._isLoaded = true; + // this._createMesh(image); + // this.emit('tileLoaded'); + // this._ready = true; + // }, false); + // image.crossOrigin = ''; + // // Load image + // image.src = url; + // this._image = image; + } + }, { + key: "_getBufferData", + value: function _getBufferData(images) { + var NW = this._tileBounds.getTopLeft(); + + var SE = this._tileBounds.getBottomRight(); + + var coordinates = [[NW.x, NW.y, 0], [SE.x, SE.y, 0]]; + return [{ + coordinates: coordinates, + images: images + }]; + } + }, { + key: "_createMesh", + value: function _createMesh(image) { + if (!this._center) { + return; + } + + this._layerData = this._getBufferData(image); + var buffer = new _image["default"]({ + layerData: this._layerData + }); + buffer.attributes.texture = buffer.texture; + var style = this.layer.get('styleOptions'); + var mesh = (0, _drawImage["default"])(buffer.attributes, style); + + this._object3D.add(mesh); + + return this._object3D; + } + }, { + key: "_createDebugMesh", + value: function _createDebugMesh() { + var canvas = document.createElement('canvas'); + var context = canvas.getContext('2d'); + canvas.width = 256; + canvas.height = 256; + context.font = 'Bold 20px Helvetica Neue, Verdana, Arial'; + context.fillStyle = '#ff0000'; + context.fillText(this._tile.join('/'), 20, 20); + context.strokeStyle = 'red'; + context.rect(0, 0, 256, 256); + context.stroke(); + return canvas; + } + }, { + key: "_abortRequest", + value: function _abortRequest() { + if (!this._image) { + return; + } + + this._image.src = ''; + } + }, { + key: "updateColor", + value: function updateColor() {} + }, { + key: "getSelectFeature", + value: function getSelectFeature() { + return {}; + } + }, { + key: "destroy", + value: function destroy() { + // Cancel any pending requests + this._abortRequest(); // Clear image reference + + + this._image = null; + + _get(_getPrototypeOf(ImageTile.prototype), "destroy", this).call(this); + } + }]); + + return ImageTile; +}(_tile["default"]); + +exports["default"] = ImageTile; \ No newline at end of file diff --git a/lib/layer/tile/imageTileLayer.js b/lib/layer/tile/imageTileLayer.js new file mode 100644 index 0000000000..e8b29bf43f --- /dev/null +++ b/lib/layer/tile/imageTileLayer.js @@ -0,0 +1,57 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _tileLayer = _interopRequireDefault(require("./tileLayer")); + +var _imageTile = _interopRequireDefault(require("./imageTile")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var ImageTileLayer = +/*#__PURE__*/ +function (_TileLayer) { + _inherits(ImageTileLayer, _TileLayer); + + function ImageTileLayer(scene, cfg) { + var _this; + + _classCallCheck(this, ImageTileLayer); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(ImageTileLayer).call(this, scene, cfg)); + _this.type = 'image'; + return _this; + } + + _createClass(ImageTileLayer, [{ + key: "_createTile", + value: function _createTile(key, layer) { + return new _imageTile["default"](key, this.url, layer); + } + }]); + + return ImageTileLayer; +}(_tileLayer["default"]); + +exports["default"] = ImageTileLayer; \ No newline at end of file diff --git a/lib/layer/tile/image_tile.js b/lib/layer/tile/image_tile.js new file mode 100644 index 0000000000..41b5a3217a --- /dev/null +++ b/lib/layer/tile/image_tile.js @@ -0,0 +1,167 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _tile = _interopRequireDefault(require("./tile")); + +var _image = _interopRequireDefault(require("../../geom/buffer/image")); + +var _drawImage = _interopRequireDefault(require("../render/image/drawImage")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var ImageTile = +/*#__PURE__*/ +function (_Tile) { + _inherits(ImageTile, _Tile); + + function ImageTile() { + _classCallCheck(this, ImageTile); + + return _possibleConstructorReturn(this, _getPrototypeOf(ImageTile).apply(this, arguments)); + } + + _createClass(ImageTile, [{ + key: "requestTileAsync", + value: function requestTileAsync() { + var _this = this; + + // Making this asynchronous really speeds up the LOD framerate + setTimeout(function () { + if (!_this._mesh) { + // this._mesh = this._createMesh(); + _this._requestTile(); + } + }, 0); + } + }, { + key: "_requestTile", + value: function _requestTile() { + var image = this._createDebugMesh(); + + this._createMesh(image); + + this.emit('tileLoaded'); // const urlParams = { + // x: this._tile[0], + // y: this._tile[1], + // z: this._tile[2] + // }; + // const url = this._getTileURL(urlParams); + // const image = document.createElement('img'); + // image.addEventListener('load', () => { + // this._isLoaded = true; + // this._createMesh(image); + // this.emit('tileLoaded'); + // this._ready = true; + // }, false); + // image.crossOrigin = ''; + // // Load image + // image.src = url; + // this._image = image; + } + }, { + key: "_getBufferData", + value: function _getBufferData(images) { + var NW = this._tileBounds.getTopLeft(); + + var SE = this._tileBounds.getBottomRight(); + + var coordinates = [[NW.x, NW.y, 0], [SE.x, SE.y, 0]]; + return [{ + coordinates: coordinates, + images: images + }]; + } + }, { + key: "_createMesh", + value: function _createMesh(image) { + if (!this._center) { + return; + } + + this._layerData = this._getBufferData(image); + var buffer = new _image["default"]({ + layerData: this._layerData + }); + buffer.attributes.texture = buffer.texture; + var style = this.layer.get('styleOptions'); + var mesh = (0, _drawImage["default"])(buffer.attributes, style); + + this._object3D.add(mesh); + + return this._object3D; + } + }, { + key: "_createDebugMesh", + value: function _createDebugMesh() { + var canvas = document.createElement('canvas'); + var context = canvas.getContext('2d'); + canvas.width = 256; + canvas.height = 256; + context.font = 'Bold 20px Helvetica Neue, Verdana, Arial'; + context.fillStyle = '#ff0000'; + context.fillText(this._tile.join('/'), 20, 20); + context.strokeStyle = 'red'; + context.rect(0, 0, 256, 256); + context.stroke(); + return canvas; + } + }, { + key: "_abortRequest", + value: function _abortRequest() { + if (!this._image) { + return; + } + + this._image.src = ''; + } + }, { + key: "updateColor", + value: function updateColor() {} + }, { + key: "getSelectFeature", + value: function getSelectFeature() { + return {}; + } + }, { + key: "destroy", + value: function destroy() { + // Cancel any pending requests + this._abortRequest(); // Clear image reference + + + this._image = null; + + _get(_getPrototypeOf(ImageTile.prototype), "destroy", this).call(this); + } + }]); + + return ImageTile; +}(_tile["default"]); + +exports["default"] = ImageTile; \ No newline at end of file diff --git a/lib/layer/tile/image_tile_layer.js b/lib/layer/tile/image_tile_layer.js new file mode 100644 index 0000000000..45d3901ca3 --- /dev/null +++ b/lib/layer/tile/image_tile_layer.js @@ -0,0 +1,57 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _tile_layer = _interopRequireDefault(require("./tile_layer")); + +var _image_tile = _interopRequireDefault(require("./image_tile")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var ImageTileLayer = +/*#__PURE__*/ +function (_TileLayer) { + _inherits(ImageTileLayer, _TileLayer); + + function ImageTileLayer(scene, cfg) { + var _this; + + _classCallCheck(this, ImageTileLayer); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(ImageTileLayer).call(this, scene, cfg)); + _this.type = 'image'; + return _this; + } + + _createClass(ImageTileLayer, [{ + key: "_createTile", + value: function _createTile(key, layer) { + return new _image_tile["default"](key, this.url, layer); + } + }]); + + return ImageTileLayer; +}(_tile_layer["default"]); + +exports["default"] = ImageTileLayer; \ No newline at end of file diff --git a/lib/layer/tile/tile-cache.js b/lib/layer/tile/tile-cache.js new file mode 100644 index 0000000000..0f58d07842 --- /dev/null +++ b/lib/layer/tile/tile-cache.js @@ -0,0 +1,58 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _lruCache = _interopRequireDefault(require("../../util/lru-cache")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var TileCache = +/*#__PURE__*/ +function () { + function TileCache() { + var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 50; + + _classCallCheck(this, TileCache); + + this._cache = new _lruCache["default"](limit); + } + + _createClass(TileCache, [{ + key: "getTile", + value: function getTile(z, x, y) { + var key = this._generateKey(z, x, y); + + return this._cache.get(key); + } + }, { + key: "setTile", + value: function setTile(tile, z, x, y) { + var key = this._generateKey(z, x, y); + + this._cache.set(key, tile); + } + }, { + key: "_generateKey", + value: function _generateKey(z, x, y) { + return [z, x, y].join('_'); + } + }, { + key: "destory", + value: function destory() { + this._cache.clear(); + } + }]); + + return TileCache; +}(); + +exports["default"] = TileCache; \ No newline at end of file diff --git a/lib/layer/tile/tile.js b/lib/layer/tile/tile.js new file mode 100644 index 0000000000..62009979df --- /dev/null +++ b/lib/layer/tile/tile.js @@ -0,0 +1,244 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var THREE = _interopRequireWildcard(require("../../core/three")); + +var _base = _interopRequireDefault(require("../../core/base")); + +var _object3dUtil = require("../../util/object3d-util"); + +var _index = _interopRequireDefault(require("../../core/controller/index")); + +var _geoCoord = require("@antv/geo-coord"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var r2d = 180 / Math.PI; +var tileURLRegex = /\{([zxy])\}/g; + +var Tile = +/*#__PURE__*/ +function (_Base) { + _inherits(Tile, _Base); + + function Tile(key, url, layer) { + var _this; + + _classCallCheck(this, Tile); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(Tile).call(this, { + scales: {}, + attrs: {} + })); + _this.layer = layer; + _this._tile = key.split('_').map(function (v) { + return v * 1; + }); + _this._path = url; + _this._tileLnglatBounds = _this._tileLnglatBounds(_this._tile); + _this._tileBounds = _this._tileBounds(_this._tileLnglatBounds); + _this._center = _this._tileBounds.getCenter(); + _this._centerLnglat = _this._tileLnglatBounds.getCenter(); + _this._object3D = new THREE.Object3D({ + name: key + }); + _this._object3D.frustumCulled = false; // this._object3D.name = key; + + _this._object3D.onBeforeRender = function () {}; + + _this._isLoaded = false; + + _this.requestTileAsync(function (data) { + return _this._init(data); + }); + + return _this; + } + + _createClass(Tile, [{ + key: "_init", + value: function _init(data) { + // this._creatSource(data); // 获取Source + this.layerSource = data; + + if (this.layerSource.data === null) { + this.isValid = false; + return; + } + + this.isValid = true; + + this._initControllers(); + + this._createMesh(); + } + }, { + key: "repaint", + value: function repaint() { + this._initControllers(); + + this._createMesh(); + } + }, { + key: "requestTileAsync", + value: function requestTileAsync(done) { + var data = this.layer.tileSource.getTileData(this._tile[0], this._tile[1], this._tile[2]); + + if (data.loaded) { + done(data.data); + } else { + data.data.then(function (data) { + done(data); + }); + } + } + }, { + key: "_initControllers", + value: function _initControllers() { + var mappingCtr = new _index["default"].Mapping({ + layer: this.layer, + mesh: this + }); + var bufferCtr = new _index["default"].Buffer({ + layer: this.layer, + mesh: this + }); + this.set('mappingController', mappingCtr); + this.set('bufferController', bufferCtr); + } + }, { + key: "_createMesh", + value: function _createMesh() {} + }, { + key: "_getTileURL", + value: function _getTileURL(urlParams) { + if (!urlParams.s) { + // Default to a random choice of a, b or c + urlParams.s = String.fromCharCode(97 + Math.floor(Math.random() * 3)); + } + + tileURLRegex.lastIndex = 0; + return this._path.replace(tileURLRegex, function (value, key) { + return urlParams[key]; + }); + } // 经纬度范围转瓦片范围 + + }, { + key: "_tileBounds", + value: function _tileBounds(lnglatBound) { + var ne = this.layer.scene.project([lnglatBound.getNorthEast().lng, lnglatBound.getNorthEast().lat]); + var sw = this.layer.scene.project([lnglatBound.getSouthWest().lng, lnglatBound.getSouthWest().lat]); + return (0, _geoCoord.toBounds)(sw, ne); + } + }, { + key: "getMesh", + value: function getMesh() { + return this._object3D; + } // Get tile bounds in WGS84 coordinates + + }, { + key: "_tileLnglatBounds", + value: function _tileLnglatBounds(tile) { + var e = this._tile2lng(tile[0] + 1, tile[2]); + + var w = this._tile2lng(tile[0], tile[2]); + + var s = this._tile2lat(tile[1] + 1, tile[2]); + + var n = this._tile2lat(tile[1], tile[2]); + + return (0, _geoCoord.toLngLatBounds)([w, n], [e, s]); + } + }, { + key: "_tile2lng", + value: function _tile2lng(x, z) { + return x / Math.pow(2, z) * 360 - 180; + } + }, { + key: "_tile2lat", + value: function _tile2lat(y, z) { + var n = Math.PI - 2 * Math.PI * y / Math.pow(2, z); + return r2d * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))); + } + }, { + key: "_retainParent", + value: function _retainParent(x, y, z) { + var minZoom = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 5; + var x2 = Math.floor(x / 2), + y2 = Math.floor(y / 2), + z2 = z - 1, + coords2 = [+x2, +y2, +z2]; + var tile = this._tiles[coords2]; // 计算保留 + + if (tile && tile.active) { + tile.retain = true; + return true; + } else if (tile && tile.loaded) { + tile.retain = true; + } + + if (z2 > minZoom) { + return this._retainParent(x2, y2, z2, minZoom); + } + + return false; + } + }, { + key: "updateColor", + value: function updateColor() { + var bufferCtr = this.get('bufferController'); + this.get('mappingController').update(); + + bufferCtr._updateColorAttributes(this.getMesh().children[0]); + } + }, { + key: "updateStyle", + value: function updateStyle() { + var bufferCtr = this.get('bufferController'); + + bufferCtr._updateStyle(this.getMesh().children[0]); + } + }, { + key: "_preRender", + value: function _preRender() {} + }, { + key: "destroy", + value: function destroy() { + _get(_getPrototypeOf(Tile.prototype), "destroy", this).call(this); + + (0, _object3dUtil.destoryObject)(this._object3D); + } + }]); + + return Tile; +}(_base["default"]); + +exports["default"] = Tile; \ No newline at end of file diff --git a/lib/layer/tile/tileCache.js b/lib/layer/tile/tileCache.js new file mode 100644 index 0000000000..ddb0e7c407 --- /dev/null +++ b/lib/layer/tile/tileCache.js @@ -0,0 +1,61 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _lruCache = _interopRequireDefault(require("../../util/lru-cache")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var TileCache = +/*#__PURE__*/ +function () { + function TileCache() { + var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 50; + var tileDestroy = arguments.length > 1 ? arguments[1] : undefined; + + _classCallCheck(this, TileCache); + + this._cache = new _lruCache["default"](limit, tileDestroy); + } + + _createClass(TileCache, [{ + key: "getTile", + value: function getTile(key) { + return this._cache.get(key); + } + }, { + key: "setTile", + value: function setTile(tile, key) { + this._cache.set(key, tile); + } + }, { + key: "destory", + value: function destory() { + this._cache.clear(); + } + }, { + key: "setNeedUpdate", + value: function setNeedUpdate() { + var _this = this; + + this._cache._order.forEach(function (key) { + var tile = _this._cache.get(key); + + tile.needUpdate = true; + }); + } + }]); + + return TileCache; +}(); + +exports["default"] = TileCache; \ No newline at end of file diff --git a/lib/layer/tile/tileLayer.js b/lib/layer/tile/tileLayer.js new file mode 100644 index 0000000000..e076450976 --- /dev/null +++ b/lib/layer/tile/tileLayer.js @@ -0,0 +1,701 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _layer = _interopRequireDefault(require("../../core/layer")); + +var _util = _interopRequireDefault(require("../../util")); + +var _diff = _interopRequireDefault(require("../../util/diff")); + +var _tileSource = _interopRequireDefault(require("../../source/tileSource")); + +var THREE = _interopRequireWildcard(require("../../core/three")); + +var _index = _interopRequireDefault(require("../../core/controller/index")); + +var _global = _interopRequireDefault(require("../../global")); + +var _tileCache = _interopRequireDefault(require("./tileCache")); + +var _geoCoord = require("@antv/geo-coord"); + +var _index2 = require("@antv/geo-coord/lib/util/index"); + +var _crsEpsg = require("@antv/geo-coord/lib/geo/crs/crs-epsg3857"); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } + +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var pointShape = _global["default"].pointShape; + +var TileLayer = +/*#__PURE__*/ +function (_Layer) { + _inherits(TileLayer, _Layer); + + function TileLayer(scene, cfg) { + var _this; + + _classCallCheck(this, TileLayer); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(TileLayer).call(this, scene, _objectSpread({}, cfg, { + minSourceZoom: 0, + maxSOurceZoom: 18, + keepBuffer: 2 + }))); + _this._tileCache = new _tileCache["default"](50, _this._destroyTile); + _this._crs = _crsEpsg.epsg3857; + _this._tiles = new THREE.Object3D(); + _this._tiles.frustumCulled = false; + _this._tileKeys = []; + _this.tileList = {}; + _this.type = _this.get('layerType'); + return _this; + } + + _createClass(TileLayer, [{ + key: "shape", + value: function shape(field, values) { + var layerType = this.get('layerType'); + + if (layerType === 'point') { + return _get(_getPrototypeOf(TileLayer.prototype), "shape", this).call(this, field, values); + } + + this.shape = field; + return this; + } + }, { + key: "source", + value: function source(data) { + var cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (data instanceof _tileSource["default"]) { + data.set('mapType', this.scene.mapType); + this.tileSource = data; + } else { + cfg.mapType = this.scene.mapType; + this.tileSource = new _tileSource["default"](data, cfg); + } + + return this; + } + }, { + key: "_initControllers", + value: function _initControllers() { + var pickCtr = new _index["default"].Picking({ + layer: this + }); + var interactionCtr = new _index["default"].Interaction({ + layer: this + }); + this.set('pickingController', pickCtr); + this.set('interacionController', interactionCtr); + } + }, { + key: "render", + value: function render() { + this._visibleWithZoom(); + + this._updateDraw(); + + this.scene._engine.update(); + + return this; + } + }, { + key: "draw", + value: function draw() { + this._object3D.add(this._tiles); + + this._calculateLOD(); + } + }, { + key: "drawTile", + value: function drawTile() {} + }, { + key: "zoomchange", + value: function zoomchange(ev) { + var _this2 = this; + + _get(_getPrototypeOf(TileLayer.prototype), "zoomchange", this).call(this, ev); + + this._visibleWithZoom(); + + requestAnimationFrame(function () { + _this2._calculateLOD(); + }); + + this._calculateLOD(); + } + }, { + key: "dragend", + value: function dragend(ev) { + var _this3 = this; + + _get(_getPrototypeOf(TileLayer.prototype), "dragend", this).call(this, ev); + + requestAnimationFrame(function () { + _this3._calculateLOD(); + }); + } + }, { + key: "_calculateLOD", + value: function _calculateLOD() { + var _this4 = this; + + /** + * 加载完成 active + * 需要显示 current + * 是否保留 retain + */ + var zoom = Math.floor(this.scene.getZoom()) - 1; + var minZoom = this.get('minZoom'); + var maxZoom = this.get('maxZoom'); + var minSourceZoom = this.tileSource.get('minSourceZoom'); + var maxSourceZoom = this.tileSource.get('maxSourceZoom'); + var currentZoom = this.scene.getZoom(); + this.tileZoom = zoom > maxSourceZoom ? maxSourceZoom : zoom; + + if (currentZoom < minZoom || currentZoom >= maxZoom || currentZoom < minSourceZoom) { + this._removeTiles(); + + this._object3D.visible = false; + return; + } else if (this.get('visible')) { + this._object3D.visible = true; + } + + this.show(); + this.updateTileList = []; + var center = this.scene.getCenter(); + + var centerPoint = this._crs.lngLatToPoint((0, _geoCoord.toLngLat)(center.lng, center.lat), this.tileZoom); + + var centerXY = centerPoint.divideBy(256).floor(); + + var pixelBounds = this._getPixelBounds(); + + var tileRange = this._pxBoundsToTileRange(pixelBounds); + + var margin = this.get('keepBuffer'); + this.noPruneRange = new _geoCoord.Bounds(tileRange.getBottomLeft().subtract([margin, -margin]), tileRange.getTopRight().add([margin, -margin])); + + if (!(isFinite(tileRange.min.x) && isFinite(tileRange.min.y) && isFinite(tileRange.max.x) && isFinite(tileRange.max.y))) { + throw new Error('Attempted to load an infinite number of tiles'); + } + + for (var j = tileRange.min.y; j <= tileRange.max.y; j++) { + for (var i = tileRange.min.x; i <= tileRange.max.x; i++) { + var coords = [i, j, this.tileZoom]; + var tile = this.tileList[coords.join('_')]; + + if (tile) { + tile.current = true; + } else { + this.tileList[coords.join('_')] = { + current: true, + coords: coords + }; + this.updateTileList.push(coords); + } + } + } + + this.updateTileList.sort(function (a, b) { + var tile1 = a; + var tile2 = b; + var d1 = Math.pow(tile1[0] * 1 - centerXY.x, 2) + Math.pow(tile1[1] * 1 - centerXY.y, 2); + var d2 = Math.pow(tile2[0] * 1 - centerXY.x, 2) + Math.pow(tile2[1] * 1 - centerXY.y, 2); + return d1 - d2; + }); + + this._pruneTiles(); // 更新瓦片数据 + + + this.updateTileList.forEach(function (coords) { + var key = coords.join('_'); + + if (_this4.tileList[key].current) { + _this4._requestTile(key, _this4); + } + }); + } + }, { + key: "_getShape", + value: function _getShape(layerData) { + var shape = null; + + if (!layerData[0].hasOwnProperty('shape')) { + return 'normal'; + } + + for (var i = 0; i < layerData.length; i++) { + shape = layerData[i].shape; + + if (shape !== undefined) { + break; + } + } + + if (pointShape['2d'].indexOf(shape) !== -1) { + return 'circle'; + } else if (pointShape['3d'].indexOf(shape) !== -1) { + return 'fill'; + } else if (this.scene.image.imagesIds.indexOf(shape) !== -1) { + return 'image'; + } + + return 'text'; + } + }, { + key: "_updateTileList", + value: function _updateTileList(x, y, z) { + var key = [x, y, z].join('_'); + var tile = this.tileList[key]; + + if (tile) { + tile.current = true; + } else { + this.tileList[key] = { + current: true, + active: false, + coords: key.split('_') + }; + this.updateTileList.push(key); + } + } + }, { + key: "_requestTile", + value: function _requestTile(key, layer) { + var _this5 = this; + + var t = this.tileList[key]; + + if (!t) { + return; + } + + var tile = this._tileCache.getTile(key); + + if (!tile) { + tile = this._createTile(key, layer); + tile.on('tileLoaded', function () { + t.active = true; + var mesh = tile.getMesh(); + mesh.name = key; + + _this5._tileCache.setTile(tile, key); + + _this5._tileKeys.push(key); + + if (mesh.type === 'composer') { + _this5.scene._engine.composerLayers.push(mesh); + + _this5.scene._engine.update(); + + _this5._pruneTiles(); + + return; + } + + if (mesh.children.length !== 0) { + _this5._tiles.add(tile.getMesh()); + + _this5._addPickTile(tile.getMesh()); + } + + _this5.scene._engine.update(); + + _this5._pruneTiles(); + }); + } else { + if (tile.getMesh().type === 'composer') { + this.scene._engine.composerLayers.push(tile.getMesh()); + + this.scene._engine.update(); + + this._pruneTiles(); + + return; + } + + if (tile.needUpdate) { + tile.updateColor(); + tile.needUpdate = false; + } + + this._tiles.add(tile.getMesh()); + + t.active = true; + + this._addPickTile(tile.getMesh()); + + this._tileKeys.push(key); + + this.scene._engine.update(); + + this._pruneTiles(); + } + } + }, { + key: "_addPickTile", + value: function _addPickTile(meshobj) { + if (this.type === 'image') { + return; + } + + var pickCtr = this.get('pickingController'); + var mesh = meshobj.children[0]; + mesh.name = meshobj.name; + pickCtr.addPickMesh(mesh); + } // 根据距离优先级查找 + + }, { + key: "getSelectFeature", + value: function getSelectFeature(id, lnglat) { + var zoom = this.tileZoom; + + var tilePoint = this._crs.lngLatToPoint((0, _geoCoord.toLngLat)(lnglat.lng, lnglat.lat), zoom); + + var tileXY = tilePoint.divideBy(256).floor(); + var key = [tileXY.x, tileXY.y, zoom].join('_'); + + var tile = this._tileCache.getTile(key); + + var feature = tile ? tile.getSelectFeature(id) : null; + return { + feature: feature + }; + } + }, { + key: "_pruneTiles", + value: function _pruneTiles() { + var tile; + var zoom = this.tileZoom; + + for (var key in this.tileList) { + var c = this.tileList[key].coords; + + if (c[2] !== zoom || !this.noPruneRange.contains(new _geoCoord.Point(c[0], c[1]))) { + this.tileList[key].current = false; + } + } + + for (var _key in this.tileList) { + tile = this.tileList[_key]; + tile.retain = tile.current; + } + + for (var _key2 in this.tileList) { + tile = this.tileList[_key2]; + + if (tile.current && !tile.active) { + var _key2$split$map = _key2.split('_').map(function (v) { + return v * 1; + }), + _key2$split$map2 = _slicedToArray(_key2$split$map, 3), + x = _key2$split$map2[0], + y = _key2$split$map2[1], + z = _key2$split$map2[2]; + + if (!this._retainParent(x, y, z, z - 5)) { + this._retainChildren(x, y, z, z + 2); + } + } + } + + this._removeOutTiles(); + } + }, { + key: "_retainParent", + value: function _retainParent(x, y, z, minZoom) { + var x2 = Math.floor(x / 2); + var y2 = Math.floor(y / 2); + var z2 = z - 1; + var tile = this.tileList[[x2, y2, z2].join('_')]; + + if (tile && tile.active) { + tile.retain = true; + return true; + } else if (tile && tile.loaded) { + tile.retain = true; + } + + if (z2 > minZoom) { + return this._retainParent(x2, y2, z2, minZoom); + } + + return false; + } + }, { + key: "_retainChildren", + value: function _retainChildren(x, y, z, maxZoom) { + for (var i = 2 * x; i < 2 * x + 2; i++) { + for (var j = 2 * y; j < 2 * y + 2; j++) { + var key = [i, j, z + 1].join('_'); + var tile = this.tileList[key]; + + if (tile && tile.active) { + tile.retain = true; + continue; + } else if (tile && tile.loaded) { + tile.retain = true; + } + + if (z + 1 < maxZoom) { + this._retainChildren(i, j, z + 1, maxZoom); + } + } + } + } // 移除视野外的tile + + }, { + key: "_removeOutTiles", + value: function _removeOutTiles() { + var _this6 = this; + + for (var key in this.tileList) { + if (!this.tileList[key].retain) { + (function () { + var tileObj = _this6._tileCache.getTile(key); + + if (tileObj) { + tileObj._abortRequest(); + + var pickCtr = _this6.get('pickingController'); + + pickCtr && pickCtr.removePickMeshByName(tileObj.getMesh().name); + + _this6._tiles.remove(tileObj.getMesh()); + } + + if (tileObj && tileObj.getMesh().type === 'composer') { + _this6.scene._engine.composerLayers = _this6.scene._engine.composerLayers.filter(function (obj) { + return obj.name !== tileObj.getMesh().name; + }); + } + + delete _this6.tileList[key]; + })(); + } + } + + if (this._tiles.children.length > Object.keys(this.tileList).length) { + this._tiles.children.forEach(function (tile) { + var key = tile.name; + + if (!_this6.tileList[key]) { + _this6._tiles.remove(tile); + } + }); + } // 移除 空的geom + + + this.scene._engine.update(); + } + }, { + key: "_removeTiles", + value: function _removeTiles() { + this.hide(); + + if (!this._tiles || !this._tiles.children) { + return; + } + + for (var i = this._tiles.children.length - 1; i >= 0; i--) { + this._tiles.remove(this._tiles.children[i]); + } + + this.tileList = []; + this._tileKeys = []; + + this._tileCache.destory(); + + var pickCtr = this.get('pickingController'); + pickCtr.removeAllMesh(); + } + }, { + key: "_getPixelBounds", + value: function _getPixelBounds() { + var viewPort = this.scene.getBounds().toBounds(); + var NE = viewPort.getNorthEast(); + var SW = viewPort.getSouthWest(); + var zoom = this.tileZoom; + var center = this.scene.getCenter(); + + var NEPoint = this._crs.lngLatToPoint((0, _geoCoord.toLngLat)(NE.lng, NE.lat), zoom); + + var SWPoint = this._crs.lngLatToPoint((0, _geoCoord.toLngLat)(SW.lng, SW.lat), zoom); + + var centerPoint = this._crs.lngLatToPoint((0, _geoCoord.toLngLat)(center.lng, center.lat), zoom); + + var topHeight = centerPoint.y - NEPoint.y; + var bottomHeight = SWPoint.y - centerPoint.y; // 跨日界线的情况 + + var leftWidth; + var rightWidth; + + if (center.lng - NE.lng > 0 || center.lng - SW.lng < 0) { + var width = Math.pow(2, zoom) * 256 / 360 * (180 - NE.lng) + Math.pow(2, zoom) * 256 / 360 * (SW.lng + 180); + + if (center.lng - NE.lng > 0) { + // 日界线在右侧 + leftWidth = Math.pow(2, zoom) * 256 / 360 * (center.lng - NE.lng); + rightWidth = width - leftWidth; + } else { + rightWidth = Math.pow(2, zoom) * 256 / 360 * (SW.lng - center.lng); + leftWidth = width - rightWidth; + } + } else { + // 不跨日界线 + leftWidth = Math.pow(2, zoom) * 256 / 360 * (center.lng - SW.lng); + rightWidth = Math.pow(2, zoom) * 256 / 360 * (NE.lng - center.lng); + } + + var pixelBounds = new _geoCoord.Bounds(centerPoint.subtract(leftWidth, topHeight), centerPoint.add(rightWidth, bottomHeight)); + return pixelBounds; + } + }, { + key: "_pxBoundsToTileRange", + value: function _pxBoundsToTileRange(pixelBounds) { + return new _geoCoord.Bounds(pixelBounds.min.divideBy(256).floor(), pixelBounds.max.divideBy(256).ceil().subtract([1, 1])); + } + }, { + key: "_wrapCoords", + value: function _wrapCoords(coords) { + var wrapX = [0, Math.pow(2, coords[2])]; + var newX = (0, _index2.wrapNum)(coords[0], wrapX); + return [newX, coords[1], coords[2]]; + } + }, { + key: "_destroyTile", + value: function _destroyTile(tile) { + tile.destroy(); + tile = null; + } + }, { + key: "_updateDraw", + value: function _updateDraw() { + var _this7 = this; + + var preAttrs = this.get('preAttrOptions'); + var nextAttrs = this.get('attrOptions'); + var preStyle = this.get('preStyleOption'); + var nextStyle = this.get('styleOptions'); + + if (preAttrs === undefined && preStyle === undefined) { + // 首次渲染 + this._setPreOption(); + + this._scaleByZoom(); + + this._initControllers(); + + this._initInteraction(); + + this._initMapEvent(); + + this.draw(); + + this._setPreOption(); + + return; + } + + if (!this._tiles.children.length > 0 || !this._object3D.visible) { + return; + } // 更新数据颜色 过滤 filter + + + if (!_util["default"].isEqual(preAttrs.color, nextAttrs.color) || !_util["default"].isEqual(preAttrs.filter, nextAttrs.filter)) { + this._tileCache.setNeedUpdate(); + + this._tiles.children.forEach(function (tile) { + var tileObj = _this7._tileCache.getTile(tile.name); + + tileObj.updateColor(); + tileObj.needUpdate = false; + + _this7.scene._engine.update(); + }); + } // 更新Size + + + if (!_util["default"].isEqual(preAttrs.size, nextAttrs.size)) {} // this._tiles.children(tile => { + // this._tileCache.get(tile.name).updateSize(); + // }); + // 更新形状 + + + if (!_util["default"].isEqual(preAttrs.shape, nextAttrs.shape)) {// this._tiles.children(tile => { + // this._tileCache.get(tile.name).updateShape(); + // }); + } + + if (!_util["default"].isEqual(preStyle, nextStyle)) { + // 判断新增,修改,删除 + var newStyle = {}; + + _util["default"].each((0, _diff["default"])(preStyle, nextStyle), function (_ref) { + var type = _ref.type, + key = _ref.key, + value = _ref.value; + type !== 'remove' && (newStyle[key] = value); // newStyle[key] = type === 'remove' ? null : value; + }); + + this._tiles.children(function (tile) { + _this7._tileCache.get(tile.name).updateStyle(); + }); + } + + this._setPreOption(); + } + }, { + key: "destroy", + value: function destroy() {} + }]); + + return TileLayer; +}(_layer["default"]); + +exports["default"] = TileLayer; \ No newline at end of file diff --git a/lib/layer/tile/tile_cache.js b/lib/layer/tile/tile_cache.js new file mode 100644 index 0000000000..ddb0e7c407 --- /dev/null +++ b/lib/layer/tile/tile_cache.js @@ -0,0 +1,61 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _lruCache = _interopRequireDefault(require("../../util/lru-cache")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var TileCache = +/*#__PURE__*/ +function () { + function TileCache() { + var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 50; + var tileDestroy = arguments.length > 1 ? arguments[1] : undefined; + + _classCallCheck(this, TileCache); + + this._cache = new _lruCache["default"](limit, tileDestroy); + } + + _createClass(TileCache, [{ + key: "getTile", + value: function getTile(key) { + return this._cache.get(key); + } + }, { + key: "setTile", + value: function setTile(tile, key) { + this._cache.set(key, tile); + } + }, { + key: "destory", + value: function destory() { + this._cache.clear(); + } + }, { + key: "setNeedUpdate", + value: function setNeedUpdate() { + var _this = this; + + this._cache._order.forEach(function (key) { + var tile = _this._cache.get(key); + + tile.needUpdate = true; + }); + } + }]); + + return TileCache; +}(); + +exports["default"] = TileCache; \ No newline at end of file diff --git a/lib/layer/tile/tile_layer.js b/lib/layer/tile/tile_layer.js new file mode 100644 index 0000000000..0e8a1b49e8 --- /dev/null +++ b/lib/layer/tile/tile_layer.js @@ -0,0 +1,706 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _layer = _interopRequireDefault(require("../../core/layer")); + +var _util = _interopRequireDefault(require("../../util")); + +var _diff = _interopRequireDefault(require("../../util/diff")); + +var _tile_source = _interopRequireDefault(require("../../source/tile_source")); + +var THREE = _interopRequireWildcard(require("../../core/three")); + +var _index = _interopRequireDefault(require("../../core/controller/index")); + +var _global = _interopRequireDefault(require("../../global")); + +var _tile_cache = _interopRequireDefault(require("./tile_cache")); + +var _geoCoord = require("@antv/geo-coord"); + +var _index2 = require("@antv/geo-coord/lib/util/index"); + +var _crsEpsg = require("@antv/geo-coord/lib/geo/crs/crs-epsg3857"); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } + +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var pointShape = _global["default"].pointShape; + +var TileLayer = +/*#__PURE__*/ +function (_Layer) { + _inherits(TileLayer, _Layer); + + function TileLayer(scene, cfg) { + var _this; + + _classCallCheck(this, TileLayer); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(TileLayer).call(this, scene, _objectSpread({}, cfg, { + minSourceZoom: 0, + maxSOurceZoom: 18, + keepBuffer: 2 + }))); + _this._tileCache = new _tile_cache["default"](50, _this._destroyTile); + _this._crs = _crsEpsg.epsg3857; + _this._tiles = new THREE.Object3D(); + _this._tiles.frustumCulled = false; + _this._tileKeys = []; + _this.tileList = {}; + _this.type = _this.get('layerType'); + _this.workerPool = _this.scene.workerPool; + return _this; + } + + _createClass(TileLayer, [{ + key: "shape", + value: function shape(field, values) { + var layerType = this.get('layerType'); + + if (layerType === 'point') { + return _get(_getPrototypeOf(TileLayer.prototype), "shape", this).call(this, field, values); + } + + this.shape = field; + return this; + } + }, { + key: "source", + value: function source(data) { + var cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (data instanceof _tile_source["default"]) { + data.set('mapType', this.scene.mapType); + this.tileSource = data; + } else { + cfg.mapType = this.scene.mapType; + this.tileSource = new _tile_source["default"](data, cfg); + this.sourceCfg = _objectSpread({}, cfg, { + url: data + }); + } + + return this; + } + }, { + key: "_initControllers", + value: function _initControllers() { + var pickCtr = new _index["default"].Picking({ + layer: this + }); + var interactionCtr = new _index["default"].Interaction({ + layer: this + }); + this.set('pickingController', pickCtr); + this.set('interacionController', interactionCtr); + } + }, { + key: "render", + value: function render() { + this._visibleWithZoom(); + + this._updateDraw(); + + this.scene._engine.update(); + + return this; + } + }, { + key: "draw", + value: function draw() { + this._object3D.add(this._tiles); + + this._calculateLOD(); + } + }, { + key: "drawTile", + value: function drawTile() {} + }, { + key: "zoomchange", + value: function zoomchange(ev) { + var _this2 = this; + + _get(_getPrototypeOf(TileLayer.prototype), "zoomchange", this).call(this, ev); + + this._visibleWithZoom(); + + requestAnimationFrame(function () { + _this2._calculateLOD(); + }); + + this._calculateLOD(); + } + }, { + key: "dragend", + value: function dragend(ev) { + var _this3 = this; + + _get(_getPrototypeOf(TileLayer.prototype), "dragend", this).call(this, ev); + + requestAnimationFrame(function () { + _this3._calculateLOD(); + }); + } + }, { + key: "_calculateLOD", + value: function _calculateLOD() { + var _this4 = this; + + /** + * 加载完成 active + * 需要显示 current + * 是否保留 retain + */ + var zoom = Math.floor(this.scene.getZoom()) - 1; + var minZoom = this.get('minZoom'); + var maxZoom = this.get('maxZoom'); + var minSourceZoom = this.tileSource.get('minSourceZoom'); + var maxSourceZoom = this.tileSource.get('maxSourceZoom'); + var currentZoom = this.scene.getZoom(); + this.tileZoom = zoom > maxSourceZoom ? maxSourceZoom : zoom; + + if (currentZoom < minZoom || currentZoom >= maxZoom || currentZoom < minSourceZoom) { + this._removeTiles(); + + this._object3D.visible = false; + return; + } else if (this.get('visible')) { + this._object3D.visible = true; + } + + this.show(); + this.updateTileList = []; + var center = this.scene.getCenter(); + + var centerPoint = this._crs.lngLatToPoint((0, _geoCoord.toLngLat)(center.lng, center.lat), this.tileZoom); + + var centerXY = centerPoint.divideBy(256).floor(); + + var pixelBounds = this._getPixelBounds(); + + var tileRange = this._pxBoundsToTileRange(pixelBounds); + + var margin = this.get('keepBuffer'); + this.noPruneRange = new _geoCoord.Bounds(tileRange.getBottomLeft().subtract([margin, -margin]), tileRange.getTopRight().add([margin, -margin])); + + if (!(isFinite(tileRange.min.x) && isFinite(tileRange.min.y) && isFinite(tileRange.max.x) && isFinite(tileRange.max.y))) { + throw new Error('Attempted to load an infinite number of tiles'); + } + + for (var j = tileRange.min.y; j <= tileRange.max.y; j++) { + for (var i = tileRange.min.x; i <= tileRange.max.x; i++) { + var coords = [i, j, this.tileZoom]; + var tile = this.tileList[coords.join('_')]; + + if (tile) { + tile.current = true; + } else { + this.tileList[coords.join('_')] = { + current: true, + coords: coords + }; + this.updateTileList.push(coords); + } + } + } + + this.updateTileList.sort(function (a, b) { + var tile1 = a; + var tile2 = b; + var d1 = Math.pow(tile1[0] * 1 - centerXY.x, 2) + Math.pow(tile1[1] * 1 - centerXY.y, 2); + var d2 = Math.pow(tile2[0] * 1 - centerXY.x, 2) + Math.pow(tile2[1] * 1 - centerXY.y, 2); + return d1 - d2; + }); + + this._pruneTiles(); // 更新瓦片数据 + + + this.updateTileList.forEach(function (coords) { + var key = coords.join('_'); + + if (_this4.tileList[key].current) { + _this4._requestTile(key, _this4); + } + }); + } + }, { + key: "_getShape", + value: function _getShape(layerData) { + var shape = null; + + if (!layerData[0].hasOwnProperty('shape')) { + return 'normal'; + } + + for (var i = 0; i < layerData.length; i++) { + shape = layerData[i].shape; + + if (shape !== undefined) { + break; + } + } + + if (pointShape['2d'].indexOf(shape) !== -1) { + return 'circle'; + } else if (pointShape['3d'].indexOf(shape) !== -1) { + return 'fill'; + } else if (this.scene.image.imagesIds.indexOf(shape) !== -1) { + return 'image'; + } + + return 'text'; + } + }, { + key: "_updateTileList", + value: function _updateTileList(x, y, z) { + var key = [x, y, z].join('_'); + var tile = this.tileList[key]; + + if (tile) { + tile.current = true; + } else { + this.tileList[key] = { + current: true, + active: false, + coords: key.split('_') + }; + this.updateTileList.push(key); + } + } + }, { + key: "_requestTile", + value: function _requestTile(key, layer) { + var _this5 = this; + + var t = this.tileList[key]; + + if (!t) { + return; + } + + var tile = this._tileCache.getTile(key); + + if (!tile) { + tile = this._createTile(key, layer); + tile.on('tileLoaded', function () { + t.active = true; + var mesh = tile.getMesh(); + mesh.name = key; + + _this5._tileCache.setTile(tile, key); + + _this5._tileKeys.push(key); + + if (mesh.type === 'composer') { + _this5.scene._engine.composerLayers.push(mesh); + + _this5.scene._engine.update(); + + _this5._pruneTiles(); + + return; + } + + if (mesh.children.length !== 0) { + _this5._tiles.add(tile.getMesh()); + + _this5._addPickTile(tile.getMesh()); + } + + _this5.scene._engine.update(); + + _this5._pruneTiles(); + }); + } else { + if (tile.getMesh().type === 'composer') { + this.scene._engine.composerLayers.push(tile.getMesh()); + + this.scene._engine.update(); + + this._pruneTiles(); + + return; + } + + if (tile.needUpdate) { + tile.updateColor(); + tile.needUpdate = false; + } + + this._tiles.add(tile.getMesh()); + + t.active = true; + + this._addPickTile(tile.getMesh()); + + this._tileKeys.push(key); + + this.scene._engine.update(); + + this._pruneTiles(); + } + } + }, { + key: "_addPickTile", + value: function _addPickTile(meshobj) { + if (this.type === 'image') { + return; + } + + var pickCtr = this.get('pickingController'); + var mesh = meshobj.children[0]; + mesh.name = meshobj.name; + pickCtr.addPickMesh(mesh); + } // 根据距离优先级查找 + + }, { + key: "getSelectFeature", + value: function getSelectFeature(id, lnglat) { + var zoom = this.tileZoom; + + var tilePoint = this._crs.lngLatToPoint((0, _geoCoord.toLngLat)(lnglat.lng, lnglat.lat), zoom); + + var tileXY = tilePoint.divideBy(256).floor(); + var key = [tileXY.x, tileXY.y, zoom].join('_'); + + var tile = this._tileCache.getTile(key); + + var feature = tile ? tile.getSelectFeature(id) : null; + return { + feature: feature + }; + } + }, { + key: "_pruneTiles", + value: function _pruneTiles() { + var tile; + var zoom = this.tileZoom; + + for (var key in this.tileList) { + var c = this.tileList[key].coords; + + if (c[2] !== zoom || !this.noPruneRange.contains(new _geoCoord.Point(c[0], c[1]))) { + this.tileList[key].current = false; + } + } + + for (var _key in this.tileList) { + tile = this.tileList[_key]; + tile.retain = tile.current; + } + + for (var _key2 in this.tileList) { + tile = this.tileList[_key2]; + + if (tile.current && !tile.active) { + var _key2$split$map = _key2.split('_').map(function (v) { + return v * 1; + }), + _key2$split$map2 = _slicedToArray(_key2$split$map, 3), + x = _key2$split$map2[0], + y = _key2$split$map2[1], + z = _key2$split$map2[2]; + + if (!this._retainParent(x, y, z, z - 5)) { + this._retainChildren(x, y, z, z + 2); + } + } + } + + this._removeOutTiles(); + } + }, { + key: "_retainParent", + value: function _retainParent(x, y, z, minZoom) { + var x2 = Math.floor(x / 2); + var y2 = Math.floor(y / 2); + var z2 = z - 1; + var tile = this.tileList[[x2, y2, z2].join('_')]; + + if (tile && tile.active) { + tile.retain = true; + return true; + } else if (tile && tile.loaded) { + tile.retain = true; + } + + if (z2 > minZoom) { + return this._retainParent(x2, y2, z2, minZoom); + } + + return false; + } + }, { + key: "_retainChildren", + value: function _retainChildren(x, y, z, maxZoom) { + for (var i = 2 * x; i < 2 * x + 2; i++) { + for (var j = 2 * y; j < 2 * y + 2; j++) { + var key = [i, j, z + 1].join('_'); + var tile = this.tileList[key]; + + if (tile && tile.active) { + tile.retain = true; + continue; + } else if (tile && tile.loaded) { + tile.retain = true; + } + + if (z + 1 < maxZoom) { + this._retainChildren(i, j, z + 1, maxZoom); + } + } + } + } // 移除视野外的tile + + }, { + key: "_removeOutTiles", + value: function _removeOutTiles() { + var _this6 = this; + + for (var key in this.tileList) { + if (!this.tileList[key].retain) { + (function () { + var tileObj = _this6._tileCache.getTile(key); + + if (tileObj) { + tileObj._abortRequest(); + + var pickCtr = _this6.get('pickingController'); + + pickCtr && pickCtr.removePickMeshByName(tileObj.getMesh().name); + + _this6._tiles.remove(tileObj.getMesh()); + } + + if (tileObj && tileObj.getMesh().type === 'composer') { + _this6.scene._engine.composerLayers = _this6.scene._engine.composerLayers.filter(function (obj) { + return obj.name !== tileObj.getMesh().name; + }); + } + + delete _this6.tileList[key]; + })(); + } + } + + if (this._tiles.children.length > Object.keys(this.tileList).length) { + this._tiles.children.forEach(function (tile) { + var key = tile.name; + + if (!_this6.tileList[key]) { + _this6._tiles.remove(tile); + } + }); + } // 移除 空的geom + + + this.scene._engine.update(); + } + }, { + key: "_removeTiles", + value: function _removeTiles() { + this.hide(); + + if (!this._tiles || !this._tiles.children) { + return; + } + + for (var i = this._tiles.children.length - 1; i >= 0; i--) { + this._tiles.remove(this._tiles.children[i]); + } + + this.tileList = []; + this._tileKeys = []; + + this._tileCache.destory(); + + var pickCtr = this.get('pickingController'); + pickCtr.removeAllMesh(); + } + }, { + key: "_getPixelBounds", + value: function _getPixelBounds() { + var viewPort = this.scene.getBounds().toBounds(); + var NE = viewPort.getNorthEast(); + var SW = viewPort.getSouthWest(); + var zoom = this.tileZoom; + var center = this.scene.getCenter(); + + var NEPoint = this._crs.lngLatToPoint((0, _geoCoord.toLngLat)(NE.lng, NE.lat), zoom); + + var SWPoint = this._crs.lngLatToPoint((0, _geoCoord.toLngLat)(SW.lng, SW.lat), zoom); + + var centerPoint = this._crs.lngLatToPoint((0, _geoCoord.toLngLat)(center.lng, center.lat), zoom); + + var topHeight = centerPoint.y - NEPoint.y; + var bottomHeight = SWPoint.y - centerPoint.y; // 跨日界线的情况 + + var leftWidth; + var rightWidth; + + if (center.lng - NE.lng > 0 || center.lng - SW.lng < 0) { + var width = Math.pow(2, zoom) * 256 / 360 * (180 - NE.lng) + Math.pow(2, zoom) * 256 / 360 * (SW.lng + 180); + + if (center.lng - NE.lng > 0) { + // 日界线在右侧 + leftWidth = Math.pow(2, zoom) * 256 / 360 * (center.lng - NE.lng); + rightWidth = width - leftWidth; + } else { + rightWidth = Math.pow(2, zoom) * 256 / 360 * (SW.lng - center.lng); + leftWidth = width - rightWidth; + } + } else { + // 不跨日界线 + leftWidth = Math.pow(2, zoom) * 256 / 360 * (center.lng - SW.lng); + rightWidth = Math.pow(2, zoom) * 256 / 360 * (NE.lng - center.lng); + } + + var pixelBounds = new _geoCoord.Bounds(centerPoint.subtract(leftWidth, topHeight), centerPoint.add(rightWidth, bottomHeight)); + return pixelBounds; + } + }, { + key: "_pxBoundsToTileRange", + value: function _pxBoundsToTileRange(pixelBounds) { + return new _geoCoord.Bounds(pixelBounds.min.divideBy(256).floor(), pixelBounds.max.divideBy(256).ceil().subtract([1, 1])); + } + }, { + key: "_wrapCoords", + value: function _wrapCoords(coords) { + var wrapX = [0, Math.pow(2, coords[2])]; + var newX = (0, _index2.wrapNum)(coords[0], wrapX); + return [newX, coords[1], coords[2]]; + } + }, { + key: "_destroyTile", + value: function _destroyTile(tile) { + tile.destroy(); + tile = null; + } + }, { + key: "_updateDraw", + value: function _updateDraw() { + var _this7 = this; + + var preAttrs = this.get('preAttrOptions'); + var nextAttrs = this.get('attrOptions'); + var preStyle = this.get('preStyleOption'); + var nextStyle = this.get('styleOptions'); + + if (preAttrs === undefined && preStyle === undefined) { + // 首次渲染 + // this._setPreOption(); + this._scaleByZoom(); + + this._initControllers(); + + this._initInteraction(); + + this._initMapEvent(); + + this.draw(); + + this._setPreOption(); + + return; + } + + if (!this._tiles.children.length > 0 || !this._object3D.visible) { + return; + } // 更新数据颜色 过滤 filter + + + if (!_util["default"].isEqual(preAttrs.color, nextAttrs.color) || !_util["default"].isEqual(preAttrs.filter, nextAttrs.filter)) { + this._tileCache.setNeedUpdate(); + + this._tiles.children.forEach(function (tile) { + var tileObj = _this7._tileCache.getTile(tile.name); + + tileObj.updateColor(); + tileObj.needUpdate = false; + + _this7.scene._engine.update(); + }); + } // 更新Size + + + if (!_util["default"].isEqual(preAttrs.size, nextAttrs.size)) {} // this._tiles.children(tile => { + // this._tileCache.get(tile.name).updateSize(); + // }); + // 更新形状 + + + if (!_util["default"].isEqual(preAttrs.shape, nextAttrs.shape)) {// this._tiles.children(tile => { + // this._tileCache.get(tile.name).updateShape(); + // }); + } + + if (!_util["default"].isEqual(preStyle, nextStyle)) { + // 判断新增,修改,删除 + var newStyle = {}; + + _util["default"].each((0, _diff["default"])(preStyle, nextStyle), function (_ref) { + var type = _ref.type, + key = _ref.key, + value = _ref.value; + type !== 'remove' && (newStyle[key] = value); // newStyle[key] = type === 'remove' ? null : value; + }); + + this._tiles.children(function (tile) { + _this7._tileCache.get(tile.name).updateStyle(); + }); + } + + this._setPreOption(); + } + }, { + key: "destroy", + value: function destroy() {} + }]); + + return TileLayer; +}(_layer["default"]); + +exports["default"] = TileLayer; \ No newline at end of file diff --git a/lib/layer/tile/vectorTile.js b/lib/layer/tile/vectorTile.js new file mode 100644 index 0000000000..cb66a98023 --- /dev/null +++ b/lib/layer/tile/vectorTile.js @@ -0,0 +1,228 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _tile = _interopRequireDefault(require("./tile")); + +var _ajax = require("../../util/ajax"); + +var _object3dUtil = require("../../util/object3d-util"); + +var THREE = _interopRequireWildcard(require("../../core/three")); + +var _maskMaterial = _interopRequireDefault(require("../../geom/material/tile/maskMaterial")); + +var _index = require("../render/index"); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var VectorTile = +/*#__PURE__*/ +function (_Tile) { + _inherits(VectorTile, _Tile); + + function VectorTile() { + _classCallCheck(this, VectorTile); + + return _possibleConstructorReturn(this, _getPrototypeOf(VectorTile).apply(this, arguments)); + } + + _createClass(VectorTile, [{ + key: "_requestTile", + // requestTileAsync(done) { + // // Making this asynchronous really speeds up the LOD framerate + // setTimeout(() => { + // if (!this._mesh) { + // // this._mesh = this._createMesh(); + // this._requestTile(done); + // } + // }, 0); + // } + value: function _requestTile(done) { + var _this = this; + + var urlParams = { + x: this._tile[0], + y: this._tile[1], + z: this._tile[2] + }; + + var url = this._getTileURL(urlParams); + + this.xhrRequest = (0, _ajax.getArrayBuffer)({ + url: url + }, function (err, data) { + if (err) { + _this._noData = true; + return; + } + + _this._isLoaded = true; + done(data.data); + }); + } + }, { + key: "_creatSource", + value: function _creatSource(data) { + if (!data) return null; + this.layerSource = this.layer.tileSource(data, { + parser: { + tile: this._tile + } + }); + } + }, { + key: "_createMesh", + value: function _createMesh() { + var _this2 = this; + + var layerData = this.layerData; + + if (this.layer.get('layerType') === 'point') { + this.layer.shape = this.layer._getShape(layerData); + } + + this.mesh = (0, _index.getRender)(this.layer.get('layerType'), this.layer.shape)(layerData, this.layer); + + if (this.mesh.type !== 'composer') { + // 热力图的情况 + this.mesh.onBeforeRender = function (renderer) { + _this2._renderMask(renderer); + }; + + this.mesh.onAfterRender = function (renderer) { + var context = renderer.context; + context.clear(context.STENCIL_BUFFER_BIT); + context.disable(context.STENCIL_TEST); + }; + + this._object3D.add(this.mesh); + } else { + // 如果是热力图 + this._object3D = this.mesh; + } + + setTimeout(function () { + _this2.emit('tileLoaded'); + }, 0); + return this._object3D; + } + }, { + key: "_renderMask", + value: function _renderMask(renderer) { + var zoom = this.layer.scene.getZoom(); + (0, _object3dUtil.updateObjecteUniform)(this.mesh, { + u_time: this.layer.scene._engine.clock.getElapsedTime(), + u_zoom: zoom + }); + + if (this.layer.get('layerType') === 'point') { + // 点图层目前不需要mask + return; + } + + var maskScene = new THREE.Scene(); + this.maskScene = maskScene; + + var tileMesh = this._tileMaskMesh(); + + maskScene.add(tileMesh); + var context = renderer.context; + renderer.autoClear = false; + renderer.clearDepth(); + context.enable(context.STENCIL_TEST); + context.stencilOp(context.REPLACE, context.REPLACE, context.REPLACE); + context.stencilFunc(context.ALWAYS, 1, 0xffffffff); + context.clearStencil(0); + context.clear(context.STENCIL_BUFFER_BIT); + context.colorMask(false, false, false, false); // config the stencil buffer to collect data for testing + + this.layer.scene._engine.renderScene(maskScene); + + context.colorMask(true, true, true, true); + context.depthMask(false); + renderer.clearDepth(); // only render where stencil is set to 1 + + context.stencilFunc(context.EQUAL, 1, 0xffffffff); // draw if == 1 + + context.stencilOp(context.KEEP, context.KEEP, context.KEEP); + } + }, { + key: "_tileMaskMesh", + value: function _tileMaskMesh() { + var tilebound = this._tileBounds; + var bl = [tilebound.getBottomLeft().x, tilebound.getBottomLeft().y, 0]; + var br = [tilebound.getBottomRight().x, tilebound.getBottomRight().y, 0]; + var tl = [tilebound.getTopLeft().x, tilebound.getTopLeft().y, 0]; + var tr = [tilebound.getTopRight().x, tilebound.getTopRight().y, 0]; + var positions = [].concat(bl, tr, br, bl, tl, tr); + var geometry = new THREE.BufferGeometry(); + geometry.addAttribute('position', new THREE.Float32BufferAttribute(positions, 3)); + var maskMaterial = new _maskMaterial["default"](); + var maskMesh = new THREE.Mesh(geometry, maskMaterial); + return maskMesh; + } + }, { + key: "_abortRequest", + value: function _abortRequest() { + if (!this.xhrRequest) { + return; + } + + this.xhrRequest.abort(); + } + }, { + key: "getSelectFeature", + value: function getSelectFeature(id) { + var featurekey = this.layerSource.originData.featureKeys[id]; + + if (featurekey && featurekey.index !== undefined) { + var featureIndex = featurekey.index; + return this.layerSource.originData.dataArray[featureIndex]; + } + + return null; + } + }, { + key: "destroy", + value: function destroy() { + _get(_getPrototypeOf(VectorTile.prototype), "destroy", this).call(this); + + (0, _object3dUtil.destoryObject)(this.maskScene); + this._object3D = null; + this.maskScene = null; + this.layerData = null; + } + }]); + + return VectorTile; +}(_tile["default"]); + +exports["default"] = VectorTile; \ No newline at end of file diff --git a/lib/layer/tile/vector_tile.js b/lib/layer/tile/vector_tile.js new file mode 100644 index 0000000000..71c9489e66 --- /dev/null +++ b/lib/layer/tile/vector_tile.js @@ -0,0 +1,182 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _tile = _interopRequireDefault(require("./tile")); + +var _object3dUtil = require("../../util/object3d-util"); + +var THREE = _interopRequireWildcard(require("../../core/three")); + +var _maskMaterial = _interopRequireDefault(require("../../geom/material/tile/maskMaterial")); + +var _index = require("../render/index"); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var VectorTile = +/*#__PURE__*/ +function (_Tile) { + _inherits(VectorTile, _Tile); + + function VectorTile() { + _classCallCheck(this, VectorTile); + + return _possibleConstructorReturn(this, _getPrototypeOf(VectorTile).apply(this, arguments)); + } + + _createClass(VectorTile, [{ + key: "_createMesh", + value: function _createMesh() { + var _this = this; + + var layerData = this.layerData; + + if (this.layer.get('layerType') === 'point') { + this.layer.shape = this.layer._getShape(layerData); + } + + this.mesh = (0, _index.getRender)(this.layer.get('layerType'), this.layer.shape)(layerData, this.layer); + + if (this.mesh.type !== 'composer') { + // 热力图的情况 + this.mesh.onBeforeRender = function (renderer) { + _this._renderMask(renderer); + }; + + this.mesh.onAfterRender = function (renderer) { + var context = renderer.context; + context.clear(context.STENCIL_BUFFER_BIT); + context.disable(context.STENCIL_TEST); + }; + + this._object3D.add(this.mesh); + } else { + // 如果是热力图 + this._object3D = this.mesh; + } + + setTimeout(function () { + _this.emit('tileLoaded'); + }, 0); + return this._object3D; + } + }, { + key: "_renderMask", + value: function _renderMask(renderer) { + var zoom = this.layer.scene.getZoom(); + (0, _object3dUtil.updateObjecteUniform)(this.mesh, { + u_time: this.layer.scene._engine.clock.getElapsedTime(), + u_zoom: zoom + }); + + if (this.layer.get('layerType') === 'point') { + // 点图层目前不需要mask + return; + } + + var maskScene = new THREE.Scene(); + this.maskScene = maskScene; + + var tileMesh = this._tileMaskMesh(); + + maskScene.add(tileMesh); + var context = renderer.context; + renderer.autoClear = false; + renderer.clearDepth(); + context.enable(context.STENCIL_TEST); + context.stencilOp(context.REPLACE, context.REPLACE, context.REPLACE); + context.stencilFunc(context.ALWAYS, 1, 0xffffffff); + context.clearStencil(0); + context.clear(context.STENCIL_BUFFER_BIT); + context.colorMask(false, false, false, false); // config the stencil buffer to collect data for testing + + this.layer.scene._engine.renderScene(maskScene); + + context.colorMask(true, true, true, true); + context.depthMask(false); + renderer.clearDepth(); // only render where stencil is set to 1 + + context.stencilFunc(context.EQUAL, 1, 0xffffffff); // draw if == 1 + + context.stencilOp(context.KEEP, context.KEEP, context.KEEP); + } + }, { + key: "_tileMaskMesh", + value: function _tileMaskMesh() { + var tilebound = this._tileBounds; + var bl = [tilebound.getBottomLeft().x, tilebound.getBottomLeft().y, 0]; + var br = [tilebound.getBottomRight().x, tilebound.getBottomRight().y, 0]; + var tl = [tilebound.getTopLeft().x, tilebound.getTopLeft().y, 0]; + var tr = [tilebound.getTopRight().x, tilebound.getTopRight().y, 0]; + var positions = [].concat(bl, tr, br, bl, tl, tr); + var geometry = new THREE.BufferGeometry(); + geometry.addAttribute('position', new THREE.Float32BufferAttribute(positions, 3)); + var maskMaterial = new _maskMaterial["default"](); + var maskMesh = new THREE.Mesh(geometry, maskMaterial); + return maskMesh; + } + }, { + key: "_abortRequest", + value: function _abortRequest() { + if (!this.xhrRequest) { + return; + } + + this.xhrRequest.abort(); + } + }, { + key: "getSelectFeature", + value: function getSelectFeature(id) { + var featurekey = this.layerSource.originData.featureKeys[id]; + + if (featurekey && featurekey.index !== undefined) { + var featureIndex = featurekey.index; + return this.layerSource.originData.dataArray[featureIndex]; + } + + return null; + } + }, { + key: "destroy", + value: function destroy() { + _get(_getPrototypeOf(VectorTile.prototype), "destroy", this).call(this); + + (0, _object3dUtil.destoryObject)(this.maskScene); + this._object3D = null; + this.maskScene = null; + this.layerData = null; + } + }]); + + return VectorTile; +}(_tile["default"]); + +exports["default"] = VectorTile; \ No newline at end of file diff --git a/lib/layer/tile/vector_tile_layer.js b/lib/layer/tile/vector_tile_layer.js new file mode 100644 index 0000000000..c3126837c4 --- /dev/null +++ b/lib/layer/tile/vector_tile_layer.js @@ -0,0 +1,53 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _tile_layer = _interopRequireDefault(require("./tile_layer")); + +var _vector_tile = _interopRequireDefault(require("./vector_tile")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var VectorTileLayer = +/*#__PURE__*/ +function (_TileLayer) { + _inherits(VectorTileLayer, _TileLayer); + + function VectorTileLayer() { + _classCallCheck(this, VectorTileLayer); + + return _possibleConstructorReturn(this, _getPrototypeOf(VectorTileLayer).apply(this, arguments)); + } + + _createClass(VectorTileLayer, [{ + key: "_createTile", + value: function _createTile(key, layer) { + return new _vector_tile["default"](key, this.url, layer); + } + }]); + + return VectorTileLayer; +}(_tile_layer["default"]); + +exports["default"] = VectorTileLayer; \ No newline at end of file diff --git a/lib/layer/tile/vector_tile_mesh.js b/lib/layer/tile/vector_tile_mesh.js new file mode 100644 index 0000000000..f5e9c4220c --- /dev/null +++ b/lib/layer/tile/vector_tile_mesh.js @@ -0,0 +1,202 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _object3dUtil = require("../../util/object3d-util"); + +var THREE = _interopRequireWildcard(require("../../core/three")); + +var _maskMaterial = _interopRequireDefault(require("../../geom/material/tile/maskMaterial")); + +var _geoCoord = require("@antv/geo-coord"); + +var _index = require("../render/index"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var r2d = 180 / Math.PI; + +var VectorTileMesh = +/*#__PURE__*/ +function () { + function VectorTileMesh(layer, data) { + _classCallCheck(this, VectorTileMesh); + + this.layer = layer; + this._object3D = new THREE.Object3D(); + this._object3D.name = data.tileId; + this._tile = data.tileId.split('_').map(function (v) { + return v * 1; + }); + this._tileLnglatBounds = this._tileLnglatBounds(this._tile); + this._tileBounds = this._tileBounds(this._tileLnglatBounds); + this._center = this._tileBounds.getCenter(); + this._centerLnglat = this._tileLnglatBounds.getCenter(); + + this._init(data); + + this.maskScene = new THREE.Scene(); + + var tileMesh = this._tileMaskMesh(); // this._object3D.add(tileMesh); + + + this.maskScene.add(tileMesh); + } + + _createClass(VectorTileMesh, [{ + key: "_init", + value: function _init(data) { + this._createMesh(data); + } + }, { + key: "_createMesh", + value: function _createMesh(data) { + var _this = this; + + this.mesh = (0, _index.getRender)(this.layer.get('type'), data.shape)(null, this.layer, data.buffer); + + if (this.mesh.type !== 'composer') { + // 热力图的情况 + this.mesh.onBeforeRender = function (renderer) { + _this._renderMask(renderer); + + var zoom = _this.layer.scene.getZoom(); + + (0, _object3dUtil.updateObjecteUniform)(_this._object3D, { + u_time: _this.layer.scene._engine.clock.getElapsedTime(), + u_zoom: zoom + }); + }; + + this.mesh.onAfterRender = function (renderer) { + var context = renderer.context; + context.clear(context.STENCIL_BUFFER_BIT); + context.disable(context.STENCIL_TEST); + }; + + this._object3D.add(this.mesh); + } else { + // 如果是热力图 + this._object3D = this.mesh; + } + + return this._object3D; + } + }, { + key: "getMesh", + value: function getMesh() { + return this._object3D; + } + }, { + key: "_renderMask", + value: function _renderMask(renderer) { + if (this.layer.get('layerType') === 'point') { + // 点图层目前不需要mask + return; + } + + var context = renderer.context; + renderer.autoClear = false; + renderer.clearDepth(); + context.enable(context.STENCIL_TEST); + context.stencilOp(context.REPLACE, context.REPLACE, context.REPLACE); + context.stencilFunc(context.ALWAYS, 1, 0xffffffff); + context.clearStencil(0); + context.clear(context.STENCIL_BUFFER_BIT); + context.colorMask(false, false, false, false); // config the stencil buffer to collect data for testing + + this.layer.scene._engine.renderScene(this.maskScene); + + context.colorMask(true, true, true, true); + context.depthMask(false); + renderer.clearDepth(); // only render where stencil is set to 1 + + context.stencilFunc(context.EQUAL, 1, 0xffffffff); // draw if == 1 + + context.stencilOp(context.KEEP, context.KEEP, context.KEEP); + } + }, { + key: "_tileMaskMesh", + value: function _tileMaskMesh() { + var tilebound = this._tileBounds; + var bl = [tilebound.getBottomLeft().x, tilebound.getBottomLeft().y, 0]; + var br = [tilebound.getBottomRight().x, tilebound.getBottomRight().y, 0]; + var tl = [tilebound.getTopLeft().x, tilebound.getTopLeft().y, 0]; + var tr = [tilebound.getTopRight().x, tilebound.getTopRight().y, 0]; + var positions = new Float32Array([].concat(bl, tr, br, bl, tl, tr)); + var geometry = new THREE.BufferGeometry(); + geometry.addAttribute('position', new THREE.Float32BufferAttribute(positions, 3)); + var maskMaterial = new _maskMaterial["default"](); + var maskMesh = new THREE.Mesh(geometry, maskMaterial); + return maskMesh; + } + }, { + key: "getSelectFeature", + value: function getSelectFeature(id) { + var featurekey = this.layerSource.originData.featureKeys[id]; + + if (featurekey && featurekey.index !== undefined) { + var featureIndex = featurekey.index; + return this.layerSource.originData.dataArray[featureIndex]; + } + + return null; + } + }, { + key: "_tileBounds", + value: function _tileBounds(lnglatBound) { + var ne = this.layer.scene.project([lnglatBound.getNorthEast().lng, lnglatBound.getNorthEast().lat]); + var sw = this.layer.scene.project([lnglatBound.getSouthWest().lng, lnglatBound.getSouthWest().lat]); + return (0, _geoCoord.toBounds)(sw, ne); + } // Get tile bounds in WGS84 coordinates + + }, { + key: "_tileLnglatBounds", + value: function _tileLnglatBounds(tile) { + var e = this._tile2lng(tile[0] + 1, tile[2]); + + var w = this._tile2lng(tile[0], tile[2]); + + var s = this._tile2lat(tile[1] + 1, tile[2]); + + var n = this._tile2lat(tile[1], tile[2]); + + return (0, _geoCoord.toLngLatBounds)([w, n], [e, s]); + } + }, { + key: "_tile2lng", + value: function _tile2lng(x, z) { + return x / Math.pow(2, z) * 360 - 180; + } + }, { + key: "_tile2lat", + value: function _tile2lat(y, z) { + var n = Math.PI - 2 * Math.PI * y / Math.pow(2, z); + return r2d * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))); + } + }, { + key: "destroy", + value: function destroy() { + (0, _object3dUtil.destoryObject)(this._object3D); + (0, _object3dUtil.destoryObject)(this.maskScene); + this._object3D = null; + this.maskScene = null; + this.layerData = null; + } + }]); + + return VectorTileMesh; +}(); + +exports["default"] = VectorTileMesh; \ No newline at end of file diff --git a/lib/map/AMap.js b/lib/map/AMap.js new file mode 100644 index 0000000000..87f7c9fa92 --- /dev/null +++ b/lib/map/AMap.js @@ -0,0 +1,296 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("../core/base")); + +var _global = _interopRequireDefault(require("../global")); + +var Theme = _interopRequireWildcard(require("../theme/index")); + +var _util = _interopRequireDefault(require("../util")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var DEG2RAD = Math.PI / 180; + +var GaodeMap = +/*#__PURE__*/ +function (_Base) { + _inherits(GaodeMap, _Base); + + _createClass(GaodeMap, [{ + key: "getDefaultCfg", + value: function getDefaultCfg() { + return _util["default"].assign(_global["default"].scene, { + resizeEnable: true, + viewMode: '3D' + }); + } + }], [{ + key: "project", + value: function project(lnglat) { + var maxs = 85.0511287798; + var lat = Math.max(Math.min(maxs, lnglat[1]), -maxs); + var scale = 256 << 20; + var d = Math.PI / 180; + var x = lnglat[0] * d; + var y = lat * d; + y = Math.log(Math.tan(Math.PI / 4 + y / 2)); + var a = 0.5 / Math.PI, + b = 0.5, + c = -0.5 / Math.PI; + d = 0.5; + x = scale * (a * x + b) - 215440491; + y = -(scale * (c * y + d) - 106744817); + return { + x: x, + y: y + }; + } + }]); + + function GaodeMap(cfg) { + var _this; + + _classCallCheck(this, GaodeMap); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(GaodeMap).call(this, cfg)); + _this.container = document.getElementById(_this.get('id')); + + _this.initMap(); + + _this.addOverLayer(); + + setTimeout(function () { + _this.emit('mapLoad'); + }, 100); + return _this; + } + + _createClass(GaodeMap, [{ + key: "initMap", + value: function initMap() { + var mapStyle = this.get('mapStyle'); + + if (mapStyle) { + switch (mapStyle) { + case 'dark': + this.set('mapStyle', Theme.DarkTheme.mapStyle); + break; + + case 'light': + this.set('mapStyle', Theme.LightTheme.mapStyle); + break; + + default: + this.set('mapStyle', mapStyle); + } + } + + this.set('zooms', [this.get('minZoom'), this.get('maxZoom')]); + var map = this.get('map'); + + if (map instanceof AMap.Map) { + this.map = map; + this.container = map.getContainer(); + this.get('mapStyle') && this.map.setMapStyle(this.get('mapStyle')); + } else { + this.map = new AMap.Map(this.container, this._attrs); + } + } + }, { + key: "asyncCamera", + value: function asyncCamera(engine) { + var _this2 = this; + + this._engine = engine; + var camera = engine._camera; + this.map.on('camerachange', function (e) { + var mapCamera = e.camera; + var fov = mapCamera.fov, + near = mapCamera.near, + far = mapCamera.far, + height = mapCamera.height, + pitch = mapCamera.pitch, + rotation = mapCamera.rotation, + aspect = mapCamera.aspect; + pitch *= DEG2RAD; + rotation *= DEG2RAD; + camera.fov = 180 * fov / Math.PI; + camera.aspect = aspect; + camera.near = near; + camera.far = far; + camera.updateProjectionMatrix(); + camera.position.z = height * Math.cos(pitch); + camera.position.x = height * Math.sin(pitch) * Math.sin(rotation); + camera.position.y = -height * Math.sin(pitch) * Math.cos(rotation); + camera.up.x = -Math.cos(pitch) * Math.sin(rotation); + camera.up.y = Math.cos(pitch) * Math.cos(rotation); + camera.up.z = Math.sin(pitch); + camera.lookAt(0, 0, 0); + camera.position.x += e.camera.position.x; + camera.position.y += -e.camera.position.y; + + _this2._engine.update(); + }); + } + }, { + key: "projectFlat", + value: function projectFlat(lnglat) { + return this.map.lngLatToGeodeticCoord(lnglat); + } + }, { + key: "getCenter", + value: function getCenter() { + return this.map.getCenter(); + } + }, { + key: "getCenterFlat", + value: function getCenterFlat() { + return this.projectFlat(this.getCenter()); + } + }, { + key: "addOverLayer", + value: function addOverLayer() { + var canvasContainer = this.container instanceof HTMLElement ? this.container : document.getElementById(this.container); + this.canvasContainer = canvasContainer; + this.renderDom = document.createElement('div'); + this.renderDom.style.cssText += 'position: absolute;top: 0; z-index:1;height: 100%;width: 100%;pointer-events: none;'; + this.renderDom.id = 'l7_canvaslayer'; + canvasContainer.appendChild(this.renderDom); + } + }, { + key: "mixMap", + value: function mixMap(scene) { + var map = this.map; + scene.project = GaodeMap.project; + + scene.getZoom = function () { + return map.getZoom(); + }; + + scene.getCenter = function () { + return map.getCenter(); + }; + + scene.getSize = function () { + return map.getSize(); + }; + + scene.getPitch = function () { + return map.getPitch(); + }; + + scene.getRotation = function () { + return map.getRotation(); + }; + + scene.getStatus = function () { + return map.getStatus(); + }; + + scene.getScale = function () { + return map.getScale(); + }; + + scene.getZoom = function () { + return map.getZoom(); + }; + + scene.setZoom = function (zoom) { + return map.setZoom(zoom); + }; + + scene.getBounds = function () { + return map.getBounds(); + }; + + scene.setZoomAndCenter = function (zoom, center) { + var lnglat = new AMap.LngLat(center[0], center[1]); + return map.setZoomAndCenter(zoom, lnglat); + }; + + scene.setBounds = function (extent) { + return map.setBounds(new AMap.Bounds([extent[0], extent[1]], [extent[2], extent[3]])); + }; + + scene.setRotation = function (rotation) { + return map.setRotation(rotation); + }; + + scene.setStatus = function (status) { + return map.setStatus(status); + }; + + scene.zoomIn = function () { + return map.zoomIn(); + }; + + scene.zoomOut = function () { + return map.zoomOut(); + }; + + scene.panTo = function (lnglat) { + return map.panTo(new AMap.LngLat(lnglat[0], lnglat[1])); + }; + + scene.panBy = function (x, y) { + return map.panBy(x, y); + }; + + scene.setPitch = function (pitch) { + return map.setPitch(pitch); + }; + + scene.pixelToLngLat = function (pixel) { + var ll = new AMap.Pixel(pixel[0], pixel[1]); + return map.pixelToLngLat(ll); + }; + + scene.lngLatToPixel = function (lnglat) { + return map.lngLatToPixel(new AMap.LngLat(lnglat[0], lnglat[1])); + }; + + scene.setMapStyle = function (style) { + return map.setMapStyle(style); + }; + + scene.fitBounds = function (extent) { + return map.setBounds(new AMap.Bounds([extent[0], extent[1]], [extent[2], extent[3]])); + }; + + scene.containerToLngLat = function (pixel) { + var ll = new AMap.Pixel(pixel.x, pixel.y); + return map.containerToLngLat(ll); + }; + } + }]); + + return GaodeMap; +}(_base["default"]); + +exports["default"] = GaodeMap; \ No newline at end of file diff --git a/lib/map/baseMap.js b/lib/map/baseMap.js new file mode 100644 index 0000000000..9a390c31f7 --- /dev/null +++ b/lib/map/baseMap.js @@ -0,0 +1 @@ +"use strict"; \ No newline at end of file diff --git a/lib/map/gaodeMap.js b/lib/map/gaodeMap.js new file mode 100644 index 0000000000..0b5e925221 --- /dev/null +++ b/lib/map/gaodeMap.js @@ -0,0 +1,129 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var GaodeMap = +/*#__PURE__*/ +function () { + function GaodeMap(map) { + _classCallCheck(this, GaodeMap); + + this.map = map; + } + + _createClass(GaodeMap, [{ + key: "getZoom", + value: function getZoom() { + return this.map.getZoom(); + } + }, { + key: "getCenter", + value: function getCenter() { + return this.map.getCenter(); + } + }, { + key: "getSize", + value: function getSize() { + return this.map.getSize(); + } + }, { + key: "getPitch", + value: function getPitch() { + return this.map.getPitch(); + } + }, { + key: "getRotation", + value: function getRotation() { + return this.map.getRotation(); + } + }, { + key: "getStatus", + value: function getStatus() { + return this.map.getStatus(); + } + }, { + key: "getScale", + value: function getScale() { + return this.map.getScale(); + } + }, { + key: "setZoom", + value: function setZoom(zoom) { + return this.map.setZoom(zoom); + } + }, { + key: "setCenter", + value: function setCenter(lnglat) { + return this.map.setCenter(lnglat); + } + }, { + key: "setBounds", + value: function setBounds(bounds) { + return this.map.setBounds(bounds); + } + }, { + key: "setRotation", + value: function setRotation(rotation) { + return this.map.setRotation(rotation); + } + }, { + key: "zoomIn", + value: function zoomIn() { + return this.map.zoomIn(); + } + }, { + key: "zoomOut", + value: function zoomOut() { + return this.map.zoomOut(); + } + }, { + key: "panTo", + value: function panTo(lngLat) { + return this.map.panTo(lngLat); + } + }, { + key: "panBy", + value: function panBy(x, y) { + return this.map.panBy(x, y); + } + }, { + key: "setPitch", + value: function setPitch(pitch) { + return this.map.setPitch(pitch); + } + }, { + key: "pixelToLngLat", + value: function pixelToLngLat(lngLat, level) { + return this.map.pixelToLngLat(lngLat, level); + } + }, { + key: "lngLatToPixel", + value: function lngLatToPixel(lngLat, level) { + return this.map.lnglatToPixel(lngLat, level); + } + }, { + key: "containerToLngLat", + value: function containerToLngLat(pixel) { + var ll = new AMap.Pixel(pixel.x, pixel.y); + return this.map.containerToLngLat(ll); + } + }, { + key: "setMapStyle", + value: function setMapStyle(style) { + return this.map.setMapStyle(style); + } + }]); + + return GaodeMap; +}(); + +exports.default = GaodeMap; \ No newline at end of file diff --git a/lib/map/index.js b/lib/map/index.js new file mode 100644 index 0000000000..7450d26db9 --- /dev/null +++ b/lib/map/index.js @@ -0,0 +1,47 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "MapBox", { + enumerable: true, + get: function get() { + return _mapbox["default"]; + } +}); +Object.defineProperty(exports, "AMap", { + enumerable: true, + get: function get() { + return _AMap["default"]; + } +}); +exports.registerMap = exports.getMap = void 0; + +var _mapbox = _interopRequireDefault(require("./mapbox")); + +var _AMap = _interopRequireDefault(require("./AMap")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +var MapType = { + amap: _AMap["default"], + mapbox: _mapbox["default"] +}; + +var getMap = function getMap(type) { + return MapType[type.toLowerCase()]; +}; + +exports.getMap = getMap; + +var registerMap = function registerMap(type, map) { + if (getMap(type)) { + throw new Error("Map type '".concat(type, "' existed.")); + } + + map.type = type; // 存储到 map 中 + + MapType[type.toLowerCase()] = map; +}; + +exports.registerMap = registerMap; \ No newline at end of file diff --git a/lib/map/mapbox.js b/lib/map/mapbox.js new file mode 100644 index 0000000000..9cb7ad9137 --- /dev/null +++ b/lib/map/mapbox.js @@ -0,0 +1,224 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("../core/base")); + +var _util = _interopRequireDefault(require("../util")); + +var _global = _interopRequireDefault(require("../global")); + +var THREE = _interopRequireWildcard(require("../core/three")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var WORLD_SIZE = 512; +var MERCATOR_A = 6378137.0; +var WORLD_SCALE = 1 / 100; +var PROJECTION_WORLD_SIZE = WORLD_SIZE / (MERCATOR_A * Math.PI) / 2; + +var MapBox = +/*#__PURE__*/ +function (_Base) { + _inherits(MapBox, _Base); + + _createClass(MapBox, [{ + key: "getDefaultCfg", + value: function getDefaultCfg() { + return _util["default"].assign(_global["default"].scene, { + resizeEnable: true, + viewMode: '3D' + }); + } + }], [{ + key: "project", + value: function project(lnglat) { + var d = Math.PI / 180; + var x = -MERCATOR_A * lnglat[0] * d * PROJECTION_WORLD_SIZE; + var y = -MERCATOR_A * Math.log(Math.tan(Math.PI * 0.25 + 0.5 * lnglat[1] * d)) * PROJECTION_WORLD_SIZE; + return { + x: x, + y: y + }; + } + }]); + + function MapBox(cfg) { + var _this; + + _classCallCheck(this, MapBox); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(MapBox).call(this, cfg)); + _this.container = _this.get('container'); + + _this.initMap(); + + _this.addOverLayer(); + + setTimeout(function () { + _this.emit('mapLoad'); + }, 100); + return _this; + } + + _createClass(MapBox, [{ + key: "initMap", + value: function initMap() { + mapboxgl.accessToken = 'pk.eyJ1IjoibHp4dWUiLCJhIjoiYnhfTURyRSJ9.Ugm314vAKPHBzcPmY1p4KQ'; + this.map = new mapboxgl.Map(this._attrs); + } + }, { + key: "asyncCamera", + value: function asyncCamera(engine) { + var _this2 = this; + + this.engine = engine; + var camera = engine._camera; + var scene = engine.world; + var pickScene = engine._picking.world; + camera.matrixAutoUpdate = false; + scene.position.x = scene.position.y = WORLD_SIZE / 2; + scene.matrixAutoUpdate = false; + pickScene.position.x = pickScene.position.y = WORLD_SIZE / 2; + pickScene.matrixAutoUpdate = false; + this.updateCamera(); + this.map.on('move', function () { + _this2.updateCamera(); + }); + } + }, { + key: "updateCamera", + value: function updateCamera() { + var engine = this.engine; + var scene = engine.world; + var pickScene = engine._picking.world; + var camera = engine._camera; // Build a projection matrix, paralleling the code found in Mapbox GL JS + + var fov = 0.6435011087932844; + var cameraToCenterDistance = 0.5 / Math.tan(fov / 2) * this.map.transform.height * WORLD_SCALE; + var halfFov = fov / 2; + var groundAngle = Math.PI / 2 + this.map.transform._pitch; + var topHalfSurfaceDistance = Math.sin(halfFov) * cameraToCenterDistance / Math.sin(Math.PI - groundAngle - halfFov); // Calculate z distance of the farthest fragment that should be rendered. + + var furthestDistance = Math.cos(Math.PI / 2 - this.map.transform._pitch) * topHalfSurfaceDistance + cameraToCenterDistance; // Add a bit extra to avoid precision problems when a fragment's distance is exactly `furthestDistance` + + var farZ = furthestDistance * 1.1; + + if (this.pitch > 50) { + farZ = 1000; + } + + var _this$map$transform$p = this.map.transform.point, + x = _this$map$transform$p.x, + y = _this$map$transform$p.y; + camera.projectionMatrix = this.makePerspectiveMatrix(fov, this.map.transform.width / this.map.transform.height, 1, farZ); + var cameraWorldMatrix = new THREE.Matrix4(); + var cameraTranslateZ = new THREE.Matrix4().makeTranslation(0, 0, cameraToCenterDistance); + var cameraRotateX = new THREE.Matrix4().makeRotationX(this.map.transform._pitch); + var cameraRotateZ = new THREE.Matrix4().makeRotationZ(this.map.transform.angle); + var cameraTranslateXY = new THREE.Matrix4().makeTranslation(x * WORLD_SCALE, -y * WORLD_SCALE, 0); // const cameraTranslateCenter = new THREE.Matrix4().makeTranslation(0, 0, cameraToCenterDistance); + // Unlike the Mapbox GL JS camera, separate camera translation and rotation out into its world matrix + // If this is applied directly to the projection matrix, it will work OK but break raycasting + + cameraWorldMatrix.premultiply(cameraTranslateZ).premultiply(cameraRotateX).premultiply(cameraRotateZ).premultiply(cameraTranslateXY); + camera.matrixWorld.copy(cameraWorldMatrix); + var zoomPow = this.map.transform.scale * WORLD_SCALE; // Handle scaling and translation of objects in the map in the world's matrix transform, not the camera + + var scale = new THREE.Matrix4(); + var translateCenter = new THREE.Matrix4(); + var translateMap = new THREE.Matrix4(); + var rotateMap = new THREE.Matrix4(); + scale.makeScale(zoomPow, zoomPow, 1.0); + translateCenter.makeTranslation(WORLD_SIZE / 2, -WORLD_SIZE / 2, 0); + translateMap.makeTranslation(-this.map.transform.x, this.map.transform.y, 0); + rotateMap.makeRotationZ(Math.PI); + scene.matrix = new THREE.Matrix4(); + scene.matrix.premultiply(rotateMap).premultiply(translateCenter).premultiply(scale); + pickScene.matrix = new THREE.Matrix4(); + pickScene.matrix.premultiply(rotateMap).premultiply(translateCenter).premultiply(scale); + } + }, { + key: "makePerspectiveMatrix", + value: function makePerspectiveMatrix(fovy, aspect, near, far) { + var out = new THREE.Matrix4(); + var f = 1.0 / Math.tan(fovy / 2), + nf = 1 / (near - far); + var newMatrix = [f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, (far + near) * nf, -1, 0, 0, 2 * far * near * nf, 0]; + out.elements = newMatrix; + return out; + } + }, { + key: "projectFlat", + value: function projectFlat(lnglat) { + return this.map.lngLatToGeodeticCoord(lnglat); + } + }, { + key: "getCenter", + value: function getCenter() { + return this.map.getCenter(); + } + }, { + key: "getCenterFlat", + value: function getCenterFlat() { + return this.projectFlat(this.getCenter()); + } + }, { + key: "addOverLayer", + value: function addOverLayer() { + var canvasContainer = document.getElementById(this.container); + this.canvasContainer = canvasContainer; + this.renderDom = document.createElement('div'); + this.renderDom.style.cssText += 'position: absolute;top: 0; z-index:10;height: 100%;width: 100%;pointer-events: none;'; + this.renderDom.id = 'l7_canvaslayer'; + canvasContainer.appendChild(this.renderDom); + } + }, { + key: "mixMap", + value: function mixMap(scene) { + var map = this.map; + + scene.getZoom = function () { + return map.getZoom(); + }; + + scene.getCenter = function () { + return map.getCenter(); + }; + + scene.getPitch = function () { + return map.getPitch(); + }; + + scene.containerToLngLat = function (point) { + return map.unproject(point); + }; + } + }]); + + return MapBox; +}(_base["default"]); + +exports["default"] = MapBox; \ No newline at end of file diff --git a/lib/map/provider.js b/lib/map/provider.js new file mode 100644 index 0000000000..8f1ec441d7 --- /dev/null +++ b/lib/map/provider.js @@ -0,0 +1,160 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.MapProvider = void 0; + +var _base = _interopRequireDefault(require("../core/base")); + +var Theme = _interopRequireWildcard(require("../theme/index")); + +var _util = _interopRequireDefault(require("../util")); + +var _global = require("../global"); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var DEG2RAD = Math.PI / 180; + +var MapProvider = +/*#__PURE__*/ +function (_Base) { + _inherits(MapProvider, _Base); + + _createClass(MapProvider, [{ + key: "getDefaultCfg", + value: function getDefaultCfg() { + return _util.default.assign(_global.scene, { + resizeEnable: true, + viewMode: '3D' + }); + } + }]); + + function MapProvider(container, cfg) { + var _this; + + _classCallCheck(this, MapProvider); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(MapProvider).call(this, cfg)); + _this.container = container; + + _this.initMap(); + + _this.addOverLayer(); + + setTimeout(function () { + _this.emit('mapLoad'); + }, 100); + return _this; + } + + _createClass(MapProvider, [{ + key: "initMap", + value: function initMap() { + var mapStyle = this.get('mapStyle'); + + switch (mapStyle) { + case 'dark': + this.set('mapStyle', Theme.DarkTheme.mapStyle); + break; + + case 'light': + this.set('mapStyle', Theme.LightTheme.mapStyle); + break; + + default: + this.set('mapStyle', mapStyle); + } + + this.set('zooms', [this.get('minZoom'), this.get('maxZoom')]); + this.map = new AMap.Map(this.container, this._attrs); + } + }, { + key: "asyncCamera", + value: function asyncCamera(engine) { + this._engine = engine; + var camera = engine._camera; + var scene = engine._scene; + var pickScene = engine._picking._pickingScene; + this.map.on('camerachange', function (e) { + var mapCamera = e.camera; + var fov = mapCamera.fov, + near = mapCamera.near, + far = mapCamera.far, + height = mapCamera.height, + pitch = mapCamera.pitch, + rotation = mapCamera.rotation, + aspect = mapCamera.aspect; + pitch *= DEG2RAD; + rotation *= DEG2RAD; + camera.fov = 180 * fov / Math.PI; + camera.aspect = aspect; + camera.near = near; + camera.far = far; + camera.updateProjectionMatrix(); + camera.position.z = height * Math.cos(pitch); + camera.position.x = height * Math.sin(pitch) * Math.sin(rotation); + camera.position.y = -height * Math.sin(pitch) * Math.cos(rotation); + camera.up.x = -Math.cos(pitch) * Math.sin(rotation); + camera.up.y = Math.cos(pitch) * Math.cos(rotation); + camera.up.z = Math.sin(pitch); + camera.lookAt(0, 0, 0); + scene.position.x = -e.camera.position.x; + scene.position.y = e.camera.position.y; + pickScene.position.x = -e.camera.position.x; + pickScene.position.y = e.camera.position.y; + }); + } + }, { + key: "projectFlat", + value: function projectFlat(lnglat) { + return this.map.lngLatToGeodeticCoord(lnglat); + } + }, { + key: "getCenter", + value: function getCenter() { + return this.map.getCenter(); + } + }, { + key: "getCenterFlat", + value: function getCenterFlat() { + return this.projectFlat(this.getCenter()); + } + }, { + key: "addOverLayer", + value: function addOverLayer() { + var canvasContainer = document.getElementById(this.container); + this.canvasContainer = canvasContainer; + this.renderDom = document.createElement('div'); + this.renderDom.style.cssText += 'position: absolute;top: 0; z-index:1;height: 100%;width: 100%;pointer-events: none;'; + this.renderDom.id = 'l7_canvaslayer'; + canvasContainer.appendChild(this.renderDom); + } + }]); + + return MapProvider; +}(_base.default); + +exports.MapProvider = MapProvider; \ No newline at end of file diff --git a/lib/scale/auto/cat.js b/lib/scale/auto/cat.js new file mode 100644 index 0000000000..40ddb1e72b --- /dev/null +++ b/lib/scale/auto/cat.js @@ -0,0 +1,94 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = _default; + +var _util = _interopRequireDefault(require("../../util")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +/** + * @fileOverview 计算分类的的坐标点 + * @author dxq613@gmail.com + */ +var MAX_COUNT = 8; +var SUB_COUNT = 4; // 控制个数不能过小 + +function getSimpleArray(data) { + var arr = []; + + _util["default"].each(data, function (sub) { + if (_util["default"].isArray(sub)) { + arr = arr.concat(sub); + } else { + arr.push(sub); + } + }); + + return arr; +} + +function getGreatestFactor(count, number) { + var i; + + for (i = number; i > 0; i--) { + if (count % i === 0) { + break; + } + } // 如果是素数,没有可以整除的数字 + + + if (i === 1) { + for (i = number; i > 0; i--) { + if ((count - 1) % i === 0) { + break; + } + } + } + + return i; +} + +function _default(info) { + var rst = {}; + var ticks = []; + var maxCount = info.maxCount || MAX_COUNT; + var categories = getSimpleArray(info.data); + var length = categories.length; + var tickCount = getGreatestFactor(length - 1, maxCount - 1) + 1; // 如果计算出来只有两个坐标点,则直接使用传入的 maxCount + + if (tickCount === 2) { + tickCount = maxCount; + } else if (tickCount < maxCount - SUB_COUNT) { + tickCount = maxCount - SUB_COUNT; + } + + var step = parseInt(length / (tickCount - 1), 10); + var groups = categories.map(function (e, i) { + return i % step === 0 ? categories.slice(i, i + step) : null; + }).filter(function (e) { + return e; + }); + + if (categories.length) { + ticks.push(categories[0]); + } + + for (var i = 1; i < groups.length && i * step < length - step; i++) { + ticks.push(groups[i][0]); + } + + if (categories.length) { + var last = categories[length - 1]; + + if (ticks.indexOf(last) === -1) { + ticks.push(last); + } + } + + rst.categories = categories; + rst.ticks = ticks; + return rst; +} \ No newline at end of file diff --git a/lib/scale/auto/number.js b/lib/scale/auto/number.js new file mode 100644 index 0000000000..7a432bef42 --- /dev/null +++ b/lib/scale/auto/number.js @@ -0,0 +1,151 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = _default; + +var _util = _interopRequireDefault(require("../../util")); + +var _util2 = _interopRequireDefault(require("./util")); + +var _global = _interopRequireDefault(require("../../global")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +/** + * @fileOverview 自动计算数字坐标轴 + * @author dxq613@gmail.com + */ +var MIN_COUNT = 5; +var MAX_COUNT = 7; + +function _default(info) { + var min = info.min; + var max = info.max; + var interval = info.interval; + var ticks = []; + var minCount = info.minCount || MIN_COUNT; + var maxCount = info.maxCount || MAX_COUNT; + var isFixedCount = minCount === maxCount; // 是否限定死了个数 + + var minLimit = _util["default"].isNil(info.minLimit) ? -Infinity : info.minLimit; // 限定的最小值 + + var maxLimit = _util["default"].isNil(info.maxLimit) ? Infinity : info.maxLimit; // 限定最大值 + + var avgCount = (minCount + maxCount) / 2; + var count = avgCount; // 用户传入的逼近数组 + + var snapArray = info.snapArray ? info.snapArray : isFixedCount ? _global["default"].snapCountArray : _global["default"].snapArray; // 如果限定大小范围,同时大小范围等于用户传入的范围,同时限定了个数,interval 按照个数均分 + + if (min === minLimit && max === maxLimit && isFixedCount) { + interval = (max - min) / (count - 1); + } + + if (_util["default"].isNil(min)) { + min = 0; + } + + if (_util["default"].isNil(max)) { + max = 0; + } + + if (max === min) { + if (min === 0) { + max = 1; + } else { + if (min > 0) { + min = 0; + } else { + max = 0; + } + } + + if (max - min < 5 && !interval && max - min >= 1) { + interval = 1; + } + } + + if (_util["default"].isNil(interval)) { + // 计算间距 + var temp = (max - min) / (avgCount - 1); + interval = _util2["default"].snapFactorTo(temp, snapArray, 'ceil'); + + if (maxCount !== minCount) { + count = parseInt((max - min) / interval, 10); + + if (count > maxCount) { + count = maxCount; + } + + if (count < minCount) { + count = minCount; + } // 不确定tick的个数时,使得tick偏小 + + + interval = _util2["default"].snapFactorTo((max - min) / (count - 1), snapArray, 'floor'); + } + } + + if (info.interval || maxCount !== minCount) { + // 校正 max 和 min + max = Math.min(_util2["default"].snapMultiple(max, interval, 'ceil'), maxLimit); // 向上逼近 + + min = Math.max(_util2["default"].snapMultiple(min, interval, 'floor'), minLimit); // 向下逼近 + + count = Math.round((max - min) / interval); + min = _util["default"].fixedBase(min, interval); + max = _util["default"].fixedBase(max, interval); + } else { + avgCount = parseInt(avgCount, 10); // 取整 + + var avg = (max + min) / 2; + + var avgTick = _util2["default"].snapMultiple(avg, interval, 'ceil'); + + var sideCount = Math.floor((avgCount - 2) / 2); + var maxTick = avgTick + sideCount * interval; + var minTick; + + if (avgCount % 2 === 0) { + minTick = avgTick - sideCount * interval; + } else { + minTick = avgTick - (sideCount + 1) * interval; + } + + if (maxTick < max) { + maxTick = maxTick + interval; + } + + if (minTick > min) { + minTick = minTick - interval; + } + + max = _util["default"].fixedBase(maxTick, interval); + min = _util["default"].fixedBase(minTick, interval); + } + + max = Math.min(max, maxLimit); + min = Math.max(min, minLimit); + ticks.push(min); + + for (var i = 1; i < count; i++) { + var tickValue = _util["default"].fixedBase(interval * i + min, interval); + + if (tickValue < max) { + ticks.push(tickValue); + } + } + + if (ticks[ticks.length - 1] < max) { + ticks.push(max); + } + + return { + min: min, + max: max, + interval: interval, + count: count, + ticks: ticks + }; +} \ No newline at end of file diff --git a/lib/scale/auto/time.js b/lib/scale/auto/time.js new file mode 100644 index 0000000000..c233b3875f --- /dev/null +++ b/lib/scale/auto/time.js @@ -0,0 +1,187 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = _default; + +var _util = _interopRequireDefault(require("../../util")); + +var _util2 = _interopRequireDefault(require("./util")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +/** + * @fileOverview 计算时间坐标轴 + * @author dxq613@gmail.com + */ +var MAX_COUNT = 6; +var SNAP_ARRAY = [1, 2, 4, 6, 8, 12]; +var MINUTE_MS = 60 * 1000; +var HOUR_MS = 3600 * 1000; +var DAY_MS = 24 * 3600 * 1000; + +function getYear(date) { + return new Date(date).getFullYear(); +} + +function createYear(year) { + return new Date(year, 0, 1).getTime(); +} + +function getMonth(date) { + return new Date(date).getMonth(); +} + +function diffMonth(min, max) { + var minYear = getYear(min); + var maxYear = getYear(max); + var minMonth = getMonth(min); + var maxMonth = getMonth(max); + return (maxYear - minYear) * 12 + (maxMonth - minMonth) % 12; +} + +function creatMonth(year, month) { + return new Date(year, month, 1).getTime(); +} + +function diffDay(min, max) { + return Math.ceil((max - min) / DAY_MS); +} + +function diffHour(min, max) { + return Math.ceil((max - min) / HOUR_MS); +} + +function diffMinus(min, max) { + return Math.ceil((max - min) / (60 * 1000)); +} + +function _default(info) { + var minInterval = info.minInterval; + var ticks = []; + var min = info.min; + var max = info.max; + var interval = info.interval; + var count; // 如果最大值和最小值相等,则设置最大值大于最小值一天 + + if (max === min) { + max = min + DAY_MS; + } // 计算间距 + + + if (_util["default"].isNil(interval)) { + var innerTime = max - min; + var dms = DAY_MS; // 天代表的秒 + + var yms = 365 * dms; // 年代表的秒 + + interval = parseInt(innerTime / (info.maxCount || MAX_COUNT), 10); + + if (minInterval && minInterval > interval) { + interval = minInterval; + } + + var yfactor = interval / yms; + var minYear = getYear(min); // 大于半年 + + if (yfactor > 0.51) { + var year = Math.ceil(yfactor); // interval = year * yms; + + var maxYear = getYear(max); + + for (var i = minYear; i <= maxYear + year; i = i + year) { + ticks.push(createYear(i)); + } + + interval = null; + } else if (yfactor > 0.0834) { + // 大于一个月 + var month = Math.ceil(yfactor / 0.0834); + var mmMoth = getMonth(min); + var dMonths = diffMonth(min, max); + + for (var _i = 0; _i <= dMonths + month; _i = _i + month) { + ticks.push(creatMonth(minYear, _i + mmMoth)); + } + + interval = null; + } else if (interval > dms * 0.5) { + // 大于一天 + var date = new Date(min); + + var _year = date.getFullYear(); + + var _month = date.getMonth(min); + + var mday = date.getDate(); + var day = Math.ceil(interval / dms); + var ddays = diffDay(min, max); + interval = day * dms; + + for (var _i2 = 0; _i2 < ddays + day; _i2 = _i2 + day) { + ticks.push(new Date(_year, _month, mday + _i2).getTime()); + } + } else if (interval > HOUR_MS) { + // 大于一个小时 + var _date = new Date(min); + + var _year2 = _date.getFullYear(); + + var _month2 = _date.getMonth(min); + + var _day = _date.getDate(); + + var hour = _date.getHours(); + + var hours = _util2["default"].snapTo(SNAP_ARRAY, Math.ceil(interval / HOUR_MS)); + + var dHours = diffHour(min, max); + interval = hours * HOUR_MS; + + for (var _i3 = 0; _i3 <= dHours + hours; _i3 = _i3 + hours) { + ticks.push(new Date(_year2, _month2, _day, hour + _i3).getTime()); + } + } else if (interval > MINUTE_MS) { + // 最小单位是分钟 + var dMinus = diffMinus(min, max); + var minutes = Math.ceil(interval / MINUTE_MS); + interval = minutes * MINUTE_MS; + + for (var _i4 = 0; _i4 <= dMinus + minutes; _i4 = _i4 + minutes) { + ticks.push(min + _i4 * MINUTE_MS); + } + } else { + if (interval < 1000) { + interval = 1000; + } + + min = Math.floor(min / 1000) * 1000; + var dSeconds = Math.ceil((max - min) / 1000); + var seconds = Math.ceil(interval / 1000); + interval = seconds * 1000; + + for (var _i5 = 0; _i5 < dSeconds + seconds; _i5 = _i5 + seconds) { + ticks.push(min + _i5 * 1000); + } + } + } + + if (!ticks.length) { + min = Math.floor(min / 1000) * 1000; + max = Math.ceil(max / 1000) * 1000; + count = (max - min) / interval; + + for (var _i6 = 0; _i6 <= count; _i6++) { + ticks.push(_util["default"].fixedBase(interval * _i6 + min, interval)); + } + } + + return { + max: max, + min: min, + interval: interval, + ticks: ticks, + count: ticks.length + }; +} \ No newline at end of file diff --git a/lib/scale/auto/util.js b/lib/scale/auto/util.js new file mode 100644 index 0000000000..1a7a9e7054 --- /dev/null +++ b/lib/scale/auto/util.js @@ -0,0 +1,212 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +/** + * @fileOverview 计算方法 + * @author dxq613@gmail.com + */ +// 如果小数点后面超过 10 位浮点数时进行一下处理 +var DECIMAL_LENGTH = 12; // 获取系数 + +function getFactor(v) { + var factor = 1; + + if (v === Infinity || v === -Infinity) { + throw new Error('Not support Infinity!'); + } + + if (v < 1) { + var count = 0; + + while (v < 1) { + factor = factor / 10; + v = v * 10; + count++; + } // 浮点数计算出现问题 + + + if (factor.toString().length > DECIMAL_LENGTH) { + factor = parseFloat(factor.toFixed(count)); + } + } else { + while (v > 10) { + factor = factor * 10; + v = v / 10; + } + } + + return factor; +} // 取小于当前值的 + + +function arrayFloor(values, value) { + var length = values.length; + + if (length === 0) { + return NaN; + } + + var pre = values[0]; + + if (value < values[0]) { + return NaN; + } + + if (value >= values[length - 1]) { + return values[length - 1]; + } + + for (var i = 1; i < values.length; i++) { + if (value < values[i]) { + break; + } + + pre = values[i]; + } + + return pre; +} // 大于当前值的第一个 + + +function arrayCeiling(values, value) { + var length = values.length; + + if (length === 0) { + return NaN; + } // var pre = values[0]; + + + var rst; + + if (value > values[length - 1]) { + return NaN; + } + + if (value < values[0]) { + return values[0]; + } + + for (var i = 1; i < values.length; i++) { + if (value <= values[i]) { + rst = values[i]; + break; + } + } + + return rst; +} + +var Util = { + // 获取逼近的数值 + snapFactorTo: function snapFactorTo(v, arr, snapType) { + // 假设 v = -512,isFloor = true + if (isNaN(v)) { + return NaN; + } + + var factor = 1; // 计算系数 + + if (v !== 0) { + if (v < 0) { + factor = -1; + } + + v = v * factor; // v = 512 + + var tmpFactor = getFactor(v); + factor = factor * tmpFactor; // factor = -100 + + v = v / tmpFactor; // v = 5.12 + } + + if (snapType === 'floor') { + v = Util.snapFloor(arr, v); // v = 5 + } else if (snapType === 'ceil') { + v = Util.snapCeiling(arr, v); // v = 6 + } else { + v = Util.snapTo(arr, v); // 四舍五入 5 + } + + var rst = v * factor; // 如果出现浮点数计算问题,需要处理一下 + + if (Math.abs(factor) < 1 && rst.toString().length > DECIMAL_LENGTH) { + var decimalVal = parseInt(1 / factor); + var symbol = factor > 0 ? 1 : -1; + rst = v / decimalVal * symbol; + } + + return rst; + }, + // 获取逼近的倍数 + snapMultiple: function snapMultiple(v, base, snapType) { + var div; + + if (snapType === 'ceil') { + div = Math.ceil(v / base); + } else if (snapType === 'floor') { + div = Math.floor(v / base); + } else { + div = Math.round(v / base); + } + + return div * base; + }, + + /** + * 获取逼近的值,用于对齐数据 + * @param {Array} values 数据集合 + * @param {Number} value 数值 + * @return {Number} 逼近的值 + */ + snapTo: function snapTo(values, value) { + // 这里假定values是升序排列 + var floorVal = arrayFloor(values, value); + var ceilingVal = arrayCeiling(values, value); + + if (isNaN(floorVal) || isNaN(ceilingVal)) { + if (values[0] >= value) { + return values[0]; + } + + var last = values[values.length - 1]; + + if (last <= value) { + return last; + } + } + + if (Math.abs(value - floorVal) < Math.abs(ceilingVal - value)) { + return floorVal; + } + + return ceilingVal; + }, + + /** + * 获取逼近的最小值,用于对齐数据 + * @param {Array} values 数据集合 + * @param {Number} value 数值 + * @return {Number} 逼近的最小值 + */ + snapFloor: function snapFloor(values, value) { + // 这里假定values是升序排列 + return arrayFloor(values, value); + }, + + /** + * 获取逼近的最大值,用于对齐数据 + * @param {Array} values 数据集合 + * @param {Number} value 数值 + * @return {Number} 逼近的最大值 + */ + snapCeiling: function snapCeiling(values, value) { + // 这里假定values是升序排列 + return arrayCeiling(values, value); + } +}; +var _default = Util; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/scale/base.js b/lib/scale/base.js new file mode 100644 index 0000000000..7c39f0fe13 --- /dev/null +++ b/lib/scale/base.js @@ -0,0 +1,244 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _util = _interopRequireDefault(require("../util")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +/** + * 度量的构造函数 + * @class Scale + */ +var Base = +/*#__PURE__*/ +function () { + _createClass(Base, [{ + key: "getDefaultCfg", + + /** + * 获取默认的配置属性 + * @protected + * @return {Object} 默认属性 + */ + value: function getDefaultCfg() { + return { + /** + * type of the scale + * @type {String} + */ + type: 'base', + + /** + * 格式化函数,输出文本或者tick时的格式化函数 + * @type {Function} + */ + formatter: null, + + /** + * 输出的值域 + * @type {Array} + */ + range: [0, 1], + + /** + * 度量的标记 + * @type {Array} + */ + ticks: null, + + /** + * 参与度量计算的值,可选项 + * @type {Array} + */ + values: [] + }; + } + }]); + + function Base(cfg) { + _classCallCheck(this, Base); + + var defaultCfg = this.getDefaultCfg(); + + _util["default"].mix(this, defaultCfg, cfg); + + this.init(); + } + /** + * 度量初始化 + * @protected + */ + + + _createClass(Base, [{ + key: "init", + value: function init() {} + /** + * 获取该度量的ticks,返回的是多个对象, + * - text: tick 的文本 + * - value: 对应的度量转换后的值 + * + * [ + * {text: 0,value:0} + * {text: 1,value:0.2} + * {text: 2,value:0.4} + * {text: 3,value:0.6} + * {text: 4,value:0.8} + * {text: 5,value:1} + * ] + * + * @param {Number} count 输出tick的个数的近似值,默认是 10 + * @return {Array} 返回 ticks 数组 + */ + + }, { + key: "getTicks", + value: function getTicks() { + var self = this; + var ticks = self.ticks; + var rst = []; + + _util["default"].each(ticks, function (tick) { + var obj; + + if (_util["default"].isObject(tick)) { + obj = tick; + } else { + obj = { + text: self.getText(tick), + tickValue: tick, + value: self.scale(tick) + }; + } + + rst.push(obj); + }); + + return rst; + } + /** + * 获取格式化后的文本 + * @param {*} value 输入的数据 + * @return {String} 格式化的文本 + */ + + }, { + key: "getText", + value: function getText(value) { + var formatter = this.formatter; + value = formatter ? formatter(value) : value; + + if (_util["default"].isNil(value) || !value.toString) { + value = ''; + } + + return value.toString(); + } + /** + * 输出的值域最小值 + * @protected + * @return {Number} 返回最小的值 + */ + + }, { + key: "rangeMin", + value: function rangeMin() { + return this.range[0]; + } + /** + * 输出的值域最大值 + * @protected + * @return {Number} 返回最大的值 + */ + + }, { + key: "rangeMax", + value: function rangeMax() { + var range = this.range; + return range[range.length - 1]; + } + /** + * 度量转换后的结果,翻转回输入域 + * @param {Number} value 需要翻转的数值 + * @return {*} 度量的输入值 + */ + + }, { + key: "invert", + value: function invert(value) { + return value; + } + /** + * 将传入的值从非数值转换成数值格式,如分类字符串、时间字符串等 + * @param {*} value 传入的值 + * @return {Number} 转换的值 + */ + + }, { + key: "translate", + value: function translate(value) { + return value; + } + /** + * 进行度量转换 + * @param {*} value 输入值 + * @return {Number} 输出值,在设定的输出值域之间,默认[0,1] + */ + + }, { + key: "scale", + value: function scale(value) { + return value; + } + /** + * 克隆一个新的scale,拥有跟当前scale相同的输入域、输出域等 + * @return {Scale} 克隆的度量 + */ + + }, { + key: "clone", + value: function clone() { + var self = this; + var constr = self.constructor; + var cfg = {}; + + _util["default"].each(self, function (v, k) { + cfg[k] = self[k]; + }); + + return new constr(cfg); + } + /** + * 更改度量的属性信息 + * @param {Object} info 属性信息 + * @chainable + * @return {Scale} 返回自身的引用 + */ + + }, { + key: "change", + value: function change(info) { + this.ticks = null; + + _util["default"].mix(this, info); + + this.init(); + return this; + } + }]); + + return Base; +}(); + +var _default = Base; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/scale/category.js b/lib/scale/category.js new file mode 100644 index 0000000000..4edbb0fcae --- /dev/null +++ b/lib/scale/category.js @@ -0,0 +1,199 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("./base")); + +var _util = _interopRequireDefault(require("../util")); + +var _cat = _interopRequireDefault(require("./auto/cat")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +/** + * 度量的构造函数 + * @class Scale.Category + */ +var Category = +/*#__PURE__*/ +function (_Base) { + _inherits(Category, _Base); + + function Category() { + _classCallCheck(this, Category); + + return _possibleConstructorReturn(this, _getPrototypeOf(Category).apply(this, arguments)); + } + + _createClass(Category, [{ + key: "getDefaultCfg", + + /** + * @override + */ + value: function getDefaultCfg() { + var cfg = _get(_getPrototypeOf(Category.prototype), "getDefaultCfg", this).call(this); + + return _util["default"].mix({}, cfg, { + /** + * type of the scale + * @type {String} + */ + type: 'cat', + + /** + * 自动生成标记时的个数 + * @type {Number} + * @default null + */ + tickCount: null, + + /** + * 是否分类度量 + * @type {Boolean} + */ + isCategory: true + }); + } + /** + * @override + */ + + }, { + key: "init", + value: function init() { + var self = this; + var values = self.values; + var tickCount = self.tickCount; + + _util["default"].each(values, function (v, i) { + values[i] = v.toString(); + }); + + if (!self.ticks) { + var ticks = values; + + if (tickCount) { + var temp = (0, _cat["default"])({ + maxCount: tickCount, + data: values + }); + ticks = temp.ticks; + } + + this.ticks = ticks; + } + } + /** + * @override + */ + + }, { + key: "getText", + value: function getText(value) { + if (this.values.indexOf(value) === -1 && _util["default"].isNumber(value)) { + value = this.values[Math.round(value)]; + } + + return _get(_getPrototypeOf(Category.prototype), "getText", this).call(this, value); + } + /** + * @override + */ + + }, { + key: "translate", + value: function translate(value) { + var index = this.values.indexOf(value); + + if (index === -1 && _util["default"].isNumber(value)) { + index = value; + } else if (index === -1) { + index = NaN; + } + + return index; + } + /** + * @override + */ + + }, { + key: "scale", + value: function scale(value) { + var rangeMin = this.rangeMin(); + var rangeMax = this.rangeMax(); + var percent; + + if (_util["default"].isString(value) || this.values.indexOf(value) !== -1) { + value = this.translate(value); + } + + if (this.values.length > 1) { + percent = value / (this.values.length - 1); + } else { + percent = value; + } + + return rangeMin + percent * (rangeMax - rangeMin); + } + /** + * @override + */ + + }, { + key: "invert", + value: function invert(value) { + if (_util["default"].isString(value)) { + // 如果已经是字符串 + return value; + } + + var min = this.rangeMin(); + var max = this.rangeMax(); // 归一到 范围内 + + if (value < min) { + value = min; + } + + if (value > max) { + value = max; + } + + var percent = (value - min) / (max - min); + var index = Math.round(percent * (this.values.length - 1)) % this.values.length; + index = index || 0; + return this.values[index]; + } + }]); + + return Category; +}(_base["default"]); + +var _default = Category; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/scale/identity.js b/lib/scale/identity.js new file mode 100644 index 0000000000..ee004083b2 --- /dev/null +++ b/lib/scale/identity.js @@ -0,0 +1,109 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("./base")); + +var _util = _interopRequireDefault(require("../util")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Identity = +/*#__PURE__*/ +function (_Base) { + _inherits(Identity, _Base); + + function Identity() { + _classCallCheck(this, Identity); + + return _possibleConstructorReturn(this, _getPrototypeOf(Identity).apply(this, arguments)); + } + + _createClass(Identity, [{ + key: "getDefaultCfg", + + /** + * @override + */ + value: function getDefaultCfg() { + var cfg = _get(_getPrototypeOf(Identity.prototype), "getDefaultCfg", this).call(this); + + return _util["default"].mix({}, cfg, { + isIdentity: true, + + /** + * @override + * @type {String} + */ + type: 'identity', + + /** + * 常量值 + * @type {*} + */ + value: null + }); + } + /** + * @override + */ + + }, { + key: "getText", + value: function getText() { + return this.value.toString(); + } + /** + * @override + */ + + }, { + key: "scale", + value: function scale(value) { + if (this.value !== value && _util["default"].isNumber(value)) { + return value; + } + + return this.range[0]; + } + /** + * @override + */ + + }, { + key: "invert", + value: function invert() { + return this.value; + } + }]); + + return Identity; +}(_base["default"]); + +var _default = Identity; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/scale/index.js b/lib/scale/index.js new file mode 100644 index 0000000000..a7f78a21ce --- /dev/null +++ b/lib/scale/index.js @@ -0,0 +1,61 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _util = _interopRequireDefault(require("../util")); + +var _base = _interopRequireDefault(require("./base")); + +var _linear = _interopRequireDefault(require("./linear")); + +var _identity = _interopRequireDefault(require("./identity")); + +var _category = _interopRequireDefault(require("./category")); + +var _time = _interopRequireDefault(require("./time")); + +var _timeCat = _interopRequireDefault(require("./time-cat")); + +var _log = _interopRequireDefault(require("./log")); + +var _pow = _interopRequireDefault(require("./pow")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +/** + * @fileOverview Scale entry, used to reference all the scales + * @author dxq613@gmail.com + */ +_base["default"].Linear = _linear["default"]; +_base["default"].Identity = _identity["default"]; +_base["default"].Cat = _category["default"]; +_base["default"].Time = _time["default"]; +_base["default"].TimeCat = _timeCat["default"]; +_base["default"].Log = _log["default"]; +_base["default"].Pow = _pow["default"]; + +var _loop = function _loop(k) { + if (_base["default"].hasOwnProperty(k)) { + var methodName = _util["default"].lowerFirst(k); + + _base["default"][methodName] = function (cfg) { + return new _base["default"][k](cfg); + }; + } +}; + +for (var k in _base["default"]) { + _loop(k); +} + +var CAT_ARR = ['cat', 'timeCat']; + +_base["default"].isCategory = function (type) { + return CAT_ARR.indexOf(type) >= 0; +}; + +var _default = _base["default"]; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/scale/linear.js b/lib/scale/linear.js new file mode 100644 index 0000000000..5f5ebbaa8e --- /dev/null +++ b/lib/scale/linear.js @@ -0,0 +1,263 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("./base")); + +var _util = _interopRequireDefault(require("../util")); + +var _number = _interopRequireDefault(require("./auto/number")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +/** + * 线性度量 + * @class Scale.Linear + */ +var Linear = +/*#__PURE__*/ +function (_Base) { + _inherits(Linear, _Base); + + function Linear() { + _classCallCheck(this, Linear); + + return _possibleConstructorReturn(this, _getPrototypeOf(Linear).apply(this, arguments)); + } + + _createClass(Linear, [{ + key: "getDefaultCfg", + + /** + * @override + */ + value: function getDefaultCfg() { + var cfg = _get(_getPrototypeOf(Linear.prototype), "getDefaultCfg", this).call(this); + + return _util["default"].mix({}, cfg, { + /** + * type of the scale + * @type {String} + */ + type: 'linear', + + /** + * 是否线性 + * @type {Boolean} + * @readOnly + * @default true + */ + isLinear: true, + + /** + * min value of the scale + * @type {Number} + * @default null + */ + min: null, + + /** + * min value limitted of the scale + * @type {Number} + * @default null + */ + minLimit: null, + + /** + * max value of the scale + * @type {Number} + * @default null + */ + max: null, + + /** + * max value limitted of the scale + * @type {Number} + * @default null + */ + maxLimit: null, + + /** + * 是否为了用户习惯,优化min,max和ticks,如果进行优化,则会根据生成的ticks调整min,max,否则舍弃(min,max)范围之外的ticks + * @type {Boolean} + * @default false + */ + nice: false, + + /** + * 自动生成标记时的个数 + * @type {Number} + * @default null + */ + tickCount: null, + + /** + * 坐标轴点之间的间距,指的是真实数据的差值 + * @type {Number} + * @default null + */ + tickInterval: null, + + /** + * 用于计算坐标点时逼近的数组 + * @type {Array} + */ + snapArray: null + }); + } + /** + * @protected + * @override + */ + + }, { + key: "init", + value: function init() { + var self = this; + + if (!self.ticks) { + self.min = self.translate(self.min); + self.max = self.translate(self.max); + self.initTicks(); + } else { + var ticks = self.ticks; + var firstValue = self.translate(ticks[0]); + var lastValue = self.translate(ticks[ticks.length - 1]); + + if (_util["default"].isNil(self.min) || self.min > firstValue) { + self.min = firstValue; + } + + if (_util["default"].isNil(self.max) || self.max < lastValue) { + self.max = lastValue; + } + } + } + /** + * 计算坐标点 + * @protected + * @return {Array} 计算完成的坐标点 + */ + + }, { + key: "calculateTicks", + value: function calculateTicks() { + var self = this; + var min = self.min; + var max = self.max; + var count = self.tickCount; + var interval = self.tickInterval; + + if (max < min) { + throw new Error("max: ".concat(max, " should not be less than min: ").concat(min)); + } + + var tmp = (0, _number["default"])({ + min: min, + max: max, + minLimit: self.minLimit, + maxLimit: self.maxLimit, + minCount: count, + maxCount: count, + interval: interval, + snapArray: this.snapArray + }); + return tmp.ticks; + } // 初始化ticks + + }, { + key: "initTicks", + value: function initTicks() { + var self = this; + var calTicks = self.calculateTicks(); + + if (self.nice) { + // 如果需要优化显示的tick + self.ticks = calTicks; + self.min = calTicks[0]; + self.max = calTicks[calTicks.length - 1]; + } else { + var ticks = []; + + _util["default"].each(calTicks, function (tick) { + if (tick >= self.min && tick <= self.max) { + ticks.push(tick); + } + }); // 如果 ticks 为空,直接输入最小值、最大值 + + + if (!ticks.length) { + ticks.push(self.min); + ticks.push(self.max); + } + + self.ticks = ticks; + } + } + /** + * @override + */ + + }, { + key: "scale", + value: function scale(value) { + if (value === null || value === undefined) { + return NaN; + } + + var max = this.max; + var min = this.min; + + if (max === min) { + return 0; + } + + var percent = Math.min(1, Math.max(0, (value - min) / (max - min))); // 数据控制到 0-1 范围 + // const percent = (value - min) / (max - min); + + var rangeMin = this.rangeMin(); + var rangeMax = this.rangeMax(); + return rangeMin + percent * (rangeMax - rangeMin); + } + /** + * @override + */ + + }, { + key: "invert", + value: function invert(value) { + var percent = (value - this.rangeMin()) / (this.rangeMax() - this.rangeMin()); + return this.min + percent * (this.max - this.min); + } + }]); + + return Linear; +}(_base["default"]); + +var _default = Linear; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/scale/log.js b/lib/scale/log.js new file mode 100644 index 0000000000..4a1879b98a --- /dev/null +++ b/lib/scale/log.js @@ -0,0 +1,237 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _linear = _interopRequireDefault(require("./linear")); + +var _util = _interopRequireDefault(require("../util")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +// 计算log +function log(a, b) { + if (a === 1) { + return 1; + } + + return Math.log(b) / Math.log(a); +} +/** + * 度量的log计算 + * @class Scale.Log + */ + + +var Log = +/*#__PURE__*/ +function (_Linear) { + _inherits(Log, _Linear); + + function Log() { + _classCallCheck(this, Log); + + return _possibleConstructorReturn(this, _getPrototypeOf(Log).apply(this, arguments)); + } + + _createClass(Log, [{ + key: "getDefaultCfg", + + /** + * @override + */ + value: function getDefaultCfg() { + var cfg = _get(_getPrototypeOf(Log.prototype), "getDefaultCfg", this).call(this); + + return _util["default"].mix({}, cfg, { + /** + * @override + */ + type: 'log', + + /** + * 进行log计算的基数 + * @type {Number} + */ + base: 2, + + /** + * @override + * log 的坐标点的个数控制在10个以下 + * @type {Number} + */ + tickCount: 10, + // 最小的tick,仅内部使用 + _minTick: null + }); + } + /** + * @override + */ + + }, { + key: "calculateTicks", + value: function calculateTicks() { + var self = this; + var base = self.base; + var minTick; + + if (self.min < 0) { + throw new Error('The minimum value must be greater than zero!'); + } + + var maxTick = log(base, self.max); + + if (self.min > 0) { + minTick = Math.floor(log(base, self.min)); + } else { + var values = self.values; + var positiveMin = self.max; // 查找大于0的第一个值, 如果都小于0,默认为1 + + _util["default"].each(values, function (value) { + if (value > 0 && value < positiveMin) { + positiveMin = value; + } + }); + + if (positiveMin === self.max) { + positiveMin = self.max / base; + } + + if (positiveMin > 1) { + positiveMin = 1; + } + + minTick = Math.floor(log(base, positiveMin)); + self._minTick = minTick; + self.positiveMin = positiveMin; + } + + var count = maxTick - minTick; + var tickCount = self.tickCount; + var avg = Math.ceil(count / tickCount); + var ticks = []; + + for (var i = minTick; i < maxTick + avg; i = i + avg) { + ticks.push(Math.pow(base, i)); + } + /**/ + + + if (self.min === 0) { + ticks.unshift(0); + } + + return ticks; + } // 获取度量计算时,value占的定义域百分比 + + }, { + key: "_getScalePercent", + value: function _getScalePercent(value) { + var max = this.max; + var min = this.min; + + if (max === min) { + return 0; + } // 如果值小于等于0,则按照0处理 + + + if (value <= 0) { + return 0; + } + + var base = this.base; + var positiveMin = this.positiveMin; // 如果min == 0, 则根据比0大的最小值,计算比例关系。这个最小值作为坐标轴上的第二个tick,第一个是0但是不显示 + + if (positiveMin) { + min = positiveMin * 1 / base; + } + + var percent; // 如果数值小于次小值,那么就计算 value / 次小值 占整体的比例 + + if (value < positiveMin) { + percent = value / positiveMin / (log(base, max) - log(base, min)); + } else { + percent = (log(base, value) - log(base, min)) / (log(base, max) - log(base, min)); + } + + return percent; + } + /** + * @override + */ + + }, { + key: "scale", + value: function scale(value) { + var percent = this._getScalePercent(value); + + var rangeMin = this.rangeMin(); + var rangeMax = this.rangeMax(); + return rangeMin + percent * (rangeMax - rangeMin); + } + /** + * @override + */ + + }, { + key: "invert", + value: function invert(value) { + var base = this.base; + var max = log(base, this.max); + var rangeMin = this.rangeMin(); + var range = this.rangeMax() - rangeMin; + var min; + var positiveMin = this.positiveMin; + + if (positiveMin) { + if (value === 0) { + return 0; + } + + min = log(base, positiveMin / base); + var appendPercent = 1 / (max - min) * range; // 0 到 positiveMin的占比 + + if (value < appendPercent) { + // 落到 0 - positiveMin 之间 + return value / appendPercent * positiveMin; + } + } else { + min = log(base, this.min); + } + + var percent = (value - rangeMin) / range; + var tmp = percent * (max - min) + min; + return Math.pow(base, tmp); + } + }]); + + return Log; +}(_linear["default"]); + +var _default = Log; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/scale/pow.js b/lib/scale/pow.js new file mode 100644 index 0000000000..73384b175b --- /dev/null +++ b/lib/scale/pow.js @@ -0,0 +1,172 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _linear = _interopRequireDefault(require("./linear")); + +var _util = _interopRequireDefault(require("../util")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +// 求以a为次幂,结果为b的基数,如 x^^a = b;求x +function calBase(a, b) { + var e = Math.E; + var value = Math.pow(e, Math.log(b) / a); // 使用换底公式求底 + + return value; +} +/** + * 度量的Pow计算 + * @class Scale.Log + */ + + +var Pow = +/*#__PURE__*/ +function (_Linear) { + _inherits(Pow, _Linear); + + function Pow() { + _classCallCheck(this, Pow); + + return _possibleConstructorReturn(this, _getPrototypeOf(Pow).apply(this, arguments)); + } + + _createClass(Pow, [{ + key: "getDefaultCfg", + + /** + * @override + */ + value: function getDefaultCfg() { + var cfg = _get(_getPrototypeOf(Pow.prototype), "getDefaultCfg", this).call(this); + + return _util["default"].mix({}, cfg, { + /** + * @override + */ + type: 'pow', + + /** + * 进行pow计算的基数 + * @type {Number} + */ + exponent: 2, + + /** + * @override + * pow 的坐标点的个数控制在10个以下 + * @type {Number} + */ + tickCount: 10 + }); + } + /** + * @override + */ + + }, { + key: "calculateTicks", + value: function calculateTicks() { + var self = this; + var exponent = self.exponent; + var min; + var max = Math.ceil(calBase(exponent, self.max)); + + if (self.min >= 0) { + min = Math.floor(calBase(exponent, self.min)); + } else { + min = 0; + } + + if (min > max) { + var tmp = max; + max = min; + min = tmp; + } + + var count = max - min; + var tickCount = self.tickCount; + var avg = Math.ceil(count / tickCount); + var ticks = []; + + for (var i = min; i < max + avg; i = i + avg) { + ticks.push(Math.pow(i, exponent)); + } + + return ticks; + } // 获取度量计算时,value占的定义域百分比 + + }, { + key: "_getScalePercent", + value: function _getScalePercent(value) { + var max = this.max; + var min = this.min; + + if (max === min) { + return 0; + } + + var exponent = this.exponent; + var percent = (calBase(exponent, value) - calBase(exponent, min)) / (calBase(exponent, max) - calBase(exponent, min)); + return percent; + } + /** + * @override + */ + + }, { + key: "scale", + value: function scale(value) { + var percent = this._getScalePercent(value); + + var rangeMin = this.rangeMin(); + var rangeMax = this.rangeMax(); + return rangeMin + percent * (rangeMax - rangeMin); + } + /** + * @override + */ + + }, { + key: "invert", + value: function invert(value) { + var percent = (value - this.rangeMin()) / (this.rangeMax() - this.rangeMin()); + var exponent = this.exponent; + var max = calBase(exponent, this.max); + var min = calBase(exponent, this.min); + var tmp = percent * (max - min) + min; + return Math.pow(tmp, exponent); + } + }]); + + return Pow; +}(_linear["default"]); + +var _default = Pow; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/scale/time-cat.js b/lib/scale/time-cat.js new file mode 100644 index 0000000000..61bd0259f8 --- /dev/null +++ b/lib/scale/time-cat.js @@ -0,0 +1,238 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _category = _interopRequireDefault(require("./category")); + +var _util = _interopRequireDefault(require("../util")); + +var _fecha = _interopRequireDefault(require("fecha")); + +var _timeUtil = _interopRequireDefault(require("./time-util")); + +var _cat = _interopRequireDefault(require("./auto/cat")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +/** + * 度量的构造函数 + * @class Scale.TimeCategory + */ +var TimeCategory = +/*#__PURE__*/ +function (_Category) { + _inherits(TimeCategory, _Category); + + function TimeCategory() { + _classCallCheck(this, TimeCategory); + + return _possibleConstructorReturn(this, _getPrototypeOf(TimeCategory).apply(this, arguments)); + } + + _createClass(TimeCategory, [{ + key: "getDefaultCfg", + + /** + * @override + */ + value: function getDefaultCfg() { + var cfg = _get(_getPrototypeOf(TimeCategory.prototype), "getDefaultCfg", this).call(this); + + return _util["default"].mix({}, cfg, { + /** + * @override + */ + type: 'timeCat', + + /** + * 格式化符 + * @type {String} + */ + mask: 'YYYY-MM-DD', + + /** + * @override + */ + tickCount: 7 + }); + } + }, { + key: "init", + value: function init() { + var self = this; + var values = this.values; // 针对时间分类类型,会将时间统一转换为时间戳 + + _util["default"].each(values, function (v, i) { + values[i] = self._toTimeStamp(v); + }); + + values.sort(function (v1, v2) { + return v1 - v2; + }); + + if (!self.ticks) { + self.ticks = this.calculateTicks(false); + } + } + /** + * 计算 ticks + * @param {boolean} formated 是否将 ticks 按照指定的 mask 格式化 + * @return {array} 返回 ticks 数组 + */ + + }, { + key: "calculateTicks", + value: function calculateTicks(formated) { + var self = this; + var count = self.tickCount; + var ticks; + + if (count) { + var temp = (0, _cat["default"])({ + maxCount: count, + data: self.values + }); + ticks = temp.ticks; + } else { + ticks = self.values; + } + + if (formated) { + _util["default"].each(ticks, function (value, index) { + ticks[index] = _fecha["default"].format(value, self.mask); + }); + } + + return ticks; + } + /** + * @override + */ + + }, { + key: "translate", + value: function translate(value) { + value = this._toTimeStamp(value); + var index = this.values.indexOf(value); + + if (index === -1) { + if (_util["default"].isNumber(value) && value < this.values.length) { + index = value; + } else { + index = NaN; + } + } + + return index; + } + /** + * @override + */ + + }, { + key: "scale", + value: function scale(value) { + var rangeMin = this.rangeMin(); + var rangeMax = this.rangeMax(); + var index = this.translate(value); + var percent; + + if (this.values.length === 1) { + percent = index; + } else if (index > -1) { + percent = index / (this.values.length - 1); + } else { + percent = 0; + } + + return rangeMin + percent * (rangeMax - rangeMin); + } + /** + * @override + */ + + }, { + key: "getText", + value: function getText(value) { + var result = ''; + var index = this.translate(value); + + if (index > -1) { + result = this.values[index]; + } else { + result = value; + } + + var formatter = this.formatter; + result = parseInt(result, 10); + result = formatter ? formatter(result) : _fecha["default"].format(result, this.mask); + return result; + } + /** + * @override + */ + + }, { + key: "getTicks", + value: function getTicks() { + var self = this; + var ticks = this.ticks; + var rst = []; + + _util["default"].each(ticks, function (tick) { + var obj; + + if (_util["default"].isObject(tick)) { + obj = tick; + } else { + obj = { + text: _util["default"].isString(tick) ? tick : self.getText(tick), + tickValue: tick, + // 用于坐标轴上文本动画时确定前后帧的对应关系 + value: self.scale(tick) + }; + } + + rst.push(obj); + }); + + return rst; + } // 将时间转换为时间戳 + + }, { + key: "_toTimeStamp", + value: function _toTimeStamp(value) { + return _timeUtil["default"].toTimeStamp(value); + } + }]); + + return TimeCategory; +}(_category["default"]); + +var _default = TimeCategory; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/scale/time-util.js b/lib/scale/time-util.js new file mode 100644 index 0000000000..684026c1af --- /dev/null +++ b/lib/scale/time-util.js @@ -0,0 +1,33 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _util = _interopRequireDefault(require("../util")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +/** + * @fileOverview 提取公共代码到util方法 + * @author dxq613@gmail.com + */ +var _default = { + toTimeStamp: function toTimeStamp(value) { + if (_util["default"].isString(value)) { + if (value.indexOf('T') > 0) { + value = new Date(value).getTime(); + } else { + value = new Date(value.replace(/-/ig, '/')).getTime(); + } + } + + if (_util["default"].isDate(value)) { + value = value.getTime(); + } + + return value; + } +}; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/scale/time.js b/lib/scale/time.js new file mode 100644 index 0000000000..645617cc5a --- /dev/null +++ b/lib/scale/time.js @@ -0,0 +1,199 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _linear = _interopRequireDefault(require("./linear")); + +var _util = _interopRequireDefault(require("../util")); + +var _time = _interopRequireDefault(require("./auto/time")); + +var _fecha = _interopRequireDefault(require("fecha")); + +var _timeUtil = _interopRequireDefault(require("./time-util")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +/** + * 时间度量的构造函数 + * @class Scale.Time + */ +var Time = +/*#__PURE__*/ +function (_Linear) { + _inherits(Time, _Linear); + + function Time() { + _classCallCheck(this, Time); + + return _possibleConstructorReturn(this, _getPrototypeOf(Time).apply(this, arguments)); + } + + _createClass(Time, [{ + key: "getDefaultCfg", + + /** + * @override + */ + value: function getDefaultCfg() { + var cfg = _get(_getPrototypeOf(Time.prototype), "getDefaultCfg", this).call(this); + + return _util["default"].mix({}, cfg, { + /** + * @override + */ + type: 'time', + + /** + * 格式化符 + * @type {String} + */ + mask: 'YYYY-MM-DD' + }); + } + /** + * @override + */ + + }, { + key: "init", + value: function init() { + var self = this; + var values = self.values; + + if (values && values.length) { + // 重新计算最大最小值 + var timeStamps = []; + var min = Infinity; // 最小值 + + var secondMin = min; // 次小值 + + var max = 0; // 使用一个循环,计算min,max,secondMin + + _util["default"].each(values, function (v) { + var timeStamp = self._toTimeStamp(v); + + if (isNaN(timeStamp)) { + throw new TypeError("Invalid Time: ".concat(v)); + } + + if (min > timeStamp) { + secondMin = min; + min = timeStamp; + } else if (secondMin > timeStamp) { + secondMin = timeStamp; + } + + if (max < timeStamp) { + max = timeStamp; + } + + timeStamps.push(timeStamp); + }); // 存在多个值时,设置最小间距 + + + if (values.length > 1) { + self.minTickInterval = secondMin - min; + } + + if (_util["default"].isNil(self.min) || self._toTimeStamp(self.min) > min) { + self.min = min; + } + + if (_util["default"].isNil(self.max) || self._toTimeStamp(self.max) < max) { + self.max = max; + } + } + + _get(_getPrototypeOf(Time.prototype), "init", this).call(this); + } + }, { + key: "calculateTicks", + value: function calculateTicks() { + var self = this; + var min = self.min; + var max = self.max; + var count = self.tickCount; + var interval = self.tickInterval; + var tmp = (0, _time["default"])({ + min: min, + max: max, + minCount: count, + maxCount: count, + interval: interval, + minInterval: self.minTickInterval + }); + return tmp.ticks; + } + /** + * @override + */ + + }, { + key: "getText", + value: function getText(value) { + var formatter = this.formatter; + value = this.translate(value); + value = formatter ? formatter(value) : _fecha["default"].format(value, this.mask); + return value; + } + /** + * @override + */ + + }, { + key: "scale", + value: function scale(value) { + if (_util["default"].isString(value)) { + value = this.translate(value); + } + + return _get(_getPrototypeOf(Time.prototype), "scale", this).call(this, value); + } + /** + * @override + */ + + }, { + key: "translate", + value: function translate(value) { + return this._toTimeStamp(value); + } // 将时间转换为时间戳 + + }, { + key: "_toTimeStamp", + value: function _toTimeStamp(value) { + return _timeUtil["default"].toTimeStamp(value); + } + }]); + + return Time; +}(_linear["default"]); + +var _default = Time; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/source/csvSource.js b/lib/source/csvSource.js new file mode 100644 index 0000000000..57083dad21 --- /dev/null +++ b/lib/source/csvSource.js @@ -0,0 +1,144 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _source = _interopRequireDefault(require("../core/source")); + +var _featureIndex = _interopRequireDefault(require("../geo/featureIndex")); + +var _d3Dsv = require("d3-dsv"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var CSVSource = +/*#__PURE__*/ +function (_Source) { + _inherits(CSVSource, _Source); + + function CSVSource() { + _classCallCheck(this, CSVSource); + + return _possibleConstructorReturn(this, _getPrototypeOf(CSVSource).apply(this, arguments)); + } + + _createClass(CSVSource, [{ + key: "prepareData", + value: function prepareData() { + var _this = this; + + this.type = 'csv'; + var data = this.get('data'); + var x = this.get('x'); + var y = this.get('y'); + var x1 = this.get('x1'); + var y1 = this.get('y1'); + var coords = this.get('coordinates'); + this.propertiesData = []; // 临时使用 + + this.geoData = []; + var csvdata = data; + Array.isArray(csvdata) || (csvdata = (0, _d3Dsv.csvParse)(data)); + this.propertiesData = csvdata; + csvdata.forEach(function (col, featureIndex) { + var coordinates = []; + + if (col.coordinates) { + coordinates = col.coordinates; + } + + if (x && y) { + coordinates = [col[x], col[y]]; + } // 点数据 + + + if (x1 && y1) { + // 弧线 或者线段 + coordinates = [[col[x], col[y]], [col[x1], col[y1]]]; + } + + if (coords && col.coords) { + coordinates = col.coords; + } + + col._id = featureIndex + 1; + + _this._coordProject(coordinates); + + _this.geoData.push(_this._coordProject(coordinates)); + }); + } + }, { + key: "featureIndex", + value: function featureIndex() { + var data = this.get('data'); + this.featureIndex = new _featureIndex.default(data); + } + }, { + key: "getSelectFeatureId", + value: function getSelectFeatureId(featureId) { + return [featureId]; + } + }, { + key: "getSelectFeature", + value: function getSelectFeature(featureId) { + return this.propertiesData[featureId]; + } + }, { + key: "_getCoord", + value: function _getCoord(geo) { + if (geo.geometry) { + // GeoJSON feature + geo = geo.geometry.coordinates; + } else if (geo.coordinates) { + // GeoJSON geometry + geo = geo.coordinates; + } + + return geo; + } + }, { + key: "_coordProject", + value: function _coordProject(geo) { + var _this2 = this; + + if (Array.isArray(geo[0][0])) { + return geo.map(function (coor) { + return _this2._coordProject(coor); + }); + } + + if (!Array.isArray(geo[0])) { + return this._coorConvert(geo); + } + + return geo.map(function (coor) { + return _this2._coorConvert(coor); + }); + } + }]); + + return CSVSource; +}(_source.default); + +exports.default = CSVSource; \ No newline at end of file diff --git a/lib/source/factory.js b/lib/source/factory.js new file mode 100644 index 0000000000..2a305b99c7 --- /dev/null +++ b/lib/source/factory.js @@ -0,0 +1,32 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.registerTransform = exports.getTransform = exports.registerParser = exports.getParser = void 0; +var TRANSFORMS = {}; +var PARSERS = {}; + +var getParser = function getParser(type) { + return PARSERS[type]; +}; + +exports.getParser = getParser; + +var registerParser = function registerParser(type, parserFunction) { + PARSERS[type] = parserFunction; +}; + +exports.registerParser = registerParser; + +var getTransform = function getTransform(type) { + return TRANSFORMS[type]; +}; + +exports.getTransform = getTransform; + +var registerTransform = function registerTransform(type, transFunction) { + TRANSFORMS[type] = transFunction; +}; + +exports.registerTransform = registerTransform; \ No newline at end of file diff --git a/lib/source/geojsonSource.js b/lib/source/geojsonSource.js new file mode 100644 index 0000000000..59e17bebc5 --- /dev/null +++ b/lib/source/geojsonSource.js @@ -0,0 +1,108 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _source = _interopRequireDefault(require("../core/source")); + +var turfMeta = _interopRequireWildcard(require("@turf/meta")); + +var _cleanCoords = _interopRequireDefault(require("@turf/clean-coords")); + +var _invariant = require("@turf/invariant"); + +var _featureIndex = _interopRequireDefault(require("../geo/featureIndex")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var GeojsonSource = +/*#__PURE__*/ +function (_Source) { + _inherits(GeojsonSource, _Source); + + function GeojsonSource() { + _classCallCheck(this, GeojsonSource); + + return _possibleConstructorReturn(this, _getPrototypeOf(GeojsonSource).apply(this, arguments)); + } + + _createClass(GeojsonSource, [{ + key: "prepareData", + value: function prepareData() { + var _this = this; + + this.type = 'geojson'; + var data = this.get('data'); + this.propertiesData = []; + this.geoData = []; + turfMeta.flattenEach(data, function (currentFeature, featureIndex) { + var coord = (0, _invariant.getCoords)((0, _cleanCoords.default)(currentFeature)); + + _this.geoData.push(_this._coordProject(coord)); + + currentFeature.properties._id = featureIndex + 1; + + _this.propertiesData.push(currentFeature.properties); + }); + } + }, { + key: "featureIndex", + value: function featureIndex() { + var data = this.get('data'); + this.featureIndex = new _featureIndex.default(data); + } + }, { + key: "getSelectFeatureId", + value: function getSelectFeatureId(featureId) { + var data = this.get('data'); + var selectFeatureIds = []; + var featureStyleId = 0; + turfMeta.flattenEach(data, function (currentFeature, featureIndex + /* , multiFeatureIndex*/ + ) { + if (featureIndex === featureId) { + selectFeatureIds.push(featureStyleId); + } + + featureStyleId++; + + if (featureIndex > featureId) { + return; + } + }); + return selectFeatureIds; + } + }, { + key: "getSelectFeature", + value: function getSelectFeature(featureId) { + var data = this.get('data'); + return data.features[featureId]; + } + }]); + + return GeojsonSource; +}(_source.default); + +exports.default = GeojsonSource; \ No newline at end of file diff --git a/lib/source/imageSource.js b/lib/source/imageSource.js new file mode 100644 index 0000000000..37a1721397 --- /dev/null +++ b/lib/source/imageSource.js @@ -0,0 +1,97 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _source = _interopRequireDefault(require("../core/source")); + +var _ajax = require("../util/ajax"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var ImageSource = +/*#__PURE__*/ +function (_Source) { + _inherits(ImageSource, _Source); + + function ImageSource() { + _classCallCheck(this, ImageSource); + + return _possibleConstructorReturn(this, _getPrototypeOf(ImageSource).apply(this, arguments)); + } + + _createClass(ImageSource, [{ + key: "prepareData", + value: function prepareData() { + this.type = 'image'; + var extent = this.get('extent'); + + var lb = this._coorConvert(extent.slice(0, 2)); + + var tr = this._coorConvert(extent.slice(2, 4)); + + this.geoData = [lb, tr]; + this.propertiesData = []; + + this._loadData(); + } + }, { + key: "_loadData", + value: function _loadData() { + var _this = this; + + var url = this.get('data'); + this.image = []; + + if (typeof url === 'string') { + (0, _ajax.getImage)({ + url: url + }, function (err, img) { + _this.image = img; + + _this.emit('imageLoaded'); + }); + } else { + var imageCount = url.length; + var imageindex = 0; + url.forEach(function (item) { + (0, _ajax.getImage)({ + url: item + }, function (err, img) { + imageindex++; + + _this.image.push(img); + + if (imageindex === imageCount) { + _this.emit('imageLoaded'); + } + }); + }); + } + } + }]); + + return ImageSource; +}(_source.default); + +exports.default = ImageSource; \ No newline at end of file diff --git a/lib/source/index.js b/lib/source/index.js new file mode 100644 index 0000000000..3dd1a03777 --- /dev/null +++ b/lib/source/index.js @@ -0,0 +1,66 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getTransform", { + enumerable: true, + get: function get() { + return _factory.getTransform; + } +}); +Object.defineProperty(exports, "registerTransform", { + enumerable: true, + get: function get() { + return _factory.registerTransform; + } +}); +Object.defineProperty(exports, "getParser", { + enumerable: true, + get: function get() { + return _factory.getParser; + } +}); +Object.defineProperty(exports, "registerParser", { + enumerable: true, + get: function get() { + return _factory.registerParser; + } +}); + +var _geojson = _interopRequireDefault(require("./parser/geojson")); + +var _image = _interopRequireDefault(require("./parser/image")); + +var _csv = _interopRequireDefault(require("./parser/csv")); + +var _json = _interopRequireDefault(require("./parser/json")); + +var _raster = _interopRequireDefault(require("./parser/raster")); + +var _mvt = _interopRequireDefault(require("./parser/mvt")); + +var _vector = _interopRequireDefault(require("./parser/vector")); + +var _factory = require("./factory"); + +var _grid = require("./transform/grid"); + +var _hexagon = require("./transform/hexagon"); + +var _map = require("./transform/map"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +// source parser +(0, _factory.registerParser)('geojson', _geojson["default"]); +(0, _factory.registerParser)('image', _image["default"]); +(0, _factory.registerParser)('csv', _csv["default"]); +(0, _factory.registerParser)('json', _json["default"]); +(0, _factory.registerParser)('raster', _raster["default"]); +(0, _factory.registerParser)('mvt', _mvt["default"]); +(0, _factory.registerParser)('vector', _vector["default"]); // 注册transform + +(0, _factory.registerTransform)('grid', _grid.aggregatorToGrid); +(0, _factory.registerTransform)('hexagon', _hexagon.pointToHexbin); +(0, _factory.registerTransform)('map', _map.map); \ No newline at end of file diff --git a/lib/source/parser/csv.js b/lib/source/parser/csv.js new file mode 100644 index 0000000000..22ecd1d595 --- /dev/null +++ b/lib/source/parser/csv.js @@ -0,0 +1,47 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = csv; + +var _d3Dsv = require("d3-dsv"); + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function csv(data, cfg) { + var x = cfg.x, + y = cfg.y, + x1 = cfg.x1, + y1 = cfg.y1; + var csvdata = (0, _d3Dsv.csvParse)(data); + var resultdata = []; + csvdata.forEach(function (col, featureIndex) { + var coordinates = []; + + if (x && y) { + coordinates = [col[x] * 1, col[y] * 1]; + } // 点数据 + + + if (x1 && y1) { + // 弧线 或者线段 + coordinates = [[col[x] * 1, col[y] * 1], [col[x1] * 1, col[y1] * 1]]; + } + + col._id = featureIndex + 1; + + var dataItem = _objectSpread({}, col, { + coordinates: coordinates + }); + + resultdata.push(dataItem); + }); + return { + dataArray: resultdata + }; +} \ No newline at end of file diff --git a/lib/source/parser/geojson.js b/lib/source/parser/geojson.js new file mode 100644 index 0000000000..ab54cf80cd --- /dev/null +++ b/lib/source/parser/geojson.js @@ -0,0 +1,61 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = geoJSON; + +var turfMeta = _interopRequireWildcard(require("@turf/meta")); + +var _invariant = require("@turf/invariant"); + +var _bkdrHash = require("../../util/bkdr-hash"); + +var _geojsonRewind = _interopRequireDefault(require("@mapbox/geojson-rewind")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function geoJSON(data, cfg) { + // 矢量瓦片图层不做 rewind + (0, _geojsonRewind["default"])(data, true); + var resultData = []; + var featureKeys = {}; + data.features = data.features.filter(function (item) { + return item != null && item.geometry && item.geometry.type && item.geometry.coordinates && item.geometry.coordinates.length > 0; + }); // 数据为空时处理 + + var i = 0; + turfMeta.flattenEach(data, function (currentFeature, featureIndex) { + // 多个polygon 拆成一个 + var coord = (0, _invariant.getCoords)(currentFeature); + var id = featureIndex + 1; + + if (cfg.idField && currentFeature.properties[cfg.idField]) { + var value = currentFeature.properties[cfg.idField]; + id = (0, _bkdrHash.djb2hash)(value) % 1000019; + featureKeys[id] = { + index: i++, + idField: value + }; + } + + var dataItem = _objectSpread({}, currentFeature.properties, { + coordinates: coord, + _id: id + }); + + resultData.push(dataItem); + }); + return { + dataArray: resultData, + featureKeys: featureKeys + }; +} \ No newline at end of file diff --git a/lib/source/parser/image.js b/lib/source/parser/image.js new file mode 100644 index 0000000000..3048f9c5a0 --- /dev/null +++ b/lib/source/parser/image.js @@ -0,0 +1,56 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = image; + +var _ajax = require("../../util/ajax"); + +function image(data, cfg) { + var extent = cfg.extent; + var images = new Promise(function (resolve) { + loadData(data, function (res) { + resolve(res); + }); + }); + var resultData = { + images: images, + _id: 1, + dataArray: [{ + coordinates: [[extent[0], extent[1]], [extent[2], extent[3]]] + }] + }; + return resultData; +} + +function loadData(data, done) { + var url = data; + var image = []; + + if (typeof url === 'string') { + (0, _ajax.getImage)({ + url: url + }, function (err, img) { + image = img; + done(image); + }); + } else { + var imageCount = url.length; + var imageindex = 0; + url.forEach(function (item) { + (0, _ajax.getImage)({ + url: item + }, function (err, img) { + imageindex++; + image.push(img); + + if (imageindex === imageCount) { + done(image); + } + }); + }); + } + + return image; +} \ No newline at end of file diff --git a/lib/source/parser/json.js b/lib/source/parser/json.js new file mode 100644 index 0000000000..54819393b7 --- /dev/null +++ b/lib/source/parser/json.js @@ -0,0 +1,66 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = json; + +var _geojsonRewind = _interopRequireDefault(require("@mapbox/geojson-rewind")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +function json(data, cfg) { + var x = cfg.x, + y = cfg.y, + x1 = cfg.x1, + y1 = cfg.y1, + coordinates = cfg.coordinates; + var resultdata = []; + data.forEach(function (col, featureIndex) { + var coords = []; + + if (x && y) { + coords = [col[x], col[y]]; + } // 点数据 + + + if (x1 && y1) { + // 弧线 或者线段 + coords = [[col[x], col[y]], [col[x1], col[y1]]]; + } + + if (coordinates) { + var geometry = { + type: 'Polygon', + coordinates: _toConsumableArray(col[coordinates]) + }; + (0, _geojsonRewind["default"])(geometry, true); + coords = geometry.coordinates; + } + + col._id = featureIndex + 1; + + var dataItem = _objectSpread({}, col, { + coordinates: coords + }); + + resultdata.push(dataItem); + }); + return { + dataArray: resultdata + }; +} \ No newline at end of file diff --git a/lib/source/parser/mvt.js b/lib/source/parser/mvt.js new file mode 100644 index 0000000000..7f9a0f6991 --- /dev/null +++ b/lib/source/parser/mvt.js @@ -0,0 +1,39 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = mvt; + +var _pbf = _interopRequireDefault(require("pbf")); + +var VectorParser = _interopRequireWildcard(require("@mapbox/vector-tile")); + +var _geojson = _interopRequireDefault(require("./geojson")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function mvt(data, cfg) { + var tile = new VectorParser.VectorTile(new _pbf["default"](data)); + var layerName = cfg.sourceLayer; + var features = []; + var vectorLayer = tile.layers[layerName]; + + if (vectorLayer === undefined) { + return null; + } + + for (var i = 0; i < vectorLayer.length; i++) { + var feature = vectorLayer.feature(i); + var geofeature = feature.toGeoJSON(cfg.tile[0], cfg.tile[1], cfg.tile[2]); + features.push(geofeature); + } + + var geodata = { + type: 'FeatureCollection', + features: features + }; + return features.length === 0 ? null : (0, _geojson["default"])(geodata, cfg); +} \ No newline at end of file diff --git a/lib/source/parser/raster.js b/lib/source/parser/raster.js new file mode 100644 index 0000000000..d830b214db --- /dev/null +++ b/lib/source/parser/raster.js @@ -0,0 +1,26 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = raster; + +function raster(data, cfg) { + var extent = cfg.extent, + width = cfg.width, + height = cfg.height, + min = cfg.min, + max = cfg.max; + var resultData = { + _id: 1, + dataArray: [{ + data: Array.from(data), + width: width, + height: height, + min: min, + max: max, + coordinates: [[extent[0], extent[1]], [extent[2], extent[3]]] + }] + }; + return resultData; +} \ No newline at end of file diff --git a/lib/source/parser/vector.js b/lib/source/parser/vector.js new file mode 100644 index 0000000000..8404db854c --- /dev/null +++ b/lib/source/parser/vector.js @@ -0,0 +1,104 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = vector; + +var _bkdrHash = require("../../util/bkdr-hash"); + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var Extent = 4096; + +function vector(data, cfg) { + var tile = cfg.tile; + var resultdata = []; + var featureKeys = {}; + var x0 = Extent * tile[0]; + var y0 = Extent * tile[1]; + + function covertP20(points) { + return points.map(function (point) { + var x1 = (x0 + point.x << 20 - tile[2] - 4) - 215440491; + var y2 = (y0 + point.y << 20 - tile[2] - 4) - 106744817; + return [x1, -y2, 0]; + }); + } + + var index = 0; + + for (var i = 0; i < data.length; i++) { + var feature = data.feature(i); + var coords = feature.loadGeometry(); + var properties = feature.properties; + var id = i + 1; + + if (cfg.idField && properties[cfg.idField]) { + var value = properties[cfg.idField]; + id = (0, _bkdrHash.djb2hash)(value) % 1000019; + featureKeys[id] = { + index: index, + idField: value + }; + } + + var geocoords = classifyRings(coords); + + for (var j = 0; j < geocoords.length; j++) { + var geo = geocoords[j].map(function (coord) { + return covertP20(coord); + }); + index++; + resultdata.push(_objectSpread({}, properties, { + _id: feature.id || id, + coordinates: geo + })); + } + } + + return { + dataArray: resultdata, + featureKeys: featureKeys + }; +} + +function signedArea(ring) { + var sum = 0; + + for (var i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) { + p1 = ring[i]; + p2 = ring[j]; + sum += (p2.x - p1.x) * (p1.y + p2.y); + } + + return sum; +} + +function classifyRings(rings) { + var len = rings.length; + if (len <= 1) return [rings]; + var polygons = []; + var polygon; + var ccw; + + for (var i = 0; i < len; i++) { + var area = signedArea(rings[i]); + if (area === 0) continue; + if (ccw === undefined) ccw = area < 0; + + if (ccw === area < 0) { + if (polygon) polygons.push(polygon); + polygon = [rings[i]]; + } else { + polygon.push(rings[i]); + } + } + + if (polygon) polygons.push(polygon); + return polygons; +} \ No newline at end of file diff --git a/lib/source/rainSource.js b/lib/source/rainSource.js new file mode 100644 index 0000000000..4810da3ae0 --- /dev/null +++ b/lib/source/rainSource.js @@ -0,0 +1,88 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.RainSource = void 0; + +var _imageSource2 = _interopRequireDefault(require("./imageSource")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var RainSource = +/*#__PURE__*/ +function (_imageSource) { + _inherits(RainSource, _imageSource); + + function RainSource() { + _classCallCheck(this, RainSource); + + return _possibleConstructorReturn(this, _getPrototypeOf(RainSource).apply(this, arguments)); + } + + _createClass(RainSource, [{ + key: "prepareData", + value: function prepareData() { + var extent = this.get('extent'); + + var lb = this._coorConvert(extent.slice(0, 2)); + + var tr = this._coorConvert(extent.slice(2, 4)); + + this.extent = [lb, tr]; + this.propertiesData = []; + + this._genaratePoints(); + + this._loadData(); + } + }, { + key: "_genaratePoints", + value: function _genaratePoints() { + var numParticles = 512 * 512; + var particleRes = this.particleRes = Math.ceil(Math.sqrt(numParticles)); + var numPoints = particleRes * particleRes; + var particleState = []; + var particleState0 = new Uint8ClampedArray(numPoints * 4); + var particleState1 = new Uint8ClampedArray(numPoints * 4); + var emptyPixels = new Uint8ClampedArray(numPoints * 4); + + for (var i = 0; i < particleState0.length; i++) { + particleState0[i] = Math.floor(Math.random() * 256); // randomize the initial particle positions + } + + this.particleIndices = new Float32Array(numPoints); + + for (var _i = 0; _i < numPoints; _i++) { + this.particleIndices[_i] = _i; + } + + this.particleImage0 = new ImageData(particleState0, particleRes, particleRes); + this.particleImage1 = new ImageData(particleState1, particleRes, particleRes); + this.backgroundImage = new ImageData(emptyPixels, particleRes, particleRes); + this.geoData = particleState; + } + }]); + + return RainSource; +}(_imageSource2.default); + +exports.RainSource = RainSource; \ No newline at end of file diff --git a/lib/source/rasterSource.js b/lib/source/rasterSource.js new file mode 100644 index 0000000000..2ed58a7119 --- /dev/null +++ b/lib/source/rasterSource.js @@ -0,0 +1,66 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _source = _interopRequireDefault(require("../core/source")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var RasterSource = +/*#__PURE__*/ +function (_Source) { + _inherits(RasterSource, _Source); + + function RasterSource() { + _classCallCheck(this, RasterSource); + + return _possibleConstructorReturn(this, _getPrototypeOf(RasterSource).apply(this, arguments)); + } + + _createClass(RasterSource, [{ + key: "prepareData", + value: function prepareData() { + this.type = 'raster'; + var extent = this.get('extent'); + + var lb = this._coorConvert(extent.slice(0, 2)); + + var tr = this._coorConvert(extent.slice(2, 4)); + + this.geoData = [lb, tr]; + this.propertiesData = []; + this.rasterData = { + data: this.get('data'), + width: this.get('width'), + height: this.get('height'), + min: this.get('min'), + max: this.get('max') + }; + } + }]); + + return RasterSource; +}(_source.default); + +exports.default = RasterSource; \ No newline at end of file diff --git a/lib/source/source_cache.js b/lib/source/source_cache.js new file mode 100644 index 0000000000..dc2ae00fb4 --- /dev/null +++ b/lib/source/source_cache.js @@ -0,0 +1,450 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("../core/base")); + +var _tile_cache = _interopRequireDefault(require("../layer/tile/tile_cache")); + +var _vector_tile_source = _interopRequireDefault(require("./vector_tile_source")); + +var _geoCoord = require("@antv/geo-coord"); + +var _vector_tile_mesh = _interopRequireDefault(require("../layer/tile/vector_tile_mesh")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } + +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +// 统一管理 source 添加,管理,更新 +var SouceCache = +/*#__PURE__*/ +function (_Base) { + _inherits(SouceCache, _Base); + + function SouceCache(scene, cfg) { + var _this; + + _classCallCheck(this, SouceCache); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(SouceCache).call(this, _objectSpread({ + cacheLimit: 50, + minZoom: 0, + maxZoom: 18, + keepBuffer: 0 + }, cfg))); + _this._tileMap = {}; // 视野内瓦片坐标序列 + + _this.tileList = {}; // 正在使用的瓦片坐标,记录瓦片的使用状态 + + _this.scene = scene; // TODO 销毁函数 + + _this._tileCache = new _tile_cache["default"](_this.get('cacheLimit'), _this._destroyTile.bind(_assertThisInitialized(_this))); + _this.layers = _this.scene.getLayers(); + _this._source = new _vector_tile_source["default"](cfg, _this.scene.style.WorkerController); + _this.layersTiles = {}; // 存储当前source所有layer的瓦片 + // this._tiles = new THREE.Object3D(); + + return _this; + } + + _createClass(SouceCache, [{ + key: "getLayerById", + value: function getLayerById(id) { + var layers = this.scene.getLayers(); + + for (var i = 0; i < layers.length; i += 1) { + if (layers[i].layerId === id * 1) { + return layers[i]; + } + } + } + /** + * 移除视野外的瓦片,计算新增的瓦片数据 + * @param {*}tileMap 瓦片列表 + */ + + }, { + key: "update", + value: function update() { + var _this2 = this; + + // if (!layercfg && this.layercfg) return; + // this._layercfg = layercfg; + this._calculateTileIDs(); // this.updateList = this._getNewTiles(this._tileMap);// 计算新增瓦片 + // this._pruneTiles(); + + + var _loop = function _loop(i) { + // 瓦片相关参数 + var tileId = _this2.updateTileList[i].join('_'); + + var tileinfo = _this2.tileList[tileId]; + tileinfo.loading = true; + + var tiles = _this2._tileCache.getTile(tileId); + + if (tiles !== undefined) { + tileinfo.active = true; + tileinfo.loaded = true; + + for (var layerId in tiles) { + var layer = _this2.getLayerById(layerId); + + var tileMesh = tiles[layerId]; + layer.tiles.add(tileMesh.getMesh()); + + _this2.scene._engine.update(); + } + + _this2._pruneTiles(); + + return "continue"; + } + + _this2._source.loadTile(tileinfo, function (err, data) { + if (!err && data !== undefined) { + _this2._renderTile(tileinfo, data); + + tileinfo.active = true; + } + + tileinfo.loaded = true; + + _this2._pruneTiles(); + }); + }; + + for (var i = 0; i < this.updateTileList.length; i++) { + var _ret = _loop(i); + + if (_ret === "continue") continue; + } + } + }, { + key: "_renderTile", + value: function _renderTile(tileinfo, data) { + var tileId = tileinfo.id; + var tiles = {}; + + for (var layerId in data) { + var layer = this.getLayerById(layerId); + var tileMesh = new _vector_tile_mesh["default"](layer, data[layerId]); + tiles[layerId] = tileMesh; + layer.tiles.add(tileMesh.getMesh()); + + this.scene._engine.update(); + } + + this._tileCache.setTile(tiles, tileId); + } // 计算视野内的瓦片坐标 + + }, { + key: "_calculateTileIDs", + value: function _calculateTileIDs() { + this._tileMap = {}; + this.updateTileList = []; + var zoom = Math.floor(this.scene.getZoom()); // - window.window.devicePixelRatio + 1; // zoom - 1 + + var minSourceZoom = this.get('minZoom'); + var maxSourceZoom = this.get('maxZoom'); + this.tileZoom = zoom > maxSourceZoom ? maxSourceZoom : zoom; + var currentZoom = this.scene.getZoom(); + + if (currentZoom < minSourceZoom) { + this._removeTiles(); // 小于source最小范围不在处理 + + + return; + } + + var pixelBounds = this._getPixelBounds(); + + var tileRange = this._pxBoundsToTileRange(pixelBounds); + + var margin = this.get('keepBuffer'); + var center = this.scene.getCenter(); + var centerPoint = this.scene.crs.lngLatToPoint((0, _geoCoord.toLngLat)(center.lng, center.lat), this.tileZoom); + var centerXY = centerPoint.divideBy(256).floor(); + this._noPruneRange = new _geoCoord.Bounds(tileRange.getBottomLeft().subtract([margin, -margin]), tileRange.getTopRight().add([margin, -margin])); + + if (!(isFinite(tileRange.min.x) && isFinite(tileRange.min.y) && isFinite(tileRange.max.x) && isFinite(tileRange.max.y))) { + throw new Error('Attempted to load an infinite number of tiles'); + } + + for (var j = tileRange.min.y; j <= tileRange.max.y; j++) { + for (var i = tileRange.min.x; i <= tileRange.max.x; i++) { + var coords = [i, j, this.tileZoom]; + var tile = this.tileList[coords.join('_')]; + + if (tile && tile.loading) { + tile.current = true; + tile.retain = true; + } else { + this.tileList[coords.join('_')] = { + current: true, + active: false, + retain: true, + loading: false, + coords: coords, + id: coords.join('_') + }; + this.updateTileList.push(coords); + } + } + } // 根据中心点排序 + + + this.updateTileList.sort(function (a, b) { + var tile1 = a; + var tile2 = b; + var d1 = Math.pow(tile1[0] * 1 - centerXY.x, 2) + Math.pow(tile1[1] * 1 - centerXY.y, 2); + var d2 = Math.pow(tile2[0] * 1 - centerXY.x, 2) + Math.pow(tile2[1] * 1 - centerXY.y, 2); + return d1 - d2; + }); + + this._pruneTiles(); + } + }, { + key: "_getPixelBounds", + value: function _getPixelBounds() { + var viewPort = this.scene.getBounds().toBounds(); + var NE = viewPort.getNorthEast(); + var SW = viewPort.getSouthWest(); + var zoom = this.tileZoom; + var center = this.scene.getCenter(); + var NEPoint = this.scene.crs.lngLatToPoint((0, _geoCoord.toLngLat)(NE.lng, NE.lat), zoom); + var SWPoint = this.scene.crs.lngLatToPoint((0, _geoCoord.toLngLat)(SW.lng, SW.lat), zoom); + var centerPoint = this.scene.crs.lngLatToPoint((0, _geoCoord.toLngLat)(center.lng, center.lat), zoom); + var topHeight = centerPoint.y - NEPoint.y; + var bottomHeight = SWPoint.y - centerPoint.y; // 跨日界线的情况 + + var leftWidth; + var rightWidth; + + if (center.lng - NE.lng > 0 || center.lng - SW.lng < 0) { + var width = Math.pow(2, zoom) * 256 / 360 * (180 - NE.lng) + Math.pow(2, zoom) * 256 / 360 * (SW.lng + 180); + + if (center.lng - NE.lng > 0) { + // 日界线在右侧 + leftWidth = Math.pow(2, zoom) * 256 / 360 * (center.lng - NE.lng); + rightWidth = width - leftWidth; + } else { + rightWidth = Math.pow(2, zoom) * 256 / 360 * (SW.lng - center.lng); + leftWidth = width - rightWidth; + } + } else { + // 不跨日界线 + leftWidth = Math.pow(2, zoom) * 256 / 360 * (center.lng - SW.lng); + rightWidth = Math.pow(2, zoom) * 256 / 360 * (NE.lng - center.lng); + } + + var pixelBounds = new _geoCoord.Bounds(centerPoint.subtract(leftWidth, topHeight), centerPoint.add(rightWidth, bottomHeight)); + return pixelBounds; + } + }, { + key: "_pxBoundsToTileRange", + value: function _pxBoundsToTileRange(pixelBounds) { + return new _geoCoord.Bounds(pixelBounds.min.divideBy(256).floor(), pixelBounds.max.divideBy(256).ceil().subtract([1, 1])); + } + }, { + key: "_loadTile", + value: function _loadTile(tile, callback) { + return this._source.loadTile(tile, callback); + } + }, { + key: "_unloadTile", + value: function _unloadTile(tile) { + if (this._source.unloadTile) { + return this._source.unloadTile(tile, function () {}); + } + } + }, { + key: "_abortTile", + value: function _abortTile(tile) { + if (this._source.abortTile) { + return this._source.abortTile(tile, function () {}); + } + } + }, { + key: "reload", + value: function reload() {} + }, { + key: "_reloadTile", + value: function _reloadTile() {} + }, { + key: "_removeTile", + value: function _removeTile() {} + }, { + key: "clearTiles", + value: function clearTiles() {} + }, { + key: "_pruneTiles", + value: function _pruneTiles() { + var tile; + var zoom = this.tileZoom; + + for (var key in this.tileList) { + var c = this.tileList[key].coords; + + if (c[2] !== zoom || !this._noPruneRange.contains(new _geoCoord.Point(c[0], c[1]))) { + this.tileList[key].current = false; + this.tileList[key].retain = false; + } + } + + for (var _key in this.tileList) { + tile = this.tileList[_key]; + + if (tile.current && !tile.active) { + var _key$split$map = _key.split('_').map(function (v) { + return v * 1; + }), + _key$split$map2 = _slicedToArray(_key$split$map, 3), + x = _key$split$map2[0], + y = _key$split$map2[1], + z = _key$split$map2[2]; + + if (!this._retainParent(x, y, z, z - 5)) { + this._retainChildren(x, y, z, z + 2); + } + } + } + + this._removeOutTiles(); + } + }, { + key: "_retainParent", + value: function _retainParent(x, y, z, minZoom) { + var x2 = Math.floor(x / 2); + var y2 = Math.floor(y / 2); + var z2 = z - 1; + var tile = this.tileList[[x2, y2, z2].join('_')]; + + if (tile && tile.active) { + tile.retain = true; + tile.current = true; + return true; + } else if (tile && tile.loaded) { + tile.retain = true; + } + + if (z2 > minZoom) { + return this._retainParent(x2, y2, z2, minZoom); + } + + return false; + } + }, { + key: "_retainChildren", + value: function _retainChildren(x, y, z, maxZoom) { + for (var i = 2 * x; i < 2 * x + 2; i++) { + for (var j = 2 * y; j < 2 * y + 2; j++) { + var key = [i, j, z + 1].join('_'); + var tile = this.tileList[key]; + + if (tile && tile.active) { + tile.retain = true; + tile.current = true; + continue; + } else if (tile && tile.loaded) { + tile.retain = true; + tile.current = true; + } + + if (z + 1 < maxZoom) { + this._retainChildren(i, j, z + 1, maxZoom); + } + } + } + } + }, { + key: "_removeOutTiles", + value: function _removeOutTiles() { + var _this3 = this; + + // 移除视野外的tile + for (var key in this.tileList) { + if (!this.tileList[key].retain) { + this._abortTile(this.tileList[key]); + + this._unloadTile(this.tileList[key]); + + delete this.tileList[key]; + } + } + + var layers = this.scene.getLayers(); + + var _loop2 = function _loop2(i) { + var id = _this3.get('sourceID'); + + var layerSource = layers[i].get('sourceOption').id; + + if (layerSource !== id) { + return { + v: void 0 + }; + } + + layers[i].tiles.children.forEach(function (tile) { + var key = tile.name; + + if (!_this3.tileList[key]) { + layers[i].tiles.remove(tile); + } + }); + }; + + for (var i = 0; i < layers.length; i++) { + var _ret2 = _loop2(i); + + if (_typeof(_ret2) === "object") return _ret2.v; + } // 移除对应的数据 + + } + }, { + key: "_destroyTile", + value: function _destroyTile(tile, key) { + this._unloadTile(key); + } // 移除视野外的tile + + }]); + + return SouceCache; +}(_base["default"]); + +exports["default"] = SouceCache; \ No newline at end of file diff --git a/lib/source/tileDataCache.js b/lib/source/tileDataCache.js new file mode 100644 index 0000000000..2aaad73c6e --- /dev/null +++ b/lib/source/tileDataCache.js @@ -0,0 +1,55 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _lruCache = _interopRequireDefault(require("../util/lru-cache")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var TileDataCache = +/*#__PURE__*/ +function () { + function TileDataCache() { + var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 50; + var tileDestroy = arguments.length > 1 ? arguments[1] : undefined; + + _classCallCheck(this, TileDataCache); + + this._cache = new _lruCache["default"](limit, tileDestroy); + } + + _createClass(TileDataCache, [{ + key: "getTile", + value: function getTile(key) { + return this._cache.get(key); + } + }, { + key: "setTile", + value: function setTile(tile, key) { + this._cache.set(key, tile); + } + }, { + key: "removeTile", + value: function removeTile(key) { + return this._cache["delete"](key); + } + }, { + key: "destory", + value: function destory() { + this._cache.clear(); + } + }]); + + return TileDataCache; +}(); + +exports["default"] = TileDataCache; \ No newline at end of file diff --git a/lib/source/tileSource.js b/lib/source/tileSource.js new file mode 100644 index 0000000000..ea62fb1a5b --- /dev/null +++ b/lib/source/tileSource.js @@ -0,0 +1,179 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _source = _interopRequireDefault(require("../core/source")); + +var _ajax = require("../util/ajax"); + +var _tileDataCache = _interopRequireDefault(require("./tileDataCache")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var tileURLRegex = /\{([zxy])\}/g; + +var TileSource = +/*#__PURE__*/ +function (_Source) { + _inherits(TileSource, _Source); + + function TileSource(url, cfg) { + var _this; + + _classCallCheck(this, TileSource); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(TileSource).call(this, cfg)); + _this.cfg = cfg; + _this.urlTemplate = url; + _this._tileDataCache = new _tileDataCache["default"](50, _this.tileDestroy); + _this.type = 'tile'; + return _this; + } + + _createClass(TileSource, [{ + key: "getTileData", + value: function getTileData(x, y, z) { + var _this2 = this; + + var key = [x, y, z].join('_'); + + var tileData = this._tileDataCache.getTile(key); + + if (!tileData) { + var tiledataPromise = new Promise(function (resolve) { + if (tileData) { + setTimeout(function () { + resolve(tileData); + }, 0); + } else { + _this2._requestTileData(x, y, z, resolve); + } + }); + tileData = { + loading: true, + data: tiledataPromise + }; + + this._tileDataCache.setTile(tileData, key); + + return tileData; + } + + return tileData; + } + }, { + key: "_init", + value: function _init() { + var parser = this.get('parser'); + this.set('minSourceZoom', parser && parser.minZoom || 0); + this.set('maxSourceZoom', parser && parser.maxZoom || 18); + } + }, { + key: "_generateSource", + value: function _generateSource(x, y, z, data) { + this.cfg.parser.tile = [x, y, z]; + var tileData = new _source["default"](_objectSpread({}, this.cfg, { + mapType: this.get('mapType'), + data: data, + tile: [x, y, z] + })); + return tileData; + } + }, { + key: "_requestTileData", + value: function _requestTileData(x, y, z, done) { + var _this3 = this; + + var urlParams = { + x: x, + y: y, + z: z + }; + + var url = this._getTileURL(urlParams); + + var key = [x, y, z].join('_'); + this.xhrRequest = (0, _ajax.getArrayBuffer)({ + url: url + }, function (err, data) { + if (err) { + _this3._noData = true; + + _this3._tileDataCache.setTile({ + loaded: true, + data: { + data: null + } + }, key); + + return; + } + + var tileData = _this3._generateSource(x, y, z, data.data); + + _this3._tileDataCache.setTile({ + loaded: true, + data: tileData + }, key); + + done(tileData); + }); + } + }, { + key: "_getTileURL", + value: function _getTileURL(urlParams) { + if (!urlParams.s) { + // Default to a random choice of a, b or c + urlParams.s = String.fromCharCode(97 + Math.floor(Math.random() * 3)); + } + + tileURLRegex.lastIndex = 0; + return this.urlTemplate.replace(tileURLRegex, function (value, key) { + return urlParams[key]; + }); + } + }, { + key: "tileDestroy", + value: function tileDestroy(tile) { + if (!tile || !tile.data || tile.loading || !tile.data.data.dataArray) { + return; + } + + var tileData = tile.data; + tileData.destroy(); + tileData.data.dataArray.length = 0; + tileData.data.featureKeys = null; + tileData.originData.dataArray.length = 0; + tileData.originData.featureKeys = null; + } + }]); + + return TileSource; +}(_source["default"]); + +exports["default"] = TileSource; \ No newline at end of file diff --git a/lib/source/tile_data_cache.js b/lib/source/tile_data_cache.js new file mode 100644 index 0000000000..2aaad73c6e --- /dev/null +++ b/lib/source/tile_data_cache.js @@ -0,0 +1,55 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _lruCache = _interopRequireDefault(require("../util/lru-cache")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var TileDataCache = +/*#__PURE__*/ +function () { + function TileDataCache() { + var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 50; + var tileDestroy = arguments.length > 1 ? arguments[1] : undefined; + + _classCallCheck(this, TileDataCache); + + this._cache = new _lruCache["default"](limit, tileDestroy); + } + + _createClass(TileDataCache, [{ + key: "getTile", + value: function getTile(key) { + return this._cache.get(key); + } + }, { + key: "setTile", + value: function setTile(tile, key) { + this._cache.set(key, tile); + } + }, { + key: "removeTile", + value: function removeTile(key) { + return this._cache["delete"](key); + } + }, { + key: "destory", + value: function destory() { + this._cache.clear(); + } + }]); + + return TileDataCache; +}(); + +exports["default"] = TileDataCache; \ No newline at end of file diff --git a/lib/source/tile_source.js b/lib/source/tile_source.js new file mode 100644 index 0000000000..ccf1f28a62 --- /dev/null +++ b/lib/source/tile_source.js @@ -0,0 +1,187 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _source = _interopRequireDefault(require("../core/source")); + +var _ajax = require("../util/ajax"); + +var _tile_data_cache = _interopRequireDefault(require("./tile_data_cache")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var tileURLRegex = /\{([zxy])\}/g; + +var TileSource = +/*#__PURE__*/ +function (_Source) { + _inherits(TileSource, _Source); + + function TileSource(url, cfg) { + var _this; + + _classCallCheck(this, TileSource); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(TileSource).call(this, cfg)); + _this.cfg = cfg; + _this.urlTemplate = url; + _this._tileDataCache = new _tile_data_cache["default"](50, _this.tileDestroy); + _this.type = 'tile'; + return _this; + } + + _createClass(TileSource, [{ + key: "getTileData", + value: function getTileData(x, y, z) { + var _this2 = this; + + var key = [x, y, z].join('_'); + + var tileData = this._tileDataCache.getTile(key); + + if (!tileData) { + var tiledataPromise = new Promise(function (resolve) { + if (tileData) { + setTimeout(function () { + resolve(tileData); + }, 0); + } else { + _this2._requestTileData(x, y, z, resolve); + } + }); + tileData = { + loading: true, + data: tiledataPromise + }; + + this._tileDataCache.setTile(tileData, key); + + return tileData; + } + + return tileData; + } + }, { + key: "_init", + value: function _init() { + var parser = this.get('parser'); + this.set('minSourceZoom', parser && parser.minZoom || 0); + this.set('maxSourceZoom', parser && parser.maxZoom || 18); + } + }, { + key: "_generateSource", + value: function _generateSource(x, y, z, data) { + this.cfg.parser.tile = [x, y, z]; + var tileData = new _source["default"](_objectSpread({}, this.cfg, { + mapType: this.get('mapType'), + data: data, + tile: [x, y, z] + })); + return tileData; + } + }, { + key: "_requestTileData", + value: function _requestTileData(x, y, z, done) { + var _this3 = this; + + var urlParams = { + x: x, + y: y, + z: z + }; + + var url = this._getTileURL(urlParams); + + var key = [x, y, z].join('_'); + this.xhrRequest = (0, _ajax.getArrayBuffer)({ + url: url + }, function (err, data) { + if (err) { + _this3._noData = true; + + _this3._tileDataCache.setTile({ + loaded: true, + data: { + data: null + } + }, key); + + return; + } + + var tileData = _this3._generateSource(x, y, z, data.data); + + _this3._tileDataCache.setTile({ + loaded: true, + data: tileData + }, key); + + done(tileData); + }); + } + }, { + key: "getRequestUrl", + value: function getRequestUrl(x, y, z) { + var urlParams = { + x: x, + y: y, + z: z + }; + return this._getTileURL(urlParams); + } + }, { + key: "_getTileURL", + value: function _getTileURL(urlParams) { + if (!urlParams.s) { + // Default to a random choice of a, b or c + urlParams.s = String.fromCharCode(97 + Math.floor(Math.random() * 3)); + } + + tileURLRegex.lastIndex = 0; + return this.urlTemplate.replace(tileURLRegex, function (value, key) { + return urlParams[key]; + }); + } + }, { + key: "tileDestroy", + value: function tileDestroy(tile) { + if (!tile || !tile.data || tile.loading || !tile.data.data || !tile.data.data.dataArray) { + return; + } + + var tileData = tile.data; + tileData.destroy(); + } + }]); + + return TileSource; +}(_source["default"]); + +exports["default"] = TileSource; \ No newline at end of file diff --git a/lib/source/transform/cluster.js b/lib/source/transform/cluster.js new file mode 100644 index 0000000000..4b779e89d2 --- /dev/null +++ b/lib/source/transform/cluster.js @@ -0,0 +1,85 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.cluster = cluster; +exports.formatData = formatData; + +var _supercluster = _interopRequireDefault(require("supercluster/dist/supercluster")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function cluster(data, option) { + var _option$radius = option.radius, + radius = _option$radius === void 0 ? 80 : _option$radius, + _option$maxZoom = option.maxZoom, + maxZoom = _option$maxZoom === void 0 ? 18 : _option$maxZoom, + _option$minZoom = option.minZoom, + minZoom = _option$minZoom === void 0 ? 0 : _option$minZoom, + field = option.field, + _option$zoom = option.zoom, + zoom = _option$zoom === void 0 ? 2 : _option$zoom; + + if (data.pointIndex) { + var _clusterPoint = data.pointIndex.getClusters(data.extent, zoom); + + data.dataArray = formatData(_clusterPoint); + return data; + } + + var pointIndex = new _supercluster["default"]({ + radius: radius, + minZoom: minZoom, + maxZoom: maxZoom, + map: function map(props) { + return { + sum: props[field] + }; + }, + reduce: function reduce(accumulated, props) { + accumulated.sum += props.sum; + } + }); + var geojson = { + type: 'FeatureCollection' + }; + geojson.features = data.dataArray.map(function (item) { + return { + type: 'Feature', + properties: _defineProperty({}, field, item[field]), + geometry: { + type: 'Point', + coordinates: item.coordinates + } + }; + }); + pointIndex.load(geojson.features); + var clusterPoint = pointIndex.getClusters(data.extent, zoom); + var resultData = clusterPoint.map(function (point, index) { + return _objectSpread({ + coordinates: point.geometry.coordinates, + _id: index + 1 + }, point.properties); + }); + data.dataArray = resultData; + return { + data: data, + pointIndex: pointIndex + }; +} + +function formatData(clusterPoint) { + return clusterPoint.map(function (point, index) { + return _objectSpread({ + coordinates: point.geometry.coordinates, + _id: index + 1 + }, point.properties); + }); +} \ No newline at end of file diff --git a/lib/source/transform/grid.js b/lib/source/transform/grid.js new file mode 100644 index 0000000000..80cc9ffd3b --- /dev/null +++ b/lib/source/transform/grid.js @@ -0,0 +1,135 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.aggregatorToGrid = aggregatorToGrid; + +var statistics = _interopRequireWildcard(require("./statistics")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +/** + * 生成四边形热力图 + */ +var R_EARTH = 6378000; + +function aggregatorToGrid(data, option) { + var dataArray = data.dataArray; + var _option$size = option.size, + size = _option$size === void 0 ? 10 : _option$size; + + var _pointsGridHash2 = _pointsGridHash(dataArray, size), + gridHash = _pointsGridHash2.gridHash, + gridOffset = _pointsGridHash2.gridOffset; + + var layerData = _getGridLayerDataFromGridHash(gridHash, gridOffset, option); + + return { + yOffset: gridOffset.xOffset / 360 * (256 << 20) / 2, + xOffset: gridOffset.xOffset / 360 * (256 << 20) / 2, + radius: gridOffset.xOffset / 360 * (256 << 20) / 2, + dataArray: layerData + }; +} + +function _pointsGridHash(dataArray, size) { + var latMin = Infinity; + var latMax = -Infinity; + var pLat; + + for (var index = 0; index < dataArray.length; index++) { + var point = dataArray[index]; + pLat = point.coordinates[1]; + + if (Number.isFinite(pLat)) { + latMin = pLat < latMin ? pLat : latMin; + latMax = pLat > latMax ? pLat : latMax; + } + } // const centerLat = (latMin + latMax) / 2; + + + var centerLat = 34.54083; + + var gridOffset = _calculateGridLatLonOffset(size, centerLat); + + if (gridOffset.xOffset <= 0 || gridOffset.yOffset <= 0) { + return { + gridHash: {}, + gridOffset: gridOffset + }; + } + + var gridHash = {}; + + for (var _index = 0; _index < dataArray.length; _index++) { + var _point = dataArray[_index]; + var lat = _point.coordinates[1]; + var lng = _point.coordinates[0]; + + if (Number.isFinite(lat) && Number.isFinite(lng)) { + var latIdx = Math.floor((lat + 90) / gridOffset.yOffset); + var lonIdx = Math.floor((lng + 180) / gridOffset.xOffset); + var key = "".concat(latIdx, "-").concat(lonIdx); + gridHash[key] = gridHash[key] || { + count: 0, + points: [] + }; + gridHash[key].count += 1; + gridHash[key].points.push(_point); + } + } + + return { + gridHash: gridHash, + gridOffset: gridOffset + }; +} // 计算网格偏移量 + + +function _calculateGridLatLonOffset(cellSize, latitude) { + var yOffset = _calculateLatOffset(cellSize); + + var xOffset = _calculateLonOffset(latitude, cellSize); + + return { + yOffset: yOffset, + xOffset: xOffset + }; +} + +function _calculateLatOffset(dy) { + return dy / R_EARTH * (180 / Math.PI); +} + +function _calculateLonOffset(lat, dx) { + return dx / R_EARTH * (180 / Math.PI) / Math.cos(lat * Math.PI / 180); +} + +function _getGridLayerDataFromGridHash(gridHash, gridOffset, option) { + return Object.keys(gridHash).reduce(function (accu, key, i) { + var idxs = key.split('-'); + var latIdx = parseInt(idxs[0], 10); + var lonIdx = parseInt(idxs[1], 10); + var item = {}; + + if (option.field && option.method) { + var columns = getColumn(gridHash[key].points, option.field); + item[option.method] = statistics[option.method](columns); + } + + Object.assign(item, { + _id: i + 1, + coordinates: [-180 + gridOffset.xOffset * lonIdx, -90 + gridOffset.yOffset * latIdx], + count: gridHash[key].count + }); + accu.push(item); + return accu; + }, []); +} + +function getColumn(data, columnName) { + return data.map(function (item) { + return item[columnName]; + }); +} \ No newline at end of file diff --git a/lib/source/transform/hexagon.js b/lib/source/transform/hexagon.js new file mode 100644 index 0000000000..6667fff284 --- /dev/null +++ b/lib/source/transform/hexagon.js @@ -0,0 +1,68 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.pointToHexbin = pointToHexbin; + +var _d3Hexbin = require("d3-hexbin"); + +var _project = require("../../geo/project"); + +var statistics = _interopRequireWildcard(require("./statistics")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var R_EARTH = 6378000; + +function pointToHexbin(data, option) { + var dataArray = data.dataArray; + var _option$size = option.size, + size = _option$size === void 0 ? 10 : _option$size; + var pixlSize = size / (2 * Math.PI * R_EARTH) * (256 << 20) / 2; + var screenPoints = dataArray.map(function (point) { + var _aProjectFlat = (0, _project.aProjectFlat)(point.coordinates), + x = _aProjectFlat.x, + y = _aProjectFlat.y; + + return _objectSpread({}, point, { + coordinates: [x, y] + }); + }); + var newHexbin = (0, _d3Hexbin.hexbin)().radius(pixlSize).x(function (d) { + return d.coordinates[0]; + }).y(function (d) { + return d.coordinates[1]; + }); + var hexbinBins = newHexbin(screenPoints); + var result = { + radius: pixlSize + }; + result.dataArray = hexbinBins.map(function (hex, index) { + if (option.field && option.method) { + var columns = getColumn(hex, option.field); + hex[option.method] = statistics[option.method](columns); + } + + var item = {}; + item[option.method] = hex[option.method]; + return _objectSpread({}, item, { + count: hex.length, + coordinates: (0, _project.unProjectFlat)([hex.x, hex.y]), + _id: index + 1 + }); + }); + return result; +} + +function getColumn(data, columnName) { + return data.map(function (item) { + return item[columnName]; + }); +} \ No newline at end of file diff --git a/lib/source/transform/map.js b/lib/source/transform/map.js new file mode 100644 index 0000000000..ac4aa6c43f --- /dev/null +++ b/lib/source/transform/map.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.map = map; + +function map(data, options) { + var callback = options.callback; + + if (callback) { + data.dataArray = data.dataArray.map(callback); + } + + return data; +} \ No newline at end of file diff --git a/lib/source/transform/statistics.js b/lib/source/transform/statistics.js new file mode 100644 index 0000000000..8ca64c259b --- /dev/null +++ b/lib/source/transform/statistics.js @@ -0,0 +1,82 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.sum = sum; +exports.max = max; +exports.min = min; +exports.mean = mean; + +function max(x) { + if (x.length === 0) { + throw new Error('max requires at least one data point'); + } + + var value = x[0]; + + for (var i = 1; i < x.length; i++) { + // On the first iteration of this loop, max is + // undefined and is thus made the maximum element in the array + if (x[i] > value) { + value = x[i]; + } + } + + return value; +} + +function min(x) { + if (x.length === 0) { + throw new Error('min requires at least one data point'); + } + + var value = x[0]; + + for (var i = 1; i < x.length; i++) { + // On the first iteration of this loop, min is + // undefined and is thus made the minimum element in the array + if (x[i] < value) { + value = x[i]; + } + } + + return value; +} + +function sum(x) { + // If the array is empty, we needn't bother computing its sum + if (x.length === 0) { + return 0; + } // Initializing the sum as the first number in the array + + + var sum = x[0]; // Keeping track of the floating-point error correction + + var correction = 0; + var transition; + + for (var i = 1; i < x.length; i++) { + transition = sum + x[i]; // Here we need to update the correction in a different fashion + // if the new absolute value is greater than the absolute sum + + if (Math.abs(sum) >= Math.abs(x[i])) { + correction += sum - transition + x[i]; + } else { + correction += x[i] - transition + sum; + } + + sum = transition; + } // Returning the corrected sum + + + return sum + correction; +} + +function mean(x) { + if (x.length === 0) { + throw new Error('mean requires at least one data point'); + } + + return sum(x) / x.length; +} \ No newline at end of file diff --git a/lib/source/vector_tile_source.js b/lib/source/vector_tile_source.js new file mode 100644 index 0000000000..5ed6dab699 --- /dev/null +++ b/lib/source/vector_tile_source.js @@ -0,0 +1,118 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _base = _interopRequireDefault(require("../core/base")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var tileURLRegex = /\{([zxy])\}/g; + +var VectorTileSource = +/*#__PURE__*/ +function (_Base) { + _inherits(VectorTileSource, _Base); + + function VectorTileSource(cfg, workerController) { + var _this; + + _classCallCheck(this, VectorTileSource); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(VectorTileSource).call(this, _objectSpread({ + type: 'vector' + }, cfg))); + _this.cfg = cfg; + _this.workerController = workerController; + _this.urlTemplate = _this.get('url'); + return _this; + } + + _createClass(VectorTileSource, [{ + key: "loadTile", + value: function loadTile(tileinfo, callback) { + var tileId = tileinfo.id.split('_'); + + var url = this._getTileURL({ + x: tileId[0], + y: tileId[1], + z: tileId[2] + }); + + var params = _objectSpread({ + id: tileinfo.id, + type: 'vector' + }, this.cfg, { + url: url + }); + + tileinfo.workerID = this.workerController.send('loadTile', params, done.bind(this)); + + function done(err, data) { + // 收到数据,处理数据 + callback(err, data); + } + } + }, { + key: "abortTile", + value: function abortTile(tileinfo) { + this.workerController.send('abortTile', { + id: tileinfo.id, + type: this.get('type'), + sourceID: this.get('sourceID') + }, undefined, tileinfo.workerID); + } + }, { + key: "unloadTile", + value: function unloadTile(tileinfo) { + this.workerController.send('removeTile', { + id: tileinfo.id, + type: this.get('type'), + sourceID: this.get('sourceID') + }, undefined, tileinfo.workerID); + } + }, { + key: "_getTileURL", + value: function _getTileURL(urlParams) { + if (!urlParams.s) { + // Default to a random choice of a, b or c + urlParams.s = String.fromCharCode(97 + Math.floor(Math.random() * 3)); + } + + tileURLRegex.lastIndex = 0; + return this.urlTemplate.replace(tileURLRegex, function (value, key) { + return urlParams[key]; + }); + } + }]); + + return VectorTileSource; +}(_base["default"]); + +exports["default"] = VectorTileSource; \ No newline at end of file diff --git a/lib/source/vector_tile_worker_source.js b/lib/source/vector_tile_worker_source.js new file mode 100644 index 0000000000..b03c92886d --- /dev/null +++ b/lib/source/vector_tile_worker_source.js @@ -0,0 +1,165 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _ajax = require("../util/ajax"); + +var _pbf = _interopRequireDefault(require("pbf")); + +var VectorParser = _interopRequireWildcard(require("@mapbox/vector-tile")); + +var _workerTile = _interopRequireDefault(require("../worker/workerTile")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +// import WorkerTile from '../worker/workerTile'; +function loadVectorTile(params, callback) { + var request = (0, _ajax.getArrayBuffer)({ + url: params.url + }, function (err, data) { + if (err) { + callback(err); + } else if (data) { + callback(null, { + vectorTile: new VectorParser.VectorTile(new _pbf["default"](data.data)), + rawData: data.data + }); + } + }); + return function () { + request.abort(); + callback(); + }; +} + +var VectorTileWorkerSource = +/*#__PURE__*/ +function () { + function VectorTileWorkerSource(actor, layerStyle, loadVectorData) { + _classCallCheck(this, VectorTileWorkerSource); + + this.actor = actor; + this.layerStyle = layerStyle; + this.loadVectorData = loadVectorData || loadVectorTile; + this.loaded = {}; + this.loading = {}; + } + + _createClass(VectorTileWorkerSource, [{ + key: "loadTile", + value: function loadTile(params, callback) { + var _this = this; + + var uid = params.id; + + if (!this.loading) { + this.loading = {}; + } + + var workerTile = this.loading[uid] = new _workerTile["default"](params); + workerTile.abort = this.loadVectorData(params, function (err, response) { + if (err || !response) { + workerTile.status = 'done'; + _this.loaded[uid] = workerTile; + return callback(err); + } // const rawTileData = response.rawData; + + + workerTile.vectorTile = response.vectorTile; + workerTile.parse(response.vectorTile, _this.layerStyle, _this.actor, function (err, result) { + if (err || !result) return callback(err); // Transferring a copy of rawTileData because the worker needs to retain its copy. + + callback(null, _objectSpread({}, result)); + }); + _this.loaded = _this.loaded || {}; + _this.loaded[uid] = workerTile; + }); + } + }, { + key: "abortTile", + value: function abortTile(params, callback) { + var loading = this.loading; + var uid = params.id; + + if (loading && loading[uid] && loading[uid].abort) { + loading[uid].abort(); + delete loading[uid]; + } + + callback(); + } + }, { + key: "reloadTile", + value: function reloadTile(params, callback) { + // 重新加载 tile + var loaded = this.loaded, + uid = params.id, + vtSource = this; + + if (loaded && loaded[uid]) { + var workerTile = loaded[uid]; + + var done = function done(err, data) { + var reloadCallback = workerTile.reloadCallback; + + if (reloadCallback) { + delete workerTile.reloadCallback; + workerTile.parse(workerTile.vectorTile, vtSource.layerStyle, vtSource.actor, reloadCallback); + } + + callback(err, data); + }; + + if (workerTile.status === 'parsing') { + workerTile.reloadCallback = done; + } else if (workerTile.status === 'done') { + // if there was no vector tile data on the initial load, don't try and re-parse tile + if (workerTile.vectorTile) { + workerTile.parse(workerTile.vectorTile, this.layerIndex, this.actor, done); + } else { + done(); + } + } + } + } + }, { + key: "removeTile", + value: function removeTile(params, callback) { + var loaded = this.loaded, + uid = params.id; + + if (loaded && loaded[uid]) { + delete loaded[uid]; + } + + callback(); + } + }, { + key: "unloadTile", + value: function unloadTile() {} + }, { + key: "hasTransition", + value: function hasTransition() {} + }]); + + return VectorTileWorkerSource; +}(); + +exports["default"] = VectorTileWorkerSource; \ No newline at end of file diff --git a/lib/theme/dark.js b/lib/theme/dark.js new file mode 100644 index 0000000000..68422d1da4 --- /dev/null +++ b/lib/theme/dark.js @@ -0,0 +1,11 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var DarkTheme = { + mapStyle: 'amap://styles/ba3e9759545cd618392ef073c0dfda8c?isPublic=true' +}; +var _default = DarkTheme; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/theme/index.js b/lib/theme/index.js new file mode 100644 index 0000000000..296bf7f4f1 --- /dev/null +++ b/lib/theme/index.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "DarkTheme", { + enumerable: true, + get: function get() { + return _dark["default"]; + } +}); +Object.defineProperty(exports, "LightTheme", { + enumerable: true, + get: function get() { + return _light["default"]; + } +}); + +var _dark = _interopRequireDefault(require("./dark")); + +var _light = _interopRequireDefault(require("./light")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } \ No newline at end of file diff --git a/lib/theme/light.js b/lib/theme/light.js new file mode 100644 index 0000000000..a759f841f7 --- /dev/null +++ b/lib/theme/light.js @@ -0,0 +1,11 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var LightTheme = { + mapStyle: 'amap://styles/a80c558f91b29cf56fa47f895fb1773c?isPublic=true' +}; +var _default = LightTheme; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/track.js b/lib/track.js new file mode 100644 index 0000000000..9d0a0cc3fc --- /dev/null +++ b/lib/track.js @@ -0,0 +1,26 @@ +"use strict"; + +var _global = _interopRequireDefault(require("./global")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @fileOverview track g2 + * @author dxq613@gmail.com + */ +var SERVER_URL = 'https://kcart.alipay.com/web/bi.do'; // 延迟发送请求 + +setTimeout(function () { + if (_global.default.trackable) { + var image = new Image(); + var newObj = { + pg: document.URL, + r: new Date().getTime(), + l7: true, + version: _global.default.version, + page_type: 'syslog' + }; + var d = encodeURIComponent(JSON.stringify([newObj])); + image.src = "".concat(SERVER_URL, "?BIProfile=merge&d=").concat(d); + } +}, 3000); \ No newline at end of file diff --git a/lib/util.js b/lib/util.js new file mode 100644 index 0000000000..cfee0688b6 --- /dev/null +++ b/lib/util.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var Utils = _interopRequireWildcard(require("@antv/util")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +var Util = Utils.mix({}, Utils, { + assign: Utils.mix, + // simple mix + merge: Utils.deepMix, + // deep mix + cloneDeep: Utils.clone, + isFinite: isFinite, + isNaN: isNaN, + snapEqual: Utils.isNumberEqual, + remove: Utils.pull, + inArray: Utils.contains +}); +Util.Array = { + groupToMap: Utils.groupToMap, + group: Utils.group, + merge: Util.merge, + values: Utils.valuesOfKey, + getRange: Utils.getRange, + firstValue: Utils.firstValue, + remove: Utils.pull +}; +var _default = Util; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/util/ajax.js b/lib/util/ajax.js new file mode 100644 index 0000000000..0e68f85f10 --- /dev/null +++ b/lib/util/ajax.js @@ -0,0 +1,197 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getVideo = exports.getImage = exports.getArrayBuffer = exports.getJSON = void 0; + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } + +function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + +function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } + +function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +var AJAXError = +/*#__PURE__*/ +function (_Error) { + _inherits(AJAXError, _Error); + + function AJAXError(message, status, url) { + var _this; + + _classCallCheck(this, AJAXError); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(AJAXError).call(this, message)); + _this.status = status; + _this.url = url; // work around for https://github.com/Rich-Harris/buble/issues/40 + + _this.name = _this.constructor.name; + _this.message = message; + return _this; + } + + _createClass(AJAXError, [{ + key: "toString", + value: function toString() { + return "".concat(this.name, ": ").concat(this.message, " (").concat(this.status, "): ").concat(this.url); + } + }]); + + return AJAXError; +}(_wrapNativeSuper(Error)); + +function makeRequest(requestParameters) { + var xhr = new XMLHttpRequest(); + xhr.open('GET', requestParameters.url, true); + + for (var k in requestParameters.headers) { + xhr.setRequestHeader(k, requestParameters.headers[k]); + } + + xhr.withCredentials = requestParameters.credentials === 'include'; + return xhr; +} + +var getJSON = function getJSON(requestParameters, callback) { + var xhr = makeRequest(requestParameters); + xhr.setRequestHeader('Accept', 'application/json'); + + xhr.onerror = function () { + callback(new Error(xhr.statusText)); + }; + + xhr.onload = function () { + if (xhr.status >= 200 && xhr.status < 300 && xhr.response) { + var data; + + try { + data = JSON.parse(xhr.response); + } catch (err) { + return callback(err); + } + + callback(null, data); + } else { + if (xhr.status === 401) { + callback(new AJAXError("".concat(xhr.statusText), xhr.status, requestParameters.url)); + } else { + callback(new AJAXError(xhr.statusText, xhr.status, requestParameters.url)); + } + } + }; + + xhr.send(); + return xhr; +}; + +exports.getJSON = getJSON; + +var getArrayBuffer = function getArrayBuffer(requestParameters, callback) { + var xhr = makeRequest(requestParameters); + xhr.responseType = 'arraybuffer'; + + xhr.onerror = function () { + callback(new Error(xhr.statusText)); + }; + + xhr.onload = function () { + var response = xhr.response; + + if (response.byteLength === 0 && xhr.status === 200) { + return callback(new Error('http status 200 returned without content.')); + } + + if (xhr.status >= 200 && xhr.status < 300 && xhr.response) { + callback(null, { + data: response, + cacheControl: xhr.getResponseHeader('Cache-Control'), + expires: xhr.getResponseHeader('Expires') + }); + } else { + callback(new AJAXError(xhr.statusText, xhr.status, requestParameters.url)); + } + }; + + xhr.send(); + return xhr; +}; + +exports.getArrayBuffer = getArrayBuffer; + +function sameOrigin(url) { + var a = window.document.createElement('a'); + a.href = url; + return a.protocol === window.document.location.protocol && a.host === window.document.location.host; +} + +var transparentPngUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII='; + +var getImage = function getImage(requestParameters, callback) { + // request the image with XHR to work around caching issues + // see https://github.com/mapbox/mapbox-gl-js/issues/1470 + return getArrayBuffer(requestParameters, function (err, imgData) { + if (err) { + callback(err); + } else if (imgData) { + var img = new window.Image(); + var URL = window.URL || window.webkitURL; + + img.onload = function () { + callback(null, img); + URL.revokeObjectURL(img.src); + }; + + var blob = new window.Blob([new Uint8Array(imgData.data)], { + type: 'image/png' + }); + img.cacheControl = imgData.cacheControl; + img.expires = imgData.expires; + img.src = imgData.data.byteLength ? URL.createObjectURL(blob) : transparentPngUrl; + } + }); +}; + +exports.getImage = getImage; + +var getVideo = function getVideo(urls, callback) { + var video = window.document.createElement('video'); + + video.onloadstart = function () { + callback(null, video); + }; + + for (var i = 0; i < urls.length; i++) { + var s = window.document.createElement('source'); + + if (!sameOrigin(urls[i])) { + video.crossOrigin = 'Anonymous'; + } + + s.src = urls[i]; + video.appendChild(s); + } + + return video; +}; + +exports.getVideo = getVideo; \ No newline at end of file diff --git a/lib/util/bkdr-hash.js b/lib/util/bkdr-hash.js new file mode 100644 index 0000000000..849e263d9e --- /dev/null +++ b/lib/util/bkdr-hash.js @@ -0,0 +1,42 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.BKDRHash = BKDRHash; +exports.djb2hash = djb2hash; + +function BKDRHash(str) { + var seed = 131; + var seed2 = 137; + var hash = 0; // make hash more sensitive for short string like 'a', 'b', 'c' + + str += 'x'; // Note: Number.MAX_SAFE_INTEGER equals 9007199254740991 + + var MAX_SAFE_INTEGER = parseInt(9007199254740991 / seed2); + + for (var i = 0; i < str.length; i++) { + if (hash > MAX_SAFE_INTEGER) { + hash = parseInt(hash / seed2); + } + + hash = hash * seed + str.charCodeAt(i); + } + + return hash; +} + +function djb2hash(str) { + var hash = 5381, + i = str.length; + + while (i) { + hash = hash * 33 ^ str.charCodeAt(--i); + } + /* JavaScript does bitwise operations (like XOR, above) on 32-bit signed + * integers. Since we want the results to be always positive, convert the + * signed int to an unsigned by doing an unsigned bitshift. */ + + + return hash >>> 0; +} \ No newline at end of file diff --git a/lib/util/common.js b/lib/util/common.js new file mode 100644 index 0000000000..ddd2cc8b59 --- /dev/null +++ b/lib/util/common.js @@ -0,0 +1,134 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var PRECISION = 0.00001; // 常量,据的精度,小于这个精度认为是0 + +var RADIAN = Math.PI / 180; +var DEGREE = 180 / Math.PI; +var _default = { + isFunction: require('lodash/isFunction'), + isObject: require('lodash/isObject'), + isBoolean: require('lodash/isBoolean'), + isNil: require('lodash/isNil'), + isString: require('lodash/isString'), + isArray: require('lodash/isArray'), + isNumber: require('lodash/isNumber'), + isEmpty: require('lodash/isEmpty'), + // isBlank + uniqueId: require('lodash/uniqueId'), + clone: require('lodash/clone'), + assign: require('lodash/assign'), + // simpleMix + merge: require('lodash/merge'), + // mix + upperFirst: require('lodash/upperFirst'), + // ucfirst + remove: require('lodash/pull'), + each: require('lodash/forEach'), + isEqual: require('lodash/isEqual'), + toArray: require('lodash/toArray'), + extend: function extend(subclass, superclass, overrides, staticOverrides) { + // 如果只提供父类构造函数,则自动生成子类构造函数 + if (!this.isFunction(superclass)) { + overrides = superclass; + superclass = subclass; + + subclass = function subclass() {}; + } + + var create = Object.create ? function (proto, c) { + return Object.create(proto, { + constructor: { + value: c + } + }); + } : function (proto, c) { + function F() {} + + F.prototype = proto; + var o = new F(); + o.constructor = c; + return o; + }; + var superObj = create(superclass.prototype, subclass); // new superclass(),//实例化父类作为子类的prototype + + subclass.prototype = this.merge(superObj, subclass.prototype); // 指定子类的prototype + + subclass.superclass = create(superclass.prototype, superclass); + this.merge(superObj, overrides); + this.merge(subclass, staticOverrides); + return subclass; + }, + augment: function augment(c) { + var args = this.toArray(arguments); + + for (var i = 1; i < args.length; i++) { + var obj = args[i]; + + if (this.isFunction(obj)) { + obj = obj.prototype; + } + + this.merge(c.prototype, obj); + } + }, + + /** + * 判断两个数是否相等 + * @param {Number} a 数 + * @param {Number} b 数 + * @return {Boolean} 是否相等 + **/ + isNumberEqual: function isNumberEqual(a, b) { + return Math.abs(a - b) < PRECISION; + }, + + /** + * 获取角度对应的弧度 + * @param {Number} degree 角度 + * @return {Number} 弧度 + **/ + toRadian: function toRadian(degree) { + return RADIAN * degree; + }, + + /** + * 获取弧度对应的角度 + * @param {Number} radian 弧度 + * @return {Number} 角度 + **/ + toDegree: function toDegree(radian) { + return DEGREE * radian; + }, + + /** + * 广义取模运算 + * @param {Number} n 被取模的值 + * @param {Number} m 模 + * @return {Number} 返回n 被 m 取模的结果 + */ + mod: function mod(n, m) { + return (n % m + m) % m; + }, + + /** + * 把a夹在min,max中间, 低于min的返回min,高于max的返回max,否则返回自身 + * @param {Number} a 数 + * @param {Number} min 下限 + * @param {Number} max 上限 + * @return {Number} 返回结果值 + **/ + clamp: function clamp(a, min, max) { + if (a < min) { + return min; + } else if (a > max) { + return max; + } + + return a; + } +}; +exports.default = _default; \ No newline at end of file diff --git a/lib/util/diff.js b/lib/util/diff.js new file mode 100644 index 0000000000..1329629f28 --- /dev/null +++ b/lib/util/diff.js @@ -0,0 +1,64 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = diff; + +var _ = _interopRequireWildcard(require("@antv/util")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function diff(a, b) { + // Throw is a or b are not objects. + if (!_.isPlainObject(a)) { + throw new Error('First parameter to diff() is not an object'); + } + + if (!_.isPlainObject(b)) { + throw new Error('Second parameter to diff() is not an object'); + } + + var changes = []; + + var keysA = _.keys(a); + + var keysB = _.keys(b); // Find the items in A that are not in B. + + + _.each(_.difference(keysA, keysB), function (key) { + changes.push({ + type: 'remove', + key: key, + value: a[key] + }); + }); // Find the items in B that are not in A. + + + _.each(_.difference(keysB, keysA), function (key) { + changes.push({ + type: 'add', + key: key, + value: b[key] + }); + }); // Find the items that are in both, but have changed. + + + _.each(intersection(keysA, keysB), function (key) { + if (!_.isEqual(a[key], b[key])) { + changes.push({ + type: 'update', + key: key, + value: b[key] + }); + } + }); + + return changes; +} + +function intersection(keysA, keysB) { + return keysA.filter(function (key) { + return keysB.indexOf(key) > -1; + }); +} \ No newline at end of file diff --git a/lib/util/dom.js b/lib/util/dom.js new file mode 100644 index 0000000000..0c4180e954 --- /dev/null +++ b/lib/util/dom.js @@ -0,0 +1,194 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _common = _interopRequireDefault(require("./common")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var TABLE = document.createElement('table'); +var TABLE_TR = document.createElement('tr'); +var FRAGMENT_REG = /^\s*<(\w+|!)[^>]*>/; +var CONTAINERS = { + tr: document.createElement('tbody'), + tbody: TABLE, + thead: TABLE, + tfoot: TABLE, + td: TABLE_TR, + th: TABLE_TR, + '*': document.createElement('div') +}; +var _default = { + getBoundingClientRect: function getBoundingClientRect(node, defaultValue) { + if (node && node.getBoundingClientRect) { + var rect = node.getBoundingClientRect(); + var top = document.documentElement.clientTop; + var left = document.documentElement.clientLeft; + return { + top: rect.top - top, + bottom: rect.bottom - top, + left: rect.left - left, + right: rect.right - left + }; + } + + return defaultValue || null; + }, + + /** + * 获取样式 + * @param {Object} dom DOM节点 + * @param {String} name 样式名 + * @param {Any} defaultValue 默认值 + * @return {String} 属性值 + */ + getStyle: function getStyle(dom, name, defaultValue) { + try { + if (window.getComputedStyle) { + return window.getComputedStyle(dom, null)[name]; + } + + return dom.currentStyle[name]; + } catch (e) { + if (!_common.default.isNil(defaultValue)) { + return defaultValue; + } + + return null; + } + }, + modifyCSS: function modifyCSS(dom, css) { + if (dom) { + for (var key in css) { + if (css.hasOwnProperty(key)) { + dom.style[key] = css[key]; + } + } + } + + return dom; + }, + + /** + * 创建DOM 节点 + * @param {String} str Dom 字符串 + * @return {HTMLElement} DOM 节点 + */ + createDom: function createDom(str) { + var name = FRAGMENT_REG.test(str) && RegExp.$1; + + if (!(name in CONTAINERS)) { + name = '*'; + } + + var container = CONTAINERS[name]; + str = str.replace(/(^\s*)|(\s*$)/g, ''); + container.innerHTML = '' + str; + var dom = container.childNodes[0]; + container.removeChild(dom); + return dom; + }, + getRatio: function getRatio() { + return window.devicePixelRatio ? window.devicePixelRatio : 2; + }, + + /** + * 获取宽度 + * @param {HTMLElement} el dom节点 + * @param {Number} defaultValue 默认值 + * @return {Number} 宽度 + */ + getWidth: function getWidth(el, defaultValue) { + var width = this.getStyle(el, 'width', defaultValue); + + if (width === 'auto') { + width = el.offsetWidth; + } + + return parseFloat(width); + }, + + /** + * 获取高度 + * @param {HTMLElement} el dom节点 + * @param {Number} defaultValue 默认值 + * @return {Number} 高度 + */ + getHeight: function getHeight(el, defaultValue) { + var height = this.getStyle(el, 'height', defaultValue); + + if (height === 'auto') { + height = el.offsetHeight; + } + + return parseFloat(height); + }, + + /** + * 获取外层高度 + * @param {HTMLElement} el dom节点 + * @param {Number} defaultValue 默认值 + * @return {Number} 高度 + */ + getOuterHeight: function getOuterHeight(el, defaultValue) { + var height = this.getHeight(el, defaultValue); + var bTop = parseFloat(this.getStyle(el, 'borderTopWidth')) || 0; + var pTop = parseFloat(this.getStyle(el, 'paddingTop')) || 0; + var pBottom = parseFloat(this.getStyle(el, 'paddingBottom')) || 0; + var bBottom = parseFloat(this.getStyle(el, 'borderBottomWidth')) || 0; + return height + bTop + bBottom + pTop + pBottom; + }, + + /** + * 获取外层宽度 + * @param {HTMLElement} el dom节点 + * @param {Number} defaultValue 默认值 + * @return {Number} 宽度 + */ + getOuterWidth: function getOuterWidth(el, defaultValue) { + var width = this.getWidth(el, defaultValue); + var bLeft = parseFloat(this.getStyle(el, 'borderLeftWidth')) || 0; + var pLeft = parseFloat(this.getStyle(el, 'paddingLeft')) || 0; + var pRight = parseFloat(this.getStyle(el, 'paddingRight')) || 0; + var bRight = parseFloat(this.getStyle(el, 'borderRightWidth')) || 0; + return width + bLeft + bRight + pLeft + pRight; + }, + + /** + * 添加事件监听器 + * @param {Object} target DOM对象 + * @param {String} eventType 事件名 + * @param {Funtion} callback 回调函数 + * @return {Object} 返回对象 + */ + addEventListener: function addEventListener(target, eventType, callback) { + if (target) { + if (target.addEventListener) { + target.addEventListener(eventType, callback, false); + return { + remove: function remove() { + target.removeEventListener(eventType, callback, false); + } + }; + } else if (target.attachEvent) { + target.attachEvent('on' + eventType, callback); + return { + remove: function remove() { + target.detachEvent('on' + eventType, callback); + } + }; + } + } + }, + requestAnimationFrame: function requestAnimationFrame(fn) { + var method = window.requestAnimationFrame || window.webkitRequestAnimationFrame || function (fn) { + return setTimeout(fn, 16); + }; + + return method(fn); + } +}; +exports.default = _default; \ No newline at end of file diff --git a/lib/util/font-util.js b/lib/util/font-util.js new file mode 100644 index 0000000000..3c83039689 --- /dev/null +++ b/lib/util/font-util.js @@ -0,0 +1,129 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.nextPowOfTwo = nextPowOfTwo; +exports.buildMapping = buildMapping; +exports.resizeImage = resizeImage; +exports.buildIconMaping = buildIconMaping; + +function nextPowOfTwo(number) { + return Math.pow(2, Math.ceil(Math.log2(number))); +} + +function buildMapping(_ref) { + var characterSet = _ref.characterSet, + getFontWidth = _ref.getFontWidth, + fontHeight = _ref.fontHeight, + buffer = _ref.buffer, + maxCanvasWidth = _ref.maxCanvasWidth, + _ref$mapping = _ref.mapping, + mapping = _ref$mapping === void 0 ? {} : _ref$mapping, + _ref$xOffset = _ref.xOffset, + xOffset = _ref$xOffset === void 0 ? 0 : _ref$xOffset, + _ref$yOffset = _ref.yOffset, + yOffset = _ref$yOffset === void 0 ? 0 : _ref$yOffset; + var row = 0; + var x = xOffset; + Array.from(characterSet).forEach(function (_char, i) { + if (!mapping[_char]) { + var width = getFontWidth(_char, i); + + if (x + width + buffer * 2 > maxCanvasWidth) { + x = 0; + row++; + } + + mapping[_char] = { + x: x + buffer, + y: yOffset + row * (fontHeight + buffer * 2) + buffer, + width: width, + height: fontHeight, + mask: true + }; + x += width + buffer * 2; + } + }); + var rowHeight = fontHeight + buffer * 2; + return { + mapping: mapping, + xOffset: x, + yOffset: yOffset + row * rowHeight, + canvasHeight: nextPowOfTwo(yOffset + (row + 1) * rowHeight) + }; +} + +function buildRowMapping(mapping, columns, yOffset) { + for (var i = 0; i < columns.length; i++) { + var _columns$i = columns[i], + icon = _columns$i.icon, + xOffset = _columns$i.xOffset; + mapping[icon.id] = Object.assign({}, icon, { + x: xOffset, + y: yOffset, + image: icon.image + }); + } +} + +function resizeImage(ctx, imageData, width, height) { + var naturalWidth = imageData.naturalWidth, + naturalHeight = imageData.naturalHeight; + + if (width === naturalWidth && height === naturalHeight) { + return imageData; + } + + ctx.canvas.height = height; + ctx.canvas.width = width; + ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); // image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight + + ctx.drawImage(imageData, 0, 0, naturalWidth, naturalHeight, 0, 0, width, height); + return ctx.canvas; +} + +function buildIconMaping(_ref2) { + var icons = _ref2.icons, + buffer = _ref2.buffer, + maxCanvasWidth = _ref2.maxCanvasWidth; + var xOffset = 0; + var yOffset = 0; + var rowHeight = 0; + var columns = []; + var mapping = {}; + + for (var i = 0; i < icons.length; i++) { + var icon = icons[i]; + + if (!mapping[icon.id]) { + var height = icon.height, + width = icon.width; // fill one row + + if (xOffset + width + buffer > maxCanvasWidth) { + buildRowMapping(mapping, columns, yOffset); + xOffset = 0; + yOffset = rowHeight + yOffset + buffer; + rowHeight = 0; + columns = []; + } + + columns.push({ + icon: icon, + xOffset: xOffset + }); + xOffset = xOffset + width + buffer; + rowHeight = Math.max(rowHeight, height); + } + } + + if (columns.length > 0) { + buildRowMapping(mapping, columns, yOffset); + } + + var canvasHeight = nextPowOfTwo(rowHeight + yOffset + buffer); + return { + mapping: mapping, + canvasHeight: canvasHeight + }; +} \ No newline at end of file diff --git a/lib/util/format.js b/lib/util/format.js new file mode 100644 index 0000000000..829cdf5d28 --- /dev/null +++ b/lib/util/format.js @@ -0,0 +1,233 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _index = _interopRequireDefault(require("../util/index")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var regexTags = /[MLHVQTCSAZ]([^MLHVQTCSAZ]*)/ig; +var regexDot = /[^\s\,]+/ig; +var regexLG = /^l\s*\(\s*([\d.]+)\s*\)\s*(.*)/i; +var regexRG = /^r\s*\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\)\s*(.*)/i; +var regexPR = /^p\s*\(\s*([axyn])\s*\)\s*(.*)/i; +var regexColorStop = /[\d.]+:(#[^\s]+|[^\)]+\))/ig; +var numColorCache = {}; + +function addStop(steps, gradient) { + var arr = steps.match(regexColorStop); + + _index.default.each(arr, function (item) { + item = item.split(':'); + gradient.addColorStop(item[0], item[1]); + }); +} + +function parseLineGradient(color, self) { + var arr = regexLG.exec(color); + + var angle = _index.default.mod(_index.default.toRadian(parseFloat(arr[1])), Math.PI * 2); + + var steps = arr[2]; + var box = self.getBBox(); + var start; + var end; + + if (angle >= 0 && angle < 0.5 * Math.PI) { + start = { + x: box.minX, + y: box.minY + }; + end = { + x: box.maxX, + y: box.maxY + }; + } else if (0.5 * Math.PI <= angle && angle < Math.PI) { + start = { + x: box.maxX, + y: box.minY + }; + end = { + x: box.minX, + y: box.maxY + }; + } else if (Math.PI <= angle && angle < 1.5 * Math.PI) { + start = { + x: box.maxX, + y: box.maxY + }; + end = { + x: box.minX, + y: box.minY + }; + } else { + start = { + x: box.minX, + y: box.maxY + }; + end = { + x: box.maxX, + y: box.minY + }; + } + + var tanTheta = Math.tan(angle); + var tanTheta2 = tanTheta * tanTheta; + var x = (end.x - start.x + tanTheta * (end.y - start.y)) / (tanTheta2 + 1) + start.x; + var y = tanTheta * (end.x - start.x + tanTheta * (end.y - start.y)) / (tanTheta2 + 1) + start.y; + var context = self.get('context'); + var gradient = context.createLinearGradient(start.x, start.y, x, y); + addStop(steps, gradient); + return gradient; +} + +function parseRadialGradient(color, self) { + var arr = regexRG.exec(color); + var fx = parseFloat(arr[1]); + var fy = parseFloat(arr[2]); + var fr = parseFloat(arr[3]); + var steps = arr[4]; + var box = self.getBBox(); + var context = self.get('context'); + var width = box.maxX - box.minX; + var height = box.maxY - box.minY; + var r = Math.sqrt(width * width + height * height) / 2; + var gradient = context.createRadialGradient(box.minX + width * fx, box.minY + height * fy, fr * r, box.minX + width / 2, box.minY + height / 2, r); + addStop(steps, gradient); + return gradient; +} + +function parsePattern(color, self) { + if (self.get('patternSource') && self.get('patternSource') === color) { + return self.get('pattern'); + } + + var pattern; + var img; + var arr = regexPR.exec(color); + var repeat = arr[1]; + var source = arr[2]; // Function to be called when pattern loads + + function onload() { + // Create pattern + var context = self.get('context'); + pattern = context.createPattern(img, repeat); + self.setSilent('pattern', pattern); // be a cache + + self.setSilent('patternSource', color); + } + + switch (repeat) { + case 'a': + repeat = 'repeat'; + break; + + case 'x': + repeat = 'repeat-x'; + break; + + case 'y': + repeat = 'repeat-y'; + break; + + case 'n': + repeat = 'no-repeat'; + break; + + default: + repeat = 'no-repeat'; + } + + img = new Image(); // If source URL is not a data URL + + if (!source.match(/^data:/i)) { + // Set crossOrigin for this image + img.crossOrigin = 'Anonymous'; + } + + img.src = source; + + if (img.complete) { + onload(); + } else { + img.onload = onload; // Fix onload() bug in IE9 + // eslint-disable-next-line + + img.src = img.src; + } + + return pattern; +} + +var _default = { + parsePath: function parsePath(path) { + path = path || []; + + if (_index.default.isArray(path)) { + return path; + } + + if (_index.default.isString(path)) { + path = path.match(regexTags); + + _index.default.each(path, function (item, index) { + item = item.match(regexDot); + + if (item[0].length > 1) { + var tag = item[0].charAt(0); + item.splice(1, 0, item[0].substr(1)); + item[0] = tag; + } + + _index.default.each(item, function (sub, i) { + if (!isNaN(sub)) { + item[i] = +sub; + } + }); + + path[index] = item; + }); + + return path; + } + }, + parseStyle: function parseStyle(color, self) { + if (_index.default.isString(color)) { + if (color[1] === '(' || color[2] === '(') { + if (color[0] === 'l') { + // regexLG.test(color) + return parseLineGradient(color, self); + } else if (color[0] === 'r') { + // regexRG.test(color) + return parseRadialGradient(color, self); + } else if (color[0] === 'p') { + // regexPR.test(color) + return parsePattern(color, self); + } + } + + return color; + } + }, + numberToColor: function numberToColor(num) { + // 增加缓存 + var color = numColorCache[num]; + + if (!color) { + var str = num.toString(16); + + for (var i = str.length; i < 6; i++) { + str = '0' + str; + } + + color = '#' + str; + numColorCache[num] = color; + } + + return color; + } +}; +exports.default = _default; \ No newline at end of file diff --git a/lib/util/geo.js b/lib/util/geo.js new file mode 100644 index 0000000000..bba713f7fd --- /dev/null +++ b/lib/util/geo.js @@ -0,0 +1,50 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.extent = extent; +exports.tranfrormCoord = tranfrormCoord; + +/** + * 计算地理数据范围 + * @param {dataArray} data 地理坐标数据 + * @return {Array} extent + */ +function extent(data) { + var extent = [Infinity, Infinity, -Infinity, -Infinity]; + data.forEach(function (item) { + var coordinates = item.coordinates; + calcExtent(extent, coordinates); + }); + return extent; +} + +function calcExtent(extent, coords) { + if (Array.isArray(coords[0])) { + coords.forEach(function (coord) { + calcExtent(extent, coord); + }); + } else { + if (extent[0] > coords[0]) extent[0] = coords[0]; + if (extent[1] > coords[1]) extent[1] = coords[1]; + if (extent[2] < coords[0]) extent[2] = coords[0]; + if (extent[3] < coords[1]) extent[3] = coords[1]; + } + + return extent; +} + +function tranfrormCoord(data, cb) { + return transform(data, cb); +} + +function transform(item, cb) { + if (Array.isArray(item[0])) { + return item.map(function (coord) { + return transform(coord, cb); + }); + } + + return cb(item); +} \ No newline at end of file diff --git a/lib/util/index.js b/lib/util/index.js new file mode 100644 index 0000000000..6a82d09942 --- /dev/null +++ b/lib/util/index.js @@ -0,0 +1,38 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _common = _interopRequireDefault(require("./common")); + +var _dom = _interopRequireDefault(require("./dom")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var Util = {}; + +_common.default.merge(Util, _common.default, _dom.default, { + mixin: function mixin(c, mixins) { + var Param = c.CFG ? 'CFG' : 'ATTRS'; + + if (c && mixins) { + c._mixins = mixins; + c[Param] = c[Param] || {}; + var temp = {}; + Util.each(mixins, function (mixin) { + Util.augment(c, mixin); + var attrs = mixin[Param]; + + if (attrs) { + Util.merge(temp, attrs); + } + }); + c[Param] = Util.merge(temp, c[Param]); + } + } +}); + +var _default = Util; +exports.default = _default; \ No newline at end of file diff --git a/lib/util/loadCSS.js b/lib/util/loadCSS.js new file mode 100644 index 0000000000..9a0607dc91 --- /dev/null +++ b/lib/util/loadCSS.js @@ -0,0 +1,29 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = loadCSS; + +function loadCSS(url) { + return new Promise(function (resolve, reject) { + try { + var style = document.createElement('style'); + style.textContent = '@import "' + url + '"'; + var fi = setInterval(function () { + try { + // Only populated when file is loaded + if (style.sheet.cssRules) { + clearInterval(fi); + resolve(); + } + } catch (e) { + throw e; + } + }, 10); + document.head.appendChild(style); + } catch (err) { + reject(err); + } + }); +} \ No newline at end of file diff --git a/lib/util/loadScript.js b/lib/util/loadScript.js new file mode 100644 index 0000000000..f34fe47a4c --- /dev/null +++ b/lib/util/loadScript.js @@ -0,0 +1,26 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = loadScript; + +/* + * @Author: ThinkGIS + * @Date: 2018-06-07 14:05:12 + * @Last Modified by: ThinkGIS + * @Last Modified time: 2018-06-08 10:03:32 + */ +function loadScript(src) { + return new Promise(function (resolve, reject) { + try { + var script = document.createElement('script'); + script.src = src; + script.onload = resolve; + script.onerror = reject; + document.head.appendChild(script); + } catch (err) { + reject(err); + } + }); +} \ No newline at end of file diff --git a/lib/util/lru-cache.js b/lib/util/lru-cache.js new file mode 100644 index 0000000000..b5ba650cae --- /dev/null +++ b/lib/util/lru-cache.js @@ -0,0 +1,121 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +/** + * LRU Cache class with limit + * + * Update order for each get/set operation + * Delete oldest when reach given limit + */ +var LRUCache = +/*#__PURE__*/ +function () { + function LRUCache() { + var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 50; + var destroy = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {}; + + _classCallCheck(this, LRUCache); + + this.limit = limit; + this.destroy = destroy; + this._order = []; + this.clear(); + } + + _createClass(LRUCache, [{ + key: "clear", + value: function clear() { + var _this = this; + + this._order.forEach(function (key) { + _this["delete"](key); + }); + + this._cache = {}; // access/update order, first item is oldest, last item is newest + + this._order = []; + } + }, { + key: "get", + value: function get(key) { + var value = this._cache[key]; + + if (value) { + // update order + this._deleteOrder(key); + + this._appendOrder(key); + } + + return value; + } + }, { + key: "set", + value: function set(key, value) { + if (!this._cache[key]) { + // if reach limit, delete the oldest + if (Object.keys(this._cache).length === this.limit) { + this["delete"](this._order[0]); + } + + this._cache[key] = value; + + this._appendOrder(key); + } else { + // if found in cache, delete the old one, insert new one to the first of list + this["delete"](key); + this._cache[key] = value; + + this._appendOrder(key); + } + } + }, { + key: "delete", + value: function _delete(key) { + var value = this._cache[key]; + + if (value) { + this._deleteCache(key); + + this._deleteOrder(key); + + this.destroy(value, key); + } + } + }, { + key: "_deleteCache", + value: function _deleteCache(key) { + delete this._cache[key]; + } + }, { + key: "_deleteOrder", + value: function _deleteOrder(key) { + var index = this._order.findIndex(function (o) { + return o === key; + }); + + if (index >= 0) { + this._order.splice(index, 1); + } + } + }, { + key: "_appendOrder", + value: function _appendOrder(key) { + this._order.push(key); + } + }]); + + return LRUCache; +}(); + +exports["default"] = LRUCache; \ No newline at end of file diff --git a/lib/util/matrix.js b/lib/util/matrix.js new file mode 100644 index 0000000000..bc2749c5e7 --- /dev/null +++ b/lib/util/matrix.js @@ -0,0 +1,128 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _common = _interopRequireDefault(require("./common")); + +var _mat = _interopRequireDefault(require("gl-matrix/src/gl-matrix/mat3")); + +var _vec = _interopRequireDefault(require("gl-matrix/src/gl-matrix/vec3")); + +var _vec2 = _interopRequireDefault(require("gl-matrix/src/gl-matrix/vec2")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +_vec2.default.angle = function (v1, v2) { + var theta = _vec2.default.dot(v1, v2) / (_vec2.default.length(v1) * _vec2.default.length(v2)); + + return Math.acos(_common.default.clamp(theta, -1, 1)); +}; +/** + * 向量 v1 到 向量 v2 夹角的方向 + * @param {Array} v1 向量 + * @param {Array} v2 向量 + * @return {Boolean} >= 0 顺时针 < 0 逆时针 + */ + + +_vec2.default.direction = function (v1, v2) { + return v1[0] * v2[1] - v2[0] * v1[1]; +}; + +_vec2.default.angleTo = function (v1, v2, direct) { + var angle = _vec2.default.angle(v1, v2); + + var angleLargeThanPI = _vec2.default.direction(v1, v2) >= 0; + + if (direct) { + if (angleLargeThanPI) { + return Math.PI * 2 - angle; + } + + return angle; + } + + if (angleLargeThanPI) { + return angle; + } + + return Math.PI * 2 - angle; +}; + +_vec2.default.vertical = function (out, v, flag) { + if (flag) { + out[0] = v[1]; + out[1] = -1 * v[0]; + } else { + out[0] = -1 * v[1]; + out[1] = v[0]; + } + + return out; +}; + +_mat.default.translate = function (out, a, v) { + var transMat = new Array(9); + + _mat.default.fromTranslation(transMat, v); + + return _mat.default.multiply(out, transMat, a); +}; + +_mat.default.rotate = function (out, a, rad) { + var rotateMat = new Array(9); + + _mat.default.fromRotation(rotateMat, rad); + + return _mat.default.multiply(out, rotateMat, a); +}; + +_mat.default.scale = function (out, a, v) { + var scaleMat = new Array(9); + + _mat.default.fromScaling(scaleMat, v); + + return _mat.default.multiply(out, scaleMat, a); +}; + +var _default = { + mat3: _mat.default, + vec2: _vec2.default, + vec3: _vec.default, + transform: function transform(m, ts) { + m = _common.default.clone(m); + + _common.default.each(ts, function (t) { + switch (t[0]) { + case 't': + _mat.default.translate(m, m, [t[1], t[2]]); + + break; + + case 's': + _mat.default.scale(m, m, [t[1], t[2]]); + + break; + + case 'r': + _mat.default.rotate(m, m, t[1]); + + break; + + case 'm': + _mat.default.multiply(m, m, t[1]); + + break; + + default: + return false; + } + }); + + return m; + } +}; +exports.default = _default; \ No newline at end of file diff --git a/lib/util/object3d-util.js b/lib/util/object3d-util.js new file mode 100644 index 0000000000..5a1da0b942 --- /dev/null +++ b/lib/util/object3d-util.js @@ -0,0 +1,83 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.destoryObject = destoryObject; +exports.updateObjecteUniform = updateObjecteUniform; +exports.getPickObject = getPickObject; + +var _picking_frag = _interopRequireDefault(require("../core/engine/picking/picking_frag.glsl")); + +var THREE = _interopRequireWildcard(require("../core/three")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function destoryObject(obj) { + if (!obj) { + return; + } + + if (obj.children) { + for (var i = 0; i < obj.children.length; i++) { + var child = obj.children[i]; + destoryObject(child); + } + } + + if (obj.geometry) { + obj.geometry.dispose(); + obj.geometry = null; + } + + if (obj.material) { + if (obj.material.map) { + obj.material.map.dispose(); + obj.material.map = null; + } + + obj.material.dispose(); + obj.material = null; + } +} + +function updateObjecteUniform(obj, newOption) { + if (!obj) { + return; + } + + if (obj.children) { + for (var i = 0; i < obj.children.length; i++) { + var child = obj.children[i]; + updateObjecteUniform(child, newOption); + } + } + + if (obj.material) { + obj.material.updateUninform(newOption); + } +} + +function getPickObject(obj, newbj) { + if (!obj) { + return; + } + + if (obj.isMesh) { + var pickmaterial = obj.material.clone(); + pickmaterial.fragmentShader = _picking_frag["default"]; + var pickMesh = new THREE[obj.type](obj.geometry, pickmaterial); + newbj.add(pickMesh); + } + + if (obj.children) { + var newObj = new THREE.Object3D(); + + for (var i = 0; i < obj.children.length; i++) { + var child = obj.children[i]; + newObj.add(getPickObject(child, newbj)); + } + } +} \ No newline at end of file diff --git a/lib/util/path.js b/lib/util/path.js new file mode 100644 index 0000000000..d09fbd4f93 --- /dev/null +++ b/lib/util/path.js @@ -0,0 +1,1036 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _common = _interopRequireDefault(require("./common")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +var SPACES = "\t\n\x0B\f\r \xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029"; +var PATH_COMMAND = new RegExp('([a-z])[' + SPACES + ',]*((-?\\d*\\.?\\d*(?:e[\\-+]?\\d+)?[' + SPACES + ']*,?[' + SPACES + ']*)+)', 'ig'); +var PATH_VALUES = new RegExp('(-?\\d*\\.?\\d*(?:e[\\-+]?\\d+)?)[' + SPACES + ']*,?[' + SPACES + ']*', 'ig'); // Parses given path string into an array of arrays of path segments + +var parsePathString = function parsePathString(pathString) { + if (!pathString) { + return null; + } + + if (_typeof(pathString) === _typeof([])) { + return pathString; + } + + var paramCounts = { + a: 7, + c: 6, + o: 2, + h: 1, + l: 2, + m: 2, + r: 4, + q: 4, + s: 4, + t: 2, + v: 1, + u: 3, + z: 0 + }; + var data = []; + String(pathString).replace(PATH_COMMAND, function (a, b, c) { + var params = []; + var name = b.toLowerCase(); + c.replace(PATH_VALUES, function (a, b) { + b && params.push(+b); + }); + + if (name === 'm' && params.length > 2) { + data.push([b].concat(params.splice(0, 2))); + name = 'l'; + b = b === 'm' ? 'l' : 'L'; + } + + if (name === 'o' && params.length === 1) { + data.push([b, params[0]]); + } + + if (name === 'r') { + data.push([b].concat(params)); + } else { + while (params.length >= paramCounts[name]) { + data.push([b].concat(params.splice(0, paramCounts[name]))); + + if (!paramCounts[name]) { + break; + } + } + } + }); + return data; +}; // http://schepers.cc/getting-to-the-point + + +var catmullRom2bezier = function catmullRom2bezier(crp, z) { + var d = []; + + for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) { + var p = [{ + x: +crp[i - 2], + y: +crp[i - 1] + }, { + x: +crp[i], + y: +crp[i + 1] + }, { + x: +crp[i + 2], + y: +crp[i + 3] + }, { + x: +crp[i + 4], + y: +crp[i + 5] + }]; + + if (z) { + if (!i) { + p[0] = { + x: +crp[iLen - 2], + y: +crp[iLen - 1] + }; + } else if (iLen - 4 === i) { + p[3] = { + x: +crp[0], + y: +crp[1] + }; + } else if (iLen - 2 === i) { + p[2] = { + x: +crp[0], + y: +crp[1] + }; + p[3] = { + x: +crp[2], + y: +crp[3] + }; + } + } else { + if (iLen - 4 === i) { + p[3] = p[2]; + } else if (!i) { + p[0] = { + x: +crp[i], + y: +crp[i + 1] + }; + } + } + + d.push(['C', (-p[0].x + 6 * p[1].x + p[2].x) / 6, (-p[0].y + 6 * p[1].y + p[2].y) / 6, (p[1].x + 6 * p[2].x - p[3].x) / 6, (p[1].y + 6 * p[2].y - p[3].y) / 6, p[2].x, p[2].y]); + } + + return d; +}; + +var ellipsePath = function ellipsePath(x, y, rx, ry, a) { + var res = []; + + if (a === null && ry === null) { + ry = rx; + } + + x = +x; + y = +y; + rx = +rx; + ry = +ry; + + if (a !== null) { + var rad = Math.PI / 180; + var x1 = x + rx * Math.cos(-ry * rad); + var x2 = x + rx * Math.cos(-a * rad); + var y1 = y + rx * Math.sin(-ry * rad); + var y2 = y + rx * Math.sin(-a * rad); + res = [['M', x1, y1], ['A', rx, rx, 0, +(a - ry > 180), 0, x2, y2]]; + } else { + res = [['M', x, y], ['m', 0, -ry], ['a', rx, ry, 0, 1, 1, 0, 2 * ry], ['a', rx, ry, 0, 1, 1, 0, -2 * ry], ['z']]; + } + + return res; +}; + +var pathToAbsolute = function pathToAbsolute(pathArray) { + pathArray = parsePathString(pathArray); + + if (!pathArray || !pathArray.length) { + return [['M', 0, 0]]; + } + + var res = []; + var x = 0; + var y = 0; + var mx = 0; + var my = 0; + var start = 0; + var pa0; + var dots; + + if (pathArray[0][0] === 'M') { + x = +pathArray[0][1]; + y = +pathArray[0][2]; + mx = x; + my = y; + start++; + res[0] = ['M', x, y]; + } + + var crz = pathArray.length === 3 && pathArray[0][0] === 'M' && pathArray[1][0].toUpperCase() === 'R' && pathArray[2][0].toUpperCase() === 'Z'; + + for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) { + res.push(r = []); + pa = pathArray[i]; + pa0 = pa[0]; + + if (pa0 !== pa0.toUpperCase()) { + r[0] = pa0.toUpperCase(); + + switch (r[0]) { + case 'A': + r[1] = pa[1]; + r[2] = pa[2]; + r[3] = pa[3]; + r[4] = pa[4]; + r[5] = pa[5]; + r[6] = +pa[6] + x; + r[7] = +pa[7] + y; + break; + + case 'V': + r[1] = +pa[1] + y; + break; + + case 'H': + r[1] = +pa[1] + x; + break; + + case 'R': + dots = [x, y].concat(pa.slice(1)); + + for (var j = 2, jj = dots.length; j < jj; j++) { + dots[j] = +dots[j] + x; + dots[++j] = +dots[j] + y; + } + + res.pop(); + res = res.concat(catmullRom2bezier(dots, crz)); + break; + + case 'O': + res.pop(); + dots = ellipsePath(x, y, pa[1], pa[2]); + dots.push(dots[0]); + res = res.concat(dots); + break; + + case 'U': + res.pop(); + res = res.concat(ellipsePath(x, y, pa[1], pa[2], pa[3])); + r = ['U'].concat(res[res.length - 1].slice(-2)); + break; + + case 'M': + mx = +pa[1] + x; + my = +pa[2] + y; + break; + // for lint + + default: + for (var _j = 1, _jj = pa.length; _j < _jj; _j++) { + r[_j] = +pa[_j] + (_j % 2 ? x : y); + } + + } + } else if (pa0 === 'R') { + dots = [x, y].concat(pa.slice(1)); + res.pop(); + res = res.concat(catmullRom2bezier(dots, crz)); + r = ['R'].concat(pa.slice(-2)); + } else if (pa0 === 'O') { + res.pop(); + dots = ellipsePath(x, y, pa[1], pa[2]); + dots.push(dots[0]); + res = res.concat(dots); + } else if (pa0 === 'U') { + res.pop(); + res = res.concat(ellipsePath(x, y, pa[1], pa[2], pa[3])); + r = ['U'].concat(res[res.length - 1].slice(-2)); + } else { + for (var k = 0, kk = pa.length; k < kk; k++) { + r[k] = pa[k]; + } + } + + pa0 = pa0.toUpperCase(); + + if (pa0 !== 'O') { + switch (r[0]) { + case 'Z': + x = +mx; + y = +my; + break; + + case 'H': + x = r[1]; + break; + + case 'V': + y = r[1]; + break; + + case 'M': + mx = r[r.length - 2]; + my = r[r.length - 1]; + break; + // for lint + + default: + x = r[r.length - 2]; + y = r[r.length - 1]; + } + } + } + + return res; +}; + +var l2c = function l2c(x1, y1, x2, y2) { + return [x1, y1, x2, y2, x2, y2]; +}; + +var q2c = function q2c(x1, y1, ax, ay, x2, y2) { + var _13 = 1 / 3; + + var _23 = 2 / 3; + + return [_13 * x1 + _23 * ax, _13 * y1 + _23 * ay, _13 * x2 + _23 * ax, _13 * y2 + _23 * ay, x2, y2]; +}; + +var a2c = function a2c(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) { + // for more information of where this math came from visit: + // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes + if (rx === ry) { + rx += 1; + } + + var _120 = Math.PI * 120 / 180; + + var rad = Math.PI / 180 * (+angle || 0); + var res = []; + var xy; + var f1; + var f2; + var cx; + var cy; + + var rotate = function rotate(x, y, rad) { + var X = x * Math.cos(rad) - y * Math.sin(rad); + var Y = x * Math.sin(rad) + y * Math.cos(rad); + return { + x: X, + y: Y + }; + }; + + if (!recursive) { + xy = rotate(x1, y1, -rad); + x1 = xy.x; + y1 = xy.y; + xy = rotate(x2, y2, -rad); + x2 = xy.x; + y2 = xy.y; + + if (x1 === x2 && y1 === y2) { + // 若弧的起始点和终点重叠则错开一点 + x2 += 1; + y2 += 1; + } // const cos = Math.cos(Math.PI / 180 * angle); + // const sin = Math.sin(Math.PI / 180 * angle); + + + var x = (x1 - x2) / 2; + var y = (y1 - y2) / 2; + var h = x * x / (rx * rx) + y * y / (ry * ry); + + if (h > 1) { + h = Math.sqrt(h); + rx = h * rx; + ry = h * ry; + } + + var rx2 = rx * rx; + var ry2 = ry * ry; + var k = (large_arc_flag === sweep_flag ? -1 : 1) * Math.sqrt(Math.abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))); + cx = k * rx * y / ry + (x1 + x2) / 2; + cy = k * -ry * x / rx + (y1 + y2) / 2; + f1 = Math.asin(((y1 - cy) / ry).toFixed(9)); + f2 = Math.asin(((y2 - cy) / ry).toFixed(9)); + f1 = x1 < cx ? Math.PI - f1 : f1; + f2 = x2 < cx ? Math.PI - f2 : f2; + f1 < 0 && (f1 = Math.PI * 2 + f1); + f2 < 0 && (f2 = Math.PI * 2 + f2); + + if (sweep_flag && f1 > f2) { + f1 = f1 - Math.PI * 2; + } + + if (!sweep_flag && f2 > f1) { + f2 = f2 - Math.PI * 2; + } + } else { + f1 = recursive[0]; + f2 = recursive[1]; + cx = recursive[2]; + cy = recursive[3]; + } + + var df = f2 - f1; + + if (Math.abs(df) > _120) { + var f2old = f2; + var x2old = x2; + var y2old = y2; + f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1); + x2 = cx + rx * Math.cos(f2); + y2 = cy + ry * Math.sin(f2); + res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]); + } + + df = f2 - f1; + var c1 = Math.cos(f1); + var s1 = Math.sin(f1); + var c2 = Math.cos(f2); + var s2 = Math.sin(f2); + var t = Math.tan(df / 4); + var hx = 4 / 3 * rx * t; + var hy = 4 / 3 * ry * t; + var m1 = [x1, y1]; + var m2 = [x1 + hx * s1, y1 - hy * c1]; + var m3 = [x2 + hx * s2, y2 - hy * c2]; + var m4 = [x2, y2]; + m2[0] = 2 * m1[0] - m2[0]; + m2[1] = 2 * m1[1] - m2[1]; + + if (recursive) { + return [m2, m3, m4].concat(res); + } + + res = [m2, m3, m4].concat(res).join().split(','); + var newres = []; + + for (var i = 0, ii = res.length; i < ii; i++) { + newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x; + } + + return newres; +}; + +var pathTocurve = function pathTocurve(path, path2) { + var p = pathToAbsolute(path); + var p2 = path2 && pathToAbsolute(path2); + var attrs = { + x: 0, + y: 0, + bx: 0, + by: 0, + X: 0, + Y: 0, + qx: null, + qy: null + }; + var attrs2 = { + x: 0, + y: 0, + bx: 0, + by: 0, + X: 0, + Y: 0, + qx: null, + qy: null + }; + var pcoms1 = []; // path commands of original path p + + var pcoms2 = []; // path commands of original path p2 + + var pfirst = ''; // temporary holder for original path command + + var pcom = ''; // holder for previous path command of original path + + var ii; + + var processPath = function processPath(path, d, pcom) { + var nx, ny; + + if (!path) { + return ['C', d.x, d.y, d.x, d.y, d.x, d.y]; + } + + !(path[0] in { + T: 1, + Q: 1 + }) && (d.qx = d.qy = null); + + switch (path[0]) { + case 'M': + d.X = path[1]; + d.Y = path[2]; + break; + + case 'A': + path = ['C'].concat(a2c.apply(0, [d.x, d.y].concat(path.slice(1)))); + break; + + case 'S': + if (pcom === 'C' || pcom === 'S') { + // In "S" case we have to take into account, if the previous command is C/S. + nx = d.x * 2 - d.bx; // And reflect the previous + + ny = d.y * 2 - d.by; // command's control point relative to the current point. + } else { + // or some else or nothing + nx = d.x; + ny = d.y; + } + + path = ['C', nx, ny].concat(path.slice(1)); + break; + + case 'T': + if (pcom === 'Q' || pcom === 'T') { + // In "T" case we have to take into account, if the previous command is Q/T. + d.qx = d.x * 2 - d.qx; // And make a reflection similar + + d.qy = d.y * 2 - d.qy; // to case "S". + } else { + // or something else or nothing + d.qx = d.x; + d.qy = d.y; + } + + path = ['C'].concat(q2c(d.x, d.y, d.qx, d.qy, path[1], path[2])); + break; + + case 'Q': + d.qx = path[1]; + d.qy = path[2]; + path = ['C'].concat(q2c(d.x, d.y, path[1], path[2], path[3], path[4])); + break; + + case 'L': + path = ['C'].concat(l2c(d.x, d.y, path[1], path[2])); + break; + + case 'H': + path = ['C'].concat(l2c(d.x, d.y, path[1], d.y)); + break; + + case 'V': + path = ['C'].concat(l2c(d.x, d.y, d.x, path[1])); + break; + + case 'Z': + path = ['C'].concat(l2c(d.x, d.y, d.X, d.Y)); + break; + + default: + break; + } + + return path; + }; + + var fixArc = function fixArc(pp, i) { + if (pp[i].length > 7) { + pp[i].shift(); + var pi = pp[i]; + + while (pi.length) { + pcoms1[i] = 'A'; // if created multiple C:s, their original seg is saved + + p2 && (pcoms2[i] = 'A'); // the same as above + + pp.splice(i++, 0, ['C'].concat(pi.splice(0, 6))); + } + + pp.splice(i, 1); + ii = Math.max(p.length, p2 && p2.length || 0); + } + }; + + var fixM = function fixM(path1, path2, a1, a2, i) { + if (path1 && path2 && path1[i][0] === 'M' && path2[i][0] !== 'M') { + path2.splice(i, 0, ['M', a2.x, a2.y]); + a1.bx = 0; + a1.by = 0; + a1.x = path1[i][1]; + a1.y = path1[i][2]; + ii = Math.max(p.length, p2 && p2.length || 0); + } + }; + + ii = Math.max(p.length, p2 && p2.length || 0); + + for (var i = 0; i < ii; i++) { + p[i] && (pfirst = p[i][0]); // save current path command + + if (pfirst !== 'C') { + // C is not saved yet, because it may be result of conversion + pcoms1[i] = pfirst; // Save current path command + + i && (pcom = pcoms1[i - 1]); // Get previous path command pcom + } + + p[i] = processPath(p[i], attrs, pcom); // Previous path command is inputted to processPath + + if (pcoms1[i] !== 'A' && pfirst === 'C') pcoms1[i] = 'C'; // A is the only command + // which may produce multiple C:s + // so we have to make sure that C is also C in original path + + fixArc(p, i); // fixArc adds also the right amount of A:s to pcoms1 + + if (p2) { + // the same procedures is done to p2 + p2[i] && (pfirst = p2[i][0]); + + if (pfirst !== 'C') { + pcoms2[i] = pfirst; + i && (pcom = pcoms2[i - 1]); + } + + p2[i] = processPath(p2[i], attrs2, pcom); + + if (pcoms2[i] !== 'A' && pfirst === 'C') { + pcoms2[i] = 'C'; + } + + fixArc(p2, i); + } + + fixM(p, p2, attrs, attrs2, i); + fixM(p2, p, attrs2, attrs, i); + var seg = p[i]; + var seg2 = p2 && p2[i]; + var seglen = seg.length; + var seg2len = p2 && seg2.length; + attrs.x = seg[seglen - 2]; + attrs.y = seg[seglen - 1]; + attrs.bx = parseFloat(seg[seglen - 4]) || attrs.x; + attrs.by = parseFloat(seg[seglen - 3]) || attrs.y; + attrs2.bx = p2 && (parseFloat(seg2[seg2len - 4]) || attrs2.x); + attrs2.by = p2 && (parseFloat(seg2[seg2len - 3]) || attrs2.y); + attrs2.x = p2 && seg2[seg2len - 2]; + attrs2.y = p2 && seg2[seg2len - 1]; + } + + return p2 ? [p, p2] : p; +}; + +var p2s = /,?([a-z]),?/gi; + +var parsePathArray = function parsePathArray(path) { + return path.join(',').replace(p2s, '$1'); +}; + +var base3 = function base3(t, p1, p2, p3, p4) { + var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4; + var t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3; + return t * t2 - 3 * p1 + 3 * p2; +}; + +var bezlen = function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) { + if (z === null) { + z = 1; + } + + z = z > 1 ? 1 : z < 0 ? 0 : z; + var z2 = z / 2; + var n = 12; + var Tvalues = [-0.1252, 0.1252, -0.3678, 0.3678, -0.5873, 0.5873, -0.7699, 0.7699, -0.9041, 0.9041, -0.9816, 0.9816]; + var Cvalues = [0.2491, 0.2491, 0.2335, 0.2335, 0.2032, 0.2032, 0.1601, 0.1601, 0.1069, 0.1069, 0.0472, 0.0472]; + var sum = 0; + + for (var i = 0; i < n; i++) { + var ct = z2 * Tvalues[i] + z2; + var xbase = base3(ct, x1, x2, x3, x4); + var ybase = base3(ct, y1, y2, y3, y4); + var comb = xbase * xbase + ybase * ybase; + sum += Cvalues[i] * Math.sqrt(comb); + } + + return z2 * sum; +}; + +var curveDim = function curveDim(x0, y0, x1, y1, x2, y2, x3, y3) { + var tvalues = []; + var bounds = [[], []]; + var a; + var b; + var c; + var t; + + for (var i = 0; i < 2; ++i) { + if (i === 0) { + b = 6 * x0 - 12 * x1 + 6 * x2; + a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3; + c = 3 * x1 - 3 * x0; + } else { + b = 6 * y0 - 12 * y1 + 6 * y2; + a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3; + c = 3 * y1 - 3 * y0; + } + + if (Math.abs(a) < 1e-12) { + if (Math.abs(b) < 1e-12) { + continue; + } + + t = -c / b; + + if (t > 0 && t < 1) { + tvalues.push(t); + } + + continue; + } + + var b2ac = b * b - 4 * c * a; + var sqrtb2ac = Math.sqrt(b2ac); + + if (b2ac < 0) { + continue; + } + + var t1 = (-b + sqrtb2ac) / (2 * a); + + if (t1 > 0 && t1 < 1) { + tvalues.push(t1); + } + + var t2 = (-b - sqrtb2ac) / (2 * a); + + if (t2 > 0 && t2 < 1) { + tvalues.push(t2); + } + } + + var j = tvalues.length; + var jlen = j; + var mt; + + while (j--) { + t = tvalues[j]; + mt = 1 - t; + bounds[0][j] = mt * mt * mt * x0 + 3 * mt * mt * t * x1 + 3 * mt * t * t * x2 + t * t * t * x3; + bounds[1][j] = mt * mt * mt * y0 + 3 * mt * mt * t * y1 + 3 * mt * t * t * y2 + t * t * t * y3; + } + + bounds[0][jlen] = x0; + bounds[1][jlen] = y0; + bounds[0][jlen + 1] = x3; + bounds[1][jlen + 1] = y3; + bounds[0].length = bounds[1].length = jlen + 2; + return { + min: { + x: Math.min.apply(0, bounds[0]), + y: Math.min.apply(0, bounds[1]) + }, + max: { + x: Math.max.apply(0, bounds[0]), + y: Math.max.apply(0, bounds[1]) + } + }; +}; + +var intersect = function intersect(x1, y1, x2, y2, x3, y3, x4, y4) { + if (Math.max(x1, x2) < Math.min(x3, x4) || Math.min(x1, x2) > Math.max(x3, x4) || Math.max(y1, y2) < Math.min(y3, y4) || Math.min(y1, y2) > Math.max(y3, y4)) { + return; + } + + var nx = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4); + var ny = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4); + var denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); + + if (!denominator) { + return; + } + + var px = nx / denominator; + var py = ny / denominator; + var px2 = +px.toFixed(2); + var py2 = +py.toFixed(2); + + if (px2 < +Math.min(x1, x2).toFixed(2) || px2 > +Math.max(x1, x2).toFixed(2) || px2 < +Math.min(x3, x4).toFixed(2) || px2 > +Math.max(x3, x4).toFixed(2) || py2 < +Math.min(y1, y2).toFixed(2) || py2 > +Math.max(y1, y2).toFixed(2) || py2 < +Math.min(y3, y4).toFixed(2) || py2 > +Math.max(y3, y4).toFixed(2)) { + return; + } + + return { + x: px, + y: py + }; +}; + +var isPointInsideBBox = function isPointInsideBBox(bbox, x, y) { + return x >= bbox.x && x <= bbox.x + bbox.width && y >= bbox.y && y <= bbox.y + bbox.height; +}; + +var rectPath = function rectPath(x, y, w, h, r) { + if (r) { + return [['M', +x + +r, y], ['l', w - r * 2, 0], ['a', r, r, 0, 0, 1, r, r], ['l', 0, h - r * 2], ['a', r, r, 0, 0, 1, -r, r], ['l', r * 2 - w, 0], ['a', r, r, 0, 0, 1, -r, -r], ['l', 0, r * 2 - h], ['a', r, r, 0, 0, 1, r, -r], ['z']]; + } + + var res = [['M', x, y], ['l', w, 0], ['l', 0, h], ['l', -w, 0], ['z']]; + res.parsePathArray = parsePathArray; + return res; +}; + +var box = function box(x, y, width, height) { + if (x === null) { + x = y = width = height = 0; + } + + if (y === null) { + y = x.y; + width = x.width; + height = x.height; + x = x.x; + } + + return { + x: x, + y: y, + width: width, + w: width, + height: height, + h: height, + x2: x + width, + y2: y + height, + cx: x + width / 2, + cy: y + height / 2, + r1: Math.min(width, height) / 2, + r2: Math.max(width, height) / 2, + r0: Math.sqrt(width * width + height * height) / 2, + path: rectPath(x, y, width, height), + vb: [x, y, width, height].join(' ') + }; +}; + +var isBBoxIntersect = function isBBoxIntersect(bbox1, bbox2) { + bbox1 = box(bbox1); + bbox2 = box(bbox2); + return isPointInsideBBox(bbox2, bbox1.x, bbox1.y) || isPointInsideBBox(bbox2, bbox1.x2, bbox1.y) || isPointInsideBBox(bbox2, bbox1.x, bbox1.y2) || isPointInsideBBox(bbox2, bbox1.x2, bbox1.y2) || isPointInsideBBox(bbox1, bbox2.x, bbox2.y) || isPointInsideBBox(bbox1, bbox2.x2, bbox2.y) || isPointInsideBBox(bbox1, bbox2.x, bbox2.y2) || isPointInsideBBox(bbox1, bbox2.x2, bbox2.y2) || (bbox1.x < bbox2.x2 && bbox1.x > bbox2.x || bbox2.x < bbox1.x2 && bbox2.x > bbox1.x) && (bbox1.y < bbox2.y2 && bbox1.y > bbox2.y || bbox2.y < bbox1.y2 && bbox2.y > bbox1.y); +}; + +var bezierBBox = function bezierBBox(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) { + if (!_common.default.isArray(p1x)) { + p1x = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y]; + } + + var bbox = curveDim.apply(null, p1x); + return box(bbox.min.x, bbox.min.y, bbox.max.x - bbox.min.x, bbox.max.y - bbox.min.y); +}; + +var findDotsAtSegment = function findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) { + var t1 = 1 - t; + var t13 = Math.pow(t1, 3); + var t12 = Math.pow(t1, 2); + var t2 = t * t; + var t3 = t2 * t; + var x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x; + var y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y; + var mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x); + var my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y); + var nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x); + var ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y); + var ax = t1 * p1x + t * c1x; + var ay = t1 * p1y + t * c1y; + var cx = t1 * c2x + t * p2x; + var cy = t1 * c2y + t * p2y; + var alpha = 90 - Math.atan2(mx - nx, my - ny) * 180 / Math.PI; // (mx > nx || my < ny) && (alpha += 180); + + return { + x: x, + y: y, + m: { + x: mx, + y: my + }, + n: { + x: nx, + y: ny + }, + start: { + x: ax, + y: ay + }, + end: { + x: cx, + y: cy + }, + alpha: alpha + }; +}; + +var interHelper = function interHelper(bez1, bez2, justCount) { + var bbox1 = bezierBBox(bez1); + var bbox2 = bezierBBox(bez2); + + if (!isBBoxIntersect(bbox1, bbox2)) { + return justCount ? 0 : []; + } + + var l1 = bezlen.apply(0, bez1); + var l2 = bezlen.apply(0, bez2); + var n1 = ~~(l1 / 8); + var n2 = ~~(l2 / 8); + var dots1 = []; + var dots2 = []; + var xy = {}; + var res = justCount ? 0 : []; + + for (var i = 0; i < n1 + 1; i++) { + var d = findDotsAtSegment.apply(0, bez1.concat(i / n1)); + dots1.push({ + x: d.x, + y: d.y, + t: i / n1 + }); + } + + for (var _i = 0; _i < n2 + 1; _i++) { + var _d = findDotsAtSegment.apply(0, bez2.concat(_i / n2)); + + dots2.push({ + x: _d.x, + y: _d.y, + t: _i / n2 + }); + } + + for (var _i2 = 0; _i2 < n1; _i2++) { + for (var j = 0; j < n2; j++) { + var di = dots1[_i2]; + var di1 = dots1[_i2 + 1]; + var dj = dots2[j]; + var dj1 = dots2[j + 1]; + var ci = Math.abs(di1.x - di.x) < 0.001 ? 'y' : 'x'; + var cj = Math.abs(dj1.x - dj.x) < 0.001 ? 'y' : 'x'; + var is = intersect(di.x, di.y, di1.x, di1.y, dj.x, dj.y, dj1.x, dj1.y); + + if (is) { + if (xy[is.x.toFixed(4)] === is.y.toFixed(4)) { + continue; + } + + xy[is.x.toFixed(4)] = is.y.toFixed(4); + var t1 = di.t + Math.abs((is[ci] - di[ci]) / (di1[ci] - di[ci])) * (di1.t - di.t); + var t2 = dj.t + Math.abs((is[cj] - dj[cj]) / (dj1[cj] - dj[cj])) * (dj1.t - dj.t); + + if (t1 >= 0 && t1 <= 1 && t2 >= 0 && t2 <= 1) { + if (justCount) { + res++; + } else { + res.push({ + x: is.x, + y: is.y, + t1: t1, + t2: t2 + }); + } + } + } + } + } + + return res; +}; + +var interPathHelper = function interPathHelper(path1, path2, justCount) { + path1 = pathTocurve(path1); + path2 = pathTocurve(path2); + var x1; + var y1; + var x2; + var y2; + var x1m; + var y1m; + var x2m; + var y2m; + var bez1; + var bez2; + var res = justCount ? 0 : []; + + for (var i = 0, ii = path1.length; i < ii; i++) { + var pi = path1[i]; + + if (pi[0] === 'M') { + x1 = x1m = pi[1]; + y1 = y1m = pi[2]; + } else { + if (pi[0] === 'C') { + bez1 = [x1, y1].concat(pi.slice(1)); + x1 = bez1[6]; + y1 = bez1[7]; + } else { + bez1 = [x1, y1, x1, y1, x1m, y1m, x1m, y1m]; + x1 = x1m; + y1 = y1m; + } + + for (var j = 0, jj = path2.length; j < jj; j++) { + var pj = path2[j]; + + if (pj[0] === 'M') { + x2 = x2m = pj[1]; + y2 = y2m = pj[2]; + } else { + if (pj[0] === 'C') { + bez2 = [x2, y2].concat(pj.slice(1)); + x2 = bez2[6]; + y2 = bez2[7]; + } else { + bez2 = [x2, y2, x2, y2, x2m, y2m, x2m, y2m]; + x2 = x2m; + y2 = y2m; + } + + var intr = interHelper(bez1, bez2, justCount); + + if (justCount) { + res += intr; + } else { + for (var k = 0, kk = intr.length; k < kk; k++) { + intr[k].segment1 = i; + intr[k].segment2 = j; + intr[k].bez1 = bez1; + intr[k].bez2 = bez2; + } + + res = res.concat(intr); + } + } + } + } + } + + return res; +}; + +var pathIntersection = function pathIntersection(path1, path2) { + return interPathHelper(path1, path2); +}; + +var _default = { + parsePathString: parsePathString, + parsePathArray: parsePathArray, + pathTocurve: pathTocurve, + pathToAbsolute: pathToAbsolute, + catmullRomToBezier: catmullRom2bezier, + rectPath: rectPath, + intersection: pathIntersection +}; +exports.default = _default; \ No newline at end of file diff --git a/lib/util/polyline-normals copy.js b/lib/util/polyline-normals copy.js new file mode 100644 index 0000000000..f51b765283 --- /dev/null +++ b/lib/util/polyline-normals copy.js @@ -0,0 +1,153 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = _default; + +var _polylineMiterUtil = require("polyline-miter-util"); + +var _glVec = require("gl-vec2"); + +/** + * 对于 polyline-normal 的改进 + * 超过阈值,miter 转成 bevel 接头, + * 要注意 Three.js 中默认 THREE.FrontFaceDirectionCCW + * @see https://zhuanlan.zhihu.com/p/59541559 + */ +function extrusions(positions, out, point, normal, scale) { + addNext(out, normal, -scale); + addNext(out, normal, scale); + positions.push(point); + positions.push(point); +} + +function addNext(out, normal, length) { + out.push([[normal[0], normal[1]], length]); +} + +function lineSegmentDistance(end, start) { + var dx = start[0] - end[0]; + var dy = start[1] - end[1]; + var dz = start[2] - end[2]; + return Math.sqrt(dx * dx + dy * dy + dz * dz); +} + +function _default(points, closed, indexOffset) { + var lineA = [0, 0]; + var lineB = [0, 0]; + var tangent = [0, 0]; + var miter = [0, 0]; + + var _lastFlip = -1; + + var _started = false; + var _normal = null; + var tmp = (0, _glVec.create)(); + var count = indexOffset || 0; + var miterLimit = 3; + var out = []; + var attrPos = []; + var attrIndex = []; + var attrDistance = [0, 0]; + + if (closed) { + points = points.slice(); + points.push(points[0]); + } + + var total = points.length; + + for (var i = 1; i < total; i++) { + var index = count; + var last = points[i - 1]; + var cur = points[i]; + var next = i < points.length - 1 ? points[i + 1] : null; + var d = lineSegmentDistance(cur, last) + attrDistance[attrDistance.length - 1]; + (0, _polylineMiterUtil.direction)(lineA, cur, last); + + if (!_normal) { + _normal = [0, 0]; + (0, _polylineMiterUtil.normal)(_normal, lineA); + } + + if (!_started) { + _started = true; + extrusions(attrPos, out, last, _normal, 1); + } + + attrIndex.push([index + 0, index + 2, index + 1]); // no miter, simple segment + + if (!next) { + // reset normal + (0, _polylineMiterUtil.normal)(_normal, lineA); + extrusions(attrPos, out, cur, _normal, 1); + attrDistance.push(d, d); + attrIndex.push([index + 1, index + 2, index + 3]); + count += 2; + } else { + // get unit dir of next line + (0, _polylineMiterUtil.direction)(lineB, next, cur); // stores tangent & miter + + var miterLen = (0, _polylineMiterUtil.computeMiter)(tangent, miter, lineA, lineB, 1); // get orientation + + var flip = (0, _glVec.dot)(tangent, _normal) < 0 ? -1 : 1; + var bevel = Math.abs(miterLen) > miterLimit; // 处理前后两条线段重合的情况,这种情况不需要使用任何接头(miter/bevel)。 + // 理论上这种情况下 miterLen = Infinity,本应通过 isFinite(miterLen) 判断, + // 但是 AMap 投影变换后丢失精度,只能通过一个阈值(1000)判断。 + + if (Math.abs(miterLen) > 1000) { + (0, _polylineMiterUtil.normal)(_normal, lineA); + extrusions(attrPos, out, cur, _normal, 1); + attrDistance.push(d, d); + attrIndex.push(_lastFlip === 1 ? [index + 1, index + 3, index + 2] : [index, index + 2, index + 3]); // 避免在 Material 中使用 THREE.DoubleSide + + attrIndex.push([index + 2, index + 3, index + 4]); + count += 2; + _lastFlip = -1; + continue; + } + + if (bevel) { + miterLen = miterLimit; // next two points in our first segment + + extrusions(attrPos, out, cur, _normal, 1); + attrIndex.push([index + 1, index + 2, index + 3]); // now add the bevel triangle + + attrIndex.push(flip === 1 ? [index + 2, index + 4, index + 5] : [index + 4, index + 5, index + 3]); + (0, _polylineMiterUtil.normal)(tmp, lineB); + (0, _glVec.copy)(_normal, tmp); // store normal for next round + + extrusions(attrPos, out, cur, _normal, 1); + attrDistance.push(d, d, d, d); // the miter is now the normal for our next join + + count += 4; + } else { + // next two points in our first segment + extrusions(attrPos, out, cur, _normal, 1); + attrIndex.push([index + 1, index + 2, index + 3]); // now add the miter triangles + + addNext(out, miter, miterLen * -flip); + attrPos.push(cur); + attrIndex.push([index + 2, index + 4, index + 3]); + attrIndex.push([index + 4, index + 5, index + 6]); + (0, _polylineMiterUtil.normal)(tmp, lineB); + (0, _glVec.copy)(_normal, tmp); // store normal for next round + + extrusions(attrPos, out, cur, _normal, 1); + attrDistance.push(d, d, d, d, d); // the miter is now the normal for our next join + + count += 5; + } + + _lastFlip = flip; + } + } + + return { + normals: out, + attrIndex: attrIndex, + attrPos: attrPos, + attrDistance: attrDistance + }; +} \ No newline at end of file diff --git a/lib/util/polyline-normals.js b/lib/util/polyline-normals.js new file mode 100644 index 0000000000..05d6cf7574 --- /dev/null +++ b/lib/util/polyline-normals.js @@ -0,0 +1,159 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = _default; + +var _polylineMiterUtil = require("polyline-miter-util"); + +var _glVec = require("gl-vec2"); + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +function extrusions(positions, out, miters, point, normal, scale) { + addNext(out, miters, normal, -scale); + addNext(out, miters, normal, scale); + positions.push.apply(positions, _toConsumableArray(point)); + positions.push.apply(positions, _toConsumableArray(point)); +} + +function addNext(out, miters, normal, length) { + out.push(normal[0], normal[1], 0); + miters.push(length); +} + +function lineSegmentDistance(end, start) { + var dx = start[0] - end[0]; + var dy = start[1] - end[1]; + var dz = start[2] - end[2]; + return Math.sqrt(dx * dx + dy * dy + dz * dz); +} + +function _default(points, closed, indexOffset) { + var lineA = [0, 0]; + var lineB = [0, 0]; + var tangent = [0, 0]; + var miter = [0, 0]; + + var _lastFlip = -1; + + var _started = false; + var _normal = null; + var tmp = (0, _glVec.create)(); + var count = indexOffset || 0; + var miterLimit = 3; + var out = []; + var attrPos = []; + var attrIndex = []; + var miters = []; + var attrDistance = [0, 0]; + + if (closed) { + points = points.slice(); + points.push(points[0]); + } + + var total = points.length; + + for (var i = 1; i < total; i++) { + var index = count; + var last = points[i - 1]; + var cur = points[i]; + var next = i < points.length - 1 ? points[i + 1] : null; + var d = lineSegmentDistance(cur, last) + attrDistance[attrDistance.length - 1]; + (0, _polylineMiterUtil.direction)(lineA, cur, last); + + if (!_normal) { + _normal = [0, 0]; + (0, _polylineMiterUtil.normal)(_normal, lineA); + } + + if (!_started) { + _started = true; + extrusions(attrPos, out, miters, last, _normal, 1); + } + + attrIndex.push(index + 0, index + 2, index + 1); // no miter, simple segment + + if (!next) { + // reset normal + (0, _polylineMiterUtil.normal)(_normal, lineA); + extrusions(attrPos, out, miters, cur, _normal, 1); + attrDistance.push(d, d); + attrIndex.push(index + 1, index + 2, index + 3); + count += 2; + } else { + // get unit dir of next line + (0, _polylineMiterUtil.direction)(lineB, next, cur); // stores tangent & miter + + var miterLen = (0, _polylineMiterUtil.computeMiter)(tangent, miter, lineA, lineB, 1); // get orientation + + var flip = (0, _glVec.dot)(tangent, _normal) < 0 ? -1 : 1; + var bevel = Math.abs(miterLen) > miterLimit; // 处理前后两条线段重合的情况,这种情况不需要使用任何接头(miter/bevel)。 + // 理论上这种情况下 miterLen = Infinity,本应通过 isFinite(miterLen) 判断, + // 但是 AMap 投影变换后丢失精度,只能通过一个阈值(1000)判断。 + + if (Math.abs(miterLen) > 1000) { + (0, _polylineMiterUtil.normal)(_normal, lineA); + extrusions(attrPos, out, miters, cur, _normal, 1); + attrDistance.push(d, d); + var indexData = _lastFlip === 1 ? [index + 1, index + 3, index + 2] : [index, index + 2, index + 3]; + attrIndex.push.apply(attrIndex, indexData); // 避免在 Material 中使用 THREE.DoubleSide + + attrIndex.push(index + 2, index + 3, index + 4); + count += 2; + _lastFlip = -1; + continue; + } + + if (bevel) { + miterLen = miterLimit; // next two points in our first segment + + extrusions(attrPos, out, miters, cur, _normal, 1); + attrIndex.push(index + 1, index + 2, index + 3); // now add the bevel triangle + + attrIndex.push.apply(attrIndex, _toConsumableArray(flip === 1 ? [index + 2, index + 4, index + 5] : [index + 4, index + 5, index + 3])); + (0, _polylineMiterUtil.normal)(tmp, lineB); + (0, _glVec.copy)(_normal, tmp); // store normal for next round + + extrusions(attrPos, out, miters, cur, _normal, 1); + attrDistance.push(d, d, d, d); // the miter is now the normal for our next join + + count += 4; + } else { + // next two points in our first segment + extrusions(attrPos, out, miters, cur, _normal, 1); + attrIndex.push(index + 1, index + 2, index + 3); // now add the miter triangles + + addNext(out, miters, miter, miterLen * -flip); + attrPos.push.apply(attrPos, _toConsumableArray(cur)); + attrIndex.push(index + 2, index + 4, index + 3); + attrIndex.push(index + 4, index + 5, index + 6); + (0, _polylineMiterUtil.normal)(tmp, lineB); + (0, _glVec.copy)(_normal, tmp); // store normal for next round + + extrusions(attrPos, out, miters, cur, _normal, 1); + attrDistance.push(d, d, d, d, d); // the miter is now the normal for our next join + + count += 5; + } + + _lastFlip = flip; + } + } + + return { + normals: out, + attrIndex: attrIndex, + attrPos: attrPos, + attrDistance: attrDistance, + miters: miters + }; +} \ No newline at end of file diff --git a/lib/util/shaderModule.js b/lib/util/shaderModule.js new file mode 100644 index 0000000000..16772527c4 --- /dev/null +++ b/lib/util/shaderModule.js @@ -0,0 +1,275 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.registerModule = registerModule; +exports.getModule = getModule; +exports.wrapUniforms = wrapUniforms; +exports.generateLightingUniforms = generateLightingUniforms; + +var _uniq = _interopRequireDefault(require("@antv/util/lib/uniq")); + +var _isString = _interopRequireDefault(require("@antv/util/lib/is-string")); + +var _colorUtil = _interopRequireDefault(require("../attr/color-util")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } + +function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var SHADER_TYPE = { + VS: 'vs', + FS: 'fs' +}; +var moduleCache = {}; +var rawContentCache = {}; +var precisionRegExp = /precision\s+(high|low|medium)p\s+float/; +var globalDefaultprecision = '#ifdef GL_FRAGMENT_PRECISION_HIGH\n precision highp float;\n #else\n precision mediump float;\n#endif\n'; +var globalDefaultAttribute = 'attribute float pickingId;\n #ifdef PICK \n varying vec4 worldId; \n #endif \n'; +var globalFSDefaultAttribute = '#ifdef PICK \n varying vec4 worldId; \n #endif \n'; +var globalDefaultInclude = '#pragma include "pick_color"\n'; +var includeRegExp = /#pragma include (["^+"]?["\ "[a-zA-Z_0-9](.*)"]*?)/g; +var uniformRegExp = /uniform\s+(bool|float|int|vec2|vec3|vec4|ivec2|ivec3|ivec4|mat2|mat3|mat4|sampler2D|samplerCube)\s+([\s\S]*?);/g; + +function processModule(rawContent, includeList, type) { + var compiled = rawContent.replace(includeRegExp, function (_, strMatch) { + var includeOpt = strMatch.split(' '); + var includeName = includeOpt[0].replace(/"/g, ''); + + if (includeList.indexOf(includeName) > -1) { + return ''; + } + + var txt = rawContentCache[includeName][type]; + includeList.push(includeName); + + var _processModule = processModule(txt, includeList, type), + content = _processModule.content; + + return content; + }); + return { + content: compiled, + includeList: includeList + }; +} + +function getUniformLengthByType(type) { + var arrayLength = 0; + + switch (type) { + case 'vec2': + case 'ivec2': + arrayLength = 2; + break; + + case 'vec3': + case 'ivec3': + arrayLength = 3; + break; + + case 'vec4': + case 'ivec4': + case 'mat2': + arrayLength = 4; + break; + + case 'mat3': + arrayLength = 9; + break; + + case 'mat4': + arrayLength = 16; + break; + + default: + } + + return arrayLength; +} + +function extractUniforms(content) { + var uniforms = {}; + content = content.replace(uniformRegExp, function (_, type, c) { + var defaultValues = c.split(':'); + var uniformName = defaultValues[0].trim(); + var defaultValue = ''; + + if (defaultValues.length > 1) { + defaultValue = defaultValues[1].trim(); + } // set default value for uniform according to its type + // eg. vec2 u -> [0.0, 0.0] + + + switch (type) { + case 'bool': + defaultValue = defaultValue === 'true'; + break; + + case 'float': + case 'int': + defaultValue = Number(defaultValue); + break; + + case 'vec2': + case 'vec3': + case 'vec4': + case 'ivec2': + case 'ivec3': + case 'ivec4': + case 'mat2': + case 'mat3': + case 'mat4': + if (defaultValue) { + defaultValue = defaultValue.replace('[', '').replace(']', '').split(',').reduce(function (prev, cur) { + prev.push(Number(cur.trim())); + return prev; + }, []); + } else { + defaultValue = new Array(getUniformLengthByType(type)).fill(0); + } + + break; + + default: + } + + uniforms[uniformName] = defaultValue; + return "uniform ".concat(type, " ").concat(uniformName, ";\n"); + }); + return { + content: content, + uniforms: uniforms + }; +} + +function registerModule(moduleName, _ref) { + var _rawContentCache$modu; + + var vs = _ref.vs, + fs = _ref.fs, + declaredUniforms = _ref.uniforms; + + var _extractUniforms = extractUniforms(vs), + extractedVS = _extractUniforms.content, + vsUniforms = _extractUniforms.uniforms; + + var _extractUniforms2 = extractUniforms(fs), + extractedFS = _extractUniforms2.content, + fsUniforms = _extractUniforms2.uniforms; + + rawContentCache[moduleName] = (_rawContentCache$modu = {}, _defineProperty(_rawContentCache$modu, SHADER_TYPE.VS, extractedVS), _defineProperty(_rawContentCache$modu, SHADER_TYPE.FS, extractedFS), _defineProperty(_rawContentCache$modu, "uniforms", _objectSpread({}, vsUniforms, {}, fsUniforms, {}, declaredUniforms)), _rawContentCache$modu); +} + +function getModule(moduleName) { + var _moduleCache$moduleNa; + + if (moduleCache[moduleName]) { + return moduleCache[moduleName]; + } + + var rawVS = rawContentCache[moduleName][SHADER_TYPE.VS]; + var rawFS = rawContentCache[moduleName][SHADER_TYPE.FS]; + rawVS = globalDefaultAttribute + globalDefaultInclude + rawVS; + rawFS = globalFSDefaultAttribute + rawFS; + + var _processModule2 = processModule(rawVS, [], SHADER_TYPE.VS), + vs = _processModule2.content, + vsIncludeList = _processModule2.includeList; + + var _processModule3 = processModule(rawFS, [], SHADER_TYPE.FS), + fs = _processModule3.content, + fsIncludeList = _processModule3.includeList; // TODO: extract uniforms and their default values from GLSL + + + var uniforms = (0, _uniq["default"])(vsIncludeList.concat(fsIncludeList).concat(moduleName)).reduce(function (prev, cur) { + return _objectSpread({}, prev, {}, rawContentCache[cur].uniforms); + }, {}); + /** + * set default precision for fragment shader + * https://stackoverflow.com/questions/28540290/why-it-is-necessary-to-set-precision-for-the-fragment-shader + */ + + if (!precisionRegExp.test(fs)) { + fs = globalDefaultprecision + fs; + } + + moduleCache[moduleName] = (_moduleCache$moduleNa = {}, _defineProperty(_moduleCache$moduleNa, SHADER_TYPE.VS, vs.trim()), _defineProperty(_moduleCache$moduleNa, SHADER_TYPE.FS, fs.trim()), _defineProperty(_moduleCache$moduleNa, "uniforms", uniforms), _moduleCache$moduleNa); + return moduleCache[moduleName]; +} + +function wrapUniforms(uniforms) { + return Object.keys(uniforms).reduce(function (prev, cur) { + prev[cur] = { + value: uniforms[cur] + }; + return prev; + }, {}); +} + +var DEFAULT_LIGHT = { + type: 'directional', + // direction: [ 1, 10.5, 12 ], + direction: [0, -10.5, 1], + ambient: [0.2, 0.2, 0.2], + diffuse: [0.6, 0.6, 0.6], + specular: [0.1, 0.1, 0.1] +}; +var DEFAULT_DIRECTIONAL_LIGHT = { + direction: [0, 0, 0], + ambient: [0, 0, 0], + diffuse: [0, 0, 0], + specular: [0, 0, 0] +}; +var DEFAULT_SPOT_LIGHT = { + position: [0, 0, 0], + direction: [0, 0, 0], + ambient: [0, 0, 0], + diffuse: [0, 0, 0], + specular: [0, 0, 0], + constant: 1, + linear: 0, + quadratic: 0, + angle: 14, + exponent: 40, + blur: 5 +}; +var COLOR_ATTRIBUTES = ['ambient', 'diffuse', 'specular']; + +function generateLightingUniforms(lights) { + var lightsMap = { + u_directional_lights: new Array(3).fill(_objectSpread({}, DEFAULT_DIRECTIONAL_LIGHT)), + u_num_of_directional_lights: 0, + u_spot_lights: new Array(3).fill(_objectSpread({}, DEFAULT_SPOT_LIGHT)), + u_num_of_spot_lights: 0 + }; + + if (!lights || !lights.length) { + lights = [DEFAULT_LIGHT]; + } + + lights.forEach(function (_ref2, i) { + var type = _ref2.type, + rest = _objectWithoutProperties(_ref2, ["type"]); + + var lightsUniformName = "u_".concat(type, "_lights"); + var lightsNumUniformName = "u_num_of_".concat(type, "_lights"); + Object.keys(rest).forEach(function (key) { + if ((0, _isString["default"])(rest[key]) && COLOR_ATTRIBUTES.indexOf(key) > -1) { + rest[key] = _colorUtil["default"].color2RGBA(rest[key]).slice(0, 3); + } + }); + lightsMap[lightsUniformName][i] = _objectSpread({}, lightsMap[lightsUniformName][i], {}, rest); + lightsMap[lightsNumUniformName]++; + }); + return lightsMap; +} \ No newline at end of file diff --git a/lib/util/throttle.js b/lib/util/throttle.js new file mode 100644 index 0000000000..421e45b917 --- /dev/null +++ b/lib/util/throttle.js @@ -0,0 +1,31 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = throttle; + +function throttle(fn, time) { + var pending = false; + var timerId; + + var later = function later() { + timerId = null; + + if (pending) { + fn(); + timerId = setTimeout(later, time); + pending = false; + } + }; + + return function () { + pending = true; + + if (!timerId) { + later(); + } + + return timerId; + }; +} \ No newline at end of file diff --git a/lib/util/version.js b/lib/util/version.js new file mode 100644 index 0000000000..539c7fda22 --- /dev/null +++ b/lib/util/version.js @@ -0,0 +1,14 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _package = _interopRequireDefault(require("../../package.json")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +var version = 'v' + _package["default"].version; +var _default = version; +exports["default"] = _default; \ No newline at end of file diff --git a/lib/util/vertex-compress.js b/lib/util/vertex-compress.js new file mode 100644 index 0000000000..3d85ef2ab4 --- /dev/null +++ b/lib/util/vertex-compress.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.packUint8ToFloat = packUint8ToFloat; + +var _clamp = _interopRequireDefault(require("@antv/util/lib/clamp")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +/** + * encode 2 8-bit unsigned int into a 16-bit float + * @param {number} a 8-bit int + * @param {number} b 8-bit int + * @return {number} float + */ +function packUint8ToFloat(a, b) { + a = (0, _clamp["default"])(Math.floor(a), 0, 255); + b = (0, _clamp["default"])(Math.floor(b), 0, 255); + return 256 * a + b; +} \ No newline at end of file diff --git a/lib/worker/actor.js b/lib/worker/actor.js new file mode 100644 index 0000000000..a50f14ae8b --- /dev/null +++ b/lib/worker/actor.js @@ -0,0 +1,120 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _worker_transform = require("./worker_transform"); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function bindAll(fns, context) { + fns.forEach(function (fn) { + if (!context[fn]) { + return; + } + + context[fn] = context[fn].bind(context); + }); +} + +var Actor = +/*#__PURE__*/ +function () { + function Actor(target, parent, mapId) { + _classCallCheck(this, Actor); + + this.target = target; + this.parent = parent; + this.mapId = mapId; + this.callbacks = {}; + this.callbackID = 0; + bindAll(['receive'], this); + this.target.addEventListener('message', this.receive, false); + } + + _createClass(Actor, [{ + key: "send", + value: function send(type, data, callback, targetMapId) { + var _this = this; + + var id = callback ? "".concat(this.mapId, "_").concat(this.callbackID++) : null; + if (callback) this.callbacks[id] = callback; + var buffer = []; + this.target.postMessage({ + targetMapId: targetMapId, + sourceMapId: this.mapId, + type: type, + id: String(id), + data: data + }, buffer); + + if (callback) { + return { + cancel: function cancel() { + return _this.target.postMessage({ + targetMapId: targetMapId, + sourceMapId: _this.mapId, + type: '', + id: String(id) + }); + } + }; + } + } + }, { + key: "receive", + value: function receive(message) { + var _this2 = this; + + // TODO 处理中断Worker + var data = message.data; + var id = data.id; + var callback; + + var done = function done(err, data) { + delete _this2.callbacks[id]; + var buffers = []; + + _this2.target.postMessage({ + // 发送结果数据 + sourceMapId: _this2.mapId, + type: '', + id: String(id), + error: err ? JSON.stringify(err) : null, + data: (0, _worker_transform.serialize)(data, buffers) + }, buffers); + }; + + if (data.type === '' || data.type === '') { + callback = this.callbacks[data.id]; + delete this.callbacks[data.id]; + + if (callback && data.error) { + callback(data.error); + } else if (callback) { + callback(null, data.data); + } + } else if (typeof data.id !== 'undefined' && this.parent[data.type]) { + // loadTile + this.parent[data.type](data.sourceMapId, data.data, done); + } else if (typeof data.id !== 'undefined' && this.parent.getWorkerSource) { + var keys = data.type.split('.'); + var params = data.data; + var workerSource = this.parent.getWorkerSource(data.sourceMapId, keys[0], params.source); + workerSource[keys[1]](params, done); + } else { + this.parent[data.type](data.data); + } + } + }]); + + return Actor; +}(); + +exports["default"] = Actor; \ No newline at end of file diff --git a/lib/worker/geojsonSourceWorker.js b/lib/worker/geojsonSourceWorker.js new file mode 100644 index 0000000000..9a390c31f7 --- /dev/null +++ b/lib/worker/geojsonSourceWorker.js @@ -0,0 +1 @@ +"use strict"; \ No newline at end of file diff --git a/lib/worker/main.worker.js b/lib/worker/main.worker.js new file mode 100644 index 0000000000..9f4a66363b --- /dev/null +++ b/lib/worker/main.worker.js @@ -0,0 +1,24 @@ +"use strict"; + +(void 0).addEventListener('message', function (e) { + var res = e.data; // res = { + // command : 'POLYGON-EXTRUDE', + // data : {data:geojson,options:{}} + // } + + var result; + + switch (res.command) { + case 'geojson': + result = res; + self.postMessage(result); + break; + + default: + self.postMessage(result); + break; + } +}); +(void 0).addEventListener('error', function (e) { + console.error('filename:' + e.filename + '\nmessage:' + e.message + '\nline:' + e.lineno); +}); \ No newline at end of file diff --git a/lib/worker/web_worker.js b/lib/worker/web_worker.js new file mode 100644 index 0000000000..00876c5541 --- /dev/null +++ b/lib/worker/web_worker.js @@ -0,0 +1,14 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = _default; + +var _index = _interopRequireDefault(require("../index")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _default() { + return new Worker(_index["default"].workerUrl); +} \ No newline at end of file diff --git a/lib/worker/worker.js b/lib/worker/worker.js new file mode 100644 index 0000000000..0530192598 --- /dev/null +++ b/lib/worker/worker.js @@ -0,0 +1,117 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _vector_tile_worker_source = _interopRequireDefault(require("../source/vector_tile_worker_source")); + +var _actor = _interopRequireDefault(require("./actor")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +// 统一管理workerSource 实例化 +var Worker = +/*#__PURE__*/ +function () { + function Worker(self) { + var _this = this; + + _classCallCheck(this, Worker); + + this.self = self; + this.actor = new _actor["default"](self, this); + this.workerSourceTypes = { + vector: _vector_tile_worker_source["default"] + }; + this.workerSources = {}; + + this.self.registerWorkerSource = function (name, WorkerSource) { + if (_this.workerSourceTypes[name]) { + throw new Error("Worker source with name \"".concat(name, "\" already registered.")); + } + + _this.workerSourceTypes[name] = WorkerSource; + }; + + this.layerStyles = {}; + } + + _createClass(Worker, [{ + key: "loadTile", + value: function loadTile(mapId, params, callback) { + this.getWorkerSource(mapId, params.type, params.sourceID).loadTile(params, callback); + } + }, { + key: "abortTile", + value: function abortTile(mapId, params, callback) { + this.getWorkerSource(mapId, params.type, params.sourceID).abortTile(params, callback); + } + }, { + key: "removeTile", + value: function removeTile(mapId, params, callback) { + this.getWorkerSource(mapId, params.type, params.sourceID).removeTile(params, callback); + } + }, { + key: "setLayers", + value: function setLayers(mapId, layercfgs, callback) { + this.layerStyles[mapId] = layercfgs; // mapid layerID + + if (this.workerSources[mapId]) { + for (var sourceId in this.workerSources[mapId].vector) { + this.workerSources[mapId].vector[sourceId].layerStyle = layercfgs; + } + } + + callback(); + } // updateLayers(id, params, callback) { + // } + + /** + * 获取workerSource + * @param {string} mapId WorkerPool Id + * @param {string} type 瓦片类型 目前支持Vector + * @param {string} source souce ID + * @return {*} WorkerSource + */ + + }, { + key: "getWorkerSource", + value: function getWorkerSource(mapId, type, source) { + var _this2 = this; + + if (!this.workerSources[mapId]) { + this.workerSources[mapId] = {}; + } + + if (!this.workerSources[mapId][type]) { + this.workerSources[mapId][type] = {}; + } + + if (!this.workerSources[mapId][type][source]) { + // use a wrapped actor so that we can attach a target mapId param + // to any messages invoked by the WorkerSource + var actor = { + send: function send(type, data, callback) { + _this2.actor.send(type, data, callback, mapId); + } + }; + this.workerSources[mapId][type][source] = new this.workerSourceTypes[type](actor, this.layerStyles[mapId]); + } + + return this.workerSources[mapId][type][source]; + } + }]); + + return Worker; +}(); + +exports["default"] = Worker; +self.worker = new Worker(self); \ No newline at end of file diff --git a/lib/worker/workerTile.js b/lib/worker/workerTile.js new file mode 100644 index 0000000000..ae9b0062e9 --- /dev/null +++ b/lib/worker/workerTile.js @@ -0,0 +1,152 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _tile_mapping = _interopRequireDefault(require("../core/controller/tile_mapping")); + +var _index = require("../geom/buffer/index"); + +var _source = _interopRequireDefault(require("../core/source")); + +var _global = _interopRequireDefault(require("../global")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var pointShape = _global["default"].pointShape; + +var WorkerTile = +/*#__PURE__*/ +function () { + function WorkerTile(params) { + _classCallCheck(this, WorkerTile); + + this.tileID = params.id; + this.source = params.sourceID; + this.params = params; + } + + _createClass(WorkerTile, [{ + key: "parse", + value: function parse(data, layerstyle, actor, callback) { + this.status = 'parsing'; + this.data = data; + + var sourceStyle = this._layerStyleGroupBySourceID(layerstyle)[this.source]; + + var tile = this.tileID.split('_'); + var sourceLayerData = {}; // 数据源解析 + + for (var sourcelayer in sourceStyle) { + // sourceLayer + var vectorLayer = data.layers[sourcelayer]; + + if (vectorLayer === undefined) { + return null; + } + + var style = sourceStyle[sourcelayer][0]; + style.sourceOption.parser.type = 'vector'; + style.sourceOption.parser.tile = tile; + var tileSource2 = new _source["default"](_objectSpread({}, style.sourceOption, { + mapType: style.mapType, + projected: true, + data: data.layers[sourcelayer] + })); + + for (var i = 0; i < sourceStyle[sourcelayer].length; i++) { + var _style = sourceStyle[sourcelayer][i]; + var tileMapping = new _tile_mapping["default"](tileSource2, _style); + + if (_style.type === 'point') { + _style.shape = this._getPointShape(tileMapping); + } + + var geometryBuffer = (0, _index.getBuffer)(_style.type, _style.shape); + var buffer = new geometryBuffer({ + layerData: tileMapping.layerData, + shape: _style.shape + }); + sourceLayerData[_style.layerId] = { + buffer: { + attributes: buffer.attributes, + indexArray: buffer.indexArray + }, + // layerData: tileMapping.layerData, + // sourceData: tileSource.data, + shape: _style.shape, + layerId: _style.layerId, + sourcelayer: sourcelayer, + tileId: this.tileID + }; + } + } + + this.status = 'done'; + callback(null, _objectSpread({}, sourceLayerData)); + } + }, { + key: "_layerStyleGroupBySourceID", + value: function _layerStyleGroupBySourceID(layerStyles) { + var sourceStyles = {}; // 支持VectorLayer + + for (var layerId in layerStyles) { + var sourceID = layerStyles[layerId].sourceOption.id; + var sourcelayer = layerStyles[layerId].sourceOption.parser.sourceLayer; + if (!sourceStyles[sourceID]) sourceStyles[sourceID] = {}; + if (!sourceStyles[sourceID][sourcelayer]) sourceStyles[sourceID][sourcelayer] = []; + sourceStyles[sourceID][sourcelayer].push(layerStyles[layerId]); + } + + return sourceStyles; + } + }, { + key: "_getPointShape", + value: function _getPointShape(tileMapping) { + var shape = null; + + if (!tileMapping.layerData[0].hasOwnProperty('shape')) { + return 'normal'; + } + + for (var i = 0; i < tileMapping.layerData.length; i++) { + shape = tileMapping.layerData[i].shape; + + if (shape !== undefined) { + break; + } + } // 2D circle 特殊处理 + + + if (pointShape['2d'].indexOf(shape) !== -1) { + return 'fill'; + } else if (pointShape['3d'].indexOf(shape) !== -1) { + return 'extrude'; + } // TODO 图片支持 + // else if (this.scene.image.imagesIds.indexOf(shape) !== -1) { + // return 'image'; + // } + + + return 'text'; + } + }]); + + return WorkerTile; +}(); + +exports["default"] = WorkerTile; \ No newline at end of file diff --git a/lib/worker/worker_controller.js b/lib/worker/worker_controller.js new file mode 100644 index 0000000000..5cbfaab0c1 --- /dev/null +++ b/lib/worker/worker_controller.js @@ -0,0 +1,96 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _actor = _interopRequireDefault(require("./actor")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var id = 1; + +function asyncAll(array, fn, callback) { + if (!array.length) { + return callback(null, []); + } + + var remaining = array.length; + var results = new Array(array.length); + var error = null; + array.forEach(function (item, i) { + fn(item, function (err, result) { + if (err) error = err; + results[i] = result; + if (--remaining === 0) callback(error, results); + }); + }); +} + +var WorkerController = +/*#__PURE__*/ +function () { + function WorkerController(workerPool, parent) { + _classCallCheck(this, WorkerController); + + this.workerPool = workerPool; + this.actors = []; + this.currentActor = 0; + this.id = id++; + var workers = this.workerPool.acquire(this.id); + + for (var i = 0; i < workers.length; i++) { + var worker = workers[i]; + var actor = new WorkerController.Actor(worker, parent, this.id); + actor.name = "Worker ".concat(i); + this.actors.push(actor); + } + } + /** + * Broadcast a message to all Workers. + */ + + + _createClass(WorkerController, [{ + key: "broadcast", + value: function broadcast(type, data, cb) { + cb = cb || function () {}; + + asyncAll(this.actors, function (actor, done) { + actor.send(type, data, done); + }, cb); + } + }, { + key: "send", + value: function send(type, data, callback, targetID) { + if (typeof targetID !== 'number' || isNaN(targetID)) { + // Use round robin to send requests to web workers. + targetID = this.currentActor = (this.currentActor + 1) % this.actors.length; + } + + this.actors[targetID].send(type, data, callback, targetID); + return targetID; + } + }, { + key: "remove", + value: function remove() { + this.actors.forEach(function (actor) { + actor.remove(); + }); + this.actors = []; + this.workerPool.release(this.id); + } + }]); + + return WorkerController; +}(); + +exports["default"] = WorkerController; +WorkerController.Actor = _actor["default"]; \ No newline at end of file diff --git a/lib/worker/worker_pool.js b/lib/worker/worker_pool.js new file mode 100644 index 0000000000..fccd86b574 --- /dev/null +++ b/lib/worker/worker_pool.js @@ -0,0 +1,65 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _web_worker = _interopRequireDefault(require("./web_worker")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +/** + * Constructs a worker pool. + * @private + */ +var WorkerPool = +/*#__PURE__*/ +function () { + function WorkerPool() { + _classCallCheck(this, WorkerPool); + + this.active = {}; + } + + _createClass(WorkerPool, [{ + key: "acquire", + value: function acquire(mapId) { + if (!this.workers) { + // Lazily look up the value of mapboxgl.workerCount so that + // client code has had a chance to set it. + this.workers = []; + + while (this.workers.length < WorkerPool.workerCount) { + this.workers.push(new _web_worker["default"]()); + } + } + + this.active[mapId] = true; + return this.workers.slice(); + } + }, { + key: "release", + value: function release(mapId) { + delete this.active[mapId]; + + if (Object.keys(this.active).length === 0) { + this.workers.forEach(function (w) { + w.terminate(); + }); + this.workers = null; + } + } + }]); + + return WorkerPool; +}(); + +exports["default"] = WorkerPool; +WorkerPool.workerCount = Math.max(Math.floor(window.navigator.hardwareConcurrency / 2), 1); \ No newline at end of file diff --git a/lib/worker/worker_transform.js b/lib/worker/worker_transform.js new file mode 100644 index 0000000000..492a942827 --- /dev/null +++ b/lib/worker/worker_transform.js @@ -0,0 +1,87 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.serialize = serialize; +exports.deserialize = deserialize; + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function serialize(input, transferables) { + if (input === null || input === undefined || typeof input === 'boolean' || typeof input === 'number' || typeof input === 'string' || input instanceof Boolean || input instanceof Number || input instanceof String || input instanceof Date || input instanceof RegExp) { + return input; + } + + if (input instanceof ArrayBuffer) { + if (transferables) { + transferables.push(input); + } + + return input; + } + + if (ArrayBuffer.isView(input)) { + var view = input; + + if (transferables) { + transferables.push(view.buffer); + } + + return view; + } + + if (input instanceof ImageData) { + if (transferables) { + transferables.push(input.data.buffer); + } + + return input; + } + + if (Array.isArray(input)) { + var serialized = []; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var item = _step.value; + serialized.push(serialize(item, transferables)); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator["return"] != null) { + _iterator["return"](); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return serialized; + } + + if (_typeof(input) === 'object') { + var properties = {}; + + for (var key in input) { + if (!input.hasOwnProperty(key)) { + continue; + } + + var property = input[key]; + properties[key] = serialize(property, transferables); + } + + return properties; + } +} + +function deserialize() {} \ No newline at end of file diff --git a/rollup.config.js b/rollup.config.js index ab9ebd61de..7c7db3e4a9 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -7,9 +7,9 @@ import resolve from 'rollup-plugin-node-resolve'; import commonjs from 'rollup-plugin-commonjs'; import builtins from 'rollup-plugin-node-builtins'; import { createFilter } from 'rollup-pluginutils'; -// import imageInliner from 'postcss-image-inliner'; +import imageInliner from 'postcss-image-inliner'; import postcss from 'rollup-plugin-postcss'; -import url from 'postcss-url'; +import postcssImport from 'postcss-import'; import { terser } from 'rollup-plugin-terser'; const { BUILD, MINIFY } = process.env; const minified = MINIFY === 'true'; @@ -45,8 +45,13 @@ const config = [ json(), // css({ raw: './build/l7.css' }), postcss({ - plugins: [ url({ url: 'inline' }) ] + modules: true, + plugins: [ + postcssImport(), + imageInliner({ assetPaths: [ '**/images/' ] }) + ] }), + // url({ url: 'inline' }), buble({ transforms: { dangerousForOf: true }, objectAssign: 'Object.assign' diff --git a/src/component/control/layer.js b/src/component/control/layer.js index d948d80237..4ff968a1ed 100644 --- a/src/component/control/layer.js +++ b/src/component/control/layer.js @@ -53,7 +53,7 @@ export default class Layers extends Control { const className = 'l7-control-layers', container = this._container = DOM.create('div', className), collapsed = this.get('collapsed'); - + // makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released container.setAttribute('aria-haspopup', true); diff --git a/src/core/scene.js b/src/core/scene.js index eb191596ab..1537b5dad1 100644 --- a/src/core/scene.js +++ b/src/core/scene.js @@ -128,7 +128,6 @@ export default class Scene extends Base { 'dblclick' ]; events.forEach(event => { - this._container.addEventListener(event, e => { // 要素拾取 if (e.target.nodeName !== 'CANVAS') return; @@ -139,6 +138,7 @@ export default class Scene extends Base { }, true); }); } + removeLayer(layer) { const layerIndex = this._layers.indexOf(layer); if (layerIndex > -1) { @@ -154,6 +154,7 @@ export default class Scene extends Base { } this.animateCount++; } + stopAnimate() { if (this.animateCount === 1) { this._engine.stop(); @@ -168,16 +169,19 @@ export default class Scene extends Base { this.map.on('mapmove', this._updateRender); this.map.on('camerachange', this._updateRender); } + unRegsterMapEvent() { this.map.off('mousemove', this._updateRender); this.map.off('mapmove', this._updateRender); this.map.off('camerachange', this._updateRender); } // control + addControl(ctr) { this.get('controlController').addControl(ctr); return this; } + removeControl(ctr) { this.get('controlController').removeControl(ctr); } diff --git a/src/worker/workerTile.js b/src/worker/workerTile.js index 40426c9435..46e4e97373 100644 --- a/src/worker/workerTile.js +++ b/src/worker/workerTile.js @@ -2,7 +2,6 @@ import TileMapping from '../core/controller/tile_mapping'; import { getBuffer } from '../geom/buffer/index'; import Source from '../core/source'; import Global from '../global'; -import { feature } from '_@turf_helpers@6.1.4@@turf/helpers'; const { pointShape } = Global; export default class WorkerTile {