Explorar el Código

Merge pull request #174 from sukolsak/glb-export

GLB and STL export
Alexander Rose hace 3 años
padre
commit
fccf8d6b87

+ 1 - 1
CHANGELOG.md

@@ -5,7 +5,7 @@ Note that since we don't clearly distinguish between a public and private interf
 
 ## [Unreleased]
 
-- [empty]
+- Add glTF (GLB) and STL support to ``geo-export`` extension.
 
 ## [v2.0.5] - 2021-04-26
 

+ 38 - 26
src/extensions/geo-export/controls.ts

@@ -7,14 +7,28 @@
 import { PluginComponent } from '../../mol-plugin-state/component';
 import { PluginContext } from '../../mol-plugin/context';
 import { Task } from '../../mol-task';
-import { ObjExporter } from './export';
 import { PluginStateObject } from '../../mol-plugin-state/objects';
 import { StateSelection } from '../../mol-state';
+import { ParamDefinition as PD } from '../../mol-util/param-definition';
 import { SetUtils } from '../../mol-util/set';
-import { zip } from '../../mol-util/zip/zip';
+import { ObjExporter } from './obj-exporter';
+import { GlbExporter } from './glb-exporter';
+import { StlExporter } from './stl-exporter';
+
+export const GeometryParams = {
+    format: PD.Select('glb', [
+        ['glb', 'glTF 2.0 Binary (.glb)'],
+        ['stl', 'Stl (.stl)'],
+        ['obj', 'Wavefront (.obj)']
+    ])
+};
 
 export class GeometryControls extends PluginComponent {
-    getFilename() {
+    readonly behaviors = {
+        params: this.ev.behavior<PD.Values<typeof GeometryParams>>(PD.getDefaultValues(GeometryParams))
+    }
+
+    private getFilename() {
         const models = this.plugin.state.data.select(StateSelection.Generators.rootsOfType(PluginStateObject.Molecule.Model)).map(s => s.obj!.data);
         const uniqueIds = new Set<string>();
         models.forEach(m => uniqueIds.add(m.entryId.toUpperCase()));
@@ -22,37 +36,35 @@ export class GeometryControls extends PluginComponent {
         return `${idString || 'molstar-model'}`;
     }
 
-    exportObj() {
-        const task = Task.create('Export OBJ', async ctx => {
+    exportGeometry() {
+        const task = Task.create('Export Geometry', async ctx => {
             try {
                 const renderObjects = this.plugin.canvas3d?.getRenderObjects()!;
-
                 const filename = this.getFilename();
-                const objExporter = new ObjExporter(filename);
+
+                let renderObjectExporter: ObjExporter | GlbExporter | StlExporter;
+                switch (this.behaviors.params.value.format) {
+                    case 'obj':
+                        renderObjectExporter = new ObjExporter(filename);
+                        break;
+                    case 'glb':
+                        renderObjectExporter = new GlbExporter();
+                        break;
+                    case 'stl':
+                        renderObjectExporter = new StlExporter();
+                        break;
+                    default: throw new Error('Unsupported format.');
+                }
+
                 for (let i = 0, il = renderObjects.length; i < il; ++i) {
                     await ctx.update({ message: `Exporting object ${i}/${il}` });
-                    await objExporter.add(renderObjects[i], this.plugin.canvas3d?.webgl!, ctx);
+                    await renderObjectExporter.add(renderObjects[i], this.plugin.canvas3d?.webgl!, ctx);
                 }
-                const { obj, mtl } = objExporter.getData();
 
-                const asciiWrite = (data: Uint8Array, str: string) => {
-                    for (let i = 0, il = str.length; i < il; ++i) {
-                        data[i] = str.charCodeAt(i);
-                    }
-                };
-                const objData = new Uint8Array(obj.length);
-                asciiWrite(objData, obj);
-                const mtlData = new Uint8Array(mtl.length);
-                asciiWrite(mtlData, mtl);
-
-                const zipDataObj = {
-                    [filename + '.obj']: objData,
-                    [filename + '.mtl']: mtlData
-                };
-                const zipData = await zip(ctx, zipDataObj);
+                const blob = await renderObjectExporter.getBlob(ctx);
                 return {
-                    zipData,
-                    filename: filename + '.zip'
+                    blob,
+                    filename: filename + '.' + renderObjectExporter.fileExtension
                 };
             } catch (e) {
                 this.plugin.log.error('' + e);

+ 306 - 0
src/extensions/geo-export/glb-exporter.ts

@@ -0,0 +1,306 @@
+/**
+ * Copyright (c) 2021 mol* contributors, licensed under MIT, See LICENSE file for more info.
+ *
+ * @author Sukolsak Sakshuwong <sukolsak@stanford.edu>
+ */
+
+import { BaseValues } from '../../mol-gl/renderable/schema';
+import { asciiWrite } from '../../mol-io/common/ascii';
+import { IsNativeEndianLittle, flipByteOrder } from '../../mol-io/common/binary';
+import { Vec3, Mat3, Mat4 } from '../../mol-math/linear-algebra';
+import { RuntimeContext } from '../../mol-task';
+import { Color } from '../../mol-util/color/color';
+import { arrayMinMax, fillSerial } from '../../mol-util/array';
+import { NumberArray } from '../../mol-util/type-helpers';
+import { MeshExporter } from './mesh-exporter';
+
+// avoiding namespace lookup improved performance in Chrome (Aug 2020)
+const v3fromArray = Vec3.fromArray;
+const v3transformMat4 = Vec3.transformMat4;
+const v3transformMat3 = Vec3.transformMat3;
+const v3normalize = Vec3.normalize;
+const v3toArray = Vec3.toArray;
+const mat3directionTransform = Mat3.directionTransform;
+
+// https://github.com/KhronosGroup/glTF/tree/master/specification/2.0
+
+export type GlbData = {
+    glb: Uint8Array
+}
+
+export class GlbExporter extends MeshExporter<GlbData> {
+    readonly fileExtension = 'glb';
+    private primitives: Record<string, any>[] = [];
+    private accessors: Record<string, any>[] = [];
+    private bufferViews: Record<string, any>[] = [];
+    private binaryBuffer: ArrayBuffer[] = [];
+    private byteOffset = 0;
+
+    private static vec3MinMax(a: NumberArray, stride: number) {
+        const min = Vec3.create(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
+        const max = Vec3.create(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
+        for (let i = 0, il = a.length; i < il; i += stride) {
+            min[0] = Math.min(a[i], min[0]);
+            min[1] = Math.min(a[i + 1], min[1]);
+            min[2] = Math.min(a[i + 2], min[2]);
+            max[0] = Math.max(a[i], max[0]);
+            max[1] = Math.max(a[i + 1], max[1]);
+            max[2] = Math.max(a[i + 2], max[2]);
+        }
+        return [ min, max ];
+    }
+
+    protected async addMeshWithColors(vertices: Float32Array, normals: Float32Array, indices: Uint32Array | undefined, groups: Float32Array | Uint8Array, vertexCount: number, drawCount: number, values: BaseValues, instanceIndex: number, isGeoTexture: boolean, ctx: RuntimeContext) {
+        const t = Mat4();
+        const n = Mat3();
+        const tmpV = Vec3();
+        const stride = isGeoTexture ? 4 : 3;
+
+        const colorType = values.dColorType.ref.value;
+        const tColor = values.tColor.ref.value.array;
+        const uAlpha = values.uAlpha.ref.value;
+        const aTransform = values.aTransform.ref.value;
+
+        Mat4.fromArray(t, aTransform, instanceIndex * 16);
+        mat3directionTransform(n, t);
+
+        const currentProgress = (vertexCount * 3) * instanceIndex;
+        await ctx.update({ isIndeterminate: false, current: currentProgress, max: (vertexCount * 3) * values.uInstanceCount.ref.value });
+
+        const vertexArray = new Float32Array(vertexCount * 3);
+        const normalArray = new Float32Array(vertexCount * 3);
+        const colorArray = new Float32Array(vertexCount * 4);
+        let indexArray: Uint32Array;
+
+        // position
+        for (let i = 0; i < vertexCount; ++i) {
+            if (i % 1000 === 0 && ctx.shouldUpdate) await ctx.update({ current: currentProgress + i });
+            v3transformMat4(tmpV, v3fromArray(tmpV, vertices, i * stride), t);
+            v3toArray(tmpV, vertexArray, i * 3);
+        }
+
+        // normal
+        for (let i = 0; i < vertexCount; ++i) {
+            if (i % 1000 === 0 && ctx.shouldUpdate) await ctx.update({ current: currentProgress + vertexCount + i });
+            v3fromArray(tmpV, normals, i * stride);
+            v3transformMat3(tmpV, v3normalize(tmpV, tmpV), n);
+            v3toArray(tmpV, normalArray, i * 3);
+        }
+
+        // color
+        for (let i = 0; i < vertexCount; ++i) {
+            if (i % 1000 === 0 && ctx.shouldUpdate) await ctx.update({ current: currentProgress + vertexCount * 2 + i });
+
+            let color: Color;
+            switch (colorType) {
+                case 'uniform':
+                    color = Color.fromNormalizedArray(values.uColor.ref.value, 0);
+                    break;
+                case 'instance':
+                    color = Color.fromArray(tColor, instanceIndex * 3);
+                    break;
+                case 'group': {
+                    const group = isGeoTexture ? GlbExporter.getGroup(groups, i) : groups[i];
+                    color = Color.fromArray(tColor, group * 3);
+                    break;
+                }
+                case 'groupInstance': {
+                    const groupCount = values.uGroupCount.ref.value;
+                    const group = isGeoTexture ? GlbExporter.getGroup(groups, i) : groups[i];
+                    color = Color.fromArray(tColor, (instanceIndex * groupCount + group) * 3);
+                    break;
+                }
+                case 'vertex':
+                    color = Color.fromArray(tColor, i * 3);
+                    break;
+                case 'vertexInstance':
+                    color = Color.fromArray(tColor, (instanceIndex * drawCount + i) * 3);
+                    break;
+                default: throw new Error('Unsupported color type.');
+            }
+            Color.toArrayNormalized(color, colorArray, i * 4);
+            colorArray[i * 4 + 3] = uAlpha;
+        }
+
+        // face
+        if (isGeoTexture) {
+            indexArray = new Uint32Array(drawCount);
+            fillSerial(indexArray);
+        } else {
+            indexArray = indices!.slice(0, drawCount);
+        }
+
+        const [ vertexMin, vertexMax ] = GlbExporter.vec3MinMax(vertexArray, 3);
+        const [ normalMin, normalMax ] = GlbExporter.vec3MinMax(normalArray, 3);
+        const [ colorMin, colorMax ] = GlbExporter.vec3MinMax(colorArray, 4);
+        const [ indexMin, indexMax ] = arrayMinMax(indexArray);
+
+        // binary buffer
+        let vertexBuffer = vertexArray.buffer;
+        let normalBuffer = normalArray.buffer;
+        let colorBuffer = colorArray.buffer;
+        let indexBuffer = indexArray.buffer;
+        if (!IsNativeEndianLittle) {
+            vertexBuffer = flipByteOrder(new Uint8Array(vertexBuffer), 4);
+            normalBuffer = flipByteOrder(new Uint8Array(normalBuffer), 4);
+            colorBuffer = flipByteOrder(new Uint8Array(colorBuffer), 4);
+            indexBuffer = flipByteOrder(new Uint8Array(indexBuffer), 4);
+        }
+        this.binaryBuffer.push(vertexBuffer, normalBuffer, colorBuffer, indexBuffer);
+
+        // buffer views
+        const bufferViewOffset = this.bufferViews.length;
+
+        this.bufferViews.push({
+            buffer: 0,
+            byteOffset: this.byteOffset,
+            byteLength: vertexBuffer.byteLength,
+            target: 34962 // ARRAY_BUFFER
+        });
+        this.byteOffset += vertexBuffer.byteLength;
+
+        this.bufferViews.push({
+            buffer: 0,
+            byteOffset: this.byteOffset,
+            byteLength: normalBuffer.byteLength,
+            target: 34962 // ARRAY_BUFFER
+        });
+        this.byteOffset += normalBuffer.byteLength;
+
+        this.bufferViews.push({
+            buffer: 0,
+            byteOffset: this.byteOffset,
+            byteLength: colorBuffer.byteLength,
+            target: 34962 // ARRAY_BUFFER
+        });
+        this.byteOffset += colorBuffer.byteLength;
+
+        this.bufferViews.push({
+            buffer: 0,
+            byteOffset: this.byteOffset,
+            byteLength: indexBuffer.byteLength,
+            target: 34963 // ELEMENT_ARRAY_BUFFER
+        });
+        this.byteOffset += indexBuffer.byteLength;
+
+        // accessors
+        const accessorOffset = this.accessors.length;
+        this.accessors.push({
+            bufferView: bufferViewOffset,
+            byteOffset: 0,
+            componentType: 5126, // FLOAT
+            count: vertexCount,
+            type: 'VEC3',
+            max: vertexMax,
+            min: vertexMin
+        });
+        this.accessors.push({
+            bufferView: bufferViewOffset + 1,
+            byteOffset: 0,
+            componentType: 5126, // FLOAT
+            count: vertexCount,
+            type: 'VEC3',
+            max: normalMax,
+            min: normalMin
+        });
+        this.accessors.push({
+            bufferView: bufferViewOffset + 2,
+            byteOffset: 0,
+            componentType: 5126, // FLOAT
+            count: vertexCount,
+            type: 'VEC4',
+            max: [...colorMax, uAlpha],
+            min: [...colorMin, uAlpha]
+        });
+        this.accessors.push({
+            bufferView: bufferViewOffset + 3,
+            byteOffset: 0,
+            componentType: 5125, // UNSIGNED_INT
+            count: drawCount,
+            type: 'SCALAR',
+            max: [ indexMax ],
+            min: [ indexMin ]
+        });
+
+        // primitive
+        this.primitives.push({
+            attributes: {
+                POSITION: accessorOffset,
+                NORMAL: accessorOffset + 1,
+                COLOR_0: accessorOffset + 2,
+            },
+            indices: accessorOffset + 3,
+            material: 0
+        });
+    }
+
+    getData() {
+        const binaryBufferLength = this.byteOffset;
+
+        const gltf = {
+            asset: {
+                version: '2.0'
+            },
+            scenes: [{
+                nodes: [ 0 ]
+            }],
+            nodes: [{
+                mesh: 0
+            }],
+            meshes: [{
+                primitives: this.primitives
+            }],
+            buffers: [{
+                byteLength: binaryBufferLength,
+            }],
+            bufferViews: this.bufferViews,
+            accessors: this.accessors,
+            materials: [{}]
+        };
+
+        const createChunk = (chunkType: number, data: ArrayBuffer[], byteLength: number, padChar: number): [ArrayBuffer[], number] => {
+            let padding = null;
+            if (byteLength % 4 !== 0) {
+                const pad = 4 - (byteLength % 4);
+                byteLength += pad;
+                padding = new Uint8Array(pad);
+                padding.fill(padChar);
+            }
+            const preamble = new ArrayBuffer(8);
+            const preambleDataView = new DataView(preamble);
+            preambleDataView.setUint32(0, byteLength, true);
+            preambleDataView.setUint32(4, chunkType, true);
+            const chunk = [preamble, ...data];
+            if (padding) {
+                chunk.push(padding.buffer);
+            }
+            return [ chunk, 8 + byteLength ];
+        };
+        const jsonString = JSON.stringify(gltf);
+        const jsonBuffer = new Uint8Array(jsonString.length);
+        asciiWrite(jsonBuffer, jsonString);
+
+        const [ jsonChunk, jsonChunkLength ] = createChunk(0x4E4F534A, [jsonBuffer.buffer], jsonBuffer.length, 0x20);
+        const [ binaryChunk, binaryChunkLength ] = createChunk(0x004E4942, this.binaryBuffer, binaryBufferLength, 0x00);
+
+        const glbBufferLength = 12 + jsonChunkLength + binaryChunkLength;
+        const header = new ArrayBuffer(12);
+        const headerDataView = new DataView(header);
+        headerDataView.setUint32(0, 0x46546C67, true); // magic number "glTF"
+        headerDataView.setUint32(4, 2, true); // version
+        headerDataView.setUint32(8, glbBufferLength, true); // length
+        const glbBuffer = [header, ...jsonChunk, ...binaryChunk];
+
+        const glb = new Uint8Array(glbBufferLength);
+        let offset = 0;
+        for (const buffer of glbBuffer) {
+            glb.set(new Uint8Array(buffer), offset);
+            offset += buffer.byteLength;
+        }
+        return { glb };
+    }
+
+    async getBlob(ctx: RuntimeContext) {
+        return new Blob([this.getData().glb], { type: 'model/gltf-binary' });
+    }
+}

+ 18 - 174
src/extensions/geo-export/export.ts → src/extensions/geo-export/mesh-exporter.ts

@@ -17,48 +17,23 @@ import { WebGLContext } from '../../mol-gl/webgl/context';
 import { MeshBuilder } from '../../mol-geo/geometry/mesh/mesh-builder';
 import { addSphere } from '../../mol-geo/geometry/mesh/builder/sphere';
 import { addCylinder } from '../../mol-geo/geometry/mesh/builder/cylinder';
-import { Vec3, Mat3, Mat4 } from '../../mol-math/linear-algebra';
+import { sizeDataFactor } from '../../mol-geo/geometry/size-data';
+import { Vec3 } from '../../mol-math/linear-algebra';
 import { RuntimeContext } from '../../mol-task';
-import { StringBuilder } from '../../mol-util';
-import { Color } from '../../mol-util/color/color';
 import { decodeFloatRGB } from '../../mol-util/float-packing';
+import { RenderObjectExporter, RenderObjectExportData } from './render-object-exporter';
 
 // avoiding namespace lookup improved performance in Chrome (Aug 2020)
 const v3fromArray = Vec3.fromArray;
-const v3transformMat4 = Vec3.transformMat4;
-const v3transformMat3 = Vec3.transformMat3;
-const mat3directionTransform = Mat3.directionTransform;
-
-type RenderObjectExportData = {
-    [k: string]: string | Uint8Array | undefined
-}
-
-interface RenderObjectExporter<D extends RenderObjectExportData> {
-    add(renderObject: GraphicsRenderObject, webgl: WebGLContext, ctx: RuntimeContext): Promise<void> | undefined
-    getData(): D
-}
-
-// http://paulbourke.net/dataformats/obj/
-// http://paulbourke.net/dataformats/mtl/
-
-export type ObjData = {
-    obj: string
-    mtl: string
-}
-
-export class ObjExporter implements RenderObjectExporter<ObjData> {
-    private obj = StringBuilder.create();
-    private mtl = StringBuilder.create();
-    private vertexOffset = 0;
-    private currentColor: Color | undefined;
-    private currentAlpha: number | undefined;
-    private materialSet = new Set<string>();
+
+export abstract class MeshExporter<D extends RenderObjectExportData> implements RenderObjectExporter<D> {
+    abstract readonly fileExtension: string;
 
     private static getSizeFromTexture(tSize: TextureImage<Uint8Array>, i: number): number {
         const r = tSize.array[i * 3];
         const g = tSize.array[i * 3 + 1];
         const b = tSize.array[i * 3 + 2];
-        return decodeFloatRGB(r, g, b);
+        return decodeFloatRGB(r, g, b) / sizeDataFactor;
     }
 
     private static getSize(values: BaseValues & SizeValues, instanceIndex: number, group: number): number {
@@ -69,20 +44,20 @@ export class ObjExporter implements RenderObjectExporter<ObjData> {
                 size = values.uSize.ref.value;
                 break;
             case 'instance':
-                size = ObjExporter.getSizeFromTexture(tSize, instanceIndex) / 100;
+                size = MeshExporter.getSizeFromTexture(tSize, instanceIndex);
                 break;
             case 'group':
-                size = ObjExporter.getSizeFromTexture(tSize, group) / 100;
+                size = MeshExporter.getSizeFromTexture(tSize, group);
                 break;
             case 'groupInstance':
                 const groupCount = values.uGroupCount.ref.value;
-                size = ObjExporter.getSizeFromTexture(tSize, instanceIndex * groupCount + group) / 100;
+                size = MeshExporter.getSizeFromTexture(tSize, instanceIndex * groupCount + group);
                 break;
         }
         return size * values.uSizeFactor.ref.value;
     }
 
-    private static getGroup(groups: Float32Array | Uint8Array, i: number): number {
+    protected static getGroup(groups: Float32Array | Uint8Array, i: number): number {
         const i4 = i * 4;
         const r = groups[i4];
         const g = groups[i4 + 1];
@@ -93,131 +68,7 @@ export class ObjExporter implements RenderObjectExporter<ObjData> {
         return decodeFloatRGB(r, g, b);
     }
 
-    private updateMaterial(color: Color, alpha: number) {
-        if (this.currentColor === color && this.currentAlpha === alpha) return;
-
-        this.currentColor = color;
-        this.currentAlpha = alpha;
-        const material = Color.toHexString(color) + alpha;
-        StringBuilder.writeSafe(this.obj, `usemtl ${material}`);
-        StringBuilder.newline(this.obj);
-        if (!this.materialSet.has(material)) {
-            this.materialSet.add(material);
-            const [r, g, b] = Color.toRgbNormalized(color);
-            const mtl = this.mtl;
-            StringBuilder.writeSafe(mtl, `newmtl ${material}\n`);
-            StringBuilder.writeSafe(mtl, 'illum 2\n'); // illumination model
-            StringBuilder.writeSafe(mtl, 'Ns 163\n'); // specular exponent
-            StringBuilder.writeSafe(mtl, 'Ni 0.001\n'); // optical density a.k.a. index of refraction
-            StringBuilder.writeSafe(mtl, 'Ka 0 0 0\n'); // ambient reflectivity
-            StringBuilder.writeSafe(mtl, 'Kd '); // diffuse reflectivity
-            StringBuilder.writeFloat(mtl, r, 1000);
-            StringBuilder.whitespace1(mtl);
-            StringBuilder.writeFloat(mtl, g, 1000);
-            StringBuilder.whitespace1(mtl);
-            StringBuilder.writeFloat(mtl, b, 1000);
-            StringBuilder.newline(mtl);
-            StringBuilder.writeSafe(mtl, 'Ks 0.25 0.25 0.25\n'); // specular reflectivity
-            StringBuilder.writeSafe(mtl, 'd '); // dissolve
-            StringBuilder.writeFloat(mtl, alpha, 1000);
-            StringBuilder.newline(mtl);
-        }
-    }
-
-    private async addMeshWithColors(vertices: Float32Array, normals: Float32Array, indices: Uint32Array | undefined, groups: Float32Array | Uint8Array, vertexCount: number, drawCount: number, values: BaseValues, instanceIndex: number, geoTexture: boolean, ctx: RuntimeContext) {
-        const obj = this.obj;
-        const t = Mat4();
-        const n = Mat3();
-        const tmpV = Vec3();
-        const stride = geoTexture ? 4 : 3;
-
-        const colorType = values.dColorType.ref.value;
-        const tColor = values.tColor.ref.value.array;
-        const uAlpha = values.uAlpha.ref.value;
-        const aTransform = values.aTransform.ref.value;
-
-        Mat4.fromArray(t, aTransform, instanceIndex * 16);
-        mat3directionTransform(n, t);
-
-        const currentProgress = (vertexCount * 2 + drawCount) * instanceIndex;
-        await ctx.update({ isIndeterminate: false, current: currentProgress, max: (vertexCount * 2 + drawCount) * values.uInstanceCount.ref.value });
-
-        // position
-        for (let i = 0; i < vertexCount; ++i) {
-            if (i % 1000 === 0 && ctx.shouldUpdate) await ctx.update({ current: currentProgress + i });
-            v3transformMat4(tmpV, v3fromArray(tmpV, vertices, i * stride), t);
-            StringBuilder.writeSafe(obj, 'v ');
-            StringBuilder.writeFloat(obj, tmpV[0], 1000);
-            StringBuilder.whitespace1(obj);
-            StringBuilder.writeFloat(obj, tmpV[1], 1000);
-            StringBuilder.whitespace1(obj);
-            StringBuilder.writeFloat(obj, tmpV[2], 1000);
-            StringBuilder.newline(obj);
-        }
-
-        // normal
-        for (let i = 0; i < vertexCount; ++i) {
-            if (i % 1000 === 0 && ctx.shouldUpdate) await ctx.update({ current: currentProgress + vertexCount + i });
-            v3transformMat3(tmpV, v3fromArray(tmpV, normals, i * stride), n);
-            StringBuilder.writeSafe(obj, 'vn ');
-            StringBuilder.writeFloat(obj, tmpV[0], 100);
-            StringBuilder.whitespace1(obj);
-            StringBuilder.writeFloat(obj, tmpV[1], 100);
-            StringBuilder.whitespace1(obj);
-            StringBuilder.writeFloat(obj, tmpV[2], 100);
-            StringBuilder.newline(obj);
-        }
-
-        // face
-        for (let i = 0; i < drawCount; i += 3) {
-            if (i % 3000 === 0 && ctx.shouldUpdate) await ctx.update({ current: currentProgress + vertexCount * 2 + i });
-            let color: Color;
-            switch (colorType) {
-                case 'uniform':
-                    color = Color.fromNormalizedArray(values.uColor.ref.value, 0);
-                    break;
-                case 'instance':
-                    color = Color.fromArray(tColor, instanceIndex * 3);
-                    break;
-                case 'group': {
-                    const group = geoTexture ? ObjExporter.getGroup(groups, i) : groups[indices![i]];
-                    color = Color.fromArray(tColor, group * 3);
-                    break;
-                }
-                case 'groupInstance': {
-                    const groupCount = values.uGroupCount.ref.value;
-                    const group = geoTexture ? ObjExporter.getGroup(groups, i) : groups[indices![i]];
-                    color = Color.fromArray(tColor, (instanceIndex * groupCount + group) * 3);
-                    break;
-                }
-                case 'vertex':
-                    color = Color.fromArray(tColor, i * 3);
-                    break;
-                case 'vertexInstance':
-                    color = Color.fromArray(tColor, (instanceIndex * drawCount + i) * 3);
-                    break;
-                default: throw new Error('Unsupported color type.');
-            }
-            this.updateMaterial(color, uAlpha);
-
-            const v1 = this.vertexOffset + (geoTexture ? i : indices![i]) + 1;
-            const v2 = this.vertexOffset + (geoTexture ? i + 1 : indices![i + 1]) + 1;
-            const v3 = this.vertexOffset + (geoTexture ? i + 2 : indices![i + 2]) + 1;
-            StringBuilder.writeSafe(obj, 'f ');
-            StringBuilder.writeInteger(obj, v1);
-            StringBuilder.writeSafe(obj, '//');
-            StringBuilder.writeIntegerAndSpace(obj, v1);
-            StringBuilder.writeInteger(obj, v2);
-            StringBuilder.writeSafe(obj, '//');
-            StringBuilder.writeIntegerAndSpace(obj, v2);
-            StringBuilder.writeInteger(obj, v3);
-            StringBuilder.writeSafe(obj, '//');
-            StringBuilder.writeInteger(obj, v3);
-            StringBuilder.newline(obj);
-        }
-
-        this.vertexOffset += vertexCount;
-    }
+    protected abstract addMeshWithColors(vertices: Float32Array, normals: Float32Array, indices: Uint32Array | undefined, groups: Float32Array | Uint8Array, vertexCount: number, drawCount: number, values: BaseValues, instanceIndex: number, isGeoTexture: boolean, ctx: RuntimeContext): void;
 
     private async addMesh(values: MeshValues, ctx: RuntimeContext) {
         const aPosition = values.aPosition.ref.value;
@@ -256,7 +107,7 @@ export class ObjExporter implements RenderObjectExporter<ObjData> {
                 v3fromArray(center, aPosition, i * 3);
 
                 const group = aGroup[i];
-                const radius = ObjExporter.getSize(values, instanceIndex, group);
+                const radius = MeshExporter.getSize(values, instanceIndex, group);
                 state.currentGroup = group;
                 addSphere(state, center, radius, 2);
             }
@@ -266,7 +117,7 @@ export class ObjExporter implements RenderObjectExporter<ObjData> {
             const normals = mesh.normalBuffer.ref.value;
             const indices = mesh.indexBuffer.ref.value;
             const groups = mesh.groupBuffer.ref.value;
-            await this.addMeshWithColors(vertices, normals, indices, groups, vertices.length / 3, indices.length, values, instanceIndex, false, ctx);
+            await this.addMeshWithColors(vertices, normals, indices, groups, mesh.vertexCount, indices.length, values, instanceIndex, false, ctx);
         }
     }
 
@@ -290,7 +141,7 @@ export class ObjExporter implements RenderObjectExporter<ObjData> {
                 v3fromArray(end, aEnd, i * 3);
 
                 const group = aGroup[i];
-                const radius = ObjExporter.getSize(values, instanceIndex, group) * aScale[i];
+                const radius = MeshExporter.getSize(values, instanceIndex, group) * aScale[i];
                 const cap = aCap[i];
                 const topCap = cap === 1 || cap === 3;
                 const bottomCap = cap >= 2;
@@ -304,7 +155,7 @@ export class ObjExporter implements RenderObjectExporter<ObjData> {
             const normals = mesh.normalBuffer.ref.value;
             const indices = mesh.indexBuffer.ref.value;
             const groups = mesh.groupBuffer.ref.value;
-            await this.addMeshWithColors(vertices, normals, indices, groups, vertices.length / 3, indices.length, values, instanceIndex, false, ctx);
+            await this.addMeshWithColors(vertices, normals, indices, groups, mesh.vertexCount, indices.length, values, instanceIndex, false, ctx);
         }
     }
 
@@ -356,14 +207,7 @@ export class ObjExporter implements RenderObjectExporter<ObjData> {
         }
     }
 
-    getData() {
-        return {
-            obj: StringBuilder.getString(this.obj),
-            mtl: StringBuilder.getString(this.mtl)
-        };
-    }
+    abstract getData(): D;
 
-    constructor(filename: string) {
-        StringBuilder.writeSafe(this.obj, `mtllib ${filename}.mtl\n`);
-    }
+    abstract getBlob(ctx: RuntimeContext): Promise<Blob>;
 }

+ 189 - 0
src/extensions/geo-export/obj-exporter.ts

@@ -0,0 +1,189 @@
+/**
+ * Copyright (c) 2021 mol* contributors, licensed under MIT, See LICENSE file for more info.
+ *
+ * @author Sukolsak Sakshuwong <sukolsak@stanford.edu>
+ */
+
+import { BaseValues } from '../../mol-gl/renderable/schema';
+import { asciiWrite } from '../../mol-io/common/ascii';
+import { Vec3, Mat3, Mat4 } from '../../mol-math/linear-algebra';
+import { RuntimeContext } from '../../mol-task';
+import { StringBuilder } from '../../mol-util';
+import { Color } from '../../mol-util/color/color';
+import { zip } from '../../mol-util/zip/zip';
+import { MeshExporter } from './mesh-exporter';
+
+// avoiding namespace lookup improved performance in Chrome (Aug 2020)
+const v3fromArray = Vec3.fromArray;
+const v3transformMat4 = Vec3.transformMat4;
+const v3transformMat3 = Vec3.transformMat3;
+const mat3directionTransform = Mat3.directionTransform;
+
+// http://paulbourke.net/dataformats/obj/
+// http://paulbourke.net/dataformats/mtl/
+
+export type ObjData = {
+    obj: string
+    mtl: string
+}
+
+export class ObjExporter extends MeshExporter<ObjData> {
+    readonly fileExtension = 'zip';
+    private obj = StringBuilder.create();
+    private mtl = StringBuilder.create();
+    private vertexOffset = 0;
+    private currentColor: Color | undefined;
+    private currentAlpha: number | undefined;
+    private materialSet = new Set<string>();
+
+    private updateMaterial(color: Color, alpha: number) {
+        if (this.currentColor === color && this.currentAlpha === alpha) return;
+
+        this.currentColor = color;
+        this.currentAlpha = alpha;
+        const material = Color.toHexString(color) + alpha;
+        StringBuilder.writeSafe(this.obj, `usemtl ${material}`);
+        StringBuilder.newline(this.obj);
+        if (!this.materialSet.has(material)) {
+            this.materialSet.add(material);
+            const [r, g, b] = Color.toRgbNormalized(color);
+            const mtl = this.mtl;
+            StringBuilder.writeSafe(mtl, `newmtl ${material}\n`);
+            StringBuilder.writeSafe(mtl, 'illum 2\n'); // illumination model
+            StringBuilder.writeSafe(mtl, 'Ns 163\n'); // specular exponent
+            StringBuilder.writeSafe(mtl, 'Ni 0.001\n'); // optical density a.k.a. index of refraction
+            StringBuilder.writeSafe(mtl, 'Ka 0 0 0\n'); // ambient reflectivity
+            StringBuilder.writeSafe(mtl, 'Kd '); // diffuse reflectivity
+            StringBuilder.writeFloat(mtl, r, 1000);
+            StringBuilder.whitespace1(mtl);
+            StringBuilder.writeFloat(mtl, g, 1000);
+            StringBuilder.whitespace1(mtl);
+            StringBuilder.writeFloat(mtl, b, 1000);
+            StringBuilder.newline(mtl);
+            StringBuilder.writeSafe(mtl, 'Ks 0.25 0.25 0.25\n'); // specular reflectivity
+            StringBuilder.writeSafe(mtl, 'd '); // dissolve
+            StringBuilder.writeFloat(mtl, alpha, 1000);
+            StringBuilder.newline(mtl);
+        }
+    }
+
+    protected async addMeshWithColors(vertices: Float32Array, normals: Float32Array, indices: Uint32Array | undefined, groups: Float32Array | Uint8Array, vertexCount: number, drawCount: number, values: BaseValues, instanceIndex: number, isGeoTexture: boolean, ctx: RuntimeContext) {
+        const obj = this.obj;
+        const t = Mat4();
+        const n = Mat3();
+        const tmpV = Vec3();
+        const stride = isGeoTexture ? 4 : 3;
+
+        const colorType = values.dColorType.ref.value;
+        const tColor = values.tColor.ref.value.array;
+        const uAlpha = values.uAlpha.ref.value;
+        const aTransform = values.aTransform.ref.value;
+
+        Mat4.fromArray(t, aTransform, instanceIndex * 16);
+        mat3directionTransform(n, t);
+
+        const currentProgress = (vertexCount * 2 + drawCount) * instanceIndex;
+        await ctx.update({ isIndeterminate: false, current: currentProgress, max: (vertexCount * 2 + drawCount) * values.uInstanceCount.ref.value });
+
+        // position
+        for (let i = 0; i < vertexCount; ++i) {
+            if (i % 1000 === 0 && ctx.shouldUpdate) await ctx.update({ current: currentProgress + i });
+            v3transformMat4(tmpV, v3fromArray(tmpV, vertices, i * stride), t);
+            StringBuilder.writeSafe(obj, 'v ');
+            StringBuilder.writeFloat(obj, tmpV[0], 1000);
+            StringBuilder.whitespace1(obj);
+            StringBuilder.writeFloat(obj, tmpV[1], 1000);
+            StringBuilder.whitespace1(obj);
+            StringBuilder.writeFloat(obj, tmpV[2], 1000);
+            StringBuilder.newline(obj);
+        }
+
+        // normal
+        for (let i = 0; i < vertexCount; ++i) {
+            if (i % 1000 === 0 && ctx.shouldUpdate) await ctx.update({ current: currentProgress + vertexCount + i });
+            v3transformMat3(tmpV, v3fromArray(tmpV, normals, i * stride), n);
+            StringBuilder.writeSafe(obj, 'vn ');
+            StringBuilder.writeFloat(obj, tmpV[0], 100);
+            StringBuilder.whitespace1(obj);
+            StringBuilder.writeFloat(obj, tmpV[1], 100);
+            StringBuilder.whitespace1(obj);
+            StringBuilder.writeFloat(obj, tmpV[2], 100);
+            StringBuilder.newline(obj);
+        }
+
+        // face
+        for (let i = 0; i < drawCount; i += 3) {
+            if (i % 3000 === 0 && ctx.shouldUpdate) await ctx.update({ current: currentProgress + vertexCount * 2 + i });
+            let color: Color;
+            switch (colorType) {
+                case 'uniform':
+                    color = Color.fromNormalizedArray(values.uColor.ref.value, 0);
+                    break;
+                case 'instance':
+                    color = Color.fromArray(tColor, instanceIndex * 3);
+                    break;
+                case 'group': {
+                    const group = isGeoTexture ? ObjExporter.getGroup(groups, i) : groups[indices![i]];
+                    color = Color.fromArray(tColor, group * 3);
+                    break;
+                }
+                case 'groupInstance': {
+                    const groupCount = values.uGroupCount.ref.value;
+                    const group = isGeoTexture ? ObjExporter.getGroup(groups, i) : groups[indices![i]];
+                    color = Color.fromArray(tColor, (instanceIndex * groupCount + group) * 3);
+                    break;
+                }
+                case 'vertex':
+                    color = Color.fromArray(tColor, indices![i] * 3);
+                    break;
+                case 'vertexInstance':
+                    color = Color.fromArray(tColor, (instanceIndex * drawCount + indices![i]) * 3);
+                    break;
+                default: throw new Error('Unsupported color type.');
+            }
+            this.updateMaterial(color, uAlpha);
+
+            const v1 = this.vertexOffset + (isGeoTexture ? i : indices![i]) + 1;
+            const v2 = this.vertexOffset + (isGeoTexture ? i + 1 : indices![i + 1]) + 1;
+            const v3 = this.vertexOffset + (isGeoTexture ? i + 2 : indices![i + 2]) + 1;
+            StringBuilder.writeSafe(obj, 'f ');
+            StringBuilder.writeInteger(obj, v1);
+            StringBuilder.writeSafe(obj, '//');
+            StringBuilder.writeIntegerAndSpace(obj, v1);
+            StringBuilder.writeInteger(obj, v2);
+            StringBuilder.writeSafe(obj, '//');
+            StringBuilder.writeIntegerAndSpace(obj, v2);
+            StringBuilder.writeInteger(obj, v3);
+            StringBuilder.writeSafe(obj, '//');
+            StringBuilder.writeInteger(obj, v3);
+            StringBuilder.newline(obj);
+        }
+
+        this.vertexOffset += vertexCount;
+    }
+
+    getData() {
+        return {
+            obj: StringBuilder.getString(this.obj),
+            mtl: StringBuilder.getString(this.mtl)
+        };
+    }
+
+    async getBlob(ctx: RuntimeContext) {
+        const { obj, mtl } = this.getData();
+        const objData = new Uint8Array(obj.length);
+        asciiWrite(objData, obj);
+        const mtlData = new Uint8Array(mtl.length);
+        asciiWrite(mtlData, mtl);
+        const zipDataObj = {
+            [this.filename + '.obj']: objData,
+            [this.filename + '.mtl']: mtlData
+        };
+        return new Blob([await zip(ctx, zipDataObj)], { type: 'application/zip' });
+    }
+
+    constructor(private filename: string) {
+        super();
+        StringBuilder.writeSafe(this.obj, `mtllib ${filename}.mtl\n`);
+    }
+}

+ 20 - 0
src/extensions/geo-export/render-object-exporter.ts

@@ -0,0 +1,20 @@
+/**
+ * Copyright (c) 2021 mol* contributors, licensed under MIT, See LICENSE file for more info.
+ *
+ * @author Sukolsak Sakshuwong <sukolsak@stanford.edu>
+ */
+
+import { GraphicsRenderObject } from '../../mol-gl/render-object';
+import { WebGLContext } from '../../mol-gl/webgl/context';
+import { RuntimeContext } from '../../mol-task';
+
+export type RenderObjectExportData = {
+    [k: string]: string | Uint8Array | undefined
+}
+
+export interface RenderObjectExporter<D extends RenderObjectExportData> {
+    readonly fileExtension: string
+    add(renderObject: GraphicsRenderObject, webgl: WebGLContext, ctx: RuntimeContext): Promise<void> | undefined
+    getData(): D
+    getBlob(ctx: RuntimeContext): Promise<Blob>
+}

+ 105 - 0
src/extensions/geo-export/stl-exporter.ts

@@ -0,0 +1,105 @@
+/**
+ * Copyright (c) 2021 mol* contributors, licensed under MIT, See LICENSE file for more info.
+ *
+ * @author Sukolsak Sakshuwong <sukolsak@stanford.edu>
+ */
+
+import { BaseValues } from '../../mol-gl/renderable/schema';
+import { asciiWrite } from '../../mol-io/common/ascii';
+import { Vec3, Mat4 } from '../../mol-math/linear-algebra';
+import { PLUGIN_VERSION } from '../../mol-plugin/version';
+import { RuntimeContext } from '../../mol-task';
+import { MeshExporter } from './mesh-exporter';
+
+// avoiding namespace lookup improved performance in Chrome (Aug 2020)
+const v3fromArray = Vec3.fromArray;
+const v3transformMat4 = Vec3.transformMat4;
+const v3triangleNormal = Vec3.triangleNormal;
+const v3toArray = Vec3.toArray;
+
+// https://www.fabbers.com/tech/STL_Format
+
+export type StlData = {
+    stl: Uint8Array
+}
+
+export class StlExporter extends MeshExporter<StlData> {
+    readonly fileExtension = 'stl';
+    private triangleBuffers: ArrayBuffer[] = [];
+    private triangleCount = 0;
+
+    protected async addMeshWithColors(vertices: Float32Array, normals: Float32Array, indices: Uint32Array | undefined, groups: Float32Array | Uint8Array, vertexCount: number, drawCount: number, values: BaseValues, instanceIndex: number, isGeoTexture: boolean, ctx: RuntimeContext) {
+        const t = Mat4();
+        const tmpV = Vec3();
+        const v1 = Vec3();
+        const v2 = Vec3();
+        const v3 = Vec3();
+        const stride = isGeoTexture ? 4 : 3;
+
+        const aTransform = values.aTransform.ref.value;
+        Mat4.fromArray(t, aTransform, instanceIndex * 16);
+
+        const currentProgress = (vertexCount + drawCount) * instanceIndex;
+        await ctx.update({ isIndeterminate: false, current: currentProgress, max: (vertexCount + drawCount) * values.uInstanceCount.ref.value });
+
+        // position
+        const vertexArray = new Float32Array(vertexCount * 3);
+        for (let i = 0; i < vertexCount; ++i) {
+            if (i % 1000 === 0 && ctx.shouldUpdate) await ctx.update({ current: currentProgress + i });
+            v3transformMat4(tmpV, v3fromArray(tmpV, vertices, i * stride), t);
+            v3toArray(tmpV, vertexArray, i * 3);
+        }
+
+        // face
+        const triangleBuffer = new ArrayBuffer(50 * drawCount);
+        const dataView = new DataView(triangleBuffer);
+        for (let i = 0; i < drawCount; i += 3) {
+            if (i % 3000 === 0 && ctx.shouldUpdate) await ctx.update({ current: currentProgress + vertexCount + i });
+
+            v3fromArray(v1, vertexArray, (isGeoTexture ? i : indices![i]) * 3);
+            v3fromArray(v2, vertexArray, (isGeoTexture ? i + 1 : indices![i + 1]) * 3);
+            v3fromArray(v3, vertexArray, (isGeoTexture ? i + 2 : indices![i + 2]) * 3);
+            v3triangleNormal(tmpV, v1, v2, v3);
+
+            const byteOffset = 50 * i;
+            dataView.setFloat32(byteOffset, tmpV[0], true);
+            dataView.setFloat32(byteOffset + 4, tmpV[1], true);
+            dataView.setFloat32(byteOffset + 8, tmpV[2], true);
+
+            dataView.setFloat32(byteOffset + 12, v1[0], true);
+            dataView.setFloat32(byteOffset + 16, v1[1], true);
+            dataView.setFloat32(byteOffset + 20, v1[2], true);
+
+            dataView.setFloat32(byteOffset + 24, v2[0], true);
+            dataView.setFloat32(byteOffset + 28, v2[1], true);
+            dataView.setFloat32(byteOffset + 32, v2[2], true);
+
+            dataView.setFloat32(byteOffset + 36, v3[0], true);
+            dataView.setFloat32(byteOffset + 40, v3[1], true);
+            dataView.setFloat32(byteOffset + 44, v3[2], true);
+        }
+
+        this.triangleBuffers.push(triangleBuffer);
+        this.triangleCount += drawCount;
+    }
+
+    getData() {
+        const stl = new Uint8Array(84 + 50 * this.triangleCount);
+
+        asciiWrite(stl, `Exported from Mol* ${PLUGIN_VERSION}`);
+
+        const dataView = new DataView(stl.buffer);
+        dataView.setUint32(80, this.triangleCount, true);
+
+        let byteOffset = 84;
+        for (const buffer of this.triangleBuffers) {
+            stl.set(new Uint8Array(buffer), byteOffset);
+            byteOffset += buffer.byteLength;
+        }
+        return { stl };
+    }
+
+    async getBlob(ctx: RuntimeContext) {
+        return new Blob([this.getData().stl], { type: 'model/stl' });
+    }
+}

+ 22 - 8
src/extensions/geo-export/ui.tsx

@@ -4,11 +4,13 @@
  * @author Sukolsak Sakshuwong <sukolsak@stanford.edu>
  */
 
+import { merge } from 'rxjs';
 import { CollapsableControls, CollapsableState } from '../../mol-plugin-ui/base';
 import { Button } from '../../mol-plugin-ui/controls/common';
 import { GetAppSvg, CubeSendSvg } from '../../mol-plugin-ui/controls/icons';
+import { ParameterControls } from '../../mol-plugin-ui/controls/parameters';
 import { download } from '../../mol-util/download';
-import { GeometryControls } from './controls';
+import { GeometryParams, GeometryControls } from './controls';
 
 interface State {
     busy?: boolean
@@ -23,24 +25,36 @@ export class GeometryExporterUI extends CollapsableControls<{}, State> {
 
     protected defaultState(): State & CollapsableState {
         return {
-            header: 'Export Geometries',
+            header: 'Export Geometry',
             isCollapsed: true,
             brand: { accent: 'cyan', svg: CubeSendSvg }
         };
     }
 
     protected renderControls(): JSX.Element {
+        const ctrl = this.controls;
         return <>
+            <ParameterControls
+                params={GeometryParams}
+                values={ctrl.behaviors.params.value}
+                onChangeValues={xs => ctrl.behaviors.params.next(xs)}
+                isDisabled={this.state.busy}
+            />
             <Button icon={GetAppSvg}
-                onClick={this.saveObj} style={{ marginTop: 1 }}
+                onClick={this.save} style={{ marginTop: 1 }}
                 disabled={this.state.busy || !this.plugin.canvas3d?.reprCount.value}>
-                Save OBJ + MTL
+                Save
             </Button>
         </>;
     }
 
     componentDidMount() {
-        this.subscribe(this.plugin.canvas3d!.reprCount, () => {
+        const merged = merge(
+            this.controls.behaviors.params,
+            this.plugin.canvas3d!.reprCount
+        );
+
+        this.subscribe(merged, () => {
             if (!this.state.isCollapsed) this.forceUpdate();
         });
     }
@@ -50,13 +64,13 @@ export class GeometryExporterUI extends CollapsableControls<{}, State> {
         this._controls = void 0;
     }
 
-    saveObj = async () => {
+    save = async () => {
         try {
             this.setState({ busy: true });
-            const data = await this.controls.exportObj();
+            const data = await this.controls.exportGeometry();
             this.setState({ busy: false });
 
-            download(new Blob([data.zipData]), data.filename);
+            download(data.blob, data.filename);
         } catch {
             this.setState({ busy: false });
         }

+ 5 - 5
src/mol-geo/geometry/size-data.ts

@@ -31,7 +31,7 @@ export function createSizes(locationIt: LocationIterator, sizeTheme: SizeTheme<a
     }
 }
 
-const sizeFactor = 100; // NOTE same factor is set in shaders
+export const sizeDataFactor = 100; // NOTE same factor is set in shaders
 
 export function getMaxSize(sizeData: SizeData): number {
     const type = sizeData.dSizeType.ref.value as SizeType;
@@ -47,7 +47,7 @@ export function getMaxSize(sizeData: SizeData): number {
                 const value = decodeFloatRGB(array[i], array[i + 1], array[i + 2]);
                 if (maxSize < value) maxSize = value;
             }
-            return maxSize / sizeFactor;
+            return maxSize / sizeDataFactor;
     }
 }
 
@@ -103,7 +103,7 @@ export function createInstanceSize(locationIt: LocationIterator, sizeFn: Locatio
     locationIt.reset();
     while (locationIt.hasNext && !locationIt.isNextNewInstance) {
         const v = locationIt.move();
-        encodeFloatRGBtoArray(sizeFn(v.location) * sizeFactor, sizes.array, v.instanceIndex * 3);
+        encodeFloatRGBtoArray(sizeFn(v.location) * sizeDataFactor, sizes.array, v.instanceIndex * 3);
         locationIt.skipInstance();
     }
     return createTextureSize(sizes, 'instance', sizeData);
@@ -116,7 +116,7 @@ export function createGroupSize(locationIt: LocationIterator, sizeFn: LocationSi
     locationIt.reset();
     while (locationIt.hasNext && !locationIt.isNextNewInstance) {
         const v = locationIt.move();
-        encodeFloatRGBtoArray(sizeFn(v.location) * sizeFactor, sizes.array, v.groupIndex * 3);
+        encodeFloatRGBtoArray(sizeFn(v.location) * sizeDataFactor, sizes.array, v.groupIndex * 3);
     }
     return createTextureSize(sizes, 'group', sizeData);
 }
@@ -129,7 +129,7 @@ export function createGroupInstanceSize(locationIt: LocationIterator, sizeFn: Lo
     locationIt.reset();
     while (locationIt.hasNext) {
         const v = locationIt.move();
-        encodeFloatRGBtoArray(sizeFn(v.location) * sizeFactor, sizes.array, v.index * 3);
+        encodeFloatRGBtoArray(sizeFn(v.location) * sizeDataFactor, sizes.array, v.index * 3);
     }
     return createTextureSize(sizes, 'groupInstance', sizeData);
 }

+ 11 - 0
src/mol-io/common/ascii.ts

@@ -0,0 +1,11 @@
+/**
+ * Copyright (c) 2021 mol* contributors, licensed under MIT, See LICENSE file for more info.
+ *
+ * @author Sukolsak Sakshuwong <sukolsak@stanford.edu>
+ */
+
+export function asciiWrite(data: Uint8Array, str: string) {
+    for (let i = 0, il = str.length; i < il; ++i) {
+        data[i] = str.charCodeAt(i);
+    }
+}