This commit is contained in:
Sean Lilley 2017-04-18 11:56:08 -04:00
parent a6ff230fc3
commit ce5221c80a
12 changed files with 676 additions and 401 deletions

View File

@ -4,16 +4,16 @@ module.exports = Material;
function Material() { function Material() {
this.ambientColor = [0.0, 0.0, 0.0, 1.0]; // Ka this.ambientColor = [0.0, 0.0, 0.0, 1.0]; // Ka
this.emissionColor = [0.0, 0.0, 0.0, 1.0]; // Ke this.emissiveColor = [0.0, 0.0, 0.0, 1.0]; // Ke
this.diffuseColor = [0.5, 0.5, 0.5, 1.0]; // Kd this.diffuseColor = [0.5, 0.5, 0.5, 1.0]; // Kd
this.specularColor = [0.0, 0.0, 0.0, 1.0]; // Ks this.specularColor = [0.0, 0.0, 0.0, 1.0]; // Ks
this.specularShininess = 0.0; // Ns this.specularShininess = 0.0; // Ns
this.alpha = 1.0; // d / Tr this.alpha = 1.0; // d / Tr
this.ambientTexture = undefined; // map_Ka this.ambientTexture = undefined; // map_Ka
this.emissionTexture = undefined; // map_Ke this.emissiveTexture = undefined; // map_Ke
this.diffuseTexture = undefined; // map_Kd this.diffuseTexture = undefined; // map_Kd
this.specularTexture = undefined; // map_Ks this.specularTexture = undefined; // map_Ks
this.specularShininessMap = undefined; // map_Ns this.specularShininessTexture = undefined; // map_Ns
this.normalMap = undefined; // map_Bump this.normalTexture = undefined; // map_Bump
this.alphaMap = undefined; // map_d this.alphaTexture = undefined; // map_d
} }

View File

@ -1,6 +1,7 @@
'use strict'; 'use strict';
var Cesium = require('cesium'); var Cesium = require('cesium');
var path = require('path'); var path = require('path');
var PNG = require('pngjs').PNG;
var Material = require('./Material'); var Material = require('./Material');
var defined = Cesium.defined; var defined = Cesium.defined;
@ -13,160 +14,463 @@ module.exports = createGltf;
* Create a glTF from obj data. * Create a glTF from obj data.
* *
* @param {Object} objData Output of obj.js, containing an array of nodes containing geometry information, materials, and images. * @param {Object} objData Output of obj.js, containing an array of nodes containing geometry information, materials, and images.
* @returns {Object} A glTF asset with the KHR_materials_common extension. * @param {Object} options An object with the following properties:
* @param {Boolean} options.logger A callback function for handling logged messages. Defaults to console.log.
* @returns {Object} A glTF asset.
* *
* @private * @private
*/ */
function createGltf(objData) { function createGltf(objData, options) {
var nodes = objData.nodes; var nodes = objData.nodes;
var materials = objData.materials; var materials = objData.materials;
var images = objData.images; var images = objData.images;
var sceneId = 'scene';
var samplerId = 'sampler';
var bufferId = 'buffer';
var vertexBufferViewId = 'bufferView_vertex';
var indexBufferViewId = 'bufferView_index';
var gltf = { var gltf = {
accessors : {}, accessors : [],
asset : {}, asset : {},
buffers : {}, buffers : [],
bufferViews : {}, bufferViews : [],
extensionsUsed : ['KHR_materials_common'], images : [],
images : {}, materials : [],
materials : {}, meshes : [],
meshes : {}, nodes : [],
nodes : {}, samplers : [],
samplers : {}, scene : 0,
scene : sceneId, scenes : [],
scenes : {}, textures : []
textures : {}
}; };
gltf.asset = { gltf.asset = {
generator : 'obj2gltf', generator : 'obj2gltf',
profile : { version: '2.0'
api : 'WebGL',
version : '1.0'
},
version: '1.0'
}; };
gltf.scenes[sceneId] = { gltf.scenes.push({
nodes : [] nodes : []
});
var bufferState = {
vertexBuffers : [],
vertexBufferByteOffset : 0,
vertexBufferViewIndex : 0,
indexBuffers : [],
indexBufferByteOffset : 0,
indexBufferViewIndex : 1
}; };
function getImageId(imagePath) { var uint32Indices = requiresUint32Indices(nodes);
return path.basename(imagePath, path.extname(imagePath));
}
function getTextureId(imagePath) { var nodesLength = nodes.length;
if (!defined(imagePath) || !defined(images[imagePath])) { for (var i = 0; i < nodesLength; ++i) {
return undefined; var node = nodes[i];
} var meshes = node.meshes;
return 'texture_' + getImageId(imagePath); var meshesLength = meshes.length;
} var meshIndex;
function createMaterial(material, hasNormals) { if (meshesLength === 1) {
var ambient = defaultValue(defaultValue(getTextureId(material.ambientTexture), material.ambientColor)); meshIndex = addMesh(gltf, materials, images, bufferState, uint32Indices, meshes[0], options);
var diffuse = defaultValue(defaultValue(getTextureId(material.diffuseTexture), material.diffuseColor)); addNode(gltf, node.name, meshIndex);
var emission = defaultValue(defaultValue(getTextureId(material.emissionTexture), material.emissionColor));
var specular = defaultValue(defaultValue(getTextureId(material.specularTexture), material.specularColor));
var alpha = defaultValue(defaultValue(material.alpha), 1.0);
var shininess = defaultValue(material.specularShininess, 0.0);
var hasSpecular = (shininess > 0.0) && (specular[0] > 0.0 || specular[1] > 0.0 || specular[2] > 0.0);
var transparent;
var transparency = 1.0;
if (typeof diffuse === 'string') {
transparency = alpha;
transparent = images[material.diffuseTexture].transparent || (transparency < 1.0);
} else { } else {
diffuse[3] = alpha; // Add meshes as child nodes
transparent = diffuse[3] < 1.0; var parentIndex = addNode(gltf, node.name);
for (var j = 0; j < meshesLength; ++j) {
var mesh = meshes[j];
meshIndex = addMesh(gltf, materials, images, bufferState, uint32Indices, mesh, options);
addNode(gltf, mesh.name, meshIndex, parentIndex);
}
}
} }
var doubleSided = transparent; if (Object.keys(gltf.images).length > 0) {
gltf.samplers.push({
if (!hasNormals) {
// Constant technique only factors in ambient and emission sources - set emission to diffuse
emission = diffuse;
diffuse = [0, 0, 0, 1];
}
var technique = hasNormals ? (hasSpecular ? 'PHONG' : 'LAMBERT') : 'CONSTANT';
return {
extensions : {
KHR_materials_common : {
technique : technique,
transparent : transparent,
doubleSided : doubleSided,
values : {
ambient : ambient,
diffuse : diffuse,
emission : emission,
specular : specular,
shininess : shininess,
transparency : transparency,
transparent : transparent,
doubleSided : doubleSided
}
}
}
};
}
if (Object.keys(images).length > 0) {
gltf.samplers[samplerId] = {
magFilter : WebGLConstants.LINEAR, magFilter : WebGLConstants.LINEAR,
minFilter : WebGLConstants.LINEAR, minFilter : WebGLConstants.LINEAR,
wrapS : WebGLConstants.REPEAT, wrapS : WebGLConstants.REPEAT,
wrapT : WebGLConstants.REPEAT wrapT : WebGLConstants.REPEAT
}; });
} }
for (var imagePath in images) { addBuffers(gltf, bufferState);
if (images.hasOwnProperty(imagePath)) {
var image = images[imagePath];
var imageId = getImageId(imagePath);
var textureId = getTextureId(imagePath);
gltf.images[imageId] = { return gltf;
name : imageId, }
function addBuffers(gltf, bufferState) {
var bufferName = 'buffer';
var vertexBufferViewName = 'bufferView_vertex';
var indexBufferViewName = 'bufferView_index';
var vertexBuffers = bufferState.vertexBuffers;
var indexBuffers = bufferState.indexBuffers;
var vertexBufferByteLength = bufferState.vertexBufferByteOffset;
var indexBufferByteLength = bufferState.indexBufferByteOffset;
var buffers = [];
buffers = buffers.concat(vertexBuffers, indexBuffers);
var buffer = Buffer.concat(buffers);
gltf.buffers.push({
name : bufferName,
byteLength : buffer.byteLength,
extras : {
_obj2gltf : {
source : buffer
}
}
});
gltf.bufferViews.push({
name : vertexBufferViewName,
buffer : 0,
byteLength : vertexBufferByteLength,
byteOffset : 0,
target : WebGLConstants.ARRAY_BUFFER
});
gltf.bufferViews.push({
name : indexBufferViewName,
buffer : 0,
byteLength : indexBufferByteLength,
byteOffset : vertexBufferByteLength,
target : WebGLConstants.ELEMENT_ARRAY_BUFFER
});
}
function getImage(images, imagePath) {
if (!defined(imagePath) || !defined(images[imagePath])) {
return undefined;
}
return images[imagePath];
}
function getImageName(imagePath) {
return path.basename(imagePath, path.extname(imagePath));
}
function getTextureName(imagePath) {
return getImageName(imagePath);
}
function addTexture(gltf, image, imagePath) {
var imageName = getImageName(imagePath);
var textureName = getTextureName(imagePath);
var imageIndex = gltf.images.length;
var textureIndex = gltf.textures.length;
gltf.images.push({
name : imageName,
extras : { extras : {
_obj2gltf : { _obj2gltf : {
source : image.source, source : image.source,
extension : image.extension extension : image.extension
} }
} }
});
gltf.textures.push({
name : textureName,
sampler : 0,
source : imageIndex
});
return textureIndex;
}
function getTextureIndex(gltf, imagePath) {
var name = getTextureName(imagePath);
var textures = gltf.textures;
var length = textures.length;
for (var i = 0; i < length; ++i) {
if (textures[i].name === name) {
return i;
}
}
}
function getTexture(gltf, images, imagePath) {
var image = getImage(images, imagePath);
if (!defined(image)) {
return undefined;
}
var textureIndex = getTextureIndex(gltf, imagePath);
if (!defined(textureIndex)) {
textureIndex = addTexture(gltf, image, imagePath);
}
return textureIndex;
}
function luminance(color) {
var value = 0.2125 * color[0] + 0.7154 * color[1] + 0.0721 * color[2];
return Math.min(value, 1.0); // Clamp just to handle edge cases
}
function addColors(left, right) {
var red = Math.min(left[0] + right[0], 1.0);
var green = Math.min(left[1] + right[1], 1.0);
var blue = Math.min(left[2] + right[2], 1.0);
return [red, green, blue];
}
function resizeChannel(sourcePixels, sourceWidth, sourceHeight, targetWidth, targetHeight) {
// Nearest neighbor sampling
var targetPixels = Buffer.alloc(targetWidth * targetHeight);
var widthRatio = sourceWidth / targetWidth;
var heightRatio = sourceHeight / targetHeight;
for (var y = 0; y < targetHeight; ++y) {
for (var x = 0; x < targetWidth; ++x) {
var targetIndex = y * targetWidth + x;
var sourceY = Math.round(y * heightRatio);
var sourceX = Math.round(x * widthRatio);
var sourceIndex = sourceY * sourceWidth + sourceX;
var sourceValue = sourcePixels.readUInt8(sourceIndex);
targetPixels.writeUInt8(sourceValue, targetIndex);
}
}
return targetPixels;
}
var scratchColor = new Array(3);
function getGrayscaleChannel(image, targetWidth, targetHeight) {
var pixels = image.decoded; // RGBA
var width = image.width;
var height = image.height;
var pixelsLength = width * height;
var grayPixels = Buffer.alloc(pixelsLength);
for (var i = 0; i < pixelsLength; ++i) {
scratchColor[0] = pixels.readUInt8(i * 4);
scratchColor[1] = pixels.readUInt8(i * 4 + 1);
scratchColor[2] = pixels.readUInt8(i * 4 + 2);
var value = luminance(scratchColor) * 255;
grayPixels.writeUInt8(value, i);
}
if (width !== targetWidth || height !== targetHeight) {
grayPixels = resizeChannel(grayPixels, width, height, targetWidth, targetHeight);
}
return grayPixels;
}
function writeChannel(pixels, channel, index, width, height) {
var pixelsLength = width * height;
for (var i = 0; i < pixelsLength; ++i) {
var value = channel.readUInt8(i);
pixels.writeUInt8(value, i * 4 + index);
}
}
function createMetallicRoughnessTexture(gltf, materialName, metallicImage, roughnessImage, options) {
if (!defined(metallicImage) && !defined(roughnessImage)) {
return undefined;
}
if (defined(metallicImage) && !defined(metallicImage.decoded)) {
options.logger('Could not get decoded image data for ' + metallicImage + '. The material will be created without a metallicRoughness texture.');
return undefined;
}
if (defined(roughnessImage) && !defined(roughnessImage.decoded)) {
options.logger('Could not get decoded image data for ' + roughnessImage + '. The material will be created without a metallicRoughness texture.');
return undefined;
}
var width;
var height;
if (defined(metallicImage) && defined(roughnessImage)) {
width = Math.min(metallicImage.width, roughnessImage.width);
height = Math.min(metallicImage.height, roughnessImage.height);
} else if (defined(metallicImage)) {
width = metallicImage.width;
height = metallicImage.height;
} else if (defined(roughnessImage)) {
width = roughnessImage.width;
height = roughnessImage.height;
}
var pixelsLength = width * height;
var pixels = Buffer.alloc(pixelsLength * 4, 0xFF); // Initialize with 4 channels, unused channels will be white
if (defined(metallicImage)) {
// Write into the B channel
var metallicChannel = getGrayscaleChannel(metallicImage, width, height);
writeChannel(pixels, metallicChannel, 2, width, height);
}
if (defined(roughnessImage)) {
// Write into the G channel
var roughnessChannel = getGrayscaleChannel(roughnessImage, width, height);
writeChannel(pixels, roughnessChannel, 1, width, height);
}
var pngInput = {
data : pixels,
width : width,
height : height
}; };
gltf.textures[textureId] = {
format : image.format, var pngOptions = {
internalFormat : image.format, width : width,
sampler : samplerId, height : height,
source : imageId, colorType : 2, // RGB
target : WebGLConstants.TEXTURE_2D, inputHasAlpha : true
type : WebGLConstants.UNSIGNED_BYTE
}; };
var encoded = PNG.sync.write(pngInput, pngOptions);
var image = {
transparent : false,
source : encoded,
extension : '.png'
};
var imageName = materialName + '-' + 'MetallicRoughness';
return addTexture(gltf, image, imageName);
}
function addMaterial(gltf, images, material, name, hasNormals, options) {
// Translate the traditional diffuse/specular material to pbr metallic roughness.
// Specular intensity is extracted from the specular color and treated as the metallic factor.
// Specular shininess is typically an exponent from 0 to 1000, and is converted to a 0-1 range as the roughness factor.
var ambientTexture = getTexture(gltf, images, material.ambientTexture);
var emissiveTexture = getTexture(gltf, images, material.emissiveTexture);
var baseColorTexture = getTexture(gltf, images, material.diffuseTexture);
var normalTexture = getTexture(gltf, images, material.normalTexture);
// Emissive and ambient represent roughly the same concept, so chose whichever is defined.
emissiveTexture = defaultValue(emissiveTexture, ambientTexture);
var metallicImage = getImage(images, material.specularTexture);
var roughnessImage = getImage(images, material.specularShininessTexture);
var metallicRoughnessTexture = createMetallicRoughnessTexture(gltf, name, metallicImage, roughnessImage, options);
var baseColorFactor = [1.0, 1.0, 1.0, 1.0];
var metallicFactor = 1.0;
var roughnessFactor = 1.0;
var emissiveFactor = [1.0, 1.0, 1.0];
if (!defined(baseColorTexture)) {
baseColorFactor = material.diffuseColor;
}
if (!defined(metallicImage)) {
metallicFactor = luminance(material.specularColor);
}
if (!defined(roughnessImage)) {
var specularShininess = material.specularShininess;
if (specularShininess > 1.0) {
specularShininess /= 1000.0;
}
roughnessFactor = specularShininess;
}
if (!defined(emissiveTexture)) {
// If ambient color is [1, 1, 1] assume it is a multiplier and instead change to [0, 0, 0]
var ambientColor = material.ambientColor;
if (ambientColor[0] === 1.0 && ambientColor[1] === 1.0 && ambientColor[2] === 1.0) {
ambientColor = [0.0, 0.0, 0.0, 1.0];
}
emissiveFactor = addColors(material.emissiveColor, ambientColor);
}
var alpha = material.alpha;
baseColorFactor[3] = alpha;
var transparent = alpha < 1.0;
if (defined(material.diffuseTexture)) {
transparent |= images[material.diffuseTexture].transparent;
}
var doubleSided = transparent;
var alphaMode = transparent ? 'BLEND' : 'OPAQUE';
if (!hasNormals) {
// TODO : what is the lighting like for models that don't have normals? Can pbrMetallicRoughness just be undefined? Is setting the baseColor to black a good approach here?
emissiveTexture = baseColorTexture;
emissiveFactor = baseColorFactor.slice(0, 3);
baseColorTexture = undefined;
baseColorFactor = [0.0, 0.0, 0.0, baseColorFactor[3]];
metallicRoughnessTexture = undefined;
metallicFactor = 0.0;
roughnessFactor = 0.0;
normalTexture = undefined;
}
var gltfMaterial = {
name : name,
pbrMetallicRoughness : {
baseColorTexture : baseColorTexture,
baseColorFactor : baseColorFactor,
metallicFactor : metallicFactor,
roughnessFactor : roughnessFactor,
metallicRoughnessTexture : metallicRoughnessTexture
},
normalTexture : normalTexture,
emissiveTexture : emissiveTexture,
emissiveFactor : emissiveFactor,
alphaMode : alphaMode,
doubleSided : doubleSided,
extras : {
_obj2gltf : {
hasNormals : hasNormals
}
}
};
var materialIndex = gltf.materials.length;
gltf.materials.push(gltfMaterial);
return materialIndex;
}
function getMaterialIndex(gltf, name) {
var materials = gltf.materials;
var length = materials.length;
for (var i = 0; i < length; ++i) {
if (materials[i].name === name) {
return i;
}
}
return undefined;
}
function getMaterial(gltf, materials, images, materialName, hasNormals, options) {
if (!defined(materialName)) {
// Create a default material if the primitive does not specify one
materialName = 'default';
}
var material = materials[materialName];
material = defined(material) ? material : new Material();
var materialIndex = getMaterialIndex(gltf, materialName);
// Check if this material has already been added but with incompatible shading
if (defined(materialIndex)) {
var gltfMaterial = gltf.materials[materialIndex];
var normalShading = gltfMaterial.extras._obj2gltf.hasNormals;
if (hasNormals !== normalShading) {
materialName += (hasNormals ? '_shaded' : '_constant');
materialIndex = getMaterialIndex(gltf, materialName);
} }
} }
var vertexBuffers = []; if (!defined(materialIndex)) {
var vertexBufferByteOffset = 0; materialIndex = addMaterial(gltf, images, material, materialName, hasNormals, options);
var indexBuffers = []; }
var indexBufferByteOffset = 0;
var accessorCount = 0;
function addVertexAttribute(array, components) { return materialIndex;
var count = array.length / components; }
function addVertexAttribute(gltf, bufferState, array, components) {
var buffer = array.toFloatBuffer(); var buffer = array.toFloatBuffer();
var count = array.length / components;
var minMax = array.getMinMax(components); var minMax = array.getMinMax(components);
var type = (components === 3 ? 'VEC3' : 'VEC2'); var type = (components === 3 ? 'VEC3' : 'VEC2');
var accessor = { var accessor = {
bufferView : vertexBufferViewId, bufferView : bufferState.vertexBufferViewIndex,
byteOffset : vertexBufferByteOffset, byteOffset : bufferState.vertexBufferByteOffset,
byteStride : 0,
componentType : WebGLConstants.FLOAT, componentType : WebGLConstants.FLOAT,
count : count, count : count,
min : minMax.min, min : minMax.min,
@ -174,38 +478,39 @@ function createGltf(objData) {
type : type type : type
}; };
vertexBufferByteOffset += buffer.length; bufferState.vertexBufferByteOffset += buffer.length;
vertexBuffers.push(buffer); bufferState.vertexBuffers.push(buffer);
var accessorId = 'accessor_' + accessorCount++;
gltf.accessors[accessorId] = accessor;
return accessorId;
}
function addIndexArray(array, uint32Indices) { var accessorIndex = gltf.accessors.length;
gltf.accessors.push(accessor);
return accessorIndex;
}
function addIndexArray(gltf, bufferState, array, uint32Indices) {
var buffer = uint32Indices ? array.toUint32Buffer() : array.toUint16Buffer(); var buffer = uint32Indices ? array.toUint32Buffer() : array.toUint16Buffer();
var componentType = uint32Indices ? WebGLConstants.UNSIGNED_INT : WebGLConstants.UNSIGNED_SHORT; var componentType = uint32Indices ? WebGLConstants.UNSIGNED_INT : WebGLConstants.UNSIGNED_SHORT;
var length = array.length; var count = array.length;
var minMax = array.getMinMax(1); var minMax = array.getMinMax(1);
var accessor = { var accessor = {
bufferView : indexBufferViewId, bufferView : bufferState.indexBufferViewIndex,
byteOffset : indexBufferByteOffset, byteOffset : bufferState.indexBufferByteOffset,
byteStride : 0,
componentType : componentType, componentType : componentType,
count : length, count : count,
min : minMax.min, min : minMax.min,
max : minMax.max, max : minMax.max,
type : 'SCALAR' type : 'SCALAR'
}; };
indexBufferByteOffset += buffer.length; bufferState.indexBufferByteOffset += buffer.length;
indexBuffers.push(buffer); bufferState.indexBuffers.push(buffer);
var accessorId = 'accessor_' + accessorCount++; var accessorIndex = gltf.accessors.length;
gltf.accessors[accessorId] = accessor; gltf.accessors.push(accessor);
return accessorId; return accessorIndex;
} }
function requiresUint32Indices(nodes) { function requiresUint32Indices(nodes) {
var nodesLength = nodes.length; var nodesLength = nodes.length;
for (var i = 0; i < nodesLength; ++i) { for (var i = 0; i < nodesLength; ++i) {
var meshes = nodes[i].meshes; var meshes = nodes[i].meshes;
@ -219,43 +524,22 @@ function createGltf(objData) {
} }
} }
return false; return false;
} }
var uint32Indices = requiresUint32Indices(nodes);
var gltfSceneNodes = gltf.scenes[sceneId].nodes;
var nodesLength = nodes.length;
for (var i = 0; i < nodesLength; ++i) {
// Add node
var node = nodes[i];
var nodeId = node.name;
gltfSceneNodes.push(nodeId);
var gltfNodeMeshes = [];
gltf.nodes[nodeId] = {
name : nodeId,
meshes : gltfNodeMeshes
};
// Add meshes to node
var meshes = node.meshes;
var meshesLength = meshes.length;
for (var j = 0; j < meshesLength; ++j) {
var mesh = meshes[j];
var meshId = mesh.name;
gltfNodeMeshes.push(meshId);
function addMesh(gltf, materials, images, bufferState, uint32Indices, mesh, options) {
var hasPositions = mesh.positions.length > 0; var hasPositions = mesh.positions.length > 0;
var hasNormals = mesh.normals.length > 0; var hasNormals = mesh.normals.length > 0;
var hasUVs = mesh.uvs.length > 0; var hasUVs = mesh.uvs.length > 0;
var attributes = {}; var attributes = {};
if (hasPositions) { if (hasPositions) {
attributes.POSITION = addVertexAttribute(mesh.positions, 3); attributes.POSITION = addVertexAttribute(gltf, bufferState, mesh.positions, 3);
} }
if (hasNormals) { if (hasNormals) {
attributes.NORMAL = addVertexAttribute(mesh.normals, 3); attributes.NORMAL = addVertexAttribute(gltf, bufferState, mesh.normals, 3);
} }
if (hasUVs) { if (hasUVs) {
attributes.TEXCOORD_0 = addVertexAttribute(mesh.uvs, 2); attributes.TEXCOORD_0 = addVertexAttribute(gltf, bufferState, mesh.uvs, 2);
} }
// Unload resources // Unload resources
@ -263,78 +547,52 @@ function createGltf(objData) {
mesh.normals = undefined; mesh.normals = undefined;
mesh.uvs = undefined; mesh.uvs = undefined;
var gltfMeshPrimitives = []; var gltfPrimitives = [];
gltf.meshes[meshId] = {
name : meshId,
primitives : gltfMeshPrimitives
};
// Add primitives to mesh
var primitives = mesh.primitives; var primitives = mesh.primitives;
var primitivesLength = primitives.length; var primitivesLength = primitives.length;
for (var k = 0; k < primitivesLength; ++k) { for (var i = 0; i < primitivesLength; ++i) {
var primitive = primitives[k]; var primitive = primitives[i];
var indexAccessorId = addIndexArray(primitive.indices, uint32Indices); var indexAccessorIndex = addIndexArray(gltf, bufferState, primitive.indices, uint32Indices);
primitive.indices = undefined; // Unload resources primitive.indices = undefined; // Unload resources
var materialId = primitive.material;
if (!defined(materialId)) { var materialIndex = getMaterial(gltf, materials, images, primitive.material, hasNormals, options);
// Create a default material if the primitive does not specify one
materialId = 'default';
}
var material = materials[materialId]; gltfPrimitives.push({
material = defined(material) ? material : new Material();
var gltfMaterial = gltf.materials[materialId];
if (defined(gltfMaterial)) {
// Check if this material has already been added but with incompatible shading
var normalShading = (gltfMaterial.extensions.KHR_materials_common.technique !== 'CONSTANT');
if (hasNormals !== normalShading) {
materialId += (hasNormals ? '_shaded' : '_constant');
gltfMaterial = gltf.materials[materialId];
}
}
if (!defined(gltfMaterial)) {
gltf.materials[materialId] = createMaterial(material, hasNormals);
}
gltfMeshPrimitives.push({
attributes : attributes, attributes : attributes,
indices : indexAccessorId, indices : indexAccessorIndex,
material : materialId, material : materialIndex,
mode : WebGLConstants.TRIANGLES mode : WebGLConstants.TRIANGLES
}); });
} }
}
}
var buffers = []; var gltfMesh = {
buffers = buffers.concat(vertexBuffers, indexBuffers); name : mesh.name,
var buffer = Buffer.concat(buffers); primitives : gltfPrimitives
gltf.buffers[bufferId] = {
byteLength : buffer.byteLength,
extras : {
_obj2gltf : {
source : buffer
}
}
}; };
gltf.bufferViews[vertexBufferViewId] = { var meshIndex = gltf.meshes.length;
buffer : bufferId, gltf.meshes.push(gltfMesh);
byteLength : vertexBufferByteOffset, return meshIndex;
byteOffset : 0, }
target : WebGLConstants.ARRAY_BUFFER
}; function addNode(gltf, name, meshIndex, parentIndex) {
var node = {
gltf.bufferViews[indexBufferViewId] = { name : name,
buffer : bufferId, mesh : meshIndex
byteLength : indexBufferByteOffset, };
byteOffset : vertexBufferByteOffset,
target : WebGLConstants.ELEMENT_ARRAY_BUFFER var nodeIndex = gltf.nodes.length;
}; gltf.nodes.push(node);
return gltf; if (defined(parentIndex)) {
var parentNode = gltf.nodes[parentIndex];
if (!defined(parentNode.children)) {
parentNode.children = [];
}
parentNode.children.push(nodeIndex);
} else {
gltf.scenes[gltf.scene].nodes.push(nodeIndex);
}
return nodeIndex;
} }

View File

@ -1,14 +1,14 @@
'use strict'; 'use strict';
var Cesium = require('cesium'); var Cesium = require('cesium');
var fsExtra = require('fs-extra'); var fsExtra = require('fs-extra');
var jpeg = require('jpeg-js');
var path = require('path'); var path = require('path');
var PNG = require('pngjs').PNG; var PNG = require('pngjs').PNG;
var Promise = require('bluebird'); var Promise = require('bluebird');
var fsExtraReadFile = Promise.promisify(fsExtra.readFile); var fsExtraReadFile = Promise.promisify(fsExtra.readFile);
var defined = Cesium.defined; var defaultValue = Cesium.defaultValue;
var WebGLConstants = Cesium.WebGLConstants;
module.exports = loadImage; module.exports = loadImage;
@ -17,67 +17,49 @@ module.exports = loadImage;
* *
* @param {String} imagePath Path to the image file. * @param {String} imagePath Path to the image file.
* @param {Object} options An object with the following properties: * @param {Object} options An object with the following properties:
* @param {Boolean} options.checkTransparency Do a more exhaustive check for texture transparency by looking at the alpha channel of each pixel. * @param {Boolean} [options.checkTransparency=false] Do a more exhaustive check for texture transparency by looking at the alpha channel of each pixel.
* @param {Boolean} [options.decode=false] Decode image.
* @returns {Promise} A promise resolving to the image information, or undefined if the file doesn't exist. * @returns {Promise} A promise resolving to the image information, or undefined if the file doesn't exist.
* *
* @private * @private
*/ */
function loadImage(imagePath, options) { function loadImage(imagePath, options) {
options = defaultValue(options, {});
options.checkTransparency = defaultValue(options.checkTransparency, false);
options.decode = defaultValue(options.decode, false);
return fsExtraReadFile(imagePath) return fsExtraReadFile(imagePath)
.then(function(data) { .then(function(data) {
var extension = path.extname(imagePath).toLowerCase(); var extension = path.extname(imagePath).toLowerCase();
var info = { var info = {
transparent : false, transparent : false,
format : getFormat(3),
source : data, source : data,
extension : extension extension : extension,
decoded : undefined,
width : undefined,
height : undefined
}; };
if (extension === '.png') { if (extension === '.png') {
return getPngInfo(data, info, options); return getPngInfo(data, info, options);
} else if (extension === '.jpg' || extension === '.jpeg') {
return getJpegInfo(data, info, options);
} }
return info; return info;
}); });
} }
function getPngInfo(data, info, options) { function hasTransparency(info) {
// Color type is encoded in the 25th bit of the png var pixels = info.decoded;
var colorType = data[25]; var pixelsLength = info.width * info.height;
var channels = getChannels(colorType);
info.format = getFormat(channels);
if (channels === 4) {
if (options.checkTransparency) {
return isTransparent(data)
.then(function(transparent) {
info.transparent = transparent;
return info;
});
}
}
return info;
}
function isTransparent(data) {
return new Promise(function(resolve, reject) {
new PNG().parse(data, function(error, data) {
if (defined(error)) {
reject(error);
return;
}
var pixels = data.data;
var pixelsLength = data.width * data.height;
for (var i = 0; i < pixelsLength; ++i) { for (var i = 0; i < pixelsLength; ++i) {
if (pixels[i * 4 + 3] < 255) { if (pixels[i * 4 + 3] < 255) {
resolve(true); return true;
return;
} }
} }
resolve(false); return false;
});
});
} }
function getChannels(colorType) { function getChannels(colorType) {
@ -95,15 +77,32 @@ function getChannels(colorType) {
} }
} }
function getFormat(channels) { function getPngInfo(data, info, options) {
switch (channels) { // Color type is encoded in the 25th bit of the png
case 1: var colorType = data[25];
return WebGLConstants.ALPHA; var channels = getChannels(colorType);
case 2:
return WebGLConstants.LUMINANCE_ALPHA; var checkTransparency = (channels === 4 && options.checkTransparency);
case 3: var decode = options.decode || checkTransparency;
return WebGLConstants.RGB;
case 4: if (decode) {
return WebGLConstants.RGBA; var decodedResults = PNG.sync.read(data);
info.decoded = decodedResults.data;
info.width = decodedResults.width;
info.height = decodedResults.height;
if (checkTransparency) {
info.transparent = hasTransparency(info);
} }
}
return info;
}
function getJpegInfo(data, info, options) {
if (options.decode) {
var decodedResults = jpeg.decode(data);
info.decoded = decodedResults.data;
info.width = decodedResults.width;
info.height = decodedResults.height;
}
return info;
} }

View File

@ -36,7 +36,7 @@ function loadMtl(mtlPath) {
]; ];
} else if (/^Ke /i.test(line)) { } else if (/^Ke /i.test(line)) {
values = line.substring(3).trim().split(' '); values = line.substring(3).trim().split(' ');
material.emissionColor = [ material.emissiveColor = [
parseFloat(values[0]), parseFloat(values[0]),
parseFloat(values[1]), parseFloat(values[1]),
parseFloat(values[2]), parseFloat(values[2]),
@ -70,17 +70,17 @@ function loadMtl(mtlPath) {
} else if (/^map_Ka /i.test(line)) { } else if (/^map_Ka /i.test(line)) {
material.ambientTexture = path.resolve(mtlDirectory, line.substring(7).trim()); material.ambientTexture = path.resolve(mtlDirectory, line.substring(7).trim());
} else if (/^map_Ke /i.test(line)) { } else if (/^map_Ke /i.test(line)) {
material.emissionTexture = path.resolve(mtlDirectory, line.substring(7).trim()); material.emissiveTexture = path.resolve(mtlDirectory, line.substring(7).trim());
} else if (/^map_Kd /i.test(line)) { } else if (/^map_Kd /i.test(line)) {
material.diffuseTexture = path.resolve(mtlDirectory, line.substring(7).trim()); material.diffuseTexture = path.resolve(mtlDirectory, line.substring(7).trim());
} else if (/^map_Ks /i.test(line)) { } else if (/^map_Ks /i.test(line)) {
material.specularTexture = path.resolve(mtlDirectory, line.substring(7).trim()); material.specularTexture = path.resolve(mtlDirectory, line.substring(7).trim());
} else if (/^map_Ns /i.test(line)) { } else if (/^map_Ns /i.test(line)) {
material.specularShininessMap = path.resolve(mtlDirectory, line.substring(7).trim()); material.specularShininessTexture = path.resolve(mtlDirectory, line.substring(7).trim());
} else if (/^map_Bump /i.test(line)) { } else if (/^map_Bump /i.test(line)) {
material.normalMap = path.resolve(mtlDirectory, line.substring(9).trim()); material.normalTexture = path.resolve(mtlDirectory, line.substring(9).trim());
} else if (/^map_d /i.test(line)) { } else if (/^map_d /i.test(line)) {
material.alphaMap = path.resolve(mtlDirectory, line.substring(6).trim()); material.alphaTexture = path.resolve(mtlDirectory, line.substring(6).trim());
} }
} }

View File

@ -287,8 +287,8 @@ function finishLoading(nodes, mtlPaths, objPath, options) {
} }
return loadMaterials(mtlPaths, objPath, options) return loadMaterials(mtlPaths, objPath, options)
.then(function(materials) { .then(function(materials) {
var imagePaths = getImagePaths(materials); var imagesOptions = getImagesOptions(materials, options);
return loadImages(imagePaths, objPath, options) return loadImages(imagesOptions, objPath, options)
.then(function(images) { .then(function(images) {
return { return {
nodes : nodes, nodes : nodes,
@ -325,16 +325,17 @@ function loadMaterials(mtlPaths, objPath, options) {
.thenReturn(materials); .thenReturn(materials);
} }
function loadImages(imagePaths, objPath, options) { function loadImages(imagesOptions, objPath, options) {
var secure = options.secure; var secure = options.secure;
var logger = options.logger; var logger = options.logger;
var images = {}; var images = {};
return Promise.map(imagePaths, function(imagePath) { return Promise.map(imagesOptions, function(imageOptions) {
var imagePath = imageOptions.imagePath;
if (secure && outsideDirectory(imagePath, objPath)) { if (secure && outsideDirectory(imagePath, objPath)) {
logger('Could not read image file at ' + imagePath + ' because it is outside of the obj directory and the secure flag is true. Material will ignore this image.'); logger('Could not read image file at ' + imagePath + ' because it is outside of the obj directory and the secure flag is true. Material will ignore this image.');
return; return;
} }
return loadImage(imagePath, options) return loadImage(imagePath, imageOptions)
.then(function(image) { .then(function(image) {
images[imagePath] = image; images[imagePath] = image;
}) })
@ -345,26 +346,47 @@ function loadImages(imagePaths, objPath, options) {
.thenReturn(images); .thenReturn(images);
} }
function getImagePaths(materials) { function getImagesOptions(materials, options) {
var imagePaths = {}; var imagesOptions = [];
for (var name in materials) { for (var name in materials) {
if (materials.hasOwnProperty(name)) { if (materials.hasOwnProperty(name)) {
var material = materials[name]; var material = materials[name];
if (defined(material.ambientTexture)) { if (defined(material.ambientTexture)) {
imagePaths[material.ambientTexture] = true; imagesOptions.push({
imagePath : material.ambientTexture
});
}
if (defined(material.emissiveTexture)) {
imagesOptions.push({
imagePath : material.emissiveTexture
});
} }
if (defined(material.diffuseTexture)) { if (defined(material.diffuseTexture)) {
imagePaths[material.diffuseTexture] = true; imagesOptions.push({
} imagePath : material.diffuseTexture,
if (defined(material.emissionTexture)) { checkTransparency : options.checkTransparency
imagePaths[material.emissionTexture] = true; });
} }
if (defined(material.specularTexture)) { if (defined(material.specularTexture)) {
imagePaths[material.specularTexture] = true; imagesOptions.push({
imagePath : material.specularTexture,
decode : true
});
}
if (defined(material.specularShininessTexture)) {
imagesOptions.push({
imagePath : material.specularShininessTexture,
decode : true
});
}
if (defined(material.normalTexture)) {
imagesOptions.push({
imagePath : material.normalTexture
});
} }
} }
} }
return Object.keys(imagePaths); return imagesOptions;
} }
function removeEmptyMeshes(meshes) { function removeEmptyMeshes(meshes) {

View File

@ -107,7 +107,7 @@ function obj2gltf(objPath, gltfPath, options) {
return loadObj(objPath, options) return loadObj(objPath, options)
.then(function(objData) { .then(function(objData) {
return createGltf(objData); return createGltf(objData, options);
}) })
.then(function(gltf) { .then(function(gltf) {
return writeUris(gltf, gltfPath, options); return writeUris(gltf, gltfPath, options);

View File

@ -29,15 +29,14 @@ function writeUris(gltf, gltfPath, options) {
var promises = []; var promises = [];
var buffer = gltf.buffers[Object.keys(gltf.buffers)[0]]; var buffer = gltf.buffers[0];
var bufferByteLength = buffer.extras._obj2gltf.source.length; var bufferByteLength = buffer.extras._obj2gltf.source.length;
var texturesByteLength = 0; var texturesByteLength = 0;
var images = gltf.images; var images = gltf.images;
for (var id in images) { var imagesLength = images.length;
if (images.hasOwnProperty(id)) { for (var i = 0; i < imagesLength; ++i) {
texturesByteLength += images[id].extras._obj2gltf.source.length; texturesByteLength += images[i].extras._obj2gltf.source.length;
}
} }
// Buffers larger than ~192MB cannot be base64 encoded due to a NodeJS limitation. Source: https://github.com/nodejs/node/issues/4266 // Buffers larger than ~192MB cannot be base64 encoded due to a NodeJS limitation. Source: https://github.com/nodejs/node/issues/4266
@ -67,20 +66,24 @@ function writeUris(gltf, gltfPath, options) {
} }
function deleteExtras(gltf) { function deleteExtras(gltf) {
var buffer = gltf.buffers[Object.keys(gltf.buffers)[0]]; var buffer = gltf.buffers[0];
delete buffer.extras; delete buffer.extras;
var images = gltf.images; var images = gltf.images;
for (var id in images) { var imagesLength = images.length;
if (images.hasOwnProperty(id)) { for (var i = 0; i < imagesLength; ++i) {
var image = images[id]; delete images[i].extras;
delete image.extras;
} }
var materials = gltf.materials;
var materialsLength = materials.length;
for (var j = 0; j < materialsLength; ++j) {
delete materials[j].extras;
} }
} }
function writeSeparateBuffer(gltf, gltfPath) { function writeSeparateBuffer(gltf, gltfPath) {
var buffer = gltf.buffers[Object.keys(gltf.buffers)[0]]; var buffer = gltf.buffers[0];
var source = buffer.extras._obj2gltf.source; var source = buffer.extras._obj2gltf.source;
var bufferName = path.basename(gltfPath, path.extname(gltfPath)); var bufferName = path.basename(gltfPath, path.extname(gltfPath));
var bufferUri = bufferName + '.bin'; var bufferUri = bufferName + '.bin';
@ -91,8 +94,7 @@ function writeSeparateBuffer(gltf, gltfPath) {
function writeSeparateTextures(gltf, gltfPath) { function writeSeparateTextures(gltf, gltfPath) {
var images = gltf.images; var images = gltf.images;
return Promise.map(Object.keys(images), function(id) { return Promise.map(images, function(image) {
var image = images[id];
var extras = image.extras._obj2gltf; var extras = image.extras._obj2gltf;
var imageUri = image.name + extras.extension; var imageUri = image.name + extras.extension;
image.uri = imageUri; image.uri = imageUri;
@ -102,20 +104,19 @@ function writeSeparateTextures(gltf, gltfPath) {
} }
function writeEmbeddedBuffer(gltf) { function writeEmbeddedBuffer(gltf) {
var buffer = gltf.buffers[Object.keys(gltf.buffers)[0]]; var buffer = gltf.buffers[0];
var source = buffer.extras._obj2gltf.source; var source = buffer.extras._obj2gltf.source;
buffer.uri = 'data:application/octet-stream;base64,' + source.toString('base64'); buffer.uri = 'data:application/octet-stream;base64,' + source.toString('base64');
} }
function writeEmbeddedTextures(gltf) { function writeEmbeddedTextures(gltf) {
var images = gltf.images; var images = gltf.images;
for (var id in images) { var imagesLength = images.length;
if (images.hasOwnProperty(id)) { for (var i = 0; i < imagesLength; ++i) {
var image = images[id]; var image = images[i];
var extras = image.extras._obj2gltf; var extras = image.extras._obj2gltf;
image.uri = 'data:' + mime.lookup(extras.extension) + ';base64,' + extras.source.toString('base64'); image.uri = 'data:' + mime.lookup(extras.extension) + ';base64,' + extras.source.toString('base64');
} }
}
} }
/** /**

View File

@ -31,6 +31,7 @@
"event-stream": "^3.3.4", "event-stream": "^3.3.4",
"fs-extra": "^2.0.0", "fs-extra": "^2.0.0",
"gltf-pipeline": "^0.1.0-alpha11", "gltf-pipeline": "^0.1.0-alpha11",
"jpeg-js": "^0.2.0",
"mime": "^1.3.4", "mime": "^1.3.4",
"pngjs": "^3.0.1", "pngjs": "^3.0.1",
"yargs": "^7.0.1" "yargs": "^7.0.1"

View File

@ -26,7 +26,7 @@ var defaultOptions = obj2gltf.defaults;
var checkTransparencyOptions = clone(defaultOptions); var checkTransparencyOptions = clone(defaultOptions);
checkTransparencyOptions.checkTransparency = true; checkTransparencyOptions.checkTransparency = true;
describe('gltf', function() { describe('createGltf', function() {
var boxObjData; var boxObjData;
var duplicateBoxObjData; var duplicateBoxObjData;
var groupObjData; var groupObjData;
@ -69,7 +69,7 @@ describe('gltf', function() {
}); });
it('simple gltf', function(done) { it('simple gltf', function(done) {
var gltf = createGltf(boxObjData); var gltf = createGltf(boxObjData, defaultOptions);
expect(writeUris(gltf, boxGltfUrl, defaultOptions) expect(writeUris(gltf, boxGltfUrl, defaultOptions)
.then(function() { .then(function() {
expect(gltf).toEqual(boxGltf); expect(gltf).toEqual(boxGltf);
@ -77,7 +77,7 @@ describe('gltf', function() {
}); });
it('multiple nodes, meshes, and primitives', function(done) { it('multiple nodes, meshes, and primitives', function(done) {
var gltf = createGltf(groupObjData); var gltf = createGltf(groupObjData, defaultOptions);
expect(writeUris(gltf, groupGltfUrl, defaultOptions) expect(writeUris(gltf, groupGltfUrl, defaultOptions)
.then(function() { .then(function() {
@ -99,7 +99,7 @@ describe('gltf', function() {
it('sets default material values', function() { it('sets default material values', function() {
boxObjData.materials.Material = new Material(); boxObjData.materials.Material = new Material();
var gltf = createGltf(boxObjData); var gltf = createGltf(boxObjData, defaultOptions);
var material = gltf.materials.Material; var material = gltf.materials.Material;
var kmc = material.extensions.KHR_materials_common; var kmc = material.extensions.KHR_materials_common;
var values = kmc.values; var values = kmc.values;
@ -118,7 +118,7 @@ describe('gltf', function() {
boxObjData.materials.Material = material; boxObjData.materials.Material = material;
boxObjData.images[diffuseTextureUrl] = diffuseTexture; boxObjData.images[diffuseTextureUrl] = diffuseTexture;
var gltf = createGltf(boxObjData); var gltf = createGltf(boxObjData, defaultOptions);
var kmc = gltf.materials.Material.extensions.KHR_materials_common; var kmc = gltf.materials.Material.extensions.KHR_materials_common;
var texture = gltf.textures.texture_cesium; var texture = gltf.textures.texture_cesium;
var image = gltf.images.cesium; var image = gltf.images.cesium;
@ -156,7 +156,7 @@ describe('gltf', function() {
material.alpha = 0.4; material.alpha = 0.4;
boxObjData.materials.Material = material; boxObjData.materials.Material = material;
var gltf = createGltf(boxObjData); var gltf = createGltf(boxObjData, defaultOptions);
var kmc = gltf.materials.Material.extensions.KHR_materials_common; var kmc = gltf.materials.Material.extensions.KHR_materials_common;
expect(kmc.values.diffuse).toEqual([0.5, 0.5, 0.5, 0.4]); expect(kmc.values.diffuse).toEqual([0.5, 0.5, 0.5, 0.4]);
@ -173,7 +173,7 @@ describe('gltf', function() {
boxObjData.images[diffuseTextureUrl] = diffuseTexture; boxObjData.images[diffuseTextureUrl] = diffuseTexture;
var gltf = createGltf(boxObjData); var gltf = createGltf(boxObjData, defaultOptions);
var kmc = gltf.materials.Material.extensions.KHR_materials_common; var kmc = gltf.materials.Material.extensions.KHR_materials_common;
expect(kmc.values.diffuse).toEqual('texture_cesium'); expect(kmc.values.diffuse).toEqual('texture_cesium');
@ -189,7 +189,7 @@ describe('gltf', function() {
boxObjData.images[transparentDiffuseTextureUrl] = transparentDiffuseTexture; boxObjData.images[transparentDiffuseTextureUrl] = transparentDiffuseTexture;
var gltf = createGltf(boxObjData); var gltf = createGltf(boxObjData, defaultOptions);
var kmc = gltf.materials.Material.extensions.KHR_materials_common; var kmc = gltf.materials.Material.extensions.KHR_materials_common;
expect(kmc.values.diffuse).toBe('texture_diffuse'); expect(kmc.values.diffuse).toBe('texture_diffuse');
@ -204,7 +204,7 @@ describe('gltf', function() {
material.specularShininess = 0.1; material.specularShininess = 0.1;
boxObjData.materials.Material = material; boxObjData.materials.Material = material;
var gltf = createGltf(boxObjData); var gltf = createGltf(boxObjData, defaultOptions);
var kmc = gltf.materials.Material.extensions.KHR_materials_common; var kmc = gltf.materials.Material.extensions.KHR_materials_common;
expect(kmc.technique).toBe('PHONG'); expect(kmc.technique).toBe('PHONG');
@ -221,7 +221,7 @@ describe('gltf', function() {
boxObjData.images[diffuseTextureUrl] = diffuseTexture; boxObjData.images[diffuseTextureUrl] = diffuseTexture;
var gltf = createGltf(boxObjData); var gltf = createGltf(boxObjData, defaultOptions);
var kmc = gltf.materials.Material.extensions.KHR_materials_common; var kmc = gltf.materials.Material.extensions.KHR_materials_common;
expect(kmc.technique).toBe('CONSTANT'); expect(kmc.technique).toBe('CONSTANT');
@ -233,7 +233,7 @@ describe('gltf', function() {
material.diffuseTexture = diffuseTextureUrl; material.diffuseTexture = diffuseTextureUrl;
boxObjData.materials.Material = material; boxObjData.materials.Material = material;
var gltf = createGltf(boxObjData); var gltf = createGltf(boxObjData, defaultOptions);
var kmc = gltf.materials.Material.extensions.KHR_materials_common; var kmc = gltf.materials.Material.extensions.KHR_materials_common;
expect(kmc.values.diffuse).toEqual([0.5, 0.5, 0.5, 1.0]); expect(kmc.values.diffuse).toEqual([0.5, 0.5, 0.5, 1.0]);
@ -243,7 +243,7 @@ describe('gltf', function() {
boxObjData.nodes[0].meshes[0].primitives[0].material = undefined; boxObjData.nodes[0].meshes[0].primitives[0].material = undefined;
// Creates a material called "default" // Creates a material called "default"
var gltf = createGltf(boxObjData); var gltf = createGltf(boxObjData, defaultOptions);
expect(gltf.materials.default).toBeDefined(); expect(gltf.materials.default).toBeDefined();
var kmc = gltf.materials.default.extensions.KHR_materials_common; var kmc = gltf.materials.default.extensions.KHR_materials_common;
expect(kmc.values.diffuse).toEqual([0.5, 0.5, 0.5, 1.0]); expect(kmc.values.diffuse).toEqual([0.5, 0.5, 0.5, 1.0]);
@ -253,7 +253,7 @@ describe('gltf', function() {
boxObjData.materials = {}; boxObjData.materials = {};
// Uses the original name of the material // Uses the original name of the material
var gltf = createGltf(boxObjData); var gltf = createGltf(boxObjData, defaultOptions);
var kmc = gltf.materials.Material.extensions.KHR_materials_common; var kmc = gltf.materials.Material.extensions.KHR_materials_common;
expect(kmc.values.diffuse).toEqual([0.5, 0.5, 0.5, 1.0]); expect(kmc.values.diffuse).toEqual([0.5, 0.5, 0.5, 1.0]);
@ -264,7 +264,7 @@ describe('gltf', function() {
boxObjData.nodes.push(duplicateBoxObjData.nodes[0]); boxObjData.nodes.push(duplicateBoxObjData.nodes[0]);
boxObjData.nodes[1].meshes[0].normals.length = 0; boxObjData.nodes[1].meshes[0].normals.length = 0;
var gltf = createGltf(boxObjData); var gltf = createGltf(boxObjData, defaultOptions);
var kmc1 = gltf.materials.Material.extensions.KHR_materials_common; var kmc1 = gltf.materials.Material.extensions.KHR_materials_common;
var kmc2 = gltf.materials.Material_constant.extensions.KHR_materials_common; var kmc2 = gltf.materials.Material_constant.extensions.KHR_materials_common;
@ -277,7 +277,7 @@ describe('gltf', function() {
boxObjData.nodes.push(duplicateBoxObjData.nodes[0]); boxObjData.nodes.push(duplicateBoxObjData.nodes[0]);
boxObjData.nodes[0].meshes[0].normals.length = 0; boxObjData.nodes[0].meshes[0].normals.length = 0;
var gltf = createGltf(boxObjData); var gltf = createGltf(boxObjData, defaultOptions);
var kmc1 = gltf.materials.Material.extensions.KHR_materials_common; var kmc1 = gltf.materials.Material.extensions.KHR_materials_common;
var kmc2 = gltf.materials.Material_shaded.extensions.KHR_materials_common; var kmc2 = gltf.materials.Material_shaded.extensions.KHR_materials_common;
@ -288,7 +288,7 @@ describe('gltf', function() {
it('runs without normals', function() { it('runs without normals', function() {
boxObjData.nodes[0].meshes[0].normals.length = 0; boxObjData.nodes[0].meshes[0].normals.length = 0;
var gltf = createGltf(boxObjData); var gltf = createGltf(boxObjData, defaultOptions);
var attributes = gltf.meshes[Object.keys(gltf.meshes)[0]].primitives[0].attributes; var attributes = gltf.meshes[Object.keys(gltf.meshes)[0]].primitives[0].attributes;
expect(attributes.POSITION).toBeDefined(); expect(attributes.POSITION).toBeDefined();
expect(attributes.NORMAL).toBeUndefined(); expect(attributes.NORMAL).toBeUndefined();
@ -298,7 +298,7 @@ describe('gltf', function() {
it('runs without uvs', function() { it('runs without uvs', function() {
boxObjData.nodes[0].meshes[0].uvs.length = 0; boxObjData.nodes[0].meshes[0].uvs.length = 0;
var gltf = createGltf(boxObjData); var gltf = createGltf(boxObjData, defaultOptions);
var attributes = gltf.meshes[Object.keys(gltf.meshes)[0]].primitives[0].attributes; var attributes = gltf.meshes[Object.keys(gltf.meshes)[0]].primitives[0].attributes;
expect(attributes.POSITION).toBeDefined(); expect(attributes.POSITION).toBeDefined();
expect(attributes.NORMAL).toBeDefined(); expect(attributes.NORMAL).toBeDefined();
@ -309,7 +309,7 @@ describe('gltf', function() {
boxObjData.nodes[0].meshes[0].normals.length = 0; boxObjData.nodes[0].meshes[0].normals.length = 0;
boxObjData.nodes[0].meshes[0].uvs.length = 0; boxObjData.nodes[0].meshes[0].uvs.length = 0;
var gltf = createGltf(boxObjData); var gltf = createGltf(boxObjData, defaultOptions);
var attributes = gltf.meshes[Object.keys(gltf.meshes)[0]].primitives[0].attributes; var attributes = gltf.meshes[Object.keys(gltf.meshes)[0]].primitives[0].attributes;
expect(attributes.POSITION).toBeDefined(); expect(attributes.POSITION).toBeDefined();
expect(attributes.NORMAL).toBeUndefined(); expect(attributes.NORMAL).toBeUndefined();
@ -349,7 +349,7 @@ describe('gltf', function() {
var indicesLength = mesh.primitives[0].indices.length; var indicesLength = mesh.primitives[0].indices.length;
var vertexCount = mesh.positions.length / 3; var vertexCount = mesh.positions.length / 3;
var gltf = createGltf(boxObjData); var gltf = createGltf(boxObjData, defaultOptions);
var primitive = gltf.meshes[Object.keys(gltf.meshes)[0]].primitives[0]; var primitive = gltf.meshes[Object.keys(gltf.meshes)[0]].primitives[0];
var indicesAccessor = gltf.accessors[primitive.indices]; var indicesAccessor = gltf.accessors[primitive.indices];
expect(indicesAccessor.count).toBe(indicesLength); expect(indicesAccessor.count).toBe(indicesLength);

View File

@ -4,7 +4,6 @@ var obj2gltf = require('../../lib/obj2gltf');
var loadImage = require('../../lib/loadImage'); var loadImage = require('../../lib/loadImage');
var clone = Cesium.clone; var clone = Cesium.clone;
var WebGLConstants = Cesium.WebGLConstants;
var pngImage = 'specs/data/box-complex-material/shininess.png'; var pngImage = 'specs/data/box-complex-material/shininess.png';
var jpgImage = 'specs/data/box-complex-material/emission.jpg'; var jpgImage = 'specs/data/box-complex-material/emission.jpg';
@ -15,12 +14,11 @@ var transparentImage = 'specs/data/box-complex-material/diffuse.png';
var defaultOptions = obj2gltf.defaults; var defaultOptions = obj2gltf.defaults;
describe('image', function() { describe('loadImage', function() {
it('loads png image', function(done) { it('loads png image', function(done) {
expect(loadImage(pngImage, defaultOptions) expect(loadImage(pngImage, defaultOptions)
.then(function(info) { .then(function(info) {
expect(info.transparent).toBe(false); expect(info.transparent).toBe(false);
expect(info.format).toBe(WebGLConstants.RGB);
expect(info.source).toBeDefined(); expect(info.source).toBeDefined();
expect(info.extension).toBe('.png'); expect(info.extension).toBe('.png');
}), done).toResolve(); }), done).toResolve();
@ -30,7 +28,6 @@ describe('image', function() {
expect(loadImage(jpgImage, defaultOptions) expect(loadImage(jpgImage, defaultOptions)
.then(function(info) { .then(function(info) {
expect(info.transparent).toBe(false); expect(info.transparent).toBe(false);
expect(info.format).toBe(WebGLConstants.RGB);
expect(info.source).toBeDefined(); expect(info.source).toBeDefined();
expect(info.extension).toBe('.jpg'); expect(info.extension).toBe('.jpg');
}), done).toResolve(); }), done).toResolve();
@ -40,7 +37,6 @@ describe('image', function() {
expect(loadImage(jpegImage, defaultOptions) expect(loadImage(jpegImage, defaultOptions)
.then(function(info) { .then(function(info) {
expect(info.transparent).toBe(false); expect(info.transparent).toBe(false);
expect(info.format).toBe(WebGLConstants.RGB);
expect(info.source).toBeDefined(); expect(info.source).toBeDefined();
expect(info.extension).toBe('.jpeg'); expect(info.extension).toBe('.jpeg');
}), done).toResolve(); }), done).toResolve();
@ -50,7 +46,6 @@ describe('image', function() {
expect(loadImage(gifImage, defaultOptions) expect(loadImage(gifImage, defaultOptions)
.then(function(info) { .then(function(info) {
expect(info.transparent).toBe(false); expect(info.transparent).toBe(false);
expect(info.format).toBe(WebGLConstants.RGB);
expect(info.source).toBeDefined(); expect(info.source).toBeDefined();
expect(info.extension).toBe('.gif'); expect(info.extension).toBe('.gif');
}), done).toResolve(); }), done).toResolve();
@ -60,7 +55,6 @@ describe('image', function() {
expect(loadImage(grayscaleImage, defaultOptions) expect(loadImage(grayscaleImage, defaultOptions)
.then(function(info) { .then(function(info) {
expect(info.transparent).toBe(false); expect(info.transparent).toBe(false);
expect(info.format).toBe(WebGLConstants.ALPHA);
expect(info.source).toBeDefined(); expect(info.source).toBeDefined();
expect(info.extension).toBe('.png'); expect(info.extension).toBe('.png');
}), done).toResolve(); }), done).toResolve();

View File

@ -9,25 +9,25 @@ function getImagePath(objPath, relativePath) {
return path.resolve(path.dirname(objPath), relativePath); return path.resolve(path.dirname(objPath), relativePath);
} }
describe('mtl', function() { describe('loadMtl', function() {
it('loads complex material', function(done) { it('loads complex material', function(done) {
expect(loadMtl(complexMaterialUrl) expect(loadMtl(complexMaterialUrl)
.then(function(materials) { .then(function(materials) {
var material = materials.Material; var material = materials.Material;
expect(material).toBeDefined(); expect(material).toBeDefined();
expect(material.ambientColor).toEqual([0.2, 0.2, 0.2, 1.0]); expect(material.ambientColor).toEqual([0.2, 0.2, 0.2, 1.0]);
expect(material.emissionColor).toEqual([0.1, 0.1, 0.1, 1.0]); expect(material.emissiveColor).toEqual([0.1, 0.1, 0.1, 1.0]);
expect(material.diffuseColor).toEqual([0.64, 0.64, 0.64, 1.0]); expect(material.diffuseColor).toEqual([0.64, 0.64, 0.64, 1.0]);
expect(material.specularColor).toEqual([0.5, 0.5, 0.5, 1.0]); expect(material.specularColor).toEqual([0.5, 0.5, 0.5, 1.0]);
expect(material.specularShininess).toEqual(96.078431); expect(material.specularShininess).toEqual(96.078431);
expect(material.alpha).toEqual(0.9); expect(material.alpha).toEqual(0.9);
expect(material.ambientTexture).toEqual(getImagePath(complexMaterialUrl, 'ambient.gif')); expect(material.ambientTexture).toEqual(getImagePath(complexMaterialUrl, 'ambient.gif'));
expect(material.emissionTexture).toEqual(getImagePath(complexMaterialUrl, 'emission.jpg')); expect(material.emissiveTexture).toEqual(getImagePath(complexMaterialUrl, 'emission.jpg'));
expect(material.diffuseTexture).toEqual(getImagePath(complexMaterialUrl, 'diffuse.png')); expect(material.diffuseTexture).toEqual(getImagePath(complexMaterialUrl, 'diffuse.png'));
expect(material.specularTexture).toEqual(getImagePath(complexMaterialUrl, 'specular.jpeg')); expect(material.specularTexture).toEqual(getImagePath(complexMaterialUrl, 'specular.jpeg'));
expect(material.specularShininessMap).toEqual(getImagePath(complexMaterialUrl, 'shininess.png')); expect(material.specularShininessTexture).toEqual(getImagePath(complexMaterialUrl, 'shininess.png'));
expect(material.normalMap).toEqual(getImagePath(complexMaterialUrl, 'bump.png')); expect(material.normalTexture).toEqual(getImagePath(complexMaterialUrl, 'bump.png'));
expect(material.alphaMap).toEqual(getImagePath(complexMaterialUrl, 'alpha.png')); expect(material.alphaTexture).toEqual(getImagePath(complexMaterialUrl, 'alpha.png'));
}), done).toResolve(); }), done).toResolve();
}); });

View File

@ -61,7 +61,7 @@ function getImagePath(objPath, relativePath) {
var defaultOptions = obj2gltf.defaults; var defaultOptions = obj2gltf.defaults;
describe('obj', function() { describe('loadObj', function() {
it('loads obj with positions, normals, and uvs', function(done) { it('loads obj with positions, normals, and uvs', function(done) {
expect(loadObj(objUrl, defaultOptions) expect(loadObj(objUrl, defaultOptions)
.then(function(data) { .then(function(data) {