units-representation.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. /**
  2. * Copyright (c) 2018-2021 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. * @author David Sehnal <david.sehnal@gmail.com>
  6. */
  7. import { ParamDefinition as PD } from '../../mol-util/param-definition';
  8. import { StructureRepresentation, StructureRepresentationStateBuilder, StructureRepresentationState } from './representation';
  9. import { Visual } from '../visual';
  10. import { Representation, RepresentationContext, RepresentationParamsGetter } from '../representation';
  11. import { Structure, Unit, StructureElement, Bond } from '../../mol-model/structure';
  12. import { Subject } from 'rxjs';
  13. import { getNextMaterialId, GraphicsRenderObject } from '../../mol-gl/render-object';
  14. import { Theme } from '../../mol-theme/theme';
  15. import { Task } from '../../mol-task';
  16. import { PickingId } from '../../mol-geo/geometry/picking';
  17. import { Loci, EmptyLoci, isEmptyLoci, isEveryLoci, isDataLoci, EveryLoci } from '../../mol-model/loci';
  18. import { MarkerAction, MarkerActions, applyMarkerAction } from '../../mol-util/marker-action';
  19. import { Overpaint } from '../../mol-theme/overpaint';
  20. import { Transparency } from '../../mol-theme/transparency';
  21. import { Mat4, EPSILON } from '../../mol-math/linear-algebra';
  22. import { Interval } from '../../mol-data/int';
  23. import { StructureParams } from './params';
  24. import { Clipping } from '../../mol-theme/clipping';
  25. import { WebGLContext } from '../../mol-gl/webgl/context';
  26. import { StructureGroup } from './visual/util/common';
  27. import { Substance } from '../../mol-theme/substance';
  28. export interface UnitsVisual<P extends StructureParams> extends Visual<StructureGroup, P> { }
  29. export function UnitsRepresentation<P extends StructureParams>(label: string, ctx: RepresentationContext, getParams: RepresentationParamsGetter<Structure, P>, visualCtor: (materialId: number, structure: Structure, props: PD.Values<P>, webgl?: WebGLContext) => UnitsVisual<P>): StructureRepresentation<P> {
  30. let version = 0;
  31. const { webgl } = ctx;
  32. const updated = new Subject<number>();
  33. const materialId = getNextMaterialId();
  34. const renderObjects: GraphicsRenderObject[] = [];
  35. const geometryState = new Representation.GeometryState();
  36. const _state = StructureRepresentationStateBuilder.create();
  37. let visuals = new Map<number, { group: Unit.SymmetryGroup, visual: UnitsVisual<P> }>();
  38. let _structure: Structure;
  39. let _groups: ReadonlyArray<Unit.SymmetryGroup>;
  40. let _params: P;
  41. let _props: PD.Values<P>;
  42. let _theme = Theme.createEmpty();
  43. function createOrUpdate(props: Partial<PD.Values<P>> = {}, structure?: Structure) {
  44. if (structure && structure !== _structure) {
  45. _params = getParams(ctx, structure);
  46. if (!_props) _props = PD.getDefaultValues(_params);
  47. }
  48. _props = Object.assign({}, _props, props);
  49. return Task.create('Creating or updating UnitsRepresentation', async runtime => {
  50. if (!_structure && !structure) {
  51. throw new Error('missing structure');
  52. } else if (structure && !_structure) {
  53. // console.log(label, 'initial structure');
  54. // First call with a structure, create visuals for each group.
  55. _groups = structure.unitSymmetryGroups;
  56. for (let i = 0; i < _groups.length; i++) {
  57. const group = _groups[i];
  58. const visual = visualCtor(materialId, structure, _props, webgl);
  59. const promise = visual.createOrUpdate({ webgl, runtime }, _theme, _props, { group, structure });
  60. if (promise) await promise;
  61. setVisualState(visual, group, _state); // current state for new visual
  62. visuals.set(group.hashCode, { visual, group });
  63. if (runtime.shouldUpdate) await runtime.update({ message: 'Creating or updating UnitsVisual', current: i, max: _groups.length });
  64. }
  65. } else if (structure && (!Structure.areUnitIdsAndIndicesEqual(structure, _structure) || structure.child !== _structure.child)) {
  66. // console.log(label, 'structures not equivalent');
  67. // Tries to re-use existing visuals for the groups of the new structure.
  68. // Creates additional visuals if needed, destroys left-over visuals.
  69. _groups = structure.unitSymmetryGroups;
  70. // const newGroups: Unit.SymmetryGroup[] = []
  71. const oldVisuals = visuals;
  72. visuals = new Map();
  73. for (let i = 0; i < _groups.length; i++) {
  74. const group = _groups[i];
  75. const visualGroup = oldVisuals.get(group.hashCode);
  76. if (visualGroup) {
  77. // console.log(label, 'found visualGroup to reuse');
  78. // console.log('old', visualGroup.group)
  79. // console.log('new', group)
  80. let { visual } = visualGroup;
  81. if (visual.mustRecreate?.({ group, structure }, _props, webgl)) {
  82. visual.destroy();
  83. visual = visualCtor(materialId, structure, _props, webgl);
  84. const promise = visual.createOrUpdate({ webgl, runtime }, _theme, _props, { group, structure });
  85. if (promise) await promise;
  86. setVisualState(visual, group, _state); // current state for new visual
  87. } else {
  88. const promise = visual.createOrUpdate({ webgl, runtime }, _theme, _props, { group, structure });
  89. if (promise) await promise;
  90. }
  91. visuals.set(group.hashCode, { visual, group });
  92. oldVisuals.delete(group.hashCode);
  93. // Remove highlight
  94. // TODO: remove selection too??
  95. if (visual.renderObject) {
  96. const arr = visual.renderObject.values.tMarker.ref.value.array;
  97. applyMarkerAction(arr, Interval.ofBounds(0, arr.length), MarkerAction.RemoveHighlight);
  98. }
  99. } else {
  100. // console.log(label, 'did not find visualGroup to reuse, creating new');
  101. // newGroups.push(group)
  102. const visual = visualCtor(materialId, structure, _props, webgl);
  103. const promise = visual.createOrUpdate({ webgl, runtime }, _theme, _props, { group, structure });
  104. if (promise) await promise;
  105. setVisualState(visual, group, _state); // current state for new visual
  106. visuals.set(group.hashCode, { visual, group });
  107. }
  108. if (runtime.shouldUpdate) await runtime.update({ message: 'Creating or updating UnitsVisual', current: i, max: _groups.length });
  109. }
  110. oldVisuals.forEach(({ visual }) => {
  111. // console.log(label, 'removed unused visual');
  112. visual.destroy();
  113. });
  114. } else if (structure && structure !== _structure && Structure.areUnitIdsAndIndicesEqual(structure, _structure)) {
  115. // console.log(label, 'structures equivalent but not identical');
  116. // Expects that for structures with the same hashCode,
  117. // the unitSymmetryGroups are the same as well.
  118. // Re-uses existing visuals for the groups of the new structure.
  119. _groups = structure.unitSymmetryGroups;
  120. // console.log('new', structure.unitSymmetryGroups)
  121. // console.log('old', _structure.unitSymmetryGroups)
  122. for (let i = 0; i < _groups.length; i++) {
  123. const group = _groups[i];
  124. const visualGroup = visuals.get(group.hashCode);
  125. if (visualGroup) {
  126. let { visual } = visualGroup;
  127. if (visual.mustRecreate?.({ group, structure }, _props, ctx.webgl)) {
  128. visual.destroy();
  129. visual = visualCtor(materialId, structure, _props, ctx.webgl);
  130. visualGroup.visual = visual;
  131. const promise = visual.createOrUpdate({ webgl, runtime }, _theme, _props, { group, structure });
  132. if (promise) await promise;
  133. setVisualState(visual, group, _state); // current state for new visual
  134. } else {
  135. const promise = visual.createOrUpdate({ webgl, runtime }, _theme, _props, { group, structure });
  136. if (promise) await promise;
  137. }
  138. visualGroup.group = group;
  139. } else {
  140. throw new Error(`expected to find visual for hashCode ${group.hashCode}`);
  141. }
  142. if (runtime.shouldUpdate) await runtime.update({ message: 'Creating or updating UnitsVisual', current: i, max: _groups.length });
  143. }
  144. } else {
  145. // console.log(label, 'no new structure');
  146. // No new structure given, just update all visuals with new props.
  147. const visualsList: { group: Unit.SymmetryGroup, visual: UnitsVisual<P> }[] = []; // TODO avoid allocation
  148. visuals.forEach(vg => visualsList.push(vg));
  149. for (let i = 0, il = visualsList.length; i < il; ++i) {
  150. let { visual, group } = visualsList[i];
  151. if (visual.mustRecreate?.({ group, structure: _structure }, _props, ctx.webgl)) {
  152. visual.destroy();
  153. visual = visualCtor(materialId, _structure, _props, webgl);
  154. visualsList[i].visual = visual;
  155. const promise = visual.createOrUpdate({ webgl, runtime }, _theme, _props, { group, structure: _structure });
  156. if (promise) await promise;
  157. setVisualState(visual, group, _state); // current state for new visual
  158. } else {
  159. const promise = visual.createOrUpdate({ webgl, runtime }, _theme, _props);
  160. if (promise) await promise;
  161. }
  162. if (runtime.shouldUpdate) await runtime.update({ message: 'Creating or updating UnitsVisual', current: i, max: il });
  163. }
  164. }
  165. // update list of renderObjects
  166. renderObjects.length = 0;
  167. visuals.forEach(({ visual }) => {
  168. if (visual.renderObject) {
  169. renderObjects.push(visual.renderObject);
  170. geometryState.add(visual.renderObject.id, visual.geometryVersion);
  171. }
  172. });
  173. geometryState.snapshot();
  174. // set new structure
  175. if (structure) _structure = structure;
  176. // increment version
  177. updated.next(version++);
  178. });
  179. }
  180. function getLoci(pickingId?: PickingId) {
  181. if (pickingId === undefined) return Structure.Loci(_structure.target);
  182. let loci: Loci = EmptyLoci;
  183. visuals.forEach(({ visual }) => {
  184. const _loci = visual.getLoci(pickingId);
  185. if (!isEmptyLoci(_loci)) loci = _loci;
  186. });
  187. return loci;
  188. }
  189. function mark(loci: Loci, action: MarkerAction) {
  190. if (!_structure) return false;
  191. if (!MarkerActions.is(_state.markerActions, action)) return false;
  192. if (Structure.isLoci(loci) || StructureElement.Loci.is(loci) || Bond.isLoci(loci)) {
  193. if (!Structure.areRootsEquivalent(loci.structure, _structure)) return false;
  194. // Remap `loci` from equivalent structure to the current `_structure`
  195. loci = Loci.remap(loci, _structure);
  196. if (Structure.isLoci(loci) || (StructureElement.Loci.is(loci) && StructureElement.Loci.isWholeStructure(loci))) {
  197. // Change to `EveryLoci` to allow for downstream optimizations
  198. loci = EveryLoci;
  199. }
  200. } else if (!isEveryLoci(loci) && !isDataLoci(loci)) {
  201. return false;
  202. }
  203. if (Loci.isEmpty(loci)) return false;
  204. let changed = false;
  205. visuals.forEach(({ visual }) => {
  206. changed = visual.mark(loci, action) || changed;
  207. });
  208. return changed;
  209. }
  210. function setVisualState(visual: UnitsVisual<P>, group: Unit.SymmetryGroup, state: Partial<StructureRepresentationState>) {
  211. const { visible, alphaFactor, pickable, overpaint, transparency, substance, clipping, transform, unitTransforms } = state;
  212. if (visible !== undefined) visual.setVisibility(visible);
  213. if (alphaFactor !== undefined) visual.setAlphaFactor(alphaFactor);
  214. if (pickable !== undefined) visual.setPickable(pickable);
  215. if (overpaint !== undefined) visual.setOverpaint(overpaint, webgl);
  216. if (transparency !== undefined) visual.setTransparency(transparency, webgl);
  217. if (substance !== undefined) visual.setSubstance(substance, webgl);
  218. if (clipping !== undefined) visual.setClipping(clipping);
  219. if (transform !== undefined) visual.setTransform(transform);
  220. if (unitTransforms !== undefined) {
  221. if (unitTransforms) {
  222. // console.log(group.hashCode, unitTransforms.getSymmetryGroupTransforms(group))
  223. visual.setTransform(undefined, unitTransforms.getSymmetryGroupTransforms(group));
  224. } else {
  225. visual.setTransform(undefined, null);
  226. }
  227. }
  228. }
  229. function setState(state: Partial<StructureRepresentationState>) {
  230. const { visible, alphaFactor, pickable, overpaint, transparency, substance, clipping, transform, unitTransforms, syncManually, markerActions } = state;
  231. const newState: Partial<StructureRepresentationState> = {};
  232. if (visible !== _state.visible) newState.visible = visible;
  233. if (alphaFactor !== _state.alphaFactor) newState.alphaFactor = alphaFactor;
  234. if (pickable !== _state.pickable) newState.pickable = pickable;
  235. if (overpaint !== undefined && _structure) {
  236. newState.overpaint = Overpaint.remap(overpaint, _structure);
  237. }
  238. if (transparency !== undefined && _structure) {
  239. newState.transparency = Transparency.remap(transparency, _structure);
  240. }
  241. if (substance !== undefined && _structure) {
  242. newState.substance = Substance.remap(substance, _structure);
  243. }
  244. if (clipping !== undefined && _structure) {
  245. newState.clipping = Clipping.remap(clipping, _structure);
  246. }
  247. if (transform !== undefined && !Mat4.areEqual(transform, _state.transform, EPSILON)) {
  248. newState.transform = transform;
  249. }
  250. if (unitTransforms !== _state.unitTransforms || unitTransforms?.version !== state.unitTransformsVersion) {
  251. newState.unitTransforms = unitTransforms;
  252. _state.unitTransformsVersion = unitTransforms ? unitTransforms?.version : -1;
  253. }
  254. if (syncManually !== _state.syncManually) newState.syncManually = syncManually;
  255. if (markerActions !== _state.markerActions) newState.markerActions = markerActions;
  256. visuals.forEach(({ visual, group }) => setVisualState(visual, group, newState));
  257. StructureRepresentationStateBuilder.update(_state, newState);
  258. }
  259. function setTheme(theme: Theme) {
  260. _theme = theme;
  261. }
  262. function destroy() {
  263. visuals.forEach(({ visual }) => visual.destroy());
  264. visuals.clear();
  265. }
  266. return {
  267. label,
  268. get groupCount() {
  269. let groupCount = 0;
  270. visuals.forEach(({ visual }) => {
  271. if (visual.renderObject) groupCount += visual.groupCount;
  272. });
  273. return groupCount;
  274. },
  275. get geometryVersion() { return geometryState.version; },
  276. get props() { return _props; },
  277. get params() { return _params; },
  278. get state() { return _state; },
  279. get theme() { return _theme; },
  280. renderObjects,
  281. updated,
  282. createOrUpdate,
  283. setState,
  284. setTheme,
  285. getLoci,
  286. mark,
  287. destroy
  288. };
  289. }