obj.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  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. // Parses mtl lines
  131. // 1) try passed in mtlreader,
  132. // 2) try file in mtllib line
  133. // 3) try <obj_filename>.mtl
  134. // 4) use default material as last resort
  135. dec.matCurrent = nil
  136. dec.line = 1
  137. // first try: use the material file passed in as an io.Reader
  138. err = dec.parse(mtlreader, dec.parseMtlLine)
  139. if err != nil {
  140. // 2) if mtlreader produces an error (eg. it's nil), try the file listed
  141. // in the OBJ's matlib line, if it exists.
  142. if dec.Matlib != "" {
  143. // ... first need to get the path of the OBJ, since mtllib is relative
  144. var mtllibPath string
  145. if objf, ok := objreader.(*os.File); ok {
  146. // NOTE (quillaja): this is a hack because we need the directory of
  147. // the OBJ, but can't get it any other way (dec.mtlDir isn't set
  148. // until AFTER this function is finished).
  149. objdir := filepath.Dir(objf.Name())
  150. mtllibPath = filepath.Join(objdir, dec.Matlib)
  151. dec.mtlDir = objdir // NOTE (quillaja): should this be set?
  152. }
  153. mtlf, errMTL := os.Open(mtllibPath)
  154. defer mtlf.Close()
  155. if errMTL == nil {
  156. err = dec.parse(mtlf, dec.parseMtlLine) // will set err to nil if successful
  157. }
  158. }
  159. // 3) if the mtllib line fails try <obj_filename>.mtl in the same directory.
  160. // process is basically identical to the above code block.
  161. if err != nil {
  162. var mtlpath string
  163. if objf, ok := objreader.(*os.File); ok {
  164. objdir := strings.TrimSuffix(objf.Name(), ".obj")
  165. mtlpath = objdir + ".mtl"
  166. dec.mtlDir = objdir // NOTE (quillaja): should this be set?
  167. }
  168. mtlf, errMTL := os.Open(mtlpath)
  169. defer mtlf.Close()
  170. if errMTL == nil {
  171. err = dec.parse(mtlf, dec.parseMtlLine) // will set err to nil if successful
  172. if err == nil {
  173. // log a warning
  174. msg := fmt.Sprintf("using material file %s", mtlpath)
  175. dec.appendWarn(mtlType, msg)
  176. }
  177. }
  178. }
  179. // 4) handle error(s) instead of simply passing it up the call stack.
  180. // range over the materials named in the OBJ file and substitute a default
  181. // But log that an error occured.
  182. if err != nil {
  183. for key := range dec.Materials {
  184. dec.Materials[key] = defaultMat
  185. }
  186. // NOTE (quillaja): could be an error of some custom type. But people
  187. // tend to ignore errors and pass them up the call stack instead
  188. // of handling them... so all this work would probably be wasted.
  189. dec.appendWarn(mtlType, "unable to parse a material file for obj. using default material instead.")
  190. }
  191. }
  192. return dec, nil
  193. }
  194. // NewGroup creates and returns a group containing as children meshes
  195. // with all the decoded objects.
  196. // A group is returned even if there is only one object decoded.
  197. func (dec *Decoder) NewGroup() (*core.Node, error) {
  198. group := core.NewNode()
  199. for i := 0; i < len(dec.Objects); i++ {
  200. mesh, err := dec.NewMesh(&dec.Objects[i])
  201. if err != nil {
  202. return nil, err
  203. }
  204. group.Add(mesh)
  205. }
  206. return group, nil
  207. }
  208. // NewMesh creates and returns a mesh from an specified decoded object.
  209. func (dec *Decoder) NewMesh(obj *Object) (*graphic.Mesh, error) {
  210. // Creates object geometry
  211. geom, err := dec.NewGeometry(obj)
  212. if err != nil {
  213. return nil, err
  214. }
  215. // Single material
  216. if geom.GroupCount() == 1 {
  217. // get Material info from mtl file and ensure it's valid.
  218. // substitute default material if it is not.
  219. var matDesc *Material
  220. var matName string
  221. if len(obj.materials) > 0 {
  222. matName = obj.materials[0]
  223. }
  224. matDesc = dec.Materials[matName]
  225. if matDesc == nil {
  226. matDesc = defaultMat
  227. // log warning
  228. msg := fmt.Sprintf("could not find material for %s. using default material.", obj.Name)
  229. dec.appendWarn(objType, msg)
  230. }
  231. // Creates material for mesh
  232. mat := material.NewStandard(&matDesc.Diffuse)
  233. ambientColor := mat.AmbientColor()
  234. mat.SetAmbientColor(ambientColor.Multiply(&matDesc.Ambient))
  235. mat.SetSpecularColor(&matDesc.Specular)
  236. mat.SetShininess(matDesc.Shininess)
  237. // Loads material textures if specified
  238. err = dec.loadTex(&mat.Material, matDesc)
  239. if err != nil {
  240. return nil, err
  241. }
  242. return graphic.NewMesh(geom, mat), nil
  243. }
  244. // Multi material
  245. mesh := graphic.NewMesh(geom, nil)
  246. for idx := 0; idx < geom.GroupCount(); idx++ {
  247. group := geom.GroupAt(idx)
  248. // get Material info from mtl file and ensure it's valid.
  249. // substitute default material if it is not.
  250. var matDesc *Material
  251. var matName string
  252. if len(obj.materials) > group.Matindex {
  253. matName = obj.materials[group.Matindex]
  254. }
  255. matDesc = dec.Materials[matName]
  256. if matDesc == nil {
  257. matDesc = defaultMat
  258. // log warning
  259. msg := fmt.Sprintf("could not find material for %s. using default material.", obj.Name)
  260. dec.appendWarn(objType, msg)
  261. }
  262. // Creates material for mesh
  263. matGroup := material.NewStandard(&matDesc.Diffuse)
  264. ambientColor := matGroup.AmbientColor()
  265. matGroup.SetAmbientColor(ambientColor.Multiply(&matDesc.Ambient))
  266. matGroup.SetSpecularColor(&matDesc.Specular)
  267. matGroup.SetShininess(matDesc.Shininess)
  268. // Loads material textures if specified
  269. err = dec.loadTex(&matGroup.Material, matDesc)
  270. if err != nil {
  271. return nil, err
  272. }
  273. mesh.AddGroupMaterial(matGroup, idx)
  274. }
  275. return mesh, nil
  276. }
  277. // NewGeometry generates and returns a geometry from the specified object
  278. func (dec *Decoder) NewGeometry(obj *Object) (*geometry.Geometry, error) {
  279. geom := geometry.NewGeometry()
  280. // Create buffers
  281. positions := math32.NewArrayF32(0, 0)
  282. normals := math32.NewArrayF32(0, 0)
  283. uvs := math32.NewArrayF32(0, 0)
  284. indices := math32.NewArrayU32(0, 0)
  285. // copy all vertex info from the decoded Object, face and index to the geometry
  286. copyVertex := func(face *Face, idx int) {
  287. var vec3 math32.Vector3
  288. var vec2 math32.Vector2
  289. pos := positions.Size() / 3
  290. // Copy vertex position and append to geometry
  291. dec.Vertices.GetVector3(3*face.Vertices[idx], &vec3)
  292. positions.AppendVector3(&vec3)
  293. // Copy vertex normal and append to geometry
  294. if face.Normals[idx] != invINDEX {
  295. dec.Normals.GetVector3(3*face.Normals[idx], &vec3)
  296. normals.AppendVector3(&vec3)
  297. }
  298. // Copy vertex uv and append to geometry
  299. if face.Uvs[idx] != invINDEX {
  300. dec.Uvs.GetVector2(2*face.Uvs[idx], &vec2)
  301. uvs.AppendVector2(&vec2)
  302. }
  303. indices.Append(uint32(pos))
  304. }
  305. var group *geometry.Group
  306. matName := ""
  307. matIndex := 0
  308. for _, face := range obj.Faces {
  309. // If face material changed, starts a new group
  310. if face.Material != matName {
  311. group = geom.AddGroup(indices.Size(), 0, matIndex)
  312. matName = face.Material
  313. matIndex++
  314. }
  315. // Copy face vertices to geometry
  316. for idx := 1; idx < len(face.Vertices)-1; idx++ {
  317. copyVertex(&face, 0)
  318. copyVertex(&face, idx)
  319. copyVertex(&face, idx+1)
  320. group.Count += 3
  321. }
  322. }
  323. geom.SetIndices(indices)
  324. geom.AddVBO(gls.NewVBO(positions).AddAttrib(gls.VertexPosition))
  325. geom.AddVBO(gls.NewVBO(normals).AddAttrib(gls.VertexNormal))
  326. geom.AddVBO(gls.NewVBO(uvs).AddAttrib(gls.VertexTexcoord))
  327. return geom, nil
  328. }
  329. // loadTex loads textures described in the material descriptor into the
  330. // specified material
  331. func (dec *Decoder) loadTex(mat *material.Material, desc *Material) error {
  332. // Checks if material descriptor specified texture
  333. if desc.MapKd == "" {
  334. return nil
  335. }
  336. // Get texture file path
  337. // If texture file path is not absolute assumes it is relative
  338. // to the directory of the material file
  339. var texPath string
  340. if filepath.IsAbs(desc.MapKd) {
  341. texPath = desc.MapKd
  342. } else {
  343. texPath = filepath.Join(dec.mtlDir, desc.MapKd)
  344. }
  345. // Try to load texture from image file
  346. tex, err := texture.NewTexture2DFromImage(texPath)
  347. if err != nil {
  348. return err
  349. }
  350. mat.AddTexture(tex)
  351. return nil
  352. }
  353. // parse reads the lines from the specified reader and dispatch them
  354. // to the specified line parser.
  355. func (dec *Decoder) parse(reader io.Reader, parseLine func(string) error) error {
  356. bufin := bufio.NewReader(reader)
  357. dec.line = 1
  358. for {
  359. // Reads next line and abort on errors (not EOF)
  360. line, err := bufin.ReadString('\n')
  361. if err != nil && err != io.EOF {
  362. return err
  363. }
  364. // Parses the line
  365. line = strings.Trim(line, blanks)
  366. perr := parseLine(line)
  367. if perr != nil {
  368. return perr
  369. }
  370. // If EOF ends of parsing.
  371. if err == io.EOF {
  372. break
  373. }
  374. dec.line++
  375. }
  376. return nil
  377. }
  378. // Parses obj file line, dispatching to specific parsers
  379. func (dec *Decoder) parseObjLine(line string) error {
  380. // Ignore empty lines
  381. fields := strings.Fields(line)
  382. if len(fields) == 0 {
  383. return nil
  384. }
  385. // Ignore comment lines
  386. ltype := fields[0]
  387. if strings.HasPrefix(ltype, "#") {
  388. return nil
  389. }
  390. switch ltype {
  391. // Material library
  392. case "mtllib":
  393. return dec.parseMatlib(fields[1:])
  394. // Object name
  395. case "o":
  396. return dec.parseObject(fields[1:])
  397. // Group names. We are considering "group" the same as "object"
  398. // This may not be right
  399. case "g":
  400. return dec.parseObject(fields[1:])
  401. // Vertex coordinate
  402. case "v":
  403. return dec.parseVertex(fields[1:])
  404. // Vertex normal coordinate
  405. case "vn":
  406. return dec.parseNormal(fields[1:])
  407. // Vertex texture coordinate
  408. case "vt":
  409. return dec.parseTex(fields[1:])
  410. // Face vertex
  411. case "f":
  412. return dec.parseFace(fields[1:])
  413. // Use material
  414. case "usemtl":
  415. return dec.parseUsemtl(fields[1:])
  416. // Smooth
  417. case "s":
  418. return dec.parseSmooth(fields[1:])
  419. default:
  420. dec.appendWarn(objType, "field not supported: "+ltype)
  421. }
  422. return nil
  423. }
  424. // Parses a mtllib line:
  425. // mtllib <name>
  426. func (dec *Decoder) parseMatlib(fields []string) error {
  427. if len(fields) < 1 {
  428. return errors.New("Material library (mtllib) with no fields")
  429. }
  430. dec.Matlib = fields[0]
  431. return nil
  432. }
  433. // Parses an object line:
  434. // o <name>
  435. func (dec *Decoder) parseObject(fields []string) error {
  436. if len(fields) < 1 {
  437. return errors.New("Object line (o) with no fields")
  438. }
  439. dec.Objects = append(dec.Objects, makeObject(fields[0]))
  440. dec.objCurrent = &dec.Objects[len(dec.Objects)-1]
  441. return nil
  442. }
  443. // makes an Object with name.
  444. func makeObject(name string) Object {
  445. var ob Object
  446. ob.Name = name
  447. ob.Faces = make([]Face, 0)
  448. ob.materials = make([]string, 0)
  449. return ob
  450. }
  451. // Parses a vertex position line
  452. // v <x> <y> <z> [w]
  453. func (dec *Decoder) parseVertex(fields []string) error {
  454. if len(fields) < 3 {
  455. return errors.New("Less than 3 vertices in 'v' line")
  456. }
  457. for _, f := range fields[:3] {
  458. val, err := strconv.ParseFloat(f, 32)
  459. if err != nil {
  460. return err
  461. }
  462. dec.Vertices.Append(float32(val))
  463. }
  464. return nil
  465. }
  466. // Parses a vertex normal line
  467. // vn <x> <y> <z>
  468. func (dec *Decoder) parseNormal(fields []string) error {
  469. if len(fields) < 3 {
  470. return errors.New("Less than 3 normals in 'vn' line")
  471. }
  472. for _, f := range fields[:3] {
  473. val, err := strconv.ParseFloat(f, 32)
  474. if err != nil {
  475. return err
  476. }
  477. dec.Normals.Append(float32(val))
  478. }
  479. return nil
  480. }
  481. // Parses a vertex texture coordinate line:
  482. // vt <u> <v> <w>
  483. func (dec *Decoder) parseTex(fields []string) error {
  484. if len(fields) < 2 {
  485. return errors.New("Less than 2 texture coords. in 'vt' line")
  486. }
  487. for _, f := range fields[:2] {
  488. val, err := strconv.ParseFloat(f, 32)
  489. if err != nil {
  490. return err
  491. }
  492. dec.Uvs.Append(float32(val))
  493. }
  494. return nil
  495. }
  496. // parseFace parses a face decription line:
  497. // f v1[/vt1][/vn1] v2[/vt2][/vn2] v3[/vt3][/vn3] ...
  498. func (dec *Decoder) parseFace(fields []string) error {
  499. // NOTE(quillaja): this wasn't really part of the original issue-29
  500. if dec.objCurrent == nil {
  501. // if a face line is encountered before a group (g) or object (o),
  502. // create a new "default" object. This 'handles' the case when
  503. // a g or o line is not specified (allowed in OBJ format)
  504. dec.parseObject([]string{fmt.Sprintf("unnamed%d", dec.line)})
  505. }
  506. // If current object has no material, appends last material if defined
  507. if len(dec.objCurrent.materials) == 0 && dec.matCurrent != nil {
  508. dec.objCurrent.materials = append(dec.objCurrent.materials, dec.matCurrent.Name)
  509. }
  510. if len(fields) < 3 {
  511. return dec.formatError("Face line with less 3 fields")
  512. }
  513. var face Face
  514. face.Vertices = make([]int, len(fields))
  515. face.Uvs = make([]int, len(fields))
  516. face.Normals = make([]int, len(fields))
  517. if dec.matCurrent != nil {
  518. face.Material = dec.matCurrent.Name
  519. } else {
  520. // TODO (quillaja): do something better than spamming warnings for each line
  521. // dec.appendWarn(objType, "No material defined")
  522. face.Material = "internal default" // causes error on in NewGeom() if ""
  523. // dec.matCurrent = defaultMat
  524. }
  525. face.Smooth = dec.smoothCurrent
  526. for pos, f := range fields {
  527. // Separate the current field in its components: v vt vn
  528. vfields := strings.Split(f, "/")
  529. if len(vfields) < 1 {
  530. return dec.formatError("Face field with no parts")
  531. }
  532. // Get the index of this vertex position (must always exist)
  533. val, err := strconv.ParseInt(vfields[0], 10, 32)
  534. if err != nil {
  535. return err
  536. }
  537. // Positive index is an absolute vertex index
  538. if val > 0 {
  539. face.Vertices[pos] = int(val - 1)
  540. // Negative vertex index is relative to the last parsed vertex
  541. } else if val < 0 {
  542. current := (len(dec.Vertices) / 3) - 1
  543. face.Vertices[pos] = current + int(val) + 1
  544. // Vertex index could never be 0
  545. } else {
  546. return dec.formatError("Face vertex index value equal to 0")
  547. }
  548. // Get the index of this vertex UV coordinate (optional)
  549. if len(vfields) > 1 && len(vfields[1]) > 0 {
  550. val, err := strconv.ParseInt(vfields[1], 10, 32)
  551. if err != nil {
  552. return err
  553. }
  554. // Positive index is an absolute UV index
  555. if val > 0 {
  556. face.Uvs[pos] = int(val - 1)
  557. // Negative vertex index is relative to the last parsed uv
  558. } else if val < 0 {
  559. current := (len(dec.Uvs) / 2) - 1
  560. face.Uvs[pos] = current + int(val) + 1
  561. // UV index could never be 0
  562. } else {
  563. return dec.formatError("Face uv index value equal to 0")
  564. }
  565. } else {
  566. face.Uvs[pos] = invINDEX
  567. }
  568. // Get the index of this vertex normal (optional)
  569. if len(vfields) >= 3 {
  570. val, err = strconv.ParseInt(vfields[2], 10, 32)
  571. if err != nil {
  572. return err
  573. }
  574. // Positive index is an absolute normal index
  575. if val > 0 {
  576. face.Normals[pos] = int(val - 1)
  577. // Negative vertex index is relative to the last parsed normal
  578. } else if val < 0 {
  579. current := (len(dec.Normals) / 3) - 1
  580. face.Normals[pos] = current + int(val) + 1
  581. // Normal index could never be 0
  582. } else {
  583. return dec.formatError("Face normal index value equal to 0")
  584. }
  585. } else {
  586. face.Normals[pos] = invINDEX
  587. }
  588. }
  589. // Appends this face to the current object
  590. dec.objCurrent.Faces = append(dec.objCurrent.Faces, face)
  591. return nil
  592. }
  593. // parseUsemtl parses a "usemtl" decription line:
  594. // usemtl <name>
  595. func (dec *Decoder) parseUsemtl(fields []string) error {
  596. if len(fields) < 1 {
  597. return dec.formatError("Usemtl with no fields")
  598. }
  599. // NOTE(quillaja): see similar nil test in parseFace()
  600. if dec.objCurrent == nil {
  601. dec.parseObject([]string{fmt.Sprintf("unnamed%d", dec.line)})
  602. }
  603. // Checks if this material has already been parsed
  604. name := fields[0]
  605. mat := dec.Materials[name]
  606. // Creates material descriptor
  607. if mat == nil {
  608. mat = new(Material)
  609. mat.Name = name
  610. dec.Materials[name] = mat
  611. }
  612. dec.objCurrent.materials = append(dec.objCurrent.materials, name)
  613. // Set this as the current material
  614. dec.matCurrent = mat
  615. return nil
  616. }
  617. // parseSmooth parses a "s" decription line:
  618. // s <0|1>
  619. func (dec *Decoder) parseSmooth(fields []string) error {
  620. if len(fields) < 1 {
  621. return dec.formatError("'s' with no fields")
  622. }
  623. if fields[0] == "0" || fields[0] == "off" {
  624. dec.smoothCurrent = false
  625. return nil
  626. }
  627. if fields[0] == "1" || fields[0] == "on" {
  628. dec.smoothCurrent = true
  629. return nil
  630. }
  631. return dec.formatError("'s' with invalid value")
  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. }