obj.go 20 KB

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