canvas3d.ts 35 KB

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