UNPKG

vtk-unstructured-viewer

Version:

A lightweight, standalone JavaScript library for parsing and processing VTK Unstructured Grid (.vtu) files in both browser and Node.js environments. Complete VTK-style API with zero dependencies for scientific visualization.

254 lines (187 loc) 9.75 kB
# VTK **Unstructured Viewer JavaScript** – VTU Parser & Unstructured Grid Toolkit > **Pure‑JS toolkit** for parsing, filtering, and exporting VTK Unstructured Grid (`.vtu`) data in Browser &Node.js. --- ## ✨ Features * **VTU parsing** via `vtkXMLUnstructuredGridReader` (ASCII, binary, appended) * **VTK‑style classes** for data processing: `vtkThreshold`, `vtkImplicitCut`, `vtkClipByScalar`, `vtkCellDataToPointData` * **Geometry extraction**: `extractBoundary(grid)` minimal polydata for WebGL * **Export**: `vtkUnstructuredGridToVTP` for one‑call round‑trip back to ParaView * **Debugger utilities**: `VTKDebugger.analyzeUnstructuredGrid(grid)`, `VTKDebugger.analyzePolyData(polydata)` * **Serialization**: `serializeUnstructuredGrid` / `deserializeUnstructuredGrid` and polydata equivalents * **Zero runtime deps** (\~12kB gzip core + helpers) --- ## 📦 Installation ```bash npm install vtk-unstructured-viewer ``` > Requires Node.js **14+** or any evergreen browser (Chrome60+, Firefox55+, Safari11+, Edge79+). --- ## 🚀 Quick Start ### 1. Parse a VTU from an ArrayBuffer ```js import vtkXMLUnstructuredGridReader from 'vtk-unstructured-viewer/vtkUnstructuredGridReader.js'; // 1. Instantiate reader const reader = new vtkXMLUnstructuredGridReader(); // 2. Load VTU file as ArrayBuffer const buffer = await fetch('/data/mesh.vtu').then(r => r.arrayBuffer()); // 3. Parse binary content await reader.parseAsArrayBuffer(buffer); // 4. Access the unstructured grid const grid = reader.grid; console.log('Points:', grid.getPoints().getData().length / grid.getPoints().getNumberOfComponents()); console.log('Cells :', grid.getConnectivity().length); ``` *Alternatively, you can fetch text and call* `await reader.parseAsText(xmlString)` *or* `await reader.setUrl(url)` *(fetch+parse).* --- ## 🛠️ API Reference ### vtkXMLUnstructuredGridReader | Method | Description | | -------------------------------------- | --------------------------------- | | `new vtkXMLUnstructuredGridReader()` | Create reader instance | | `await reader.parseAsArrayBuffer(buf)` | Parse binary/appended VTU content | | `await reader.parseAsText(text)` | Parse ASCII VTU XML | | `await reader.setUrl(url, opts)` | Fetch & parse VTU from URL | | `reader.grid` | Instance of `vtkUnstructuredGrid` | | `reader.setDataAccessHelper(helper)` | Use custom fetch helper | ### vtkUnstructuredGrid | Method | Description | | ---------------------------------------------------------------------- | -------------------------------------------------------------- | | `new vtkUnstructuredGrid()` | Create empty grid | | `setPoints({values,numberOfComponents,getData,getNumberOfComponents})` | Set vertex coordinates | | `getPoints()` | DataArray-like object (`getData()`, `getNumberOfComponents()`) | | `setConnectivity(Uint32Array)` | Cell‑to‑point connectivity | | `getConnectivity()` | Pair with `getOffsets()` and `getTypes()` | | `setOffsets(Uint32Array)` | Cell offsets | | `getOffsets()` | | | `setTypes(Uint8Array)` | VTK cell type codes | | `getTypes()` | | | `setFacesConnectivity(Uint32Array)` | Polyhedron face connectivity | | `getFacesConnectivity()` | | | `setFacesOffsets(Uint32Array)` | Face offsets | | `getFacesOffsets()` | | | `setPolyhedronToFaces(Int32Array)` | Map polyhedron→face IDs | | `setPolyhedronOffsets(Uint32Array)` | Polyhedron offsets | | `getBounds(): [xmin,xmax,ymin,ymax,zmin,zmax]` | Axis‑aligned bounding box | | `toVTPString()` | Serialize entire grid VTP XML string | ### Data Filters #### vtkThreshold ```js const f = new vtkThreshold(); f.setScalarArrayName('pressure'); f.setLowerThreshold(0.0); f.setUpperThreshold(1.0); f.setInvert(false); const filteredGrid = f.execute(grid); ``` #### vtkImplicitCut ```js const cutter = new vtkImplicitCut(); cutter.setScalarArrayName('velocity'); cutter.setCutFunction((x,y,z) => x+y-z); cutter.setCutValue(0.5); const slicePoly = cutter.execute(grid); ``` #### vtkClipByScalar ```js const clipper = new vtkClipByScalar(); clipper.setScalarArrayName('temperature'); clipper.setClipValue(300); clipper.setInsideOut(true); const isoPoly = clipper.execute(grid, { perfect: true }); ``` #### vtkCellDataToPointData ```js const c2p = new vtkCellDataToPointData(); c2p.setInputArrayName('velocity'); c2p.setOutputArrayName('velocity_pt'); const gridWithPoints = c2p.execute(grid); ``` ### Geometry & Export ```js import { extractBoundary } from 'vtk-unstructured-viewer/vtkGeometryFilter.js'; import vtkUnstructuredGridToVTP from 'vtk-unstructured-viewer/vtkUnstructuredGridToVTP.js'; // Extract exterior faces const polyData = extractBoundary(grid); // Serialize / save VTP const writer = new vtkUnstructuredGridToVTP(); writer.setExtractBoundaryCells(true); writer.setPassPointData(true); writer.setPassCellData(false); const surfacePoly = writer.execute(grid); const xml = writer.getVTPString(surfacePoly); writer.saveVTP('output.vtp'); ``` ### Debugging & Serialization ```js import VTKDebugger from 'vtk-unstructured-viewer/vtkDebugger.js'; import { serializeUnstructuredGrid, deserializeUnstructuredGrid } from 'vtk-unstructured-viewer/utils.js'; VTKDebugger.analyzeUnstructuredGrid(grid); VTKDebugger.analyzePolyData(polyData); const json = serializeUnstructuredGrid(grid); const restoredGrid = deserializeUnstructuredGrid(json); ``` --- ## 🔬 Example Workflow ```js async function processVtu(url) { const reader = new vtkXMLUnstructuredGridReader(); const buffer = await fetch(url).then(r => r.arrayBuffer()); await reader.parseAsArrayBuffer(buffer); let grid = reader.grid; // Threshold const thresh = new vtkThreshold(); thresh.setScalarArrayName('alpha.water'); thresh.setLowerThreshold(0.2); thresh.setUpperThreshold(1.0); grid = thresh.execute(grid); // Interpolate to points const c2p = new vtkCellDataToPointData(); c2p.setInputArrayName('alpha.water'); grid = c2p.execute(grid); // Clip const clipper = new vtkClipByScalar(); clipper.setScalarArrayName('alpha.water'); clipper.setClipValue(0.5); const surfacePoly = clipper.execute(grid); // Export const writer = new vtkUnstructuredGridToVTP(); writer.setPassPointData(true); writer.saveVTP('phase.vtp'); } ``` --- ## 📐 Supported VTK Cell Types Supports all standard and higher‑order VTK cell types: triangles, quads, tets, hexes, wedges, pyramids, voxels, polygons, polyhedra, and their quadratic/Lagrange variants. --- ## 🚀 Performance * **Streaming XML parser** 1M+ cells on mid‑range machines * **Typed arrays** zero‑copy math, GPU‑friendly layout * **32/64‑bit floats** precision choice per dataset --- ## 🤝 Compatibility | Environment | Requirement | | --------------- | ----------- | | Chrome | 60 | | Firefox | 55 | | Safari | 11 | | Edge (Chromium) | 79 | | Node.js | 14 (ESM) | --- ## 🛡️ Error Handling Example ```js try { const reader = new vtkXMLUnstructuredGridReader(); const buf = await fetch('bad.vtu').then(r => r.arrayBuffer()); await reader.parseAsArrayBuffer(buf); } catch (err) { console.error('VTU parse error:', err.message); } ``` --- ## © License & Support This package is **proprietary**. See [LICENSE](LICENSE). * Docs & issues [https://github.com/sridhar-mani/vtk-unstructured-viewer](https://github.com/sridhar-mani/vtk-unstructured-viewer) * Email support [support@example.com](mailto:support@example.com) --- ## 🔎 SEO Keywords VTK VTU unstructured grid vtk.js CFD FEA WebGL JavaScript mesh processing iso‑surface threshold filter geometry filter browser visualization Node.js