obj.go 24 KB

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