├── .gitignore ├── LICENSE ├── README.md ├── package-lock.json ├── package.json ├── public ├── electron.js ├── favicon.ico ├── favicon.svg ├── index.html └── manifest.json ├── src ├── App.css ├── App.js ├── App.test.js ├── BabylonScene │ └── index.js ├── Viewer │ └── index.js ├── index.css ├── index.js └── serviceWorker.js └── yarn.lock /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | /dist 14 | 15 | # misc 16 | .DS_Store 17 | .env.local 18 | .env.development.local 19 | .env.test.local 20 | .env.production.local 21 | 22 | npm-debug.log* 23 | yarn-debug.log* 24 | yarn-error.log* 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Todor Imreorov 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## What is this 2 | 3 | Boilerplate to create react+babylonjs apps that can also run inside electron. 4 | 5 | This is something I made over the weekend to see how babylonjs works with reactjs and electron. 6 | At the time I released it, The Babylonjs team doesn't seem to have solid examples of this, just a few code snippets. 7 | 8 | Hopefuly could be useful for others... 9 | 10 | ## How to use 11 | Clone this repository, then run 12 | ### `npm install` 13 | ### `npm start` 14 | ### `npm run electron` 15 | 16 | ## Available Scripts 17 | 18 | In the project directory, you can run: 19 | 20 | ### `npm start` 21 | 22 | Runs the app in the development mode.
23 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 24 | 25 | The page will reload if you make edits.
26 | You will also see any lint errors in the console. 27 | 28 | ### `npm run electron` 29 | 30 | Runs the electron app in the development mode. You will need to run npm start first. 31 | 32 | ### `npm test` 33 | 34 | Launches the test runner in the interactive watch mode.
35 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 36 | 37 | ### `npm run build` 38 | 39 | Builds the electron app 40 | 41 | ### `npm run build-portable` 42 | 43 | Builds the electron app as a single executable (smaller file, but takes longer to start) 44 | 45 | ### `npm run build-web` 46 | 47 | Builds the app for production to the `build` folder.
48 | It correctly bundles React in production mode and optimizes the build for the best performance. 49 | 50 | The build is minified and the filenames include the hashes.
51 | Your app is ready to be deployed! 52 | 53 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 54 | 55 | ### `npm run eject` 56 | 57 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 58 | 59 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 60 | 61 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 62 | 63 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 64 | 65 | ## Learn More 66 | 67 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 68 | 69 | To learn React, check out the [React documentation](https://reactjs.org/). 70 | 71 | ### Code Splitting 72 | 73 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting 74 | 75 | ### Analyzing the Bundle Size 76 | 77 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size 78 | 79 | ### Making a Progressive Web App 80 | 81 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app 82 | 83 | ### Advanced Configuration 84 | 85 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration 86 | 87 | ### Deployment 88 | 89 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment 90 | 91 | ### `npm run build` fails to minify 92 | 93 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify 94 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "main": "public/electron.js", 3 | "name": "babylon-react-electron-app", 4 | "author": "Todor Imreorov", 5 | "description": "Boilerplate example app", 6 | "version": "0.2.0", 7 | "homepage": "./", 8 | "private": true, 9 | "dependencies": { 10 | "babylonjs": "^4.0.3", 11 | "electron-is": "^3.0.0", 12 | "react": "^16.8.3", 13 | "react-dom": "^16.8.3", 14 | "react-scripts": "2.1.5" 15 | }, 16 | "devDependencies": { 17 | "electron": "^5.0.1", 18 | "electron-builder": "^20.40.2", 19 | "typescript": "^3.4.5" 20 | }, 21 | "scripts": { 22 | "start": "react-scripts start", 23 | "test": "react-scripts test", 24 | "eject": "react-scripts eject", 25 | "electron-static": "npm run build-web && electron build/electron.js", 26 | "build-web": "react-scripts build", 27 | "build": "npm run build-web && build --win", 28 | "build-portable": "npm run build-web && build --win portable", 29 | "electron": "electron public/electron.js" 30 | }, 31 | "build": { 32 | "asar": true, 33 | "appId": "com.electron.babylon", 34 | "copyright": "MIT", 35 | "productName": "babylon-react-electron-app", 36 | "win":{ 37 | "icon": "public/icon.png", 38 | "publisherName": "Todor Imreorov" 39 | } 40 | }, 41 | "eslintConfig": { 42 | "extends": "react-app" 43 | }, 44 | "browserslist": [ 45 | ">0.2%", 46 | "not dead", 47 | "not ie <= 11", 48 | "not op_mini all" 49 | ] 50 | } 51 | -------------------------------------------------------------------------------- /public/electron.js: -------------------------------------------------------------------------------- 1 | const electron = require('electron') 2 | const isDev = require('electron-is').dev(); 3 | const ipcMain = electron.ipcMain; 4 | const {dialog} = require('electron') 5 | // server = require("./localhost") 6 | // Module to control application life. 7 | const app = electron.app 8 | // Module to create native browser window. 9 | const BrowserWindow = electron.BrowserWindow 10 | // Keep a global reference of the window object, if you don't, the window will 11 | // be closed automatically when the JavaScript object is garbage collected. 12 | let mainWindow 13 | let yarnWindow 14 | let yarnRunnerWindow 15 | 16 | function createWindow () { 17 | // Create the browser window. 18 | let {width, height} = require('electron').screen.getPrimaryDisplay().size; 19 | mainWindow = new BrowserWindow({ 20 | defaultWidth: 1000, 21 | defaultHeight: 800, 22 | maximize: false, 23 | autoHideMenuBar: true 24 | }); 25 | mainWindow.maximize() 26 | // and load the index.html of the app. 27 | if (isDev) { 28 | mainWindow.loadURL(`http://localhost:3000/index.html`) 29 | mainWindow.webContents.openDevTools() 30 | } else { 31 | mainWindow.loadURL(`file://${__dirname}/index.html`) 32 | } 33 | 34 | mainWindow.on('close', function (event) { 35 | 36 | event.preventDefault(); 37 | mainWindow.webContents.send('closing'); 38 | mainWindow.destroy() 39 | }); 40 | 41 | // Emitted when the window is closed. 42 | mainWindow.on('closed', function () { 43 | // Dereference the window object, usually you would store windows 44 | // in an array if your app supports multi windows, this is the time 45 | // when you should delete the corresponding element. 46 | 47 | mainWindow = null 48 | }); 49 | 50 | mainWindow.webContents.on('dom-ready', () => { 51 | if (mainWindow.isMaximized) { 52 | } 53 | mainWindow.webContents.send('loaded'); 54 | }); 55 | } 56 | 57 | // This method will be called when Electron has finished 58 | // initialization and is ready to create browser windows. 59 | // Some APIs can only be used after this event occurs. 60 | app.on('ready', createWindow) 61 | 62 | // Quit when all windows are closed. 63 | app.on('window-all-closed', function () { 64 | // On OS X it is common for applications and their menu bar 65 | // to stay active until the user quits explicitly with Cmd + Q 66 | if (process.platform !== 'darwin') { 67 | app.quit() 68 | } 69 | }) 70 | 71 | app.on('activate', function () { 72 | // On OS X it's common to re-create a window in the app when the 73 | // dock icon is clicked and there are no other windows open. 74 | if (mainWindow === null) { 75 | createWindow(); 76 | } 77 | }) 78 | 79 | // In this file you can include the rest of your app's specific main process 80 | // code. You can also put them in separate files and require them here. 81 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blurymind/babylon-react-electron-app/eb64aac0d2a1070fab8debfd1806b2b57919b4f8/public/favicon.ico -------------------------------------------------------------------------------- /public/favicon.svg: -------------------------------------------------------------------------------- 1 | logo_page -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 10 | 11 | 15 | 16 | 25 | React App 26 | 27 | 28 | 29 |
30 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | } 10 | ], 11 | "start_url": ".", 12 | "display": "standalone", 13 | "theme_color": "#000000", 14 | "background_color": "#ffffff" 15 | } 16 | -------------------------------------------------------------------------------- /src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | animation: App-logo-spin infinite 20s linear; 7 | height: 40vmin; 8 | pointer-events: none; 9 | } 10 | 11 | .App-header { 12 | background-color: #282c34; 13 | min-height: 100vh; 14 | display: flex; 15 | flex-direction: column; 16 | align-items: center; 17 | justify-content: center; 18 | font-size: calc(10px + 2vmin); 19 | color: white; 20 | } 21 | 22 | .App-link { 23 | color: #61dafb; 24 | } 25 | 26 | @keyframes App-logo-spin { 27 | from { 28 | transform: rotate(0deg); 29 | } 30 | to { 31 | transform: rotate(360deg); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/App.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import './App.css'; 3 | 4 | import Viewer from './Viewer/'; 5 | 6 | class App extends Component { 7 | render() { 8 | return ( 9 |
10 | 11 |
12 | ); 13 | } 14 | } 15 | 16 | export default App; 17 | -------------------------------------------------------------------------------- /src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); 7 | ReactDOM.render(, div); 8 | ReactDOM.unmountComponentAtNode(div); 9 | }); 10 | -------------------------------------------------------------------------------- /src/BabylonScene/index.js: -------------------------------------------------------------------------------- 1 | import * as BABYLON from 'babylonjs'; 2 | import React, { Component } from 'react'; 3 | 4 | export type SceneEventArgs = { 5 | engine: BABYLON.Engine, 6 | scene: BABYLON.Scene, 7 | canvas: HTMLCanvasElement 8 | }; 9 | 10 | export type SceneProps = { 11 | engineOptions?: BABYLON.EngineOptions, 12 | adaptToDeviceRatio?: boolean, 13 | onSceneMount?: (args: SceneEventArgs) => void, 14 | width?: number, 15 | height?: number 16 | }; 17 | 18 | export default class BabylonScene extends Component, {}> { 19 | 20 | // private scene: BABYLON.Scene; 21 | // private engine: BABYLON.Engine; 22 | // private canvas: HTMLCanvasElement; 23 | 24 | onResizeWindow = () => { 25 | if (this.engine) { 26 | this.engine.resize(); 27 | this.forceUpdate() 28 | } 29 | } 30 | 31 | componentDidMount () { 32 | this.engine = new BABYLON.Engine( 33 | this.canvas, 34 | true, 35 | this.props.engineOptions, 36 | this.props.adaptToDeviceRatio 37 | ); 38 | 39 | let scene = new BABYLON.Scene(this.engine); 40 | this.scene = scene; 41 | 42 | if (typeof this.props.onSceneMount === 'function') { 43 | this.props.onSceneMount({ 44 | scene, 45 | engine: this.engine, 46 | canvas: this.canvas 47 | }); 48 | } else { 49 | console.error('onSceneMount function not available'); 50 | } 51 | 52 | // Resize the babylon engine when the window is resized 53 | window.addEventListener('resize', this.onResizeWindow); 54 | } 55 | 56 | componentWillUnmount () { 57 | window.removeEventListener('resize', this.onResizeWindow); 58 | } 59 | 60 | onCanvasLoaded = (c : HTMLCanvasElement) => { 61 | if (c !== null) { 62 | this.canvas = c; 63 | } 64 | } 65 | 66 | render () { 67 | // 'rest' can contain additional properties that you can flow through to canvas: 68 | // (id, className, etc.) 69 | const { width, height, ...rest } = this.props; 70 | 71 | const opts: any = {}; 72 | 73 | if (width !== undefined && height !== undefined) { 74 | opts.width = width; 75 | opts.height = height; 76 | } else { 77 | opts.width = window.innerWidth; 78 | opts.height = window.innerHeight; 79 | } 80 | 81 | return ( 82 | 86 | ) 87 | } 88 | } -------------------------------------------------------------------------------- /src/Viewer/index.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import * as BABYLON from 'babylonjs'; 3 | import BabylonScene from '../BabylonScene/'; // import the component above linking to file we just created. 4 | 5 | export default class Viewer extends Component<{}, {}> { 6 | onSceneMount = (e: SceneEventArgs) => { 7 | const { canvas, scene, engine } = e; 8 | 9 | // This creates and positions a free camera (non-mesh) 10 | const camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 5, -10), scene); 11 | // This targets the camera to scene origin 12 | camera.setTarget(BABYLON.Vector3.Zero()); 13 | // This attaches the camera to the canvas 14 | camera.attachControl(canvas, true); 15 | // This creates a light, aiming 0,1,0 - to the sky (non-mesh) 16 | const light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene); 17 | // Default intensity is 1. Let's dim the light a small amount 18 | light.intensity = 0.7; 19 | // Our built-in 'sphere' shape. Params: name, subdivs, size, scene 20 | const sphere = BABYLON.Mesh.CreateSphere("sphere1", 16, 2, scene); 21 | // Move the sphere upward 1/2 its height 22 | sphere.position.y = 1; 23 | // Our built-in 'ground' shape. Params: name, width, depth, subdivs, scene 24 | const ground = BABYLON.Mesh.CreateGround("ground1", 6, 6, 2, scene); 25 | 26 | engine.runRenderLoop(() => { 27 | if (scene) { 28 | scene.render(); 29 | } 30 | }); 31 | } 32 | 33 | render() { 34 | return ( 35 | //
36 | 37 | //
38 | ) 39 | } 40 | } -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", 5 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", 6 | sans-serif; 7 | -webkit-font-smoothing: antialiased; 8 | -moz-osx-font-smoothing: grayscale; 9 | } 10 | 11 | code { 12 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", 13 | monospace; 14 | } 15 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | 9 | // If you want your app to work offline and load faster, you can change 10 | // unregister() to register() below. Note this comes with some pitfalls. 11 | // Learn more about service workers: http://bit.ly/CRA-PWA 12 | serviceWorker.unregister(); 13 | -------------------------------------------------------------------------------- /src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read http://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.1/8 is considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit http://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See http://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl) 104 | .then(response => { 105 | // Ensure service worker exists, and that we really are getting a JS file. 106 | const contentType = response.headers.get('content-type'); 107 | if ( 108 | response.status === 404 || 109 | (contentType != null && contentType.indexOf('javascript') === -1) 110 | ) { 111 | // No service worker found. Probably a different app. Reload the page. 112 | navigator.serviceWorker.ready.then(registration => { 113 | registration.unregister().then(() => { 114 | window.location.reload(); 115 | }); 116 | }); 117 | } else { 118 | // Service worker found. Proceed as normal. 119 | registerValidSW(swUrl, config); 120 | } 121 | }) 122 | .catch(() => { 123 | console.log( 124 | 'No internet connection found. App is running in offline mode.' 125 | ); 126 | }); 127 | } 128 | 129 | export function unregister() { 130 | if ('serviceWorker' in navigator) { 131 | navigator.serviceWorker.ready.then(registration => { 132 | registration.unregister(); 133 | }); 134 | } 135 | } 136 | --------------------------------------------------------------------------------