representation.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. /**
  2. * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. import { ParamDefinition as PD } from '../mol-util/param-definition';
  7. import { WebGLContext } from '../mol-gl/webgl/context';
  8. import { ColorTheme } from '../mol-theme/color';
  9. import { SizeTheme } from '../mol-theme/size';
  10. import { ThemeRegistryContext, Theme } from '../mol-theme/theme';
  11. import { Subject } from 'rxjs';
  12. import { GraphicsRenderObject } from '../mol-gl/render-object';
  13. import { Task } from '../mol-task';
  14. import { PickingId } from '../mol-geo/geometry/picking';
  15. import { MarkerAction, MarkerActions } from '../mol-util/marker-action';
  16. import { Loci as ModelLoci, EmptyLoci, isEmptyLoci } from '../mol-model/loci';
  17. import { Overpaint } from '../mol-theme/overpaint';
  18. import { Transparency } from '../mol-theme/transparency';
  19. import { Mat4 } from '../mol-math/linear-algebra';
  20. import { getQualityProps } from './util';
  21. import { BaseGeometry } from '../mol-geo/geometry/base';
  22. import { Visual } from './visual';
  23. import { CustomProperty } from '../mol-model-props/common/custom-property';
  24. import { Clipping } from '../mol-theme/clipping';
  25. // export interface RepresentationProps {
  26. // visuals?: string[]
  27. // }
  28. export type RepresentationProps = { [k: string]: any }
  29. export interface RepresentationContext {
  30. readonly webgl?: WebGLContext
  31. readonly colorThemeRegistry: ColorTheme.Registry
  32. readonly sizeThemeRegistry: SizeTheme.Registry
  33. }
  34. export type RepresentationParamsGetter<D, P extends PD.Params> = (ctx: ThemeRegistryContext, data: D) => P
  35. export type RepresentationFactory<D, P extends PD.Params, S extends Representation.State> = (ctx: RepresentationContext, getParams: RepresentationParamsGetter<D, P>) => Representation<D, P, S>
  36. //
  37. export interface RepresentationProvider<D = any, P extends PD.Params = any, S extends Representation.State = any, Id extends string = string> {
  38. readonly name: Id,
  39. readonly label: string
  40. readonly description: string
  41. readonly factory: RepresentationFactory<D, P, S>
  42. readonly getParams: RepresentationParamsGetter<D, P>
  43. readonly defaultValues: PD.Values<P>
  44. readonly defaultColorTheme: { name: string, props?: {} }
  45. readonly defaultSizeTheme: { name: string, props?: {} }
  46. readonly isApplicable: (data: D) => boolean
  47. readonly ensureCustomProperties?: {
  48. attach: (ctx: CustomProperty.Context, data: D) => Promise<void>,
  49. detach: (data: D) => void
  50. }
  51. }
  52. export namespace RepresentationProvider {
  53. export type ParamValues<R extends RepresentationProvider<any, any, any>> = R extends RepresentationProvider<any, infer P, any> ? PD.Values<P> : never;
  54. export function getDetaultParams<R extends RepresentationProvider<D, any, any>, D>(r: R, ctx: ThemeRegistryContext, data: D) {
  55. return PD.getDefaultValues(r.getParams(ctx, data));
  56. }
  57. }
  58. export type AnyRepresentationProvider = RepresentationProvider<any, {}, Representation.State>
  59. export const EmptyRepresentationProvider = {
  60. label: '',
  61. description: '',
  62. factory: () => Representation.Empty,
  63. getParams: () => ({}),
  64. defaultValues: {}
  65. };
  66. function getTypes(list: { name: string, provider: RepresentationProvider<any, any, any> }[]) {
  67. return list.map(e => [e.name, e.provider.label] as [string, string]);
  68. }
  69. export class RepresentationRegistry<D, S extends Representation.State> {
  70. private _list: { name: string, provider: RepresentationProvider<D, any, any> }[] = []
  71. private _map = new Map<string, RepresentationProvider<D, any, any>>()
  72. private _name = new Map<RepresentationProvider<D, any, any>, string>()
  73. get default() { return this._list[0]; }
  74. get types(): [string, string][] { return getTypes(this._list); }
  75. constructor() {};
  76. add<P extends PD.Params>(provider: RepresentationProvider<D, P, S>) {
  77. if (this._map.has(provider.name)) {
  78. throw new Error(`${provider.name} already registered.`);
  79. }
  80. this._list.push({ name: provider.name, provider });
  81. this._map.set(provider.name, provider);
  82. this._name.set(provider, provider.name);
  83. }
  84. getName(provider: RepresentationProvider<D, any, any>): string {
  85. if (!this._name.has(provider)) throw new Error(`'${provider.label}' is not a registered represenatation provider.`);
  86. return this._name.get(provider)!;
  87. }
  88. remove(provider: RepresentationProvider<D, any, any>) {
  89. const name = provider.name;
  90. this._list.splice(this._list.findIndex(e => e.name === name), 1);
  91. const p = this._map.get(name);
  92. if (p) {
  93. this._map.delete(name);
  94. this._name.delete(p);
  95. }
  96. }
  97. get<P extends PD.Params>(name: string): RepresentationProvider<D, P, S> {
  98. return this._map.get(name) || EmptyRepresentationProvider as unknown as RepresentationProvider<D, P, S>;
  99. }
  100. get list() {
  101. return this._list;
  102. }
  103. getApplicableList(data: D) {
  104. return this._list.filter(e => e.provider.isApplicable(data));
  105. }
  106. getApplicableTypes(data: D) {
  107. return getTypes(this.getApplicableList(data));
  108. }
  109. }
  110. //
  111. export { Representation };
  112. interface Representation<D, P extends PD.Params = {}, S extends Representation.State = Representation.State> {
  113. readonly label: string
  114. readonly updated: Subject<number>
  115. /** Number of addressable groups in all visuals of the representation */
  116. readonly groupCount: number
  117. readonly renderObjects: ReadonlyArray<GraphicsRenderObject>
  118. readonly props: Readonly<PD.Values<P>>
  119. readonly params: Readonly<P>
  120. readonly state: Readonly<S>
  121. readonly theme: Readonly<Theme>
  122. createOrUpdate: (props?: Partial<PD.Values<P>>, data?: D) => Task<void>
  123. setState: (state: Partial<S>) => void
  124. setTheme: (theme: Theme) => void
  125. /** If no pickingId is given, returns a Loci for the whole representation */
  126. getLoci: (pickingId?: PickingId) => ModelLoci
  127. mark: (loci: ModelLoci, action: MarkerAction) => boolean
  128. destroy: () => void
  129. }
  130. namespace Representation {
  131. export interface Loci<T extends ModelLoci = ModelLoci> { loci: T, repr?: Representation.Any }
  132. export namespace Loci {
  133. export function areEqual(a: Loci, b: Loci) {
  134. return a.repr === b.repr && ModelLoci.areEqual(a.loci, b.loci);
  135. }
  136. export function isEmpty(a: Loci) {
  137. return ModelLoci.isEmpty(a.loci);
  138. }
  139. export const Empty: Loci = { loci: EmptyLoci };
  140. }
  141. export interface State {
  142. /** Controls if the representation's renderobjects are rendered or not */
  143. visible: boolean
  144. /** A factor applied to alpha value of the representation's renderobjects */
  145. alphaFactor: number
  146. /** Controls if the representation's renderobjects are pickable or not */
  147. pickable: boolean
  148. /** Controls if the representation's renderobjects is rendered in color pass (i.e., not pick and depth) or not */
  149. colorOnly: boolean
  150. /** Overpaint applied to the representation's renderobjects */
  151. overpaint: Overpaint
  152. /** Per group transparency applied to the representation's renderobjects */
  153. transparency: Transparency
  154. /** Bit mask of per group clipping applied to the representation's renderobjects */
  155. clipping: Clipping
  156. /** Controls if the representation's renderobjects are synced automatically with GPU or not */
  157. syncManually: boolean
  158. /** A transformation applied to the representation's renderobjects */
  159. transform: Mat4
  160. /** Bit mask of allowed marker actions */
  161. markerActions: MarkerActions
  162. }
  163. export function createState(): State {
  164. return { visible: true, alphaFactor: 1, pickable: true, colorOnly: false, syncManually: false, transform: Mat4.identity(), overpaint: Overpaint.Empty, transparency: Transparency.Empty, clipping: Clipping.Empty, markerActions: MarkerActions.All };
  165. }
  166. export function updateState(state: State, update: Partial<State>) {
  167. if (update.visible !== undefined) state.visible = update.visible;
  168. if (update.alphaFactor !== undefined) state.alphaFactor = update.alphaFactor;
  169. if (update.pickable !== undefined) state.pickable = update.pickable;
  170. if (update.colorOnly !== undefined) state.colorOnly = update.colorOnly;
  171. if (update.overpaint !== undefined) state.overpaint = update.overpaint;
  172. if (update.transparency !== undefined) state.transparency = update.transparency;
  173. if (update.clipping !== undefined) state.clipping = update.clipping;
  174. if (update.syncManually !== undefined) state.syncManually = update.syncManually;
  175. if (update.transform !== undefined) Mat4.copy(state.transform, update.transform);
  176. if (update.markerActions !== undefined) state.markerActions = update.markerActions;
  177. }
  178. export interface StateBuilder<S extends State> {
  179. create(): S
  180. update(state: S, update: Partial<S>): void
  181. }
  182. export const StateBuilder: StateBuilder<State> = { create: createState, update: updateState };
  183. export type Any = Representation<any, any, any>
  184. export const Empty: Any = {
  185. label: '', groupCount: 0, renderObjects: [], props: {}, params: {}, updated: new Subject(), state: createState(), theme: Theme.createEmpty(),
  186. createOrUpdate: () => Task.constant('', undefined),
  187. setState: () => {},
  188. setTheme: () => {},
  189. getLoci: () => EmptyLoci,
  190. mark: () => false,
  191. destroy: () => {}
  192. };
  193. export type Def<D, P extends PD.Params = {}, S extends State = State> = { [k: string]: RepresentationFactory<D, P, S> }
  194. export function createMulti<D, P extends PD.Params = {}, S extends State = State>(label: string, ctx: RepresentationContext, getParams: RepresentationParamsGetter<D, P>, stateBuilder: StateBuilder<S>, reprDefs: Def<D, P>): Representation<D, P, S> {
  195. let version = 0;
  196. const updated = new Subject<number>();
  197. const currentState = stateBuilder.create();
  198. let currentTheme = Theme.createEmpty();
  199. let currentParams: P;
  200. let currentProps: PD.Values<P>;
  201. let currentData: D;
  202. const reprMap: { [k: number]: string } = {};
  203. const reprList: Representation<D, P>[] = Object.keys(reprDefs).map((name, i) => {
  204. reprMap[i] = name;
  205. const repr = reprDefs[name](ctx, getParams);
  206. repr.setState(currentState);
  207. return repr;
  208. });
  209. return {
  210. label,
  211. updated,
  212. get groupCount() {
  213. let groupCount = 0;
  214. if (currentProps) {
  215. const { visuals } = currentProps;
  216. for (let i = 0, il = reprList.length; i < il; ++i) {
  217. if (!visuals || visuals.includes(reprMap[i])) {
  218. groupCount += reprList[i].groupCount;
  219. }
  220. }
  221. }
  222. return groupCount;
  223. },
  224. get renderObjects() {
  225. const renderObjects: GraphicsRenderObject[] = [];
  226. if (currentProps) {
  227. const { visuals } = currentProps;
  228. for (let i = 0, il = reprList.length; i < il; ++i) {
  229. if (!visuals || visuals.includes(reprMap[i])) {
  230. renderObjects.push(...reprList[i].renderObjects);
  231. }
  232. }
  233. }
  234. return renderObjects;
  235. },
  236. get props() { return currentProps; },
  237. get params() { return currentParams; },
  238. createOrUpdate: (props: Partial<P> = {}, data?: D) => {
  239. if (data && data !== currentData) {
  240. currentParams = getParams(ctx, data);
  241. currentData = data;
  242. if (!currentProps) currentProps = PD.getDefaultValues(currentParams) as P;
  243. }
  244. const qualityProps = getQualityProps(Object.assign({}, currentProps, props), currentData);
  245. Object.assign(currentProps, props, qualityProps);
  246. const { visuals } = currentProps;
  247. return Task.create(`Creating or updating '${label}' representation`, async runtime => {
  248. for (let i = 0, il = reprList.length; i < il; ++i) {
  249. if (!visuals || visuals.includes(reprMap[i])) {
  250. await reprList[i].createOrUpdate(currentProps, currentData).runInContext(runtime);
  251. }
  252. }
  253. updated.next(version++);
  254. });
  255. },
  256. get state() { return currentState; },
  257. get theme() { return currentTheme; },
  258. getLoci: (pickingId?: PickingId) => {
  259. const { visuals } = currentProps;
  260. for (let i = 0, il = reprList.length; i < il; ++i) {
  261. if (!visuals || visuals.includes(reprMap[i])) {
  262. const loci = reprList[i].getLoci(pickingId);
  263. if (!isEmptyLoci(loci)) return loci;
  264. }
  265. }
  266. return EmptyLoci;
  267. },
  268. mark: (loci: ModelLoci, action: MarkerAction) => {
  269. let marked = false;
  270. for (let i = 0, il = reprList.length; i < il; ++i) {
  271. marked = reprList[i].mark(loci, action) || marked;
  272. }
  273. return marked;
  274. },
  275. setState: (state: Partial<S>) => {
  276. stateBuilder.update(currentState, state);
  277. for (let i = 0, il = reprList.length; i < il; ++i) {
  278. reprList[i].setState(currentState);
  279. }
  280. },
  281. setTheme: (theme: Theme) => {
  282. for (let i = 0, il = reprList.length; i < il; ++i) {
  283. reprList[i].setTheme(theme);
  284. }
  285. },
  286. destroy() {
  287. for (let i = 0, il = reprList.length; i < il; ++i) {
  288. reprList[i].destroy();
  289. }
  290. }
  291. };
  292. }
  293. export function fromRenderObject(label: string, renderObject: GraphicsRenderObject): Representation<GraphicsRenderObject, BaseGeometry.Params> {
  294. let version = 0;
  295. const updated = new Subject<number>();
  296. const currentState = Representation.createState();
  297. const currentTheme = Theme.createEmpty();
  298. const currentParams = PD.clone(BaseGeometry.Params);
  299. const currentProps = PD.getDefaultValues(BaseGeometry.Params);
  300. return {
  301. label,
  302. updated,
  303. get groupCount() { return renderObject.values.uGroupCount.ref.value; },
  304. get renderObjects() { return [renderObject]; },
  305. get props() { return currentProps; },
  306. get params() { return currentParams; },
  307. createOrUpdate: (props: Partial<PD.Values<BaseGeometry.Params>> = {}) => {
  308. const qualityProps = getQualityProps(Object.assign({}, currentProps, props));
  309. Object.assign(currentProps, props, qualityProps);
  310. return Task.create(`Updating '${label}' representation`, async runtime => {
  311. // TODO
  312. updated.next(version++);
  313. });
  314. },
  315. get state() { return currentState; },
  316. get theme() { return currentTheme; },
  317. getLoci: () => {
  318. // TODO
  319. return EmptyLoci;
  320. },
  321. mark: (loci: ModelLoci, action: MarkerAction) => {
  322. // TODO
  323. return false;
  324. },
  325. setState: (state: Partial<State>) => {
  326. if (state.visible !== undefined) Visual.setVisibility(renderObject, state.visible);
  327. if (state.alphaFactor !== undefined) Visual.setAlphaFactor(renderObject, state.alphaFactor);
  328. if (state.pickable !== undefined) Visual.setPickable(renderObject, state.pickable);
  329. if (state.colorOnly !== undefined) Visual.setColorOnly(renderObject, state.colorOnly);
  330. if (state.overpaint !== undefined) {
  331. // TODO
  332. }
  333. if (state.transparency !== undefined) {
  334. // TODO
  335. }
  336. if (state.transform !== undefined) Visual.setTransform(renderObject, state.transform);
  337. Representation.updateState(currentState, state);
  338. },
  339. setTheme: () => { },
  340. destroy() { }
  341. };
  342. }
  343. }