controls.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * Copyright (c) 2021 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Sukolsak Sakshuwong <sukolsak@stanford.edu>
  5. */
  6. import { PluginComponent } from '../../mol-plugin-state/component';
  7. import { PluginContext } from '../../mol-plugin/context';
  8. import { Task } from '../../mol-task';
  9. import { ObjExporter } from './export';
  10. import { PluginStateObject } from '../../mol-plugin-state/objects';
  11. import { StateSelection } from '../../mol-state';
  12. import { SetUtils } from '../../mol-util/set';
  13. import { zip } from '../../mol-util/zip/zip';
  14. export class GeometryControls extends PluginComponent {
  15. getFilename() {
  16. const models = this.plugin.state.data.select(StateSelection.Generators.rootsOfType(PluginStateObject.Molecule.Model)).map(s => s.obj!.data);
  17. const uniqueIds = new Set<string>();
  18. models.forEach(m => uniqueIds.add(m.entryId.toUpperCase()));
  19. const idString = SetUtils.toArray(uniqueIds).join('-');
  20. return `${idString || 'molstar-model'}`;
  21. }
  22. exportObj() {
  23. const task = Task.create('Export OBJ', async ctx => {
  24. try {
  25. const renderObjects = this.plugin.canvas3d?.getRenderObjects()!;
  26. const filename = this.getFilename();
  27. const objExporter = new ObjExporter(filename);
  28. for (let i = 0, il = renderObjects.length; i < il; ++i) {
  29. await ctx.update({ message: `Exporting object ${i}/${il}` });
  30. await objExporter.add(renderObjects[i], ctx);
  31. }
  32. const { obj, mtl } = objExporter.getData();
  33. const asciiWrite = (data: Uint8Array, str: string) => {
  34. for (let i = 0, il = str.length; i < il; ++i) {
  35. data[i] = str.charCodeAt(i);
  36. }
  37. };
  38. const objData = new Uint8Array(obj.length);
  39. asciiWrite(objData, obj);
  40. const mtlData = new Uint8Array(mtl.length);
  41. asciiWrite(mtlData, mtl);
  42. const zipDataObj = {
  43. [filename + '.obj']: objData,
  44. [filename + '.mtl']: mtlData
  45. };
  46. const zipData = await zip(ctx, zipDataObj);
  47. return {
  48. zipData,
  49. filename: filename + '.zip'
  50. };
  51. } catch (e) {
  52. this.plugin.log.error('' + e);
  53. throw e;
  54. }
  55. });
  56. return this.plugin.runTask(task, { useOverlay: true });
  57. }
  58. constructor(private plugin: PluginContext) {
  59. super();
  60. }
  61. }