Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,21 @@ Blocks have input and output ports. Some might also have additional, optional in

Named by noun.

- `FbxInputBlock`
- Input: `string` which is a URL (HTTPS or data) that points to an FBX file.
- Output: output (BabylonScene)
- Resources: Babylon FBX loader
- Behavior: Uses the Babylon scene loader to load an FBX using NullEngine.
- `GltfInputBlock`
- Input: `string` which is a URL (HTTPS or data) that points to a glTF or GLB.
- Output: output (BabylonScene)
- Resources: Babylon glTF loader
- Behavior: Uses the Babylon scene loader to load a glTF using NullEngine.
- `StlInputBlock`
- Input: `string` which is a URL (HTTPS or data) that points to an STL file.
- Output: output (BabylonScene)
- Resources: Babylon STL loader
- Behavior: Uses the Babylon scene loader to load an STL using NullEngine.
- `DracoEncoderBlock`
- Input: none
- Output: output (DracoEncoder)
Expand Down
22 changes: 22 additions & 0 deletions src/blocks/fbxInputBlock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Block, type BlockOptions } from "../block/block";
import { defineBlock } from "../block/blockDefinition";
import { BabylonSceneType, UrlType } from "../block/connectionPointType";
import { NullEngineResource } from "../resources/nullEngineResource";
import { loadSingleFileSceneWithPluginAsync } from "../helpers/loadSceneWithPlugin";

const FbxInputBlockDefinition = /* @__PURE__ */ defineBlock({
type: "input.fbx",
input: UrlType,
output: BabylonSceneType,
resources: {
engine: NullEngineResource,
},
runAsync: (url, _config, { engine }) => loadSingleFileSceneWithPluginAsync(url, engine, ".fbx", () => import("@babylonjs/loaders/FBX/index.js")),
});

/** Loads an FBX URL into a Babylon.js scene. */
export class FbxInputBlock extends Block<typeof FbxInputBlockDefinition> {
public constructor(options?: BlockOptions<typeof FbxInputBlockDefinition>) {
super(FbxInputBlockDefinition, options);
}
}
33 changes: 3 additions & 30 deletions src/blocks/gltfInputBlock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Block, type BlockOptions } from "../block/block";
import { defineBlock } from "../block/blockDefinition";
import { BabylonSceneType, UrlType } from "../block/connectionPointType";
import { NullEngineResource } from "../resources/nullEngineResource";
import { fetchOrThrowAsync, isHttpUrl, loadSceneWithPluginAsync, toBase64 } from "../helpers/loadSceneWithPlugin";

const GltfInputBlockDefinition = /* @__PURE__ */ defineBlock({
type: "input.gltf",
Expand All @@ -11,10 +12,8 @@ const GltfInputBlockDefinition = /* @__PURE__ */ defineBlock({
engine: NullEngineResource,
},
runAsync: async (url, _config, { engine }) => {
const [{ LoadSceneAsync }] = await Promise.all([import("@babylonjs/core/Loading/sceneLoader.js"), import("@babylonjs/loaders/glTF/index.js")]);

if (!isHttpUrl(url)) {
return LoadSceneAsync(url, engine);
return loadSceneWithPluginAsync(url, engine, () => import("@babylonjs/loaders/glTF/index.js"));
}

const abortController = new AbortController();
Expand All @@ -23,7 +22,7 @@ const GltfInputBlockDefinition = /* @__PURE__ */ defineBlock({
const resolvedUrl = response.url || url;
const format = await readGltfResponseAsync(response, resolvedUrl);

return await LoadSceneAsync(format.source, engine, {
return await loadSceneWithPluginAsync(format.source, engine, () => import("@babylonjs/loaders/glTF/index.js"), {
rootUrl: new URL(".", resolvedUrl).href,
pluginExtension: format.extension,
name: new URL(resolvedUrl).pathname.split("/").pop() ?? "",
Expand All @@ -46,19 +45,6 @@ export class GltfInputBlock extends Block<typeof GltfInputBlockDefinition> {
}
}

function isHttpUrl(url: string): boolean {
const scheme = url.slice(0, 8).toLowerCase();
return scheme.startsWith("http://") || scheme.startsWith("https://");
}

async function fetchOrThrowAsync(url: string, signal: AbortSignal): Promise<Response> {
const response = await fetch(url, { signal });
if (!response.ok) {
throw new Error(`Failed to fetch "${url}": HTTP ${response.status} ${response.statusText}`.trim());
}
return response;
}

interface GltfResponse {
readonly extension: ".gltf" | ".glb";
readonly source: string | Uint8Array;
Expand Down Expand Up @@ -130,16 +116,3 @@ async function fetchAsDataUriAsync(url: string, signal: AbortSignal): Promise<st
const data = new Uint8Array(await response.arrayBuffer());
return `data:${contentType};base64,${toBase64(data)}`;
}

function toBase64(data: Uint8Array): string {
if (typeof Buffer === "function") {
return Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString("base64");
}

const chunkSize = 32_768;
let binary = "";
for (let offset = 0; offset < data.length; offset += chunkSize) {
binary += String.fromCharCode(...data.subarray(offset, offset + chunkSize));
}
return btoa(binary);
}
22 changes: 22 additions & 0 deletions src/blocks/stlInputBlock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Block, type BlockOptions } from "../block/block";
import { defineBlock } from "../block/blockDefinition";
import { BabylonSceneType, UrlType } from "../block/connectionPointType";
import { NullEngineResource } from "../resources/nullEngineResource";
import { loadSingleFileSceneWithPluginAsync } from "../helpers/loadSceneWithPlugin";

const StlInputBlockDefinition = /* @__PURE__ */ defineBlock({
type: "input.stl",
input: UrlType,
output: BabylonSceneType,
resources: {
engine: NullEngineResource,
},
runAsync: (url, _config, { engine }) => loadSingleFileSceneWithPluginAsync(url, engine, ".stl", () => import("@babylonjs/loaders/STL/index.js")),
});

/** Loads an STL URL into a Babylon.js scene. */
export class StlInputBlock extends Block<typeof StlInputBlockDefinition> {
public constructor(options?: BlockOptions<typeof StlInputBlockDefinition>) {
super(StlInputBlockDefinition, options);
}
}
57 changes: 57 additions & 0 deletions src/helpers/loadSceneWithPlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import type { AbstractEngine } from "@babylonjs/core/Engines/abstractEngine.js";
import type { LoadOptions } from "@babylonjs/core/Loading/sceneLoader.js";
import type { Scene } from "@babylonjs/core/scene.js";

type SceneSource = string | ArrayBufferView;

export async function loadSceneWithPluginAsync(source: SceneSource, engine: AbstractEngine, loadPluginAsync: () => Promise<unknown>, options?: LoadOptions): Promise<Scene> {
const [{ LoadSceneAsync }] = await Promise.all([import("@babylonjs/core/Loading/sceneLoader.js"), loadPluginAsync()]);
return LoadSceneAsync(source, engine, options);
}

export async function loadSingleFileSceneWithPluginAsync(url: string, engine: AbstractEngine, pluginExtension: string, loadPluginAsync: () => Promise<unknown>): Promise<Scene> {
if (!isHttpUrl(url)) {
return loadSceneWithPluginAsync(url, engine, loadPluginAsync, { pluginExtension });
}

const abortController = new AbortController();
try {
const response = await fetchOrThrowAsync(url, abortController.signal);
const resolvedUrl = response.url || url;
const contentType = response.headers.get("content-type")?.split(";", 1)[0] || "application/octet-stream";
const source = `data:${contentType};base64,${toBase64(new Uint8Array(await response.arrayBuffer()))}`;
return await loadSceneWithPluginAsync(source, engine, loadPluginAsync, {
rootUrl: new URL(".", resolvedUrl).href,
pluginExtension,
name: new URL(resolvedUrl).pathname.split("/").pop() ?? "",
});
} finally {
abortController.abort();
}
}

export function isHttpUrl(url: string): boolean {
const scheme = url.slice(0, 8).toLowerCase();
return scheme.startsWith("http://") || scheme.startsWith("https://");
}

export async function fetchOrThrowAsync(url: string, signal: AbortSignal): Promise<Response> {
const response = await fetch(url, { signal });
if (!response.ok) {
throw new Error(`Failed to fetch "${url}": HTTP ${response.status} ${response.statusText}`.trim());
}
return response;
}

export function toBase64(data: Uint8Array): string {
if (typeof Buffer === "function") {
return Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString("base64");
}

const chunkSize = 32_768;
let binary = "";
for (let offset = 0; offset < data.length; offset += chunkSize) {
binary += String.fromCharCode(...data.subarray(offset, offset + chunkSize));
}
return btoa(binary);
}
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
export { CompressTexturesBlock } from "./blocks/compressTexturesBlock";
export { DracoEncoderBlock } from "./blocks/dracoEncoderBlock";
export { FbxInputBlock } from "./blocks/fbxInputBlock";
export { GltfInputBlock } from "./blocks/gltfInputBlock";
export { GltfOutputBlock, type GltfOutputBlockOptions } from "./blocks/gltfOutputBlock";
export { StlInputBlock } from "./blocks/stlInputBlock";
export { NodeAsset } from "./nodeAsset/nodeAsset";
export { NodeAssetContext } from "./nodeAsset/nodeAssetContext";
41 changes: 41 additions & 0 deletions tests/helpers/fbx.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
export function generateFbxDataUri(): string {
return `data:application/octet-stream;base64,${btoa(generateFbxData())}`;
}

export function generateFbxData(): string {
return `; FBX 7.4.0 project file
GlobalSettings: {
Version: 1000
Properties70: {
P: "UpAxis", "int", "Integer", "",1
P: "UpAxisSign", "int", "Integer", "",1
P: "FrontAxis", "int", "Integer", "",2
P: "FrontAxisSign", "int", "Integer", "",1
P: "CoordAxis", "int", "Integer", "",0
P: "CoordAxisSign", "int", "Integer", "",1
}
}
Objects: {
Geometry: 1, "Geometry::Triangle", "Mesh" {
Vertices: *9 {
a: 0,0,0,1,0,0,0,1,0
}
PolygonVertexIndex: *3 {
a: 0,1,-3
}
LayerElementNormal: 0 {
MappingInformationType: "ByControlPoint"
ReferenceInformationType: "Direct"
Normals: *9 {
a: 0,0,1,0,0,1,0,0,1
}
}
}
Model: 2, "Model::Triangle", "Mesh" {
}
}
Connections: {
C: "OO", 1, 2
C: "OO", 2, 0
}`;
}
15 changes: 15 additions & 0 deletions tests/helpers/stl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export function generateStlDataUri(): string {
return `data:application/octet-stream;base64,${btoa(generateStlData())}`;
}

export function generateStlData(): string {
return `solid triangle
facet normal 0 0 1
outer loop
vertex 0 0 0
vertex 1 0 0
vertex 0 1 0
endloop
endfacet
endsolid triangle`;
}
48 changes: 48 additions & 0 deletions tests/integration/fbxInput.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { describe, expect, it, vi } from "vitest";

import { FbxInputBlock, GltfOutputBlock, NodeAsset, NodeAssetContext } from "../../src/index";
import { generateFbxData, generateFbxDataUri } from "../helpers/fbx";
import { parseGlbAsync } from "../helpers/glb";

describe("FBX input", () => {
it("loads generated FBX data without relying on a URL extension", async () => {
const { json } = await parseGlbAsync(await roundTripAsync(new FbxInputBlock({ input: generateFbxDataUri() })));

expect(json.meshes).toHaveLength(1);
expect(json.meshes?.[0]?.primitives).toHaveLength(1);
});

it("loads an extensionless HTTP asset", async () => {
vi.stubGlobal(
"fetch",
vi.fn(() => Promise.resolve(new Response(generateFbxData())))
);

try {
const { json } = await parseGlbAsync(await roundTripAsync(new FbxInputBlock({ input: "https://example.com/model" })));

expect(json.meshes).toHaveLength(1);
} finally {
vi.unstubAllGlobals();
}
});

it("accepts input through an execution context", async () => {
const source = new FbxInputBlock();
const destination = new GltfOutputBlock();
source.output.connectTo(destination.input);
const asset = new NodeAsset({ name: "context-fbx-to-glb", outputBlock: destination });
const context = new NodeAssetContext(asset);
context.setInput(source, generateFbxDataUri());

const { json } = await parseGlbAsync(await asset.executeAsync(context));

expect(json.meshes).toHaveLength(1);
});
});

async function roundTripAsync(source: FbxInputBlock): Promise<File> {
const destination = new GltfOutputBlock();
source.output.connectTo(destination.input);
return new NodeAsset({ name: "fbx-roundtrip", outputBlock: destination }).executeAsync();
}
48 changes: 48 additions & 0 deletions tests/integration/stlInput.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { describe, expect, it, vi } from "vitest";

import { GltfOutputBlock, NodeAsset, NodeAssetContext, StlInputBlock } from "../../src/index";
import { parseGlbAsync } from "../helpers/glb";
import { generateStlData, generateStlDataUri } from "../helpers/stl";

describe("STL input", () => {
it("loads generated STL data without relying on a URL extension", async () => {
const { json } = await parseGlbAsync(await roundTripAsync(new StlInputBlock({ input: generateStlDataUri() })));

expect(json.meshes).toHaveLength(1);
expect(json.meshes?.[0]?.primitives).toHaveLength(1);
});

it("loads an extensionless HTTP asset", async () => {
vi.stubGlobal(
"fetch",
vi.fn(() => Promise.resolve(new Response(generateStlData())))
);

try {
const { json } = await parseGlbAsync(await roundTripAsync(new StlInputBlock({ input: "https://example.com/model" })));

expect(json.meshes).toHaveLength(1);
} finally {
vi.unstubAllGlobals();
}
});

it("accepts input through an execution context", async () => {
const source = new StlInputBlock();
const destination = new GltfOutputBlock();
source.output.connectTo(destination.input);
const asset = new NodeAsset({ name: "context-stl-to-glb", outputBlock: destination });
const context = new NodeAssetContext(asset);
context.setInput(source, generateStlDataUri());

const { json } = await parseGlbAsync(await asset.executeAsync(context));

expect(json.meshes).toHaveLength(1);
});
});

async function roundTripAsync(source: StlInputBlock): Promise<File> {
const destination = new GltfOutputBlock();
source.output.connectTo(destination.input);
return new NodeAsset({ name: "stl-roundtrip", outputBlock: destination }).executeAsync();
}
Loading