obj.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  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. fmt.Println("Hi!", reader)
  360. bufin := bufio.NewReader(reader)
  361. dec.line = 1
  362. for {
  363. // Reads next line and abort on errors (not EOF)
  364. line, err := bufin.ReadString('\n')
  365. if err != nil && err != io.EOF {
  366. return err
  367. }
  368. // Parses the line
  369. line = strings.Trim(line, blanks)
  370. perr := parseLine(line)
  371. if perr != nil {
  372. return perr
  373. }
  374. // If EOF ends of parsing.
  375. if err == io.EOF {
  376. break
  377. }
  378. dec.line++
  379. }
  380. return nil
  381. }
  382. // Parses obj file line, dispatching to specific parsers
  383. func (dec *Decoder) parseObjLine(line string) error {
  384. // Ignore empty lines
  385. fields := strings.Fields(line)
  386. if len(fields) == 0 {
  387. return nil
  388. }
  389. // Ignore comment lines
  390. ltype := fields[0]
  391. if strings.HasPrefix(ltype, "#") {
  392. return nil
  393. }
  394. switch ltype {
  395. // Material library
  396. case "mtllib":
  397. return dec.parseMatlib(fields[1:])
  398. // Object name
  399. case "o":
  400. return dec.parseObject(fields[1:])
  401. // Group names. We are considering "group" the same as "object"
  402. // This may not be right
  403. case "g":
  404. return dec.parseObject(fields[1:])
  405. // Vertex coordinate
  406. case "v":
  407. return dec.parseVertex(fields[1:])
  408. // Vertex normal coordinate
  409. case "vn":
  410. return dec.parseNormal(fields[1:])
  411. // Vertex texture coordinate
  412. case "vt":
  413. return dec.parseTex(fields[1:])
  414. // Face vertex
  415. case "f":
  416. return dec.parseFace(fields[1:])
  417. // Use material
  418. case "usemtl":
  419. return dec.parseUsemtl(fields[1:])
  420. // Smooth
  421. case "s":
  422. return dec.parseSmooth(fields[1:])
  423. default:
  424. dec.appendWarn(objType, "field not supported: "+ltype)
  425. }
  426. return nil
  427. }
  428. // Parses a mtllib line:
  429. // mtllib <name>
  430. func (dec *Decoder) parseMatlib(fields []string) error {
  431. if len(fields) < 1 {
  432. return errors.New("Material library (mtllib) with no fields")
  433. }
  434. dec.Matlib = fields[0]
  435. return nil
  436. }
  437. // Parses an object line:
  438. // o <name>
  439. func (dec *Decoder) parseObject(fields []string) error {
  440. if len(fields) < 1 {
  441. return errors.New("Object line (o) with no fields")
  442. }
  443. dec.Objects = append(dec.Objects, makeObject(fields[0]))
  444. dec.objCurrent = &dec.Objects[len(dec.Objects)-1]
  445. return nil
  446. }
  447. // makes an Object with name.
  448. func makeObject(name string) Object {
  449. var ob Object
  450. ob.Name = name
  451. ob.Faces = make([]Face, 0)
  452. ob.materials = make([]string, 0)
  453. return ob
  454. }
  455. // Parses a vertex position line
  456. // v <x> <y> <z> [w]
  457. func (dec *Decoder) parseVertex(fields []string) error {
  458. if len(fields) < 3 {
  459. return errors.New("Less than 3 vertices in 'v' line")
  460. }
  461. for _, f := range fields[:3] {
  462. val, err := strconv.ParseFloat(f, 32)
  463. if err != nil {
  464. return err
  465. }
  466. dec.Vertices.Append(float32(val))
  467. }
  468. return nil
  469. }
  470. // Parses a vertex normal line
  471. // vn <x> <y> <z>
  472. func (dec *Decoder) parseNormal(fields []string) error {
  473. if len(fields) < 3 {
  474. return errors.New("Less than 3 normals in 'vn' line")
  475. }
  476. for _, f := range fields[:3] {
  477. val, err := strconv.ParseFloat(f, 32)
  478. if err != nil {
  479. return err
  480. }
  481. dec.Normals.Append(float32(val))
  482. }
  483. return nil
  484. }
  485. // Parses a vertex texture coordinate line:
  486. // vt <u> <v> <w>
  487. func (dec *Decoder) parseTex(fields []string) error {
  488. if len(fields) < 2 {
  489. return errors.New("Less than 2 texture coords. in 'vt' line")
  490. }
  491. for _, f := range fields[:2] {
  492. val, err := strconv.ParseFloat(f, 32)
  493. if err != nil {
  494. return err
  495. }
  496. dec.Uvs.Append(float32(val))
  497. }
  498. return nil
  499. }
  500. // parseFace parses a face decription line:
  501. // f v1[/vt1][/vn1] v2[/vt2][/vn2] v3[/vt3][/vn3] ...
  502. func (dec *Decoder) parseFace(fields []string) error {
  503. // NOTE(quillaja): this wasn't really part of the original issue-29
  504. if dec.objCurrent == nil {
  505. // if a face line is encountered before a group (g) or object (o),
  506. // create a new "default" object. This 'handles' the case when
  507. // a g or o line is not specified (allowed in OBJ format)
  508. dec.parseObject([]string{fmt.Sprintf("unnamed%d", dec.line)})
  509. }
  510. // If current object has no material, appends last material if defined
  511. if len(dec.objCurrent.materials) == 0 && dec.matCurrent != nil {
  512. dec.objCurrent.materials = append(dec.objCurrent.materials, dec.matCurrent.Name)
  513. }
  514. if len(fields) < 3 {
  515. return dec.formatError("Face line with less 3 fields")
  516. }
  517. var face Face
  518. face.Vertices = make([]int, len(fields))
  519. face.Uvs = make([]int, len(fields))
  520. face.Normals = make([]int, len(fields))
  521. if dec.matCurrent != nil {
  522. face.Material = dec.matCurrent.Name
  523. } else {
  524. // TODO (quillaja): do something better than spamming warnings for each line
  525. // dec.appendWarn(objType, "No material defined")
  526. face.Material = "internal default" // causes error on in NewGeom() if ""
  527. // dec.matCurrent = defaultMat
  528. }
  529. face.Smooth = dec.smoothCurrent
  530. for pos, f := range fields {
  531. // Separate the current field in its components: v vt vn
  532. vfields := strings.Split(f, "/")
  533. if len(vfields) < 1 {
  534. return dec.formatError("Face field with no parts")
  535. }
  536. // Get the index of this vertex position (must always exist)
  537. val, err := strconv.ParseInt(vfields[0], 10, 32)
  538. if err != nil {
  539. return err
  540. }
  541. // Positive index is an absolute vertex index
  542. if val > 0 {
  543. face.Vertices[pos] = int(val - 1)
  544. // Negative vertex index is relative to the last parsed vertex
  545. } else if val < 0 {
  546. current := (len(dec.Vertices) / 3) - 1
  547. face.Vertices[pos] = current + int(val) + 1
  548. // Vertex index could never be 0
  549. } else {
  550. return dec.formatError("Face vertex index value equal to 0")
  551. }
  552. // Get the index of this vertex UV coordinate (optional)
  553. if len(vfields) > 1 && len(vfields[1]) > 0 {
  554. val, err := strconv.ParseInt(vfields[1], 10, 32)
  555. if err != nil {
  556. return err
  557. }
  558. // Positive index is an absolute UV index
  559. if val > 0 {
  560. face.Uvs[pos] = int(val - 1)
  561. // Negative vertex index is relative to the last parsed uv
  562. } else if val < 0 {
  563. current := (len(dec.Uvs) / 2) - 1
  564. face.Uvs[pos] = current + int(val) + 1
  565. // UV index could never be 0
  566. } else {
  567. return dec.formatError("Face uv index value equal to 0")
  568. }
  569. } else {
  570. face.Uvs[pos] = invINDEX
  571. }
  572. // Get the index of this vertex normal (optional)
  573. if len(vfields) >= 3 {
  574. val, err = strconv.ParseInt(vfields[2], 10, 32)
  575. if err != nil {
  576. return err
  577. }
  578. // Positive index is an absolute normal index
  579. if val > 0 {
  580. face.Normals[pos] = int(val - 1)
  581. // Negative vertex index is relative to the last parsed normal
  582. } else if val < 0 {
  583. current := (len(dec.Normals) / 3) - 1
  584. face.Normals[pos] = current + int(val) + 1
  585. // Normal index could never be 0
  586. } else {
  587. return dec.formatError("Face normal index value equal to 0")
  588. }
  589. } else {
  590. face.Normals[pos] = invINDEX
  591. }
  592. }
  593. // Appends this face to the current object
  594. dec.objCurrent.Faces = append(dec.objCurrent.Faces, face)
  595. return nil
  596. }
  597. // parseUsemtl parses a "usemtl" decription line:
  598. // usemtl <name>
  599. func (dec *Decoder) parseUsemtl(fields []string) error {
  600. if len(fields) < 1 {
  601. return dec.formatError("Usemtl with no fields")
  602. }
  603. // NOTE(quillaja): see similar nil test in parseFace()
  604. if dec.objCurrent == nil {
  605. dec.parseObject([]string{fmt.Sprintf("unnamed%d", dec.line)})
  606. }
  607. // Checks if this material has already been parsed
  608. name := fields[0]
  609. mat := dec.Materials[name]
  610. // Creates material descriptor
  611. if mat == nil {
  612. mat = new(Material)
  613. mat.Name = name
  614. dec.Materials[name] = mat
  615. }
  616. dec.objCurrent.materials = append(dec.objCurrent.materials, name)
  617. // Set this as the current material
  618. dec.matCurrent = mat
  619. return nil
  620. }
  621. // parseSmooth parses a "s" decription line:
  622. // s <0|1>
  623. func (dec *Decoder) parseSmooth(fields []string) error {
  624. if len(fields) < 1 {
  625. return dec.formatError("'s' with no fields")
  626. }
  627. if fields[0] == "0" || fields[0] == "off" {
  628. dec.smoothCurrent = false
  629. return nil
  630. }
  631. dec.smoothCurrent = true
  632. return nil
  633. }
  634. /******************************************************************************
  635. mtl parse functions
  636. */
  637. // Parses material file line, dispatching to specific parsers
  638. func (dec *Decoder) parseMtlLine(line string) error {
  639. // Ignore empty lines
  640. fields := strings.Fields(line)
  641. if len(fields) == 0 {
  642. return nil
  643. }
  644. // Ignore comment lines
  645. ltype := fields[0]
  646. if strings.HasPrefix(ltype, "#") {
  647. return nil
  648. }
  649. switch ltype {
  650. case "newmtl":
  651. return dec.parseNewmtl(fields[1:])
  652. case "d":
  653. return dec.parseDissolve(fields[1:])
  654. case "Ka":
  655. return dec.parseKa(fields[1:])
  656. case "Kd":
  657. return dec.parseKd(fields[1:])
  658. case "Ke":
  659. return dec.parseKe(fields[1:])
  660. case "Ks":
  661. return dec.parseKs(fields[1:])
  662. case "Ni":
  663. return dec.parseNi(fields[1:])
  664. case "Ns":
  665. return dec.parseNs(fields[1:])
  666. case "illum":
  667. return dec.parseIllum(fields[1:])
  668. case "map_Kd":
  669. return dec.parseMapKd(fields[1:])
  670. default:
  671. dec.appendWarn(mtlType, "field not supported: "+ltype)
  672. }
  673. return nil
  674. }
  675. // Parses new material definition
  676. // newmtl <mat_name>
  677. func (dec *Decoder) parseNewmtl(fields []string) error {
  678. if len(fields) < 1 {
  679. return dec.formatError("newmtl with no fields")
  680. }
  681. // Checks if material has already been seen
  682. name := fields[0]
  683. mat := dec.Materials[name]
  684. // Creates material descriptor
  685. if mat == nil {
  686. mat = new(Material)
  687. mat.Name = name
  688. dec.Materials[name] = mat
  689. }
  690. dec.matCurrent = mat
  691. return nil
  692. }
  693. // Parses the dissolve factor (opacity)
  694. // d <factor>
  695. func (dec *Decoder) parseDissolve(fields []string) error {
  696. if len(fields) < 1 {
  697. return dec.formatError("'d' with no fields")
  698. }
  699. val, err := strconv.ParseFloat(fields[0], 32)
  700. if err != nil {
  701. return dec.formatError("'d' parse float error")
  702. }
  703. dec.matCurrent.Opacity = float32(val)
  704. return nil
  705. }
  706. // Parses ambient reflectivity:
  707. // Ka r g b
  708. func (dec *Decoder) parseKa(fields []string) error {
  709. if len(fields) < 3 {
  710. return dec.formatError("'Ka' with less than 3 fields")
  711. }
  712. var colors [3]float32
  713. for pos, f := range fields[:3] {
  714. val, err := strconv.ParseFloat(f, 32)
  715. if err != nil {
  716. return err
  717. }
  718. colors[pos] = float32(val)
  719. }
  720. dec.matCurrent.Ambient.Set(colors[0], colors[1], colors[2])
  721. return nil
  722. }
  723. // Parses diffuse reflectivity:
  724. // Kd r g b
  725. func (dec *Decoder) parseKd(fields []string) error {
  726. if len(fields) < 3 {
  727. return dec.formatError("'Kd' with less than 3 fields")
  728. }
  729. var colors [3]float32
  730. for pos, f := range fields[:3] {
  731. val, err := strconv.ParseFloat(f, 32)
  732. if err != nil {
  733. return err
  734. }
  735. colors[pos] = float32(val)
  736. }
  737. dec.matCurrent.Diffuse.Set(colors[0], colors[1], colors[2])
  738. return nil
  739. }
  740. // Parses emissive color:
  741. // Ke r g b
  742. func (dec *Decoder) parseKe(fields []string) error {
  743. if len(fields) < 3 {
  744. return dec.formatError("'Ke' with less than 3 fields")
  745. }
  746. var colors [3]float32
  747. for pos, f := range fields[:3] {
  748. val, err := strconv.ParseFloat(f, 32)
  749. if err != nil {
  750. return err
  751. }
  752. colors[pos] = float32(val)
  753. }
  754. dec.matCurrent.Emissive.Set(colors[0], colors[1], colors[2])
  755. return nil
  756. }
  757. // Parses specular reflectivity:
  758. // Ks r g b
  759. func (dec *Decoder) parseKs(fields []string) error {
  760. if len(fields) < 3 {
  761. return dec.formatError("'Ks' with less than 3 fields")
  762. }
  763. var colors [3]float32
  764. for pos, f := range fields[:3] {
  765. val, err := strconv.ParseFloat(f, 32)
  766. if err != nil {
  767. return err
  768. }
  769. colors[pos] = float32(val)
  770. }
  771. dec.matCurrent.Specular.Set(colors[0], colors[1], colors[2])
  772. return nil
  773. }
  774. // Parses optical density, also known as index of refraction
  775. // Ni <optical_density>
  776. func (dec *Decoder) parseNi(fields []string) error {
  777. if len(fields) < 1 {
  778. return dec.formatError("'Ni' with no fields")
  779. }
  780. val, err := strconv.ParseFloat(fields[0], 32)
  781. if err != nil {
  782. return dec.formatError("'d' parse float error")
  783. }
  784. dec.matCurrent.Refraction = float32(val)
  785. return nil
  786. }
  787. // Parses specular exponent
  788. // Ns <specular_exponent>
  789. func (dec *Decoder) parseNs(fields []string) error {
  790. if len(fields) < 1 {
  791. return dec.formatError("'Ns' with no fields")
  792. }
  793. val, err := strconv.ParseFloat(fields[0], 32)
  794. if err != nil {
  795. return dec.formatError("'d' parse float error")
  796. }
  797. dec.matCurrent.Shininess = float32(val)
  798. return nil
  799. }
  800. // Parses illumination model (0 to 10)
  801. // illum <ilum_#>
  802. func (dec *Decoder) parseIllum(fields []string) error {
  803. if len(fields) < 1 {
  804. return dec.formatError("'illum' with no fields")
  805. }
  806. val, err := strconv.ParseUint(fields[0], 10, 32)
  807. if err != nil {
  808. return dec.formatError("'d' parse int error")
  809. }
  810. dec.matCurrent.Illum = int(val)
  811. return nil
  812. }
  813. // Parses color texture linked to the diffuse reflectivity of the material
  814. // map_Kd [-options] <filename>
  815. func (dec *Decoder) parseMapKd(fields []string) error {
  816. if len(fields) < 1 {
  817. return dec.formatError("No fields")
  818. }
  819. dec.matCurrent.MapKd = fields[0]
  820. return nil
  821. }
  822. func (dec *Decoder) formatError(msg string) error {
  823. return fmt.Errorf("%s in line:%d", msg, dec.line)
  824. }
  825. func (dec *Decoder) appendWarn(ftype string, msg string) {
  826. wline := fmt.Sprintf("%s(%d): %s", ftype, dec.line, msg)
  827. dec.Warnings = append(dec.Warnings, wline)
  828. }