Lorem ipsum dolor sit amet, consectetur adipiscing elit. Test link
Posts

GLBView in Android using Three.js

GLBView in Android


import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;

import org.jetbrains.annotations.NotNull;

import three.core.Object3D;
import three.core.Scene;
import three.loaders.GLTFLoader;
import three.materials.Material;
import three.materials.MeshBasicMaterial;
import three.objects.Mesh;
import three.renderers.WebGLRenderer;

public class GLBView extends GLSurfaceView {

    private WebGLRenderer renderer;
    private Scene scene;
    private Camera camera;
    private Mesh mesh;

    public GLBView(Context context) {
        super(context);
        init();
    }

    public GLBView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        setEGLContextClientVersion(2);

        renderer = new WebGLRenderer();
        setRenderer(renderer);

        GLTFLoader loader = new GLTFLoader();
        loader.load(getContext(), R.raw.my_model, new GLTFLoader.OnLoadCallback() {
            @Override
            public void onLoad(@NotNull Object3D object3D, @NotNull GLTFLoader.GLTF gltf) {
                // The model has loaded successfully. Now we can add it to the scene.
                scene = new Scene();
                scene.add(object3D);

                // Create a camera and position it to view the model.
                camera = new Camera();
                camera.position.set(0, 0, 5);

                // Create a material for the model.
                Material material = new MeshBasicMaterial();

                // Create a mesh using the loaded model and the material.
                mesh = new Mesh(object3D.geometry, material);
                scene.add(mesh);
            }

            @Override
            public void onError(Throwable throwable) {
                // Handle any errors that occur during loading.
            }
        });
    }

    @Override
    public void onDrawFrame(GL10 gl10) {
        super.onDrawFrame(gl10);

        if (scene != null && camera != null) {
            // Render the scene with the camera.
            renderer.render(scene, camera);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
    }

    @Override
    public void onPause() {
        super.onPause();
        setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    }

    // This method can be used to set the camera's position.
    public void setCameraPosition(float x, float y, float z) {
        if (camera != null) {
            camera.position.set(x, y, z);
        }
    }

    // This method can be used to set the material for the mesh.
    public void setMaterial(Material material) {
        if (mesh != null) {
            mesh.material = material;
        }
    }
}

        

Post a Comment