context.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import { Transformer, Transform, State } from 'mol-state';
  7. import { Canvas3D } from 'mol-canvas3d/canvas3d';
  8. import { StateTransforms } from './state/transforms';
  9. import { PluginStateObject as PSO } from './state/base';
  10. import { PluginStateObjects as SO } from './state/objects';
  11. import { RxEventHelper } from 'mol-util/rx-event-helper';
  12. import { PluginState } from './state';
  13. import { MolScriptBuilder } from 'mol-script/language/builder';
  14. import { PluginCommand, PluginCommands } from './command';
  15. import { Task } from 'mol-task';
  16. import { merge } from 'rxjs';
  17. import { PluginBehaviors } from './behavior';
  18. import { Loci, EmptyLoci } from 'mol-model/loci';
  19. import { Representation } from 'mol-repr';
  20. export class PluginContext {
  21. private disposed = false;
  22. private ev = RxEventHelper.create();
  23. readonly state = new PluginState(this);
  24. readonly commands = new PluginCommand.Manager();
  25. readonly events = {
  26. state: {
  27. data: this.state.data.events,
  28. behavior: this.state.behavior.events
  29. }
  30. };
  31. readonly behaviors = {
  32. state: {
  33. data: this.state.data.behaviors,
  34. behavior: this.state.behavior.behaviors
  35. },
  36. canvas: {
  37. highlightLoci: this.ev.behavior<{ loci: Loci, repr?: Representation.Any }>({ loci: EmptyLoci }),
  38. selectLoci: this.ev.behavior<{ loci: Loci, repr?: Representation.Any }>({ loci: EmptyLoci }),
  39. },
  40. command: this.commands.behaviour
  41. };
  42. readonly canvas3d: Canvas3D;
  43. initViewer(canvas: HTMLCanvasElement, container: HTMLDivElement) {
  44. try {
  45. (this.canvas3d as Canvas3D) = Canvas3D.create(canvas, container);
  46. this.canvas3d.animate();
  47. console.log('canvas3d created');
  48. return true;
  49. } catch (e) {
  50. console.error(e);
  51. return false;
  52. }
  53. }
  54. /**
  55. * This should be used in all transform related request so that it could be "spoofed" to allow
  56. * "static" access to resources.
  57. */
  58. async fetch(url: string, type: 'string' | 'binary' = 'string'): Promise<string | Uint8Array> {
  59. const req = await fetch(url, { referrerPolicy: 'origin-when-cross-origin' });
  60. return type === 'string' ? await req.text() : new Uint8Array(await req.arrayBuffer());
  61. }
  62. async runTask<T>(task: Task<T>) {
  63. return await task.run(p => console.log(p), 250);
  64. }
  65. dispose() {
  66. if (this.disposed) return;
  67. this.commands.dispose();
  68. this.canvas3d.dispose();
  69. this.ev.dispose();
  70. this.state.dispose();
  71. this.disposed = true;
  72. }
  73. async _test_initBehaviours() {
  74. const tree = this.state.behavior.tree.build()
  75. .toRoot().apply(PluginBehaviors.Data.SetCurrentObject, { ref: PluginBehaviors.Data.SetCurrentObject.id })
  76. .and().toRoot().apply(PluginBehaviors.Data.Update, { ref: PluginBehaviors.Data.Update.id })
  77. .and().toRoot().apply(PluginBehaviors.Data.RemoveObject, { ref: PluginBehaviors.Data.RemoveObject.id })
  78. .and().toRoot().apply(PluginBehaviors.Representation.AddRepresentationToCanvas, { ref: PluginBehaviors.Representation.AddRepresentationToCanvas.id })
  79. .and().toRoot().apply(PluginBehaviors.Representation.HighlightLoci, { ref: PluginBehaviors.Representation.HighlightLoci.id })
  80. .and().toRoot().apply(PluginBehaviors.Representation.SelectLoci, { ref: PluginBehaviors.Representation.SelectLoci.id })
  81. .getTree();
  82. await this.runTask(this.state.behavior.update(tree));
  83. }
  84. applyTransform(state: State, a: Transform.Ref, transformer: Transformer, params: any) {
  85. const tree = state.tree.build().to(a).apply(transformer, params);
  86. return PluginCommands.State.Update.dispatch(this, { state, tree });
  87. }
  88. updateTransform(state: State, a: Transform.Ref, params: any) {
  89. const tree = state.build().to(a).update(params);
  90. return PluginCommands.State.Update.dispatch(this, { state, tree });
  91. }
  92. _test_createState(url: string) {
  93. const b = this.state.data.tree.build();
  94. const query = MolScriptBuilder.struct.generator.atomGroups({
  95. // 'atom-test': MolScriptBuilder.core.rel.eq([
  96. // MolScriptBuilder.struct.atomProperty.macromolecular.label_comp_id(),
  97. // MolScriptBuilder.es('C')
  98. // ]),
  99. 'residue-test': MolScriptBuilder.core.rel.eq([
  100. MolScriptBuilder.struct.atomProperty.macromolecular.label_comp_id(),
  101. 'ALA'
  102. ])
  103. });
  104. const newTree = b.toRoot()
  105. .apply(StateTransforms.Data.Download, { url })
  106. .apply(StateTransforms.Data.ParseCif)
  107. .apply(StateTransforms.Model.ParseTrajectoryFromMmCif, {}, { ref: 'trajectory' })
  108. .apply(StateTransforms.Model.CreateModelFromTrajectory, { modelIndex: 0 }, { ref: 'model' })
  109. .apply(StateTransforms.Model.CreateStructureFromModel, { }, { ref: 'structure' })
  110. .apply(StateTransforms.Model.CreateStructureAssembly)
  111. .apply(StateTransforms.Model.CreateStructureSelection, { query, label: 'ALA residues' })
  112. .apply(StateTransforms.Visuals.CreateStructureRepresentation)
  113. .getTree();
  114. this.runTask(this.state.data.update(newTree));
  115. }
  116. private initEvents() {
  117. merge(this.events.state.data.object.created, this.events.state.behavior.object.created).subscribe(o => {
  118. if (!PSO.isBehavior(o.obj)) return;
  119. console.log('registering behavior', o.obj.label);
  120. o.obj.data.register();
  121. });
  122. merge(this.events.state.data.object.removed, this.events.state.behavior.object.removed).subscribe(o => {
  123. if (!PSO.isBehavior(o.obj)) return;
  124. o.obj.data.unregister();
  125. });
  126. merge(this.events.state.data.object.replaced, this.events.state.behavior.object.replaced).subscribe(o => {
  127. if (o.oldObj && PSO.isBehavior(o.oldObj)) o.oldObj.data.unregister();
  128. if (o.newObj && PSO.isBehavior(o.newObj)) o.newObj.data.register();
  129. });
  130. }
  131. _test_centerView() {
  132. const sel = this.state.data.select(q => q.root.subtree().ofType(SO.Molecule.Structure.type));
  133. if (!sel.length) return;
  134. const center = (sel[0].obj! as SO.Molecule.Structure).data.boundary.sphere.center;
  135. this.canvas3d.camera.setState({ target: center });
  136. this.canvas3d.requestDraw(true);
  137. }
  138. async _test_nextModel() {
  139. const traj = this.state.data.select('trajectory')[0].obj as SO.Molecule.Trajectory;
  140. //const modelIndex = (this.state.data.select('model')[0].transform.params as CreateModelFromTrajectory.Params).modelIndex;
  141. const newTree = this.state.data.build().to('model').update(
  142. StateTransforms.Model.CreateModelFromTrajectory,
  143. old => ({ modelIndex: (old.modelIndex + 1) % traj.data.length }))
  144. .getTree();
  145. // const newTree = StateTree.updateParams(this.state.data.tree, 'model', { modelIndex: (modelIndex + 1) % traj.data.length });
  146. await this.runTask(this.state.data.update(newTree));
  147. // this.viewer.requestDraw(true);
  148. }
  149. _test_playModels() {
  150. const update = async () => {
  151. await this._test_nextModel();
  152. setTimeout(update, 1000 / 15);
  153. }
  154. update();
  155. }
  156. constructor() {
  157. this.initEvents();
  158. this._test_initBehaviours();
  159. }
  160. // logger = ;
  161. // settings = ;
  162. }