canvas3d.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  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 { BehaviorSubject, Subscription } from 'rxjs';
  8. import { now } from '../mol-util/now';
  9. import { Vec3, Vec2 } from '../mol-math/linear-algebra';
  10. import { InputObserver, ModifiersKeys, ButtonsType } from '../mol-util/input/input-observer';
  11. import { Renderer, RendererStats, RendererParams } from '../mol-gl/renderer';
  12. import { GraphicsRenderObject } from '../mol-gl/render-object';
  13. import { TrackballControls, TrackballControlsParams } from './controls/trackball';
  14. import { Viewport } from './camera/util';
  15. import { createContext, WebGLContext, getGLContext } from '../mol-gl/webgl/context';
  16. import { Representation } from '../mol-repr/representation';
  17. import { Scene } from '../mol-gl/scene';
  18. import { PickingId } from '../mol-geo/geometry/picking';
  19. import { MarkerAction } from '../mol-util/marker-action';
  20. import { Loci, EmptyLoci, isEmptyLoci } from '../mol-model/loci';
  21. import { Camera } from './camera';
  22. import { ParamDefinition as PD } from '../mol-util/param-definition';
  23. import { DebugHelperParams } from './helper/bounding-sphere-helper';
  24. import { SetUtils } from '../mol-util/set';
  25. import { Canvas3dInteractionHelper, Canvas3dInteractionHelperParams } from './helper/interaction-events';
  26. import { PostprocessingParams } from './passes/postprocessing';
  27. import { MultiSampleHelper, MultiSampleParams, MultiSamplePass } from './passes/multi-sample';
  28. import { PickData } from './passes/pick';
  29. import { PickHelper } from './passes/pick';
  30. import { ImagePass, ImageProps } from './passes/image';
  31. import { Sphere3D } from '../mol-math/geometry';
  32. import { isDebugMode } from '../mol-util/debug';
  33. import { CameraHelperParams } from './helper/camera-helper';
  34. import { produce } from 'immer';
  35. import { HandleHelperParams } from './helper/handle-helper';
  36. import { StereoCamera, StereoCameraParams } from './camera/stereo';
  37. import { Helper } from './helper/helper';
  38. import { Passes } from './passes/passes';
  39. import { shallowEqual } from '../mol-util';
  40. import { MarkingParams } from './passes/marking';
  41. import { GraphicsRenderVariantsBlended, GraphicsRenderVariantsWboit } from '../mol-gl/webgl/render-item';
  42. export const Canvas3DParams = {
  43. camera: PD.Group({
  44. mode: PD.Select('perspective', PD.arrayToOptions(['perspective', 'orthographic'] as const), { label: 'Camera' }),
  45. helper: PD.Group(CameraHelperParams, { isFlat: true }),
  46. stereo: PD.MappedStatic('off', {
  47. on: PD.Group(StereoCameraParams),
  48. off: PD.Group({})
  49. }, { cycle: true, hideIf: p => p?.mode !== 'perspective' }),
  50. manualReset: PD.Boolean(false, { isHidden: true }),
  51. }, { pivot: 'mode' }),
  52. cameraFog: PD.MappedStatic('on', {
  53. on: PD.Group({
  54. intensity: PD.Numeric(15, { min: 1, max: 100, step: 1 }),
  55. }),
  56. off: PD.Group({})
  57. }, { cycle: true, description: 'Show fog in the distance' }),
  58. cameraClipping: PD.Group({
  59. radius: PD.Numeric(100, { min: 0, max: 99, step: 1 }, { label: 'Clipping', description: 'How much of the scene to show.' }),
  60. far: PD.Boolean(true, { description: 'Hide scene in the distance' }),
  61. }, { pivot: 'radius' }),
  62. viewport: PD.MappedStatic('canvas', {
  63. canvas: PD.Group({}),
  64. 'static-frame': PD.Group({
  65. x: PD.Numeric(0),
  66. y: PD.Numeric(0),
  67. width: PD.Numeric(128),
  68. height: PD.Numeric(128)
  69. }),
  70. 'relative-frame': PD.Group({
  71. x: PD.Numeric(0.33, { min: 0, max: 1, step: 0.01 }),
  72. y: PD.Numeric(0.33, { min: 0, max: 1, step: 0.01 }),
  73. width: PD.Numeric(0.5, { min: 0.01, max: 1, step: 0.01 }),
  74. height: PD.Numeric(0.5, { min: 0.01, max: 1, step: 0.01 })
  75. })
  76. }),
  77. cameraResetDurationMs: PD.Numeric(250, { min: 0, max: 1000, step: 1 }, { description: 'The time it takes to reset the camera.' }),
  78. transparentBackground: PD.Boolean(false),
  79. multiSample: PD.Group(MultiSampleParams),
  80. postprocessing: PD.Group(PostprocessingParams),
  81. marking: PD.Group(MarkingParams),
  82. renderer: PD.Group(RendererParams),
  83. trackball: PD.Group(TrackballControlsParams),
  84. interaction: PD.Group(Canvas3dInteractionHelperParams),
  85. debug: PD.Group(DebugHelperParams),
  86. handle: PD.Group(HandleHelperParams),
  87. };
  88. export const DefaultCanvas3DParams = PD.getDefaultValues(Canvas3DParams);
  89. export type Canvas3DProps = PD.Values<typeof Canvas3DParams>
  90. export type PartialCanvas3DProps = {
  91. [K in keyof Canvas3DProps]?: Canvas3DProps[K] extends { name: string, params: any } ? Canvas3DProps[K] : Partial<Canvas3DProps[K]>
  92. }
  93. export { Canvas3DContext };
  94. /** Can be used to create multiple Canvas3D objects */
  95. interface Canvas3DContext {
  96. readonly canvas: HTMLCanvasElement
  97. readonly webgl: WebGLContext
  98. readonly input: InputObserver
  99. readonly passes: Passes
  100. readonly attribs: Readonly<Canvas3DContext.Attribs>
  101. readonly contextLost: BehaviorSubject<now.Timestamp>
  102. readonly contextRestored: BehaviorSubject<now.Timestamp>
  103. dispose: (options?: Partial<{ doNotForceWebGLContextLoss: boolean }>) => void
  104. }
  105. namespace Canvas3DContext {
  106. export const DefaultAttribs = {
  107. /** true by default to avoid issues with Safari (Jan 2021) */
  108. antialias: true,
  109. /** true to support multiple Canvas3D objects with a single context */
  110. preserveDrawingBuffer: true,
  111. pixelScale: 1,
  112. pickScale: 0.25,
  113. /** extra pixels to around target to check in case target is empty */
  114. pickPadding: 1,
  115. enableWboit: true,
  116. preferWebGl1: false
  117. };
  118. export type Attribs = typeof DefaultAttribs
  119. export function fromCanvas(canvas: HTMLCanvasElement, attribs: Partial<Attribs> = {}): Canvas3DContext {
  120. const a = { ...DefaultAttribs, ...attribs };
  121. const { antialias, preserveDrawingBuffer, pixelScale, preferWebGl1 } = a;
  122. const gl = getGLContext(canvas, {
  123. antialias,
  124. preserveDrawingBuffer,
  125. alpha: true, // the renderer requires an alpha channel
  126. depth: true, // the renderer requires a depth buffer
  127. premultipliedAlpha: true, // the renderer outputs PMA
  128. preferWebGl1
  129. });
  130. if (gl === null) throw new Error('Could not create a WebGL rendering context');
  131. const input = InputObserver.fromElement(canvas, { pixelScale, preventGestures: true });
  132. const webgl = createContext(gl, { pixelScale });
  133. const passes = new Passes(webgl, attribs);
  134. if (isDebugMode) {
  135. const loseContextExt = gl.getExtension('WEBGL_lose_context');
  136. if (loseContextExt) {
  137. // Hold down shift+ctrl+alt and press any mouse button to call `loseContext`.
  138. // After 1 second `restoreContext` will be called.
  139. canvas.addEventListener('mousedown', e => {
  140. if (webgl.isContextLost) return;
  141. if (!e.shiftKey || !e.ctrlKey || !e.altKey) return;
  142. if (isDebugMode) console.log('lose context');
  143. loseContextExt.loseContext();
  144. setTimeout(() => {
  145. if (!webgl.isContextLost) return;
  146. if (isDebugMode) console.log('restore context');
  147. loseContextExt.restoreContext();
  148. }, 1000);
  149. }, false);
  150. }
  151. }
  152. // https://www.khronos.org/webgl/wiki/HandlingContextLost
  153. const contextLost = new BehaviorSubject<now.Timestamp>(0 as now.Timestamp);
  154. const handleWebglContextLost = (e: Event) => {
  155. webgl.setContextLost();
  156. e.preventDefault();
  157. if (isDebugMode) console.log('context lost');
  158. contextLost.next(now());
  159. };
  160. const handlewWebglContextRestored = () => {
  161. if (!webgl.isContextLost) return;
  162. webgl.handleContextRestored(() => {
  163. passes.draw.reset();
  164. });
  165. if (isDebugMode) console.log('context restored');
  166. };
  167. canvas.addEventListener('webglcontextlost', handleWebglContextLost, false);
  168. canvas.addEventListener('webglcontextrestored', handlewWebglContextRestored, false);
  169. return {
  170. canvas,
  171. webgl,
  172. input,
  173. passes,
  174. attribs: a,
  175. contextLost,
  176. contextRestored: webgl.contextRestored,
  177. dispose: (options?: Partial<{ doNotForceWebGLContextLoss: boolean }>) => {
  178. input.dispose();
  179. canvas.removeEventListener('webglcontextlost', handleWebglContextLost, false);
  180. canvas.removeEventListener('webglcontextrestored', handlewWebglContextRestored, false);
  181. webgl.destroy(options);
  182. }
  183. };
  184. }
  185. }
  186. export { Canvas3D };
  187. interface Canvas3D {
  188. readonly webgl: WebGLContext,
  189. add(repr: Representation.Any): void
  190. remove(repr: Representation.Any): void
  191. /**
  192. * This function must be called if animate() is not set up so that add/remove actions take place.
  193. */
  194. commit(isSynchronous?: boolean): void
  195. /**
  196. * Function for external "animation" control
  197. * Calls commit.
  198. */
  199. tick(t: now.Timestamp, options?: { isSynchronous?: boolean, manualDraw?: boolean }): void
  200. update(repr?: Representation.Any, keepBoundingSphere?: boolean): void
  201. clear(): void
  202. syncVisibility(): void
  203. requestDraw(force?: boolean): void
  204. /** Reset the timers, used by "animate" */
  205. resetTime(t: number): void
  206. animate(): void
  207. /**
  208. * Pause animation loop and optionally any rendering
  209. * @param noDraw pause any rendering (drawPaused = true)
  210. */
  211. pause(noDraw?: boolean): void
  212. /** Sets drawPaused = false without starting the built in animation loop */
  213. resume(): void
  214. identify(x: number, y: number): PickData | undefined
  215. mark(loci: Representation.Loci, action: MarkerAction, noDraw?: boolean): void
  216. getLoci(pickingId: PickingId | undefined): Representation.Loci
  217. notifyDidDraw: boolean,
  218. readonly didDraw: BehaviorSubject<now.Timestamp>
  219. readonly commited: BehaviorSubject<now.Timestamp>
  220. readonly reprCount: BehaviorSubject<number>
  221. readonly resized: BehaviorSubject<any>
  222. handleResize(): void
  223. /** performs handleResize on the next animation frame */
  224. requestResize(): void
  225. /** Focuses camera on scene's bounding sphere, centered and zoomed. */
  226. requestCameraReset(options?: { durationMs?: number, snapshot?: Camera.SnapshotProvider }): void
  227. readonly camera: Camera
  228. readonly boundingSphere: Readonly<Sphere3D>
  229. readonly boundingSphereVisible: Readonly<Sphere3D>
  230. setProps(props: PartialCanvas3DProps | ((old: Canvas3DProps) => Partial<Canvas3DProps> | void), doNotRequestDraw?: boolean /* = false */): void
  231. getImagePass(props: Partial<ImageProps>): ImagePass
  232. getRenderObjects(): GraphicsRenderObject[]
  233. /** Returns a copy of the current Canvas3D instance props */
  234. readonly props: Readonly<Canvas3DProps>
  235. readonly input: InputObserver
  236. readonly stats: RendererStats
  237. readonly interaction: Canvas3dInteractionHelper['events']
  238. dispose(): void
  239. }
  240. const requestAnimationFrame = typeof window !== 'undefined'
  241. ? window.requestAnimationFrame
  242. : (f: (time: number) => void) => setImmediate(() => f(Date.now())) as unknown as number;
  243. const cancelAnimationFrame = typeof window !== 'undefined'
  244. ? window.cancelAnimationFrame
  245. : (handle: number) => clearImmediate(handle as unknown as NodeJS.Immediate);
  246. namespace Canvas3D {
  247. export interface HoverEvent { current: Representation.Loci, buttons: ButtonsType, button: ButtonsType.Flag, modifiers: ModifiersKeys, page?: Vec2, position?: Vec3 }
  248. export interface DragEvent { current: Representation.Loci, buttons: ButtonsType, button: ButtonsType.Flag, modifiers: ModifiersKeys, pageStart: Vec2, pageEnd: Vec2 }
  249. export interface ClickEvent { current: Representation.Loci, buttons: ButtonsType, button: ButtonsType.Flag, modifiers: ModifiersKeys, page?: Vec2, position?: Vec3 }
  250. export function create({ webgl, input, passes, attribs }: Canvas3DContext, props: Partial<Canvas3DProps> = {}): Canvas3D {
  251. const p: Canvas3DProps = { ...DefaultCanvas3DParams, ...props };
  252. const reprRenderObjects = new Map<Representation.Any, Set<GraphicsRenderObject>>();
  253. const reprUpdatedSubscriptions = new Map<Representation.Any, Subscription>();
  254. const reprCount = new BehaviorSubject(0);
  255. let startTime = now();
  256. const didDraw = new BehaviorSubject<now.Timestamp>(0 as now.Timestamp);
  257. const commited = new BehaviorSubject<now.Timestamp>(0 as now.Timestamp);
  258. const { gl, contextRestored } = webgl;
  259. let x = 0;
  260. let y = 0;
  261. let width = 128;
  262. let height = 128;
  263. updateViewport();
  264. const scene = Scene.create(webgl, passes.draw.wboitEnabled ? GraphicsRenderVariantsWboit : GraphicsRenderVariantsBlended);
  265. const camera = new Camera({
  266. position: Vec3.create(0, 0, 100),
  267. mode: p.camera.mode,
  268. fog: p.cameraFog.name === 'on' ? p.cameraFog.params.intensity : 0,
  269. clipFar: p.cameraClipping.far
  270. }, { x, y, width, height }, { pixelScale: attribs.pixelScale });
  271. const stereoCamera = new StereoCamera(camera, p.camera.stereo.params);
  272. const controls = TrackballControls.create(input, camera, p.trackball);
  273. const renderer = Renderer.create(webgl, p.renderer);
  274. const helper = new Helper(webgl, scene, p);
  275. const pickHelper = new PickHelper(webgl, renderer, scene, helper, passes.pick, { x, y, width, height }, attribs.pickPadding);
  276. const interactionHelper = new Canvas3dInteractionHelper(identify, getLoci, input, camera, p.interaction);
  277. const multiSampleHelper = new MultiSampleHelper(passes.multiSample);
  278. let cameraResetRequested = false;
  279. let nextCameraResetDuration: number | undefined = void 0;
  280. let nextCameraResetSnapshot: Camera.SnapshotProvider | undefined = void 0;
  281. let resizeRequested = false;
  282. let notifyDidDraw = true;
  283. function getLoci(pickingId: PickingId | undefined) {
  284. let loci: Loci = EmptyLoci;
  285. let repr: Representation.Any = Representation.Empty;
  286. if (pickingId) {
  287. const cameraHelperLoci = helper.camera.getLoci(pickingId);
  288. if (cameraHelperLoci !== EmptyLoci) return { loci: cameraHelperLoci, repr };
  289. loci = helper.handle.getLoci(pickingId);
  290. reprRenderObjects.forEach((_, _repr) => {
  291. const _loci = _repr.getLoci(pickingId);
  292. if (!isEmptyLoci(_loci)) {
  293. if (!isEmptyLoci(loci)) {
  294. console.warn('found another loci, this should not happen');
  295. }
  296. loci = _loci;
  297. repr = _repr;
  298. }
  299. });
  300. }
  301. return { loci, repr };
  302. }
  303. function mark(reprLoci: Representation.Loci, action: MarkerAction, noDraw = false) {
  304. const { repr, loci } = reprLoci;
  305. let changed = false;
  306. if (repr) {
  307. changed = repr.mark(loci, action);
  308. } else {
  309. changed = helper.handle.mark(loci, action);
  310. changed = helper.camera.mark(loci, action) || changed;
  311. reprRenderObjects.forEach((_, _repr) => { changed = _repr.mark(loci, action) || changed; });
  312. }
  313. if (changed && !noDraw) {
  314. scene.update(void 0, true);
  315. helper.handle.scene.update(void 0, true);
  316. helper.camera.scene.update(void 0, true);
  317. const prevPickDirty = pickHelper.dirty;
  318. draw(true);
  319. pickHelper.dirty = prevPickDirty; // marking does not change picking buffers
  320. }
  321. }
  322. function render(force: boolean) {
  323. if (webgl.isContextLost) return false;
  324. let resized = false;
  325. if (resizeRequested) {
  326. handleResize(false);
  327. resizeRequested = false;
  328. resized = true;
  329. }
  330. if (x > gl.drawingBufferWidth || x + width < 0 ||
  331. y > gl.drawingBufferHeight || y + height < 0
  332. ) return false;
  333. let didRender = false;
  334. controls.update(currentTime);
  335. const cameraChanged = camera.update();
  336. const shouldRender = force || cameraChanged || resized || forceNextRender;
  337. forceNextRender = false;
  338. const multiSampleChanged = multiSampleHelper.update(shouldRender, p.multiSample);
  339. if (shouldRender || multiSampleChanged) {
  340. let cam: Camera | StereoCamera = camera;
  341. if (p.camera.stereo.name === 'on') {
  342. stereoCamera.update();
  343. cam = stereoCamera;
  344. }
  345. if (MultiSamplePass.isEnabled(p.multiSample)) {
  346. if (!cameraChanged) {
  347. while (!multiSampleHelper.render(renderer, cam, scene, helper, true, p.transparentBackground, p));
  348. } else {
  349. multiSampleHelper.render(renderer, cam, scene, helper, true, p.transparentBackground, p);
  350. }
  351. } else {
  352. passes.draw.render(renderer, cam, scene, helper, true, p.transparentBackground, p.postprocessing, p.marking);
  353. }
  354. pickHelper.dirty = true;
  355. didRender = true;
  356. }
  357. return didRender;
  358. }
  359. let forceNextRender = false;
  360. let forceDrawAfterAllCommited = false;
  361. let currentTime = 0;
  362. let drawPaused = false;
  363. function draw(force?: boolean) {
  364. if (drawPaused) return;
  365. if (render(!!force) && notifyDidDraw) {
  366. didDraw.next(now() - startTime as now.Timestamp);
  367. }
  368. }
  369. function requestDraw(force?: boolean) {
  370. forceNextRender = forceNextRender || !!force;
  371. }
  372. let animationFrameHandle = 0;
  373. function tick(t: now.Timestamp, options?: { isSynchronous?: boolean, manualDraw?: boolean }) {
  374. currentTime = t;
  375. commit(options?.isSynchronous);
  376. camera.transition.tick(currentTime);
  377. if (options?.manualDraw) {
  378. return;
  379. }
  380. draw(false);
  381. if (!camera.transition.inTransition && !webgl.isContextLost) {
  382. interactionHelper.tick(currentTime);
  383. }
  384. }
  385. function _animate() {
  386. tick(now());
  387. animationFrameHandle = requestAnimationFrame(_animate);
  388. }
  389. function resetTime(t: now.Timestamp) {
  390. startTime = t;
  391. controls.start(t);
  392. }
  393. function animate() {
  394. drawPaused = false;
  395. controls.start(now());
  396. if (animationFrameHandle === 0) _animate();
  397. }
  398. function pause(noDraw = false) {
  399. drawPaused = noDraw;
  400. cancelAnimationFrame(animationFrameHandle);
  401. animationFrameHandle = 0;
  402. }
  403. function identify(x: number, y: number): PickData | undefined {
  404. const cam = p.camera.stereo.name === 'on' ? stereoCamera : camera;
  405. return webgl.isContextLost ? undefined : pickHelper.identify(x, y, cam);
  406. }
  407. function commit(isSynchronous: boolean = false) {
  408. const allCommited = commitScene(isSynchronous);
  409. // Only reset the camera after the full scene has been commited.
  410. if (allCommited) {
  411. resolveCameraReset();
  412. if (forceDrawAfterAllCommited) {
  413. if (helper.debug.isEnabled) helper.debug.update();
  414. draw(true);
  415. forceDrawAfterAllCommited = false;
  416. }
  417. commited.next(now());
  418. }
  419. }
  420. function resolveCameraReset() {
  421. if (!cameraResetRequested) return;
  422. const boundingSphere = scene.boundingSphereVisible;
  423. const { center, radius } = boundingSphere;
  424. const autoAdjustControls = controls.props.autoAdjustMinMaxDistance;
  425. if (autoAdjustControls.name === 'on') {
  426. const minDistance = autoAdjustControls.params.minDistanceFactor * radius + autoAdjustControls.params.minDistancePadding;
  427. const maxDistance = Math.max(autoAdjustControls.params.maxDistanceFactor * radius, autoAdjustControls.params.maxDistanceMin);
  428. controls.setProps({ minDistance, maxDistance });
  429. }
  430. if (radius > 0) {
  431. const duration = nextCameraResetDuration === undefined ? p.cameraResetDurationMs : nextCameraResetDuration;
  432. const focus = camera.getFocus(center, radius);
  433. const next = typeof nextCameraResetSnapshot === 'function' ? nextCameraResetSnapshot(scene, camera) : nextCameraResetSnapshot;
  434. const snapshot = next ? { ...focus, ...next } : focus;
  435. camera.setState({ ...snapshot, radiusMax: scene.boundingSphere.radius }, duration);
  436. }
  437. nextCameraResetDuration = void 0;
  438. nextCameraResetSnapshot = void 0;
  439. cameraResetRequested = false;
  440. }
  441. const oldBoundingSphereVisible = Sphere3D();
  442. const cameraSphere = Sphere3D();
  443. function shouldResetCamera() {
  444. if (camera.state.radiusMax === 0) return true;
  445. if (camera.transition.inTransition || nextCameraResetSnapshot) return false;
  446. let cameraSphereOverlapsNone = true, isEmpty = true;
  447. Sphere3D.set(cameraSphere, camera.state.target, camera.state.radius);
  448. // check if any renderable has moved outside of the old bounding sphere
  449. // and if no renderable is overlapping with the camera sphere
  450. for (const r of scene.renderables) {
  451. if (!r.state.visible) continue;
  452. const b = r.values.boundingSphere.ref.value;
  453. if (!b.radius) continue;
  454. isEmpty = false;
  455. const cameraDist = Vec3.distance(cameraSphere.center, b.center);
  456. if ((cameraDist > cameraSphere.radius || cameraDist > b.radius || b.radius > camera.state.radiusMax) && !Sphere3D.includes(oldBoundingSphereVisible, b)) return true;
  457. if (Sphere3D.overlaps(cameraSphere, b)) cameraSphereOverlapsNone = false;
  458. }
  459. return cameraSphereOverlapsNone || (!isEmpty && cameraSphere.radius <= 0.1);
  460. }
  461. const sceneCommitTimeoutMs = 250;
  462. function commitScene(isSynchronous: boolean) {
  463. if (!scene.needsCommit) return true;
  464. // snapshot the current bounding sphere of visible objects
  465. Sphere3D.copy(oldBoundingSphereVisible, scene.boundingSphereVisible);
  466. if (!scene.commit(isSynchronous ? void 0 : sceneCommitTimeoutMs)) return false;
  467. if (helper.debug.isEnabled) helper.debug.update();
  468. if (!p.camera.manualReset && (reprCount.value === 0 || shouldResetCamera())) {
  469. cameraResetRequested = true;
  470. }
  471. if (oldBoundingSphereVisible.radius === 0) nextCameraResetDuration = 0;
  472. camera.setState({ radiusMax: scene.boundingSphere.radius }, 0);
  473. reprCount.next(reprRenderObjects.size);
  474. if (isDebugMode) consoleStats();
  475. return true;
  476. }
  477. function consoleStats() {
  478. console.table(scene.renderables.map(r => ({
  479. drawCount: r.values.drawCount.ref.value,
  480. instanceCount: r.values.instanceCount.ref.value,
  481. materialId: r.materialId,
  482. renderItemId: r.id,
  483. })));
  484. console.log(webgl.stats);
  485. const { texture, attribute, elements } = webgl.resources.getByteCounts();
  486. console.log({
  487. texture: `${(texture / 1024 / 1024).toFixed(3)} MiB`,
  488. attribute: `${(attribute / 1024 / 1024).toFixed(3)} MiB`,
  489. elements: `${(elements / 1024 / 1024).toFixed(3)} MiB`,
  490. });
  491. }
  492. function add(repr: Representation.Any) {
  493. registerAutoUpdate(repr);
  494. const oldRO = reprRenderObjects.get(repr);
  495. const newRO = new Set<GraphicsRenderObject>();
  496. repr.renderObjects.forEach(o => newRO.add(o));
  497. if (oldRO) {
  498. if (!SetUtils.areEqual(newRO, oldRO)) {
  499. newRO.forEach(o => { if (!oldRO.has(o)) scene.add(o); });
  500. oldRO.forEach(o => { if (!newRO.has(o)) scene.remove(o); });
  501. }
  502. } else {
  503. repr.renderObjects.forEach(o => scene.add(o));
  504. }
  505. reprRenderObjects.set(repr, newRO);
  506. scene.update(repr.renderObjects, false);
  507. forceDrawAfterAllCommited = true;
  508. if (isDebugMode) consoleStats();
  509. }
  510. function remove(repr: Representation.Any) {
  511. unregisterAutoUpdate(repr);
  512. const renderObjects = reprRenderObjects.get(repr);
  513. if (renderObjects) {
  514. renderObjects.forEach(o => scene.remove(o));
  515. reprRenderObjects.delete(repr);
  516. forceDrawAfterAllCommited = true;
  517. if (isDebugMode) consoleStats();
  518. }
  519. }
  520. function registerAutoUpdate(repr: Representation.Any) {
  521. if (reprUpdatedSubscriptions.has(repr)) return;
  522. reprUpdatedSubscriptions.set(repr, repr.updated.subscribe(_ => {
  523. if (!repr.state.syncManually) add(repr);
  524. }));
  525. }
  526. function unregisterAutoUpdate(repr: Representation.Any) {
  527. const updatedSubscription = reprUpdatedSubscriptions.get(repr);
  528. if (updatedSubscription) {
  529. updatedSubscription.unsubscribe();
  530. reprUpdatedSubscriptions.delete(repr);
  531. }
  532. }
  533. function getProps(): Canvas3DProps {
  534. const radius = scene.boundingSphere.radius > 0
  535. ? 100 - Math.round((camera.transition.target.radius / scene.boundingSphere.radius) * 100)
  536. : 0;
  537. return {
  538. camera: {
  539. mode: camera.state.mode,
  540. helper: { ...helper.camera.props },
  541. stereo: { ...p.camera.stereo },
  542. manualReset: !!p.camera.manualReset
  543. },
  544. cameraFog: camera.state.fog > 0
  545. ? { name: 'on' as const, params: { intensity: camera.state.fog } }
  546. : { name: 'off' as const, params: {} },
  547. cameraClipping: { far: camera.state.clipFar, radius },
  548. cameraResetDurationMs: p.cameraResetDurationMs,
  549. transparentBackground: p.transparentBackground,
  550. viewport: p.viewport,
  551. postprocessing: { ...p.postprocessing },
  552. marking: { ...p.marking },
  553. multiSample: { ...p.multiSample },
  554. renderer: { ...renderer.props },
  555. trackball: { ...controls.props },
  556. interaction: { ...interactionHelper.props },
  557. debug: { ...helper.debug.props },
  558. handle: { ...helper.handle.props },
  559. };
  560. }
  561. const contextRestoredSub = contextRestored.subscribe(() => {
  562. pickHelper.dirty = true;
  563. draw(true);
  564. // Unclear why, but in Chrome with wboit enabled the first `draw` only clears
  565. // the drawingBuffer. Note that in Firefox the drawingBuffer is preserved after
  566. // context loss so it is unclear if it behaves the same.
  567. draw(true);
  568. });
  569. const resized = new BehaviorSubject<any>(0);
  570. function handleResize(draw = true) {
  571. passes.updateSize();
  572. updateViewport();
  573. syncViewport();
  574. if (draw) requestDraw(true);
  575. resized.next(+new Date());
  576. }
  577. return {
  578. webgl,
  579. add,
  580. remove,
  581. commit,
  582. update: (repr, keepSphere) => {
  583. if (repr) {
  584. if (!reprRenderObjects.has(repr)) return;
  585. scene.update(repr.renderObjects, !!keepSphere);
  586. } else {
  587. scene.update(void 0, !!keepSphere);
  588. }
  589. forceDrawAfterAllCommited = true;
  590. },
  591. clear: () => {
  592. reprUpdatedSubscriptions.forEach(v => v.unsubscribe());
  593. reprUpdatedSubscriptions.clear();
  594. reprRenderObjects.clear();
  595. scene.clear();
  596. helper.debug.clear();
  597. requestDraw(true);
  598. reprCount.next(reprRenderObjects.size);
  599. },
  600. syncVisibility: () => {
  601. if (camera.state.radiusMax === 0) {
  602. cameraResetRequested = true;
  603. nextCameraResetDuration = 0;
  604. }
  605. if (scene.syncVisibility()) {
  606. if (helper.debug.isEnabled) helper.debug.update();
  607. }
  608. requestDraw(true);
  609. },
  610. requestDraw,
  611. tick,
  612. animate,
  613. resetTime,
  614. pause,
  615. resume: () => { drawPaused = false; },
  616. identify,
  617. mark,
  618. getLoci,
  619. handleResize,
  620. requestResize: () => {
  621. resizeRequested = true;
  622. },
  623. requestCameraReset: options => {
  624. nextCameraResetDuration = options?.durationMs;
  625. nextCameraResetSnapshot = options?.snapshot;
  626. cameraResetRequested = true;
  627. },
  628. camera,
  629. boundingSphere: scene.boundingSphere,
  630. boundingSphereVisible: scene.boundingSphereVisible,
  631. get notifyDidDraw() { return notifyDidDraw; },
  632. set notifyDidDraw(v: boolean) { notifyDidDraw = v; },
  633. didDraw,
  634. commited,
  635. reprCount,
  636. resized,
  637. setProps: (properties, doNotRequestDraw = false) => {
  638. const props: PartialCanvas3DProps = typeof properties === 'function'
  639. ? produce(getProps(), properties as any)
  640. : properties;
  641. const cameraState: Partial<Camera.Snapshot> = Object.create(null);
  642. if (props.camera && props.camera.mode !== undefined && props.camera.mode !== camera.state.mode) {
  643. cameraState.mode = props.camera.mode;
  644. }
  645. if (props.cameraFog !== undefined && props.cameraFog.params) {
  646. const newFog = props.cameraFog.name === 'on' ? props.cameraFog.params.intensity : 0;
  647. if (newFog !== camera.state.fog) cameraState.fog = newFog;
  648. }
  649. if (props.cameraClipping !== undefined) {
  650. if (props.cameraClipping.far !== undefined && props.cameraClipping.far !== camera.state.clipFar) {
  651. cameraState.clipFar = props.cameraClipping.far;
  652. }
  653. if (props.cameraClipping.radius !== undefined) {
  654. const radius = (scene.boundingSphere.radius / 100) * (100 - props.cameraClipping.radius);
  655. if (radius > 0 && radius !== cameraState.radius) {
  656. // if radius = 0, NaNs happen
  657. cameraState.radius = Math.max(radius, 0.01);
  658. }
  659. }
  660. }
  661. if (Object.keys(cameraState).length > 0) camera.setState(cameraState);
  662. if (props.camera?.helper) helper.camera.setProps(props.camera.helper);
  663. if (props.camera?.manualReset !== undefined) p.camera.manualReset = props.camera.manualReset;
  664. if (props.camera?.stereo !== undefined) Object.assign(p.camera.stereo, props.camera.stereo);
  665. if (props.cameraResetDurationMs !== undefined) p.cameraResetDurationMs = props.cameraResetDurationMs;
  666. if (props.transparentBackground !== undefined) p.transparentBackground = props.transparentBackground;
  667. if (props.viewport !== undefined) {
  668. const doNotUpdate = p.viewport === props.viewport ||
  669. (p.viewport.name === props.viewport.name && shallowEqual(p.viewport.params, props.viewport.params));
  670. if (!doNotUpdate) {
  671. p.viewport = props.viewport;
  672. updateViewport();
  673. syncViewport();
  674. }
  675. }
  676. if (props.postprocessing) Object.assign(p.postprocessing, props.postprocessing);
  677. if (props.marking) Object.assign(p.marking, props.marking);
  678. if (props.multiSample) Object.assign(p.multiSample, props.multiSample);
  679. if (props.renderer) renderer.setProps(props.renderer);
  680. if (props.trackball) controls.setProps(props.trackball);
  681. if (props.interaction) interactionHelper.setProps(props.interaction);
  682. if (props.debug) helper.debug.setProps(props.debug);
  683. if (props.handle) helper.handle.setProps(props.handle);
  684. if (cameraState.mode === 'orthographic') {
  685. p.camera.stereo.name = 'off';
  686. }
  687. if (!doNotRequestDraw) {
  688. requestDraw(true);
  689. }
  690. },
  691. getImagePass: (props: Partial<ImageProps> = {}) => {
  692. return new ImagePass(webgl, renderer, scene, camera, helper, passes.draw.wboitEnabled, props);
  693. },
  694. getRenderObjects(): GraphicsRenderObject[] {
  695. const renderObjects: GraphicsRenderObject[] = [];
  696. scene.forEach((_, ro) => renderObjects.push(ro));
  697. return renderObjects;
  698. },
  699. get props() {
  700. return getProps();
  701. },
  702. get input() {
  703. return input;
  704. },
  705. get stats() {
  706. return renderer.stats;
  707. },
  708. get interaction() {
  709. return interactionHelper.events;
  710. },
  711. dispose: () => {
  712. contextRestoredSub.unsubscribe();
  713. scene.clear();
  714. helper.debug.clear();
  715. controls.dispose();
  716. renderer.dispose();
  717. interactionHelper.dispose();
  718. }
  719. };
  720. function updateViewport() {
  721. const oldX = x, oldY = y, oldWidth = width, oldHeight = height;
  722. if (p.viewport.name === 'canvas') {
  723. x = 0;
  724. y = 0;
  725. width = gl.drawingBufferWidth;
  726. height = gl.drawingBufferHeight;
  727. } else if (p.viewport.name === 'static-frame') {
  728. x = p.viewport.params.x * webgl.pixelRatio;
  729. height = p.viewport.params.height * webgl.pixelRatio;
  730. y = gl.drawingBufferHeight - height - p.viewport.params.y * webgl.pixelRatio;
  731. width = p.viewport.params.width * webgl.pixelRatio;
  732. } else if (p.viewport.name === 'relative-frame') {
  733. x = Math.round(p.viewport.params.x * gl.drawingBufferWidth);
  734. height = Math.round(p.viewport.params.height * gl.drawingBufferHeight);
  735. y = Math.round(gl.drawingBufferHeight - height - p.viewport.params.y * gl.drawingBufferHeight);
  736. width = Math.round(p.viewport.params.width * gl.drawingBufferWidth);
  737. }
  738. if (oldX !== x || oldY !== y || oldWidth !== width || oldHeight !== height) {
  739. forceNextRender = true;
  740. }
  741. }
  742. function syncViewport() {
  743. pickHelper.setViewport(x, y, width, height);
  744. renderer.setViewport(x, y, width, height);
  745. Viewport.set(camera.viewport, x, y, width, height);
  746. Viewport.set(controls.viewport, x, y, width, height);
  747. }
  748. }
  749. }