Is this code approach incorrect?

// useBabylon.jsx
// Its a  Context API 

 class BabylonInstanceEngine {
    reactCanvas = null;
    engine;
    scene;
    utilLayer;
    canvas;

    initialize(_canva) {
 
      if (!_canva) return;
      this.canvas = _canva;
      this.engine = new Engine(this.canvas);
      this.scene = new Scene(this.engine);
      this.run();

      if (this.scene.isReady()) {
        this.camera = new ArcRotateCamera(
          "camera1",
          (3 * Math.PI) / 2,
          -Math.PI / 2,
          20,
          Vector3.Zero(),
          this.scene
        );

        this.camera.setTarget(Vector3.Zero());

        this.camera.attachControl(this.canvas, true);

        const light = new HemisphericLight(
          "light",
          new Vector3(0, 1, 0),
          this.scene
        );

        light.intensity = 0.7;
        light.diffuse = new Color3(1, 0, 0);
        light.groundColor = new Color3(0, 0, 1);
        light.specular = new Color3(0, 1, 0);
    
        this.run();
      } else {
        console.log("Scene is not working");
      }
    }

    run() {
      if (this.engine && this.scene) {
        this.engine.runRenderLoop(() => {
          this.scene.render();
        });
      }
    }

    returnScene() {
      return this.scene;
    }

    debu() {
      try {
        this.scene.debugLayer.show({
          embedMode: true,
          gizmoCamera: this.camera,
        });
        console.log("Inspector Working " );
      } catch (error) {
        console.log("Inspector Error");
      }
    }


This button is for creating the ground mesh in the scene

// InstanceBox.jsx
// This is a component in my project i am importing this into App.jsx to display in side panel

import { useBabylon } from "@/babylon/useBabylon";

function InstanceBox() {

  const {babylonInstanceEngine,setAllMesh} = useBabylon();

return  <button
            className="border-2 border-[#2cead7] w-full sm:w-40 lg:w-52 p-2 sm:p-3 hover:bg-red-500 active:bg-red-700 transition duration-300"
            onClick={() => {
              const scene = babylonInstanceEngine.returnScene();
              const ground = MeshBuilder.CreateGround(
                "ground",
                { width: 6, height: 6 },
                scene
              );
              setAllMesh((prevMesh) => [...prevMesh, ground]);
            }}
          >
            Ground
          </button>
}
export default InstanceBox;

SceneBox.jsx is contain canva

//SceneBox.jsx

import { useEffect, useRef } from "react";
import { useBabylon } from "../babylon/useBabylon";

function SceneBox() {
  const { babylonInstanceEngine } = useBabylon();
  const canvasRef = useRef(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (canvas) {
      babylonInstanceEngine.initialize(canvas);
      babylonInstanceEngine.run();
      babylonInstanceEngine.resize();     
    }
  }, []);

  return (
    <div className="w-[72%] h-screen bg-black border-[#2cead7] border-2 ">
      <div className="flex flex-row justify-between px-10">
        <h1 className="font-medium text-white">SceneBox</h1>
      </div>
      <canvas ref={canvasRef} className="w-[100%] h-[600px]" />
    </div>
  );
}

export default SceneBox;

App.jsx

import InstanceBox from "./components/InstanceBox";
import SceneBox from "./components/SceneBox";

function App() {
  return (
    <>
      <div className="flex flex-row">
        <InstanceBox />
        <SceneBox />
      </div>
    </>
  );
}

export default App;

Hey everyone, I just want to know if this code approach is correct. I’ve written my entire code like this, and I’m facing some issues. Before I continue, I want to ensure that everything is okay so I don’t encounter any problems later.

You are using useBabylon() in both of your components. InstanceBox and SceneBox. This means that you’ll init the babylon.js engine twice. I can’t see a useBabylon.ts fle so I’m not sure.

You listed a useBabylon.jsx file which I’m not sure of. What’s the purpose of the file?

Also you are missing letters in some variables. Is it an intention?

I can’t tell you more from the code fragments you have provided. Do you have a repo to look at?

useBabylon is a context API designed to provide state management and share state across components without prop drilling.

Here is the full code of the useBabylon.jsx.

// useBabylon.jsx
// This is reastAPI code for initialize scene 

import { createContext, useContext, useState } from "react";
import {Engine,Scene,ArcRotateCamera,HemisphericLight,MeshBuilder,DebugLayer,} from "@babylonjs/core";

export const BabylonContext = createContext();

export const BabylonProvider = ({ children }) => {
  const [allMesh, setAllMesh] = useState([]);

 class BabylonInstanceEngine {
    reactCanvas = null;
    engine;
    scene;
    utilLayer;
    canvas;

    initialize(_canva) {
 
      if (!_canva) return;
      this.canvas = _canva;
      this.engine = new Engine(this.canvas);
      this.scene = new Scene(this.engine);
      this.run();

      if (this.scene.isReady()) {
        this.camera = new ArcRotateCamera(
          "camera1",
          (3 * Math.PI) / 2,
          -Math.PI / 2,
          20,
          Vector3.Zero(),
          this.scene
        );

        this.camera.setTarget(Vector3.Zero());

        this.camera.attachControl(this.canvas, true);

        const light = new HemisphericLight(
          "light",
          new Vector3(0, 1, 0),
          this.scene
        );

        light.intensity = 0.7;
        light.diffuse = new Color3(1, 0, 0);
        light.groundColor = new Color3(0, 0, 1);
        light.specular = new Color3(0, 1, 0);
    
        this.run();
      } else {
        console.log("Scene is not working");
      }
    }

    run() {
      if (this.engine && this.scene) {
        this.engine.runRenderLoop(() => {
          this.scene.render();
        });
      }
    }

    returnScene() {
      return this.scene;
    }

    debu() {
      try {
        this.scene.debugLayer.show({
          embedMode: true,
          gizmoCamera: this.camera,
        });
        console.log("Inspector Working " );
      } catch (error) {
        console.log("Inspector Error");
      }
    }
const babylonInstanceEngine = new BabylonInstanceEngine();

  return (
    <BabylonContext.Provider
      value={{babylonInstanceEngine,allMesh,setAllMesh}}
    >
      {children}
    </BabylonContext.Provider>
  );
};

export const useBabylon = () => {
  const babylonContextValue = useContext(BabylonContext);
  if (!babylonContextValue) {
    throw new Error("useBabylon use outside of provider");
  }

  return babylonContextValue;
};

Here is the repo but the code in it is so clustered i don’t think it will be easy to understand

Is this your repo? Or are we looking at a repo of someone else?

Do you want to know the code quality? Whether it is implemented with best practices kept in mind? Or what is the question? Sorry, I’m lost.

Yup code quality that i was asking and also about my current code have any issue that will gonna me cause problem now or later in my work.

Right now i am using this code and i am facing some problem. I am not able to understand where this error is and why it’s there . That’s why i am asking you to review my code.

Here is the hosted project link:

And follow same step as i am gonna tell you now to see what is the error:

  1. Click on the ground button in left side panel and you will see ground mesh appear in the scene
  2. Then click on the properties on right top side
  3. After that check the console
  4. When you click on the properties it’s tries to open the INSPECTOR but it throw some error instead.

This is not how love at first sight looks :crazy_face:

The inspector is not working because the code doesn’t import it correctly.
There are numerous flaws in this project. You should not use it…

Try @brianzinn 's GitHub - brianzinn/react-babylonjs: React for Babylon 3D engine starter project on github

:face_holding_back_tears::face_holding_back_tears: Hey Hey in my it’s working fine. Ahm let me push my latest code on github and then check it if the issue remain persisted or not

I HAVE PUSHED MY LATEST CODE

I’m sorry I don’t have time to create a code review. There is a lot to improve in this codebase.

What I can do is make some recommendations:

  1. Switch to Typescript.

  2. Get better at React: There are tons of videos about React on YT, but this is one of them I can recommend (and whole his channel)

  1. No no no! Pleaae find any resource explaining imports/exports…

Switch to HTMX. Just kidding :sweat_smile:

1 Like

this project for now is prototype and testing out stuff. And that import i have to write because of some error that kept on occurs.

Well But Thanks You for taking your time to look into my query.

1 Like