scene.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. /**
  2. * Copyright (c) 2018-2023 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 { WebGLContext } from './webgl/context';
  8. import { GraphicsRenderObject, createRenderable } from './render-object';
  9. import { Object3D } from './object3d';
  10. import { Sphere3D } from '../mol-math/geometry/primitives/sphere3d';
  11. import { CommitQueue } from './commit-queue';
  12. import { now } from '../mol-util/now';
  13. import { arraySetRemove } from '../mol-util/array';
  14. import { BoundaryHelper } from '../mol-math/geometry/boundary-helper';
  15. import { hash1 } from '../mol-data/util';
  16. import { GraphicsRenderable } from './renderable';
  17. import { GraphicsRenderVariants } from './webgl/render-item';
  18. import { clamp } from '../mol-math/interpolate';
  19. const boundaryHelper = new BoundaryHelper('98');
  20. function calculateBoundingSphere(renderables: GraphicsRenderable[], boundingSphere: Sphere3D, onlyVisible: boolean): Sphere3D {
  21. boundaryHelper.reset();
  22. for (let i = 0, il = renderables.length; i < il; ++i) {
  23. if (onlyVisible && !renderables[i].state.visible) continue;
  24. const boundingSphere = renderables[i].values.boundingSphere.ref.value;
  25. if (!boundingSphere.radius) continue;
  26. boundaryHelper.includeSphere(boundingSphere);
  27. }
  28. boundaryHelper.finishedIncludeStep();
  29. for (let i = 0, il = renderables.length; i < il; ++i) {
  30. if (onlyVisible && !renderables[i].state.visible) continue;
  31. const boundingSphere = renderables[i].values.boundingSphere.ref.value;
  32. if (!boundingSphere.radius) continue;
  33. boundaryHelper.radiusSphere(boundingSphere);
  34. }
  35. return boundaryHelper.getSphere(boundingSphere);
  36. }
  37. function renderableSort(a: GraphicsRenderable, b: GraphicsRenderable) {
  38. const drawProgramIdA = (a.getProgram('colorBlended') || a.getProgram('colorWboit') || a.getProgram('colorDpoit')).id;
  39. const drawProgramIdB = (b.getProgram('colorBlended') || b.getProgram('colorWboit') || b.getProgram('colorDpoit')).id;
  40. const materialIdA = a.materialId;
  41. const materialIdB = b.materialId;
  42. if (drawProgramIdA !== drawProgramIdB) {
  43. // sort by program id to minimize gl state changes
  44. return drawProgramIdA - drawProgramIdB;
  45. } else if (materialIdA !== materialIdB) {
  46. // sort by material id to minimize gl state changes
  47. return materialIdA - materialIdB;
  48. } else {
  49. return a.id - b.id;
  50. }
  51. }
  52. interface Scene extends Object3D {
  53. readonly count: number
  54. readonly renderables: ReadonlyArray<GraphicsRenderable>
  55. readonly boundingSphere: Sphere3D
  56. readonly boundingSphereVisible: Sphere3D
  57. readonly primitives: Scene.Group
  58. readonly volumes: Scene.Group
  59. /** Returns `true` if some visibility has changed, `false` otherwise. */
  60. syncVisibility: () => boolean
  61. update: (objects: ArrayLike<GraphicsRenderObject> | undefined, keepBoundingSphere: boolean) => void
  62. add: (o: GraphicsRenderObject) => void // GraphicsRenderable
  63. remove: (o: GraphicsRenderObject) => void
  64. commit: (maxTimeMs?: number) => boolean
  65. readonly needsCommit: boolean
  66. readonly commitQueueSize: number
  67. has: (o: GraphicsRenderObject) => boolean
  68. clear: () => void
  69. forEach: (callbackFn: (value: GraphicsRenderable, key: GraphicsRenderObject) => void) => void
  70. /** Marker average of primitive renderables */
  71. readonly markerAverage: number
  72. /** Opacity average of primitive renderables */
  73. readonly opacityAverage: number
  74. /** Is `true` if any primitive renderable (possibly) has any opaque part */
  75. readonly hasOpaque: boolean
  76. }
  77. namespace Scene {
  78. export interface Group extends Object3D {
  79. readonly renderables: ReadonlyArray<GraphicsRenderable>
  80. }
  81. export function create(ctx: WebGLContext, variants = GraphicsRenderVariants): Scene {
  82. const renderableMap = new Map<GraphicsRenderObject, GraphicsRenderable>();
  83. const renderables: GraphicsRenderable[] = [];
  84. const boundingSphere = Sphere3D();
  85. const boundingSphereVisible = Sphere3D();
  86. const primitives: GraphicsRenderable[] = [];
  87. const volumes: GraphicsRenderable[] = [];
  88. let boundingSphereDirty = true;
  89. let boundingSphereVisibleDirty = true;
  90. let markerAverageDirty = true;
  91. let opacityAverageDirty = true;
  92. let hasOpaqueDirty = true;
  93. let markerAverage = 0;
  94. let opacityAverage = 0;
  95. let hasOpaque = false;
  96. const object3d = Object3D.create();
  97. const { view, position, direction, up } = object3d;
  98. function add(o: GraphicsRenderObject) {
  99. if (!renderableMap.has(o)) {
  100. const renderable = createRenderable(ctx, o, variants);
  101. renderables.push(renderable);
  102. if (o.type === 'direct-volume') {
  103. volumes.push(renderable);
  104. } else {
  105. primitives.push(renderable);
  106. }
  107. renderableMap.set(o, renderable);
  108. boundingSphereDirty = true;
  109. boundingSphereVisibleDirty = true;
  110. } else {
  111. console.warn(`RenderObject with id '${o.id}' already present`);
  112. }
  113. }
  114. function remove(o: GraphicsRenderObject) {
  115. const renderable = renderableMap.get(o);
  116. if (renderable) {
  117. renderable.dispose();
  118. arraySetRemove(renderables, renderable);
  119. arraySetRemove(primitives, renderable);
  120. arraySetRemove(volumes, renderable);
  121. renderableMap.delete(o);
  122. boundingSphereDirty = true;
  123. boundingSphereVisibleDirty = true;
  124. }
  125. }
  126. const commitBulkSize = 100;
  127. function commit(maxTimeMs: number) {
  128. const start = now();
  129. let i = 0;
  130. while (true) {
  131. const o = commitQueue.tryGetRemove();
  132. if (!o) break;
  133. remove(o);
  134. if (++i % commitBulkSize === 0 && now() - start > maxTimeMs) return false;
  135. }
  136. while (true) {
  137. const o = commitQueue.tryGetAdd();
  138. if (!o) break;
  139. add(o);
  140. if (++i % commitBulkSize === 0 && now() - start > maxTimeMs) return false;
  141. }
  142. renderables.sort(renderableSort);
  143. markerAverageDirty = true;
  144. opacityAverageDirty = true;
  145. hasOpaqueDirty = true;
  146. return true;
  147. }
  148. const commitQueue = new CommitQueue();
  149. let visibleHash = -1;
  150. function computeVisibleHash() {
  151. let hash = 23;
  152. for (let i = 0, il = renderables.length; i < il; ++i) {
  153. if (!renderables[i].state.visible) continue;
  154. hash = (31 * hash + renderables[i].id) | 0;
  155. }
  156. hash = hash1(hash);
  157. if (hash === -1) hash = 0;
  158. return hash;
  159. }
  160. function syncVisibility() {
  161. const newVisibleHash = computeVisibleHash();
  162. if (newVisibleHash !== visibleHash) {
  163. boundingSphereVisibleDirty = true;
  164. markerAverageDirty = true;
  165. opacityAverageDirty = true;
  166. hasOpaqueDirty = true;
  167. visibleHash = newVisibleHash;
  168. return true;
  169. } else {
  170. return false;
  171. }
  172. }
  173. function calculateMarkerAverage() {
  174. if (primitives.length === 0) return 0;
  175. let count = 0;
  176. let markerAverage = 0;
  177. for (let i = 0, il = primitives.length; i < il; ++i) {
  178. if (!primitives[i].state.visible) continue;
  179. markerAverage += primitives[i].values.markerAverage.ref.value;
  180. count += 1;
  181. }
  182. return count > 0 ? markerAverage / count : 0;
  183. }
  184. function calculateOpacityAverage() {
  185. if (primitives.length === 0) return 0;
  186. let count = 0;
  187. let opacityAverage = 0;
  188. for (let i = 0, il = primitives.length; i < il; ++i) {
  189. const p = primitives[i];
  190. if (!p.state.visible) continue;
  191. // TODO: simplify, handle in renderable.state???
  192. // uAlpha is updated in "render" so we need to recompute it here
  193. const alpha = clamp(p.values.alpha.ref.value * p.state.alphaFactor, 0, 1);
  194. const xray = p.values.dXrayShaded?.ref.value ? 0.5 : 1;
  195. const fuzzy = p.values.dPointStyle?.ref.value === 'fuzzy' ? 0.5 : 1;
  196. const text = p.values.dGeometryType.ref.value === 'text' ? 0.5 : 1;
  197. opacityAverage += (1 - p.values.transparencyAverage.ref.value) * alpha * xray * fuzzy * text;
  198. count += 1;
  199. }
  200. return count > 0 ? opacityAverage / count : 0;
  201. }
  202. function calculateHasOpaque() {
  203. if (primitives.length === 0) return false;
  204. for (let i = 0, il = primitives.length; i < il; ++i) {
  205. const p = primitives[i];
  206. if (!p.state.visible) continue;
  207. if (p.state.opaque) return true;
  208. if (p.state.alphaFactor === 1 && p.values.alpha.ref.value === 1 && p.values.transparencyAverage.ref.value !== 1) return true;
  209. if (p.values.dTransparentBackfaces?.ref.value === 'opaque') return true;
  210. }
  211. return false;
  212. }
  213. return {
  214. view, position, direction, up,
  215. renderables,
  216. primitives: { view, position, direction, up, renderables: primitives },
  217. volumes: { view, position, direction, up, renderables: volumes },
  218. syncVisibility,
  219. update(objects, keepBoundingSphere) {
  220. Object3D.update(object3d);
  221. if (objects) {
  222. for (let i = 0, il = objects.length; i < il; ++i) {
  223. renderableMap.get(objects[i])?.update();
  224. }
  225. } else {
  226. for (let i = 0, il = renderables.length; i < il; ++i) {
  227. renderables[i].update();
  228. }
  229. }
  230. if (!keepBoundingSphere) {
  231. boundingSphereDirty = true;
  232. boundingSphereVisibleDirty = true;
  233. } else {
  234. syncVisibility();
  235. }
  236. markerAverageDirty = true;
  237. opacityAverageDirty = true;
  238. hasOpaqueDirty = true;
  239. },
  240. add: (o: GraphicsRenderObject) => commitQueue.add(o),
  241. remove: (o: GraphicsRenderObject) => commitQueue.remove(o),
  242. commit: (maxTime = Number.MAX_VALUE) => commit(maxTime),
  243. get commitQueueSize() { return commitQueue.size; },
  244. get needsCommit() { return !commitQueue.isEmpty; },
  245. has: (o: GraphicsRenderObject) => {
  246. return renderableMap.has(o);
  247. },
  248. clear: () => {
  249. for (let i = 0, il = renderables.length; i < il; ++i) {
  250. renderables[i].dispose();
  251. }
  252. renderables.length = 0;
  253. primitives.length = 0;
  254. volumes.length = 0;
  255. renderableMap.clear();
  256. boundingSphereDirty = true;
  257. boundingSphereVisibleDirty = true;
  258. },
  259. forEach: (callbackFn: (value: GraphicsRenderable, key: GraphicsRenderObject) => void) => {
  260. renderableMap.forEach(callbackFn);
  261. },
  262. get count() {
  263. return renderables.length;
  264. },
  265. get boundingSphere() {
  266. if (boundingSphereDirty) {
  267. calculateBoundingSphere(renderables, boundingSphere, false);
  268. boundingSphereDirty = false;
  269. }
  270. return boundingSphere;
  271. },
  272. get boundingSphereVisible() {
  273. if (boundingSphereVisibleDirty) {
  274. calculateBoundingSphere(renderables, boundingSphereVisible, true);
  275. boundingSphereVisibleDirty = false;
  276. }
  277. return boundingSphereVisible;
  278. },
  279. get markerAverage() {
  280. if (markerAverageDirty) {
  281. markerAverage = calculateMarkerAverage();
  282. markerAverageDirty = false;
  283. }
  284. return markerAverage;
  285. },
  286. get opacityAverage() {
  287. if (opacityAverageDirty) {
  288. opacityAverage = calculateOpacityAverage();
  289. opacityAverageDirty = false;
  290. }
  291. return opacityAverage;
  292. },
  293. get hasOpaque() {
  294. if (hasOpaqueDirty) {
  295. hasOpaque = calculateHasOpaque();
  296. hasOpaqueDirty = false;
  297. }
  298. return hasOpaque;
  299. },
  300. };
  301. }
  302. }
  303. export { Scene };