Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add position to state.size #1

Closed
wants to merge 9 commits into from
2 changes: 1 addition & 1 deletion docs/getting-started/installation.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ npm install three @react-three/fiber

> Fiber is compatible with React v18.0.0+ and works with ReactDOM and React Native.

Getting started with React Three Fiber is not nearly has hard as you might have thought, but various frameworks may require particular attention.
Getting started with React Three Fiber is not nearly as hard as you might have thought, but various frameworks may require particular attention.

We've put together guides for getting started with each popular framework:

Expand Down
6 changes: 6 additions & 0 deletions packages/fiber/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# @react-three/fiber

## 8.0.27

### Patch Changes

- 7940995: fix: resume on xrsession end, export internal events

## 8.0.26

### Patch Changes
Expand Down
2 changes: 1 addition & 1 deletion packages/fiber/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@react-three/fiber",
"version": "8.0.26",
"version": "8.0.27",
"description": "A React renderer for Threejs",
"keywords": [
"react",
Expand Down
28 changes: 19 additions & 9 deletions packages/fiber/src/core/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -215,12 +215,11 @@ function createRoot<TCanvas extends Element>(canvas: TCanvas): ReconcilerRoot<TC

// Toggle render switching on session
const handleSessionChange = () => {
const gl = store.getState().gl
gl.xr.enabled = gl.xr.isPresenting
// @ts-ignore
// WebXRManager's signature is incorrect.
// See: https://github.com/pmndrs/react-three-fiber/pull/2017#discussion_r790134505
gl.xr.setAnimationLoop(gl.xr.isPresenting ? handleXRFrame : null)
const state = store.getState()
state.gl.xr.enabled = state.gl.xr.isPresenting

state.gl.xr.setAnimationLoop(state.gl.xr.isPresenting ? handleXRFrame : null)
if (!state.gl.xr.isPresenting) invalidate(state)
}

// WebXR session manager
Expand Down Expand Up @@ -277,8 +276,19 @@ function createRoot<TCanvas extends Element>(canvas: TCanvas): ReconcilerRoot<TC
// Check pixelratio
if (dpr && state.viewport.dpr !== calculateDpr(dpr)) state.setDpr(dpr)
// Check size, allow it to take on container bounds initially
size = size || { width: canvas.parentElement?.clientWidth ?? 0, height: canvas.parentElement?.clientHeight ?? 0 }
if (!is.equ(size, state.size, shallowLoose)) state.setSize(size.width, size.height, size.updateStyle)
size =
size ||
(canvas.parentElement
? {
width: canvas.parentElement.clientWidth,
height: canvas.parentElement.clientHeight,
top: canvas.parentElement.clientTop,
left: canvas.parentElement.clientLeft,
}
: { width: 0, height: 0, top: 0, left: 0 })
if (!is.equ(size, state.size, shallowLoose)) {
state.setSize(size.width, size.height, size.updateStyle, size.top, size.left)
}
// Check frameloop
if (state.frameloop !== frameloop) state.setFrameloop(frameloop)
// Check pointer missed
Expand Down Expand Up @@ -382,7 +392,7 @@ export type InjectState = Partial<
compute?: ComputeFunction
connected?: any
}
size?: { width: number; height: number }
size?: Size
}
>

Expand Down
31 changes: 20 additions & 11 deletions packages/fiber/src/core/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import create, { GetState, SetState, StoreApi, UseBoundStore } from 'zustand'
import { prepare } from './renderer'
import { DomEvent, EventManager, PointerCaptureTarget, ThreeEvent } from './events'
import { calculateDpr, Camera, isOrthographicCamera, updateCamera } from './utils'
import { RectReadOnly } from 'react-use-measure'

// Keys that shouldn't be copied between R3F stores
export const privateKeys = [
Expand Down Expand Up @@ -32,7 +33,7 @@ export type Subscription = {
}

export type Dpr = number | [min: number, max: number]
export type Size = { width: number; height: number; updateStyle?: boolean }
export type Size = { width: number; height: number; top: number; left: number; updateStyle?: boolean }
export type Viewport = Size & {
/** The initial pixel ratio */
initialDpr: number
Expand Down Expand Up @@ -133,8 +134,12 @@ export type RootState = {
advance: (timestamp: number, runGlobalEffects?: boolean) => void
/** Shortcut to setting the event layer */
setEvents: (events: Partial<EventManager<any>>) => void
/** Shortcut to manual sizing */
setSize: (width: number, height: number, updateStyle?: boolean) => void
/**
* Shortcut to manual sizing
*
* @todo before releasing next major version (v9), re-order arguments here to width, height, top, left, updateStyle
*/
setSize: (width: number, height: number, updateStyle?: boolean, top?: number, left?: number) => void
/** Shortcut to manual setting the pixel ratio */
setDpr: (dpr: Dpr) => void
/** Shortcut to frameloop flags */
Expand All @@ -161,19 +166,19 @@ const createStore = (
camera: Camera = get().camera,
target: THREE.Vector3 | Parameters<THREE.Vector3['set']> = defaultTarget,
size: Size = get().size,
) {
const { width, height } = size
): Omit<Viewport, 'dpr' | 'initialDpr'> {
const { width, height, top, left } = size
const aspect = width / height
if (target instanceof THREE.Vector3) tempTarget.copy(target)
else tempTarget.set(...target)
const distance = camera.getWorldPosition(position).distanceTo(tempTarget)
if (isOrthographicCamera(camera)) {
return { width: width / camera.zoom, height: height / camera.zoom, factor: 1, distance, aspect }
return { width: width / camera.zoom, height: height / camera.zoom, top, left, factor: 1, distance, aspect }
} else {
const fov = (camera.fov * Math.PI) / 180 // convert vertical fov to radians
const h = 2 * Math.tan(fov / 2) * distance // visible height
const w = h * (width / height)
return { width: w, height: h, factor: width / w, distance, aspect }
return { width: w, height: h, top, left, factor: width / w, distance, aspect }
}
}

Expand All @@ -183,7 +188,7 @@ const createStore = (

const pointer = new THREE.Vector2()

return {
const rootState: RootState = {
set,
get,

Expand Down Expand Up @@ -229,12 +234,14 @@ const createStore = (
},
},

size: { width: 0, height: 0, updateStyle: false },
size: { width: 0, height: 0, top: 0, left: 0, updateStyle: false },
viewport: {
initialDpr: 0,
dpr: 0,
width: 0,
height: 0,
top: 0,
left: 0,
aspect: 0,
distance: 0,
factor: 0,
Expand All @@ -243,9 +250,9 @@ const createStore = (

setEvents: (events: Partial<EventManager<any>>) =>
set((state) => ({ ...state, events: { ...state.events, ...events } })),
setSize: (width: number, height: number, updateStyle?: boolean) => {
setSize: (width: number, height: number, updateStyle?: boolean, top?: number, left?: number) => {
const camera = get().camera
const size = { width, height, updateStyle }
const size = { width, height, top: top || 0, left: left || 0, updateStyle }
set((state) => ({ size, viewport: { ...state.viewport, ...getCurrentViewport(camera, defaultTarget, size) } }))
},
setDpr: (dpr: Dpr) =>
Expand Down Expand Up @@ -308,6 +315,8 @@ const createStore = (
},
},
}

return rootState
})

const state = rootState.getState()
Expand Down
1 change: 1 addition & 0 deletions packages/fiber/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,6 @@ export type {
export type { ThreeEvent, Events, EventManager, ComputeFunction } from './core/events'
export type { ObjectMap, Camera } from './core/utils'
export * from './web/Canvas'
export { createEvents } from './core/events'
export { createPointerEvents as events } from './web/events'
export * from './core'
10 changes: 5 additions & 5 deletions packages/fiber/src/native/Canvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { ExpoWebGLRenderingContext, GLView } from 'expo-gl'
import { SetBlock, Block, ErrorBoundary, useMutableCallback } from '../core/utils'
import { extend, createRoot, unmountComponentAtNode, RenderProps, ReconcilerRoot } from '../core'
import { createTouchEvents } from './events'
import { RootState } from '../core/store'
import { RootState, Size } from '../core/store'
import { polyfills } from './polyfills'

export interface Props extends Omit<RenderProps<HTMLCanvasElement>, 'size' | 'dpr'>, ViewProps {
Expand Down Expand Up @@ -44,7 +44,7 @@ export const Canvas = /*#__PURE__*/ React.forwardRef<View, Props>(
// their own elements by using the createRoot API instead
React.useMemo(() => extend(THREE), [])

const [{ width, height }, setSize] = React.useState({ width: 0, height: 0 })
const [{ width, height, top, left }, setSize] = React.useState<Size>({ width: 0, height: 0, top: 0, left: 0 })
const [canvas, setCanvas] = React.useState<HTMLCanvasElement | null>(null)
const [bind, setBind] = React.useState<any>()
React.useImperativeHandle(forwardedRef, () => viewRef.current)
Expand All @@ -65,8 +65,8 @@ export const Canvas = /*#__PURE__*/ React.forwardRef<View, Props>(
React.useLayoutEffect(() => polyfills(), [])

const onLayout = React.useCallback((e: LayoutChangeEvent) => {
const { width, height } = e.nativeEvent.layout
setSize({ width, height })
const { width, height, x, y } = e.nativeEvent.layout
setSize({ width, height, top: y, left: x })
}, [])

// Called on context create or swap
Expand Down Expand Up @@ -102,7 +102,7 @@ export const Canvas = /*#__PURE__*/ React.forwardRef<View, Props>(
// expo-gl can only render at native dpr/resolution
// https://github.com/expo/expo-three/issues/39
dpr: PixelRatio.get(),
size: { width, height },
size: { width, height, top, left },
// Pass mutable reference to onPointerMissed so it's free to update
onPointerMissed: (...args) => handlePointerMissed.current?.(...args),
// Overwrite onCreated to apply RN bindings
Expand Down
6 changes: 3 additions & 3 deletions packages/fiber/src/web/Canvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export const Canvas = /*#__PURE__*/ React.forwardRef<HTMLCanvasElement, Props>(f
// their own elements by using the createRoot API instead
React.useMemo(() => extend(THREE), [])

const [containerRef, { width, height }] = useMeasure({ scroll: true, debounce: { scroll: 50, resize: 0 }, ...resize })
const [containerRef, containerRect] = useMeasure({ scroll: true, debounce: { scroll: 50, resize: 0 }, ...resize })
const canvasRef = React.useRef<HTMLCanvasElement>(null!)
const divRef = React.useRef<HTMLDivElement>(null!)
const [canvas, setCanvas] = React.useState<HTMLCanvasElement | null>(null)
Expand All @@ -67,7 +67,7 @@ export const Canvas = /*#__PURE__*/ React.forwardRef<HTMLCanvasElement, Props>(f

const root = React.useRef<ReconcilerRoot<HTMLElement>>(null!)

if (width > 0 && height > 0 && canvas) {
if (containerRect.width > 0 && containerRect.height > 0 && canvas) {
if (!root.current) root.current = createRoot<HTMLElement>(canvas)
root.current.configure({
gl,
Expand All @@ -82,7 +82,7 @@ export const Canvas = /*#__PURE__*/ React.forwardRef<HTMLCanvasElement, Props>(f
performance,
raycaster,
camera,
size: { width, height },
size: containerRect,
// Pass mutable reference to onPointerMissed so it's free to update
onPointerMissed: (...args) => handlePointerMissed.current?.(...args),
onCreated: (state) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/fiber/tests/core/hooks.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ describe('hooks', () => {
expect(result.camera instanceof THREE.Camera).toBeTruthy()
expect(result.scene instanceof THREE.Scene).toBeTruthy()
expect(result.raycaster instanceof THREE.Raycaster).toBeTruthy()
expect(result.size).toEqual({ height: 0, width: 0, updateStyle: false })
expect(result.size).toEqual({ height: 0, width: 0, top: 0, left: 0, updateStyle: false })
})

it('can handle useFrame hook', async () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/test-renderer/src/__tests__/RTTR.hooks.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ describe('ReactThreeTestRenderer Hooks', () => {
expect(result.camera instanceof THREE.Camera).toBeTruthy()
expect(result.scene instanceof THREE.Scene).toBeTruthy()
expect(result.raycaster instanceof THREE.Raycaster).toBeTruthy()
expect(result.size).toEqual({ height: 0, width: 0, updateStyle: false })
expect(result.size).toEqual({ height: 0, width: 0, top: 0, left: 0, updateStyle: false })
})

it('can handle useLoader hook', async () => {
Expand Down