2 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include "obj-loader.h"
37 ObjLoader::ObjLoader()
40 mMaterialLoaded = false;
44 ObjLoader::~ObjLoader()
49 bool ObjLoader::IsSceneLoaded()
54 bool ObjLoader::IsMaterialLoaded()
56 return mMaterialLoaded;
59 //TODO: Use a function that can generate more than one normal/tangent per vertex (using angle)
60 void ObjLoader::CalculateTangentArray(const Dali::Vector<Vector3>& vertex,
61 const Dali::Vector<Vector2>& texcoord,
62 Dali::Vector<TriIndex>& triangle,
63 Dali::Vector<Vector3>& normal,
64 Dali::Vector<Vector3>& tangent)
67 normal.Resize(vertex.Size());
69 Dali::Vector<Vector3> tangents;
70 tangents.Resize( vertex.Size() );
72 // Resize of a vector of Vector3 will initialise with the default constructor, setting to all zeros.
74 for ( unsigned long a = 0; a < triangle.Size(); a++ )
76 Vector3 tangentVector, normalVector;
78 const Vector3& v0 = vertex[triangle[a].pntIndex[0]];
79 const Vector3& v1 = vertex[triangle[a].pntIndex[1]];
80 const Vector3& v2 = vertex[triangle[a].pntIndex[2]];
82 Vector3 edge1 = v1 - v0;
83 Vector3 edge2 = v2 - v0;
85 normalVector = edge1.Cross(edge2);
87 const Vector2& w0 = texcoord[triangle[a].texIndex[0]];
88 const Vector2& w1 = texcoord[triangle[a].texIndex[1]];
89 const Vector2& w2 = texcoord[triangle[a].texIndex[2]];
91 float deltaU1 = w1.x - w0.x;
92 float deltaV1 = w1.y - w0.y;
93 float deltaU2 = w2.x - w0.x;
94 float deltaV2 = w2.y - w0.y;
96 float f = 1.0f / (deltaU1 * deltaV2 - deltaU2 * deltaV1);
98 tangentVector.x = f * ( deltaV2 * edge1.x - deltaV1 * edge2.x );
99 tangentVector.y = f * ( deltaV2 * edge1.y - deltaV1 * edge2.y );
100 tangentVector.z = f * ( deltaV2 * edge1.z - deltaV1 * edge2.z );
102 tangents[triangle[a].pntIndex[0]] += tangentVector;
103 tangents[triangle[a].pntIndex[1]] += tangentVector;
104 tangents[triangle[a].pntIndex[2]] += tangentVector;
106 normal[triangle[a].pntIndex[0]] += normalVector;
107 normal[triangle[a].pntIndex[1]] += normalVector;
108 normal[triangle[a].pntIndex[2]] += normalVector;
111 for ( unsigned long a = 0; a < triangle.Size(); a++ )
113 for ( unsigned long j = 0; j < 3; j++ )
115 triangle[a].nrmIndex[j] = triangle[a].pntIndex[j];
119 for ( unsigned long a = 0; a < normal.Size(); a++ )
121 normal[a].Normalize();
123 const Vector3& n = normal[a];
124 const Vector3& t = tangents[a];
126 // Gram-Schmidt orthogonalize
127 Vector3 calc = t - n * n.Dot(t);
129 tangent[a] = Vector3( calc.x,calc.y,calc.z );
134 void ObjLoader::CenterAndScale( bool center, Dali::Vector<Vector3>& points )
136 BoundingVolume newAABB;
138 Vector3 sceneSize = GetSize();
140 float biggestDimension = sceneSize.x;
141 if( sceneSize.y > biggestDimension )
143 biggestDimension = sceneSize.y;
145 if( sceneSize.z > biggestDimension )
147 biggestDimension = sceneSize.z;
152 for( unsigned int ui = 0; ui < points.Size(); ++ui )
154 points[ui] = points[ui] - GetCenter();
155 points[ui] = points[ui] / biggestDimension;
156 newAABB.ConsiderNewPointInVolume(points[ui]);
159 mSceneAABB = newAABB;
162 void ObjLoader::CreateGeometryArray(Dali::Vector<Vertex> & vertices,
163 Dali::Vector<Vector2> & textures,
164 Dali::Vector<VertexExt> & verticesExt,
165 Dali::Vector<unsigned short> & indices)
167 //If we don't have tangents, calculate them
168 //we need to recalculate the normals too, because we need just one normal,tangent, bitangent per vertex
169 //In the case of a textureless object, we don't need tangents and so we skip this step
170 //TODO: Use a better function to calculate tangents
171 if( mTangents.Size() == 0 && mHasTexture && mHasNormalMap )
173 mTangents.Resize( mNormals.Size() );
174 mBiTangents.Resize( mNormals.Size() );
175 CalculateTangentArray( mPoints, mTextures, mTriangles, mNormals, mTangents );
176 for ( unsigned int ui = 0 ; ui < mNormals.Size() ; ++ui )
178 mBiTangents[ui] = mNormals[ui].Cross(mTangents[ui]);
182 bool mapsCorrespond; //True if the sizes of the arrays necessary for the object agree.
186 mapsCorrespond = ( mPoints.Size() == mTextures.Size() ) && ( mTextures.Size() == mNormals.Size() );
190 mapsCorrespond = ( mPoints.Size() == mNormals.Size() );
193 //Check the number of points textures and normals
194 if ( mapsCorrespond )
196 int numPoints = mPoints.Size();
197 int numIndices = 3 * mTriangles.Size();
198 vertices.Resize( numPoints );
199 textures.Resize( numPoints );
200 verticesExt.Resize( numPoints );
201 indices.Resize( numIndices );
203 //We create the vertices array. For now we just copy points info
204 for (unsigned int ui = 0 ; ui < mPoints.Size() ; ++ui )
207 vertex.position = mPoints[ui];
208 vertices[ui] = vertex;
212 textures[ui] = Vector2();
213 verticesExt[ui] = VertexExt();
219 //We copy the indices
220 for ( unsigned int ui = 0 ; ui < mTriangles.Size() ; ++ui )
222 for ( int j = 0 ; j < 3 ; ++j )
224 indices[indiceIndex] = mTriangles[ui].pntIndex[j];
227 vertices[mTriangles[ui].pntIndex[j]].normal = mNormals[mTriangles[ui].nrmIndex[j]];
231 textures[mTriangles[ui].pntIndex[j]] = mTextures[mTriangles[ui].texIndex[j]];
234 if ( mHasNormalMap && mHasTexture )
236 verticesExt[mTriangles[ui].pntIndex[j]].tangent = mTangents[mTriangles[ui].nrmIndex[j]];
237 verticesExt[mTriangles[ui].pntIndex[j]].bitangent = mBiTangents[mTriangles[ui].nrmIndex[j]];
244 int numVertices = 3 * mTriangles.Size();
245 vertices.Resize( numVertices );
246 textures.Resize( numVertices );
247 verticesExt.Resize( numVertices );
251 //We have to normalize the arrays so we can draw we just one index array
252 for ( unsigned int ui = 0 ; ui < mTriangles.Size() ; ++ui )
254 for ( int j = 0 ; j < 3 ; ++j )
257 vertex.position = mPoints[mTriangles[ui].pntIndex[j]];
258 vertex.normal = mNormals[mTriangles[ui].nrmIndex[j]];
259 vertices[index] = vertex;
263 textures[index] = mTextures[mTriangles[ui].texIndex[j]];
266 if ( mHasNormalMap && mHasTexture )
269 vertexExt.tangent = mTangents[mTriangles[ui].nrmIndex[j]];
270 vertexExt.bitangent = mBiTangents[mTriangles[ui].nrmIndex[j]];
271 verticesExt[index] = vertexExt;
280 bool ObjLoader::Load( char* objBuffer, std::streampos fileSize, std::string& materialFile )
284 std::string vet[4], name;
288 TriIndex triangle,triangle2;
289 int pntAcum = 0, texAcum = 0, nrmAcum = 0;
291 bool hasTexture = false;
292 bool hasNormalMap = false;
295 //Init AABB for the file
298 std::string strMatActual;
300 std::string input = objBuffer;
301 std::istringstream ss(input);
302 ss.imbue( std::locale( "C" ) );
306 std::getline( ss, line );
308 while ( std::getline( ss, line ) )
310 std::istringstream isline( line, std::istringstream::in );
317 //Two different objects in the same file
321 mPoints.PushBack( point );
323 mSceneAABB.ConsiderNewPointInVolume( point );
325 else if ( tag == "vn" )
331 mNormals.PushBack( point );
333 else if ( tag == "#_#tangent" )
339 mTangents.PushBack( point );
342 else if ( tag == "#_#binormal" )
348 mBiTangents.PushBack( point );
351 else if ( tag == "vt" )
356 texture.y = 1.0-texture.y;
357 mTextures.PushBack( texture );
359 else if ( tag == "#_#vt1" )
364 texture.y = 1.0-texture.y;
365 mTextures2.PushBack( texture );
367 else if ( tag == "s" )
370 else if ( tag == "f" )
380 while( isline >> vet[numIndices] )
388 if ( strstr( vet[0].c_str(),"//" ) ) //No texture coordinates.
390 for( int i = 0 ; i < numIndices; i++)
392 std::istringstream isindex( vet[i] );
393 isindex >> ptIdx[i] >> separator >> separator2 >> nrmIdx[i];
397 else if ( strstr( vet[0].c_str(),"/" ) ) //Has texture coordinates, and possibly also normals.
399 for( int i = 0 ; i < numIndices; i++ )
401 std::istringstream isindex( vet[i] );
402 isindex >> ptIdx[i] >> separator >> texIdx[i] >> separator2 >> nrmIdx[i];
406 else //Has just points.
408 for( int i = 0 ; i < numIndices; i++ )
410 std::istringstream isindex( vet[i] );
417 //If it is a triangle
418 if( numIndices == 3 )
420 for( int i = 0 ; i < 3; i++ )
422 triangle.pntIndex[i] = ptIdx[i] - 1 - pntAcum;
423 triangle.nrmIndex[i] = nrmIdx[i] - 1 - nrmAcum;
424 triangle.texIndex[i] = texIdx[i] - 1 - texAcum;
426 mTriangles.PushBack( triangle );
429 //If on the other hand it is a quad, we will create two triangles
430 else if( numIndices == 4 )
432 for( int i = 0 ; i < 3; i++ )
434 triangle.pntIndex[i] = ptIdx[i] - 1 - pntAcum;
435 triangle.nrmIndex[i] = nrmIdx[i] - 1 - nrmAcum;
436 triangle.texIndex[i] = texIdx[i] - 1 - texAcum;
438 mTriangles.PushBack( triangle );
441 for( int i = 0 ; i < 3; i++ )
443 int idx = ( i + 2 ) % numIndices;
444 triangle2.pntIndex[i] = ptIdx[idx] - 1 - pntAcum;
445 triangle2.nrmIndex[i] = nrmIdx[idx] - 1 - nrmAcum;
446 triangle2.texIndex[i] = texIdx[idx] - 1 - texAcum;
448 mTriangles.PushBack( triangle2 );
452 else if ( tag == "usemtl" )
454 isline >> strMatActual;
456 else if ( tag == "mtllib" )
458 isline >> strMatActual;
460 else if ( tag == "g" )
471 CenterAndScale( true, mPoints );
473 mHasTexture = hasTexture;
474 mHasNormalMap = hasNormalMap;
482 void ObjLoader::LoadMaterial( char* objBuffer, std::streampos fileSize, std::string& texture0Url,
483 std::string& texture1Url, std::string& texture2Url )
489 std::string input = objBuffer;
490 std::istringstream ss(input);
491 ss.imbue(std::locale("C"));
494 std::getline( ss, line );
496 while ( std::getline( ss, line ) )
498 std::istringstream isline( line, std::istringstream::in );
503 if ( tag == "newmtl" ) //name of the material
507 else if ( tag == "Kd" ) //diffuse color
509 isline >> fR >> fG >> fB;
511 else if ( tag == "Kd" ) //Ambient color
513 isline >> fR >> fG >> fB;
515 else if ( tag == "Tf" ) //color
518 else if ( tag == "Ni" )
521 else if ( tag == "map_Kd" )
526 else if ( tag == "bump" )
530 mHasNormalMap = true;
532 else if ( tag == "map_Ks" )
539 mMaterialLoaded = true;
542 Geometry ObjLoader::CreateGeometry( Toolkit::Model3dView::IlluminationType illuminationType )
544 Dali::Vector<Vertex> vertices;
545 Dali::Vector<Vector2> textures;
546 Dali::Vector<VertexExt> verticesExt;
547 Dali::Vector<unsigned short> indices;
549 CreateGeometryArray( vertices, textures, verticesExt, indices );
551 //All vertices need at least Position and Normal
552 Property::Map vertexFormat;
553 vertexFormat["aPosition"] = Property::VECTOR3;
554 vertexFormat["aNormal"] = Property::VECTOR3;
555 PropertyBuffer surfaceVertices = PropertyBuffer::New( vertexFormat );
556 surfaceVertices.SetData( &vertices[0], vertices.Size() );
558 Geometry surface = Geometry::New();
559 surface.AddVertexBuffer( surfaceVertices );
561 //Some need texture coordinates
562 if( ( (illuminationType == Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP ) ||
563 (illuminationType == Toolkit::Model3dView::DIFFUSE_WITH_TEXTURE ) ) && mHasTexture )
565 Property::Map textureFormat;
566 textureFormat["aTexCoord"] = Property::VECTOR2;
567 PropertyBuffer extraVertices = PropertyBuffer::New( textureFormat );
568 extraVertices.SetData( &textures[0], textures.Size() );
570 surface.AddVertexBuffer( extraVertices );
573 //Some need tangent and bitangent
574 if( illuminationType == Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP && mHasNormalMap && mHasTexture )
576 Property::Map vertexExtFormat;
577 vertexExtFormat["aTangent"] = Property::VECTOR3;
578 vertexExtFormat["aBiNormal"] = Property::VECTOR3;
579 PropertyBuffer extraVertices = PropertyBuffer::New( vertexExtFormat );
580 extraVertices.SetData( &verticesExt[0], verticesExt.Size() );
582 surface.AddVertexBuffer( extraVertices );
585 if ( indices.Size() )
587 surface.SetIndexBuffer ( &indices[0], indices.Size() );
597 Vector3 ObjLoader::GetCenter()
599 Vector3 center = GetSize() * 0.5 + mSceneAABB.pointMin;
603 Vector3 ObjLoader::GetSize()
605 Vector3 size = mSceneAABB.pointMax - mSceneAABB.pointMin;
609 void ObjLoader::ClearArrays()
619 mSceneLoaded = false;
622 bool ObjLoader::IsTexturePresent()
627 bool ObjLoader::IsNormalMapPresent()
629 return mHasNormalMap;
632 } // namespace Internal
633 } // namespace Toolkit