Giter Club home page Giter Club logo

webgl-obj-loader's Introduction

webgl-obj-loader

Build Status

A simple script to help bring OBJ models to your WebGL world. I originally wrote this script for my CS Graphics class so that we didn't have to only have cubes and spheres for models in order to learn WebGL. At the time, the only sort of model loader for WebGL was Mr. Doob's ThreeJS. And in order to use the loaders you had to use the entire framework (or do some very serious hacking and duct-taping in order get the model information). My main focus in creating this loader was to easily allow importing models without having to have special knowledge of a 3D graphics program (like Blender) while keeping it low-level enough so that the focus was on learning WebGL rather than learning some framework.

Mesh(objStr)

The main Mesh class. The constructor will parse through the OBJ file data and collect the vertex, vertex normal, texture, and face information. This information can then be used later on when creating your VBOs. Look at the initMeshBuffers source for an example of how to use the newly created Mesh

Attributes:

  • vertices: an array containing the vertex values that correspond to each unique face index. The array is flat in that each vertex's component is an element of the array. For example: with verts = [1, -1, 1, ...], verts[0] is x, verts[1] is y, and verts[2] is z. Continuing on, verts[3] would be the beginning of the next vertex: its x component. This is in preparation for using gl.ELEMENT_ARRAY_BUFFER for the gl.drawElements call.
    • Note that the vertices attribute is the Geometric Vertex and denotes the position in 3D space.
  • vertexNormals: an array containing the vertex normals that correspond to each unique face index. It is flat, just like vertices.
  • textures: an array containing the s and t (or u and v) coordinates for this mesh's texture. It is flat just like vertices except it goes by groups of 2 instead of 3.
  • indices: an array containing the indicies to be used in conjunction with the above three arrays in order to draw the triangles that make up faces. See below for more information on element indices.

Element Index

The indices attribute is a list of numbers that represent the indices of the above vertex groups. For example, the Nth index, mesh.indices[N], may contain the value 38. This points to the 39th (zero indexed) element. For Mesh classes, this points to a unique group vertex, normal, and texture values. However, the vertices, normals, and textures attributes are flattened lists of each attributes' components, e.g. the vertices list is a repeating pattern of [X, Y, Z, X, Y, Z, ...], so you cannot directly use the element index in order to look up the corresponding vertex position. That is to say mesh.vertices[38] does not point to the 39th vertex's X component. The following diagram illustrates how the element index under the hood:

obj loader element index description

After describing the attribute data to WebGL via vertexAttribPointer(), what was once separate array elements in JS is now just one block of data on the graphics card. That block of data in its entirety is considered a single element.

To use the element index in order to index one of the attribute arrays in JS, you will have to mimic this "chunking" of data by taking into account the number of components in an attribute (e.g. a vertex has 3 components; x, y, and z). Have a look at the following code snippet to see how to correctly use the element index in order to access an attribute for that index:

// there are 3 components for a geometric vertex: X, Y, and Z
const NUM_COMPONENTS_FOR_VERTS = 3;
elementIdx = mesh.indices[SOME_IDX]; // e.g. 38
// in order to get the X component of the vertex component of element "38"
elementVertX = mesh.vertices[(elementIdx * NUM_COMPONENTS_FOR_VERTS) + 0]
// in order to get the Y component of the vertex component of element "38"
elementVertY = mesh.vertices[(elementIdx * NUM_COMPONENTS_FOR_VERTS) + 1]
// in order to get the Z component of the vertex component of element "38"
elementVertZ = mesh.vertices[(elementIdx * NUM_COMPONENTS_FOR_VERTS) + 2]

Params:

  • objStr a string representation of an OBJ file with newlines preserved.

A simple example:

In your index.html file:

<html>
    <head>
        <script type="text/plain" id="my_cube.obj">
            ####
            #
            #	OBJ File Generated by Blender
            #
            ####
            o my_cube.obj
            v 1 1 1
            v -1 1 1
            v -1 -1 1
            v 1 -1 1
            v 1 1 -1
            v -1 1 -1
            v -1 -1 -1
            v 1 -1 -1
            vn 0 0 1
            vn 1 0 0
            vn -1 0 0
            vn 0 0 -1
            vn 0 1 0
            vn 0 -1 0
            f 1//1 2//1 3//1
            f 3//1 4//1 1//1
            f 5//2 1//2 4//2
            f 4//2 8//2 5//2
            f 2//3 6//3 7//3
            f 7//3 3//3 2//3
            f 7//4 8//4 5//4
            f 5//4 6//4 7//4
            f 5//5 6//5 2//5
            f 2//5 1//5 5//5
            f 8//6 4//6 3//6
            f 3//6 7//6 8//6
        </script>
    </head>
</html>

And in your app.js:

var gl = canvas.getContext('webgl');
var objStr = document.getElementById('my_cube.obj').innerHTML;
var mesh = new OBJ.Mesh(objStr);

// use the included helper function to initialize the VBOs
// if you don't want to use this function, have a look at its
// source to see how to use the Mesh instance.
OBJ.initMeshBuffers(gl, mesh);
// have a look at the initMeshBuffers docs for an exmample of how to
// render the model at this point

Some helper functions

downloadMeshes(nameAndURLs, completionCallback, meshes)

Takes in a JS Object of mesh_name, '/url/to/OBJ/file' pairs and a callback function. Each OBJ file will be ajaxed in and automatically converted to an OBJ.Mesh. When all files have successfully downloaded the callback function provided will be called and passed in an object containing the newly created meshes.

Note: In order to use this function as a way to download meshes, a webserver of some sort must be used.

Params:

  • nameAndURLs: an object where the key is the name of the mesh and the value is the url to that mesh's OBJ file

  • completionCallback: should contain a function that will take one parameter: an object array where the keys will be the unique object name and the value will be a Mesh object

  • meshes: In case other meshes are loaded separately or if a previously declared variable is desired to be used, pass in a (possibly empty) json object of the pattern: { 'mesh_name': OBJ.Mesh }

A simple example:

var app = {};
    app.meshes = {};

var gl = document.getElementById('mycanvas').getContext('webgl');

function webGLStart(meshes){
  app.meshes = meshes;
  // initialize the VBOs
  OBJ.initMeshBuffers(gl, app.meshes.suzanne);
  OBJ.initMeshBuffers(gl, app.meshes.sphere);
  ... other cool stuff ...
  // refer to the initMeshBuffers docs for an example of
  // how to render the mesh to the screen after calling
  // initMeshBuffers
}

window.onload = function(){
  OBJ.downloadMeshes({
    'suzanne': 'models/suzanne.obj', // located in the models folder on the server
    'sphere': 'models/sphere.obj'
  }, webGLStart);
}

initMeshBuffers(gl, mesh)

Takes in the WebGL context and a Mesh, then creates and appends the buffers to the mesh object as attributes.

Params:

  • gl WebGLRenderingContext the canvas.getContext('webgl') context instance

  • mesh Mesh a single OBJ.Mesh instance

The newly created mesh attributes are:

Attrbute Description
normalBuffer contains the model's Vertex Normals
normalBuffer.itemSize set to 3 items
normalBuffer.numItems the total number of vertex normals
textureBuffer contains the model's Texture Coordinates
textureBuffer.itemSize set to 2 items (or 3 if W texture coord is enabled)
textureBuffer.numItems the number of texture coordinates
vertexBuffer contains the model's Vertex Position Coordinates (does not include w)
vertexBuffer.itemSize set to 3 items
vertexBuffer.numItems the total number of vertices
indexBuffer contains the indices of the faces
indexBuffer.itemSize is set to 1
indexBuffer.numItems the total number of indices

A simple example (a lot of steps are missing, so don't copy and paste):

var gl   = canvas.getContext('webgl'),
var mesh = new OBJ.Mesh(obj_file_data);
// compile the shaders and create a shader program
var shaderProgram = gl.createProgram();
// compilation stuff here
...
// make sure you have vertex, vertex normal, and texture coordinate
// attributes located in your shaders and attach them to the shader program
shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);

shaderProgram.vertexNormalAttribute = gl.getAttribLocation(shaderProgram, "aVertexNormal");
gl.enableVertexAttribArray(shaderProgram.vertexNormalAttribute);

shaderProgram.textureCoordAttribute = gl.getAttribLocation(shaderProgram, "aTextureCoord");
gl.enableVertexAttribArray(shaderProgram.textureCoordAttribute);

// create and initialize the vertex, vertex normal, and texture coordinate buffers
// and save on to the mesh object
OBJ.initMeshBuffers(gl, mesh);

// now to render the mesh
gl.bindBuffer(gl.ARRAY_BUFFER, mesh.vertexBuffer);
gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, mesh.vertexBuffer.itemSize, gl.FLOAT, false, 0, 0);

// it's possible that the mesh doesn't contain
// any texture coordinates (e.g. suzanne.obj in the development branch).
// in this case, the texture vertexAttribArray will need to be disabled
// before the call to drawElements
if(!mesh.textures.length){
  gl.disableVertexAttribArray(shaderProgram.textureCoordAttribute);
}
else{
  // if the texture vertexAttribArray has been previously
  // disabled, then it needs to be re-enabled
  gl.enableVertexAttribArray(shaderProgram.textureCoordAttribute);
  gl.bindBuffer(gl.ARRAY_BUFFER, mesh.textureBuffer);
  gl.vertexAttribPointer(shaderProgram.textureCoordAttribute, mesh.textureBuffer.itemSize, gl.FLOAT, false, 0, 0);
}

gl.bindBuffer(gl.ARRAY_BUFFER, mesh.normalBuffer);
gl.vertexAttribPointer(shaderProgram.vertexNormalAttribute, mesh.normalBuffer.itemSize, gl.FLOAT, false, 0, 0);

gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, model.mesh.indexBuffer);
gl.drawElements(gl.TRIANGLES, model.mesh.indexBuffer.numItems, gl.UNSIGNED_SHORT, 0);

deleteMeshBuffers(gl, mesh)

Deletes the mesh's buffers, which you would do when deleting an object from a scene so that you don't leak video memory. Excessive buffer creation and deletion leads to video memory fragmentation. Beware.

Node.js

npm install webgl-obj-loader

var fs = require('fs');
var OBJ = require('webgl-obj-loader');

var meshPath = './development/models/sphere.obj';
var opt = { encoding: 'utf8' };

fs.readFile(meshPath, opt, function (err, data){
  if (err) return console.error(err);
  var mesh = new OBJ.Mesh(data);
});

Webpack Support

Thanks to mentos1386 for the webpack-obj-loader!

Demo

http://frenchtoast747.github.com/webgl-obj-loader/ This demo is the same thing inside of the gh-pages branch. Do a git checkout gh-pages inside of the webgl-obj-loader directory to see how the OBJ loader is used in a project.

ChangeLog

2.0.3

  • Add simple support for N-Gons (thanks qtip!)
    • This uses a very elementary algorithm to triangulate N-gons, but should still produce a full mesh.
      • Any help to create a better triangulation algorithm would be greatly appreciated! Please create a pull request.

2.0.0

  • Updated to TypeScript
  • Breaking change: the Mesh option indicesPerMaterial has been removed in favor of always providing the indices per material.
    • Instead of mesh.indices holding an array of arrays of numbers, mesh.indicesPerMaterial will now hold the indices where the top level array index is the index of the material and the inner arrays are the indices for that material.
  • Breaking change: the Layout class has changed from directly applying attributes to the Layout instance to creating an attributeMap

1.1.0

  • Add Support for separating mesh indices by materials.
  • Add calculation for tangents and bitangents
  • Add runtime OBJ library version.

1.0.1

  • Add support for 3D texture coordinates. By default the third texture coordinate, w, is truncated. Support can be enabled by passing enableWTextureCoord: true in the options parameter of the Mesh class.

1.0.0

  • Modularized all of the source files into ES6 modules.
    • The Mesh, MaterialLibrary, and Material classes are now actual ES6 classes.
  • Added tests for each of the classes
    • Found a bug in the Mesh class. Vertex normals would not appear if the face declaration used the shorthand variant; e.g. f 1/1
  • Provided Initial MTL file parsing support.
    • Still requires Documentation. For now, have a look at the tests in the test directory for examples of use.
    • Use the new downloadModels() function in order to download the OBJ meshes complete with their MTL files attached. If the MTL files reference images, by default, those images will be downloaded and attached.
  • The downloading functions now use the new fetch() API which utilizes promises.

0.1.1

  • Support for NodeJS.

0.1.0

  • Dropped jQuery dependency: downloadMeshes no longer requires jQuery to ajax in the OBJ files.
  • changed namespace to something a little shorter: OBJ
  • Updated documentation

0.0.3

  • Initial support for Quad models

0.0.2

  • Texture Coordinates are now loaded into mesh.textures

0.0.1

  • Vertex Normals are now loaded into mesh.vertexNormals

Bitdeli Badge

webgl-obj-loader's People

Contributors

ap1 avatar bitdeli-chef avatar dependabot[bot] avatar frenchtoast747 avatar novalain avatar qtip avatar sabinewren avatar shaneallgeier avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

webgl-obj-loader's Issues

normalize vertices

I'm not sure if this is a best practice or not. It's frustrating when meshes' vertices are values greater than +/- 1. A friend described to me a trick where you fit a model to clip space by iterating over each vertex, keeping track of max & min x, y, & z values, then pass over them again multiplying them to fit within exactly the 2x2x2 clipping cube. This would make meshes that appear too small be a more reasonable size, and meshes that are too large fit within the standard clipping cube. You could always transform the vertices later with a model matrix. One issue is non uniform scaling. We wouldn't want to non-uniformly scale each axis, or that would mess up the dimensions of the model. Instead, we'd want to find out which axis was closest (or farthest, I guess) to -1:1 and just uniformly scale each axis. It might be a better idea to do this offline once for the obj, rather than every time at runtime. Either a command line tool, or an optional argument at runtime would be helpful.

Clarify attribute indexing documentation

The current documentation around the indicesPerMaterial attribute is very confusing as many different terms are used interchangeably.

The Readme states that the indices can be used to index into the attribute component arrays such like

submeshIndices = indicesPerMaterial[0];
attributeIndex = submeshIndices[0];
vertices[attributeIndex];
normals[attributeIndex];
textures[attributeIndex];

However the attribute arrays themselves are flattened so that each element stores an attribute component rather than a vertex full attribute. Therefore to store information for a full vertex one must index the attribute arrays once for each component of the vertex attribute (so 3 times for a position and 2 times for a texture coordinate).
But it isn't clear which is the correct method of doing this either:

attributeIndex0 = submeshIndices[0];
attributeIndex1 = submeshIndices[1];
attributeIndex2 = submeshIndices[2];
Vector3 actualVertexPosition;
actualVertexPosition.x = vertices[attributeIndex0];
actualVertexPosition.y = vertices[attributeIndex1];
actualVertexPosition.z = vertices[attributeIndex2];

or

attributeIndex = submeshIndices[0];
Vector3 actualVertexPosition;
actualVertexPosition.x = vertices[attributeIndex];
actualVertexPosition.y = vertices[attributeIndex + 1];
actualVertexPosition.z = vertices[attributeIndex + 2];

I'm guessing the latter otherwise it wouldn't work with attributes of different sizes, but that's just my guess. The documentation should be clearer to specify which is correct.

What also doesn't help is the naming of the vertices attribute which is in fact vertex positions and so should be named positions, but maybe I should make a separate issue for that?

Does this support colors

Since mtl format is not supported I want to set a fixed color to my mesh. Would it work to create a new program with color shaders enable the attribute?

'window' is not defined in node.js

I'm using .mjs in my node.js project and I import the loader with:

import OBJ from "webgl-obj-loader";

But when importing I get the error that window is undefined in webgl-obj-loader.min.js. I fixed it by replacing window with: typeof window !== "undefined" ? window : global.

I'm not sure if that is the right fix to use this project in node, I can create a PR if it's fine

Multiple textures

How do I handle a model with multiple textures? Is there a way to know what texture-coordinates a specific texture should have on the model?

For example, a horse, where the tail is a seperate texture, or a man with a hat

vertices, normals, textures all strings

even with 78d9d17 I still see strings in the browser. Usually, this isn't an issue, but if you try and transform them you'll run into funky bugs. I need to sit and run a bisection to see where I broke this, figure out why it's different in node.js, then write a unit test to catch this.

Separate index buffers per-material

Sometimes it's not desirable to pass all the material information to a single shader, but rather switch shaders between materials.

One solution would be to have the materials hold separate index buffers to accomplish this.

Texture bug

line 169 of mesh.js
should be
coords = elements.slice(0, 2);
instead of
coords = elements.slice(0, 1);

Layout.SPECULAR_EXPONENT Attribute size

in webgl-obj-loader.js I had to change the line
Layout.DISSOLVE = new Attribute("dissolve", 3, TYPES.FLOAT);
to
Layout.DISSOLVE = new Attribute("dissolve", 1, TYPES.FLOAT);
for my materials to parse correctly

Webpack Loader

Hey, awesome job on loader!

I'm working on a project that is using webpack. I couldn't find any webpack loaders for obj files, so i made my own which just calls this library new Mesh(source). Just want to leave this here for people that are using webpack.

webpack-obj-loader

error

  1. download the same image mutiple times, you can get all images paths and set in the hashmap, then,download in queue;
  2. error check filename( see below)

[node.js] bunch of strings

looks like the arrays are a bunch of strings in node.js.
vertices, vertexNormals, textures are strings, while indices are numbers.

development example dosen't work well.

Thanks for your good works,I have cloned this project and attempted to run the deveplement examples,but it warns with 'mesh.js:534 Material "Gold" not found in mesh. Did you forget to call addMaterialLibrary(...)?'.
I have no idea whether I have overlooked something.

Add submesh support

The parser currently only supports separating submeshes via 'usemtl' statements. However a large part of the OBJ format (and meshes in general) is the ability to split meshes into submeshes or 'groups' via the 'g' option.

Without this support the parser will currently provide single arrays of vertex attributes as opposed to separate arrays of attributes per group, for meshes without 'usemtl' statements.

Documentation / Example for materials

Thanks for making this library! I'm looking forward to playing with it :)

One thing at a glance - I downloaded some basic sphere model from turbosquid and it comes with some material. When I load it via webl-obj-loader and console.log the mesh returned from downloadMeshes I see there's some materials.

Looking the source of material.js- I see lots of great comments on what a material is - e.g. diffuse, specular, etc.

However, I don't see any documentation of how to use this in a shader. I understand that there is no 1:1 correspondence since lighting is implementation specific, and using this library as opposed to Three.JS is all about getting down and dirty to DIY.

Still, any documentation or leads on how to get from materials to shader/js implementation is helpful. Sortof like nice how to you did with initMeshBuffers... e.g. maybe provide a helper util, but show code samples of the reasoning behind it so it's easier to build from scratch?

Right now I'm just learning WebGL and sortof at a place of basically understanding how to apply a directional light by formula (e.g. this article) - to give some context :)

Any thoughts on this are appreciated.

Thanks!

UV layout, error in the code.

Hi there, I just spotted that (webgl-obj-loader.js; line 866):
_case layout.Layout.UV.key:
dataView.setFloat32(offset, this.textures[i * 2], true);
dataView.setFloat32(offset + 4, this.vertices[i * 2 + 1], true);

probably should look like
_case layout.Layout.UV.key:
dataView.setFloat32(offset, this.textures[i * 2], true);
dataView.setFloat32(offset + 4, this.textures[i * 2 + 1], true);

which seems to solve a small problem that I had with correct gBuffer mappings ; D

web worker

Though this would change the interface, parsing should really be done in a separate thread so as not to block the main thread of execution. Meshes like the Stanford Dragon (~9MB) will trigger a slow script warning.

Support N-gons in an OBJ model

Currently, if a model has more than 4 vertices in a face, the model will not load correctly and will have gaps. To prevent this from happening, the model first needs to be pre-processed and triangulated to make it WebGL happy.

This is somewhat of a pain for people wanting to learn WebGL, but not care about how model files are laid out (or how to use some third party program to pre-process the file).

Instead, the model should be converted to triangles on the fly.

Create MTL Option Parser Class

The image/texture/reflection map files have options that can be passed along with the filename. A new option parser class should be created to be able to handle these options.

Note, according to the Wikipedia page, the format specifies that the filename always comes after the options, however, there is at least one vendor that allows for the filename to come before. This should be considered.

The most difficult part of parsing the options (and why we most likely have to write a custom parser) is due to the -o, -s, and -t options allowing 0, 1, or 2 args.

obj texturecoordinates

Hi,

thank you for your nice script.

i now encountered obj files exported from cinema 4d which have 3 numbers per texturecoordinate, which does not make sense for 2d textures.
all the indices for texture coordinates are wrong when loading this .obj file.

i fixed it by checking the number of elements and reducing it to 2 if >2

do you want me to create a pull request for this ?

cannot load .obj file

Hi everyone, I'm a noob in 3D graphics. I tried to load the model I attach
bb8.obj.zip
but it doesn't show up. I downloaded the model from http://tf3dm.com, and it seems to work in http://www.meshlabjs.net/

I cloned webgl-obj-loader and checked out in the gh-pages branch. Then I added my model in the models/ directory and makes the window.onload function in webgl.js load "bb8.obj" instead of "suzanne,obj" and the result is... that nothing appear on the pedestal
screen

I looked at the javascript console, and this is what I got:

    non well-formed tunnel_ceiling.obj:1:2
    non well-formed tunnel_walls.obj:1:2
    non well-formed room_walls.obj:1:2
    non well-formed room_ceiling.obj:1:2
    non well-formed room_floor.obj:1:2
    non well-formed room_tunnel_ceiling.obj:1:2
    non well-formed room_tunnel_walls.obj:1:2
    non well-formed room_wall_broken.obj:1:2
    non well-formed room_wall_unbroken.obj:1:2
    non well-formed bb8.obj:1:2
    non well-formed pedestal.obj:1:2
    non well-formed boulder.obj:1:2

A "non well formed" for each .obj files I tried to load (also for those that I didn't changed such as "boulder.obj"). I get the same errors on http://frenchtoast747.github.io/webgl-obj-loader/, but of course I can see suzanne on the pedestal.

I watched into the .obj files, and I saw that there were some missing lines in bb8.obj, that I added:

    o bb8.obj
    g default

but nothing changed.

I also noticed that the lines are in different order from the other files: in "suzanne.obj", there are a lot of lines that starts with "v", then a lot of lines that starts with "vn", then a lot of lines that starts with "f"
in "bb8.obj", there are a lot of lines that starts with "v", then a lot of lines that starts with "vn", then a lot of lines that starts with "vt", then a line that begins with "s" and finally lot of lines that begins with "f" and "s", mixed.
As I said before, I know nothing about the obj format, I can just guess that each line defines a vertex, and in the two files the lines order is different.
I wonder why webgl-obj-loader cannot load my .obj file, or as an alternative, can you please tell me how to reorder the lines in my file to get it loaded?

Thank you in advance,
Lucio

Support .mtl files

Usually, when an .obj file is exported, a .mtl file is exported as well.

The .mtl contains information such as texture maps and colors. An .obj file will reference a lib name from which to load material names. The name of the lib is the name of the corresponding .mtl file to load. A material is then prefixed before one or more faces that use that material.

For example:

# at the top of SomeModel.obj file
mtllib SomeModel.mtl
# ...vertex, vertex normal, and texture coord definitions here...
usemtl my_material
f 2/1/1 4/2/2 3/3/3
f 5/4/4 7/5/5 6/6/6
...

While parsing, the material information should be associated with the specific faces. Several simple models that I have seen usually only have a single material that applies to all faces, although, this may not always be the case.

I'm not entirely sure how to handle application of MTL information to the OBJ model at the moment.

This addition could greatly help in getting models with simple textures loaded quickly in an organized manner.

Helpful reading materials:
http://nendowingsmirai.yuku.com/forum/viewtopic/id/1723#.VEf6cPnF9wB
http://people.cs.clemson.edu/~dhouse/courses/405/docs/brief-mtl-file-format.html
https://en.wikipedia.org/wiki/Wavefront_.obj_file#Material_template_library

DownloadModels() use.

I'm trying to use the downloadModels() function like this:

OBJ.downloadModels([{
        obj: 'model/test.obj',
        mtl: true 
    }]).then(function(result){console.log("success")}, function(err){console.log("error")});

The files are actually successfully requested to the server but nothing is ever printed to the console.
What am I doing wrong?

I get "" in filename on the sponza

I get empty string ("") in filename on the sponza 3d model material downloaded from this site https://casual-effects.com/data/.

Maybe I dont understand the source code yet, can somebody tell me where can I get the texture image path/filename from each material.

my code is more or less this:

var sponzaMeshObjText = getString('Assets/sponza/sponza.obj');
var sponzaMeshObj = new OBJ.Mesh(sponzaMeshObjText);
var material = new OBJ.Material(sponzaMeshObj.materialNames[0]);
console.log(material);

I could load it manually but the sponza model have a lot of meshes and textures.

Allow for interleaving the data into a single buffer

Currently, the loader expects the user to bind a grand total of four different buffers before drawing the mesh. There should be an option that allows the Mesh instance to interleave all of the data into a single list.

Missing TypeScript header file

This module is currently missing and index.d.ts file which means that it is not compatible with TypeScript without type casting to any type, which removes the benefit of the static typing.

If any maintainer of this repo is interested, I would be happy to open a PR to add one?

worker pool

Depends on #12 . Once the interface has been changed to work async with 1 worker, we should try to spawn multiple workers, since an obj file should be able to be parsed in parallel, and recombined in order.

Add support for calculating tangents and bitangents

With the existing support for .mtl files it would make sense for the library to calculate the tangents and bitangents as an option. These are later needed for calculating the TBN matrix when dealing with normal maps.

The tangents and bitangents are derived from the vertices positions and (most commonly) the direction of the texture coordinates.

Set up Travis-CI

I've caught myself pushing without running a few tests already. It would be nice to set up the continuous integration in order to automatically run. This will make accepting pull requests that much easier.

how do I load a model in webgl2 with multiple material/objects?

Hello

I've been trying this method:

  1. Create a one global array buffer for each type of data (position, uv, normal, etc).

  2. Then create one element buffer array (index) for each material index data.

  3. Create one VAO for each material index array. Every VAO is going to be bound to all the global array buffer and one respective element buffer.

  4. Lastly I draw every VAO.

I tried this approach with Drovaric sponza from https://casual-effects.com/data/ and it works fine, but it does not have normal data, so I used blender to generate the normals and I get a bad result when drawing the mesh, like the the vertices are out of order.

in the case of using OBJ.initMeshBuffers, how would i go about it?

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.