Skip to content

Commit

Permalink
#70 Move graphics options and other customisations to user profile, i…
Browse files Browse the repository at this point in the history
…mprove profile cache tracking mechanism.
  • Loading branch information
aggregate1166877 committed Dec 2, 2021
1 parent 8ef4e99 commit 3d0b44e
Show file tree
Hide file tree
Showing 16 changed files with 220 additions and 118 deletions.
19 changes: 4 additions & 15 deletions app/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import { onDocumentReady, onReadyToBoot, logBootInfo }
from './local/windowLoadListener';

// Game modules.
import scenes from './scenes';
import './local/toast';
import * as THREE from 'three';
import * as CANNON from 'cannon';
Expand All @@ -30,7 +29,6 @@ window.debug.CANNON = CANNON;
// Debug reference to API.
window.debug.api = api;

// const defaultScene = 'logDepthDemo';
const defaultScene = logicalSceneGroup.space;

// Integration tests. Note that these will no longer run by itself. The user
Expand Down Expand Up @@ -73,15 +71,6 @@ if (process.env && process.env.NODE_ENV !== 'production') {
console.groupCollapsed(`Pre-init (build number: ${packageJson.releaseNumber}).`);
logBootInfo(`System boot v${packageJson.releaseNumber}`); // ▓
discoverShaders();

// Register all scenes.
// for (let scene of scenes) {
// console.log('Registering scene', scene.name);
// scene.register();
// }
// Register all camera controllers.
// modeControl.initAll(); // bookm - check that disabling this does not break too many things

console.groupEnd();

onDocumentReady(() => {
Expand Down Expand Up @@ -125,12 +114,12 @@ function initCore() {
// TODO: implement mechanism to always keep track of player ship location
// and auto-save on occasion. This is not however a current priority and
// should only be done once the player actually has systems to explore.
const { defaultShipPosition } = userProfile.getCurrentConfig({
identifier: 'debugTools'
const { currentPosition } = userProfile.getCurrentConfig({
identifier: 'gameState',
});

api.setPlayerShipLocation(defaultShipPosition.location);
api.setPlayerShipRotation(defaultShipPosition.rotation);
api.setPlayerShipLocation(currentPosition.location);
api.setPlayerShipRotation(currentPosition.rotation);
});
}

Expand Down
9 changes: 6 additions & 3 deletions app/lighting/levelLighting.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as THREE from 'three';
import userProfile from '../userProfile';

// Applies lighting from local star. This is here and not in spaceLighting
// because in reality this lighting is all fake - this lighting is in a scene
Expand All @@ -9,9 +10,11 @@ function applyLighting({ scene }) {
const light = new THREE.DirectionalLight(0xffffff, 2);
light.castShadow = true;

// TODO: move into graphics menu as 'horizontal shadow distance (in meters)'.
const shadowCamWidth = 3;
const shadowCamHeight = 3;
const { graphics } = userProfile.getCurrentConfig({
identifier: 'userOptions',
});
const shadowCamWidth = graphics.shadowDistanceMeters;
const shadowCamHeight = graphics.shadowDistanceMeters;

light.shadow.camera.top = shadowCamHeight;
light.shadow.camera.bottom = -shadowCamHeight;
Expand Down
2 changes: 1 addition & 1 deletion app/local/controls.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ let doublePresses;

// Load controls from profile. This will run at boot, and every time the user
// remaps their controls.
userProfile.addCacheListener(({ controls: storedControls }) => {
userProfile.cacheChangeEvent.getEveryChange(({ controls: storedControls }) => {
controls = storedControls.controls;
doublePresses = storedControls.doublePresses;
});
Expand Down
78 changes: 47 additions & 31 deletions app/local/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { startupEvent, getStartupEmitter } from '../emitters';
import contextualInput from './contextualInput';
import { preBootPlaceholder } from '../reactComponents/Modal';
import { logBootInfo } from './windowLoadListener';
import userProfile from '../userProfile';
import {
activateSceneGroup,
renderActiveScenes,
Expand All @@ -28,12 +29,11 @@ import { createRenderer } from './renderer';
import AssetFinder from './AssetFinder';
import OffscreenSkyboxWorker from '../managedWorkers/OffscreenSkyboxWorker';
import ChangeTracker from '../emitters/ChangeTracker';
import { getEnums } from '../userProfile/defaultsConfigs';

// 1 micrometer to 100 billion light years in one scene, with 1 unit = 1 meter?
// preposterous! and yet...
const NEAR = 0.001, FAR = 1e27;
let SCREEN_WIDTH = window.innerWidth;
let SCREEN_HEIGHT = window.innerHeight;

// Used to generate delta.
let deltaPrevTime = Date.now();
Expand Down Expand Up @@ -94,10 +94,6 @@ window.$options = {
repeatRate: 50,
};
window.$displayOptions = {
// Rendering resolution scale. Great for developers and wood PCs alike.
// TODO: Call this "Resolution quality (Supersampling)" in the graphics menu. // 20% 50% 75% 'match native' 150% 200% 400%
resolutionScale: 1,

limitFps: false,
// On my machine, the frame limiter itself actually causes a 9% performance
// drop when enabled, hence the 1.09. May need to actually track this
Expand All @@ -108,10 +104,6 @@ window.$displayOptions = {
window.$webWorkers = {
offscreenSkybox: new OffscreenSkyboxWorker(),
};
// TODO: implement anti-aliasing (and other options) in the graphics menu.
// window.$primaryRendererParams = {
// antialias: true,
// };
// The preBootPlaceholder stores functions that match the actual model object.
// Calling those functions queue them as requests. Once the menu system has
// booted, all requests are then honored as the actual modal functions.
Expand Down Expand Up @@ -182,6 +174,11 @@ function init({ defaultScene }) {
console.log('Initialising core.');
logBootInfo('Core init start');

// User configurations.
const { debug, display, graphics } = userProfile.getCurrentConfig({
identifier: 'userOptions'
});

// Controls.
contextualInput.init();

Expand All @@ -193,35 +190,39 @@ function init({ defaultScene }) {
$modal.alert('Error: canvas not available; no rendering will work.');
}

const camera = new THREE.PerspectiveCamera(56.25, SCREEN_WIDTH / SCREEN_HEIGHT, NEAR, FAR);
const camera = new THREE.PerspectiveCamera(
display.fieldOfView, window.innerWidth / window.innerHeight, NEAR, FAR
);
const primaryRenderer = createRenderer({
initialisation: {
canvas: primaryCanvas,
// This is unfortunately only done during init, so changing at runtime
// requires recreating the whole renderer.
antialias: graphics.antialias,
},
options: {
width: window.innerWidth,
height: window.innerHeight,
shadowMapEnabled: true,
// TODO: move into graphics are 'soft shadows'.
shadowMapType: THREE.PCFSoftShadowMap,
shadowMapEnabled: graphics.enableShadows,
shadowMapType: graphics.shadowType,
devicePixelRatio: window.devicePixelRatio,
toneMapping: display.toneMapping,
}
});
// const skyboxRenderer = createRenderer('skyboxRenderer', {
// doNotCreateElement: true,
// });

AssetFinder.getStarCatalogWFallback({
name: 'bsc5p_3d_min',
fallbackName: 'constellation_test',
callback: (error, fileName, parentDir) => {
console.log('catalog path:', { error, fileName, parentDir });
$webWorkers.offscreenSkybox.init({
canvas: starfieldCanvas,
width: 2048, // TODO: move skybox resolution to graphics menu.
height: 2048,
width: graphics.skyboxResolution,
height: graphics.skyboxResolution,
skyboxAntialias: graphics.skyboxAntialias,
pixelRatio: window.devicePixelRatio,
catalogPath: `../${parentDir}/${fileName}`,
debugSides: debug.debugSkyboxSides,
debugCorners: debug.debugSkyboxCorners,
});
},
});
Expand All @@ -240,6 +241,7 @@ function init({ defaultScene }) {

animate();
startupEmitter.emit(startupEvent.firstFrameRendered);
updatePrimaryRendererSizes();
logBootInfo('Self-test pass');
}
});
Expand All @@ -252,12 +254,6 @@ function init({ defaultScene }) {
}

function initView({ primaryRenderer, camera }) {
// TODO: make FOV adjustable in graphics menu.
// TODO: all option to press Alt that temporarily zoom in by decreasing perspective.
// const camera = new THREE.PerspectiveCamera(56.25, SCREEN_WIDTH / SCREEN_HEIGHT, NEAR, FAR);
// camera.position.copy(new THREE.Vector3(0, 0, 0));
// camera.rotation.setFromVector3(new THREE.Vector3(0, 0, 0));
// levelScene.add(camera);
const ptrLockControls = new PointerLockControls(camera, document.body);

// Postprocessing.
Expand Down Expand Up @@ -318,19 +314,26 @@ function initPlayer() {

function updatePrimaryRendererSizes() {
if (!$game.primaryRenderer) {
console.error('Cannot update primary renderer: not ready.');
return;
}

// Recalculate size for both renderers when screen size or split location changes
SCREEN_WIDTH = window.innerWidth;
SCREEN_HEIGHT = window.innerHeight;
let screenWidth = window.innerWidth;
let screenHeight = window.innerHeight;

$game.primaryRenderer.setSize( SCREEN_WIDTH * $displayOptions.resolutionScale, SCREEN_HEIGHT * $displayOptions.resolutionScale);
const { graphics } = userProfile.getCurrentConfig({
identifier: 'userOptions',
});

const scale = graphics.resolutionScale;
$game.primaryRenderer.setSize(screenWidth * scale, screenHeight * scale);
$game.primaryRenderer.domElement.style.width = '100%';
$game.primaryRenderer.domElement.style.height = '100%';
$game.camera.aspect = SCREEN_WIDTH / SCREEN_HEIGHT;
$game.camera.aspect = screenWidth / screenHeight;
$game.camera.updateProjectionMatrix();

console.log('window resized to:', SCREEN_WIDTH, SCREEN_HEIGHT);
console.log('window resized to:', screenWidth, screenHeight);
}

/**
Expand Down Expand Up @@ -394,6 +397,19 @@ $game.playerShip.getOnce(() => {
// TODO: remove me once the game is more stable.
startupEmitter.on(startupEvent.ready, () => {
closeLoadingScreen();

// For some reason the game takes nearly 5x longer to boot in fullscreen...
// slower boot happens even if the res scale is at 0.1 (less than 200x200
// effective res), albeit not as bad. So I guess we wait until fully booted
// before switching. Might need to create tiny splash in future that covers
// the whole window during boot.
userProfile.cacheChangeEvent.getOnce(({ userOptions }) => {
const userDisplayChoice = userOptions.display.displayMode;
const displayEnum = getEnums({ identifier: 'userOptions' }).display;
if (userDisplayChoice === displayEnum.displayMode.borderlessFullscreen) {
nw.Window.get().enterFullscreen();
}
});
});

// Waits for the game to load so that it can trigger startupEvent.ready.
Expand Down
11 changes: 1 addition & 10 deletions app/local/renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ function createRenderer({
options = {},
} = { initialisation: {}, options: {} }) {
const renderer = new THREE.WebGLRenderer({
antialias: true,
logarithmicDepthBuffer: true,
alpha: true,
...initialisation,
Expand All @@ -18,17 +17,9 @@ function createRenderer({

renderer.setPixelRatio(options.devicePixelRatio);
renderer.setSize(options.width, options.height);

renderer.shadowMap.enabled = !!options.shadowMapEnabled;
renderer.shadowMap.type = options.shadowMapType;

// TODO: give options for shaders 'colourful' vs 'filmic'.
// renderer.toneMapping = THREE.ACESFilmicToneMapping;
// renderer.toneMapping = THREE.NoToneMapping;

// TODO: add to graphics menu.
// renderer.gammaOutput = true;
// renderer.gammaFactor = 2.2;
renderer.toneMapping = options.toneMapping;

return renderer;
}
Expand Down
4 changes: 1 addition & 3 deletions app/logicalSceneGroup/space.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,7 @@ const space = new LogicalSceneGroup({

const spaceWorld = physics.initSpacePhysics({ scene: cache.levelScene, debug: true });

// TODO: replace this with a mechanism whereby this retrieved from the
// LSG manager. These vars are currently used by shipPilot,
// speedTracker, and api.setPlayerShipLocation.
// TODO: make this work with the new ChangeTracker mechanism.
// ----------------------------------------------------------------------
$game.spaceScene = spaceScene;
$game.levelScene = levelScene;
Expand Down
17 changes: 12 additions & 5 deletions app/managedWorkers/OffscreenSkyboxWorker.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import ManagedWorker from './ManagedWorker';
import * as THREE from 'three';
import Unit from '../local/Unit';
import { logBootInfo } from '../local/windowLoadListener';

export default class OffscreenSkyboxWorker extends ManagedWorker {
constructor() {
Expand All @@ -26,7 +27,7 @@ export default class OffscreenSkyboxWorker extends ManagedWorker {
}
});

this.addWorkerListener('renderFace', ({ error, value }) => {
this.addWorkerListener('renderFace', ({ value }) => {
const { x, y, z, sideNumber, tag } = value;
if (tag === 'internal cascade') {
// Caution: this is request**Post**AnimationFrame, not
Expand All @@ -48,18 +49,22 @@ export default class OffscreenSkyboxWorker extends ManagedWorker {
this.applySkyboxFromCache();
}
}
)
);
}
);
}
});

this.addWorkerListener('testHeavyPayload', ({ error, value }) => {
console.log('testHeavyPayload:', value.length, 'KB transferred.');
console.log('testHeavyPayload:', value.length, 'KB transferred. Error:', error);
});
}

init({ canvas, width, height, pixelRatio, catalogPath }) {
init({
canvas, width, height, skyboxAntialias, pixelRatio, catalogPath,
debugSides, debugCorners,
}) {
logBootInfo('Scanning skies');
if (!'transferControlToOffscreen' in canvas) {
console.error('offscreenControl required for skybox to render.');
return $modal.alert('Error: offscreen canvas not available; stars will not render.');
Expand All @@ -72,9 +77,11 @@ export default class OffscreenSkyboxWorker extends ManagedWorker {
drawingSurface: offscreenControl,
width,
height,
skyboxAntialias,
pixelRatio,
catalogPath,
// debugCorners: true,
debugSides,
debugCorners,
}, [ offscreenControl ]);
}

Expand Down
2 changes: 1 addition & 1 deletion app/reactComponents/Menu/DebugTools.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export default class DebugTools extends React.Component {

loadShipPos = () => {
const positions = userProfile.getCurrentConfig({
identifier: 'debugTools'
identifier: 'debugTools',
}).storedShipPositions;

$modal.listPrompt({
Expand Down
Loading

0 comments on commit 3d0b44e

Please sign in to comment.