React Fiber Reconciler Renderer for Regl WebGL

Last update: Apr 13, 2022

react-regl

This library enables Regl shader WebGL draw commands to be rendered directly as React components.

Stability npm version Dependency Status Build Status

Demos

View demos in the Storybook

There is a React Storybook included in the /docs directory with usage examples. The source for the Storybook is in the /stories directory and demonstrates how to create the examples.

Visit the Regl gallery page for more ideas on usage.

Install

npm install --save react-regl

Example Usage

import React from 'react'
import regl, { ReglFrame } from 'react-regl';

// Define a draw call for rendering a 2D triangle
const Triangle = regl({
  // Shaders in regl are just strings.  You can use glslify or whatever you want
  // to define them.  No need to manually create shader objects.

  vert: `
          precision mediump float;
          attribute vec2 position;
          void main () {
            gl_Position = vec4(position, 0, 1);
          }`,

  frag:`
          precision mediump float;
          uniform vec4 color;
          void main () {
            gl_FragColor = color;
          }`,

  // Here we define the vertex attributes for the above shader
  attributes:{
    position: [
      [-1, 0],
      [0, -1],
      [1, 1]
    ]
    // regl automatically infers sane defaults for the vertex attribute pointers
  },

  uniforms:{
    // This defines a dynamic regl value that can bethat can be passed as a react prop
    color: regl.prop('color')
  },

  // This tells regl the number of vertices to draw in this command
  count: 3
});

// Create an 'App' component that renders a regl frame and
// renders the triangle draw call
const App = () => {
  return (
    <ReglFrame>
      <Triangle color={[1, 0, 0, 1]} />
    </ReglFrame>
  );
};

// Mount React and render the App component
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

Motivation and Goals

This repo, react-regl brings a JSX interface to regl, enabling easy integration of Regl UI into existing react projects. react-regl Allows you to render regl draw commands as react components. You can define the regl draw command as you would with raw regl but with react-regl you can pass arnd render it as react component.

regl is a stateless functional abstraction for WebGl. Regl makes working with WebGL a more productive experience. Its stateless nature makes it easier to reason about WebGL programs. Regl's design was influenced by React. It follows React's unidirectional data flow to stateless component model. This module wraps Regl with a React reconciler for a fuller React experience

Regl vs Other WebGL frameworks

Regl follows the unix philosophy of "small sharp tools" or "do one thing and do it well". Regl has full test coverage and aims for stable non-breaking updates. Other popular WebGL frameworks encompass much more responsiblity, usually including heavy abstractions for: scene graphs, animation systems, input systems, and cross device compatibility. The large amount of responsiblity in these other libraries leads to unstable, breaking releases, and lacking documentation and support.

Development

npm link and local installs npm i -S [email protected]:../react-regl should link to consuming project. npm run build should be run in the react-regl module directory

React peer dependency error

If default npm link or local install fails with od errors about duplicate react versions you need to ensure the module is loading react from the consuming host project

cd my-app
npm link ../react-regl

Link its copy of React back to the app's React

cd ../react-regl
npm link ../my-app/node_modules/react

Publishing

publish to npm with the version command and patch minor major or explicit tag 4.0.0-beta.2

npm version

npm version will create a git tag that needs to be pushed..

git push --tags

GitHub

https://github.com/kevzettler/react-regl/
Comments
  • 1. ReglFrame color not persisting across React redraw calls

    I'm testing the basic triangle example and noticed that the background color (green in this example) is respected when I render the react component for the first time, but if I change the react component color prop (e.g. on a button click to trigger a re-render in react), the triangle color changes as expected, but the ReglFrame background color turns black (instead of green).

     <ReglFrame width={width} height={height} color={[0, 1, 0, 1]}>
        <Triangle color={props.color}/>
    </ReglFrame>
    

    Also, this may be a separate issue, but alpha in ReglFrame's color doesn't affect anything in the frame background. Is there a way to enable alpha support?

    Reviewed by gouldingken at 2021-07-14 05:03
  • 2. Invalid JSX error

    I'm trying to follow the basic triangle example, but I'm getting JSX errors. I've tried to see if I can change anything in the tsconfig file to work around this, but I can't see anything that you're doing different.

    What am I missing?

    'Triangle' cannot be used as a JSX component.
      Its return type 'IDregl<Regl>' is not a valid JSX element.
        Type 'IDregl<Regl>' is missing the following properties from type 'ReactElement<any, any>': type, props, key  TS2786
    
        36 |         <ReglFrame
        37 |             color={[0.40625, 0.94921, 0.996, 1]}>
      > 38 |             <Triangle />
           |              ^
        39 |         </ReglFrame>
        40 |     );
        41 | };
    
    
    Reviewed by gouldingken at 2021-07-13 05:07
  • 3. Immediately accessing props passed to regl JSX?

    There may already be a way to do this, but I haven't been able to find it in any of the examples:

    I'm trying to modify my shader code by passing in a '#define' value for an array length. As far as I know I can't use the regular "uniforms" method of passing these values to my shader, so I typically use '#define' or const with a hard-coded value that I feed into my shader string.

    Ideally this value would be a prop that I can pass to my React component and it would modify the shader code. I tried passing a value as a 'prop' (which seems very clean and React-friendly). But when I try to access the value on regl.prop - it returns a deferred-regl function expecting (context, props) and I'm not sure whether I can access the value at that point.

    Is there a way to do this currently? If not, it would be a really helpful feature.

    FWIW I noticed three.js uses a 'defines' object to abstract this further - but I don't think regl exposes that in the same way.

    const frag = (nArr) => {
        // language=GLSL
        return `
            precision mediump float;
    
            #define N_ARR ${nArr}
            #define MAX_STACK 2
           ...
    
    const ColorizerRegl = regl({
        vert,
        frag: frag(regl.prop('nArr')),
        attributes: {
            position: [
                0, 4,
                -4, -4,
                4, -4,
            ]
        },
    
        uniforms: {
            textureReference: regl.prop('reference'),
            textureData: regl.prop('data'),
            textureCurrent: regl.prop('current'),
            dataWidth: regl.prop('dataWidth'),
        },
    
        count: 3
    });
    
    <ColorizerRegl nArr={metaData.nArr}
           reference={images.reference}
           data={images.data}
           current={images.current}
           dataWidth={metaData.dataWidth}/>
    
    Reviewed by gouldingken at 2021-07-20 03:35
  • 4. Unable to reproduce basic example with React 16.6+

    Hi,

    Thanks for putting together this library. I've been trying to get a basic example running using the minimal "draw a canvas, and shade it" example from the storybook. I was getting the same error as reported in #7 when developing locally in a storybook. Here's the same code sample running in a sandbox.

    import React from "react";
    import ReactDOM from "react-dom";
    import Regl from "react-regl";
    
    class App extends React.Component {
      constructor(props) {
        super(props);
      }
    
      componentDidCatch(e, info) {
        console.log(e, info);
      }
    
      render() {
        return <Regl width={500} height={500} color={[0.5, 0.5, 0.5, 1]} />;
      }
    }
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);
    

    https://codesandbox.io/s/nn4x2nx6ml

    An error comes out in the console about having difficulty with accessing the store prop:

    **Warning: Failed child context type: Cannot read property 'store' of undefined**
    

    Downgrading to older React 16.1.1 for both react and react-dom fixes the issue. However, that version is missing some features that I want to use in a current project (hooks, etc), so I'd like to try to find a workaround that lets me use the latest react together with this library.

    Reviewed by hydrosquall at 2019-03-23 17:16
  • 5. Module not found: Can't resolve 'react-regl'

    Steps to reproduce:

    npx create-react-app new_app
    cd new_app
    npm install --save react-regl
    

    Then use this code in src/App.js:

    import React from "react";
    import ReactDOM from "react-dom";
    import Regl from "react-regl";
    
    export default class App extends React.Component {
      constructor(props) {
        super(props);
      }
    
      componentDidCatch(e, info) {
        console.log(e, info);
      }
    
      render() {
        return <Regl width={500} height={500} color={[0.5, 0.5, 0.5, 1]} />;
      }
    }
    

    Then: npm run start

    What I do wrong?

    Reviewed by Nizarius at 2019-04-12 19:24
  • 6. Add lodash as dependency

    Based on this line,

    https://github.com/kevzettler/react-regl/blob/56153852342f7b52d52fc41fab25dde2f949fc04/src/nodes/DrawNode.js#L5

    , users need to install lodash separately for this library to work. The reason for my not opening a PR directly is in case you have an opinion about adding it as a core vs peer dependency.

    Reviewed by hydrosquall at 2019-03-23 16:53
  • 7. Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue.

    Hi, thanks for your great work. I get the above error message when trying the following:

    app.js

    import React, { Component } from 'react'; import Regl from 'react-regl'; import Triangle from './triangle.jsx';

    class App extends Component {

    render() {
        return (
            <div className="App">
                <h1>React Regl example</h1>
                <Regl width={window.innerWidth} height={window.innerHeight} color={[0,0,0,1]}>
                    <Triangle color={[0.812, 0.792, 0.098, 1]} positions={[[-0.5, 0], [0, -0.5], [0.25, 1]]} />
                </Regl>
            </div>
        );
    }
    

    }

    export default App;

    and triangle.jsx: ` import React,{Component} from 'react'; import {Draw} from 'react-regl';

    class Triangle extends Component { render(){ return ( <Draw vert={` precision mediump float; attribute vec2 position; void main(){ gl_Position=vec4(position,0,1) }

        `}
            frag={`
            precision mediump float;
            uniform vec4 color;
            void main(){
                gl_FragColor=color;
            }
            `}
            attributes={{
                position:this.props.positions
            }}
            uniforms={{
                color: this.props.color
            }}
            count={3}
            />
        )
    }
    

    }

    export default Triangle `

    Reviewed by clickglue at 2018-09-06 20:33
  • 8. How to access `regl.texture`

    I was trying to replicate the Baboon texture example from http://regl.party/examples when I noticed that there is no simple way to reach regl.texture method in react-regl. Actually there is no way to reach the initialized regl object as far as I can tell. Am I missing something? Is there a built-in way to do this?

    Reviewed by RodrigoRoaRodriguez at 2018-04-02 18:08
  • 9. fix for github security

    This is a fix as mentioned here: https://github.com/heroku/heroku-buildpack-nodejs/issues/959

    for GitHub security changes as released here: https://github.blog/2021-09-01-improving-git-protocol-security-github/

    Thank you for this package,

    Reviewed by DanRossLi at 2022-01-11 03:12
  • 10. Bump elliptic from 6.4.1 to 6.5.4

    Bumps elliptic from 6.4.1 to 6.5.4.

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    Reviewed by dependabot[bot] at 2021-03-09 01:53
  • 11. Bump ini from 1.3.5 to 1.3.7

    Bumps ini from 1.3.5 to 1.3.7.

    Commits
    • c74c8af 1.3.7
    • 024b8b5 update deps, add linting
    • 032fbaf Use Object.create(null) to avoid default object property hazards
    • 2da9039 1.3.6
    • cfea636 better git push script, before publish instead of after
    • 56d2805 do not allow invalid hazardous string as section name
    • See full diff in compare view
    Maintainer changes

    This version was pushed to npm by isaacs, a new releaser for ini since your current version.


    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    Reviewed by dependabot[bot] at 2020-12-11 03:30
  • 12. Shared global deferred regl causes issues with multiple ReglFrame instances and mounting/unmounting

    The regl calls are deferred, they are not executed until the ReglFrame component mounts and passes a canvas draw context to the reglInit function and then passes a regl reference set method. This will then trigger all the deferred functions to execute. If ReglFrame is unmounted it will call regl.destroy and then when a new ReglFram is mounted it will reinitalize all the deferred functions with the new regl handle. This reinitialization of the deferred function seems to cause some some failures. This can be observed in the storybook by changing between the different stories. This causes a mount and unmount of the ReglFrame components. Which triggers the set/unset of the deferred regl components.

    Further concerns are that the deferred resources are defined in shared global scope. So deferred resources that are not part of the ReglFrame component tree are re-initalized. In the story book this means that when you change between stories all of the resources for all other stories are reinitalized.

    An idea for improvement here is ReglFrame should not call the global deferred set function which will execution all know deferred functions. Instead ReglFrame should execute a tree of the deferreds it will render. This will have some edge cases where a resources is defined in a scope out side of the render time tree but still used.

    Reviewed by kevzettler at 2021-03-09 04:01
Connect, discover, be free to choose between WebGL / Canvas (PIXI) / DOM or any other UI renderer
Connect, discover, be free to choose between WebGL / Canvas (PIXI) / DOM or any other UI renderer

React Liberty Be free to choose between WebGL / Canvas / DOM / Native or any other UI renderer This is a React library designed to abstract renderer b

Sep 10, 2021
🍙 A minimal implementation of react-dom using react-reconciler
🍙 A minimal implementation of react-dom using react-reconciler

react-tiny-dom react-tiny-dom is a minimal implementation of react-dom as custom renderer using React 16 official Renderer API. The purpose of this pr

May 10, 2022
Osd-react-renderer - A custom React renderer for OpenSeadragon

osd-react-renderer A custom React renderer for OpenSeadragon viewer, built using

Jan 24, 2022
Reactron is a React component visualizer that allows you to traverse an app's fiber tree and render components individually.
Reactron is a React component visualizer that allows you to traverse an app's fiber tree and render components individually.

Reactron Empowering the Development Process from Top to Bottom A tool for the complete and total visualization of your React application Reactron bols

Mar 14, 2022
React JSX Renderer is a React Component for rendering JSX to React nodes.

React JSX Renderer A React Component for Rendering JSX. Description React JSX Renderer is a React Component for rendering JSX to React nodes.

Jan 9, 2022
🇨🇭 A React renderer for Three.js (web and react-native)
🇨🇭 A React renderer for Three.js (web and react-native)

react-three-fiber react-three-fiber is a React renderer for threejs on the web and react-native. npm install three react-three-fiber These demos are r

May 15, 2022
🇨🇭 A React renderer for Three.js (web and react-native)
🇨🇭 A React renderer for Three.js (web and react-native)

react-three-fiber react-three-fiber is a React renderer for threejs on the web and react-native. npm install three react-three-fiber These demos are r

May 19, 2022
[ Unmaintained due to raphamorim/react-ape ] React Renderer for low memory applications
[ Unmaintained due to raphamorim/react-ape ] React Renderer for low memory applications

React-TV · react-tv: React Renderer for low memory applications. react-tv-cli: React Packager for TVs. Currently under development. import React from

May 10, 2022
⚛️ A React renderer for Figma
⚛️ A React renderer for Figma

React Figma A React renderer for Figma. Use React components as a source for your designs. ?? Compatible with react-native, react-sketchapp, react-pri

May 10, 2022
⃝ A react null renderer

Nothing to see here ... Quite so. This package allows you to bring Reacts high-level component abstraction to Node, or wherever you need it. Why not m

Apr 18, 2022
A React renderer for Hardware.

React Hardware React Hardware enables you to build firmata-based hardware applications using a consistent developer experience based on JavaScript and

May 4, 2022
A react renderer for browser's dev console
A react renderer for browser's dev console

Konsul is an abstraction of the browser's console that comes with a React renderer. It offers text styling, images, style inheritance, buttons with cl

Jan 3, 2022
React custom renderer for Appcelerator® Titanium™ SDK
React custom renderer for Appcelerator® Titanium™ SDK

⚠️ Maintainer wanted! Create an issue if you want to maintain it! react-titanium A React custom renderer for Appcelerator® Titanium™ SDK. This rendere

Mar 6, 2022
React renderer for NativeScript
React renderer for NativeScript

React NativeScript is A React renderer for NativeScript, allowing you to write a NativeScript app using the familiar React style. I'm always hanging o

Apr 21, 2022
A react renderer for blessed.

react-blessed A React custom renderer for the blessed library. This renderer should currently be considered as experimental, is subject to change and

May 17, 2022
a react renderer for the command line

This repository is now archived This project was originally created as an alternative to the Ink library, as a separate renderer for a real React comp

Dec 2, 2020
📟 A React Renderer for SSD1306 OLED chip on Raspberry Pi.
📟 A React Renderer for SSD1306 OLED chip on Raspberry Pi.

React SSD1306 A React Renderer for SSD1306 OLED chip on Raspberry Pi For those who doesn't have the device, a canvas-based web emulator is also includ

Apr 19, 2022
React renderer with X11 as a target
React renderer with X11 as a target

react-x11 React custom rendering where side effects are communication with X11 server. The goal is to create a simple library where you would apply yo

Apr 26, 2022
React renderer for building user interfaces in Unity UI

React Unity React Unity is a way to build interactive UI in Unity3D using React. It can be used together with packages like Typescript, redux, i18next

May 16, 2022