question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to load an obj file?

See original GitHub issue

Hi folks! Thanks for maintaining this project!

I’m wondering if you have an example of loading an OBJ file and applying a texture? All I want to achieve is to being able to load a model, apply a texture and rotate it.

This is what I have so far:

import React, { Component } from 'react';
import { ScrollView, Text, StyleSheet } from 'react-native';
import Expo, { Asset, GLView } from 'expo';
import * as THREE from 'three';
import ExpoTHREE from 'expo-three';
global.THREE = THREE;
require('./OBJLoader');


console.disableYellowBox = true;


export default class ModelScreen extends Component {
  static navigationOptions = {
    title: '3D Model',
  };

  state = {
    loaded: false,
  }

  componentWillMount() {
    this.preloadAssetsAsync();
  }

  async preloadAssetsAsync() {
    await Promise.all([
      require('../assets/suzuki.obj'),
      require('../assets/MotociklySuzuki_LOW001.jpg'),
      require('../assets/male02.obj'),
      require('../assets/UV_Grid_Sm.jpg'),
    ].map((module) => Asset.fromModule(module).downloadAsync()));
    this.setState({ loaded: true });
  }

  onContextCreate = async (gl) => {
    const width = gl.drawingBufferWidth;
    const height = gl.drawingBufferHeight;
    console.log(width, height);
    gl.createRenderbuffer = () => {};
    gl.bindRenderbuffer = () => {};
    gl.renderbufferStorage  = () => {};
    gl.framebufferRenderbuffer  = () => {};

    const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 2000 );
		camera.position.z = 250;

    const scene = new THREE.Scene();
		const ambient = new THREE.AmbientLight( 0x101030 );
		const directionalLight = new THREE.DirectionalLight( 0xffeedd );
		directionalLight.position.set( 0, 0, 1 );
    scene.add(ambient);
		scene.add(directionalLight);

    // Texture
    const textureAsset = Asset.fromModule(require('../assets/MotociklySuzuki_LOW001.jpg'));
    const texture = new THREE.Texture();
    texture.image = {
      data: textureAsset,
      width: textureAsset.width,
      height: textureAsset.height,
    };;
		texture.needsUpdate = true;
    texture.isDataTexture = true;
    const material =  new THREE.MeshPhongMaterial({ map: texture });

    // Object
    const modelAsset = Asset.fromModule(require('../assets/suzuki.obj'));
    const loader = new THREE.OBJLoader();
    const model = loader.parse(
      await Expo.FileSystem.readAsStringAsync(modelAsset.localUri));

    model.traverse((child) => {
      if (child instanceof THREE.Mesh) {
        child.material = material;
      }
    });

    model.position.y = - 95;
		scene.add(model);


    const renderer = ExpoTHREE.createRenderer({ gl });
    renderer.setPixelRatio(2);
		renderer.setSize(width, height);


    const animate = () => {
      // camera.position.x += ( 7.25 - camera.position.x ) * .05;
			// camera.position.y += ( 62.75 - camera.position.y ) * .05;

			camera.lookAt( scene.position );

			renderer.render( scene, camera );
      gl.endFrameEXP();
      requestAnimationFrame(animate);
    };
    animate();
  };

  render() {
    return (
      <ScrollView style={styles.container}>
        <Text>This is your avatar:</Text>
        { this.state.loaded &&
          <GLView
            ref={(ref) => this.glView = ref}
            style={styles.glview}
            onContextCreate={this.onContextCreate}
          />
        }
        <Text>Something here!</Text>
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 15,
    backgroundColor: '#fff',
  },
  glview: {
    width: 350,
    height: 500
  },
});

I don’t get any errors, the app builds and runs ok, but I don’t see anything on the GLView, any pointers?

Thanks in advance!

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:1
  • Comments:24 (11 by maintainers)

github_iconTop GitHub Comments

3reactions
EvanBaconcommented, Jan 27, 2018
1reaction
TheCodeDestroyercommented, Oct 23, 2018

@EvanBacon I apologize for necro posting, just seemed like the proper issue to ask this. Calling loadAsync should work for FBX files as well(as long as they are added to assetExts)?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Tutorial 7 : Model loading - OpenGL-Tutorial.org
In this tutorial we will learn how to load 3D meshes from files. ... To keep this tutorial as simple as possible, we'll...
Read more >
Three.js Loading a .OBJ File
The .OBJ loader can be passed an object of name / material pairs. When it loads the .OBJ file, any material name it...
Read more >
WebGL Load Obj
OBJ files into it the best practice is to use a format that requires as little parsing as possible. .GLTF is a format...
Read more >
OpenGL Programming/Modern OpenGL Tutorial Load OBJ
Remove all elements from the scene (right click on them and press x) · In the top menu, click on Add > Mesh...
Read more >
Loading an .Obj model file | Apple Developer Forums
Maybe a problem with the file? I created a Torus in Blender and exported it as a triangulated obj file. Seemed to load...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found