obj.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  1. // Copyright 2016 The G3N Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package obj is used to parse the Wavefront OBJ file format (*.obj), including
  5. // associated materials (*.mtl). Not all features of the OBJ format are
  6. // supported. Basic format info: https://en.wikipedia.org/wiki/Wavefront_.obj_file
  7. package obj
  8. import (
  9. "bufio"
  10. "errors"
  11. "fmt"
  12. "io"
  13. "math"
  14. "os"
  15. "path/filepath"
  16. "strconv"
  17. "strings"
  18. "github.com/g3n/engine/core"
  19. "github.com/g3n/engine/geometry"
  20. "github.com/g3n/engine/gls"
  21. "github.com/g3n/engine/graphic"
  22. "github.com/g3n/engine/material"
  23. "github.com/g3n/engine/math32"
  24. "github.com/g3n/engine/texture"
  25. )
  26. // Decoder contains all decoded data from the obj and mtl files
  27. type Decoder struct {
  28. Objects []Object // decoded objects
  29. Matlib string // name of the material lib
  30. Materials map[string]*Material // maps material name to object
  31. Vertices math32.ArrayF32 // vertices positions array
  32. Normals math32.ArrayF32 // vertices normals
  33. Uvs math32.ArrayF32 // vertices texture coordinates
  34. Warnings []string // warning messages
  35. line uint // current line number
  36. objCurrent *Object // current object
  37. matCurrent *Material // current material
  38. smoothCurrent bool // current smooth state
  39. mtlDir string // Directory of material file
  40. }
  41. // Object contains all information about one decoded object
  42. type Object struct {
  43. Name string // Object name
  44. Faces []Face // Faces
  45. materials []string // Materials used in this object
  46. }
  47. // Face contains all information about an object face
  48. type Face struct {
  49. Vertices []int // Indices to the face vertices
  50. Uvs []int // Indices to the face UV coordinates
  51. Normals []int // Indices to the face normals
  52. Material string // Material name
  53. Smooth bool // Smooth face
  54. }
  55. // Material contains all information about an object material
  56. type Material struct {
  57. Name string // Material name
  58. Illum int // Illumination model
  59. Opacity float32 // Opacity factor
  60. Refraction float32 // Refraction factor
  61. Shininess float32 // Shininess (specular exponent)
  62. Ambient math32.Color // Ambient color reflectivity
  63. Diffuse math32.Color // Diffuse color reflectivity
  64. Specular math32.Color // Specular color reflectivity
  65. Emissive math32.Color // Emissive color
  66. MapKd string // Texture file linked to diffuse color
  67. }
  68. // Light gray default material used as when other materials cannot be loaded.
  69. var defaultMat = &Material{
  70. Diffuse: math32.Color{R: 0.7, G: 0.7, B: 0.7},
  71. Ambient: math32.Color{R: 0.7, G: 0.7, B: 0.7},
  72. Specular: math32.Color{R: 0.5, G: 0.5, B: 0.5},
  73. Shininess: 30.0,
  74. }
  75. // Local constants
  76. const (
  77. blanks = "\r\n\t "
  78. invINDEX = math.MaxUint32
  79. objType = "obj"
  80. mtlType = "mtl"
  81. )
  82. // Decode decodes the specified obj and mtl files returning a decoder
  83. // object and an error. Passing an empty string (or otherwise invalid path)
  84. // to mtlpath will cause the decoder to check the 'mtllib' file in the OBJ if
  85. // present, and fall back to a default material as a last resort.
  86. func Decode(objpath string, mtlpath string) (*Decoder, error) {
  87. // Opens obj file
  88. fobj, err := os.Open(objpath)
  89. if err != nil {
  90. return nil, err
  91. }
  92. defer fobj.Close()
  93. // Opens mtl file
  94. // if mtlpath=="", then os.Open() will produce an error,
  95. // causing fmtl to be nil
  96. fmtl, err := os.Open(mtlpath)
  97. defer fmtl.Close() // will produce (ignored) err if fmtl==nil
  98. // if fmtl==nil, the io.Reader in DecodeReader() will be (T=*os.File, V=nil)
  99. // which is NOT equal to plain nil or (io.Reader, nil) but will produce
  100. // the desired result of passing nil to DecodeReader() per it's func comment.
  101. dec, err := DecodeReader(fobj, fmtl)
  102. if err != nil {
  103. return nil, err
  104. }
  105. dec.mtlDir = filepath.Dir(objpath)
  106. return dec, nil
  107. }
  108. // DecodeReader decodes the specified obj and mtl readers returning a decoder
  109. // object and an error if a problem was encoutered while parsing the OBJ.
  110. //
  111. // Pass a valid io.Reader to override the materials defined in the OBJ file,
  112. // or `nil` to use the materials listed in the OBJ's "mtllib" line (if present),
  113. // a ".mtl" file with the same name as the OBJ file if presemt, or a default
  114. // material as a last resort. No error will be returned for problems
  115. // with materials--a gray default material will be used if nothing else works.
  116. func DecodeReader(objreader, mtlreader io.Reader) (*Decoder, error) {
  117. dec := new(Decoder)
  118. dec.Objects = make([]Object, 0)
  119. dec.Warnings = make([]string, 0)
  120. dec.Materials = make(map[string]*Material)
  121. dec.Vertices = math32.NewArrayF32(0, 0)
  122. dec.Normals = math32.NewArrayF32(0, 0)
  123. dec.Uvs = math32.NewArrayF32(0, 0)
  124. dec.line = 1
  125. // Parses obj lines
  126. err := dec.parse(objreader, dec.parseObjLine)
  127. if err != nil {
  128. return nil, err
  129. }
  130. if (mtlreader != nil) {
  131. // Parses mtl lines
  132. // 1) try passed in mtlreader,
  133. // 2) try file in mtllib line
  134. // 3) try <obj_filename>.mtl
  135. // 4) use default material as last resort
  136. dec.matCurrent = nil
  137. dec.line = 1
  138. // first try: use the material file passed in as an io.Reader
  139. err = dec.parse(mtlreader, dec.parseMtlLine)
  140. if err != nil {
  141. // 2) if mtlreader produces an error (eg. it's nil), try the file listed
  142. // in the OBJ's matlib line, if it exists.
  143. if dec.Matlib != "" {
  144. // ... first need to get the path of the OBJ, since mtllib is relative
  145. var mtllibPath string
  146. if objf, ok := objreader.(*os.File); ok {
  147. // NOTE (quillaja): this is a hack because we need the directory of
  148. // the OBJ, but can't get it any other way (dec.mtlDir isn't set
  149. // until AFTER this function is finished).
  150. objdir := filepath.Dir(objf.Name())
  151. mtllibPath = filepath.Join(objdir, dec.Matlib)
  152. dec.mtlDir = objdir // NOTE (quillaja): should this be set?
  153. }
  154. mtlf, errMTL := os.Open(mtllibPath)
  155. defer mtlf.Close()
  156. if errMTL == nil {
  157. err = dec.parse(mtlf, dec.parseMtlLine) // will set err to nil if successful
  158. }
  159. }
  160. // 3) if the mtllib line fails try <obj_filename>.mtl in the same directory.
  161. // process is basically identical to the above code block.
  162. if err != nil {
  163. var mtlpath string
  164. if objf, ok := objreader.(*os.File); ok {
  165. objdir := strings.TrimSuffix(objf.Name(), ".obj")
  166. mtlpath = objdir + ".mtl"
  167. dec.mtlDir = objdir // NOTE (quillaja): should this be set?
  168. }
  169. mtlf, errMTL := os.Open(mtlpath)
  170. defer mtlf.Close()
  171. if errMTL == nil {
  172. err = dec.parse(mtlf, dec.parseMtlLine) // will set err to nil if successful
  173. if err == nil {
  174. // log a warning
  175. msg := fmt.Sprintf("using material file %s", mtlpath)
  176. dec.appendWarn(mtlType, msg)
  177. }
  178. }
  179. }
  180. // 4) handle error(s) instead of simply passing it up the call stack.
  181. // range over the materials named in the OBJ file and substitute a default
  182. // But log that an error occured.
  183. if err != nil {
  184. fmt.Println("Using default material")
  185. for key := range dec.Materials {
  186. dec.Materials[key] = defaultMat
  187. }
  188. // NOTE (quillaja): could be an error of some custom type. But people
  189. // tend to ignore errors and pass them up the call stack instead
  190. // of handling them... so all this work would probably be wasted.
  191. dec.appendWarn(mtlType, "unable to parse a material file for obj. using default material instead.")
  192. }
  193. }
  194. }
  195. return dec, nil
  196. }
  197. // NewGroup creates and returns a group containing as children meshes
  198. // with all the decoded objects.
  199. // A group is returned even if there is only one object decoded.
  200. func (dec *Decoder) NewGroup() (*core.Node, error) {
  201. group := core.NewNode()
  202. for i := 0; i < len(dec.Objects); i++ {
  203. mesh, err := dec.NewMesh(&dec.Objects[i])
  204. if err != nil {
  205. return nil, err
  206. }
  207. group.Add(mesh)
  208. }
  209. return group, nil
  210. }
  211. // NewMesh creates and returns a mesh from an specified decoded object.
  212. func (dec *Decoder) NewMesh(obj *Object) (*graphic.Mesh, error) {
  213. // Creates object geometry
  214. geom, err := dec.NewGeometry(obj)
  215. if err != nil {
  216. return nil, err
  217. }
  218. // Single material
  219. if geom.GroupCount() == 1 {
  220. // get Material info from mtl file and ensure it's valid.
  221. // substitute default material if it is not.
  222. var matDesc *Material
  223. var matName string
  224. if len(obj.materials) > 0 {
  225. matName = obj.materials[0]
  226. }
  227. matDesc = dec.Materials[matName]
  228. if matDesc == nil {
  229. matDesc = defaultMat
  230. // log warning
  231. msg := fmt.Sprintf("could not find material for %s. using default material.", obj.Name)
  232. dec.appendWarn(objType, msg)
  233. }
  234. // Creates material for mesh
  235. mat := material.NewStandard(&matDesc.Diffuse)
  236. ambientColor := mat.AmbientColor()
  237. mat.SetAmbientColor(ambientColor.Multiply(&matDesc.Ambient))
  238. mat.SetSpecularColor(&matDesc.Specular)
  239. mat.SetShininess(matDesc.Shininess)
  240. // Loads material textures if specified
  241. err = dec.loadTex(&mat.Material, matDesc)
  242. if err != nil {
  243. return nil, err
  244. }
  245. return graphic.NewMesh(geom, mat), nil
  246. }
  247. // Multi material
  248. mesh := graphic.NewMesh(geom, nil)
  249. for idx := 0; idx < geom.GroupCount(); idx++ {
  250. group := geom.GroupAt(idx)
  251. // get Material info from mtl file and ensure it's valid.
  252. // substitute default material if it is not.
  253. var matDesc *Material
  254. var matName string
  255. if len(obj.materials) > group.Matindex {
  256. matName = obj.materials[group.Matindex]
  257. }
  258. matDesc = dec.Materials[matName]
  259. if matDesc == nil {
  260. matDesc = defaultMat
  261. // log warning
  262. msg := fmt.Sprintf("could not find material for %s. using default material.", obj.Name)
  263. dec.appendWarn(objType, msg)
  264. }
  265. // Creates material for mesh
  266. matGroup := material.NewStandard(&matDesc.Diffuse)
  267. ambientColor := matGroup.AmbientColor()
  268. matGroup.SetAmbientColor(ambientColor.Multiply(&matDesc.Ambient))
  269. matGroup.SetSpecularColor(&matDesc.Specular)
  270. matGroup.SetShininess(matDesc.Shininess)
  271. // Loads material textures if specified
  272. err = dec.loadTex(&matGroup.Material, matDesc)
  273. if err != nil {
  274. return nil, err
  275. }
  276. mesh.AddGroupMaterial(matGroup, idx)
  277. }
  278. return mesh, nil
  279. }
  280. // NewGeometry generates and returns a geometry from the specified object
  281. func (dec *Decoder) NewGeometry(obj *Object) (*geometry.Geometry, error) {
  282. geom := geometry.NewGeometry()
  283. // Create buffers
  284. positions := math32.NewArrayF32(0, 0)
  285. normals := math32.NewArrayF32(0, 0)
  286. uvs := math32.NewArrayF32(0, 0)
  287. indices := math32.NewArrayU32(0, 0)
  288. // copy all vertex info from the decoded Object, face and index to the geometry
  289. copyVertex := func(face *Face, idx int) {
  290. var vec3 math32.Vector3
  291. var vec2 math32.Vector2
  292. pos := positions.Size() / 3
  293. // Copy vertex position and append to geometry
  294. dec.Vertices.GetVector3(3*face.Vertices[idx], &vec3)
  295. positions.AppendVector3(&vec3)
  296. // Copy vertex normal and append to geometry
  297. if face.Normals[idx] != invINDEX {
  298. dec.Normals.GetVector3(3*face.Normals[idx], &vec3)
  299. normals.AppendVector3(&vec3)
  300. }
  301. // Copy vertex uv and append to geometry
  302. if face.Uvs[idx] != invINDEX {
  303. dec.Uvs.GetVector2(2*face.Uvs[idx], &vec2)
  304. uvs.AppendVector2(&vec2)
  305. }
  306. indices.Append(uint32(pos))
  307. }
  308. var group *geometry.Group
  309. matName := ""
  310. matIndex := 0
  311. for _, face := range obj.Faces {
  312. // If face material changed, starts a new group
  313. if face.Material != matName {
  314. group = geom.AddGroup(indices.Size(), 0, matIndex)
  315. matName = face.Material
  316. matIndex++
  317. }
  318. // Copy face vertices to geometry
  319. for idx := 1; idx < len(face.Vertices)-1; idx++ {
  320. copyVertex(&face, 0)
  321. copyVertex(&face, idx)
  322. copyVertex(&face, idx+1)
  323. group.Count += 3
  324. }
  325. }
  326. geom.SetIndices(indices)
  327. geom.AddVBO(gls.NewVBO(positions).AddAttrib(gls.VertexPosition))
  328. geom.AddVBO(gls.NewVBO(normals).AddAttrib(gls.VertexNormal))
  329. geom.AddVBO(gls.NewVBO(uvs).AddAttrib(gls.VertexTexcoord))
  330. return geom, nil
  331. }
  332. // loadTex loads textures described in the material descriptor into the
  333. // specified material
  334. func (dec *Decoder) loadTex(mat *material.Material, desc *Material) error {
  335. // Checks if material descriptor specified texture
  336. if desc.MapKd == "" {
  337. return nil
  338. }
  339. // Get texture file path
  340. // If texture file path is not absolute assumes it is relative
  341. // to the directory of the material file
  342. var texPath string
  343. if filepath.IsAbs(desc.MapKd) {
  344. texPath = desc.MapKd
  345. } else {
  346. texPath = filepath.Join(dec.mtlDir, desc.MapKd)
  347. }
  348. // Try to load texture from image file
  349. tex, err := texture.NewTexture2DFromImage(texPath)
  350. if err != nil {
  351. return err
  352. }
  353. mat.AddTexture(tex)
  354. return nil
  355. }
  356. // parse reads the lines from the specified reader and dispatch them
  357. // to the specified line parser.
  358. func (dec *Decoder) parse(reader io.Reader, parseLine func(string) error) error {
  359. bufin := bufio.NewReader(reader)
  360. dec.line = 1
  361. for {
  362. // Reads next line and abort on errors (not EOF)
  363. line, err := bufin.ReadString('\n')
  364. if err != nil && err != io.EOF {
  365. return err
  366. }
  367. // Parses the line
  368. line = strings.Trim(line, blanks)
  369. perr := parseLine(line)
  370. if perr != nil {
  371. return perr
  372. }
  373. // If EOF ends of parsing.
  374. if err == io.EOF {
  375. break
  376. }
  377. dec.line++
  378. }
  379. return nil
  380. }
  381. // Parses obj file line, dispatching to specific parsers
  382. func (dec *Decoder) parseObjLine(line string) error {
  383. // Ignore empty lines
  384. fields := strings.Fields(line)
  385. if len(fields) == 0 {
  386. return nil
  387. }
  388. // Ignore comment lines
  389. ltype := fields[0]
  390. if strings.HasPrefix(ltype, "#") {
  391. return nil
  392. }
  393. switch ltype {
  394. // Material library
  395. case "mtllib":
  396. return dec.parseMatlib(fields[1:])
  397. // Object name
  398. case "o":
  399. return dec.parseObject(fields[1:])
  400. // Group names. We are considering "group" the same as "object"
  401. // This may not be right
  402. case "g":
  403. return dec.parseObject(fields[1:])
  404. // Vertex coordinate
  405. case "v":
  406. return dec.parseVertex(fields[1:])
  407. // Vertex normal coordinate
  408. case "vn":
  409. return dec.parseNormal(fields[1:])
  410. // Vertex texture coordinate
  411. case "vt":
  412. return dec.parseTex(fields[1:])
  413. // Face vertex
  414. case "f":
  415. return dec.parseFace(fields[1:])
  416. // Use material
  417. case "usemtl":
  418. return dec.parseUsemtl(fields[1:])
  419. // Smooth
  420. case "s":
  421. return dec.parseSmooth(fields[1:])
  422. default:
  423. dec.appendWarn(objType, "field not supported: "+ltype)
  424. }
  425. return nil
  426. }
  427. // Parses a mtllib line:
  428. // mtllib <name>
  429. func (dec *Decoder) parseMatlib(fields []string) error {
  430. if len(fields) < 1 {
  431. return errors.New("Material library (mtllib) with no fields")
  432. }
  433. dec.Matlib = fields[0]
  434. return nil
  435. }
  436. // Parses an object line:
  437. // o <name>
  438. func (dec *Decoder) parseObject(fields []string) error {
  439. if len(fields) < 1 {
  440. return errors.New("Object line (o) with no fields")
  441. }
  442. dec.Objects = append(dec.Objects, makeObject(fields[0]))
  443. dec.objCurrent = &dec.Objects[len(dec.Objects)-1]
  444. return nil
  445. }
  446. // makes an Object with name.
  447. func makeObject(name string) Object {
  448. var ob Object
  449. ob.Name = name
  450. ob.Faces = make([]Face, 0)
  451. ob.materials = make([]string, 0)
  452. return ob
  453. }
  454. // Parses a vertex position line
  455. // v <x> <y> <z> [w]
  456. func (dec *Decoder) parseVertex(fields []string) error {
  457. if len(fields) < 3 {
  458. return errors.New("Less than 3 vertices in 'v' line")
  459. }
  460. for _, f := range fields[:3] {
  461. val, err := strconv.ParseFloat(f, 32)
  462. if err != nil {
  463. return err
  464. }
  465. dec.Vertices.Append(float32(val))
  466. }
  467. return nil
  468. }
  469. // Parses a vertex normal line
  470. // vn <x> <y> <z>
  471. func (dec *Decoder) parseNormal(fields []string) error {
  472. if len(fields) < 3 {
  473. return errors.New("Less than 3 normals in 'vn' line")
  474. }
  475. for _, f := range fields[:3] {
  476. val, err := strconv.ParseFloat(f, 32)
  477. if err != nil {
  478. return err
  479. }
  480. dec.Normals.Append(float32(val))
  481. }
  482. return nil
  483. }
  484. // Parses a vertex texture coordinate line:
  485. // vt <u> <v> <w>
  486. func (dec *Decoder) parseTex(fields []string) error {
  487. if len(fields) < 2 {
  488. return errors.New("Less than 2 texture coords. in 'vt' line")
  489. }
  490. for _, f := range fields[:2] {
  491. val, err := strconv.ParseFloat(f, 32)
  492. if err != nil {
  493. return err
  494. }
  495. dec.Uvs.Append(float32(val))
  496. }
  497. return nil
  498. }
  499. // parseFace parses a face decription line:
  500. // f v1[/vt1][/vn1] v2[/vt2][/vn2] v3[/vt3][/vn3] ...
  501. func (dec *Decoder) parseFace(fields []string) error {
  502. // NOTE(quillaja): this wasn't really part of the original issue-29
  503. if dec.objCurrent == nil {
  504. // if a face line is encountered before a group (g) or object (o),
  505. // create a new "default" object. This 'handles' the case when
  506. // a g or o line is not specified (allowed in OBJ format)
  507. dec.parseObject([]string{fmt.Sprintf("unnamed%d", dec.line)})
  508. }
  509. // If current object has no material, appends last material if defined
  510. if len(dec.objCurrent.materials) == 0 && dec.matCurrent != nil {
  511. dec.objCurrent.materials = append(dec.objCurrent.materials, dec.matCurrent.Name)
  512. }
  513. if len(fields) < 3 {
  514. return dec.formatError("Face line with less 3 fields")
  515. }
  516. var face Face
  517. face.Vertices = make([]int, len(fields))
  518. face.Uvs = make([]int, len(fields))
  519. face.Normals = make([]int, len(fields))
  520. if dec.matCurrent != nil {
  521. face.Material = dec.matCurrent.Name
  522. } else {
  523. // TODO (quillaja): do something better than spamming warnings for each line
  524. // dec.appendWarn(objType, "No material defined")
  525. face.Material = "internal default" // causes error on in NewGeom() if ""
  526. // dec.matCurrent = defaultMat
  527. }
  528. face.Smooth = dec.smoothCurrent
  529. for pos, f := range fields {
  530. // Separate the current field in its components: v vt vn
  531. vfields := strings.Split(f, "/")
  532. if len(vfields) < 1 {
  533. return dec.formatError("Face field with no parts")
  534. }
  535. // Get the index of this vertex position (must always exist)
  536. val, err := strconv.ParseInt(vfields[0], 10, 32)
  537. if err != nil {
  538. return err
  539. }
  540. // Positive index is an absolute vertex index
  541. if val > 0 {
  542. face.Vertices[pos] = int(val - 1)
  543. // Negative vertex index is relative to the last parsed vertex
  544. } else if val < 0 {
  545. current := (len(dec.Vertices) / 3) - 1
  546. face.Vertices[pos] = current + int(val) + 1
  547. // Vertex index could never be 0
  548. } else {
  549. return dec.formatError("Face vertex index value equal to 0")
  550. }
  551. // Get the index of this vertex UV coordinate (optional)
  552. if len(vfields) > 1 && len(vfields[1]) > 0 {
  553. val, err := strconv.ParseInt(vfields[1], 10, 32)
  554. if err != nil {
  555. return err
  556. }
  557. // Positive index is an absolute UV index
  558. if val > 0 {
  559. face.Uvs[pos] = int(val - 1)
  560. // Negative vertex index is relative to the last parsed uv
  561. } else if val < 0 {
  562. current := (len(dec.Uvs) / 2) - 1
  563. face.Uvs[pos] = current + int(val) + 1
  564. // UV index could never be 0
  565. } else {
  566. return dec.formatError("Face uv index value equal to 0")
  567. }
  568. } else {
  569. face.Uvs[pos] = invINDEX
  570. }
  571. // Get the index of this vertex normal (optional)
  572. if len(vfields) >= 3 {
  573. val, err = strconv.ParseInt(vfields[2], 10, 32)
  574. if err != nil {
  575. return err
  576. }
  577. // Positive index is an absolute normal index
  578. if val > 0 {
  579. face.Normals[pos] = int(val - 1)
  580. // Negative vertex index is relative to the last parsed normal
  581. } else if val < 0 {
  582. current := (len(dec.Normals) / 3) - 1
  583. face.Normals[pos] = current + int(val) + 1
  584. // Normal index could never be 0
  585. } else {
  586. return dec.formatError("Face normal index value equal to 0")
  587. }
  588. } else {
  589. face.Normals[pos] = invINDEX
  590. }
  591. }
  592. // Appends this face to the current object
  593. dec.objCurrent.Faces = append(dec.objCurrent.Faces, face)
  594. return nil
  595. }
  596. // parseUsemtl parses a "usemtl" decription line:
  597. // usemtl <name>
  598. func (dec *Decoder) parseUsemtl(fields []string) error {
  599. if len(fields) < 1 {
  600. return dec.formatError("Usemtl with no fields")
  601. }
  602. // NOTE(quillaja): see similar nil test in parseFace()
  603. if dec.objCurrent == nil {
  604. dec.parseObject([]string{fmt.Sprintf("unnamed%d", dec.line)})
  605. }
  606. // Checks if this material has already been parsed
  607. name := fields[0]
  608. mat := dec.Materials[name]
  609. // Creates material descriptor
  610. if mat == nil {
  611. mat = new(Material)
  612. mat.Name = name
  613. dec.Materials[name] = mat
  614. }
  615. dec.objCurrent.materials = append(dec.objCurrent.materials, name)
  616. // Set this as the current material
  617. dec.matCurrent = mat
  618. return nil
  619. }
  620. // parseSmooth parses a "s" decription line:
  621. // s <0|1>
  622. func (dec *Decoder) parseSmooth(fields []string) error {
  623. if len(fields) < 1 {
  624. return dec.formatError("'s' with no fields")
  625. }
  626. if fields[0] == "0" || fields[0] == "off" {
  627. dec.smoothCurrent = false
  628. return nil
  629. }
  630. dec.smoothCurrent = true
  631. return nil
  632. }
  633. /******************************************************************************
  634. mtl parse functions
  635. */
  636. // Parses material file line, dispatching to specific parsers
  637. func (dec *Decoder) parseMtlLine(line string) error {
  638. // Ignore empty lines
  639. fields := strings.Fields(line)
  640. if len(fields) == 0 {
  641. return nil
  642. }
  643. // Ignore comment lines
  644. ltype := fields[0]
  645. if strings.HasPrefix(ltype, "#") {
  646. return nil
  647. }
  648. switch ltype {
  649. case "newmtl":
  650. return dec.parseNewmtl(fields[1:])
  651. case "d":
  652. return dec.parseDissolve(fields[1:])
  653. case "Ka":
  654. return dec.parseKa(fields[1:])
  655. case "Kd":
  656. return dec.parseKd(fields[1:])
  657. case "Ke":
  658. return dec.parseKe(fields[1:])
  659. case "Ks":
  660. return dec.parseKs(fields[1:])
  661. case "Ni":
  662. return dec.parseNi(fields[1:])
  663. case "Ns":
  664. return dec.parseNs(fields[1:])
  665. case "illum":
  666. return dec.parseIllum(fields[1:])
  667. case "map_Kd":
  668. return dec.parseMapKd(fields[1:])
  669. default:
  670. dec.appendWarn(mtlType, "field not supported: "+ltype)
  671. }
  672. return nil
  673. }
  674. // Parses new material definition
  675. // newmtl <mat_name>
  676. func (dec *Decoder) parseNewmtl(fields []string) error {
  677. if len(fields) < 1 {
  678. return dec.formatError("newmtl with no fields")
  679. }
  680. // Checks if material has already been seen
  681. name := fields[0]
  682. mat := dec.Materials[name]
  683. // Creates material descriptor
  684. if mat == nil {
  685. mat = new(Material)
  686. mat.Name = name
  687. dec.Materials[name] = mat
  688. }
  689. dec.matCurrent = mat
  690. return nil
  691. }
  692. // Parses the dissolve factor (opacity)
  693. // d <factor>
  694. func (dec *Decoder) parseDissolve(fields []string) error {
  695. if len(fields) < 1 {
  696. return dec.formatError("'d' with no fields")
  697. }
  698. val, err := strconv.ParseFloat(fields[0], 32)
  699. if err != nil {
  700. return dec.formatError("'d' parse float error")
  701. }
  702. dec.matCurrent.Opacity = float32(val)
  703. return nil
  704. }
  705. // Parses ambient reflectivity:
  706. // Ka r g b
  707. func (dec *Decoder) parseKa(fields []string) error {
  708. if len(fields) < 3 {
  709. return dec.formatError("'Ka' with less than 3 fields")
  710. }
  711. var colors [3]float32
  712. for pos, f := range fields[:3] {
  713. val, err := strconv.ParseFloat(f, 32)
  714. if err != nil {
  715. return err
  716. }
  717. colors[pos] = float32(val)
  718. }
  719. dec.matCurrent.Ambient.Set(colors[0], colors[1], colors[2])
  720. return nil
  721. }
  722. // Parses diffuse reflectivity:
  723. // Kd r g b
  724. func (dec *Decoder) parseKd(fields []string) error {
  725. if len(fields) < 3 {
  726. return dec.formatError("'Kd' with less than 3 fields")
  727. }
  728. var colors [3]float32
  729. for pos, f := range fields[:3] {
  730. val, err := strconv.ParseFloat(f, 32)
  731. if err != nil {
  732. return err
  733. }
  734. colors[pos] = float32(val)
  735. }
  736. dec.matCurrent.Diffuse.Set(colors[0], colors[1], colors[2])
  737. return nil
  738. }
  739. // Parses emissive color:
  740. // Ke r g b
  741. func (dec *Decoder) parseKe(fields []string) error {
  742. if len(fields) < 3 {
  743. return dec.formatError("'Ke' with less than 3 fields")
  744. }
  745. var colors [3]float32
  746. for pos, f := range fields[:3] {
  747. val, err := strconv.ParseFloat(f, 32)
  748. if err != nil {
  749. return err
  750. }
  751. colors[pos] = float32(val)
  752. }
  753. dec.matCurrent.Emissive.Set(colors[0], colors[1], colors[2])
  754. return nil
  755. }
  756. // Parses specular reflectivity:
  757. // Ks r g b
  758. func (dec *Decoder) parseKs(fields []string) error {
  759. if len(fields) < 3 {
  760. return dec.formatError("'Ks' with less than 3 fields")
  761. }
  762. var colors [3]float32
  763. for pos, f := range fields[:3] {
  764. val, err := strconv.ParseFloat(f, 32)
  765. if err != nil {
  766. return err
  767. }
  768. colors[pos] = float32(val)
  769. }
  770. dec.matCurrent.Specular.Set(colors[0], colors[1], colors[2])
  771. return nil
  772. }
  773. // Parses optical density, also known as index of refraction
  774. // Ni <optical_density>
  775. func (dec *Decoder) parseNi(fields []string) error {
  776. if len(fields) < 1 {
  777. return dec.formatError("'Ni' with no fields")
  778. }
  779. val, err := strconv.ParseFloat(fields[0], 32)
  780. if err != nil {
  781. return dec.formatError("'d' parse float error")
  782. }
  783. dec.matCurrent.Refraction = float32(val)
  784. return nil
  785. }
  786. // Parses specular exponent
  787. // Ns <specular_exponent>
  788. func (dec *Decoder) parseNs(fields []string) error {
  789. if len(fields) < 1 {
  790. return dec.formatError("'Ns' with no fields")
  791. }
  792. val, err := strconv.ParseFloat(fields[0], 32)
  793. if err != nil {
  794. return dec.formatError("'d' parse float error")
  795. }
  796. dec.matCurrent.Shininess = float32(val)
  797. return nil
  798. }
  799. // Parses illumination model (0 to 10)
  800. // illum <ilum_#>
  801. func (dec *Decoder) parseIllum(fields []string) error {
  802. if len(fields) < 1 {
  803. return dec.formatError("'illum' with no fields")
  804. }
  805. val, err := strconv.ParseUint(fields[0], 10, 32)
  806. if err != nil {
  807. return dec.formatError("'d' parse int error")
  808. }
  809. dec.matCurrent.Illum = int(val)
  810. return nil
  811. }
  812. // Parses color texture linked to the diffuse reflectivity of the material
  813. // map_Kd [-options] <filename>
  814. func (dec *Decoder) parseMapKd(fields []string) error {
  815. if len(fields) < 1 {
  816. return dec.formatError("No fields")
  817. }
  818. dec.matCurrent.MapKd = fields[0]
  819. return nil
  820. }
  821. func (dec *Decoder) formatError(msg string) error {
  822. return fmt.Errorf("%s in line:%d", msg, dec.line)
  823. }
  824. func (dec *Decoder) appendWarn(ftype string, msg string) {
  825. wline := fmt.Sprintf("%s(%d): %s", ftype, dec.line, msg)
  826. dec.Warnings = append(dec.Warnings, wline)
  827. }