Skip to content
3DGIPublic

About

Typescript modules for city models

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

11 Commits

Folders and files

Repository files navigation

vimoc

Modules for parsing and reprojecting CityJSON and CityJSONSeq, colouring objects by attribute, and rendering CityJSON and 3D Tiles with Three.js and MapLibre. The CityJSON modules originated in CJLoupe and are licensed under GPL-3.0-or-later. The MapLibre viewer incorporates code from 3DToML. See its MIT license and notice.

Installation

Install from the GitHub repository with Bun, replacing OWNER and REF with the repository owner and a tag or commit.

bun add git+https://github.com/OWNER/vimoc.git#REF

The package exports source for Bun and TypeScript-aware bundlers such as Vite. For the MapLibre viewers, install three@0.185.1 and maplibre-gl@6.15.0. Add @types/three@^0.185.0 for TypeScript. The bundler must handle CSS, PNGs, and the MapLibre worker asset. Keep the MapLibre version pinned because the shared viewer uses its internal camera API for terrain depth alignment.

The standalone vimoc/cj-three module also supports three@^0.181.2 with @types/three@^0.181.0.

Entry points

Import Responsibilities
vimoc/cityjson-core Parsing, dataset composition, object identity, attribute inheritance, LoD resolution, reprojection, and packed geometry buffers
vimoc/cityjson-core/io File and URL loading with browser APIs and optional cancellation for fetches
vimoc/colors Attribute analysis, palettes, histograms, and colour settings
vimoc/cj-three Geometry construction, materials, batching, source-aware picking, and a scene layer
vimoc/maplibre Shared MapLibre and Three.js viewer with a custom layer, camera, terrain and basemap controls
vimoc/maplibre/cityjson CityJSON placement, styling and picking in the shared viewer
vimoc/maplibre/3dtiles 3DToML's MapTilesViewer, with streamed tiles, structural metadata and styling

Using a layer in a Three.js scene

import { parseCityJson } from 'vimoc/cityjson-core'
import { createCityLayer } from 'vimoc/cj-three'

const dataset = parseCityJson(sourceText, 'buildings.city.json')
const layer = createCityLayer({ appearanceMode: 'semantic', onChange: requestRender })
scene.add(layer.group)
layer.setData(dataset)

const hit = layer.pick(raycaster)
// hit: featureId, objectId, geometryIndex, faceIndex, point and distance

// When the host removes the layer:
layer.dispose()

The host owns the scene, camera, renderer, controls, and rendering schedule. The layer owns its geometry, materials, and colour textures. dispose() releases those resources, detaches the group, and can safely be called more than once. Methods that change a disposed layer throw.

Dataset coordinates are world coordinates. The layer renders relative to the dataset centre by default. layer.origin exposes the offset. Supply an origin to align several datasets with the host scene. Picking returns a point in the host scene's coordinate system.

Use setGeometryDisplayMode, setAppearance, setTheme, and setAttributeColors to change presentation. previewColorDomain({ min, max }) updates colour uniforms for that layer. Use previewColorMapBand({ min, max }) with attribute values to preserve the band in the continuous colour texture and apply the configured missing colour outside it. Pass null to restore the ramp. Use setSelectedObject(hit) to highlight a picked object. Call updateFeature(featureId) after changing a feature in the host's dataset.

Reprojecting CityJSON

Pass { reprojection: { targetCrs, transform } } to parseCityJson, parseCityJsonSequence, or the file and URL loaders. The parser applies the transform to decoded Float64 coordinates before computing bounds and invoking the feature and dataset callbacks.

Call reprojectDataset(dataset, { targetCrs, transform }) for an already parsed dataset. This returns new vertex buffers and derives feature extents, dataset bounds and the centre from the transformed geometry. It also transforms any validation error locations. Object extents supplied in the source are recalculated from their geometry when available.

The callback receives (x, y, z, sourceCrs) and returns [x, y, z] in the target CRS. The source CRS comes from the dataset's current coordinate system or the original metadata.referenceSystem. Supply sourceCrs to override it. Use getDatasetCrs(dataset) to read the current CRS. The dataset's original metadata records its source. When combining datasets, give them a common working CRS first.

Showing CityJSON on MapLibre

import { parseCityJson } from 'vimoc/cityjson-core'
import { MapCityJsonViewer } from 'vimoc/maplibre/cityjson'

const dataset = parseCityJson(sourceText, 'buildings.city.json')
const viewer = new MapCityJsonViewer(document.getElementById('map')!, {
  dataset,
  // This example's source is already longitude, latitude and altitude in metres.
  toLngLat: (lng, lat, height) => [lng, lat, height],
  cityLayer: { appearanceMode: 'semantic' },
})

const unsubscribe = viewer.on('object-picked', hit => {
  if (hit) console.log(hit.objectId, hit.attributes, hit.lngLatHeight)
})

// When the host removes the viewer:
unsubscribe()
viewer.destroy()

Give the map container a nonzero width and height and use a Mercator basemap. For projected inputs, supply a toLngLat(x, y, z, sourceCrs) callback that converts the source CRS and returns altitude in metres relative to the map's elevation datum. The adapter projects the returned coordinates to Mercator once per dataset. Pan, pitch and zoom update the map transform each frame.

The map viewers use fixed ambient and hemisphere lighting in the local east/up/south frame. A host that needs its own lights can set them up in its viewer subclass's onSceneReady().

Use viewer.setData(dataset) to replace the model and viewer.setData(null) to clear it. Use viewer.cityLayer for LoD and appearance controls. fitToData() frames the current data. The viewer automatically fits the first dataset unless an initial camera is supplied or fitOnLoad is disabled.

Streaming 3D Tiles

Install the additional peers for this entry point.

bun add 3d-tiles-renderer@0.5.3 @bertt/3dtilesrenderer-styling-plugin@0.1.0 tweakpane@^1.6.1
import { MapTilesViewer } from 'vimoc/maplibre/3dtiles'

const viewer = new MapTilesViewer(document.getElementById('map')!, {
  tilesUrl: 'https://example.org/buildings/tileset.json',
  initialCamera: { lng: 5.3872, lat: 52.1552, ox: 400, oy: 400, oz: 400 },
})

3DToML clients can switch the import to this entry point and keep their existing viewer options, events and methods, including setTilesUrl(). Feature picking and attribute styling use the tileset's glTF structural metadata. The tile peers are optional package dependencies for parser, Three.js, and CityJSON map clients.

For another model format, extend MapThreeViewer. Add the source's Three.js group in onSceneReady(), place it in the viewer's local east/up/south frame in updateModelFrame(), and release the source's resources in disposeModels(). Streaming sources can use the split projection and view camera in updateModels().

Packed geometry and attributes

feature.vertices is a Float64Array of world-space XYZ triples. Geometry stores polygon indices, ring offsets, polygon offsets, and source face indices in Uint32Array buffers. vertexAt, vertexCount, and polygonAt expose these buffers to callers. polygonAt returns views into index storage.

collectAttributeValues(dataset, key, inheritFromParents) yields keyed values for analyzeAttributeValues(key, entries). Pass the analysis to colorizeAttributeAnalysis(analysis, paletteId, paletteColors, seed, customColors) to change the palette without rescanning the dataset. The colour module also accepts keyed values from other data sources.

The Cyclic group in CONTINUOUS_COLORMAP_GROUPS includes Twilight, Twilight Shifted, and HSV, sampled from the Matplotlib colormaps. Each palette joins at the same colour at both ends of the mapped range.

Use collectAttributeFields(dataset, mode) to list object and semantic surface fields for a geometry display mode. collectSurfaceAttributeValues(dataset, key, mode) yields one value per referenced semantic surface, including its type when key is "type". Pass the resulting colour model to layer.setAttributeColors(attributeColorState(model, "surface", paletteColors)). Faces without a value use the missing colour. Object fields use the same flow with "object" and can inherit values from parents.

The dataset stores information needed for rendering. Hosts can retain original source text with the loader's onLoad(dataset, text) callback. Use the parser option onSourceObjects(objects) to inspect decoded CityObjects. It runs once for a CityJSON document and once per CityJSONSeq feature record, including records without renderable geometry. Use onDataset(dataset, header) to inspect the decoded header after all object records have been processed.

Development

bun install
bun test
bun run typecheck

About

Typescript modules for city models

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages