|
| 1 | +/** |
| 2 | + * @author Richard Davey <rich@photonstorm.com> |
| 3 | + * @copyright 2020 Photon Storm Ltd. |
| 4 | + * @license {@link https://opensource.org/licenses/MIT|MIT License} |
| 5 | + */ |
| 6 | + |
| 7 | +var GetColor = require('../../display/color/GetColor'); |
| 8 | + |
| 9 | +/** |
| 10 | + * Takes a Wavefront Material file and extracts the diffuse reflectivity of the named |
| 11 | + * materials, converts them to integer color values and returns them. |
| 12 | + * |
| 13 | + * This is used internally by the `addOBJ` and `addModel` methods, but is exposed for |
| 14 | + * public consumption as well. |
| 15 | + * |
| 16 | + * Note this only works with diffuse values, specified in the `Kd r g b` format, where |
| 17 | + * `g` and `b` are optional, but `r` is required. It does not support spectral rfl files, |
| 18 | + * or any other material statement (such as `Ka` or `Ks`) |
| 19 | + * |
| 20 | + * @method Phaser.Geom.Mesh.ParseObjMaterial |
| 21 | + * @since 3.50.0 |
| 22 | + * |
| 23 | + * @param {string} mtl - The OBJ MTL file as a raw string, i.e. loaded via `this.load.text`. |
| 24 | + * |
| 25 | + * @return {object} The parsed material colors, where each property of the object matches the material name. |
| 26 | + */ |
| 27 | +var ParseObjMaterial = function (mtl) |
| 28 | +{ |
| 29 | + var output = {}; |
| 30 | + |
| 31 | + var lines = mtl.split('\n'); |
| 32 | + |
| 33 | + var currentMaterial = ''; |
| 34 | + |
| 35 | + for (var i = 0; i < lines.length; i++) |
| 36 | + { |
| 37 | + var line = lines[i].trim(); |
| 38 | + |
| 39 | + if (line.indexOf('#') === 0 || line === '') |
| 40 | + { |
| 41 | + continue; |
| 42 | + } |
| 43 | + |
| 44 | + var lineItems = line.replace(/\s\s+/g, ' ').trim().split(' '); |
| 45 | + |
| 46 | + switch (lineItems[0].toLowerCase()) |
| 47 | + { |
| 48 | + case 'newmtl': |
| 49 | + { |
| 50 | + currentMaterial = lineItems[1]; |
| 51 | + break; |
| 52 | + } |
| 53 | + |
| 54 | + // The diffuse reflectivity of the current material |
| 55 | + // Support r, [g], [b] format, where g and b are optional |
| 56 | + case 'kd': |
| 57 | + { |
| 58 | + var r = Math.floor(lineItems[1] * 255); |
| 59 | + var g = (lineItems.length >= 2) ? Math.floor(lineItems[2] * 255) : r; |
| 60 | + var b = (lineItems.length >= 3) ? Math.floor(lineItems[3] * 255) : r; |
| 61 | + |
| 62 | + output[currentMaterial] = GetColor(r, g, b); |
| 63 | + |
| 64 | + break; |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + return output; |
| 70 | +}; |
| 71 | + |
| 72 | +module.exports = ParseObjMaterial; |
0 commit comments