Skip to content

Commit

Permalink
Viewer API Improvements (#2072)
Browse files Browse the repository at this point in the history
* Fix some monstrous bugs with index buffer shuffling now that we've changed our approach a bit.~

* Finished with the new material management approach for mesh batches. SelectionExtension now uses this approach and also considers existing material opacities when setting select and hover materials

* Updated LineBatch to work with the new material management approach

* Implemented the required draw range related changes to the point batch

* Text batche now work with the new material management

* SpeckleLineMaterial and SpecklePointsMaterial are now SpeckleMaterial as well. Had to rename two properties of SpeckleMaterial due to some typescript named property clash thing, but nothing really changed

* Removed eslint-disable clauses in materials where they were no longer needed. Removed unused imports and overrides

* Added the RTE define for some materials by default. It can still be overriden if users want to

* Stencil outlines is now an toggle-able option for any SpeckleMaterial. Restricted to meshes

* Implemented setting desired material for all geometry types via RenderMaterial and DisplayStyle data. SpeckleRenderer now has three overloaded setMaterial function. One for a material instance, one for a filer material and one for RenderData&DisplayStyle. Moved material hash related functionality from NodeRendeView into Materials

* Added MaterialOptions which can be used when setting materials based on RenderMaterial/DisplayStyle to toggle various material features like stencilOutlines, pointSize. SelectionExtension now uses data material to set materials, and things are so much more simpler and nicer

* Added public method for setting seletion extension options

* After some profiling, realized three.js was doing a lot of pointless work each frame so now we're caching materials created from RenderMaterial/DisplayStyle to avoid this. Perf is nice and sharp now

* addRenderTreeAsync is now a generator. Handled automatic zooming on viewer loading. Disabled section tool by default

* Centralized RTE and shadow RTE buffer in an extended webglrenderer. This avoids re-computing rte data for each material over and over. Also, rte data is now centralized and available to materials

* SpeckleMeshes now use a cached material clone as their batch material like any other material they use

* Cleaned up Materils. Updated the debug show batches function use the new material manipulation system. So much easier now

* Real time measurement exist now as a separate extension. Existing functionality preserved, besides one or two small additions. Renamed the MEASUREMENTS object layer to OVERLAY for a more generic usage. SelectionExtension can now be enabled/disabled. Added an additional overload to the setCameraView method in ICameraController which takes a box3 as target to focus the camera on

* Removed viewer related events from input and replaced them everywhere with the proper input event types where required

* Fixed two issues with the shadowcatcher. One was a regression introduced after we centralized the RTE data. The other was a super old one one and was essentially causing the shadowcatcher to generate the contact shadows incorrectly because the correct transform textures were not bound (this is three.js being a pain)

* WIP on the filtering extension

* FilteringExtension is done. Kept the same implementation

* Added filter reset function

* Removed uniform texture and batch count binding from each material's OnBeforeRender function. Additionallit our material override function from SpeckleMesh now uses our fast copy instead of three's copy function for materials. This decreased CPU overhead each frame by 20+% and also eliminated the ugly call to SpeckleMesh's function for updating the material with the transform texture and batch object count from each material's render callback which was not supposed to be there

* Update RenderingStats to measure CPU render time per frame.

* Added early and late update functions for extensions. First gets called before the core's update, and the latter afterwards

* All speckle materials now use the centralized RTE data. Updated the fasts copy method to copy userdata defined uniforms where needed

* Added explosion extension. Additional cleanup

* Dirty transforms are marked on a per batch object basis, whenever their transforms gets changed. This automates the transform texture update execution, so we no longer need to manually mark entire batches as dirty

* Added getObjects which returns all batch objects in the scene and getObjects which takes an rv an returns only the batch object associated with that rv. Both of these methods are availale on the renderer

* Added setters for position, rotiation and scale in batch object

* Diff extension is complete. We stuck with creating material instances and using those for coloring since it ensures maximum draw call efficiency. Fixed an issue in MeshBatch where transparent draw groups were not always sorted at the end of the group list leading to incorect opauque object selection during the depth pass

* RV batch materials are obtained via the viewer-core API based on the RV itslef. This removed the need to get all batch materials for the differ

* Small cleanup

* Removed all circular dependencies besides one, like I predicted. The final one will dissapaear on it's own in the near future when we'll gracefull make DataTree obsolete. As a note, the circular dependencies were very shallow, reffering to enums/interfaces/statics declared in specific files. There was no real circular dependency on a class level

* Removed last circular dependency just for the sake of completion

* SpeckleRendere now has a clipping volume which is used internally to reject picks outside of it, and it's also exposed to the outside world to be used however

* Implemented the SpeckleLoader along with it's abstract supertype. Data loading is now done through this loader which handles tree population with raw data as well as render view data.

* Working minimal obj loader

* Added total node counting and displaying

* Viewer's load object now takes a loader of any speckle loader base class and uses that to load, instead of taking urls and tokens. This allows for any kind of loader to work with the vieweer's load function. Moved indexing of obj geometry to the obj geometry convertor. Loaders now take the target world tree instance instead of a viewer instance

* Loaders can now load from string and array buffer data where implemented. ObjLoader can now load from a string payload. Sandbox can now load obj files from the UI using a file picker

* alex/API2.0-core

* Started on #1673. Fixed an issue with walkAsync where the recursive generator would waste too much time idle.

* Solution for #1673. Replaced the old async pausing approach with a better version that has true variable wait time, and does not add additional dead wait time. Render tree building is now several times faster

* Cut down some more on load time by using a lookup table for determined speckle types. For a very large number of objects, getting the actual speckle type was quite slow. For our reference stream with 1kk objects we cut down around 2 seconds of load time

* BoxFromObjects now returns the correctly transformed aabb

* Implemented optimisations for batch building step from the loading process. Reduced the step's time by around 50%

* Implemented a NodeMap which allows us to search for nodes very very fast.

* Added a dynamic pause in the loader which stops the converter from blocking. Paramater object types are not added as nodes anymore. Callback from converter is not without arguments

* Replaced some internal walks with the newer and much faster id finding approach

* Disable object shallow cloning acrss the speckle converter

* Fixed the issues with block instances and revit instances caused by not duplicating speckle objects in the converter

* getObjectPropertis is now async and slightly improved the execution time of the flatten function which it uses

* Set caching to true by default

* Fix for display style hashing

* Implemented legacy viewer as a wrapper around the old viewer API

* Started testing FE1 with API 2.0. Fixed some legacy issues. Also the camera controller extension now exposes it's underlying controls object for the sake of not messing around with unwatend changes in FE1

* Updated FE1 with API2.0 selection changes

* Fixing selection bugs

* The viewer now ignores duplicate id nodes

* Fixes to object properties population, camera zooming and adding subtrees in core

* Fixed some filtering issues. Added UpdateFlags to the viewer's requestRender function

* Fixed an issue where section boxes were incorrectly added to the URL

* Objects with no id are not given nodes into the tree

* Updates to FE2 for API2.0. Also fixed a really really obscure bug in viewer-core where a material an incorrect material was set when reseting the batch to the default material

* We now store separate node maps for each model loaded. Each node now holds it's subtree id (as a small number for memory considerations)

* Render request after updating the visual diff

* Fixed some missing update calls on shadows

* Reverted FE1 changes and pinned the viewer library to a specific (latest) version pre-API2.0

* We're adding a viewer node for loaded models as subtree parent. This is because we're no longer spoofing ids and the model parent id needs to be preserved

* Fixed an issue where clicking on a comment bubble made the pipeline use accumulation improperly, leading to dark blight

* Null check for setMaterial. Fixed another case of dark blight. Hack required by frontend

* Fixed the issue with filtering state not propagating in the FE

* Updated selection event changes

* Fixed an issue where an undefined subtree id would yield an incorrect render tree upon requesting it

* Fixed an issue where undefined nodes were returned as valid when searching of ids

* NodeRenderView now holds it's subtree id along the speckle id. This allows for precise node matching when looking for specific nodes

* Fixed an issue with BlockInstances not instancing underlying meshes from breps

* Some fixes to diffing. Some older than API2.0, some new. Render views now have guid composed of their id and subtreeid.

* Update node render view id with guid where needed

* Unload function now checks for requested resource to unload before trying to unload it

* Check for the existence of a batch before applying draw ranges. Inthe FE, extension can temporarily keep dead rvs in their state when switching between streams leading to errors

* Fixed an issue for filtering where subtree roots would cause incorrect rv additions to the ghosted rv lists

* Unified block instance and revit instance conversion implementation

* Separted instanced from non-instanced rvs. Working on InstancedMeshBatch

* WIP on instanced types

* Implemented visual for box draging

* BoxSelection extension beautified and documented along with some small but welcomed changes to the viewer-core

* Viewer's getExtension now looks in the prototype chain before returning an undefined extension

* Added the extended Selection extension here for possible later use

* First iteration on instancing. General idea works. Still WIP on several fronts

* Fixed issues related to incorrect transform being calculated for instanced geometry. Fixed an issue with incorrect bounds being calculated

* Fixed a few issues with instanced vs non instanced render view gathering

* Disabled box selection extension

* Fixed some linter errors

* Disabled a lint 'error'

* Fixed issues with depth rendering and instanced objects and fixed draw range visibility for instanced batches in a minimalistic way

* Updated the measurements extension with the visiblity option

* Restructed a bit our implementation for the acceleration structure because now the BLAS needs to aggregate an instance of three-mesh-bvh not extend it. So that instanced batch objects can share a single bvh instance -> no redundancy

* WIP

* Revert "WIP"

This reverts commit 20d4bbf.

* More WIP on trying to make instanced geometry TAS and BAS work properly

* Both Tas and Bas intersection testing seem to working fine. Now we need to implemented draw grouping for instanced mesh batches

* Added draw group management to InstancedMeshBatch. It works in the same manner as for non instanced batches, but the offset value refers to instances not triangles. I believe it could be simplified, but I'd like to get it up and working first

* Draw groups need to hold the index and count from the instanced buffer attribute

* Added array shuffling to the instanced mesh batch using the same approach we used for the non instanced one.

* Instanced batches now dynamically add InstancedMesh objects based on draw groups and a computed transform buffer

* Applying draw range updates for instanced batches now works. Still some issues to handle. It aint much, but it's honest work

* Disabled some more RTE until setting visibility for draw ranges is finished

* Moved getting opaque, transparent and stencil draw ranges out from Batcher and on to a per-batch basis. Now instanced batches correctly apply draw ranges and get their opaque, transparent and stecil ranges

* Fixed an issue with setting the visibility ranges for instanced mesh batches

* Instanced attributes for instanced meshes now no longer allocate

* Shadow depth material for instances is now set in the speckle renderer

* R-enabled RTE globally. Made instancing work with RTE. Made instancing work with both RTE and shadowmapping.

* Fixed an issue with materials building up in the mesh batch's cache incorrectly

* Implemented gradient indexs attributes for instanced batches. Thismeans, any color ramp based material like the ones we use for filtering now works

* Changed the way compound ids are created for instances, so that less memory is required. i.e chrome is not crashing anymore on particular streams

* Implemented reseting the draw ranges for instanced mesh batches. We no longer double buffer the gradient index buffer. We just create a new one when shuffling, populate it, then copy it over at the end. We're still double buffering the transforms buffer since that one is larger and we might not want to allocate it each time we shuffle

* Removed references of draw groups with ids since we're not doing that anymore. Fixed an issue with mesh batches where the material cache would keep piling materials incorrectly

* Several issues with selective transformations on instanced batches fixed.

* Added default null materials for instanced meshes both with and without vertex colors

* Got rid of the patched InstancedMesh because it was ridiculously slow. Instead we're now computing the scene box using our acceleration structures where available and three.s boundingbox where not available

* Minor, yet big regression fix

* Fixed regression

* Exported some extra types

* WIP on instanced balancing

* Instanced objects under a certain threshold now get batched together as regular mesh batches

* Forgot to update the rvs aabb

* Unified instanced and non instanced batch creation. Instances which do not qualify for instanced batching anre now mixed together with the rest of the non instanced batched objects

* Added some timing information to instanced batches

* Fixed an issue with zooming in on objects not working in the selection extension. Fixed an issue with object picking failing due to fp precision for objects right at the edge of the clipping volume.

* Removed logs

* Update stream moving via UI

* Removed the priority argument from loadObject since it's not needed anymore

* Updated LegacyViewer

* Fixed an issue with API 2.0 where the legacy form of transforms with only an array of values as the matrix would not work

* Updated FE1 viewer package to latest before API 2.0

* Disabled selection when measurement mode is on

* Updated ibl params updating

* Fixed an issue with measurement text not showing up

* Logs

* lockfile

* Made DataTree obsolete. Removed unused 'input' property from viewer

* Fixed circular dependencies

* Removed DebugViewer, other small changes

* Small changes

* Small fixes

* Added id to NodeData

* Removed unused bounds property in rendertree

* Notes to future self + ExtendedExtension is now exported

* Removed an unused function from renderer. Removed the parent argumetn from getRenderViewerForNode... since it was legacy and has no meaning anymore.

* Removed the instance type check in getRenderViewesForNode method. Should not be needed anymore and it was bad to begin with anyway

* Removed some test code

* Small changes

* Removed pointless bounds calculation. Added note

* Added return types

* Ingestigating large group operations

* Nested nodes from TreeNode are now optional. Small update to node render view.

* #1818 Remove the concept of speckle data existing behind a 'data' field

* Removed unneeded property

* made arguments options in transformTRS

* getBoundingBox from acceleration structures have an optional argument now

* Several Batch methods no longer take variable numbe of arguments, but arrays now

* Added note

* Note

* Removed unused things

* Note and made the raycaster protected in intersections

* Added some typings

* Replaceds some functions with accessors. Added typings. Renamed stuff

* Removed some unused properties.

* Typings for measurements

* Small typing changes

* Fixed some more compile errors

* Sources from 'batching' folder are now strict compile compliant

* Sources from 'materials' folder are now strict compile compliant

* Sources from 'extensions' folder are now strict compile compliant

* Sources from 'tree' folder are now strict compile compliant

* Viewer interface, implementation, legacy implementation and the exports now comply with the strict compilation flag. Also added the new tsconfig

* Sources from 'objects' folder now comply to the strict compilation rules

* Sources from 'pipeline' now satisfy the requirements for strict compilation

* Sources from 'loaders' folder are now compiling with strict. That was so much fun

* Sources from 'query' folder are now compiling with strict

* Another round of correction triggered by previous changes

* Update the declaration file in the object loader to contain a member that needs to be public

* SpeckleRenderer along with the rest of the surces from the root 'modules' folder are not compiled with strict

* Completely deprecated DataTree. Updated the dependencies with @types/underscore. Fixed remaining compilation issues

* Fixed a failing build on the CI regarding a timeout id

* Fixed compile errors from sandbox

* Another fix

* All EventEmiter child classes now have mapped event handler argument types, so that when attaching to a specific event, the provided handler has the correct types for it's arguments. Implicitly, got rid of the the unknown types in all event handlers.

* Disabled verbatimModuleSyntax because it was messing things up. Fixed an issue with an improper import

* Fixed frontend-2 linting errors. Also added all the event payload maps to the viewer export

* Some good additions but mostly typescript catering

* Some more typescript catering, but also something useful. The intersect function is now overloaded so that when you specify only the ObjectLayers.STREAM_CONTENT_MESH object layer in it's layers argument it will always return a ExtendedMeshIntersection which guarantees to have a batchObject, face and it's object is of type SpeckleMesh | SpeckleInstancedMesh. Generally you mostly raycast against meshes and getting a three.js intersection object which has all it's fileds optional led to some very useless defined checks. With this we can avoid all of them

* Continued from yesterday, finished with the changes in intersections. Added MeshIntersection which is returned by all bvh intersections. This eliminates the need to check for face, faceIndex or index on intersection results from intersection meshes. Groups from MeshBatch and InstancedMeshBatch are now always DrawRanges(they always were)

* Mostly catering to typescript

* Removed underscore and all unused dependancies. Fixed remaining lint and build errors

* Minor changes

* Added the no-non-null assertion rule to the sandbox

* getExtension never returns null, but rather throws an exception if requested extension does not exist. Added hasExtension for (theoretical) situations where you want to check for extension existence but don't want to go by try/catch with getExtension. Fixed remaining lint/build errors

* getBatches now returns explicit batch types based on the geometry type that you provide

* Adding the lockfile

* undoing unnecessary FE2 changes

* Merged viewer/fe SpeckleObject types

* Fixed two small issues

* Minor linting issues

---------

Co-authored-by: Kristaps Fabians Geikins <fabians@speckle.systems>
  • Loading branch information
AlexandruPopovici and fabis94 authored May 7, 2024
1 parent 3c91af0 commit ec78d31
Show file tree
Hide file tree
Showing 109 changed files with 3,405 additions and 2,526 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ const { hideObjects, showObjects, isolateObjects, unIsolateObjects } =
const isAtomic = computed(() => props.treeItem.atomic === true)
const speckleData = props.treeItem?.raw as SpeckleObject
const rawSpeckleData = props.treeItem?.raw as Record<string, unknown>
const rawSpeckleData = props.treeItem?.raw as SpeckleObject
const headerAndSubheader = computed(() => {
return getHeaderAndSubheaderForSpeckleObject(rawSpeckleData)
Expand Down
2 changes: 1 addition & 1 deletion packages/frontend-2/components/viewer/selection/Object.vue
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@
class="pl-2"
>
<ViewerSelectionObject
:object="(kvp.value as Record<string,unknown>) || {}"
:object="(kvp.value as SpeckleObject) || {}"
:title="(kvp.key as string)"
:unfold="false"
/>
Expand Down
4 changes: 2 additions & 2 deletions packages/frontend-2/components/viewer/settings/Menu.vue
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ const localViewerSettings = useSynchronizedCookie<ViewerUserSettings>(
const { instance } = useInjectedViewer()
const setViewerCameraHandlerControlsMaxPolarAngle = (angle: number) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
instance.getExtension(CameraController).controls.maxPolarAngle = angle
const extension = instance.getExtension(CameraController)
if (extension) extension.controls.maxPolarAngle = angle
}
const toggleTurntableMode = () => {
Expand Down
15 changes: 3 additions & 12 deletions packages/frontend-2/lib/common/helpers/sceneExplorer.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { type SpeckleObject, type SpeckleReference } from '@speckle/viewer'

// Note: minor typing hacks for less squiggly lines in the explorer.
// TODO: ask alex re viewer data tree types

Expand All @@ -10,15 +12,4 @@ export type ExplorerNode = {
children: ExplorerNode[]
}

export type SpeckleReference = {
referencedId: string
}

export interface SpeckleObject {
id?: string
elements?: SpeckleReference[]
children?: SpeckleObject[] | SpeckleReference[]
name?: string
speckle_type?: string
[key: string]: unknown
}
export type { SpeckleObject, SpeckleReference }
Original file line number Diff line number Diff line change
Expand Up @@ -306,13 +306,14 @@ function useViewerCameraIntegration() {

const loadCameraDataFromViewer = () => {
const controls = instance.getExtension(CameraController).controls
let cameraManuallyChanged = false

const viewerPos = new Vector3()
const viewerTarget = new Vector3()

controls.getPosition(viewerPos)
controls.getTarget(viewerTarget)

let cameraManuallyChanged = false
if (!areVectorsLooselyEqual(position.value, viewerPos)) {
if (hasInitialLoadFired.value) position.value = viewerPos.clone()
cameraManuallyChanged = true
Expand Down
6 changes: 3 additions & 3 deletions packages/frontend-2/lib/viewer/composables/ui.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { SpeckleViewer, timeoutAt, type Optional } from '@speckle/shared'
import { SpeckleViewer, timeoutAt } from '@speckle/shared'
import type { TreeNode } from '@speckle/viewer'
import { CameraController, MeasurementsExtension } from '@speckle/viewer'
import type { MeasurementOptions, PropertyInfo } from '@speckle/viewer'
Expand Down Expand Up @@ -64,14 +64,14 @@ export function useCameraUtilities() {
instance.setView(...args)
}

let cameraController: Optional<CameraController> = undefined
let cameraController: CameraController | null = null
const truck = (
...args: Parameters<NonNullable<typeof cameraController>['controls']['truck']>
) => {
if (!cameraController) {
cameraController = instance.getExtension(CameraController)
}
cameraController.controls.truck(...args)
cameraController?.controls.truck(...args)
}

const zoomExtentsOrSelection = () => {
Expand Down
12 changes: 6 additions & 6 deletions packages/frontend-2/lib/viewer/composables/viewer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { TimeoutError, timeoutAt } from '@speckle/shared'
import type { MaybeAsync, Nullable } from '@speckle/shared'
import { Vector3 } from 'three'
import { areVectorsLooselyEqual } from '~~/lib/viewer/helpers/three'
import { CameraController } from '@speckle/viewer'
import { CameraController, type ViewerEventPayload } from '@speckle/viewer'
import type { TreeNode } from '@speckle/viewer'
import type { SpeckleObject } from '~~/lib/common/helpers/sceneExplorer'

Expand Down Expand Up @@ -78,9 +78,9 @@ function getFirstVisibleSelectionHit(
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useViewerEventListener<A = any>(
name: ViewerEvent | ViewerEvent[],
listener: (...args: A[]) => MaybeAsync<void>,
export function useViewerEventListener<K extends ViewerEvent>(
name: K | K[],
listener: (args: ViewerEventPayload[K]) => MaybeAsync<void>,
options?: Partial<{
state: InitialStateWithRequestAndResponse
}>
Expand Down Expand Up @@ -135,7 +135,8 @@ export function useViewerCameraTracker(
}

// Only invoke callback if position/target changed in a meaningful way
const controls = instance.getExtension(CameraController).controls
const extension = instance.getExtension(CameraController)
const controls = extension.controls
const viewerPos = new Vector3()
const viewerTarget = new Vector3()

Expand Down Expand Up @@ -165,7 +166,6 @@ export function useViewerCameraTracker(

onMounted(() => {
const extension = instance.getExtension(CameraController)

extension.controls.addEventListener('update', finalCallback)
})

Expand Down
2 changes: 1 addition & 1 deletion packages/objectloader/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,6 @@ export default class ObjectLoader {
): SpeckleObject | SpeckleObject[]

async *getObjectIterator(): Generator<SpeckleObject, SpeckleObject>

async getObject(id: string): Promise<Record<string, unknown>>
dispose(): void
}
3 changes: 3 additions & 0 deletions packages/viewer-sandbox/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ const config = {
parserOptions: {
sourceType: 'module'
},
rules: {
'@typescript-eslint/no-non-null-assertion': 'error'
},
overrides: [
{
files: '*.ts',
Expand Down
25 changes: 10 additions & 15 deletions packages/viewer-sandbox/src/Extensions/BoxSelection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,7 @@ import { ObjectLayers } from '@speckle/viewer'
import { NodeRenderView } from '@speckle/viewer'
import { SelectionExtension } from '@speckle/viewer'
import { BatchObject } from '@speckle/viewer'
import {
Extension,
IViewer,
GeometryType,
MeshBatch,
CameraController
} from '@speckle/viewer'
import { Extension, IViewer, GeometryType, CameraController } from '@speckle/viewer'
import {
Matrix4,
ShaderMaterial,
Expand Down Expand Up @@ -113,17 +107,18 @@ export class BoxSelection extends Extension {

/** Gets the object ids that fall withing the provided selection box */
private getSelectionIds(selectionBox: Box3) {
/** Get the renderer */
const renderer = this.viewer.getRenderer()
/** Get the mesh batches */
const batches = this.viewer
.getRenderer()
.batcher.getBatches(undefined, GeometryType.MESH) as MeshBatch[]

const batches = renderer.batcher.getBatches(undefined, GeometryType.MESH)
/** Compute the clip matrix */
const clipMatrix = new Matrix4()
clipMatrix.multiplyMatrices(
this.viewer.getRenderer().renderingCamera.projectionMatrix,
this.viewer.getRenderer().renderingCamera.matrixWorldInverse
)
if (renderer.renderingCamera) {
clipMatrix.multiplyMatrices(
renderer.renderingCamera.projectionMatrix,
renderer.renderingCamera.matrixWorldInverse
)
}

/** We're using three-mesh-bvh library for out BVH
* Go over each batch and test it against the TAS only.
Expand Down
16 changes: 9 additions & 7 deletions packages/viewer-sandbox/src/Extensions/CameraPlanes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import {
Extension,
GeometryType,
IViewer,
MeshBatch,
Vector3
} from '@speckle/viewer'
import { PerspectiveCamera } from 'three'
Expand All @@ -20,17 +19,18 @@ export class CameraPlanes extends Extension {

public constructor(viewer: IViewer) {
super(viewer)
this.camerController = viewer.getExtension(
CameraController as new () => CameraController
)
this.camerController = viewer.getExtension(CameraController) as CameraController
}

public onEarlyUpdate(): void {
this.computePerspectiveCameraPlanes()
}

public computePerspectiveCameraPlanes() {
const camera = this.viewer.getRenderer().renderingCamera as PerspectiveCamera
const renderer = this.viewer.getRenderer()
if (!renderer.renderingCamera) return

const camera = renderer.renderingCamera as PerspectiveCamera
const minDist = this.getClosestGeometryDistance(camera)
if (minDist === Number.POSITIVE_INFINITY) return

Expand All @@ -42,7 +42,7 @@ export class CameraPlanes extends Extension {
1 +
Math.pow(Math.tan(((fov / 180) * Math.PI) / 2), 2) * (Math.pow(aspect, 2) + 1)
)
this.viewer.getRenderer().renderingCamera.near = nearPlane
renderer.renderingCamera.near = nearPlane
console.log(minDist, nearPlane)
}

Expand All @@ -55,11 +55,13 @@ export class CameraPlanes extends Extension {

const batches = this.viewer
.getRenderer()
.batcher.getBatches(undefined, GeometryType.MESH) as MeshBatch[]
.batcher.getBatches(undefined, GeometryType.MESH)
let minDist = Number.POSITIVE_INFINITY
const minPoint = new Vector3()
for (let b = 0; b < batches.length; b++) {
const result = batches[b].mesh.TAS.closestPointToPoint(cameraPosition)
if (!result) continue

const planarity = cameraDir.dot(
new Vector3().subVectors(result.point, cameraPosition).normalize()
)
Expand Down
8 changes: 6 additions & 2 deletions packages/viewer-sandbox/src/Extensions/ExtendedSelection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,14 @@ export class ExtendedSelection extends SelectionExtension {
}

private initGizmo() {
const rendeder = this.viewer.getRenderer()
if (!rendeder.renderingCamera)
throw new Error('Cannot use ExtendedSelection without a rendering camera')

/** Create a new TransformControls gizmo */
this.transformControls = new TransformControls(
this.viewer.getRenderer().renderingCamera,
this.viewer.getRenderer().renderer.domElement
rendeder.renderingCamera,
rendeder.renderer.domElement
)
/** The gizmo creates an entire hierarchy of children internally,
* and three.js objects do not inherit parent layer values, so
Expand Down
Loading

0 comments on commit ec78d31

Please sign in to comment.