Skip to content

Commit

Permalink
V8, react 18 beta (#1630)
Browse files Browse the repository at this point in the history
* react 18 alpha

* up use-asset

* fix flat

* silence disposal errors

* support instanced event cancelation

* simplify useFrame

* Allow partial WebGLRenderer params (#1656)

Without the `Partial` the `gl` props is practically unusable as it requires all the params to be present in the prop.

* is.test: 'is equal' test to use alredy declared obj and array. (#1643)

* refactor into utility functions

* refactor

* bring over diffprops bug

* Merge branch 'master' into v8

* chore: move dpr calc to utils

* chore: don't use `is` outside of renderer

* fix(core): set null parent in prepare

* fix args in createinstance

* fix primitve leftovers on switch, add gltf example

* chore(web): fix mangled import

* make applyprops return the instance

* fix merge

* spread props over container div, change dpr default, fix createRoot

* export createroot

* fix cherrypick

* [v8] feat: add react-native support (#1699)

* chore: add native target from: #1384

Co-authored by @swittk.

* fix: set initial render size

* refactor: cleanup render API, remove shim

* chore: cleanup canvas, TS

* chore: map events

TODO: bind them

* refactor: move expo to Canvas, allow custom renderers

* chore: add RN types

* refactor: accept constructor args in canvas

* chore: bind events

* chore: synchronously get handlers from target

* chore: remove dependency on expo-three

* chore: cleanup Canvas TS

* chore: create native entrypoint

* chore: cleanup context init

* refactor: accept context over canvas

* fix: passthrough gl props

* chore: remove entrypoint

This is created automatically but we'll have to update the CI to skip it.

* chore: update canvas props TS

* chore: fix native exports

* chore: hide __mocks__ from npm output

* chore: add TS to native entrypoint

* chore: cleanup context TS

* chore: update native recipe

* chore: add back in bootstrap tip for native

TODO: update https://github.com/expo/examples/tree/master/with-react-three-fiber

* chore: mirror dpr/size fix from #1707

* feat: add v5 native props

* chore: add expo-gl as a dependency

* chore: don't use `is` outside of renderer

* feat(native): export native useLoader

* fix(native/hooks): respect module paths, fix constructor compar

* chore(native): streamline loader TS, mirror GLProps from web

* chore(native): defer to RenderProps for GL

* docs: remove expo-gl dep, use same API

* chore: delete RN key in package

* chore: bump native deps

* chore(native): pin dpr to screen dpr

* fix(native): set color management defaults

* Merge branch 'v8' into native

* chore(Canvas): accept native props

* chore(native): export createRoot

* fix(Canvas): pass onCreated

* [v8] feat: remove vr prop for dynamic render switching (#1702)

* fix(Canvas): pass events & size

* feat: add `renderVisible` prop to only render while in view

* remove zustand sub selector

* feat(core): make `frameloop` reactive

* chore: `renderVisible` => `include`

* chore: add demo for IncludeProp

* docs: add `intersect` prop and internal `setFrameloop`

* chore: cleanup example with styled-components

* chore: revert `intersect` for native

* chore: fix peer dep range for native

* [v8] refactor(core): use-asset => suspend-react (#1797)

* refactor(core): use-asset => suspend-react

* fix(native/hooks): use correct import

* fix(core): fix shallow equality in useLoader

* chore(hooks): fix TS

* fix: use correct keys syntax

* chore: remove `intersect` prop from web & docs, example

* chore: add react-native key for lib interop

* update deps

* update version

* chore: fix native peer dep

* chore: update references from github namespace react-spring to pmndrs

* fix: tree-shaking

* fix: revert removing mergerefs, use pure annotations instead

* align both canvases

* update usemeasure

* Fix missing type for Float32BufferAttribute (#1862)

Missing Float32BufferAttriute type causes Typescript error "Property 'float32BufferAttribute' does not exist on type 'JSX.IntrinsicElements'.ts(2339)"

Example of use of float32BufferAttribute
```jsx
<instancedBufferGeometry attach="geometry" instanceCount={count}>
        <float32BufferAttribute
          attachObject={['attributes', 'position']}
          args={[positionArray, 3]}
        />
        <instancedBufferAttribute
          attachObject={['attributes', 'offset']}
          args={[offsetArray, 3]}
        />
      </instancedBufferGeometry>
```

* fix(Canvas): unmount current context

* [v8] fix: use new act API & fix extend for tests (#1891)

* feat(test-renderer): add RegExp matcher support to `findByProps` and `findAllByProps` (#1890)

* chore: apply fix to applyProps

* fix: schedule child.dispose() (#1887)

* chore: fix eslint

* add camera:manual

* remove console log

* move up to react rc

* update examples to react-router 6

* fix three types

* unify attach

* fix suspense re-attach

* chore: update tests

* fix(types): use new attach API

* switch to createRoot

* chore: update test-renderer snapshot

* publish new beta

* fix(RTTR): use createRoot

* chore(tests): use createRoot

* fix(web): render when canvas is created

* refactor: move createRoot to core (#1915)

* chore(native): add expo unimodules as dep (#1916)

* clean up example

* up version

* chore(tests): add native coverage, sort tests (#1917)

* fix(native): revert to Pressability (#1923)

* fix(native): use relative coords for events

* fix(core): safely allocate `now` (#1959)

* chore: update new tests to v8 API

* fix(native): use expo modules (#1927)

* chore: update docs for v8 (#1976)

* experiment: unify hooks (#1994)

* fix(native): unpin and correctly mark peer deps (#2004)

* fix(native): unpin and correctly mark peer deps

* chore: add expo-asset as dev dep

* feat(core): pass XRFrame to subscribers (#2017)

* fix(native): move expo-gl to peer dep, update react-native instructions/example (#2033)

* up package

* fix: remove unused resize-observer-polyfill dep (#2044)

* chore(native): export instance types

* docs(changeset): new beta for library testing

* RELEASING: Releasing 2 package(s)

Releases:
  @react-three/[email protected]
  @react-three/[email protected]

[skip ci]

* v8.0.0-beta.5

* root.configure()

* fix(configure): only configure shadowmap if present

* fix(native): prefer to resolve external assets

* cleanup refactor, extend is.equ

* perf adjustments to the renderloop

* release new beta

* fix(types): add Object3D to IntrinsicElements (#2099)

* fix(types): add more bufferAttribute intrinsic elements (#2102)

* rc1

* rc

* fix test

* fix(types): move @types/react-reconciler to dependencies (#2126)

* introduce the inject native element, which creates a layered host context

* new beta

* remove host context, make one up with portals

* inject example

* use userdata instead of __context

* chore: update instance snapshots for new args handling

* inject cleanup

* example: update `MultiMaterial` example (#2144)

* fix(attach): add back `attachArray`

* chore: revert code and update example

* chore: revert code

Co-authored-by: Cody Bennett <[email protected]>

* fix: is.equ and attach arrays

* remove arrayed attach, prefer function with cleanup

* fix: events were broken due to is.equ

* enforce attach fn cleanup

* refactor portal context

* add inject layer for portals, expose it, too

* completely revamp portals

* cleanup

* refactor(core): create an array when indexing with attach (#2145)

* refactor(core): create an array when indexing with attach

* chore: cleanup attach exp

* make 139 peer, remove color correction

* update snapshots

* fix(Canvas): memoize `onPointerMissed` (#2146)

* chore: changes to examples & local linking (#2151)

* chore: changes to examples & local linking

* .

* .

* .

* minor changes

* minor changes

* removes bright backgrounds

* .

* removes unused stuff

* removes unused stuff

* .

* .

* .

* .

* .

* .

* .

* .

* work on viewcube

* fix colors

* chore: fixes vite config (#2152)

* fix types

* portal inject layers

* constrain inject state to a subset, auto increase priority

* demo cleanup

* new compute api

* multi view demo (using skissor)

* fix clearcolor

* connect events to the canvas parent instead of the canvas itself

* cleanup

* instead of hijacking the store, make up a new one in createportal

* new beta

* chore(demos): cleanup render effects

Nits from #2153

* chore(tests): de-escalate react-dom/client warnings

* fix: tests, add parent property

* fix: native canvas registers its parent

* chore(tests): fix react-dom silence

* chore(tests): remove react-dom/client workaround

* chore(tests): move console mock to setuptests

* chore(tests): UseStore => UseBoundStore

* fix: remove parent

* fix: black list for inject layer props

* chore(docs): update createRoot signature

* chore(docs): add notes on webxr useframe signature

* chore(docs): streamline render methods (#2162)

* feat(core): default `physicallyCorrectLights` to true (#2148)

* feat(core): default `physicallyCorrectLights` to true

* chore: streamline gl defaults

* chore(docs): note new gl defaults

* chore(tests): flip gl prop case, respect lighting preferences

* mm as the default example

* chore: revert physicallyCorrectLights

* deprecate mouse, setevents, more inline docs

* forgot partial

* update all dependencies

* clean up demos

* add missing migration parts

* add missing migration parts

* fix: applyProps was supposed to return the instance

* migration

* last beta

* migration example

Co-authored-by: Dušan Maliarik <[email protected]>
Co-authored-by: Anderson Leite <[email protected]>
Co-authored-by: Cody Bennett <[email protected]>
Co-authored-by: Cody Bennett <[email protected]>
Co-authored-by: dangrabcad <[email protected]>
Co-authored-by: davidblnc <[email protected]>
Co-authored-by: Karol Stopyra <[email protected]>
Co-authored-by: Egor Blinov <[email protected]>
Co-authored-by: Alexander Nanberg <[email protected]>
Co-authored-by: Josh <[email protected]>
Co-authored-by: Nathan Bierema <[email protected]>
Co-authored-by: susiwen8 <[email protected]>
Co-authored-by: Gianmarco <[email protected]>
  • Loading branch information
14 people authored Mar 30, 2022
1 parent 836d847 commit 347ea79
Show file tree
Hide file tree
Showing 99 changed files with 15,091 additions and 8,991 deletions.
9 changes: 9 additions & 0 deletions .changeset/pre.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"mode": "pre",
"tag": "beta",
"initialVersions": {
"@react-three/fiber": "8.0.0-beta-05",
"@react-three/test-renderer": "8.0.0-beta-00"
},
"changesets": ["tender-deers-swim"]
}
6 changes: 6 additions & 0 deletions .changeset/tender-deers-swim.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@react-three/fiber': patch
'@react-three/test-renderer': patch
---

new beta for library testing
15 changes: 7 additions & 8 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,7 @@
"es6": true,
"node": true
},
"extends": [
"prettier",
"plugin:prettier/recommended",
"plugin:react-hooks/recommended",
"plugin:import/errors",
"plugin:import/warnings"
],
"extends": ["prettier", "plugin:prettier/recommended", "plugin:react-hooks/recommended", "plugin:import/recommended"],
"plugins": ["@typescript-eslint", "react", "react-hooks", "import", "jest", "prettier"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
Expand Down Expand Up @@ -66,5 +60,10 @@
"project": "./tsconfig.json"
}
}
]
],
"rules": {
"import/no-unresolved": "off",
"import/named": "off",
"import/namespace": "off"
}
}
40 changes: 20 additions & 20 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
node_modules/
coverage/
dist/
build/
types/
# commit types in src
!packages/*/src/types/
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/
.DS_Store
.vscode
.docz/
package-lock.json
coverage/
.idea
yarn-error.log
.size-snapshot.json
__tests__/__image_snapshots__/__diff_output__
node_modules/
coverage/
dist/
build/
types/
# commit types in src
!packages/*/src/types/
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/
.DS_Store
.vscode
.docz/
package-lock.json
coverage/
.idea
yarn-error.log
.size-snapshot.json
__tests__/__image_snapshots__/__diff_output__
29 changes: 14 additions & 15 deletions docs/API/additional-exports.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,17 @@ title: Additional Exports
nav: 9
---

| export | usage |
| ---------------------- | -------------------------------------------------------------- |
| addEffect | Adds a global render callback which is called each frame |
| addAfterEffect | Adds a global after-render callback which is called each frame |
| addTail | Adds a global callback which is called when rendering stops |
| invalidate | Forces view global invalidation |
| advance | Advances the frameloop (given that it's set to 'never') |
| extend | Extends the native-object catalogue |
| createPortal | Creates a portal (it's a React feature for re-parenting) |
| render | Renders three JSX into a canvas |
| unmountComponentAtNode | Unmounts root scene |
| events | Dom pointer-event system |
| applyProps | `applyProps(element, props)` sets element properties, |
| act | usage with react-testing |
| | |
| export | usage |
| -------------- | -------------------------------------------------------------- |
| addEffect | Adds a global render callback which is called each frame |
| addAfterEffect | Adds a global after-render callback which is called each frame |
| addTail | Adds a global callback which is called when rendering stops |
| invalidate | Forces view global invalidation |
| advance | Advances the frameloop (given that it's set to 'never') |
| extend | Extends the native-object catalogue |
| createPortal | Creates a portal (it's a React feature for re-parenting) |
| createRoot | Creates a root that can render three JSX into a canvas |
| events | Dom pointer-event system |
| applyProps | `applyProps(element, props)` sets element properties, |
| act | usage with react-testing |
| | |
113 changes: 95 additions & 18 deletions docs/API/canvas.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const App = () => (
)
```

### Render Props
## Render Props

| Prop | Description | Default |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
Expand All @@ -30,20 +30,18 @@ const App = () => (
| camera | Props that go into the default camera, or your own `THREE.Camera` | `{ fov: 75, near: 0.1, far: 1000, position: [0, 0, 5] }` |
| shadows | Props that go into `gl.shadowMap`, can also be set true for `PCFsoft` | `false` |
| raycaster | Props that go into the default raycaster | `{}` |
| vr | Switches renderer to VR mode, then uses `gl.setAnimationLoop` | `false` |
| mode | React mode: legacy, blocking, concurrent | `blocking` |
| frameloop | Render mode: always, demand, never | `always` |
| resize | Resize config, see react-use-measure's options | `{ scroll: true, debounce: { scroll: 50, resize: 0 } }` |
| orthographic | Creates an orthographic camera | `false` |
| dpr | Pixel-ratio, use `window.devicePixelRatio`, or automatic: [min, max] | `undefined` |
| dpr | Pixel-ratio, use `window.devicePixelRatio`, or automatic: [min, max] | `[1, 2]` |
| linear | Switch off automatic sRGB encoding and gamma correction | `false` |
| flat | Use `THREE.NoToneMapping` instead of `THREE.ACESFilmicToneMapping` | `false` |
| onCreated | Callback after the canvas has rendered (but not yet committed) | `(state) => {}` |
| onPointerMissed | Response for pointer clicks that have missed any target | `(event) => {}` |

### Render defaults
## Render defaults

Canvas uses the [render function](/react-three-fiber/api/render-function) which will create a translucent `THREE.WebGLRenderer` with the following constructor args:
Canvas uses [createRoot](#createroot) which will create a translucent `THREE.WebGLRenderer` with the following constructor args:

- antialias=true
- alpha=true
Expand All @@ -61,21 +59,100 @@ It will also create the following scene internals:
- A `THREE.PCFSoftShadowMap` if `shadows` is true
- A `THREE.Scene` (into which all the JSX is rendered) and a `THREE.Raycaster`

<Hint>
In recent versions of threejs, `THREE.ColorManagement.legacy` will be set to false to enable automatic conversion of colors according to the renderer's configured color space. R3F will handle texture encoding conversion. For more on this topic, see [https://threejs.org/docs/#manual/en/introduction/Color-management](https://threejs.org/docs/#manual/en/introduction/Color-management).

The colorspace will be set to sRGB (unless "linear" is true), all colors and textures will be
auto-converted. Consult [donmccurdy.com: Color Management in
three.js](https://www.donmccurdy.com/2020/06/17/color-management-in-threejs) for more information
about this. Unless "flat" is true it will set up `THREE.ACESFilmicToneMapping` for slightly more
contrast.
## Custom Canvas

</Hint>
R3F can render to a root, similar to how `react-dom` and all the other React renderers work. This allows you to shave off `react-dom` (~40kb), `react-use-measure` (~3kb) and, if you don't need them, `pointer-events` (~7kb) (you need to explicitly import `events` and add them to the config otherwise).

<Hint>
Roots have the same options and properties as `Canvas`, but you are responsible for resizing it. It requires an existing DOM `<canvas>` object into which it renders.

Canvas creates a [resize observer](https://github.com/pmndrs/react-use-measure) to update the canvas size.
### CreateRoot

Consider Resize-Observer polyfills for older Safari browsers. We recommend
[juggle/resize-observer](https://github.com/juggle/resize-observer).
Creates a root targeting a canvas, rendering JSX.

</Hint>
```jsx
import { createRoot, events } from '@react-three/fiber'

let root

const handleResize = () => {
const size = { width: window.innerWidth, height: window.innerHeight }

// Create root with a size, events
root = createRoot(document.querySelector('canvas'), {
events,
size,
})

// Render JSX
root.render(<mesh />)

// Can also tweak root root options after creation:
root.configure({ size })

// Or to unmount and dispose of memory:
root.unmount()
}
handleResize()

window.addEventListener('resize', handleResize)

// to unmount
root.unmount()
```

## Tree-shaking

New with v8, the underlying reconciler no longer pulls in the THREE namespace automatically.

This enables a granular catalogue which also enables tree-shaking via the `extend` API:

```jsx
import { extend, createRoot } from '@react-three/fiber'
import { Mesh, BoxGeometry, MeshStandardMaterial } from 'three'

extend({ Mesh, BoxGeometry, MeshStandardMaterial })

createRoot(canvas).render(
<>
<mesh>
<boxGeometry />
<meshStandardMaterial />
</mesh>
</>,
)
```

There's an [official babel plugin](https://github.com/pmndrs/react-three-babel) which will do this for you automatically:

```jsx
// In:

import { createRoot } from '@react-three/fiber'

createRoot(canvasNode).render(
<mesh>
<boxGeometry />
<meshStandardMaterial />
</mesh>,
)

// Out:

import { createRoot, extend } from '@react-three/fiber'
import { Mesh as _Mesh, BoxGeometry as _BoxGeometry, MeshStandardMaterial as _MeshStandardMaterial } from 'three'

extend({
Mesh: _Mesh,
BoxGeometry: _BoxGeometry,
MeshStandardMaterial: _MeshStandardMaterial,
})

createRoot(canvasNode).render(
<mesh>
<boxGeometry />
<meshStandardMaterial />
</mesh>,
)
```
3 changes: 1 addition & 2 deletions docs/API/hooks.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ The hook is reactive, if you resize the browser for instance, you get fresh meas
| camera | Camera | `THREE.PerspectiveCamera` |
| mouse | Contains updated, normalized, centric pointer coordinates | `THREE.Vector2` |
| clock | Running system clock | `THREE.Clock` |
| vr | True when the system is in VR mode | `boolean` |
| linear | True when the colorspace is linear | `boolean` |
| flat | True when no tonemapping is used | `boolean` |
| frameloop | React render-mode | `always`, `demand`, `never` |
Expand Down Expand Up @@ -111,7 +110,7 @@ This hook allows you to execute code on every rendered frame, like running effec
import { useFrame } from '@react-three/fiber'

function Foo() {
useFrame((state, delta) => {
useFrame((state, delta, xrFrame) => {
// This function runs at the native refresh rate inside of a shared render-loop
})
```
Expand Down
72 changes: 19 additions & 53 deletions docs/API/objects.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,14 @@ Properties that have a `setScalar` method (for instance `Vector3`) can be set li
<mesh scale={1} />
```

## Piercing into nested properties

If you want to reach into nested attributes (for instance: `mesh.rotation.x`), just use dash-case.

```jsx
<mesh rotation-x={1} material-uniforms-resolution-value={[512, 512]} />
```

## Dealing with non-scene objects

You can put non-Object3D primitives (geometries, materials, etc) into the render tree as well. They take the same properties and constructor arguments they normally would.
Expand Down Expand Up @@ -94,44 +102,20 @@ The following attaches a material to the `material` property of a mesh and a geo
<boxGeometry />
```

### Nesting

You can nest primitive objects, too:

```jsx
<mesh>
<meshBasicMaterial attach="material">
<texture attach="map" image={img} onUpdate={self => (self.needsUpdate = true)} />
```

### AttachArray

Sometimes attaching isn't enough. The following example attaches effects to an array called "passes" of the parent `effectComposer`. `attachArray` adds the object to the target array and takes it out on unmount:

```jsx
<effectComposer>
<renderPass attachArray="passes" scene={scene} camera={camera} />
<glitchPass attachArray="passes" renderToScreen />
```

### AttachObject

You can also attach to named parent properties using `attachObject={[target, name]}`, which adds the object and takes it out on unmount. The following adds a buffer-attribute to `parent.attributes.position`.
You can also deeply nest attach through piercing. The following adds a buffer-attribute to `parent.attributes.position`.

```jsx
<bufferGeometry attach="geometry">
<bufferAttribute attachObject={['attributes', 'position']} count={v.length / 3} array={v} itemSize={3} />
<bufferAttribute attach="attributes-position" count={v.length / 3} array={v} itemSize={3} />
```

### AttachFns

Some objects have special add/remove function, you can't easily attach objects. In that case `attachFns` gives you full control.
Some objects have special add/remove function, you can't easily attach objects. In that case `attach` gives you full control.

The following uses the effect composer from the [vanruesc/postprocessing](https://github.com/vanruesc/postprocessing) library, which works differently than three/examples/jsm. You need to call `Composer.addPass` to add an effect and `Composer.removePass` to remove it.

```jsx
<effectComposer>
<renderPass attachFns={["addPass", "removePass"]} args={[scene, camera]} />
<renderPass args={[scene, camera]} attach={["addPass", "removePass"]} />
```

And in the case the add/remove functions are more complex:
Expand All @@ -140,18 +124,20 @@ And in the case the add/remove functions are more complex:
<effectComposer>
<renderPass
args={[scene, camera]}
attachFns={[
attach={[
(parent, self) => parent.addPass(self),
(parent, self) => parent.removePass(self)
]} />
```

## Piercing into nested properties
### Nesting

If you want to reach into nested attributes (for instance: `mesh.rotation.x`), just use dash-case.
You can nest primitive objects, too:

```jsx
<mesh rotation-x={1} material-uniforms-resolution-value={[512, 512]} />
<mesh>
<meshBasicMaterial attach="material">
<texture attach="map" image={img} onUpdate={self => (self.needsUpdate = true)} />
```

## Putting already existing objects into the scene-graph
Expand Down Expand Up @@ -181,27 +167,7 @@ return (
<transformControls />
```
If you are using Typescript, it is important to let Typescript be aware of the new elements.
```tsx
import { extend, ReactThreeFiber } from '@react-three/fiber'
import { OrbitControls } from 'three-stdlib'

extend({ OrbitControls })

declare global {
namespace JSX {
interface IntrinsicElements {
orbitControls: ReactThreeFiber.Object3DNode<
OrbitControls,
typeof OrbitControls
>
}
}
}
```
If you're using TypeScript, you'll also need to [extend the JSX namespace](/react-three-fiber/tutorials/typescript#extending-jsx-intrinsic-elements).
## Disposal
Expand Down
Loading

0 comments on commit 347ea79

Please sign in to comment.