Leveraging observables for loading fbx files in three.js

Currently, I am utilizing three.js to exhibit some 3D-meshes within the browser. However, I am facing a challenge where I need to execute a specific function only after certain elements have finished loading. While some models just require importing, others necessitate additional operations to be performed on them. The standard loading code incorporates adding the object to the scene. Nevertheless, for a particular mesh, I need to include panels internally (where the panel is a submesh of the fbx) utilizing a duplicate function that I have crafted. It appears that declaring an observer at load start may be necessary, yet no event exists for this purpose, and the load function only returns void.

My query is: How can I append a function to the onLoad callback (via observable or any other method) where I can access the object, specifically the THREE:Group created in the load function.

Desired process: Ideally, I wish to establish an observable for each mesh being loaded, so that once the loading process is complete, I can execute a predefined function designated for that particular observable.

UPDATE: I have modified the code to align better with my goals. Although the current functionality is operational, it does not feel optimal.

load( url: string, onLoad: ( object: Group ) => void, onProgress?: ( event: ProgressEvent ) => void, onError?: ( event: ErrorEvent ) => void ) : void;
    loadFBX = (name: string, materials: TextureMapper[], onComplete, raycastable: boolean = true) => {
        MeshLoader.loader.load('../../assets/meshes/' + name + '.fbx', (object: THREE.Group) => {
            // irrelevant loader code...
            onComplete();
        });
    }

The desired behavior might resemble the following code snippet, where the object is captured to enable function execution. However, I am grappling with finding a feasible solution.

    this.loader.loadFBX('Loggia-panel', [
      { meshName: 'Loggia-frame', material: 'aluminium' },
      { meshName: 'Loggia-board', material: 'woodLight' }],
      () => {
        const mesh = this.scene.getObjectByName('Loggia-board');
        for (const object of MeshManipulator.array(mesh, 33, new Vector3(0, 0, 2))) {
          mesh.parent.add(object);
        }

        mesh.parent.position.set(-70, 0, -55);
        this.scene.add(MeshManipulator.duplicate(mesh.parent, new Vector3(70, 0, -55)));
      });

UPDATE: I am experimenting with an approach where I can return an observable, although I am unsure about assigning and returning it in this manner. My understanding of observables is still in progress. Nevertheless, I have realized that the observable can be returned, and the observer will manage an event when triggered by the onComplete function.

    loadFBX = (fileName: string): Observable<Object3D> => {
        MeshLoader.loader.load('../../assets/meshes/' + fileName + '.FBX', (object: THREE.Group) => {
            // set the object3D observable and notify the observer to trigger an event
        });
    }

Answer №1

function createLoaderObservable(fbxUrl: string): Observable<any> {
return new Observable((observer) => {
    loader.load(
      fbxUrl,
      (fbx) => {
        observer.next(fbx);
        observer.complete();
      },
      (event: ProgressEvent<EventTarget>) => {},
      (event) => observer.error(event),
    );
});}

Consider giving this approach a try. It's an example of transforming loader callbacks into an observable method.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporate a generic type into a React Functional Component

I have developed the following component: import { FC } from "react"; export interface Option<T> { value: T; label: string; } interface TestComponentProps { name: string; options: Option<string>[]; value: string; onChang ...

Is it possible to access the reference of a component in a different component?

Within my component called Box, I am returning a mesh object that belongs to the Object3d type. The challenge I face now is how to obtain a reference to this particular object in my Floor component. I attempted assigning another ref in my App component and ...

Angular2 Animation Transitions not triggering consistently for all events

Initially, take a look at this Plunkr I derived this from an example of page transition animation In essence, I am in need of setting custom states as I have varied animations for distinct actions within the site (e.g., initial load versus in-app page tr ...

Discovering the data type in Typescript through the use of Generics

In my data structure, I am using generics to build it. However, when I try to populate data, I encounter the need to convert simple formats into the correct types. The issue arises as the class is configured with Generics, making it difficult for me to det ...

Restricting the number of mat-chips in Angular and preventing the input from being disabled

Here is my recreation of a small portion of my project on StackBlitz. I am encountering 4 issues in this snippet: I aim to restrict the user to only one mat-chip. I attempted using [disabled]="selectedOption >=1", but I do not want to disable ...

Exploring the Comparison Between Angular RxJS Observables: Using takeUntil and unsubscribing via Subscription

When it comes to unsubscribing from observables in Angular components utilizing ngOnDestroy, there are multiple approaches available. Which of the following options is more preferable and why? Option 1: takeUntil The usage of RxJS takeUntil for unsubscri ...

Tips for accessing HttpParams within a WebApi Controller while utilizing the [HttpPut] method

I am attempting to update a specific resource by accessing it through the PUT method in an Angular service. RollBackBatchById(selectedBatchId: number) { const params = new HttpParams(); params.append('resourceId', resourceId.toString()); ...

Steps to retrieve the HTTP response from an ngxs action

Is it possible to receive an HTTP response in a component without storing the result? I want to use the response directly in the component without saving it. How can I achieve this? @Action(GetNovels, { cancelUncompleted: true }) getNovels(ctx: StateCont ...

Reusing Angular components multiple times within a single template - dynamically adding lists within them

I created this new component that includes a table (which is an array of key-value pairs) and a form below it. The form is designed to add new values to the table. Here is the Angular code I used: @Component({ selector: 'app-key-value-table', ...

Unable to sign out user from the server side using Next.js and Supabase

Is there a way to log out a user on the server side using Supabase as the authentication provider? I initially thought that simply calling this function would work: export const getServerSideProps: GetServerSideProps = withPageAuth({ redirectTo: &apos ...

React TypeScript - Module not found

Organizational structure: src - components - About.tsx In an attempt to optimize performance, I am experimenting with lazy loading: const About = React.lazy(() => import('components/About')); However, Visual Studio Code is flagging &ap ...

Update to the latest version of typescript, implemented a read-only array

After updating my project from Typescript 3.5 to 3.8, everything was running smoothly except for some operations on arrays. const usedROI = this.rois.find((roi) => roi.id === roiId); usedROI.position.height = position.height; ERROR TypeErro ...

Bringing in numerous modules within Angular

Currently, I am in the process of developing an application using Angular 4 and Angular Material. Each Material directive necessitates importing its module individually. For instance, when working on a navigation bar, the nav.module.ts file begins to take ...

How to Invoke a Function from Entry Component to Parent Component in Angular 7

My module includes the DragDropComponent in entry components, where the parent component consumes it like this: Parent Component: upload(data) { const modalRef = this.model.open(DragNDropComponent, { data: data, panelClass: 'defa ...

Unable to run unit tests on project using my custom React library

If any of you have encountered this issue or know how to solve it, please help me. I created an NPM package that can be found at https://www.npmjs.com/package/@applaudo/react-clapp-ui It installs and runs smoothly in other projects using create react app; ...

The Children Element in Next.js and React Context with TypeScript is lacking certain properties

Encountering a mysterious error while trying to implement React's Context API in Next.js with TypeScript. The issue seems to be revolving around wrapping the context provider around the _app.tsx file. Even though I am passing values to the Context Pr ...

Bringing in a script and invoking a function on a specific variable

As a newcomer to Typescript, I've been experimenting with some code I came across online to enhance the appearance of links on my website. <script src="https://wow.zamimg.com/widgets/power.js"></script> <script>var wowhead_tooltips ...

To determine if two constant objects share identical structures in TypeScript, you can compare their properties

There are two theme objects available: const lightMode = { background: "white", text: { primary: "dark", secondary: "darkgrey" }, } as const const darkMode = { background: "black", text: { prim ...

The ng build process remains active and does not exit while staying in the terminal

Since upgrading to Angular 15, I have encountered an issue with my build process. "build:project:prod": "ng build project --configuration prod --stats-json=true --single-bundle=true && npm run copyAssets" After the build comple ...

Styles applied in the child component will have a cascading effect on the entire webpage

My webpage is divided into two parts: child1 and child2. Page Hierarchy: Parent Child1 Child2 Here are the CSS styles included in the page: Child1 -> z-index: 1 Child2 -> z-index: 2 What I want to achieve is to add a backdrop to the entire ...