Skip to content

ThreeView Class

ThreeView is the main class for creating and managing 3D map visualizations using Three.js and WebGL. It provides a comprehensive API for layer management, camera control, rendering, and event handling.

import ThreeView, { JAPAN_GSI_ELEVATION_DECODER } from "@navaramap/three";
import { DefaultPlugin } from "@navaramap/three_default_plugin";
import { Vector3 } from "three";
// Create ThreeView instance
const view = new ThreeView({
shadow: true,
animation: true,
backgroundColor: 0x0a0a0f,
logarithmicDepthBuffer: true,
});
const plugin = new DefaultPlugin();
view.addPlugin(plugin);
// Initialize the view
await view.init();
// Add default photorealistic objects (sky, stars, sun, light probe)
const defaultLayers = plugin.addDefaultPhotorealScene();
// Add terrain layer
const terrainSource = view.addSource({
type: "raster-dem",
url: "https://cyberjapandata.gsi.go.jp/xyz/dem_png/{z}/{x}/{y}.png",
elevationDecoder: JAPAN_GSI_ELEVATION_DECODER(),
maxZoom: 15,
minZoom: 5,
});
view.addLayer({
type: "terrain",
source: terrainSource,
terrain: {
castShadow: true,
receiveShadow: true,
},
});
// Add hillshade layer
const hillshadeSource = view.addSource({
type: "raster-dem",
// Credit:
// - Geospatial Information Authority of Japan Tiles - Digital Elevation Map
// https://maps.gsi.go.jp/development/ichiran.html
url: "https://cyberjapandata.gsi.go.jp/xyz/dem_png/{z}/{x}/{y}.png",
elevationDecoder: JAPAN_GSI_ELEVATION_DECODER(),
minZoom: 6,
maxZoom: 15,
});
view.addLayer({
type: "raster",
source: hillshadeSource,
hillshade: {},
});
// Add raster tile layer
const rasterSource = view.addSource({
type: "raster-tile",
url: "https://tile.openstreetmap.org/{z}/{x}/{y}.png",
maxZoom: 23,
});
view.addLayer({
type: "raster",
source: rasterSource,
raster: {
color: new Color().setHex(0xffffff),
opacity: 1,
},
});
// Set camera position
view.setCamera({
lng: 139.7,
lat: 35.7,
height: 1000,
pitch: -45,
heading: 0,
roll: 0,
});

Type: HTMLElement | undefined

Description: The HTML container element for rendering the view. When specified, ThreeView adds a canvas within this container.

Example:

const view = new ThreeView({
container: document.getElementById("map") ?? undefined,
});

Type: HTMLCanvasElement | OffscreenCanvas | undefined

Description: The canvas element used for rendering. When specified, this canvas is used. When not specified, a new canvas is created.

Example:

const view = new ThreeView({
canvas: document.getElementById("canvas") as HTMLCanvasElement,
});

Type: number | undefined

Description: Override for the device pixel ratio. Affects rendering quality on high-DPI displays. When not specified, the device’s default value is used.

Example:

const view = new ThreeView({
pixelRatio: 2,
});

Type: boolean | undefined

Description: Whether to disable automatic resize handling on window resize events. When true, the view is not automatically resized when the window size changes.

Default: false

Example:

const view = new ThreeView({
disableAutoResize: true,
});

Type: boolean | undefined

Description: Whether to enable debug mode. When true, additional debug information such as performance statistics overlays is displayed.

Default: false

Example:

const view = new ThreeView({
debug: true,
});

Type: AtmosphereOptions | undefined

Description: Configuration options for atmospheric rendering. Configures the sky, sun, and atmospheric scattering effects. Sun and moon positions are automatically calculated based on the date specified in the date property and reflected in related Descriptors such as SunLightDesc.

export type AtmosphereOptions = {
atmosphereAssetsUrl?: string; // URL for atmosphere asset files
stbnUrl?: string; // URL for STBN textures
date?: Date; // Date and time used for sun/moon position calculations
};

Example:

const view = new ThreeView({
atmosphere: {
atmosphereAssetsUrl: "/assets/atmosphere",
date: new Date("2024-06-21T12:00:00"),
},
});
// The date can be changed after initialization
await view.init();
view.atmosphere.date = new Date("2024-12-21T18:00:00");

Type: Color | undefined

Description: The background color of the scene. Specify an instance of the Color class.

Default: 0x0a0a0f (dark blue-gray)

Example:

import ThreeView, { Color } from "@navaramap/three";
const view = new ThreeView({
backgroundColor: new Color().setHex(0x1a1a2e),
});

Type: boolean | undefined

Description: Configuration option for feature picking. When enabled, the pick event fires when a feature is clicked.

Default: true

Example:

const view = new ThreeView({
picking: true,
});
// Listen for pick events
view.on("pick", (info) => {
if (info) {
console.log("Selected feature:", info.properties);
}
});

Type: boolean | undefined

Description: Whether to run the main loop every frame. When true, rendering occurs continuously. When false, rendering occurs only when changes are detected or forceUpdate() is called.

Default: false

Example:

const view = new ThreeView({
animation: true,
});

Type: number | undefined

Description: Number of MSAA (Multi-Sample Anti-Aliasing) samples. When 0, MSAA is disabled. Use with caution as it impacts performance.

Default: 0

Example:

const view = new ThreeView({
multisampling: 4,
});

Type: boolean | undefined

Description: Whether to use half-precision floating-point numbers (half-float) for post-processing. When true, rendering quality is improved.

Default: true

Example:

const view = new ThreeView({
halfFloat: true,
});

Type: boolean | undefined

Description: Whether to use a logarithmic depth buffer. When true, depth precision is improved at large scales. Some effects do not support this, so it should be set to false in such cases.

Default: true

Example:

const view = new ThreeView({
logarithmicDepthBuffer: true,
});

Type: boolean | undefined

Description: Whether to enable shadow mapping. Must be specified at initialization and cannot be changed later.

Default: false

Example:

const view = new ThreeView({
shadow: true,
});

Type: number | undefined

Description: Milliseconds without data or tile processing activity that must elapse before the idle event fires. Continuous animations and effects do not count as activity. Lowering this value makes the engine report idle sooner; raising it delays the notification until a longer quiet period has passed.

Default: 100

Example:

const view = new ThreeView({
idleThreshold: 200,
});
view.on("idle", () => {
console.log("Engine has been idle for 200 ms");
});

Type: boolean | undefined

Description: Whether to enable optimizations for mobile devices. When true, settings suitable for mobile devices are applied, such as lower pixel ratios and lighter effects.

Default: Auto-detected from the device (mobile devices are optimized automatically). Set explicitly to override the detection.

Example:

const view = new ThreeView({
mobileOptimization: true,
});

Type: number | undefined

Description: Memory budget in bytes for tile caches (WASM buffers + estimated GPU cost). Tiles leaving the view are retained until the budget is exceeded, then evicted least-recently-visited first — panning back is refetch-free while total usage stays capped.

Default: Device-dependent — desktop: a quarter of the reported device memory capped at 2 GB; mobile: 512 MB (256 MB when the device reports less than 4 GB). See getDefaultCacheBytes().

Example:

const view = new ThreeView({
cacheBytes: 512 * 1024 * 1024, // 512 MB
});

Type: Partial<LodFogSettings> | undefined

Description: LOD fog: a distance-based screen-space-error relaxation used by tile LOD selection — far tiles tolerate a larger error and stay coarser while near tiles keep full resolution. Purely an LOD control; it never affects visual fog rendering. Partial values are merged over the device default.

type LodFogSettings = {
enabled: boolean;
// Distance scale of the relaxation ramp (2.0e-4 ≈ 63% strength at 5km)
density: number;
// Maximum SSE relaxation (in pixels) at far distance
sseFactor: number;
};

Default: Device-memory-dependent — desktop: { density: 2.0e-4, sseFactor: 2.0 }; low-memory devices ship a stronger curve so the tile working set stays small. See getDefaultLodFog().

Example:

const view = new ThreeView({
lodFog: { density: 2.5e-4, sseFactor: 3.0 },
});

Type: Partial<DynamicSseSettings> | undefined

Description: Dynamic screen-space error (CesiumJS dynamicScreenSpaceError equivalent): tilted, street-level horizon views tolerate a larger error for far tiles, cutting the tile working set in exactly the views that over-refine. Zero effect looking straight down; fades out as the camera climbs past maxHeight meters. Partial values are merged over the default.

type DynamicSseSettings = {
enabled: boolean;
// Distance scale of the relaxation ramp before tilt/height scaling
density: number;
// Maximum SSE relaxation (in pixels) at full tilt and saturation
sseFactor: number;
// Fraction of the height band below which the effect is at full strength
heightFalloff: number;
// Camera height band (meters above the ellipsoid) the effect fades across
minHeight: number;
maxHeight: number;
};

Default: { enabled: true, density: 2.0e-4, sseFactor: 24.0, heightFalloff: 0.25, minHeight: 0, maxHeight: 8000 }. See getDefaultDynamicSse().

Example:

const view = new ThreeView({
dynamicSse: { sseFactor: 16.0, maxHeight: 4000 },
});

Type: object | undefined

Description: Overrides for the worker-side memory budgets and the memory-pressure LOD degrade. Defaults derive from the device memory together with cacheBytes — see getDefaultMemoryBudgets().

type MemoryBudgetOptions = {
// WASM heap budget per tile worker; the pool recycles a worker above it
maxWorkerHeapBytes?: number;
// Font-worker cache budget (font data + atlas pixels; caps further growth)
fontBudgetBytes?: number;
// In-flight data fetch cap per tile pipeline
maxPendingRequests?: number;
// Resting (base) memory-pressure SSE multiplier; > 1 keeps far tiles coarser even without pressure
sseMultiplierMin?: number;
// Ceiling the dynamic memory-pressure SSE degrade can climb to
sseMultiplierMax?: number;
};

Example:

const view = new ThreeView({
memoryBudget: {
maxWorkerHeapBytes: 128 * 1024 * 1024,
sseMultiplierMin: 1.0,
sseMultiplierMax: 8.0,
},
});

Type: { enabled: boolean; url?: string } | undefined

Description: Configuration for shared water textures. When enabled, a single water normal texture is shared across all meshes that use water effects. This is more efficient than each mesh loading its own texture individually.

Default: Disabled when omitted (the shared water texture is loaded only when { enabled: true } is passed).

type WaterTextureOptions = {
enabled: boolean; // Whether to enable water texture sharing
url?: string; // URL for custom water normal texture (uses built-in texture when omitted)
};

Example:

// Use built-in texture
const view = new ThreeView({
waterTexture: { enabled: true },
});
// Use a custom texture
const viewWithCustomWater = new ThreeView({
waterTexture: {
enabled: true,
url: "https://example.com/water-normal.png",
},
});

Type: GlobeOptions

Description: Additional options related to globe display. ThreeView constructor options inherit from GlobeOptions.

type GlobeOptions = {
maxSse?: number; // Screen space error threshold for LOD calculations (initialization only)
segments?: number; // Number of segments for mesh tessellation (initialization only)
color?: Color; // Base color of the globe surface
hideUnderground?: boolean; // Whether to hide underground geometry
shouldComputeNormalFromVertex?: boolean; // Whether to compute normals from vertex positions (initialization only)
transparent?: boolean; // Whether to make the material transparent
opacity?: number; // Global material opacity (0.0-1.0)
wireframe?: boolean; // Whether to render in wireframe mode
};

Disabling hideUnderground may cause unexpected behavior with some effect Descriptors.

Example:

import ThreeView, { Color } from "@navaramap/three";
const view = new ThreeView({
maxSse: 2,
segments: 10,
color: new Color().setHex(0x1a1a2e),
hideUnderground: true,
wireframe: false,
});