UNPKG

react-three-nephilim

Version:
485 lines (484 loc) 23.6 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Nephilim = void 0; var _react = _interopRequireWildcard(require("react")); var _tween = _interopRequireDefault(require("@tweenjs/tween.js")); var Three = _interopRequireWildcard(require("three")); var Loaders = _interopRequireWildcard(require("./Loaders")); var _CSS3DRenderer = require("three/examples/jsm/renderers/CSS3DRenderer"); var _EffectComposer = require("./EffectComposer"); var _Decoration = require("./Decoration/Decoration"); var _Controller = require("./Controller"); var _Action = require("./Action"); var _Motion = require("./Motion"); var _Helpers = require("./Helpers"); require("../css/styles.css"); function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } var Nephilim = exports.Nephilim = function (_Component) { function Nephilim(props) { var _this; _classCallCheck(this, Nephilim); _this = _callSuper(this, Nephilim, [props]); _defineProperty(_this, "setEventListeners", function () { window.addEventListener('mousemove', _this.onMouseMove); window.addEventListener('touchmove', _this.onTouchMove); window.addEventListener('resize', _this.onResize); window.addEventListener('click', _this.onClick); }); _defineProperty(_this, "setInitialRoute", function () { var _withInterface = (0, _Helpers.withInterface)(_this.props), router = _withInterface.router; var sceneId = null; if (_this.route) { var origin = "/".concat(_this.route.split('/')[1]); for (var r in router) { if (router[r] === origin || router[r].path === origin) { sceneId = r; } } } else if (_this.activeScene) { sceneId = _this.activeScene.id; } if (sceneId) { var callback = router && router[sceneId].callback ? function () { return router[sceneId].callback(_this, _this.route); } : false; _this.navigate(sceneId, { callback: callback }); } }); _defineProperty(_this, "setPPEffects", function (effects) { var _withInterface2 = (0, _Helpers.withInterface)(_this.props), postProcessing = _withInterface2.postProcessing; var _this$container = _this.container, clientWidth = _this$container.clientWidth, clientHeight = _this$container.clientHeight; var pp = postProcessing; if (!pp || !(effects !== null && effects !== void 0 && effects.length)) return false; _this.isPPEnabled = true; _this.composer.passes.length = 1; effects.forEach(function (e, ei) { var ppEffect = null; if (e.includes('Shader')) { ppEffect = new _EffectComposer.Passes.ShaderPass(pp[e].src || _EffectComposer.Shaders[e]); if (pp[e].uniforms) { for (var u in pp[e].uniforms) { ppEffect.uniforms[u].value = pp[e].uniforms[u]; } } } else { var Pass = pp[e].src || _EffectComposer.Passes[e]; var params = []; if (pp[e].isScene) { params.push(_this.visual); } if (pp[e].isCamera) { params.push(_this.camera); } ppEffect = _construct(Pass, params.concat(_toConsumableArray(pp[e].params || []))); } ppEffect.renderToScreen = ei === effects.length - 1; _this.composer.addPass(ppEffect); }); _this.composer.setSize(clientWidth, clientHeight); }); _defineProperty(_this, "setLoadingManager", function () { _this.loaders = {}; _this.loadingManager = new Three.LoadingManager(); _this.animationLoader = new Three.AnimationLoader(_this.loadingManager); _this.audioLoader = new Three.AudioLoader(_this.loadingManager); _this.textureLoader = new Three.TextureLoader(_this.loadingManager); _this.loadingManager.onProgress = function (item, loaded, total) { return _this.setState({ loaded: loaded, total: total }); }; _this.loadingManager.onLoad = function () { return _this.setState({ loading: false }); }; }); _defineProperty(_this, "setLoader", function (l) { if (Loaders[l] && !_this.loaders[l]) { _this.loaders[l] = new Loaders[l](_this.loadingManager); } return _this.loaders[l]; }); _defineProperty(_this, "setVisualState", function (id, state) { return _this.find(id).setVisualState(state); }); _defineProperty(_this, "setMotion", function (id, motion) { return _this.find(id).setMotion(motion); }); _defineProperty(_this, "getAction", function (id) { return _this.actions[id]; }); _defineProperty(_this, "connectActions", function (decoration, actions) { for (var a in actions) { if (!_this.actions[a]) _this.actions[a] = new _Action.Action(); _this.actions[a].addDecoration(decoration, actions[a]); } }); _defineProperty(_this, "resetActions", function () { return _tween["default"].removeAll(); }); _defineProperty(_this, "executeActionsSequence", function (actionIds, params) { _this.actions[actionIds[0]].begin(_this.buildActionsSequence(actionIds, 1, params)); }); _defineProperty(_this, "buildActionsSequence", function (actionIds, index, params) { var p = _objectSpread({}, params); if (actionIds[index]) { p.callback = function () { return _this.actions[actionIds[index]].begin(params); }; } if (index < actionIds.length - 1) { params = _this.buildActionsSequence(actionIds, index + 1, params); } return p; }); _defineProperty(_this, "enablePostProcessing", function (isEnabled) { return _this.isPPEnabled = isEnabled; }); _defineProperty(_this, "enableLayerRendering", function (isEnabled) { return _this.isLayerRendering = isEnabled; }); _defineProperty(_this, "find", function (id) { for (var k in _this.children) { var c = _this.children[k].find(id); if (c) return c; } }); _defineProperty(_this, "findAll", function (id) { var all = []; for (var k in _this.children) { _this.children[k].findAll(id, all); } return all; }); _defineProperty(_this, "update", function () { for (var k in _this.children) { _this.children[k].update(); } if (_this.isPPEnabled) { if (_this.isLayerRendering) { for (var l in _this.layers) { _this.camera.layers.set(_this.layers[l]); _this.composer.render(); } _this.glRenderer.clearDepth(); _this.camera.layers.set(0); _this.glRenderer.render(_this.visual, _this.camera); } else { _this.composer.render(); } } else if (_this.glRenderer) { _this.glRenderer.render(_this.visual, _this.camera); } if (_this.cssRenderer) { _this.cssRenderer.render(_this.visual, _this.camera); } _tween["default"].update(); _this.onUpdateHandlers.forEach(function (handler) { return handler(); }); requestAnimationFrame(_this.update); }); _defineProperty(_this, "updateLayout", function () { if (_this.children) { for (var c in _this.children) { _this.children[c].updateLayout(); } } }); _defineProperty(_this, "navigate", function (id, params) { var _withInterface3 = (0, _Helpers.withInterface)(_this.props), router = _withInterface3.router; var scene = _this.find(id); if (scene) { var events = ['onMouseWheel', 'onMouseMove', 'onClick', 'onKeyUp', 'onTouchMove', 'onTouchStart']; for (var e = 0; e < events.length; e++) { window[events[e].toLowerCase()] = scene.props[events[e]] || null; } _this.activeScene = scene; } if (router) { window.history.pushState({}, _this.activeScene.id, router[id].path || router[id]); } if (_this.activeScene.ppEffects) { _this.setPPEffects(_this.activeScene.ppEffects); } _this.actions["".concat(id, ":Navigate")].begin(_objectSpread(_objectSpread({ duration: _this.activeScene.props.navigationDuration }, params), {}, { enforce: true })); }); _defineProperty(_this, "findIntersects", function () { _this.raycaster.setFromCamera(_this.mouse, _this.camera); if (_this.activeScene) { if (_this.activeScene.isGLEvents) { _this.intersects = _this.raycaster.intersectObjects(_this.activeScene.visual.children, true); } } else { _this.intersects = _this.raycaster.intersectObjects(_this.visual.children, true); } }); _defineProperty(_this, "onUpdate", function (handler) { return _this.onUpdateHandlers.push(handler); }); _defineProperty(_this, "clearUpdateHandlers", function () { return _this.onUpdateHandlers = []; }); _defineProperty(_this, "isSceneActive", function (id) { return id === _this.activeScene.id; }); _defineProperty(_this, "onMouseMove", function (_ref) { var clientX = _ref.clientX, clientY = _ref.clientY; var _this$container2 = _this.container, offsetWidth = _this$container2.offsetWidth, offsetHeight = _this$container2.offsetHeight; var _this$container$getBo = _this.container.getBoundingClientRect(), top = _this$container$getBo.top, left = _this$container$getBo.left; _this.mouse.x = (clientX - left) / offsetWidth * 2 - 1; _this.mouse.y = -((clientY - top) / offsetHeight) * 2 + 1; if (_this.glRenderer) { if (_this.onMouseStopTimeout) { clearTimeout(_this.onMouseStopTimeout); } _this.onMouseStopTimeout = setTimeout(function () { _this.findIntersects(); if (_this.intersects.length) { var visual = _this.intersects[0].object; if (visual.onMouseOver) visual.onMouseOver(visual); } }, 25); } }); _defineProperty(_this, "onTouchMove", function (_ref2) { var changedTouches = _ref2.changedTouches; var _changedTouches$ = changedTouches[0], clientX = _changedTouches$.clientX, clientY = _changedTouches$.clientY; var _this$container3 = _this.container, offsetWidth = _this$container3.offsetWidth, offsetHeight = _this$container3.offsetHeight; var _this$container$getBo2 = _this.container.getBoundingClientRect(), top = _this$container$getBo2.top, left = _this$container$getBo2.left; _this.touch.x = (clientX - left) / offsetWidth * 2 - 1; _this.touch.y = -((clientY - top) / offsetHeight) * 2 + 1; }); _defineProperty(_this, "onResize", function () { if (_this.onResizeTimeout) { clearTimeout(_this.onResizeTimeout); } _this.onResizeTimeout = setTimeout(function () { var _this$container4 = _this.container, clientWidth = _this$container4.clientWidth, clientHeight = _this$container4.clientHeight; if (_this.glRenderer) { _this.glRenderer.setSize(clientWidth, clientHeight); } if (_this.cssRenderer) { _this.cssRenderer.setSize(clientWidth, clientHeight); } if (_this.isPPEnabled) { _this.composer.setSize(clientWidth, clientHeight); } _this.camera.aspect = clientWidth / clientHeight; _this.camera.updateProjectionMatrix(); _this.setState({ deviceOrientation: (0, _Helpers.getDeviceOrientation)() }); _this.updateLayout(); }, 20); }); _defineProperty(_this, "onClick", function () { if (_this.intersects.length) { var visual = _this.intersects[0].object; if (visual.onClick) visual.onClick(visual); } }); var _withInterface4 = (0, _Helpers.withInterface)(props), camera = _withInterface4.camera, glRenderer = _withInterface4.glRenderer, cssRenderer = _withInterface4.cssRenderer, _postProcessing = _withInterface4.postProcessing, isLayerRendering = _withInterface4.isLayerRendering, isColorManagement = _withInterface4.isColorManagement; _this.state = { deviceOrientation: (0, _Helpers.getDeviceOrientation)(), loading: true, loaded: 0, total: 0 }; _this.children = {}; _this.actions = {}; _this.layers = {}; _this.intersects = []; _this.onUpdateHandlers = []; _this.isPPEnabled = false; _this.isActionsEnabled = true; _this.mouse = new Three.Vector2(-1, -1); _this.touch = new Three.Vector2(-1, -1); _this.visual = new Three.Scene(); _this.isLayerRendering = isLayerRendering; _this.camera = new Three[camera.type](camera.fov, 1, camera.near, camera.far); if (glRenderer) { _this.glRenderer = new Three.WebGLRenderer(glRenderer); _this.glRenderer.setPixelRatio(window.devicePixelRatio); _this.raycaster = new Three.Raycaster(); _this.audioListener = new Three.AudioListener(); _this.camera.add(_this.audioListener); _this.setLoadingManager(); if (glRenderer.autoClear !== undefined) { _this.glRenderer.autoClear = glRenderer.autoClear; } if (isColorManagement === false) { Three.ColorManagement.enabled = false; _this.glRenderer.outputColorSpace = Three.LinearSRGBColorSpace; } } else { _this.state.loading = false; } if (cssRenderer) { _this.cssRenderer = new _CSS3DRenderer.CSS3DRenderer(); } if (_postProcessing) { _this.composer = new _EffectComposer.EffectComposer(_this.glRenderer); _this.composer.addPass(new _EffectComposer.Passes.RenderPass(_this.visual, _this.camera)); } if (window.location.pathname !== '/') { _this.route = window.location.pathname; } _Decoration.Decoration.prototype.manager = _this; _Controller.Controller.prototype.manager = _this; _Action.Action.prototype.manager = _this; _Motion.Motion.prototype.manager = _this; return _this; } _inherits(Nephilim, _Component); return _createClass(Nephilim, [{ key: "componentDidMount", value: function componentDidMount() { var _this2 = this; if (this.glRenderer) { this.glContainer.appendChild(this.glRenderer.domElement); setTimeout(function () { if (!_this2.state.total) { _this2.setState({ loading: false }); } }, 100); } if (this.cssRenderer) { this.cssContainer.appendChild(this.cssRenderer.domElement); } this.setEventListeners(); this.setInitialRoute(); this.update(); this.onResize(); } }, { key: "render", value: function render() { var _this3 = this; var children = this.props.children; var _this$state = this.state, loading = _this$state.loading, loaded = _this$state.loaded, total = _this$state.total, deviceOrientation = _this$state.deviceOrientation; return _react["default"].createElement(_Helpers.NephilimProvider, { value: { deviceOrientation: deviceOrientation, setPPEffects: this.setPPEffects, setLoader: this.setLoader, setVisualState: this.setVisualState, setMotion: this.setMotion, getAction: this.getAction, connectActions: this.connectActions, resetActions: this.resetActions, executeActionsSequence: this.executeActionsSequence, enablePostProcessing: this.enablePostProcessing, enableLayerRendering: this.enableLayerRendering, find: this.find, findAll: this.findAll, navigate: this.navigate, onUpdate: this.onUpdate, clearUpdateHandlers: this.clearUpdateHandlers, isSceneActive: this.isSceneActive } }, _react["default"].createElement("div", { ref: function ref(c) { return _this3.container = c; }, className: 'rtc-container' }, _react["default"].createElement("div", { id: 'portal', className: 'rtc-renderer-container' }), _react["default"].createElement("div", { ref: function ref(c) { return _this3.glContainer = c; }, className: 'rtc-renderer-container' }), _react["default"].createElement("div", { ref: function ref(c) { return _this3.cssContainer = c; }, className: 'rtc-renderer-container' }), loading && _react["default"].createElement("div", { className: 'rtc-loader-container' }, _react["default"].createElement("div", { className: 'rtc-loader-container rtc-gradient' }, _toConsumableArray(Array(7)).map(function (h, hi) { return _react["default"].createElement("div", { key: hi, className: "rtc-hexagon rtc-".concat(hi === 0 ? 'center' : "side".concat(hi)) }, _react["default"].createElement("div", { className: 'rtc-hp1' }), _react["default"].createElement("div", { className: 'rtc-hp1 rtc-hp2' }), _react["default"].createElement("div", { className: 'rtc-hp1 rtc-hp3' })); }), _react["default"].createElement("div", { className: 'rtc-text-loader' }, "Loading resources (", loaded, " of ", total, ")")))), children); } }]); }(_react.Component);