bond-intra-unit-cylinder.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. /**
  2. * Copyright (c) 2018-2022 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 { VisualContext } from '../../visual';
  9. import { Unit, Structure, StructureElement, Bond } from '../../../mol-model/structure';
  10. import { Theme } from '../../../mol-theme/theme';
  11. import { Mesh } from '../../../mol-geo/geometry/mesh/mesh';
  12. import { Vec3 } from '../../../mol-math/linear-algebra';
  13. import { arrayEqual } from '../../../mol-util';
  14. import { createLinkCylinderImpostors, createLinkCylinderMesh, LinkBuilderProps, LinkStyle } from './util/link';
  15. import { UnitsMeshParams, UnitsVisual, UnitsMeshVisual, UnitsCylindersParams, UnitsCylindersVisual } from '../units-visual';
  16. import { VisualUpdateState } from '../../util';
  17. import { BondType } from '../../../mol-model/structure/model/types';
  18. import { BondCylinderParams, BondIterator, eachIntraBond, getIntraBondLoci, ignoreBondType, makeIntraBondIgnoreTest } from './util/bond';
  19. import { Sphere3D } from '../../../mol-math/geometry';
  20. import { IntAdjacencyGraph } from '../../../mol-math/graph';
  21. import { WebGLContext } from '../../../mol-gl/webgl/context';
  22. import { Cylinders } from '../../../mol-geo/geometry/cylinders/cylinders';
  23. import { SortedArray } from '../../../mol-data/int';
  24. import { arrayIntersectionSize } from '../../../mol-util/array';
  25. import { StructureGroup } from './util/common';
  26. // avoiding namespace lookup improved performance in Chrome (Aug 2020)
  27. const isBondType = BondType.is;
  28. function getIntraUnitBondCylinderBuilderProps(unit: Unit.Atomic, structure: Structure, theme: Theme, props: PD.Values<IntraUnitBondCylinderParams>): LinkBuilderProps {
  29. const elements = unit.elements;
  30. const bonds = unit.bonds;
  31. const { edgeCount, a, b, edgeProps, offset } = bonds;
  32. const { order: _order, flags: _flags } = edgeProps;
  33. const { sizeFactor, sizeAspectRatio, adjustCylinderLength, aromaticBonds, includeTypes, excludeTypes, multipleBonds } = props;
  34. const mbOff = multipleBonds === 'off';
  35. const mbSymmetric = multipleBonds === 'symmetric';
  36. const include = BondType.fromNames(includeTypes);
  37. const exclude = BondType.fromNames(excludeTypes);
  38. const ignoreComputedAromatic = ignoreBondType(include, exclude, BondType.Flag.Computed);
  39. const vRef = Vec3(), delta = Vec3();
  40. const pos = unit.conformation.invariantPosition;
  41. let stub: undefined | ((edgeIndex: number) => boolean);
  42. const locE = StructureElement.Location.create(structure, unit);
  43. const locB = Bond.Location(structure, unit, undefined, structure, unit, undefined);
  44. const { child } = structure;
  45. if (props.includeParent && child) {
  46. const childUnit = child.unitMap.get(unit.id);
  47. if (!childUnit) throw new Error('expected childUnit to exist');
  48. stub = (edgeIndex: number) => {
  49. const eA = elements[a[edgeIndex]];
  50. const eB = elements[b[edgeIndex]];
  51. return SortedArray.has(childUnit.elements, eA) && !SortedArray.has(childUnit.elements, eB);
  52. };
  53. }
  54. const radius = (edgeIndex: number) => {
  55. locB.aIndex = a[edgeIndex];
  56. locB.bIndex = b[edgeIndex];
  57. return theme.size.size(locB) * sizeFactor;
  58. };
  59. const radiusA = (edgeIndex: number) => {
  60. locE.element = elements[a[edgeIndex]];
  61. return theme.size.size(locE) * sizeFactor;
  62. };
  63. const radiusB = (edgeIndex: number) => {
  64. locE.element = elements[b[edgeIndex]];
  65. return theme.size.size(locE) * sizeFactor;
  66. };
  67. const { elementRingIndices, elementAromaticRingIndices } = unit.rings;
  68. const deloTriplets = aromaticBonds ? unit.resonance.delocalizedTriplets : undefined;
  69. return {
  70. linkCount: edgeCount * 2,
  71. referencePosition: (edgeIndex: number) => {
  72. let aI = a[edgeIndex], bI = b[edgeIndex];
  73. const rI = deloTriplets?.getThirdElement(aI, bI);
  74. if (rI !== undefined) return pos(elements[rI], vRef);
  75. if (aI > bI) [aI, bI] = [bI, aI];
  76. if (offset[aI + 1] - offset[aI] === 1) [aI, bI] = [bI, aI];
  77. const aR = elementAromaticRingIndices.get(aI) || elementRingIndices.get(aI);
  78. let maxSize = 0;
  79. for (let i = offset[aI], il = offset[aI + 1]; i < il; ++i) {
  80. const _bI = b[i];
  81. if (_bI !== bI && _bI !== aI) {
  82. if (aR) {
  83. const _bR = elementAromaticRingIndices.get(_bI) || elementRingIndices.get(_bI);
  84. if (!_bR) continue;
  85. const size = arrayIntersectionSize(aR, _bR);
  86. if (size > maxSize) {
  87. maxSize = size;
  88. pos(elements[_bI], vRef);
  89. }
  90. } else {
  91. return pos(elements[_bI], vRef);
  92. }
  93. }
  94. }
  95. return maxSize > 0 ? vRef : null;
  96. },
  97. position: (posA: Vec3, posB: Vec3, edgeIndex: number) => {
  98. pos(elements[a[edgeIndex]], posA);
  99. pos(elements[b[edgeIndex]], posB);
  100. if (adjustCylinderLength) {
  101. const rA = radiusA(edgeIndex), rB = radiusB(edgeIndex);
  102. const r = Math.min(rA, rB) * sizeAspectRatio;
  103. const oA = Math.sqrt(Math.max(0, rA * rA - r * r)) - 0.05;
  104. const oB = Math.sqrt(Math.max(0, rB * rB - r * r)) - 0.05;
  105. if (oA <= 0.01 && oB <= 0.01) return;
  106. Vec3.normalize(delta, Vec3.sub(delta, posB, posA));
  107. Vec3.scaleAndAdd(posA, posA, delta, oA);
  108. Vec3.scaleAndAdd(posB, posB, delta, -oB);
  109. }
  110. },
  111. style: (edgeIndex: number) => {
  112. const o = _order[edgeIndex];
  113. const f = _flags[edgeIndex];
  114. if (isBondType(f, BondType.Flag.MetallicCoordination) || isBondType(f, BondType.Flag.HydrogenBond)) {
  115. // show metallic coordinations and hydrogen bonds with dashed cylinders
  116. return LinkStyle.Dashed;
  117. } else if (o === 3) {
  118. return mbOff ? LinkStyle.Solid :
  119. mbSymmetric ? LinkStyle.Triple :
  120. LinkStyle.OffsetTriple;
  121. } else if (aromaticBonds) {
  122. const aI = a[edgeIndex], bI = b[edgeIndex];
  123. const aR = elementAromaticRingIndices.get(aI);
  124. const bR = elementAromaticRingIndices.get(bI);
  125. const arCount = (aR && bR) ? arrayIntersectionSize(aR, bR) : 0;
  126. if (isBondType(f, BondType.Flag.Aromatic) || (arCount && !ignoreComputedAromatic)) {
  127. if (arCount === 2) {
  128. return LinkStyle.MirroredAromatic;
  129. } else {
  130. return LinkStyle.Aromatic;
  131. }
  132. }
  133. }
  134. return (o !== 2 || mbOff) ? LinkStyle.Solid :
  135. mbSymmetric ? LinkStyle.Double :
  136. LinkStyle.OffsetDouble;
  137. },
  138. radius: (edgeIndex: number) => {
  139. return radius(edgeIndex) * sizeAspectRatio;
  140. },
  141. ignore: makeIntraBondIgnoreTest(structure, unit, props),
  142. stub
  143. };
  144. }
  145. function createIntraUnitBondCylinderImpostors(ctx: VisualContext, unit: Unit, structure: Structure, theme: Theme, props: PD.Values<IntraUnitBondCylinderParams>, cylinders?: Cylinders): Cylinders {
  146. if (!Unit.isAtomic(unit)) return Cylinders.createEmpty(cylinders);
  147. if (!unit.bonds.edgeCount) return Cylinders.createEmpty(cylinders);
  148. const { child } = structure;
  149. const childUnit = child?.unitMap.get(unit.id);
  150. if (child && !childUnit) return Cylinders.createEmpty(cylinders);
  151. const builderProps = getIntraUnitBondCylinderBuilderProps(unit, structure, theme, props);
  152. const { cylinders: c, boundingSphere } = createLinkCylinderImpostors(ctx, builderProps, props, cylinders);
  153. if (boundingSphere) {
  154. c.setBoundingSphere(boundingSphere);
  155. } else if (c.cylinderCount > 0) {
  156. const sphere = Sphere3D.expand(Sphere3D(), (childUnit ?? unit).boundary.sphere, 1 * props.sizeFactor);
  157. c.setBoundingSphere(sphere);
  158. }
  159. return c;
  160. }
  161. function createIntraUnitBondCylinderMesh(ctx: VisualContext, unit: Unit, structure: Structure, theme: Theme, props: PD.Values<IntraUnitBondCylinderParams>, mesh?: Mesh): Mesh {
  162. if (!Unit.isAtomic(unit)) return Mesh.createEmpty(mesh);
  163. if (!unit.bonds.edgeCount) return Mesh.createEmpty(mesh);
  164. const { child } = structure;
  165. const childUnit = child?.unitMap.get(unit.id);
  166. if (child && !childUnit) return Mesh.createEmpty(mesh);
  167. const builderProps = getIntraUnitBondCylinderBuilderProps(unit, structure, theme, props);
  168. const { mesh: m, boundingSphere } = createLinkCylinderMesh(ctx, builderProps, props, mesh);
  169. if (boundingSphere) {
  170. m.setBoundingSphere(boundingSphere);
  171. } else if (m.triangleCount > 0) {
  172. const sphere = Sphere3D.expand(Sphere3D(), (childUnit ?? unit).boundary.sphere, 1 * props.sizeFactor);
  173. m.setBoundingSphere(sphere);
  174. }
  175. return m;
  176. }
  177. export const IntraUnitBondCylinderParams = {
  178. ...UnitsMeshParams,
  179. ...UnitsCylindersParams,
  180. ...BondCylinderParams,
  181. sizeFactor: PD.Numeric(0.3, { min: 0, max: 10, step: 0.01 }),
  182. sizeAspectRatio: PD.Numeric(2 / 3, { min: 0, max: 3, step: 0.01 }),
  183. tryUseImpostor: PD.Boolean(true),
  184. includeParent: PD.Boolean(false),
  185. };
  186. export type IntraUnitBondCylinderParams = typeof IntraUnitBondCylinderParams
  187. export function IntraUnitBondCylinderVisual(materialId: number, structure: Structure, props: PD.Values<IntraUnitBondCylinderParams>, webgl?: WebGLContext) {
  188. return props.tryUseImpostor && webgl && webgl.extensions.fragDepth
  189. ? IntraUnitBondCylinderImpostorVisual(materialId)
  190. : IntraUnitBondCylinderMeshVisual(materialId);
  191. }
  192. export function IntraUnitBondCylinderImpostorVisual(materialId: number): UnitsVisual<IntraUnitBondCylinderParams> {
  193. return UnitsCylindersVisual<IntraUnitBondCylinderParams>({
  194. defaultProps: PD.getDefaultValues(IntraUnitBondCylinderParams),
  195. createGeometry: createIntraUnitBondCylinderImpostors,
  196. createLocationIterator: BondIterator.fromGroup,
  197. getLoci: getIntraBondLoci,
  198. eachLocation: eachIntraBond,
  199. setUpdateState: (state: VisualUpdateState, newProps: PD.Values<IntraUnitBondCylinderParams>, currentProps: PD.Values<IntraUnitBondCylinderParams>, newTheme: Theme, currentTheme: Theme, newStructureGroup: StructureGroup, currentStructureGroup: StructureGroup) => {
  200. state.createGeometry = (
  201. newProps.sizeFactor !== currentProps.sizeFactor ||
  202. newProps.sizeAspectRatio !== currentProps.sizeAspectRatio ||
  203. newProps.linkScale !== currentProps.linkScale ||
  204. newProps.linkSpacing !== currentProps.linkSpacing ||
  205. newProps.ignoreHydrogens !== currentProps.ignoreHydrogens ||
  206. newProps.ignoreHydrogensVariant !== currentProps.ignoreHydrogensVariant ||
  207. newProps.linkCap !== currentProps.linkCap ||
  208. newProps.aromaticScale !== currentProps.aromaticScale ||
  209. newProps.aromaticSpacing !== currentProps.aromaticSpacing ||
  210. newProps.aromaticDashCount !== currentProps.aromaticDashCount ||
  211. newProps.dashCount !== currentProps.dashCount ||
  212. newProps.dashScale !== currentProps.dashScale ||
  213. newProps.dashCap !== currentProps.dashCap ||
  214. newProps.stubCap !== currentProps.stubCap ||
  215. !arrayEqual(newProps.includeTypes, currentProps.includeTypes) ||
  216. !arrayEqual(newProps.excludeTypes, currentProps.excludeTypes) ||
  217. newProps.adjustCylinderLength !== currentProps.adjustCylinderLength ||
  218. newProps.aromaticBonds !== currentProps.aromaticBonds ||
  219. newProps.multipleBonds !== currentProps.multipleBonds
  220. );
  221. const newUnit = newStructureGroup.group.units[0];
  222. const currentUnit = currentStructureGroup.group.units[0];
  223. if (Unit.isAtomic(newUnit) && Unit.isAtomic(currentUnit)) {
  224. if (!IntAdjacencyGraph.areEqual(newUnit.bonds, currentUnit.bonds)) {
  225. state.createGeometry = true;
  226. state.updateTransform = true;
  227. state.updateColor = true;
  228. state.updateSize = true;
  229. }
  230. }
  231. },
  232. mustRecreate: (structureGroup: StructureGroup, props: PD.Values<IntraUnitBondCylinderParams>, webgl?: WebGLContext) => {
  233. return !props.tryUseImpostor || !webgl;
  234. }
  235. }, materialId);
  236. }
  237. export function IntraUnitBondCylinderMeshVisual(materialId: number): UnitsVisual<IntraUnitBondCylinderParams> {
  238. return UnitsMeshVisual<IntraUnitBondCylinderParams>({
  239. defaultProps: PD.getDefaultValues(IntraUnitBondCylinderParams),
  240. createGeometry: createIntraUnitBondCylinderMesh,
  241. createLocationIterator: BondIterator.fromGroup,
  242. getLoci: getIntraBondLoci,
  243. eachLocation: eachIntraBond,
  244. setUpdateState: (state: VisualUpdateState, newProps: PD.Values<IntraUnitBondCylinderParams>, currentProps: PD.Values<IntraUnitBondCylinderParams>, newTheme: Theme, currentTheme: Theme, newStructureGroup: StructureGroup, currentStructureGroup: StructureGroup) => {
  245. state.createGeometry = (
  246. newProps.sizeFactor !== currentProps.sizeFactor ||
  247. newProps.sizeAspectRatio !== currentProps.sizeAspectRatio ||
  248. newProps.radialSegments !== currentProps.radialSegments ||
  249. newProps.linkScale !== currentProps.linkScale ||
  250. newProps.linkSpacing !== currentProps.linkSpacing ||
  251. newProps.ignoreHydrogens !== currentProps.ignoreHydrogens ||
  252. newProps.ignoreHydrogensVariant !== currentProps.ignoreHydrogensVariant ||
  253. newProps.linkCap !== currentProps.linkCap ||
  254. newProps.aromaticScale !== currentProps.aromaticScale ||
  255. newProps.aromaticSpacing !== currentProps.aromaticSpacing ||
  256. newProps.aromaticDashCount !== currentProps.aromaticDashCount ||
  257. newProps.dashCount !== currentProps.dashCount ||
  258. newProps.dashScale !== currentProps.dashScale ||
  259. newProps.dashCap !== currentProps.dashCap ||
  260. newProps.stubCap !== currentProps.stubCap ||
  261. !arrayEqual(newProps.includeTypes, currentProps.includeTypes) ||
  262. !arrayEqual(newProps.excludeTypes, currentProps.excludeTypes) ||
  263. newProps.adjustCylinderLength !== currentProps.adjustCylinderLength ||
  264. newProps.aromaticBonds !== currentProps.aromaticBonds ||
  265. newProps.multipleBonds !== currentProps.multipleBonds
  266. );
  267. const newUnit = newStructureGroup.group.units[0];
  268. const currentUnit = currentStructureGroup.group.units[0];
  269. if (Unit.isAtomic(newUnit) && Unit.isAtomic(currentUnit)) {
  270. if (!IntAdjacencyGraph.areEqual(newUnit.bonds, currentUnit.bonds)) {
  271. state.createGeometry = true;
  272. state.updateTransform = true;
  273. state.updateColor = true;
  274. state.updateSize = true;
  275. }
  276. }
  277. },
  278. mustRecreate: (structureGroup: StructureGroup, props: PD.Values<IntraUnitBondCylinderParams>, webgl?: WebGLContext) => {
  279. return props.tryUseImpostor && !!webgl;
  280. }
  281. }, materialId);
  282. }