### Install WWT Engine Packages with npm
Source: https://github.com/worldwidetelescope/wwt-webgl-engine/blob/master/docs/engine/content/getting-started/bundled-typescript-model.md
Installs the WWT engine and helper packages using npm. This command adds the necessary libraries to your project's dependencies, enabling you to use the WWT engine in your application.
```sh
$ npm install --save @wwtelescope/engine @wwtelescope/engine-helpers
```
--------------------------------
### Activate Freestanding Mode with TypeScript Model
Source: https://github.com/worldwidetelescope/wwt-webgl-engine/blob/master/docs/engine/content/freestanding-mode/_index.md
This example illustrates activating freestanding mode within the bundled TypeScript model of the WWT WebGL engine. It involves passing the 'freestandingAssetBaseurl' parameter to the WWTInstance constructor, which is part of the '@wwtelescope/engine-helpers' package. This setting ensures the engine can load necessary static assets.
```typescript
// Example usage with InitControlSettings and WWTInstance constructor
// Assuming 'InitControlSettings' and 'WWTInstance' are imported from '@wwtelescope/engine-helpers'
const settings: InitControlSettings = {
freestandingAssetBaseurl: "https://myassets.org/wwtengine",
// ... other settings
};
const wwtInstance = new WWTInstance(settings);
```
--------------------------------
### Change Background and Foreground Images
Source: https://context7.com/worldwidetelescope/wwt-webgl-engine/llms.txt
Provides examples for setting background and foreground images in the WWT viewer. Images can be set by name (case-insensitive substring match) or by retrieving default imagesets. It also shows how to control foreground opacity and look up imagesets by name.
```javascript
import { ImageSetType, BandPass } from '@wwtelescope/engine-types';
// Set by name (case-insensitive substring match)
wwt.setBackgroundImageByName("PanSTARRS");
wwt.setForegroundImageByName("WISE");
// Get default imageset for specific type/bandpass
const defaultSky = wwt.getDefaultImageset(ImageSetType.sky, BandPass.visible);
wwt.setForegroundImageByName(defaultSky.get_name());
// Control foreground opacity (0-100)
script_interface.setForegroundOpacity(50);
// Lookup imageset by name
const imageset = wwt.getImagesetByName("DSS");
if (imageset !== null) {
console.log("Found:", imageset.get_name());
}
```
--------------------------------
### Add Polyline Annotation using WWT API
Source: https://github.com/worldwidetelescope/wwt-webgl-engine/blob/master/docs/engine/content/tutorial/annotations/index.md
Illustrates how to add a polyline annotation in addition to circular annotations. This code snippet extends the previous example by creating a PolyLine object, adding points to it, setting its opacity, and then registering it with the WWT engine. It requires the wwtlib library.
```javascript
function add_annotations() {
const pl = new wwtlib.PolyLine();
for (var i = 0; i < centers.length; i++) {
const c = new wwtlib.Circle();
c.setCenter(centers[i][0], centers[i][1]);
c.set_radius(0.005);
c.set_lineColor("#7ced72");
script_interface.addAnnotation(c);
pl.addPoint(centers[i][0], centers[i][1]);
}
pl.addPoint(centers[0][0], centers[0][1]);
pl.set_opacity(0.5);
script_interface.addAnnotation(pl);
}
```
--------------------------------
### Create Project Directory and Navigate
Source: https://github.com/worldwidetelescope/wwt-webgl-engine/blob/master/docs/engine/content/tutorial/basic-window/index.md
These shell commands are used to create a new directory for the WWT tutorial project and then navigate into it. This sets up the basic file structure for the tutorial.
```shell
$ mkdir wwt-tutorial
$ cd wwt-tutorial
```
--------------------------------
### Serve Local Files with http-server
Source: https://github.com/worldwidetelescope/wwt-webgl-engine/blob/master/docs/engine/content/tutorial/basic-window/index.md
This command uses npx to launch the http-server package, which serves the current directory over HTTP. This is necessary for opening the HTML file in a browser due to browser security restrictions on local files.
```shell
$ npx http-server
```
--------------------------------
### Initialize WWT Engine (Hosted JavaScript)
Source: https://context7.com/worldwidetelescope/wwt-webgl-engine/llms.txt
Basic initialization of the WWT engine using the hosted JavaScript SDK. Suitable for simple web pages without build tools. It sets up a canvas element and registers a callback for when the engine is ready. Dependencies: `wwtsdk.js` script.
```html
WWT Application
```
--------------------------------
### Add Circle Annotations
Source: https://context7.com/worldwidetelescope/wwt-webgl-engine/llms.txt
Illustrates how to create and add circular annotations to the sky view. Circles can be defined by their center coordinates, radius, color, line width, opacity, and ID. Examples include adding multiple circles, removing a specific circle, and clearing all annotations.
```javascript
// Create circles at specific RA/Dec positions
const centers = [
[246.597, -24.350], // RA, Dec in degrees
[246.679, -24.342],
[246.600, -24.413],
];
for (let i = 0; i < centers.length; i++) {
const circle = script_interface.createCircle(false); // false = not filled
circle.setCenter(centers[i][0], centers[i][1]);
circle.set_radius(0.005); // radius in degrees
circle.set_lineColor("#7ced72");
circle.set_lineWidth(2);
circle.set_opacity(0.8); // 0-1 range
circle.set_id(`circle_${i}`);
circle.set_label("Point " + (i + 1));
circle.set_showHoverLabel(true);
script_interface.addAnnotation(circle);
}
// Remove specific annotation
// script_interface.removeAnnotation(circle);
// Clear all annotations
// script_interface.clearAnnotations();
```
--------------------------------
### Navigate to Place Objects in WWT Engine
Source: https://context7.com/worldwidetelescope/wwt-webgl-engine/llms.txt
Demonstrates how to navigate the WorldWideTelescope view to predefined `Place` objects. This includes creating a `Place` with astronomical coordinates and properties, then using `wwt.gotoTarget` with options for smooth motion, tracking, and duration. Basic zoom and move functionalities are also shown.
```javascript
// Create a Place for a specific location
const place = wwtlib.Place.create(
"M31", // name
0.71189, // RA hours
41.268889, // Dec degrees
wwtlib.Classification.galaxy,
"Constellation",
wwtlib.ImageSetType.sky,
0.5 // zoom level
);
// Navigate to place
wwt.gotoTarget(
place,
false, // noZoom: false = use place's zoom
false, // instant: false = smooth motion
true, // trackObject: true = follow moving objects
3.0 // duration in seconds (optional)
);
// Zoom control
wwt.zoom(0.5); // Zoom out by factor of 2 (larger = more zoom out)
wwt.zoom(2.0); // Zoom in by factor of 2
// Move view position
wwt.move(10, 5); // Move view by pixel amounts
```
--------------------------------
### Initialize WWT Engine (TypeScript/npm)
Source: https://context7.com/worldwidetelescope/wwt-webgl-engine/llms.txt
Initialize the WWT engine using npm packages with TypeScript. This method is designed for more sophisticated applications and leverages async/await for cleaner asynchronous operations. Dependencies: `@wwtelescope/engine-helpers` npm package.
```typescript
import { WWTInstance } from '@wwtelescope/engine-helpers';
// Asynchronous initialization
async function initWWT() {
const wwt = new WWTInstance({
elId: 'wwtcanvas',
startInternalRenderLoop: true,
});
await wwt.waitForReady();
console.log("WWT is ready!");
// Access core components:
// wwt.ctl - WWTControl instance
// wwt.si - ScriptInterface instance
// wwt.lm - LayerManager instance
// wwt.stc - SpaceTimeController instance
return wwt;
}
// HTML:
```
--------------------------------
### Initialize and Slew WWT View with JavaScript Callback
Source: https://github.com/worldwidetelescope/wwt-webgl-engine/blob/master/docs/engine/content/tutorial/slew/index.md
This JavaScript code initializes the WWT engine and sets up a callback to slew the view once the engine is ready. It demonstrates fetching the WWT singleton instance and using `gotoRADecZoom` to navigate. Dependencies include the `wwtlib` library.
```javascript
var script_interface, wwt;
function init_wwt() {
const builder = new wwtlib.WWTControlBuilder("wwtcanvas");
builder.startRenderLoop(true);
script_interface = builder.create();
script_interface.add_ready(on_ready);
}
function on_ready() {
console.log("WWT is ready!");
wwt = wwtlib.WWTControl.singleton;
wwt.gotoRADecZoom(17.75, -28.9, 10, false);
}
window.addEventListener("load", init_wwt);
```
--------------------------------
### HTML Structure for WWT Application
Source: https://github.com/worldwidetelescope/wwt-webgl-engine/blob/master/docs/engine/content/tutorial/basic-window/index.md
This HTML code sets up a basic webpage to host the WWT canvas. It includes the WWT SDK script and a div element for the canvas, along with JavaScript to initialize the WWT control.
```html
My First WWT Application
```
--------------------------------
### Configure Engine Builder Options
Source: https://context7.com/worldwidetelescope/wwt-webgl-engine/llms.txt
Configure initial settings for the WWT engine builder before instantiation. Options include setting the initial view (coordinates and zoom), the rendering mode (sky, earth, black), and enabling freestanding mode. Dependencies: `@wwtelescope/engine` npm package.
```typescript
import { WWTControlBuilder } from '@wwtelescope/engine';
const builder = new WWTControlBuilder("wwtcanvas");
// Configure initial view (declination, RA in degrees, zoom level)
builder.initialView(0, 0, 360);
// Set initial mode: "sky", "earth", or "black"
builder.initialMode("sky");
// Enable freestanding mode (no worldwidetelescope.org dependencies)
builder.freestandingMode("https://web.wwtassets.org/engine/assets");
// Control render loop (false = manual control via renderOneFrame)
builder.startRenderLoop(false);
const scriptInterface = builder.create();
```
--------------------------------
### Vue App Initialization with WWT Engine
Source: https://github.com/worldwidetelescope/wwt-webgl-engine/blob/master/docs/engine/engine-pinia-index.md
The main application file for a Vue app using the WWT engine. It initializes the Vue app, uses the wwtPinia plugin, registers the WorldWideTelescope component, and mounts the app to the DOM.
```javascript
import { createApp } from "vue";
import { wwtPinia, WWTComponent } from "@wwtelescope/engine-pinia";
import App from "./App.vue";
createApp(App)
.use(wwtPinia)
.component('WorldWideTelescope', WWTComponent)
.mount("#app");
```
--------------------------------
### Configure Color Maps in JavaScript
Source: https://context7.com/worldwidetelescope/wwt-webgl-engine/llms.txt
Demonstrates how to create and apply color maps for scalar-to-color mapping using built-in colormaps or custom color lists. It shows mapping scalar values to colors.
```javascript
import { ColorMapContainer, Color } from '@wwtelescope/engine';
// Use built-in Matplotlib colormaps
const viridis = ColorMapContainer.fromNamedColormap("viridis");
// Available: viridis, plasma, inferno, magma, cividis, greys, gray,
// purples, blues, greens, oranges, reds, rdylbu
// Create custom colormap from hex colors
const custom = ColorMapContainer.fromStringList([
"#000000",
"#ff0000",
"#ffff00",
"#ffffff"
]);
// Create from ARGB values
const argb = ColorMapContainer.fromArgbList([
[255, 0, 0, 0], // Black
[255, 255, 0, 0], // Red
[255, 255, 255, 0], // Yellow
[255, 255, 255, 255] // White
]);
// Map scalar value to color
const color = viridis.findClosestColor(0.5); // value 0-1
console.log("RGB:", color.r, color.g, color.b);
```
--------------------------------
### Load Image Collection using WTML
Source: https://context7.com/worldwidetelescope/wwt-webgl-engine/llms.txt
Demonstrates how to load external imagery datasets using WTML collection files. It shows both a plain JavaScript approach with callbacks and a TypeScript version using Promises. Ensure the WTML file path is correct and accessible.
```javascript
// Plain JavaScript with callback
script_interface.add_collectionLoaded(on_wtml_loaded);
script_interface.loadImageCollection(
"https://data1.wwtassets.org/packages/2023/07_jwst/weic2316a/index.wtml",
false // loadChildFolders (optional)
);
function on_wtml_loaded() {
console.log("Collection loaded");
// Imagesets from WTML are now available by name
wwt.setForegroundImageByName("Rho Ophiuchi cloud complex");
script_interface.setForegroundOpacity(100); // 0-100 range
}
```
```typescript
// TypeScript/helpers version with Promise
const folder = await wwt.loadImageCollection(
"https://data1.wwtassets.org/packages/2023/07_jwst/weic2316a/index.wtml"
);
console.log("Loaded folder:", folder.get_name());
```
--------------------------------
### Vue App Initialization with Custom ID
Source: https://github.com/worldwidetelescope/wwt-webgl-engine/blob/master/docs/engine/engine-pinia-index.md
Demonstrates initializing a Vue app with a custom ID to allow multiple WWT instances on the same page. This is an alternative to using iframes for managing separate WWT instances.
```javascript
...
createApp(App, {
customId: "myCustomId"
})
.use(wwtPinia)
.component('WorldWideTelescope', WWTComponent)
.mount("#app");
```
--------------------------------
### Create Spreadsheet (Data Table) Layer
Source: https://context7.com/worldwidetelescope/wwt-webgl-engine/llms.txt
Demonstrates creating a visual layer from CSV data, allowing large datasets to be rendered with customizable markers and colors. This involves defining column mappings for RA, Dec, size, and color, and setting rendering options like plot type and marker scale. The created layer can be accessed later via the LayerManager.
```javascript
import { PlotTypes, MarkerScales } from '@wwtelescope/engine-types';
const csv_data = `\
ra,dec,size,color,name
246.597,-24.350,1,#FF0000,Star A
246.679,-24.342,2,#00FF00,Star B
246.600,-24.413,3,#8888FF,Star C
`;
const layer = wwtlib.LayerManager.createSpreadsheetLayer(
"Sky", // reference frame
"My Layer", // layer name
csv_data // CSV data with \r\n line endings
);
// Configure column mappings
layer.set_lngColumn(0); // Column 0 = RA/longitude
layer.set_latColumn(1); // Column 1 = Dec/latitude
layer.set_sizeColumn(2); // Column 2 = marker size
layer.set_colorMapColumn(3); // Column 3 = color
// Set rendering options
layer.set_astronomical(true);
layer.set_plotType(PlotTypes.circle);
layer.set_markerScale(MarkerScales.screen); // or MarkerScales.world
layer.set_opacity(0.8); // 0-1 range
layer.set_enabled(true);
// Access layer later via LayerManager
const allLayers = wwtlib.LayerManager.get_allMaps();
```
--------------------------------
### Initialize WWT Engine with TypeScript
Source: https://github.com/worldwidetelescope/wwt-webgl-engine/blob/master/docs/engine/content/getting-started/bundled-typescript-model.md
Initializes the WWT engine using the WWTInstance class from '@wwtelescope/engine-helpers'. This code snippet demonstrates asynchronous initialization, waiting for the engine to be ready before proceeding. It requires the HTML element with the ID 'wwtcanvas' to be present.
```ts
import { WWTInstance } from '@wwtelescope/engine-helpers';
// asynchronous initialization:
const wwt = new WWTInstance({
elId: 'wwtcanvas',
startInternalRenderLoop: true,
});
await wwt.waitForReady();
```
--------------------------------
### Event Handling Callbacks with WWT Engine Script Interface
Source: https://context7.com/worldwidetelescope/wwt-webgl-engine/llms.txt
Shows how to register and remove callback functions for various WorldWideTelescope engine events using the `script_interface`. Events include engine ready, view arrival, collection loading, and tour readiness. Callbacks are removed using object equality.
```javascript
// Ready event - engine initialized
script_interface.add_ready(function() {
console.log("Engine ready");
});
// Arrived event - view navigation completed
script_interface.add_arrived(function() {
console.log("View arrived at destination");
const ra = script_interface.getRA(); // hours
const dec = script_interface.getDec(); // degrees
console.log(`Now at: RA ${ra}h, Dec ${dec}°`);
});
// Collection loaded event
script_interface.add_collectionLoaded(function() {
console.log("WTML collection loaded");
});
// Tour ready event
script_interface.add_tourReady(function() {
console.log("Tour loaded and ready");
});
// Remove callback (requires saved reference)
const callback = function() { console.log("arrived"); };
script_interface.add_arrived(callback);
script_interface.remove_arrived(callback); // Removes by object equality
```
--------------------------------
### Astronomical Coordinate Calculations in JavaScript
Source: https://context7.com/worldwidetelescope/wwt-webgl-engine/llms.txt
Demonstrates performing coordinate transformations and astronomical calculations using utility functions. This includes creating coordinate objects, converting between systems, and calculating rise/transit/set times.
```javascript
import {
Coordinates,
AstroCalc,
Constellations
} from '@wwtelescope/engine';
// Create coordinate object
const coords = Coordinates.fromRaDec(12.5, 45.2); // hours, degrees
console.log("RA:", coords.get_RA(), "Dec:", coords.get_dec());
const altAz = Coordinates.fromLatLng(42.36, -71.06); // lat, lng degrees
// Convert RA/Dec to 3D unit vector
const vec3d = Coordinates.raDecTo3d(12.5 * 15, 45.2); // needs degrees
// Convert equatorial to horizon coordinates
const location = Coordinates.fromLatLng(42.36, -71.06);
const utcTime = new Date();
const horizon = Coordinates.equitorialToHorizon(coords, location, utcTime);
console.log("Altitude:", horizon.get_alt(), "Azimuth:", horizon.get_az());
// Find constellation for position
const constAbbr = Constellations.containment.findConstellationForPoint(
12.5, // RA hours
45.2 // Dec degrees
);
const fullName = Constellations.fullNames[constAbbr];
console.log(`${constAbbr} - ${fullName}`);
// Calculate rise/set/transit times
const riseSet = AstroCalc.getRiseTransitSet(
2459000.5, // Julian date
42.36, // latitude degrees
-71.06, // longitude degrees
12.0, 45.0, // RA1, Dec1 (day before)
12.5, 45.2, // RA2, Dec2 (current day)
13.0, 45.4, // RA3, Dec3 (day after)
0 // type: 0=star
);
console.log("Rises:", riseSet.rise, "Transits:", riseSet.transit);
```
--------------------------------
### Load and Display Tiled FITS Data in WWT (JavaScript)
Source: https://github.com/worldwidetelescope/wwt-webgl-engine/blob/master/docs/engine/content/tutorial/fits-images/index.md
This JavaScript code snippet demonstrates how to load a collection of tiled FITS data using a WTML index file in the WWT web engine. It includes functions to handle collection loading, add image set layers with specific URLs and display modes, and configure image properties like scaling and color mapping after loading. It relies on the `wwtlib` library and `script_interface` for WWT interactions.
```javascript
// ... earlier code omitted ...
function on_ready() {
console.log("WWT is ready!");
wwt = wwtlib.WWTControl.singleton;
script_interface.add_collectionLoaded(on_wtml_loaded);
script_interface.loadImageCollection("http://data1.wwtassets.org/packages/2021/09_phat_fits/index.wtml");
}
function on_wtml_loaded() {
add_fits();
}
// ... intervening code omitted ...
function add_fits() {
script_interface.addImageSetLayer(
"http://data1.wwtassets.org/packages/2021/09_phat_fits/f475w/{1}/{3}/{3}_{2}.fits",
"preloaded", // different mode: identify imagery using WTML metadata
"PHAT F475W",
true, // automatically slew to the image center
on_fits_loaded
);
}
function on_fits_loaded(layer) {
// For technical reasons, with tiled FITS data we need to wait a frame
// before applying the scale parameters -- otherwise they'll be overridden
// by defaults specified in the WTML.
window.requestAnimationFrame(function () {
layer.setImageScalePhysical(wwtlib.ScaleTypes.linear, -0.1, 0.4);
});
layer.set_colorMapperName("viridis");
}
```
--------------------------------
### Load FITS Image Layer in JavaScript
Source: https://context7.com/worldwidetelescope/wwt-webgl-engine/llms.txt
Adds a single FITS file as an image layer with automatic download and parsing. It includes a callback function to access FITS-specific properties and modify layer settings.
```javascript
const layer = script_interface.addImageSetLayer(
"https://example.com/data/image.fits",
"auto", // mode: "auto", "fits", or imageset name
"FITS Layer", // layer name
true, // goto: move camera to image center
onFitsLoaded // callback when loaded
);
function onFitsLoaded(layer) {
console.log("FITS loaded");
// Access FITS-specific properties
const fitsImage = layer.getFitsImage();
console.log("Dimensions:", fitsImage.width, "x", fitsImage.height);
console.log("Axes:", fitsImage.numAxis);
// Compute histogram
const histogram = fitsImage.computeHistogram(256);
// Access FITS properties
const props = fitsImage.fitsProperties;
console.log("Min/Max:", props.minVal, props.maxVal);
console.log("Scale:", props.scaleType);
props.colorMapName = "viridis";
props.lowerCut = 0.1;
props.upperCut = 0.9;
}
// Change layer order in stack
script_interface.setImageSetLayerOrder(layer.id, 5);
```
--------------------------------
### Change Background Image - JavaScript
Source: https://github.com/worldwidetelescope/wwt-webgl-engine/blob/master/docs/engine/content/tutorial/change-bg/index.md
This JavaScript code demonstrates how to initialize the WWT control, set a callback for when the view arrives at its destination, and then change the background image to 'PanSTARRS'. It utilizes `wwtlib.WWTControlBuilder` and `wwtlib.WWTControl.singleton`.
```javascript
var script_interface, wwt;
function init_wwt() {
const builder = new wwtlib.WWTControlBuilder("wwtcanvas");
builder.startRenderLoop(true);
script_interface = builder.create();
script_interface.add_ready(on_ready);
}
function on_ready() {
console.log("WWT is ready!");
wwt = wwtlib.WWTControl.singleton;
script_interface.add_arrived(on_arrived);
wwt.gotoRADecZoom(17.75, -28.9, 10, false);
}
function on_arrived() {
wwt.setBackgroundImageByName("PanSTARRS");
}
window.addEventListener("load", init_wwt);
```
--------------------------------
### Load and Display Foreground Image with WWT API (JavaScript)
Source: https://github.com/worldwidetelescope/wwt-webgl-engine/blob/master/docs/engine/content/tutorial/add-image/index.md
This JavaScript code demonstrates how to initialize the WWT engine, load an image collection specified by a WTML URL, and set a particular image ('Rho Ophiuchi cloud complex') as the foreground. It includes callbacks for when the WWT engine is ready and when the collection is loaded. The code also sets the opacity and navigates to a specific celestial coordinate.
```javascript
var script_interface, wwt;
function init_wwt() {
const builder = new wwtlib.WWTControlBuilder("wwtcanvas");
builder.startRenderLoop(true);
script_interface = builder.create();
script_interface.add_ready(on_ready);
}
function on_ready() {
console.log("WWT is ready!");
wwt = wwtlib.WWTControl.singleton;
script_interface.add_collectionLoaded(on_wtml_loaded);
script_interface.loadImageCollection("https://data1.wwtassets.org/packages/2023/07_jwst/weic2316a/index.wtml");
}
function on_wtml_loaded() {
wwt.setForegroundImageByName("Rho Ophiuchi cloud complex");
script_interface.setForegroundOpacity(100);
script_interface.add_arrived(on_arrived);
wwt.gotoRADecZoom(16.442, -24.385, 1.06, false);
}
function on_arrived() {
wwt.setBackgroundImageByName("PanSTARRS");
}
window.addEventListener("load", init_wwt);
```
--------------------------------
### Astronomical Formatting and Conversions with @wwtelescope/astro
Source: https://context7.com/worldwidetelescope/wwt-webgl-engine/llms.txt
Demonstrates angle and coordinate conversions using the @wwtelescope/astro library. Includes unit conversions (degrees, radians, hours), formatting Right Ascension (RA) and Declination (Dec) into sexagesimal formats, formatting longitude, normalizing angles, and calculating great-circle distances. The library is imported directly.
```typescript
import {
D2R, R2D, H2R, R2H, D2H, H2D,
fmtHours, fmtDegLat, fmtDegLon,
distance, angnorm
} from '@wwtelescope/astro';
// Convert between units
const degrees = 45;
const radians = degrees * D2R;
const hours = degrees * D2H;
console.log(`${degrees}° = ${radians} rad = ${hours} hr`);
// Format RA as sexagesimal hours
const raRad = 3.7; // radians
const raStr = fmtHours(raRad, ":", ":", 2); // "14:12:34.56"
const raStrHms = fmtHours(raRad, "h", "m", 2, "s"); // "14h12m34.56s"
// Format declination as sexagesimal degrees
const decRad = 0.8; // radians
const decStr = fmtDegLat(decRad, ":", ":", 1); // "+45:50:23.4"
const decStrDms = fmtDegLat(decRad, "°", "'", 1, "\""); // "+45°50'23.4\""
// Format longitude (0-360)
const lonRad = 5.5;
const lonStr = fmtDegLon(lonRad, ":", ":", 0); // "315:12:45"
// Normalize angle to [0, 2π)
const normalized = angnorm(-0.5); // Returns positive equivalent
// Calculate great-circle distance
const dist = distance(
1.0, 0.5, // RA1, Dec1 in radians
1.1, 0.6 // RA2, Dec2 in radians
);
console.log("Angular separation:", dist * R2D, "degrees");
```
--------------------------------
### Add Polygon and Polyline Annotations
Source: https://context7.com/worldwidetelescope/wwt-webgl-engine/llms.txt
Shows how to create polygon and polyline annotations for overlaying geometric shapes. Polylines connect a series of points, while polygons can be filled or outlined. Customization options include color, opacity, and fill properties. Note that polygon points should be in counterclockwise order for correct rendering.
```javascript
// Create polyline connecting points
const polyline = script_interface.createPolyLine(false);
const points = [
[246.597, -24.350],
[246.679, -24.342],
[246.600, -24.413],
];
for (let i = 0; i < points.length; i++) {
polyline.addPoint(points[i][0], points[i][1]);
}
polyline.addPoint(points[0][0], points[0][1]); // Close the shape
polyline.set_lineColor("#ffffff");
polyline.set_opacity(0.5);
script_interface.addAnnotation(polyline);
// Create filled polygon (IMPORTANT: points must be counterclockwise)
const polygon = script_interface.createPolygon(true); // true = filled
polygon.addPoint(246.6, -24.35);
polygon.addPoint(246.65, -24.35);
polygon.addPoint(246.65, -24.40);
polygon.addPoint(246.6, -24.40);
polygon.set_fillColor("#ff0000");
polygon.set_fill(true);
polygon.set_opacity(0.3);
script_interface.addAnnotation(polygon);
```
--------------------------------
### Create and Configure a Spreadsheet Layer in JavaScript
Source: https://github.com/worldwidetelescope/wwt-webgl-engine/blob/master/docs/engine/content/tutorial/table-layer/index.md
This code demonstrates how to create a spreadsheet layer using the WWT LayerManager. It takes CSV data, sets column mappings for RA, Dec, size, and color, and configures the layer's appearance and type.
```javascript
// ... earlier code omitted ...
function on_wtml_loaded() {
wwt.setForegroundImageByName("Rho Ophiuchi cloud complex");
script_interface.setForegroundOpacity(100);
script_interface.add_arrived(on_arrived);
wwt.gotoRADecZoom(16.442, -24.385, 1.06, false);
add_spreadsheet();
}
// ... intervening code omitted ...
const csv_data = `\
ra,dec,size,color\
246.597,-24.350,1,#FF0000\
246.679,-24.342,2,#00FF00\
246.600,-24.413,3,#8888FF\
`;
function add_spreadsheet() {
const layer = wwtlib.LayerManager.createSpreadsheetLayer(
"Sky", // the reference frame for these data
"My Layer", // a name for the layer
csv_data // the actual data
);
layer.set_lngColumn(0); // the 0'th column stores longitudes (RA)
layer.set_latColumn(1); // the 1st column stores latitudes (Dec)
layer.set_sizeColumn(2); // etc.
layer.set_astronomical(true);
layer.set_plotType(wwtlib.PlotTypes.circle);
layer.set_markerScale(wwtlib.MarkerScales.screen);
}
// ... following code omitted ...
```
--------------------------------
### Configure Engine Settings in JavaScript
Source: https://context7.com/worldwidetelescope/wwt-webgl-engine/llms.txt
Provides code to access and modify global rendering settings for constellations, grids, and solar system elements. It covers enabling/disabling features and setting colors and locations.
```javascript
const settings = script_interface.settings;
// Constellation display
settings.set_showConstellationBoundries(true);
settings.set_showConstellationFigures(true);
settings.set_showConstellationLabels(true);
settings.set_showConstellationPictures(false);
settings.set_constellationFigureColor("#0088ff");
settings.set_constellationBoundryColor("#ffffff");
// Grid overlays
settings.set_showGrid(true); // Equatorial grid
settings.set_showEquatorialGridText(true);
settings.set_showAltAzGrid(false); // Altitude-azimuth grid
settings.set_showGalacticGrid(false);
settings.set_showEclipticGrid(false);
settings.set_showCrosshairs(true);
settings.set_crosshairsColor("#ffff00");
// Galactic and horizon modes
settings.set_galacticMode(false);
settings.set_localHorizonMode(false);
// Location for horizon mode
settings.set_locationLat(42.3601); // Boston latitude
settings.set_locationLng(-71.0589); // Boston longitude
settings.set_locationAltitude(10); // meters
// Solar system settings
settings.set_showSolarSystem(true);
settings.set_solarSystemScale(1.0);
settings.set_actualPlanetScale(false);
settings.set_solarSystemLighting(true);
settings.set_solarSystemOrbits(true);
settings.set_solarSystemMinorPlanets(false);
```
--------------------------------
### Activate Freestanding Mode with JavaScript Model
Source: https://github.com/worldwidetelescope/wwt-webgl-engine/blob/master/docs/engine/content/freestanding-mode/_index.md
This code snippet shows how to enable freestanding mode at the lowest level of abstraction using the hosted JavaScript model. It involves calling the 'freestandingMode()' method on the WWTControlBuilder class, exported from the '@wwtelescope/engine' package. This method requires the asset base URL as a parameter, similar to other integration methods.
```javascript
// Example usage with WWTControlBuilder
// Assuming 'WWTControlBuilder' is imported from '@wwtelescope/engine'
const wwtControlBuilder = new WWTControlBuilder();
wwtControlBuilder.freestandingMode("https://myassets.org/wwtengine");
// ... further configuration using wwtControlBuilder
```
--------------------------------
### Slew WWT View using Vue/Pinia Promise
Source: https://github.com/worldwidetelescope/wwt-webgl-engine/blob/master/docs/engine/content/tutorial/slew/index.md
This snippet shows how to slew the WWT view in a Vue/Pinia component model using `engineStore().gotoRADecZoom()`. Similar to the TypeScript approach, this method returns a promise, enabling easier management of asynchronous tasks and advanced visual effects.
```javascript
engineStore().gotoRADecZoom(/* ... arguments ... */);
```
--------------------------------
### Slew WWT View using TypeScript Promise
Source: https://github.com/worldwidetelescope/wwt-webgl-engine/blob/master/docs/engine/content/tutorial/slew/index.md
This code snippet demonstrates slewing the WWT view using the `WWTInstance.gotoRADecZoom()` method within a bundled TypeScript model. This method returns a promise, facilitating asynchronous operations and complex effect construction without relying heavily on callbacks.
```typescript
WWTInstance.gotoRADecZoom(/* ... arguments ... */);
```