diff --git a/src/html/helmetOverlay.html b/src/html/helmetOverlay.html index acb2f1c70..5c7e6b6cd 100644 --- a/src/html/helmetOverlay.html +++ b/src/html/helmetOverlay.html @@ -1,7 +1,6 @@

-

\ No newline at end of file diff --git a/src/shaders/telluricPlanetMaterial/vertex.glsl b/src/shaders/telluricPlanetMaterial/vertex.glsl index 6704161f1..9c4f3e39d 100644 --- a/src/shaders/telluricPlanetMaterial/vertex.glsl +++ b/src/shaders/telluricPlanetMaterial/vertex.glsl @@ -9,7 +9,7 @@ uniform mat4 normalMatrix; uniform vec3 planetPosition; -uniform mat4 planetInverseRotationMatrix; +uniform mat4 inversePlanetWorldMatrix; varying vec3 vPositionW; varying vec3 vNormalW; @@ -32,13 +32,13 @@ void main() { vPositionW = vec3(world * vec4(position, 1.0)); vNormalW = normalize(mat3(normalMatrix) * normal); - vPosition = vPositionW - planetPosition; + vPosition = vec3(inversePlanetWorldMatrix * vec4(vPositionW, 1.0)); vLocalPosition = position; - vUnitSamplePoint = mat3(planetInverseRotationMatrix) * normalize(vPosition); - vSamplePointScaled = mat3(planetInverseRotationMatrix) * vPosition / 1000e3; - vSphereNormalW = mat3(normalMatrix) * vUnitSamplePoint; - vSamplePoint = mat3(planetInverseRotationMatrix) * vPosition; + vUnitSamplePoint = normalize(vPosition); + vSamplePointScaled = vPosition / 1000e3; + vSphereNormalW = normalize(vPosition); + vSamplePoint = vPosition; vNormal = normal; } diff --git a/src/ts/architecture/Readme.md b/src/ts/architecture/Readme.md new file mode 100644 index 000000000..30f585b2e --- /dev/null +++ b/src/ts/architecture/Readme.md @@ -0,0 +1,28 @@ +# Architecture of interface spanning from simple Transforms to complex Celestial bodies and Space stations: + +![img.png](img.png) + +This folder contains all the abstraction necessary to the architecture of the image. + +This means all the node except the leaves (upper nodes) which are the actual concrete implementation of celestial bodies and space stations. + +It all starts with simple `Transformable` and `BoundingSphere`: +those are simple objects that possess a BaylonJS `TransformNode` for their position, rotation, scaling and a bounding volume to make simple calculations for distances. + +An `OrbitalObject` builds on top of this by adding the notion of orbit. They possess `OrbitProperties` that describes their motion around their `parent` which can be null in the case of some objects (think like stars). + +`OrbitalObject` also possess `PhysicalProperties` that complement the `OrbitProperties` with information such as mass, axial tilting and rotation period. + +To sum up, an `OrbitalObject` is an object that can rotate around another `OrbitalObject` and rotate on itself. + +`CelestialBody` builds up on top of `OrbitalObject` by adding the notion of `BODY_TYPE` and `radius` that is expected from spherical objects. + +`CelestialBody` are spherical orbital objects that encompasses both planets and stellar objects. +They can have specific post-processes applied to them (like atmosphere, clouds, rings...), which is why they also implement `HasPostProcesses`. + +`StellarObject` builds on top of `CelestialBody` by adding a `PointLight` that is used to light up the scene. They also have a `STELLAR_TYPE` that describes their type (star, black hole, neutron star). + +`Planet` builds on top of `CelestialBody` by adding new `PlanetPhysicalProperties` that describe their temperature and pressure. They also keep track of their number of moons. + +The other nodes are the concrete implementations of all these abstractions. +They can be found in their respective folders (`planets` for `TelluricPlanet` and `GasPlanet`, `stellarObjects` for `Star`, `BlackHole` and `NeutronStar`, and spaceStations for `SpaceStation`). \ No newline at end of file diff --git a/src/ts/architecture/boundingSphere.ts b/src/ts/architecture/boundingSphere.ts new file mode 100644 index 000000000..ccfdd6246 --- /dev/null +++ b/src/ts/architecture/boundingSphere.ts @@ -0,0 +1,3 @@ +export interface BoundingSphere { + getBoundingRadius(): number; +} diff --git a/src/ts/architecture/canHaveRings.ts b/src/ts/architecture/canHaveRings.ts new file mode 100644 index 000000000..ef751257c --- /dev/null +++ b/src/ts/architecture/canHaveRings.ts @@ -0,0 +1,5 @@ +import { RingsUniforms } from "../postProcesses/rings/ringsUniform"; + +export interface CanHaveRings { + getRingsUniforms(): RingsUniforms | null; +} diff --git a/src/ts/architecture/celestialBody.ts b/src/ts/architecture/celestialBody.ts new file mode 100644 index 000000000..9fcbded53 --- /dev/null +++ b/src/ts/architecture/celestialBody.ts @@ -0,0 +1,18 @@ +import { OrbitalObject, OrbitalObjectModel } from "./orbitalObject"; +import { HasPostProcesses } from "./hasPostProcesses"; +import { CanHaveRings } from "./canHaveRings"; +import { BODY_TYPE } from "../model/common"; + +export interface CelestialBody extends OrbitalObject, CanHaveRings, HasPostProcesses { + model: CelestialBodyModel; + + /** + * Returns the radius of the celestial body + */ + getRadius(): number; +} + +export interface CelestialBodyModel extends OrbitalObjectModel { + readonly bodyType: BODY_TYPE; + readonly radius: number; +} diff --git a/src/ts/architecture/hasPostProcesses.ts b/src/ts/architecture/hasPostProcesses.ts new file mode 100644 index 000000000..29cb70862 --- /dev/null +++ b/src/ts/architecture/hasPostProcesses.ts @@ -0,0 +1,5 @@ +import { PostProcessType } from "../postProcesses/postProcessTypes"; + +export interface HasPostProcesses { + postProcesses: PostProcessType[]; +} diff --git a/src/ts/architecture/img.png b/src/ts/architecture/img.png new file mode 100644 index 000000000..c01a63bce Binary files /dev/null and b/src/ts/architecture/img.png differ diff --git a/src/ts/architecture/orbitalObject.ts b/src/ts/architecture/orbitalObject.ts new file mode 100644 index 000000000..0c25f5a34 --- /dev/null +++ b/src/ts/architecture/orbitalObject.ts @@ -0,0 +1,94 @@ +import { Transformable } from "./transformable"; +import { BoundingSphere } from "./boundingSphere"; +import { OrbitProperties } from "../orbit/orbitProperties"; +import { rotateVector3AroundInPlace } from "../utils/algebra"; +import { Quaternion, Vector3 } from "@babylonjs/core/Maths/math"; +import { getRotationQuaternion, setRotationQuaternion, translate } from "../uberCore/transforms/basicTransform"; +import { OrbitalObjectPhysicalProperties } from "./physicalProperties"; + +export interface OrbitalObject extends Transformable, BoundingSphere { + name: string; + + model: OrbitalObjectModel; + + getRotationAxis(): Vector3; + + getOrbitProperties(): OrbitProperties; + + getPhysicalProperties(): OrbitalObjectPhysicalProperties; + + getTypeName(): string; + + parent: OrbitalObject | null; +} + +export class OrbitalObject { + static getRotationAxis(object: OrbitalObject) { + return object.getTransform().up; + } + + static computeNextOrbitalPosition(object: OrbitalObject, deltaTime: number) { + const orbit = object.getOrbitProperties(); + if (orbit.period === 0 || object.parent === null) return object.getTransform().getAbsolutePosition(); + + const barycenter = object.parent.getTransform().getAbsolutePosition(); + + // enforce distance to orbit center + const oldPosition = object.getTransform().getAbsolutePosition().subtract(barycenter); + const newPosition = oldPosition.clone(); + + // rotate the object around the barycenter of the orbit, around the normal to the orbital plane + const dtheta = (2 * Math.PI * deltaTime) / orbit.period; + rotateVector3AroundInPlace(newPosition, barycenter, orbit.normalToPlane, dtheta); + + newPosition.normalize().scaleInPlace(orbit.radius); + + // enforce orbital plane + const correctionAxis = Vector3.Cross(orbit.normalToPlane, newPosition.normalizeToNew()); + const correctionAngle = 0.5 * Math.PI - Vector3.GetAngleBetweenVectors(orbit.normalToPlane, newPosition.normalizeToNew(), correctionAxis); + newPosition.applyRotationQuaternionInPlace(Quaternion.RotationAxis(correctionAxis, correctionAngle)); + + return newPosition.addInPlace(barycenter); + } + + static updateOrbitalPosition(object: OrbitalObject, deltaTime: number) { + const orbit = object.getOrbitProperties(); + if (orbit.period === 0 || object.parent === null) return; + + const oldPosition = object.getTransform().getAbsolutePosition(); + const newPosition = OrbitalObject.computeNextOrbitalPosition(object, deltaTime); + translate(object.getTransform(), newPosition.subtractInPlace(oldPosition)); + } + + static getDeltaTheta(object: OrbitalObject, deltaTime: number) { + if (object.getPhysicalProperties().rotationPeriod === 0) return 0; + return (2 * Math.PI * deltaTime) / object.getPhysicalProperties().rotationPeriod; + } + + /** + * Updates the rotation of the body around its axis + * @param object + * @param deltaTime The time elapsed since the last update + * @returns The elapsed angle of rotation around the axis + */ + static updateRotation(object: OrbitalObject, deltaTime: number) { + const dtheta = OrbitalObject.getDeltaTheta(object, deltaTime); + if (dtheta === 0) return; + + const elementaryRotationQuaternion = Quaternion.RotationAxis(OrbitalObject.getRotationAxis(object), dtheta); + const newQuaternion = elementaryRotationQuaternion.multiply(getRotationQuaternion(object.getTransform())); + + setRotationQuaternion(object.getTransform(), newQuaternion); + } +} + +export interface OrbitalObjectModel { + rng: (step: number) => number; + seed: number; + + orbit: OrbitProperties; + physicalProperties: OrbitalObjectPhysicalProperties; + + readonly parentBody: OrbitalObjectModel | null; + readonly childrenBodies: OrbitalObjectModel[]; +} diff --git a/src/ts/architecture/physicalProperties.ts b/src/ts/architecture/physicalProperties.ts new file mode 100644 index 000000000..3ef753687 --- /dev/null +++ b/src/ts/architecture/physicalProperties.ts @@ -0,0 +1,24 @@ +export type OrbitalObjectPhysicalProperties = { + mass: number; + rotationPeriod: number; + axialTilt: number; +}; + +export type StarPhysicalProperties = OrbitalObjectPhysicalProperties & { + temperature: number; +}; + +export type BlackHolePhysicalProperties = OrbitalObjectPhysicalProperties & { + accretionDiskRadius: number; +}; + +export type PlanetPhysicalProperties = OrbitalObjectPhysicalProperties & { + minTemperature: number; + maxTemperature: number; + pressure: number; +}; + +export type TelluricPlanetPhysicalProperties = PlanetPhysicalProperties & { + waterAmount: number; + oceanLevel: number; +}; diff --git a/src/ts/architecture/planet.ts b/src/ts/architecture/planet.ts new file mode 100644 index 000000000..f574ff7fa --- /dev/null +++ b/src/ts/architecture/planet.ts @@ -0,0 +1,18 @@ +import { Camera } from "@babylonjs/core/Cameras/camera"; +import { CelestialBody, CelestialBodyModel } from "./celestialBody"; +import { PlanetPhysicalProperties } from "./physicalProperties"; +import { Transformable } from "./transformable"; + +export interface Planet extends CelestialBody { + model: PlanetModel; + + updateMaterial(controller: Camera, stellarObjects: Transformable[], deltaTime: number): void; +} + +export interface PlanetModel extends CelestialBodyModel { + physicalProperties: PlanetPhysicalProperties; + + nbMoons: number; + + getApparentRadius(): number; +} diff --git a/src/ts/architecture/stellarObject.ts b/src/ts/architecture/stellarObject.ts new file mode 100644 index 000000000..b1b88df0c --- /dev/null +++ b/src/ts/architecture/stellarObject.ts @@ -0,0 +1,13 @@ +import { PointLight } from "@babylonjs/core/Lights/pointLight"; +import { CelestialBody, CelestialBodyModel } from "./celestialBody"; +import { STELLAR_TYPE } from "../stellarObjects/common"; + +export interface StellarObject extends CelestialBody { + model: StellarObjectModel; + + getLight(): PointLight; +} + +export interface StellarObjectModel extends CelestialBodyModel { + stellarType: STELLAR_TYPE; +} diff --git a/src/ts/architecture/transformable.ts b/src/ts/architecture/transformable.ts new file mode 100644 index 000000000..10c74de25 --- /dev/null +++ b/src/ts/architecture/transformable.ts @@ -0,0 +1,7 @@ +import { TransformNode } from "@babylonjs/core/Meshes"; + +export interface Transformable { + getTransform(): TransformNode; + + dispose(): void; +} diff --git a/src/ts/assets.ts b/src/ts/assets.ts index d133bfd7b..fac4de48c 100644 --- a/src/ts/assets.ts +++ b/src/ts/assets.ts @@ -19,6 +19,7 @@ import plumeParticle from "../asset/textures/plume.png"; import atmosphereLUT from "../shaders/textures/atmosphereLUT.glsl"; +import seamlessPerlin from "../asset/perlin.png"; import spaceship from "../asset/spaceship/spaceship2.glb"; import shipCarrier from "../asset/spacestation/shipcarrier.glb"; import banana from "../asset/banana/banana.glb"; @@ -70,6 +71,7 @@ export class Assets { static AtmosphereLUT: ProceduralTexture; + static SeamlessPerlin: Texture; private static Spaceship: Mesh; private static EndeavorSpaceship: Mesh; private static Spacestation: Mesh; @@ -107,6 +109,7 @@ export class Assets { Assets.manager.addTextureTask("PlumeParticle", plumeParticle).onSuccess = (task) => (Assets.PlumeParticle = task.texture); + Assets.manager.addTextureTask("SeamlessPerlin", seamlessPerlin).onSuccess = (task) => (Assets.SeamlessPerlin = task.texture); Assets.AtmosphereLUT = new ProceduralTexture("atmosphereLUT", 100, { fragmentSource: atmosphereLUT }, scene, undefined, false, false); Assets.AtmosphereLUT.refreshRate = 0; diff --git a/src/ts/bodies/abstractBody.ts b/src/ts/bodies/abstractBody.ts deleted file mode 100644 index f868362e7..000000000 --- a/src/ts/bodies/abstractBody.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { BodyModel } from "../model/common"; -import { Scene } from "@babylonjs/core/scene"; -import { AbstractObject } from "./abstractObject"; - -export abstract class AbstractBody extends AbstractObject { - abstract readonly model: BodyModel; - - /** - * An abstract representation of a celestial body - * @param name the name of the celestial body - * @param parentBody the parent body of this body - * @param scene - */ - protected constructor(name: string, scene: Scene, parentBody?: AbstractBody) { - super(name, scene, parentBody); - } - - /** - * Returns the radius of the celestial body - */ - public getRadius(): number { - return this.model.radius; - } - - /** - * Returns apparent radius of the celestial body (can be greater than the actual radius for example : ocean) - */ - public override getBoundingRadius(): number { - return this.getRadius(); - } - - /** - * Returns the diameter of the celestial body - */ - public getDiameter(): number { - return 2 * this.getRadius(); - } -} diff --git a/src/ts/bodies/abstractObject.ts b/src/ts/bodies/abstractObject.ts deleted file mode 100644 index 157ec122a..000000000 --- a/src/ts/bodies/abstractObject.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { Vector3, Quaternion } from "@babylonjs/core/Maths/math"; -import { BaseModel } from "../model/common"; -import { Scene } from "@babylonjs/core/scene"; -import { PostProcessType } from "../postProcesses/postProcessTypes"; -import { BaseObject, Common } from "./common"; -import { TransformNode } from "@babylonjs/core/Meshes"; -import { getRotationQuaternion, setRotationQuaternion, translate } from "../uberCore/transforms/basicTransform"; -import { Camera } from "@babylonjs/core/Cameras/camera"; -import { PhysicsAggregate } from "@babylonjs/core/Physics/v2/physicsAggregate"; - -import { OrbitalObject } from "../orbit/orbit"; -import { PhysicsShapeType } from "@babylonjs/core/Physics/v2/IPhysicsEnginePlugin"; -import { rotateVector3AroundInPlace } from "../utils/algebra"; - -export abstract class AbstractObject implements OrbitalObject, BaseObject, Common { - private readonly transform: TransformNode; - - readonly aggregate: PhysicsAggregate; - - readonly postProcesses: PostProcessType[] = []; - - //TODO: make an universal clock ?? or not it could be funny - private internalClock = 0; - - readonly name: string; - - abstract readonly model: BaseModel; - - readonly parentObject: OrbitalObject | null; - - /** - * An abstract representation of a celestial body - * @param name the name of the celestial body - * @param parentObject the parent object of this object - * @param scene - */ - protected constructor(name: string, scene: Scene, parentObject?: OrbitalObject) { - this.name = name; - - this.parentObject = parentObject ?? null; - - this.transform = new TransformNode(name, scene); - - this.aggregate = new PhysicsAggregate( - this.getTransform(), - PhysicsShapeType.CONTAINER, - { - mass: 0, - restitution: 0.2 - }, - scene - ); - this.aggregate.body.setMassProperties({ inertia: Vector3.Zero(), mass: 0 }); - this.aggregate.body.disablePreStep = false; - } - - public getTransform(): TransformNode { - return this.transform; - } - - public abstract getBoundingRadius(): number; - - public abstract getTypeName(): string; - - /** - * Returns the axis of rotation of the body - */ - public getRotationAxis(): Vector3 { - return this.transform.up; - } - - /** - * Returns the internal clock of the body (in seconds) - * @returns the internal clock of the body (in seconds) - */ - public getInternalClock(): number { - return this.internalClock; - } - - /** - * Updates the internal clock of the body by adding the time elapsed since the last update - * @param deltaTime the time elapsed since the last update - */ - public updateInternalClock(deltaTime: number): void { - this.internalClock += deltaTime; - } - - public computeNextOrbitalPosition(deltaTime: number) { - if (this.model.orbit.period === 0 || this.parentObject === null) return this.transform.getAbsolutePosition(); - - const barycenter = this.parentObject.getTransform().getAbsolutePosition(); - - // enforce distance to orbit center - const oldPosition = this.transform.getAbsolutePosition().subtract(barycenter); - const newPosition = oldPosition.clone(); - - // rotate the object around the barycenter of the orbit, around the normal to the orbital plane - const dtheta = (2 * Math.PI * deltaTime) / this.model.orbit.period; - rotateVector3AroundInPlace(newPosition, barycenter, this.model.orbit.normalToPlane, dtheta); - - newPosition.normalize().scaleInPlace(this.model.orbit.radius); - - // enforce orbital plane - const correctionAxis = Vector3.Cross(this.model.orbit.normalToPlane, newPosition.normalizeToNew()); - const correctionAngle = 0.5 * Math.PI - Vector3.GetAngleBetweenVectors(this.model.orbit.normalToPlane, newPosition.normalizeToNew(), correctionAxis); - newPosition.applyRotationQuaternionInPlace(Quaternion.RotationAxis(correctionAxis, correctionAngle)); - - return newPosition.addInPlace(barycenter); - } - - public updateOrbitalPosition(deltaTime: number) { - if (this.model.orbit.period === 0 || this.parentObject === null) return; - - const oldPosition = this.transform.getAbsolutePosition(); - const newPosition = this.computeNextOrbitalPosition(deltaTime); - translate(this.transform, newPosition.subtractInPlace(oldPosition)); - } - - public getDeltaTheta(deltaTime: number) { - if (this.model.physicalProperties.rotationPeriod === 0) return 0; - return (2 * Math.PI * deltaTime) / this.model.physicalProperties.rotationPeriod; - } - - /** - * Updates the rotation of the body around its axis - * @param deltaTime The time elapsed since the last update - * @returns The elapsed angle of rotation around the axis - */ - public updateRotation(deltaTime: number) { - const dtheta = this.getDeltaTheta(deltaTime); - if (dtheta === 0) return; - - const elementaryRotationQuaternion = Quaternion.RotationAxis(this.getRotationAxis(), dtheta); - const newQuaternion = elementaryRotationQuaternion.multiply(getRotationQuaternion(this.transform)); - - setRotationQuaternion(this.transform, newQuaternion); - } - - public abstract computeCulling(camera: Camera): void; - - public dispose(): void { - this.transform.dispose(); - } -} diff --git a/src/ts/bodies/common.ts b/src/ts/bodies/common.ts deleted file mode 100644 index 1afe90a78..000000000 --- a/src/ts/bodies/common.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { Camera } from "@babylonjs/core/Cameras/camera"; -import { Transformable } from "../uberCore/transforms/basicTransform"; -import { PostProcessType } from "../postProcesses/postProcessTypes"; - -export interface Common { - computeCulling(camera: Camera): void; -} - -export interface BoundingSphere extends Transformable { - /** - * Returns apparent radius of the celestial body (can be greater than the actual radius for example : ocean) - */ - getBoundingRadius(): number; -} - -export interface BaseObject extends BoundingSphere { - name: string; - postProcesses: PostProcessType[]; -} diff --git a/src/ts/bodies/cullable.ts b/src/ts/bodies/cullable.ts new file mode 100644 index 000000000..a21f0c403 --- /dev/null +++ b/src/ts/bodies/cullable.ts @@ -0,0 +1,5 @@ +import { Camera } from "@babylonjs/core/Cameras/camera"; + +export interface Cullable { + computeCulling(camera: Camera): void; +} \ No newline at end of file diff --git a/src/ts/defaultController/defaultControls.ts b/src/ts/defaultController/defaultControls.ts index 915fea530..d261898aa 100644 --- a/src/ts/defaultController/defaultControls.ts +++ b/src/ts/defaultController/defaultControls.ts @@ -90,4 +90,9 @@ export class DefaultControls implements Controls { public addInput(input: Input): void { this.inputs.push(input); } + + dispose() { + this.transform.dispose(); + this.camera.dispose(); + } } diff --git a/src/ts/index.ts b/src/ts/index.ts index 5815a6c39..7ba4f0b5a 100644 --- a/src/ts/index.ts +++ b/src/ts/index.ts @@ -11,8 +11,8 @@ import { Vector3 } from "@babylonjs/core/Maths/math.vector"; import { Color3 } from "@babylonjs/core/Maths/math.color"; import { ShipControls } from "./spaceship/shipControls"; import { PostProcessType } from "./postProcesses/postProcessTypes"; -import { TelluricPlanemoModel } from "./planemos/telluricPlanemo/telluricPlanemoModel"; -import { GasPlanetModel } from "./planemos/gasPlanet/gasPlanetModel"; +import { TelluricPlanetModel } from "./planets/telluricPlanet/telluricPlanetModel"; +import { GasPlanetModel } from "./planets/gasPlanet/gasPlanetModel"; import { getForwardDirection, getRotationQuaternion, setRotationQuaternion, translate } from "./uberCore/transforms/basicTransform"; import { parsePercentageFrom01, parseSpeed } from "./utils/parseToStrings"; @@ -21,7 +21,7 @@ import { Mouse } from "./inputs/mouse"; import { Keyboard } from "./inputs/keyboard"; import { StarModel } from "./stellarObjects/star/starModel"; import { RingsUniforms } from "./postProcesses/rings/ringsUniform"; -import { getMoonSeed } from "./planemos/common"; +import { getMoonSeed } from "./planets/common"; import { Gamepad } from "./inputs/gamepad"; import { CharacterControls } from "./spacelegs/characterControls"; @@ -119,7 +119,7 @@ terminaModel.orbit.radius = 50 * sunModel.radius; terminaModel.orbit.period = 60 * 60; const termina = StarSystemHelper.makeStar(starSystem, terminaModel);*/ -const planetModel = new TelluricPlanemoModel(0.4233609183800225, sunModel); +const planetModel = new TelluricPlanetModel(0.4233609183800225, sunModel); planetModel.physicalProperties.minTemperature = -55; planetModel.physicalProperties.maxTemperature = 30; @@ -131,11 +131,10 @@ const planet = StarSystemHelper.makeTelluricPlanet(starSystem, planetModel); planet.model.ringsUniforms = new RingsUniforms(planet.model.rng); planet.postProcesses.push(PostProcessType.RING); - //const spacestation = new SpaceStation(starSystemView.scene, planet); //starSystemView.getStarSystem().addSpaceStation(spacestation); -const moonModel = new TelluricPlanemoModel(getMoonSeed(planetModel, 0), planetModel); +const moonModel = new TelluricPlanetModel(getMoonSeed(planetModel, 0), planetModel); moonModel.physicalProperties.mass = 2; moonModel.physicalProperties.rotationPeriod = 7 * 60 * 60; moonModel.physicalProperties.minTemperature = -180; @@ -156,7 +155,7 @@ moon.material.setTexture("plainNormalMap", Assets.DirtNormalMap); moon.material.setTexture("bottomNormalMap", Assets.DirtNormalMap); moon.material.updateConstants(); -const aresModel = new TelluricPlanemoModel(0.3725, sunModel); +const aresModel = new TelluricPlanetModel(0.3725, sunModel); aresModel.physicalProperties.mass = 7; aresModel.physicalProperties.rotationPeriod = (24 * 60 * 60) / 30; aresModel.physicalProperties.minTemperature = -30; @@ -214,13 +213,13 @@ if (aresAtmosphere) { document.addEventListener("keydown", (e) => { if (engine.isPaused()) return; - if(e.key === "x") { + if (e.key === "x") { let nbVertices = 0; let nbInstances = 0; - planet.sides.forEach(side => { + planet.sides.forEach((side) => { side.executeOnEveryChunk((chunk) => { nbVertices += Settings.VERTEX_RESOLUTION * Settings.VERTEX_RESOLUTION; - chunk.instancePatches.forEach(patch => { + chunk.instancePatches.forEach((patch) => { nbInstances += patch.getNbInstances(); }); }); diff --git a/src/ts/mandelbulb/mandelbulb.ts b/src/ts/mandelbulb/mandelbulb.ts index c95a96eb0..23790691a 100644 --- a/src/ts/mandelbulb/mandelbulb.ts +++ b/src/ts/mandelbulb/mandelbulb.ts @@ -1,14 +1,27 @@ import { Camera } from "@babylonjs/core/Cameras/camera"; import { MandelbulbModel } from "./mandelbulbModel"; -import { AbstractBody } from "../bodies/abstractBody"; -import { Planemo } from "../planemos/planemo"; -import { UberScene } from "../uberCore/uberScene"; import { PostProcessType } from "../postProcesses/postProcessTypes"; import { Axis } from "@babylonjs/core/Maths/math.axis"; +import { CelestialBody } from "../architecture/celestialBody"; +import { TransformNode } from "@babylonjs/core/Meshes"; +import { Scene } from "@babylonjs/core/scene"; +import { OrbitProperties } from "../orbit/orbitProperties"; +import { RingsUniforms } from "../postProcesses/rings/ringsUniform"; +import { Vector3 } from "@babylonjs/core/Maths/math.vector"; +import { Cullable } from "../bodies/cullable"; +import { OrbitalObjectPhysicalProperties } from "../architecture/physicalProperties"; + +export class Mandelbulb implements CelestialBody, Cullable { + readonly name: string; -export class Mandelbulb extends AbstractBody implements Planemo { readonly model: MandelbulbModel; + private readonly transform: TransformNode; + + readonly postProcesses: PostProcessType[] = []; + + readonly parent: CelestialBody | null = null; + /** * New Gas Planet * @param name The name of the planet @@ -16,21 +29,57 @@ export class Mandelbulb extends AbstractBody implements Planemo { * @param parentBody The bodies the planet is orbiting * @param model The model to create the planet from or a seed for the planet in [-1, 1] */ - constructor(name: string, scene: UberScene, model: MandelbulbModel | number, parentBody?: AbstractBody) { - super(name, scene, parentBody); + constructor(name: string, scene: Scene, model: MandelbulbModel | number, parentBody: CelestialBody | null = null) { + this.name = name; this.model = model instanceof MandelbulbModel ? model : new MandelbulbModel(model, parentBody?.model); + this.parent = parentBody; + + this.transform = new TransformNode(`${name}Transform`, scene); + this.postProcesses.push(PostProcessType.MANDELBULB); this.getTransform().rotate(Axis.X, this.model.physicalProperties.axialTilt); } + getTransform(): TransformNode { + return this.transform; + } + + getRotationAxis(): Vector3 { + return this.getTransform().up; + } + + getOrbitProperties(): OrbitProperties { + return this.model.orbit; + } + + getPhysicalProperties(): OrbitalObjectPhysicalProperties { + return this.model.physicalProperties; + } + + getRingsUniforms(): RingsUniforms | null { + return this.model.ringsUniforms; + } + + getRadius(): number { + return this.model.radius; + } + + getBoundingRadius(): number { + return this.model.radius; + } + getTypeName(): string { return "Anomaly"; } - public override computeCulling(camera: Camera): void { + computeCulling(camera: Camera): void { // do nothing } + + dispose() { + this.transform.dispose(); + } } diff --git a/src/ts/mandelbulb/mandelbulbModel.ts b/src/ts/mandelbulb/mandelbulbModel.ts index 50e70a76c..a65cd3673 100644 --- a/src/ts/mandelbulb/mandelbulbModel.ts +++ b/src/ts/mandelbulb/mandelbulbModel.ts @@ -1,14 +1,17 @@ import { seededSquirrelNoise } from "squirrel-noise"; import { OrbitProperties } from "../orbit/orbitProperties"; -import { BODY_TYPE, BodyModel, GENERATION_STEPS, PlanemoModel, PlanetPhysicalProperties } from "../model/common"; +import { BODY_TYPE, GENERATION_STEPS } from "../model/common"; import { Color3 } from "@babylonjs/core/Maths/math.color"; import { normalRandom, randRange, randRangeInt } from "extended-random"; import { clamp } from "../utils/math"; import { getOrbitalPeriod, getPeriapsis } from "../orbit/orbit"; import { Vector3 } from "@babylonjs/core/Maths/math.vector"; +import { PlanetModel } from "../architecture/planet"; +import { PlanetPhysicalProperties } from "../architecture/physicalProperties"; +import { CelestialBodyModel } from "../architecture/celestialBody"; -export class MandelbulbModel implements PlanemoModel { +export class MandelbulbModel implements PlanetModel { readonly bodyType = BODY_TYPE.MANDELBULB; readonly seed: number; readonly rng: (step: number) => number; @@ -19,9 +22,9 @@ export class MandelbulbModel implements PlanemoModel { readonly physicalProperties: PlanetPhysicalProperties; - readonly parentBody: BodyModel | null; + readonly parentBody: CelestialBodyModel | null; - readonly childrenBodies: BodyModel[] = []; + readonly childrenBodies: CelestialBodyModel[] = []; readonly nbMoons: number; @@ -30,7 +33,7 @@ export class MandelbulbModel implements PlanemoModel { readonly power: number; readonly accentColor: Color3; - constructor(seed: number, parentBody?: BodyModel) { + constructor(seed: number, parentBody?: CelestialBodyModel) { this.seed = seed; this.rng = seededSquirrelNoise(this.seed); diff --git a/src/ts/model/common.ts b/src/ts/model/common.ts index c60117f90..494270521 100644 --- a/src/ts/model/common.ts +++ b/src/ts/model/common.ts @@ -1,7 +1,3 @@ -import { STELLAR_TYPE } from "../stellarObjects/common"; -import { RingsUniforms } from "../postProcesses/rings/ringsUniform"; -import { OrbitProperties } from "../orbit/orbitProperties"; - export enum GENERATION_STEPS { AXIAL_TILT = 100, ORBIT = 200, @@ -26,69 +22,8 @@ export enum GENERATION_STEPS { export enum BODY_TYPE { STAR, - TELLURIC, - GAS, + TELLURIC_PLANET, + GAS_PLANET, MANDELBULB, BLACK_HOLE } - -export type PhysicalProperties = { - mass: number; - rotationPeriod: number; - axialTilt: number; -}; - -export type StarPhysicalProperties = PhysicalProperties & { - temperature: number; -}; - -export type BlackHolePhysicalProperties = PhysicalProperties & { - accretionDiskRadius: number; -}; - -export type PlanetPhysicalProperties = PhysicalProperties & { - minTemperature: number; - maxTemperature: number; - pressure: number; -}; - -export type SolidPhysicalProperties = PlanetPhysicalProperties & { - waterAmount: number; - oceanLevel: number; -}; - -export interface BaseModel { - rng: (step: number) => number; - seed: number; - - orbit: OrbitProperties; - physicalProperties: PhysicalProperties; - - readonly parentBody: BaseModel | null; - readonly childrenBodies: BaseModel[]; -} - -export interface BodyModel extends BaseModel { - readonly bodyType: BODY_TYPE; - readonly radius: number; - - readonly ringsUniforms: RingsUniforms | null; -} - -export interface StellarObjectModel extends BodyModel { - stellarType: STELLAR_TYPE; -} - -//https://en.wiktionary.org/wiki/planemo#English -export interface PlanemoModel extends BodyModel { - physicalProperties: PlanetPhysicalProperties; - - nbMoons: number; - - getApparentRadius(): number; -} - -export function depth(model: BaseModel): number { - if (model.parentBody === null) return 0; - return depth(model.parentBody) + 1; -} diff --git a/src/ts/orbit/axisRenderer.ts b/src/ts/orbit/axisRenderer.ts index af14a86ac..ff98a0007 100644 --- a/src/ts/orbit/axisRenderer.ts +++ b/src/ts/orbit/axisRenderer.ts @@ -1,8 +1,8 @@ import { LinesMesh, MeshBuilder } from "@babylonjs/core/Meshes"; import { Color3, Vector3 } from "@babylonjs/core/Maths/math"; import { StandardMaterial } from "@babylonjs/core/Materials/standardMaterial"; -import { Transformable } from "../uberCore/transforms/basicTransform"; -import { BoundingSphere } from "../bodies/common"; +import { BoundingSphere } from "../architecture/boundingSphere"; +import { Transformable } from "../architecture/transformable"; export class AxisRenderer { private axisMeshes: LinesMesh[] = []; diff --git a/src/ts/orbit/orbit.ts b/src/ts/orbit/orbit.ts index 1ac540cfa..0c5330b8d 100644 --- a/src/ts/orbit/orbit.ts +++ b/src/ts/orbit/orbit.ts @@ -1,7 +1,5 @@ import { Matrix, Vector3 } from "@babylonjs/core/Maths/math.vector"; import { OrbitProperties } from "./orbitProperties"; -import { Transformable } from "../uberCore/transforms/basicTransform"; -import { BaseModel } from "../model/common"; /** * @@ -50,10 +48,9 @@ export function getPeriapsis(radius: number, p: number) { /** * - * @param periapsis - * @param apoapsis - * @param otherBodies * @see https://www.wikiwand.com/fr/Lois_de_Kepler#/Troisi%C3%A8me_loi_%E2%80%93_Loi_des_p%C3%A9riodes + * @param radius + * @param parentMass */ export function getOrbitalPeriod(radius: number, parentMass: number) { if (parentMass === 0) return 0; @@ -62,11 +59,3 @@ export function getOrbitalPeriod(radius: number, parentMass: number) { const M = parentMass; return Math.sqrt((4 * Math.PI ** 2 * a ** 3) / (G * M)); } - -export interface OrbitalObject extends Transformable { - parentObject: OrbitalObject | null; - - model: BaseModel; - - updateOrbitalPosition(deltaTime: number): void; -} diff --git a/src/ts/orbit/orbitRenderer.ts b/src/ts/orbit/orbitRenderer.ts index d0acfd51e..18ce5c1cc 100644 --- a/src/ts/orbit/orbitRenderer.ts +++ b/src/ts/orbit/orbitRenderer.ts @@ -2,7 +2,8 @@ import { LinesMesh, MeshBuilder } from "@babylonjs/core/Meshes"; import { Color3, Vector3 } from "@babylonjs/core/Maths/math"; import { StandardMaterial } from "@babylonjs/core/Materials/standardMaterial"; import { setUpVector } from "../uberCore/transforms/basicTransform"; -import { getPointOnOrbitLocal, OrbitalObject } from "./orbit"; +import { getPointOnOrbitLocal } from "./orbit"; +import { OrbitalObject } from "../architecture/orbitalObject"; export class OrbitRenderer { private orbitMeshes: LinesMesh[] = []; @@ -25,7 +26,7 @@ export class OrbitRenderer { } private createOrbitMesh(orbitalObject: OrbitalObject) { - const orbit = orbitalObject.model.orbit; + const orbit = orbitalObject.getOrbitProperties(); const nbSteps = 1000; const timestep = orbit.period / nbSteps; const points: Vector3[] = []; @@ -58,10 +59,10 @@ export class OrbitRenderer { const orbitalObject = this.orbitalObjects[i]; const orbitMesh = this.orbitMeshes[i]; - orbitMesh.position = orbitalObject.parentObject?.getTransform().position ?? Vector3.Zero(); + orbitMesh.position = orbitalObject.parent?.getTransform().position ?? Vector3.Zero(); orbitMesh.computeWorldMatrix(true); - const normalToPlane = orbitalObject.model.orbit.normalToPlane; + const normalToPlane = orbitalObject.getOrbitProperties().normalToPlane; setUpVector(orbitMesh, normalToPlane); } } diff --git a/src/ts/physicSpaceship.ts b/src/ts/physicSpaceship.ts index 70831cd0a..c3eb98099 100644 --- a/src/ts/physicSpaceship.ts +++ b/src/ts/physicSpaceship.ts @@ -21,15 +21,15 @@ import "../styles/index.scss"; import { Assets } from "./assets"; import { PhysicsViewer } from "@babylonjs/core/Debug/physicsViewer"; import { Spaceship } from "./spaceshipExtended/spaceship"; -import { TelluricPlanemoModel } from "./planemos/telluricPlanemo/telluricPlanemoModel"; -import { TelluricPlanemo } from "./planemos/telluricPlanemo/telluricPlanemo"; +import { TelluricPlanetModel } from "./planets/telluricPlanet/telluricPlanetModel"; +import { TelluricPlanet } from "./planets/telluricPlanet/telluricPlanet"; import { UberScene } from "./uberCore/uberScene"; import { Settings } from "./settings"; import { translate } from "./uberCore/transforms/basicTransform"; import { StarModel } from "./stellarObjects/star/starModel"; import { Keyboard } from "./inputs/keyboard"; import { Star } from "./stellarObjects/star/star"; -import { ChunkForgeWorkers } from "./planemos/telluricPlanemo/terrain/chunks/chunkForgeWorkers"; +import { ChunkForgeWorkers } from "./planets/telluricPlanet/terrain/chunks/chunkForgeWorkers"; const canvas = document.getElementById("renderer") as HTMLCanvasElement; canvas.width = window.innerWidth; @@ -97,8 +97,8 @@ const auroraModel = new StarModel(984); const aurora = new Star("Aurora", scene, auroraModel); aurora.getTransform().setAbsolutePosition(new Vector3(0, aurora.getRadius() * 10.0, aurora.getRadius() * 40.0)); -const newtonModel = new TelluricPlanemoModel(152); -const newton = new TelluricPlanemo("newton", scene, newtonModel); +const newtonModel = new TelluricPlanetModel(152); +const newton = new TelluricPlanet("newton", scene, newtonModel); newton.getTransform().setAbsolutePosition(new Vector3(0, -newtonModel.radius - 10e3, 0)); newton.updateLOD(camera.globalPosition, chunkForge); @@ -150,8 +150,8 @@ function updateBeforeHavok() { } // planet thingy - newton.updateInternalClock(-deltaTime / 10); - aurora.updateInternalClock(-deltaTime / 10); + //newton.updateInternalClock(-deltaTime / 10); + //aurora.updateInternalClock(-deltaTime / 10); newton.updateLOD(camera.globalPosition, chunkForge); newton.material.update(camera.globalPosition, [aurora]); diff --git a/src/ts/planemos/planemo.ts b/src/ts/planemos/planemo.ts deleted file mode 100644 index 4dd8956c4..000000000 --- a/src/ts/planemos/planemo.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { PlanemoModel } from "../model/common"; -import { AbstractBody } from "../bodies/abstractBody"; -import { StellarObject } from "../stellarObjects/stellarObject"; -import { Camera } from "@babylonjs/core/Cameras/camera"; - -export interface Planemo extends AbstractBody { - model: PlanemoModel; -} - -export interface PlanemoMaterial { - updateMaterial(controller: Camera, stellarObjects: StellarObject[], deltaTime: number): void; -} diff --git a/src/ts/planemos/common.ts b/src/ts/planets/common.ts similarity index 60% rename from src/ts/planemos/common.ts rename to src/ts/planets/common.ts index c278d0e32..5f0fa8c3a 100644 --- a/src/ts/planemos/common.ts +++ b/src/ts/planets/common.ts @@ -1,8 +1,9 @@ import { centeredRand } from "extended-random"; -import { GENERATION_STEPS, PlanemoModel } from "../model/common"; +import { GENERATION_STEPS } from "../model/common"; import { Settings } from "../settings"; +import { PlanetModel } from "../architecture/planet"; -export function getMoonSeed(model: PlanemoModel, index: number) { +export function getMoonSeed(model: PlanetModel, index: number) { if (index > model.nbMoons) throw new Error("Moon out of bound! " + index); return centeredRand(model.rng, GENERATION_STEPS.MOONS + index) * Settings.SEED_HALF_RANGE; } diff --git a/src/ts/planemos/gasPlanet/gasPlanet.ts b/src/ts/planets/gasPlanet/gasPlanet.ts similarity index 51% rename from src/ts/planemos/gasPlanet/gasPlanet.ts rename to src/ts/planets/gasPlanet/gasPlanet.ts index f3d2171ef..43783fd4c 100644 --- a/src/ts/planemos/gasPlanet/gasPlanet.ts +++ b/src/ts/planets/gasPlanet/gasPlanet.ts @@ -1,9 +1,6 @@ import { GasPlanetMaterial } from "./gasPlanetMaterial"; -import { AbstractBody } from "../../bodies/abstractBody"; import { UberScene } from "../../uberCore/uberScene"; -import { Planemo, PlanemoMaterial } from "../planemo"; import { GasPlanetModel } from "./gasPlanetModel"; -import { StellarObject } from "../../stellarObjects/stellarObject"; import { MeshBuilder } from "@babylonjs/core/Meshes/meshBuilder"; import { Axis } from "@babylonjs/core/Maths/math.axis"; import { Mesh } from "@babylonjs/core/Meshes/mesh"; @@ -12,13 +9,29 @@ import { isSizeOnScreenEnough } from "../../utils/isObjectVisibleOnScreen"; import { Camera } from "@babylonjs/core/Cameras/camera"; import { Vector3 } from "@babylonjs/core/Maths/math.vector"; import { PhysicsShapeSphere } from "@babylonjs/core/Physics/v2/physicsShape"; +import { Planet } from "../../architecture/planet"; +import { OrbitProperties } from "../../orbit/orbitProperties"; +import { TransformNode } from "@babylonjs/core/Meshes"; +import { CelestialBody } from "../../architecture/celestialBody"; +import { OrbitalObject } from "../../architecture/orbitalObject"; +import { PhysicsAggregate } from "@babylonjs/core/Physics/v2/physicsAggregate"; +import { PhysicsShapeType } from "@babylonjs/core/Physics/v2/IPhysicsEnginePlugin"; +import { Cullable } from "../../bodies/cullable"; +import { RingsUniforms } from "../../postProcesses/rings/ringsUniform"; +import { OrbitalObjectPhysicalProperties } from "../../architecture/physicalProperties"; +import { Transformable } from "../../architecture/transformable"; -export class GasPlanet extends AbstractBody implements Planemo, PlanemoMaterial { +export class GasPlanet implements Planet, Cullable { private readonly mesh: Mesh; readonly material: GasPlanetMaterial; + readonly aggregate: PhysicsAggregate; readonly model: GasPlanetModel; + name: string; + parent: OrbitalObject | null; + postProcesses: PostProcessType[] = []; + /** * New Gas Planet * @param name The name of the planet @@ -26,8 +39,10 @@ export class GasPlanet extends AbstractBody implements Planemo, PlanemoMaterial * @param parentBody The bodies the planet is orbiting * @param model The model to create the planet from or a seed for the planet in [-1, 1] */ - constructor(name: string, scene: UberScene, model: GasPlanetModel | number, parentBody?: AbstractBody) { - super(name, scene, parentBody); + constructor(name: string, scene: UberScene, model: GasPlanetModel | number, parentBody: CelestialBody | null = null) { + this.name = name; + + this.parent = parentBody; this.model = model instanceof GasPlanetModel ? model : new GasPlanetModel(model, parentBody?.model); @@ -39,8 +54,18 @@ export class GasPlanet extends AbstractBody implements Planemo, PlanemoMaterial }, scene ); - this.mesh.parent = this.getTransform(); + this.aggregate = new PhysicsAggregate( + this.getTransform(), + PhysicsShapeType.CONTAINER, + { + mass: 0, + restitution: 0.2 + }, + scene + ); + this.aggregate.body.setMassProperties({ inertia: Vector3.Zero(), mass: 0 }); + this.aggregate.body.disablePreStep = false; const physicsShape = new PhysicsShapeSphere(Vector3.Zero(), this.model.radius, scene); this.aggregate.shape.addChildFromParent(this.getTransform(), physicsShape, this.mesh); @@ -53,22 +78,49 @@ export class GasPlanet extends AbstractBody implements Planemo, PlanemoMaterial this.getTransform().rotate(Axis.X, this.model.physicalProperties.axialTilt); } - updateMaterial(controller: Camera, stellarObjects: StellarObject[], deltaTime: number): void { + updateMaterial(controller: Camera, stellarObjects: Transformable[], deltaTime: number): void { this.material.update(controller, stellarObjects, deltaTime); } + public getRadius(): number { + return this.model.radius; + } + + public getBoundingRadius(): number { + return this.model.radius; + } + + getRotationAxis(): Vector3 { + return this.getTransform().up; + } + + getRingsUniforms(): RingsUniforms | null { + return this.model.ringsUniforms; + } + getTypeName(): string { return "Gas Planet"; } - public override computeCulling(camera: Camera): void { + public computeCulling(camera: Camera): void { this.mesh.isVisible = isSizeOnScreenEnough(this, camera); } - public override dispose(): void { - this.aggregate.dispose(); + public dispose(): void { this.mesh.dispose(); + this.aggregate.dispose(); this.material.dispose(); - super.dispose(); + } + + getOrbitProperties(): OrbitProperties { + return this.model.orbit; + } + + getPhysicalProperties(): OrbitalObjectPhysicalProperties { + return this.model.physicalProperties; + } + + getTransform(): TransformNode { + return this.mesh; } } diff --git a/src/ts/planemos/gasPlanet/gasPlanetMaterial.ts b/src/ts/planets/gasPlanet/gasPlanetMaterial.ts similarity index 94% rename from src/ts/planemos/gasPlanet/gasPlanetMaterial.ts rename to src/ts/planets/gasPlanet/gasPlanetMaterial.ts index 2e9af5022..52743ceee 100644 --- a/src/ts/planemos/gasPlanet/gasPlanetMaterial.ts +++ b/src/ts/planets/gasPlanet/gasPlanetMaterial.ts @@ -1,9 +1,8 @@ import surfaceMaterialFragment from "../../../shaders/gasPlanetMaterial/fragment.glsl"; import surfaceMaterialVertex from "../../../shaders/gasPlanetMaterial/vertex.glsl"; -import { GazColorSettings } from "../telluricPlanemo/colorSettingsInterface"; +import { GazColorSettings } from "../telluricPlanet/colorSettingsInterface"; import { normalRandom, randRange, randRangeInt } from "extended-random"; import { GasPlanetModel } from "./gasPlanetModel"; -import { StellarObject } from "../../stellarObjects/stellarObject"; import { ShaderMaterial } from "@babylonjs/core/Materials/shaderMaterial"; import { Effect } from "@babylonjs/core/Materials/effect"; import { Scene } from "@babylonjs/core/scene"; @@ -13,6 +12,7 @@ import { TransformNode } from "@babylonjs/core/Meshes"; import { Star } from "../../stellarObjects/star/star"; import { flattenVector3Array } from "../../utils/algebra"; import { Camera } from "@babylonjs/core/Cameras/camera"; +import { Transformable } from "../../architecture/transformable"; export class GasPlanetMaterial extends ShaderMaterial { readonly planet: TransformNode; @@ -78,7 +78,7 @@ export class GasPlanetMaterial extends ShaderMaterial { this.setFloat("colorSharpness", this.colorSettings.colorSharpness); } - public update(player: Camera, stellarObjects: StellarObject[], deltaTime: number) { + public update(player: Camera, stellarObjects: Transformable[], deltaTime: number) { this.clock += deltaTime; this.setMatrix("normalMatrix", this.planet.getWorldMatrix().clone().invert().transpose()); diff --git a/src/ts/planemos/gasPlanet/gasPlanetModel.ts b/src/ts/planets/gasPlanet/gasPlanetModel.ts similarity index 82% rename from src/ts/planemos/gasPlanet/gasPlanetModel.ts rename to src/ts/planets/gasPlanet/gasPlanetModel.ts index 0a6158f54..198b33e4c 100644 --- a/src/ts/planemos/gasPlanet/gasPlanetModel.ts +++ b/src/ts/planets/gasPlanet/gasPlanetModel.ts @@ -1,7 +1,7 @@ import { seededSquirrelNoise } from "squirrel-noise"; import { normalRandom, randRangeInt, uniformRandBool } from "extended-random"; import { Settings } from "../../settings"; -import { BODY_TYPE, BodyModel, GENERATION_STEPS, PlanemoModel, PlanetPhysicalProperties } from "../../model/common"; +import { BODY_TYPE, GENERATION_STEPS } from "../../model/common"; import { RingsUniforms } from "../../postProcesses/rings/ringsUniform"; import { Quaternion } from "@babylonjs/core/Maths/math"; import { Axis } from "@babylonjs/core/Maths/math.axis"; @@ -9,9 +9,12 @@ import { OrbitProperties } from "../../orbit/orbitProperties"; import { clamp } from "../../utils/math"; import { getOrbitalPeriod, getPeriapsis } from "../../orbit/orbit"; import { Vector3 } from "@babylonjs/core/Maths/math.vector"; +import { PlanetModel } from "../../architecture/planet"; +import { PlanetPhysicalProperties } from "../../architecture/physicalProperties"; +import { CelestialBodyModel } from "../../architecture/celestialBody"; -export class GasPlanetModel implements PlanemoModel { - readonly bodyType = BODY_TYPE.GAS; +export class GasPlanetModel implements PlanetModel { + readonly bodyType = BODY_TYPE.GAS_PLANET; readonly seed: number; readonly rng: (step: number) => number; @@ -25,11 +28,11 @@ export class GasPlanetModel implements PlanemoModel { readonly nbMoons: number; - readonly parentBody: BodyModel | null; + readonly parentBody: CelestialBodyModel | null; - readonly childrenBodies: BodyModel[] = []; + readonly childrenBodies: CelestialBodyModel[] = []; - constructor(seed: number, parentBody?: BodyModel) { + constructor(seed: number, parentBody?: CelestialBodyModel) { this.seed = seed; this.rng = seededSquirrelNoise(this.seed); diff --git a/src/ts/planemos/telluricPlanemo/colorSettingsInterface.ts b/src/ts/planets/telluricPlanet/colorSettingsInterface.ts similarity index 100% rename from src/ts/planemos/telluricPlanemo/colorSettingsInterface.ts rename to src/ts/planets/telluricPlanet/colorSettingsInterface.ts diff --git a/src/ts/planemos/telluricPlanemo/telluricPlanemo.ts b/src/ts/planets/telluricPlanet/telluricPlanet.ts similarity index 56% rename from src/ts/planemos/telluricPlanemo/telluricPlanemo.ts rename to src/ts/planets/telluricPlanet/telluricPlanet.ts index ed8e8a787..b8cf1590e 100644 --- a/src/ts/planemos/telluricPlanemo/telluricPlanemo.ts +++ b/src/ts/planets/telluricPlanet/telluricPlanet.ts @@ -3,30 +3,48 @@ import { Direction } from "../../utils/direction"; import { Vector3 } from "@babylonjs/core/Maths/math.vector"; import { Axis } from "@babylonjs/core/Maths/math.axis"; -import { TelluricPlanemoMaterial } from "./telluricPlanemoMaterial"; +import { TelluricPlanetMaterial } from "./telluricPlanetMaterial"; import { waterBoilingPointCelsius } from "../../utils/waterMechanics"; -import { AbstractBody } from "../../bodies/abstractBody"; import { UberScene } from "../../uberCore/uberScene"; -import { Planemo, PlanemoMaterial } from "../planemo"; -import { TelluricPlanemoModel } from "./telluricPlanemoModel"; +import { TelluricPlanetModel } from "./telluricPlanetModel"; import { PostProcessType } from "../../postProcesses/postProcessTypes"; import { Camera } from "@babylonjs/core/Cameras/camera"; import { ChunkTree } from "./terrain/chunks/chunkTree"; import { PhysicsShapeSphere } from "@babylonjs/core/Physics/v2/physicsShape"; -import { Transformable } from "../../uberCore/transforms/basicTransform"; +import { Transformable } from "../../architecture/transformable"; import { ChunkForge } from "./terrain/chunks/chunkForge"; import { Observable } from "@babylonjs/core/Misc/observable"; import { PlanetChunk } from "./terrain/chunks/planetChunk"; +import { Planet } from "../../architecture/planet"; +import { Cullable } from "../../bodies/cullable"; +import { TransformNode } from "@babylonjs/core/Meshes"; +import { OrbitProperties } from "../../orbit/orbitProperties"; +import { PhysicsAggregate } from "@babylonjs/core/Physics/v2/physicsAggregate"; +import { PhysicsShapeType } from "@babylonjs/core/Physics/v2/IPhysicsEnginePlugin"; +import { OrbitalObject } from "../../architecture/orbitalObject"; +import { CelestialBody } from "../../architecture/celestialBody"; +import { RingsUniforms } from "../../postProcesses/rings/ringsUniform"; +import { OrbitalObjectPhysicalProperties } from "../../architecture/physicalProperties"; +import { rotate } from "../../uberCore/transforms/basicTransform"; + +export class TelluricPlanet implements Planet, Cullable { + readonly name: string; -export class TelluricPlanemo extends AbstractBody implements Planemo, PlanemoMaterial { readonly sides: ChunkTree[]; // stores the 6 sides of the sphere - readonly material: TelluricPlanemoMaterial; + readonly material: TelluricPlanetMaterial; - readonly model: TelluricPlanemoModel; + readonly model: TelluricPlanetModel; readonly onChunkCreatedObservable = new Observable(); + private readonly transform: TransformNode; + readonly aggregate: PhysicsAggregate; + + readonly postProcesses: PostProcessType[] = []; + + readonly parent: OrbitalObject | null; + /** * New Telluric Planet * @param name The name of the planet @@ -34,12 +52,31 @@ export class TelluricPlanemo extends AbstractBody implements Planemo, PlanemoMat * @param model The model to build the planet or a seed for the planet in [-1, 1] * @param parentBody */ - constructor(name: string, scene: UberScene, model: TelluricPlanemoModel | number, parentBody?: AbstractBody) { - super(name, scene, parentBody); + constructor(name: string, scene: UberScene, model: TelluricPlanetModel | number, parentBody: CelestialBody | null = null) { + this.name = name; + + this.parent = parentBody; - this.model = model instanceof TelluricPlanemoModel ? model : new TelluricPlanemoModel(model, parentBody?.model); + this.model = model instanceof TelluricPlanetModel ? model : new TelluricPlanetModel(model, parentBody?.model); - this.getTransform().rotate(Axis.X, this.model.physicalProperties.axialTilt); + this.transform = new TransformNode(`${name}Transform`, scene); + + rotate(this.transform, Axis.X, this.model.physicalProperties.axialTilt); + this.transform.computeWorldMatrix(true); + + this.aggregate = new PhysicsAggregate( + this.getTransform(), + PhysicsShapeType.CONTAINER, + { + mass: 0, + restitution: 0.2 + }, + scene + ); + this.aggregate.body.setMassProperties({ inertia: Vector3.Zero(), mass: 0 }); + this.aggregate.body.disablePreStep = false; + const physicsShape = new PhysicsShapeSphere(Vector3.Zero(), this.model.radius, scene); + this.aggregate.shape.addChildFromParent(this.getTransform(), physicsShape, this.getTransform()); this.postProcesses.push(PostProcessType.SHADOW); @@ -60,10 +97,7 @@ export class TelluricPlanemo extends AbstractBody implements Planemo, PlanemoMat if (this.model.ringsUniforms !== null) this.postProcesses.push(PostProcessType.RING); if (this.model.cloudsUniforms !== null) this.postProcesses.push(PostProcessType.CLOUDS); - this.material = new TelluricPlanemoMaterial(this.name, this.getTransform(), this.model, scene); - - const physicsShape = new PhysicsShapeSphere(Vector3.Zero(), this.model.radius, scene); - this.aggregate.shape.addChildFromParent(this.getTransform(), physicsShape, this.getTransform()); + this.material = new TelluricPlanetMaterial(this.name, this.getTransform(), this.model, scene); this.sides = [ new ChunkTree(Direction.Up, this.name, this.model, this.aggregate, this.material, scene), @@ -77,8 +111,28 @@ export class TelluricPlanemo extends AbstractBody implements Planemo, PlanemoMat this.sides.forEach((side) => side.onChunkCreatedObservable.add((chunk) => this.onChunkCreatedObservable.notifyObservers(chunk))); } + getTransform(): TransformNode { + return this.transform; + } + + getRotationAxis(): Vector3 { + return this.getTransform().up; + } + + getOrbitProperties(): OrbitProperties { + return this.model.orbit; + } + + getPhysicalProperties(): OrbitalObjectPhysicalProperties { + return this.model.physicalProperties; + } + + getRingsUniforms(): RingsUniforms | null { + return this.model.ringsUniforms; + } + getTypeName(): string { - return "Telluric Planemo"; + return "Telluric Planet"; } /** @@ -94,18 +148,22 @@ export class TelluricPlanemo extends AbstractBody implements Planemo, PlanemoMat this.material.update(controller.globalPosition, stellarObjects); } - public override getBoundingRadius(): number { - return super.getRadius() + this.model.physicalProperties.oceanLevel; + public getRadius(): number { + return this.model.radius; + } + + public getBoundingRadius(): number { + return this.getRadius() + this.model.physicalProperties.oceanLevel; } - public override computeCulling(camera: Camera): void { + public computeCulling(camera: Camera): void { for (const side of this.sides) side.computeCulling(camera); } - public override dispose(): void { - this.material.dispose(); + public dispose(): void { for (const side of this.sides) side.dispose(); + this.material.dispose(); this.aggregate.dispose(); - super.dispose(); + this.transform.dispose(); } } diff --git a/src/ts/planemos/telluricPlanemo/telluricPlanemoMaterial.ts b/src/ts/planets/telluricPlanet/telluricPlanetMaterial.ts similarity index 71% rename from src/ts/planemos/telluricPlanemo/telluricPlanemoMaterial.ts rename to src/ts/planets/telluricPlanet/telluricPlanetMaterial.ts index 5ff70d3da..013f3cd57 100644 --- a/src/ts/planemos/telluricPlanemo/telluricPlanemoMaterial.ts +++ b/src/ts/planets/telluricPlanet/telluricPlanetMaterial.ts @@ -5,44 +5,45 @@ import surfaceMaterialVertex from "../../../shaders/telluricPlanetMaterial/verte import { Assets } from "../../assets"; import { UberScene } from "../../uberCore/uberScene"; import { centeredRand, normalRandom } from "extended-random"; -import { TelluricPlanemoModel } from "./telluricPlanemoModel"; +import { TelluricPlanetModel } from "./telluricPlanetModel"; import { Effect } from "@babylonjs/core/Materials/effect"; import { ShaderMaterial } from "@babylonjs/core/Materials/shaderMaterial"; import { Color3 } from "@babylonjs/core/Maths/math.color"; import { Vector3 } from "@babylonjs/core/Maths/math"; import { TransformNode } from "@babylonjs/core/Meshes"; -import { getInverseRotationMatrix, Transformable } from "../../uberCore/transforms/basicTransform"; +import { getInverseRotationMatrix } from "../../uberCore/transforms/basicTransform"; import { Star } from "../../stellarObjects/star/star"; import { flattenVector3Array } from "../../utils/algebra"; import lutFragment from "../../../shaders/telluricPlanetMaterial/utils/lut.glsl"; import { ProceduralTexture } from "@babylonjs/core/Materials/Textures/Procedurals/proceduralTexture"; +import { Transformable } from "../../architecture/transformable"; /** - * The material for telluric planemos. + * The material for telluric planets. * It is responsible for the shading of the surface of the planet (biome blending, normal mapping and color) */ -export class TelluricPlanemoMaterial extends ShaderMaterial { +export class TelluricPlanetMaterial extends ShaderMaterial { /** - * The transform node of the planemo associated with this material + * The transform node of the planet associated with this material */ - private readonly planemoTransform: TransformNode; + private readonly planetTransform: TransformNode; readonly colorSettings: ColorSettings; /** - * The model of the planemo associated with this material + * The model of the planet associated with this material */ - private readonly planemoModel: TelluricPlanemoModel; + private readonly planetModel: TelluricPlanetModel; /** - * Creates a new telluric planemo material - * @param planetName The name of the planemo - * @param planet The transform node of the planemo - * @param model The model of the planemo associated with this material + * Creates a new telluric planet material + * @param planetName The name of the planet + * @param planet The transform node of the planet + * @param model The model of the planet associated with this material * @param scene */ - constructor(planetName: string, planet: TransformNode, model: TelluricPlanemoModel, scene: UberScene) { + constructor(planetName: string, planet: TransformNode, model: TelluricPlanetModel, scene: UberScene) { const shaderName = "surfaceMaterial"; if (Effect.ShadersStore[`${shaderName}FragmentShader`] === undefined) { Effect.ShadersStore[`${shaderName}FragmentShader`] = surfaceMaterialFragment; @@ -73,7 +74,7 @@ export class TelluricPlanemoMaterial extends ShaderMaterial { "star_colors", "nbStars", - "planetInverseRotationMatrix", + "inversePlanetWorldMatrix", "playerPosition", @@ -100,8 +101,8 @@ export class TelluricPlanemoMaterial extends ShaderMaterial { samplers: ["lut", "bottomNormalMap", "plainNormalMap", "beachNormalMap", "desertNormalMap", "snowNormalMap", "steepNormalMap"] }); - this.planemoModel = model; - this.planemoTransform = planet; + this.planetModel = model; + this.planetTransform = planet; this.colorSettings = { mode: ColorMode.DEFAULT, @@ -142,17 +143,17 @@ export class TelluricPlanemoMaterial extends ShaderMaterial { this.setColor3("desertColor", this.colorSettings.desertColor); this.setColor3("bottomColor", this.colorSettings.bottomColor); - this.setVector3("planetPosition", this.planemoTransform.getAbsolutePosition()); + this.setVector3("planetPosition", this.planetTransform.getAbsolutePosition()); - if (Effect.ShadersStore["telluricPlanemoLutFragmentShader"] === undefined) { - Effect.ShadersStore["telluricPlanemoLutFragmentShader"] = lutFragment; + if (Effect.ShadersStore["telluricPlanetLutFragmentShader"] === undefined) { + Effect.ShadersStore["telluricPlanetLutFragmentShader"] = lutFragment; } this.setTexture("lut", Assets.EmptyTexture); - const lut = new ProceduralTexture("lut", 4096, "telluricPlanemoLut", scene, null, true, false); - lut.setFloat("minTemperature", this.planemoModel.physicalProperties.minTemperature); - lut.setFloat("maxTemperature", this.planemoModel.physicalProperties.maxTemperature); - lut.setFloat("pressure", this.planemoModel.physicalProperties.pressure); + const lut = new ProceduralTexture("lut", 4096, "telluricPlanetLut", scene, null, true, false); + lut.setFloat("minTemperature", this.planetModel.physicalProperties.minTemperature); + lut.setFloat("maxTemperature", this.planetModel.physicalProperties.maxTemperature); + lut.setFloat("pressure", this.planetModel.physicalProperties.pressure); lut.refreshRate = 0; lut.executeWhenReady(() => { this.setTexture("lut", lut); @@ -162,11 +163,11 @@ export class TelluricPlanemoMaterial extends ShaderMaterial { } public updateConstants(): void { - this.setFloat("planetRadius", this.planemoModel.radius); + this.setFloat("planetRadius", this.planetModel.radius); this.setInt("colorMode", this.colorSettings.mode); - this.setFloat("waterLevel", this.planemoModel.physicalProperties.oceanLevel); + this.setFloat("waterLevel", this.planetModel.physicalProperties.oceanLevel); this.setFloat("beachSize", this.colorSettings.beachSize); this.setFloat("steepSharpness", this.colorSettings.steepSharpness); @@ -179,27 +180,28 @@ export class TelluricPlanemoMaterial extends ShaderMaterial { this.setTexture("beachNormalMap", Assets.SandNormalMap1); this.setTexture("desertNormalMap", Assets.SandNormalMap2); - this.setFloat("minTemperature", this.planemoModel.physicalProperties.minTemperature); - this.setFloat("maxTemperature", this.planemoModel.physicalProperties.maxTemperature); - this.setFloat("pressure", this.planemoModel.physicalProperties.pressure); - this.setFloat("waterAmount", this.planemoModel.physicalProperties.waterAmount); + this.setFloat("minTemperature", this.planetModel.physicalProperties.minTemperature); + this.setFloat("maxTemperature", this.planetModel.physicalProperties.maxTemperature); + this.setFloat("pressure", this.planetModel.physicalProperties.pressure); + this.setFloat("waterAmount", this.planetModel.physicalProperties.waterAmount); this.setFloat( "maxElevation", - this.planemoModel.terrainSettings.continent_base_height + this.planemoModel.terrainSettings.max_mountain_height + this.planemoModel.terrainSettings.max_bump_height + this.planetModel.terrainSettings.continent_base_height + this.planetModel.terrainSettings.max_mountain_height + this.planetModel.terrainSettings.max_bump_height ); } - public update(activeControllerPosition: Vector3, stellarObjects: Transformable[]) { - this.setMatrix("normalMatrix", this.planemoTransform.getWorldMatrix().clone().invert().transpose()); - this.setMatrix("planetInverseRotationMatrix", getInverseRotationMatrix(this.planemoTransform)); + public update(cameraPosition: Vector3, stellarObjects: Transformable[]) { + const inversePlanetWorldMatrix = this.planetTransform.getWorldMatrix().clone().invert(); + this.setMatrix("normalMatrix", inversePlanetWorldMatrix.transpose()); + this.setMatrix("inversePlanetWorldMatrix", inversePlanetWorldMatrix); - this.setVector3("playerPosition", activeControllerPosition); + this.setVector3("playerPosition", cameraPosition); this.setArray3("star_positions", flattenVector3Array(stellarObjects.map((star) => star.getTransform().getAbsolutePosition()))); this.setArray3("star_colors", flattenVector3Array(stellarObjects.map((star) => (star instanceof Star ? star.model.surfaceColor : Vector3.One())))); this.setInt("nbStars", stellarObjects.length); - this.setVector3("planetPosition", this.planemoTransform.getAbsolutePosition()); + this.setVector3("planetPosition", this.planetTransform.getAbsolutePosition()); } } diff --git a/src/ts/planemos/telluricPlanemo/telluricPlanemoModel.ts b/src/ts/planets/telluricPlanet/telluricPlanetModel.ts similarity index 87% rename from src/ts/planemos/telluricPlanemo/telluricPlanemoModel.ts rename to src/ts/planets/telluricPlanet/telluricPlanetModel.ts index 8686b306a..051783833 100644 --- a/src/ts/planemos/telluricPlanemo/telluricPlanemoModel.ts +++ b/src/ts/planets/telluricPlanet/telluricPlanetModel.ts @@ -1,7 +1,7 @@ import { seededSquirrelNoise } from "squirrel-noise"; import { normalRandom, randRangeInt, uniformRandBool } from "extended-random"; import { Settings } from "../../settings"; -import { BODY_TYPE, BodyModel, GENERATION_STEPS, PlanemoModel, SolidPhysicalProperties } from "../../model/common"; +import { BODY_TYPE, GENERATION_STEPS } from "../../model/common"; import { TerrainSettings } from "./terrain/terrainSettings"; import { clamp } from "terrain-generation"; import { RingsUniforms } from "../../postProcesses/rings/ringsUniform"; @@ -11,9 +11,12 @@ import { Vector3 } from "@babylonjs/core/Maths/math.vector"; import { getOrbitalPeriod, getPeriapsis } from "../../orbit/orbit"; import { OrbitProperties } from "../../orbit/orbitProperties"; import { CloudsUniforms } from "../../postProcesses/clouds/cloudsUniforms"; +import { PlanetModel } from "../../architecture/planet"; +import { TelluricPlanetPhysicalProperties } from "../../architecture/physicalProperties"; +import { CelestialBodyModel } from "../../architecture/celestialBody"; -export class TelluricPlanemoModel implements PlanemoModel { - readonly bodyType = BODY_TYPE.TELLURIC; +export class TelluricPlanetModel implements PlanetModel { + readonly bodyType = BODY_TYPE.TELLURIC_PLANET; readonly seed: number; readonly rng: (step: number) => number; @@ -21,7 +24,7 @@ export class TelluricPlanemoModel implements PlanemoModel { readonly orbit: OrbitProperties; - readonly physicalProperties: SolidPhysicalProperties; + readonly physicalProperties: TelluricPlanetPhysicalProperties; readonly terrainSettings: TerrainSettings; @@ -33,17 +36,17 @@ export class TelluricPlanemoModel implements PlanemoModel { private isSatelliteOfTelluric = false; private isSatelliteOfGas = false; - readonly parentBody: BodyModel | null; - readonly childrenBodies: BodyModel[] = []; + readonly parentBody: CelestialBodyModel | null; + readonly childrenBodies: CelestialBodyModel[] = []; - constructor(seed: number, parentBody?: BodyModel) { + constructor(seed: number, parentBody?: CelestialBodyModel) { this.seed = seed; this.rng = seededSquirrelNoise(this.seed); this.parentBody = parentBody ?? null; - if (this.parentBody?.bodyType === BODY_TYPE.TELLURIC) this.isSatelliteOfTelluric = true; - if (this.parentBody?.bodyType === BODY_TYPE.GAS) this.isSatelliteOfGas = true; + if (this.parentBody?.bodyType === BODY_TYPE.TELLURIC_PLANET) this.isSatelliteOfTelluric = true; + if (this.parentBody?.bodyType === BODY_TYPE.GAS_PLANET) this.isSatelliteOfGas = true; if (this.isSatelliteOfTelluric) { this.radius = Math.max(0.03, normalRandom(0.06, 0.03, this.rng, GENERATION_STEPS.RADIUS)) * Settings.EARTH_RADIUS; diff --git a/src/ts/planemos/telluricPlanemo/terrain/chunks/chunkForge.ts b/src/ts/planets/telluricPlanet/terrain/chunks/chunkForge.ts similarity index 100% rename from src/ts/planemos/telluricPlanemo/terrain/chunks/chunkForge.ts rename to src/ts/planets/telluricPlanet/terrain/chunks/chunkForge.ts diff --git a/src/ts/planemos/telluricPlanemo/terrain/chunks/chunkForgeWorkers.ts b/src/ts/planets/telluricPlanet/terrain/chunks/chunkForgeWorkers.ts similarity index 100% rename from src/ts/planemos/telluricPlanemo/terrain/chunks/chunkForgeWorkers.ts rename to src/ts/planets/telluricPlanet/terrain/chunks/chunkForgeWorkers.ts diff --git a/src/ts/planemos/telluricPlanemo/terrain/chunks/chunkTree.ts b/src/ts/planets/telluricPlanet/terrain/chunks/chunkTree.ts similarity index 97% rename from src/ts/planemos/telluricPlanemo/terrain/chunks/chunkTree.ts rename to src/ts/planets/telluricPlanet/terrain/chunks/chunkTree.ts index 31b97fa71..040775e4f 100644 --- a/src/ts/planemos/telluricPlanemo/terrain/chunks/chunkTree.ts +++ b/src/ts/planets/telluricPlanet/terrain/chunks/chunkTree.ts @@ -4,7 +4,7 @@ import { BuildTask, TaskType } from "./taskTypes"; import { Settings } from "../../../../settings"; import { getChunkSphereSpacePositionFromPath } from "../../../../utils/chunkUtils"; import { TerrainSettings } from "../terrainSettings"; -import { TelluricPlanemoModel } from "../../telluricPlanemoModel"; +import { TelluricPlanetModel } from "../../telluricPlanetModel"; import { Material } from "@babylonjs/core/Materials/material"; import { Vector3 } from "@babylonjs/core/Maths/math.vector"; import { PhysicsAggregate } from "@babylonjs/core/Physics/v2/physicsAggregate"; @@ -38,7 +38,7 @@ export class ChunkTree { private deleteSemaphores: DeleteSemaphore[] = []; - readonly planetModel: TelluricPlanemoModel; + readonly planetModel: TelluricPlanetModel; readonly planetName: string; readonly planetSeed: number; @@ -60,7 +60,7 @@ export class ChunkTree { * @param material * @param scene */ - constructor(direction: Direction, planetName: string, planetModel: TelluricPlanemoModel, parentAggregate: PhysicsAggregate, material: Material, scene: UberScene) { + constructor(direction: Direction, planetName: string, planetModel: TelluricPlanetModel, parentAggregate: PhysicsAggregate, material: Material, scene: UberScene) { this.rootChunkLength = planetModel.radius * 2; this.planetName = planetName; this.planetSeed = planetModel.seed; diff --git a/src/ts/planemos/telluricPlanemo/terrain/chunks/deleteSemaphore.ts b/src/ts/planets/telluricPlanet/terrain/chunks/deleteSemaphore.ts similarity index 100% rename from src/ts/planemos/telluricPlanemo/terrain/chunks/deleteSemaphore.ts rename to src/ts/planets/telluricPlanet/terrain/chunks/deleteSemaphore.ts diff --git a/src/ts/planemos/telluricPlanemo/terrain/chunks/planetChunk.ts b/src/ts/planets/telluricPlanet/terrain/chunks/planetChunk.ts similarity index 93% rename from src/ts/planemos/telluricPlanemo/terrain/chunks/planetChunk.ts rename to src/ts/planets/telluricPlanet/terrain/chunks/planetChunk.ts index 83634b677..9c273bf34 100644 --- a/src/ts/planemos/telluricPlanemo/terrain/chunks/planetChunk.ts +++ b/src/ts/planets/telluricPlanet/terrain/chunks/planetChunk.ts @@ -8,27 +8,25 @@ import "@babylonjs/core/Engines/Extensions/engine.query"; import { TransformNode, VertexData } from "@babylonjs/core/Meshes"; import { PhysicsAggregate } from "@babylonjs/core/Physics/v2/physicsAggregate"; import { Observable } from "@babylonjs/core/Misc/observable"; -import { Transformable } from "../../../../uberCore/transforms/basicTransform"; import { ThinInstancePatch } from "../instancePatch/thinInstancePatch"; import { randomDownSample } from "../instancePatch/matrixBuffer"; import { Assets } from "../../../../assets"; import { isSizeOnScreenEnough } from "../../../../utils/isObjectVisibleOnScreen"; import { Camera } from "@babylonjs/core/Cameras/camera"; import { IPatch } from "../instancePatch/iPatch"; -import { TelluricPlanemoModel } from "../../telluricPlanemoModel"; -import { BoundingSphere } from "../../../../bodies/common"; +import { TelluricPlanetModel } from "../../telluricPlanetModel"; +import { BoundingSphere } from "../../../../architecture/boundingSphere"; import { PhysicsMotionType, PhysicsShapeType } from "@babylonjs/core/Physics/v2/IPhysicsEnginePlugin"; import { LockConstraint } from "@babylonjs/core/Physics/v2/physicsConstraint"; import { AbstractMesh } from "@babylonjs/core/Meshes/abstractMesh"; +import { Transformable } from "../../../../architecture/transformable"; export class PlanetChunk implements Transformable, BoundingSphere { public readonly mesh: Mesh; private readonly depth: number; public readonly cubePosition: Vector3; - private readonly transform: TransformNode; - - readonly planetModel: TelluricPlanemoModel; + readonly planetModel: TelluricPlanetModel; readonly chunkSideLength: number; @@ -50,15 +48,13 @@ export class PlanetChunk implements Transformable, BoundingSphere { private disposed = false; - constructor(path: number[], direction: Direction, parentAggregate: PhysicsAggregate, material: Material, planetModel: TelluricPlanemoModel, rootLength: number, scene: Scene) { + constructor(path: number[], direction: Direction, parentAggregate: PhysicsAggregate, material: Material, planetModel: TelluricPlanetModel, rootLength: number, scene: Scene) { const id = `D${direction}P${path.join("")}`; this.depth = path.length; this.chunkSideLength = rootLength / 2 ** this.depth; - this.transform = new TransformNode(`${id}Transform`, scene); - this.planetModel = planetModel; this.mesh = new Mesh(`Chunk${id}`, scene); @@ -67,8 +63,7 @@ export class PlanetChunk implements Transformable, BoundingSphere { this.mesh.material = material; //this.mesh.material = Assets.DebugMaterial(id, false, false); - this.transform.parent = parentAggregate.transformNode; - this.mesh.parent = this.transform; + this.mesh.parent = parentAggregate.transformNode; this.mesh.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE; this.mesh.occlusionType = AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC; @@ -87,11 +82,11 @@ export class PlanetChunk implements Transformable, BoundingSphere { position.normalize().scaleInPlace(rootLength / 2); - this.transform.position = position; + this.getTransform().position = position; } public getTransform(): TransformNode { - return this.transform; + return this.mesh; } /** @@ -183,7 +178,6 @@ export class PlanetChunk implements Transformable, BoundingSphere { this.helpers.forEach((helper) => helper.dispose()); this.instancePatches.forEach((patch) => patch.dispose()); this.mesh.dispose(); - this.transform.dispose(); this.onRecieveVertexDataObservable.clear(); this.onDisposeObservable.clear(); diff --git a/src/ts/planemos/telluricPlanemo/terrain/chunks/taskTypes.ts b/src/ts/planets/telluricPlanet/terrain/chunks/taskTypes.ts similarity index 100% rename from src/ts/planemos/telluricPlanemo/terrain/chunks/taskTypes.ts rename to src/ts/planets/telluricPlanet/terrain/chunks/taskTypes.ts diff --git a/src/ts/planemos/telluricPlanemo/terrain/chunks/workerDataTypes.ts b/src/ts/planets/telluricPlanet/terrain/chunks/workerDataTypes.ts similarity index 100% rename from src/ts/planemos/telluricPlanemo/terrain/chunks/workerDataTypes.ts rename to src/ts/planets/telluricPlanet/terrain/chunks/workerDataTypes.ts diff --git a/src/ts/planemos/telluricPlanemo/terrain/chunks/workerPool.ts b/src/ts/planets/telluricPlanet/terrain/chunks/workerPool.ts similarity index 100% rename from src/ts/planemos/telluricPlanemo/terrain/chunks/workerPool.ts rename to src/ts/planets/telluricPlanet/terrain/chunks/workerPool.ts diff --git a/src/ts/planemos/telluricPlanemo/terrain/instancePatch/hierarchyInstancePatch.ts b/src/ts/planets/telluricPlanet/terrain/instancePatch/hierarchyInstancePatch.ts similarity index 100% rename from src/ts/planemos/telluricPlanemo/terrain/instancePatch/hierarchyInstancePatch.ts rename to src/ts/planets/telluricPlanet/terrain/instancePatch/hierarchyInstancePatch.ts diff --git a/src/ts/planemos/telluricPlanemo/terrain/instancePatch/iPatch.ts b/src/ts/planets/telluricPlanet/terrain/instancePatch/iPatch.ts similarity index 94% rename from src/ts/planemos/telluricPlanemo/terrain/instancePatch/iPatch.ts rename to src/ts/planets/telluricPlanet/terrain/instancePatch/iPatch.ts index 747a0e0d8..04d04630d 100644 --- a/src/ts/planemos/telluricPlanemo/terrain/instancePatch/iPatch.ts +++ b/src/ts/planets/telluricPlanet/terrain/instancePatch/iPatch.ts @@ -1,4 +1,3 @@ -import { Vector3 } from "@babylonjs/core/Maths/math.vector"; import { TransformNode } from "@babylonjs/core/Meshes/transformNode"; export interface IPatch { diff --git a/src/ts/planemos/telluricPlanemo/terrain/instancePatch/instancePatch.ts b/src/ts/planets/telluricPlanet/terrain/instancePatch/instancePatch.ts similarity index 100% rename from src/ts/planemos/telluricPlanemo/terrain/instancePatch/instancePatch.ts rename to src/ts/planets/telluricPlanet/terrain/instancePatch/instancePatch.ts diff --git a/src/ts/planemos/telluricPlanemo/terrain/instancePatch/matrixBuffer.ts b/src/ts/planets/telluricPlanet/terrain/instancePatch/matrixBuffer.ts similarity index 99% rename from src/ts/planemos/telluricPlanemo/terrain/instancePatch/matrixBuffer.ts rename to src/ts/planets/telluricPlanet/terrain/instancePatch/matrixBuffer.ts index b243beeae..f3a39d863 100644 --- a/src/ts/planemos/telluricPlanemo/terrain/instancePatch/matrixBuffer.ts +++ b/src/ts/planets/telluricPlanet/terrain/instancePatch/matrixBuffer.ts @@ -68,7 +68,6 @@ export function decomposeModelMatrix(matrix: Float32Array, position: Vector3, ro rotation.copyFrom(Quaternion.FromRotationMatrix(rotationMatrix)); } - export function applyTransformationToBuffer(transformation: Matrix, matrixBuffer: Float32Array): Float32Array { const nbMatrices = Math.floor(matrixBuffer.length / 16); const result = new Float32Array(matrixBuffer.length); @@ -79,4 +78,4 @@ export function applyTransformationToBuffer(transformation: Matrix, matrixBuffer matrix.copyToArray(result, index); } return result; -} \ No newline at end of file +} diff --git a/src/ts/planemos/telluricPlanemo/terrain/instancePatch/patchManager.ts b/src/ts/planets/telluricPlanet/terrain/instancePatch/patchManager.ts similarity index 100% rename from src/ts/planemos/telluricPlanemo/terrain/instancePatch/patchManager.ts rename to src/ts/planets/telluricPlanet/terrain/instancePatch/patchManager.ts diff --git a/src/ts/planemos/telluricPlanemo/terrain/instancePatch/thinInstancePatch.ts b/src/ts/planets/telluricPlanet/terrain/instancePatch/thinInstancePatch.ts similarity index 92% rename from src/ts/planemos/telluricPlanemo/terrain/instancePatch/thinInstancePatch.ts rename to src/ts/planets/telluricPlanet/terrain/instancePatch/thinInstancePatch.ts index d6f187d9e..c65aaaf49 100644 --- a/src/ts/planemos/telluricPlanemo/terrain/instancePatch/thinInstancePatch.ts +++ b/src/ts/planets/telluricPlanet/terrain/instancePatch/thinInstancePatch.ts @@ -21,8 +21,8 @@ export class ThinInstancePatch implements IPatch { } public static CreateSquare(parent: TransformNode, position: Vector3, size: number, resolution: number) { - const buffer = createSquareMatrixBuffer(position, size, resolution); - return new ThinInstancePatch(parent, buffer); + const buffer = createSquareMatrixBuffer(position, size, resolution); + return new ThinInstancePatch(parent, buffer); } public clearInstances(): void { @@ -54,7 +54,7 @@ export class ThinInstancePatch implements IPatch { } public syncWithParent(): void { - if(this.baseMesh === null) throw new Error("Tried to sync with parent but no base mesh was set."); + if (this.baseMesh === null) throw new Error("Tried to sync with parent but no base mesh was set."); this.matrixBuffer.set(applyTransformationToBuffer(this.parent.computeWorldMatrix(), this.rawMatrixBuffer)); this.baseMesh.thinInstanceBufferUpdated("matrix"); } diff --git a/src/ts/planemos/telluricPlanemo/terrain/terrainSettings.ts b/src/ts/planets/telluricPlanet/terrain/terrainSettings.ts similarity index 100% rename from src/ts/planemos/telluricPlanemo/terrain/terrainSettings.ts rename to src/ts/planets/telluricPlanet/terrain/terrainSettings.ts diff --git a/src/ts/planemos/telluricPlanemo/terrain/workers/buildScript.ts b/src/ts/planets/telluricPlanet/terrain/workers/buildScript.ts similarity index 100% rename from src/ts/planemos/telluricPlanemo/terrain/workers/buildScript.ts rename to src/ts/planets/telluricPlanet/terrain/workers/buildScript.ts diff --git a/src/ts/playground.ts b/src/ts/playground.ts index 05536fc0e..b12da8753 100644 --- a/src/ts/playground.ts +++ b/src/ts/playground.ts @@ -11,8 +11,8 @@ import { Engine } from "@babylonjs/core/Engines/engine"; import HavokPhysics from "@babylonjs/havok"; import { HavokPlugin } from "@babylonjs/core/Physics/v2/Plugins/havokPlugin"; import { setMaxLinVel } from "./utils/havok"; -import { TelluricPlanemo } from "./planemos/telluricPlanemo/telluricPlanemo"; -import { ChunkForgeWorkers } from "./planemos/telluricPlanemo/terrain/chunks/chunkForgeWorkers"; +import { TelluricPlanet } from "./planets/telluricPlanet/telluricPlanet"; +import { ChunkForgeWorkers } from "./planets/telluricPlanet/terrain/chunks/chunkForgeWorkers"; import { StarfieldPostProcess } from "./postProcesses/starfieldPostProcess"; import { Quaternion } from "@babylonjs/core/Maths/math"; import { AtmosphericScatteringPostProcess } from "./postProcesses/atmosphericScatteringPostProcess"; @@ -50,7 +50,7 @@ camera.angularSensibility /= 10; scene.setActiveCamera(camera); camera.attachControl(canvas, true); -const planet = new TelluricPlanemo("xrPlanet", scene, 0.51, undefined); +const planet = new TelluricPlanet("xrPlanet", scene, 0.51, undefined); translate(planet.getTransform(), new Vector3(0, 0, sphereRadius * 4)); const hemiLight = new HemisphericLight("hemiLight", new Vector3(0, 1, 0), scene); @@ -87,7 +87,7 @@ scene.onBeforeRenderObservable.add(() => { chunkForge.update(); - star.updateMaterial(); + star.updateMaterial(deltaTime); ocean.update(deltaTime); }); diff --git a/src/ts/postProcesses/atmosphericScatteringPostProcess.ts b/src/ts/postProcesses/atmosphericScatteringPostProcess.ts index 81db8e088..5e5a1634f 100644 --- a/src/ts/postProcesses/atmosphericScatteringPostProcess.ts +++ b/src/ts/postProcesses/atmosphericScatteringPostProcess.ts @@ -6,11 +6,11 @@ import { Assets } from "../assets"; import { getActiveCameraUniforms, getObjectUniforms, getSamplers, getStellarObjectsUniforms } from "./uniforms"; import { UberPostProcess } from "../uberCore/postProcesses/uberPostProcess"; import { centeredRand } from "extended-random"; -import { TelluricPlanemo } from "../planemos/telluricPlanemo/telluricPlanemo"; -import { GasPlanet } from "../planemos/gasPlanet/gasPlanet"; +import { TelluricPlanet } from "../planets/telluricPlanet/telluricPlanet"; +import { GasPlanet } from "../planets/gasPlanet/gasPlanet"; import { ObjectPostProcess } from "./objectPostProcess"; import { UniformEnumType, ShaderSamplers, ShaderUniforms, SamplerEnumType } from "../uberCore/postProcesses/types"; -import { Transformable } from "../uberCore/transforms/basicTransform"; +import { Transformable } from "../architecture/transformable"; export interface AtmosphereUniforms { atmosphereRadius: number; @@ -27,9 +27,9 @@ export interface AtmosphereUniforms { export class AtmosphericScatteringPostProcess extends UberPostProcess implements ObjectPostProcess { readonly atmosphereUniforms: AtmosphereUniforms; - readonly object: TelluricPlanemo | GasPlanet; + readonly object: TelluricPlanet | GasPlanet; - constructor(name: string, planet: GasPlanet | TelluricPlanemo, atmosphereHeight: number, scene: UberScene, stellarObjects: Transformable[]) { + constructor(name: string, planet: GasPlanet | TelluricPlanet, atmosphereHeight: number, scene: UberScene, stellarObjects: Transformable[]) { const shaderName = "atmosphericScattering"; if (Effect.ShadersStore[`${shaderName}FragmentShader`] === undefined) { Effect.ShadersStore[`${shaderName}FragmentShader`] = atmosphericScatteringFragment; diff --git a/src/ts/postProcesses/clouds/flatCloudsPostProcess.ts b/src/ts/postProcesses/clouds/flatCloudsPostProcess.ts index 83892709e..6db77d50d 100644 --- a/src/ts/postProcesses/clouds/flatCloudsPostProcess.ts +++ b/src/ts/postProcesses/clouds/flatCloudsPostProcess.ts @@ -6,9 +6,9 @@ import { UberPostProcess } from "../../uberCore/postProcesses/uberPostProcess"; import { getActiveCameraUniforms, getObjectUniforms, getSamplers, getStellarObjectsUniforms } from "../uniforms"; import { ObjectPostProcess, UpdatablePostProcess } from "../objectPostProcess"; import { ShaderSamplers, ShaderUniforms } from "../../uberCore/postProcesses/types"; -import { Transformable } from "../../uberCore/transforms/basicTransform"; +import { Transformable } from "../../architecture/transformable"; import { CloudsUniforms } from "./cloudsUniforms"; -import { BoundingSphere } from "../../bodies/common"; +import { BoundingSphere } from "../../architecture/boundingSphere"; export class FlatCloudsPostProcess extends UberPostProcess implements ObjectPostProcess, UpdatablePostProcess { readonly cloudUniforms: CloudsUniforms; diff --git a/src/ts/postProcesses/lensFlarePostProcess.ts b/src/ts/postProcesses/lensFlarePostProcess.ts index 52be5cdde..b6fa86f9d 100644 --- a/src/ts/postProcesses/lensFlarePostProcess.ts +++ b/src/ts/postProcesses/lensFlarePostProcess.ts @@ -5,13 +5,13 @@ import { UberPostProcess } from "../uberCore/postProcesses/uberPostProcess"; import { ObjectPostProcess } from "./objectPostProcess"; import { Effect } from "@babylonjs/core/Materials/effect"; import { ShaderSamplers, ShaderUniforms, UniformEnumType } from "../uberCore/postProcesses/types"; -import { StellarObject } from "../stellarObjects/stellarObject"; import { Vector3 } from "@babylonjs/core/Maths/math.vector"; import { moveTowards } from "../utils/moveTowards"; import { Star } from "../stellarObjects/star/star"; import { PhysicsRaycastResult } from "@babylonjs/core/Physics/physicsRaycastResult"; import { PhysicsEngineV2 } from "@babylonjs/core/Physics/v2"; import { Matrix } from "@babylonjs/core/Maths/math"; +import { StellarObject } from "../architecture/stellarObject"; export type LensFlareSettings = { visibility: number; @@ -71,7 +71,7 @@ export class LensFlarePostProcess extends UberPostProcess implements ObjectPostP const start = scene.activeCamera.globalPosition; const end = object.getTransform().getAbsolutePosition(); (scene.getPhysicsEngine() as PhysicsEngineV2).raycastToRef(start, end, raycastResult); - const occulted = raycastResult.hasHit && raycastResult.body?.transformNode.name !== object.name; + const occulted = raycastResult.hasHit && raycastResult.body?.transformNode !== object.getTransform(); const isNotVisible = occulted || settings.behindCamera; diff --git a/src/ts/postProcesses/mandelbulbPostProcess.ts b/src/ts/postProcesses/mandelbulbPostProcess.ts index a9089949d..a046449c1 100644 --- a/src/ts/postProcesses/mandelbulbPostProcess.ts +++ b/src/ts/postProcesses/mandelbulbPostProcess.ts @@ -4,9 +4,9 @@ import { getActiveCameraUniforms, getObjectUniforms, getSamplers, getStellarObje import { UberPostProcess } from "../uberCore/postProcesses/uberPostProcess"; import { ObjectPostProcess } from "./objectPostProcess"; import { Effect } from "@babylonjs/core/Materials/effect"; -import { StellarObject } from "../stellarObjects/stellarObject"; import { UniformEnumType, ShaderSamplers, ShaderUniforms } from "../uberCore/postProcesses/types"; import { Mandelbulb } from "../mandelbulb/mandelbulb"; +import { StellarObject } from "../architecture/stellarObject"; export interface MandelbulbSettings { rotationPeriod: number; diff --git a/src/ts/postProcesses/matterJetPostProcess.ts b/src/ts/postProcesses/matterJetPostProcess.ts index bd5422a4d..218eda0bb 100644 --- a/src/ts/postProcesses/matterJetPostProcess.ts +++ b/src/ts/postProcesses/matterJetPostProcess.ts @@ -6,7 +6,6 @@ import { Effect } from "@babylonjs/core/Materials/effect"; import { StellarObject } from "../stellarObjects/stellarObject"; import { ObjectPostProcess, UpdatablePostProcess } from "./objectPostProcess"; import { UniformEnumType, ShaderSamplers, ShaderUniforms } from "../uberCore/postProcesses/types"; -import { BaseObject } from "../bodies/common"; export interface MatterJetUniforms { // the rotation period in seconds of the matter jet @@ -19,7 +18,7 @@ export interface MatterJetUniforms { */ export class MatterJetPostProcess extends UberPostProcess implements ObjectPostProcess, UpdatablePostProcess { matterJetUniforms: MatterJetUniforms; - object: BaseObject; + object: StellarObject; constructor(name: string, stellarObject: StellarObject, scene: UberScene) { const shaderName = "matterjet"; diff --git a/src/ts/postProcesses/objectPostProcess.ts b/src/ts/postProcesses/objectPostProcess.ts index d0f8b4167..3fe98d27f 100644 --- a/src/ts/postProcesses/objectPostProcess.ts +++ b/src/ts/postProcesses/objectPostProcess.ts @@ -1,5 +1,5 @@ import { PostProcess } from "@babylonjs/core/PostProcesses/postProcess"; -import { Transformable } from "../uberCore/transforms/basicTransform"; +import { Transformable } from "../architecture/transformable"; export interface UpdatablePostProcess extends PostProcess { /** diff --git a/src/ts/postProcesses/oceanPostProcess.ts b/src/ts/postProcesses/oceanPostProcess.ts index 38f5c44e1..f76daaf2e 100644 --- a/src/ts/postProcesses/oceanPostProcess.ts +++ b/src/ts/postProcesses/oceanPostProcess.ts @@ -5,10 +5,11 @@ import { UberScene } from "../uberCore/uberScene"; import { UberPostProcess } from "../uberCore/postProcesses/uberPostProcess"; import { getActiveCameraUniforms, getObjectUniforms, getSamplers, getStellarObjectsUniforms } from "./uniforms"; import { ObjectPostProcess, UpdatablePostProcess } from "./objectPostProcess"; -import { getInverseRotationQuaternion, Transformable } from "../uberCore/transforms/basicTransform"; +import { getInverseRotationQuaternion } from "../uberCore/transforms/basicTransform"; import { UniformEnumType, ShaderSamplers, ShaderUniforms, SamplerEnumType } from "../uberCore/postProcesses/types"; -import { BoundingSphere } from "../bodies/common"; +import { BoundingSphere } from "../architecture/boundingSphere"; import { Assets } from "../assets"; +import { Transformable } from "../architecture/transformable"; export type OceanUniforms = { oceanRadius: number; diff --git a/src/ts/postProcesses/postProcessManager.ts b/src/ts/postProcesses/postProcessManager.ts index 2bc6f2aa6..f7ccf51b4 100644 --- a/src/ts/postProcesses/postProcessManager.ts +++ b/src/ts/postProcesses/postProcessManager.ts @@ -1,27 +1,24 @@ import { UberScene } from "../uberCore/uberScene"; import { UberRenderingPipeline } from "../uberCore/uberRenderingPipeline"; import { OceanPostProcess } from "./oceanPostProcess"; -import { TelluricPlanemo } from "../planemos/telluricPlanemo/telluricPlanemo"; +import { TelluricPlanet } from "../planets/telluricPlanet/telluricPlanet"; import { FlatCloudsPostProcess } from "./clouds/flatCloudsPostProcess"; import { Settings } from "../settings"; import { AtmosphericScatteringPostProcess } from "./atmosphericScatteringPostProcess"; -import { AbstractBody } from "../bodies/abstractBody"; import { RingsPostProcess } from "./rings/ringsPostProcess"; import { StarfieldPostProcess } from "./starfieldPostProcess"; import { VolumetricLight } from "./volumetricLight"; import { BlackHolePostProcess } from "./blackHolePostProcess"; -import { GasPlanet } from "../planemos/gasPlanet/gasPlanet"; +import { GasPlanet } from "../planets/gasPlanet/gasPlanet"; import { ColorCorrection } from "../uberCore/postProcesses/colorCorrection"; import { makeSplitRenderEffects } from "../utils/extractRelevantPostProcesses"; import { CloudsPostProcess } from "./volumetricCloudsPostProcess"; -import { StellarObject } from "../stellarObjects/stellarObject"; import { Engine } from "@babylonjs/core/Engines/engine"; import { FxaaPostProcess } from "@babylonjs/core/PostProcesses/fxaaPostProcess"; import { PostProcessRenderEffect } from "@babylonjs/core/PostProcesses/RenderPipeline/postProcessRenderEffect"; import { BloomEffect } from "@babylonjs/core/PostProcesses/bloomEffect"; import { Texture } from "@babylonjs/core/Materials/Textures/texture"; import "@babylonjs/core/PostProcesses/RenderPipeline/postProcessRenderPipelineManagerSceneComponent"; -import { AbstractObject } from "../bodies/abstractObject"; import { PostProcessType } from "./postProcessTypes"; import { MandelbulbPostProcess } from "./mandelbulbPostProcess"; import { ShadowPostProcess } from "./shadowPostProcess"; @@ -34,6 +31,8 @@ import { Mandelbulb } from "../mandelbulb/mandelbulb"; import { Star } from "../stellarObjects/star/star"; import { BlackHole } from "../stellarObjects/blackHole/blackHole"; import { NeutronStar } from "../stellarObjects/neutronStar/neutronStar"; +import { CelestialBody } from "../architecture/celestialBody"; +import { StellarObject } from "../architecture/stellarObject"; /** * The order in which the post processes are rendered when away from a planet @@ -78,7 +77,7 @@ export class PostProcessManager { private currentRenderingOrder: PostProcessType[] = spaceRenderingOrder; - private currentBody: AbstractObject | null = null; + private currentBody: CelestialBody | null = null; private readonly starFields: StarfieldPostProcess[] = []; private readonly volumetricLights: VolumetricLight[] = []; @@ -152,7 +151,8 @@ export class PostProcessManager { return this.starFields; }); - this.bloomRenderEffect = new BloomEffect(scene, 1, 0.3, 32); + this.bloomRenderEffect = new BloomEffect(scene, 1.0, 1.0, 32); + this.bloomRenderEffect.threshold = 0.7; } /** @@ -160,7 +160,7 @@ export class PostProcessManager { * @param planet A telluric planet * @param stellarObjects An array of stars or black holes */ - public addOcean(planet: TelluricPlanemo, stellarObjects: StellarObject[]) { + public addOcean(planet: TelluricPlanet, stellarObjects: StellarObject[]) { const ocean = new OceanPostProcess(`${planet.name}Ocean`, planet, this.scene, stellarObjects); this.oceans.push(ocean); } @@ -169,7 +169,7 @@ export class PostProcessManager { * Returns the ocean post process for the given planet. Throws an error if no ocean is found. * @param planet A telluric planet */ - public getOcean(planet: TelluricPlanemo): OceanPostProcess | null { + public getOcean(planet: TelluricPlanet): OceanPostProcess | null { return this.oceans.find((ocean) => ocean.object === planet) ?? null; } @@ -178,7 +178,7 @@ export class PostProcessManager { * @param planet A telluric planet * @param stellarObjects An array of stars or black holes */ - public async addClouds(planet: TelluricPlanemo, stellarObjects: StellarObject[]) { + public async addClouds(planet: TelluricPlanet, stellarObjects: StellarObject[]) { const uniforms = planet.model.cloudsUniforms; if (uniforms === null) throw new Error( @@ -193,7 +193,7 @@ export class PostProcessManager { * Returns the clouds post process for the given planet. Throws an error if no clouds are found. * @param planet A telluric planet */ - public getClouds(planet: TelluricPlanemo): CloudsPostProcess | null { + public getClouds(planet: TelluricPlanet): CloudsPostProcess | null { return this.clouds.find((clouds) => clouds.object === planet) ?? null; } @@ -202,7 +202,7 @@ export class PostProcessManager { * @param planet A gas or telluric planet * @param stellarObjects An array of stars or black holes */ - public addAtmosphere(planet: GasPlanet | TelluricPlanemo, stellarObjects: StellarObject[]) { + public addAtmosphere(planet: GasPlanet | TelluricPlanet, stellarObjects: StellarObject[]) { const atmosphere = new AtmosphericScatteringPostProcess( `${planet.name}Atmosphere`, planet, @@ -217,7 +217,7 @@ export class PostProcessManager { * Returns the atmosphere post process for the given planet. Throws an error if no atmosphere is found. * @param planet A gas or telluric planet */ - public getAtmosphere(planet: GasPlanet | TelluricPlanemo): AtmosphericScatteringPostProcess | null { + public getAtmosphere(planet: GasPlanet | TelluricPlanet): AtmosphericScatteringPostProcess | null { return this.atmospheres.find((atmosphere) => atmosphere.object === planet) ?? null; } @@ -226,7 +226,7 @@ export class PostProcessManager { * @param body A body * @param stellarObjects An array of stars or black holes */ - public async addRings(body: AbstractBody, stellarObjects: StellarObject[]) { + public async addRings(body: CelestialBody, stellarObjects: StellarObject[]) { return RingsPostProcess.CreateAsync(body, this.scene, stellarObjects).then((rings) => { this.rings.push(rings); }); @@ -236,7 +236,7 @@ export class PostProcessManager { * Returns the rings post process for the given body. Throws an error if no rings are found. * @param body A body */ - public getRings(body: AbstractObject): RingsPostProcess | null { + public getRings(body: CelestialBody): RingsPostProcess | null { return this.rings.find((rings) => rings.object === body) ?? null; } @@ -254,8 +254,9 @@ export class PostProcessManager { * Creates a new Starfield postprocess and adds it to the manager. * @param stellarObjects An array of stars or black holes * @param planets An array of planets + * @param starfieldRotation */ - public addStarField(stellarObjects: StellarObject[], planets: AbstractBody[], starfieldRotation: Quaternion) { + public addStarField(stellarObjects: StellarObject[], planets: CelestialBody[], starfieldRotation: Quaternion) { this.starFields.push(new StarfieldPostProcess(this.scene, stellarObjects, planets, starfieldRotation)); } @@ -296,7 +297,7 @@ export class PostProcessManager { return this.matterJets.find((mj) => mj.object === neutronStar) ?? null; } - public async addShadowCaster(body: AbstractBody, stellarObjects: StellarObject[]) { + public async addShadowCaster(body: CelestialBody, stellarObjects: StellarObject[]) { return ShadowPostProcess.CreateAsync(body, this.scene, stellarObjects).then((shadow) => { this.shadows.push(shadow); }); @@ -306,7 +307,7 @@ export class PostProcessManager { this.lensFlares.push(new LensFlarePostProcess(stellarObject, this.scene)); } - public setBody(body: AbstractBody) { + public setBody(body: CelestialBody) { this.currentBody = body; const rings = this.getRings(body); diff --git a/src/ts/postProcesses/rings/ringsPostProcess.ts b/src/ts/postProcesses/rings/ringsPostProcess.ts index 7befceedf..a8036979c 100644 --- a/src/ts/postProcesses/rings/ringsPostProcess.ts +++ b/src/ts/postProcesses/rings/ringsPostProcess.ts @@ -1,5 +1,4 @@ import ringsFragment from "../../../shaders/ringsFragment.glsl"; -import { AbstractBody } from "../../bodies/abstractBody"; import { UberScene } from "../../uberCore/uberScene"; import { UberPostProcess } from "../../uberCore/postProcesses/uberPostProcess"; import { getActiveCameraUniforms, getObjectUniforms, getSamplers, getStellarObjectsUniforms } from "../uniforms"; @@ -7,19 +6,20 @@ import { ObjectPostProcess } from "../objectPostProcess"; import { Effect } from "@babylonjs/core/Materials/effect"; import { ShaderSamplers, ShaderUniforms } from "../../uberCore/postProcesses/types"; import { RingsUniforms } from "./ringsUniform"; -import { Transformable } from "../../uberCore/transforms/basicTransform"; +import { CelestialBody } from "../../architecture/celestialBody"; +import { Transformable } from "../../architecture/transformable"; export class RingsPostProcess extends UberPostProcess implements ObjectPostProcess { readonly ringsUniforms: RingsUniforms; - readonly object: AbstractBody; + readonly object: CelestialBody; - public static async CreateAsync(body: AbstractBody, scene: UberScene, stellarObjects: Transformable[]): Promise { + public static async CreateAsync(body: CelestialBody, scene: UberScene, stellarObjects: Transformable[]): Promise { const shaderName = "rings"; if (Effect.ShadersStore[`${shaderName}FragmentShader`] === undefined) { Effect.ShadersStore[`${shaderName}FragmentShader`] = ringsFragment; } - const ringsUniforms = body.model.ringsUniforms; + const ringsUniforms = body.getRingsUniforms(); if (ringsUniforms === null) throw new Error( `RingsPostProcess: ringsUniforms are null. This should not be possible as the postprocess should not be created if the body has no rings. Body: ${body.name}` @@ -37,7 +37,7 @@ export class RingsPostProcess extends UberPostProcess implements ObjectPostProce }); } - private constructor(name: string, shaderName: string, uniforms: ShaderUniforms, samplers: ShaderSamplers, scene: UberScene, body: AbstractBody, ringsUniforms: RingsUniforms) { + private constructor(name: string, shaderName: string, uniforms: ShaderUniforms, samplers: ShaderSamplers, scene: UberScene, body: CelestialBody, ringsUniforms: RingsUniforms) { super(name, shaderName, uniforms, samplers, scene); this.object = body; diff --git a/src/ts/postProcesses/shadowPostProcess.ts b/src/ts/postProcesses/shadowPostProcess.ts index 70a03d3d4..af9460efa 100644 --- a/src/ts/postProcesses/shadowPostProcess.ts +++ b/src/ts/postProcesses/shadowPostProcess.ts @@ -1,15 +1,15 @@ import shadowFragment from "../../shaders/shadowFragment.glsl"; -import { AbstractBody } from "../bodies/abstractBody"; import { UberScene } from "../uberCore/uberScene"; import { UberPostProcess } from "../uberCore/postProcesses/uberPostProcess"; import { getActiveCameraUniforms, getObjectUniforms, getSamplers, getStellarObjectsUniforms } from "./uniforms"; import { ObjectPostProcess } from "./objectPostProcess"; -import { StellarObject } from "../stellarObjects/stellarObject"; import { Effect } from "@babylonjs/core/Materials/effect"; import { SamplerEnumType, ShaderSamplers, ShaderUniforms, UniformEnumType } from "../uberCore/postProcesses/types"; import { PostProcessType } from "./postProcessTypes"; import { RingsUniforms } from "./rings/ringsUniform"; import { Assets } from "../assets"; +import { CelestialBody } from "../architecture/celestialBody"; +import { StellarObject } from "../architecture/stellarObject"; export type ShadowUniforms = { hasRings: boolean; @@ -18,17 +18,17 @@ export type ShadowUniforms = { }; export class ShadowPostProcess extends UberPostProcess implements ObjectPostProcess { - readonly object: AbstractBody; + readonly object: CelestialBody; readonly shadowUniforms: ShadowUniforms; - public static async CreateAsync(body: AbstractBody, scene: UberScene, stellarObjects: StellarObject[]): Promise { + public static async CreateAsync(body: CelestialBody, scene: UberScene, stellarObjects: StellarObject[]): Promise { const shaderName = "shadow"; if (Effect.ShadersStore[`${shaderName}FragmentShader`] === undefined) { Effect.ShadersStore[`${shaderName}FragmentShader`] = shadowFragment; } const shadowUniforms: ShadowUniforms = { - hasRings: body.model.ringsUniforms !== null, + hasRings: body.getRingsUniforms() !== null, hasClouds: body.postProcesses.includes(PostProcessType.CLOUDS), hasOcean: body.postProcesses.includes(PostProcessType.OCEAN) }; @@ -64,8 +64,9 @@ export class ShadowPostProcess extends UberPostProcess implements ObjectPostProc } ]; - const ringsUniforms = body.model.ringsUniforms as RingsUniforms; if (shadowUniforms.hasRings) { + const ringsUniforms = body.getRingsUniforms(); + if (ringsUniforms === null) throw new Error("shadowUniforms.hasRings is true and yet body.getRingsUniforms() returned null!"); uniforms.push(...ringsUniforms.getShaderUniforms()); return ringsUniforms.getShaderSamplers(scene).then((ringSamplers) => { @@ -90,7 +91,7 @@ export class ShadowPostProcess extends UberPostProcess implements ObjectPostProc private constructor( name: string, - body: AbstractBody, + body: CelestialBody, scene: UberScene, shaderName: string, uniforms: ShaderUniforms, diff --git a/src/ts/postProcesses/starfieldPostProcess.ts b/src/ts/postProcesses/starfieldPostProcess.ts index 630b3adcd..d96567d50 100644 --- a/src/ts/postProcesses/starfieldPostProcess.ts +++ b/src/ts/postProcesses/starfieldPostProcess.ts @@ -1,11 +1,10 @@ import starfieldFragment from "../../shaders/starfieldFragment.glsl"; -import { TelluricPlanemo } from "../planemos/telluricPlanemo/telluricPlanemo"; +import { TelluricPlanet } from "../planets/telluricPlanet/telluricPlanet"; import { UberScene } from "../uberCore/uberScene"; import { getActiveCameraUniforms, getSamplers, getStellarObjectsUniforms } from "./uniforms"; import { UberPostProcess } from "../uberCore/postProcesses/uberPostProcess"; import { Settings } from "../settings"; import { nearestBody } from "../utils/nearestBody"; -import { AbstractBody } from "../bodies/abstractBody"; import { Assets } from "../assets"; import { Effect } from "@babylonjs/core/Materials/effect"; import { Vector3 } from "@babylonjs/core/Maths/math.vector"; @@ -14,10 +13,11 @@ import { Axis } from "@babylonjs/core/Maths/math.axis"; import { SamplerEnumType, ShaderSamplers, ShaderUniforms, UniformEnumType } from "../uberCore/postProcesses/types"; import { Matrix, Quaternion } from "@babylonjs/core/Maths/math"; import { BlackHole } from "../stellarObjects/blackHole/blackHole"; -import { Transformable } from "../uberCore/transforms/basicTransform"; +import { Transformable } from "../architecture/transformable"; +import { CelestialBody } from "../architecture/celestialBody"; export class StarfieldPostProcess extends UberPostProcess { - constructor(scene: UberScene, stellarObjects: Transformable[], bodies: AbstractBody[], starfieldRotation: Quaternion) { + constructor(scene: UberScene, stellarObjects: Transformable[], bodies: CelestialBody[], starfieldRotation: Quaternion) { const shaderName = "starfield"; if (Effect.ShadersStore[`${shaderName}FragmentShader`] === undefined) { Effect.ShadersStore[`${shaderName}FragmentShader`] = starfieldFragment; @@ -53,8 +53,8 @@ export class StarfieldPostProcess extends UberPostProcess { vis = 0.5 + vis * 0.5; let vis2 = 1.0; const nearest = nearestBody(camera.globalPosition, bodies); - if (nearest instanceof TelluricPlanemo) { - const planet = nearest as TelluricPlanemo; + if (nearest instanceof TelluricPlanet) { + const planet = nearest as TelluricPlanet; if (planet.postProcesses.includes(PostProcessType.ATMOSPHERE)) { const height = planet.getTransform().getAbsolutePosition().length(); //FIXME: has to be dynamic diff --git a/src/ts/postProcesses/uniforms.ts b/src/ts/postProcesses/uniforms.ts index 25cb3d317..710365223 100644 --- a/src/ts/postProcesses/uniforms.ts +++ b/src/ts/postProcesses/uniforms.ts @@ -1,9 +1,9 @@ import { UberScene } from "../uberCore/uberScene"; import { SamplerEnumType, ShaderSamplers, ShaderUniforms, UniformEnumType } from "../uberCore/postProcesses/types"; import { Vector3 } from "@babylonjs/core/Maths/math.vector"; -import { BoundingSphere } from "../bodies/common"; +import { BoundingSphere } from "../architecture/boundingSphere"; import { Star } from "../stellarObjects/star/star"; -import { Transformable } from "../uberCore/transforms/basicTransform"; +import { Transformable } from "../architecture/transformable"; import { Scene } from "@babylonjs/core/scene"; export function getActiveCameraUniforms(scene: Scene): ShaderUniforms { diff --git a/src/ts/postProcesses/volumetricCloudsPostProcess.ts b/src/ts/postProcesses/volumetricCloudsPostProcess.ts index 84048013e..d541ebebb 100644 --- a/src/ts/postProcesses/volumetricCloudsPostProcess.ts +++ b/src/ts/postProcesses/volumetricCloudsPostProcess.ts @@ -8,8 +8,9 @@ import { Effect } from "@babylonjs/core/Materials/effect"; import { UniformEnumType, ShaderSamplers, ShaderUniforms } from "../uberCore/postProcesses/types"; import { StellarObject } from "../stellarObjects/stellarObject"; import { CloudsUniforms } from "./clouds/cloudsUniforms"; -import { Transformable } from "../uberCore/transforms/basicTransform"; -import { BoundingSphere } from "../bodies/common"; + +import { BoundingSphere } from "../architecture/boundingSphere"; +import { Transformable } from "../architecture/transformable"; export type CloudsPostProcess = FlatCloudsPostProcess | VolumetricCloudsPostProcess; diff --git a/src/ts/proceduralAssets/butterfly/butterflyMaterial.ts b/src/ts/proceduralAssets/butterfly/butterflyMaterial.ts index 9454e19b3..35b99e030 100644 --- a/src/ts/proceduralAssets/butterfly/butterflyMaterial.ts +++ b/src/ts/proceduralAssets/butterfly/butterflyMaterial.ts @@ -29,10 +29,10 @@ export function createButterflyMaterial(scene: Scene, player?: TransformNode) { scene.onBeforeRenderObservable.add(() => { elapsedSeconds += scene.getEngine().getDeltaTime() / 1000; - if(scene.activeCamera === null) throw new Error("Active camera is null"); + if (scene.activeCamera === null) throw new Error("Active camera is null"); const star = scene.lights[1]; - if(!(star instanceof PointLight)) throw new Error("Could not find star light"); + if (!(star instanceof PointLight)) throw new Error("Could not find star light"); const lightDirection = star.position.subtract(scene.activeCamera.globalPosition).normalize(); butterflyMaterial.setVector3("lightDirection", lightDirection); diff --git a/src/ts/proceduralAssets/grass/grassBlade.ts b/src/ts/proceduralAssets/grass/grassBlade.ts index 2993dc2b1..694e4b29b 100644 --- a/src/ts/proceduralAssets/grass/grassBlade.ts +++ b/src/ts/proceduralAssets/grass/grassBlade.ts @@ -6,84 +6,84 @@ import { createGrassMaterial } from "./grassMaterial"; // rotation using https://www.wikiwand.com/en/Rodrigues%27_rotation_formula function rotateAround(vector: Vector3, axis: Vector3, theta: number) { - // Please note that unit vector are required, i did not divide by the norms - return vector - .scale(Math.cos(theta)) - .addInPlace(Vector3.Cross(axis, vector).scaleInPlace(Math.sin(theta))) - .addInPlace(axis.scale(Vector3.Dot(axis, vector) * (1.0 - Math.cos(theta)))); + // Please note that unit vector are required, i did not divide by the norms + return vector + .scale(Math.cos(theta)) + .addInPlace(Vector3.Cross(axis, vector).scaleInPlace(Math.sin(theta))) + .addInPlace(axis.scale(Vector3.Dot(axis, vector) * (1.0 - Math.cos(theta)))); } export function createGrassBlade(scene: Scene, nbStacks: number) { - const nbVertices = 2 * nbStacks + 1; - const nbTriangles = 2 * (nbStacks - 1) + 1; - - const positions = new Float32Array(nbVertices * 3); - const normals = new Float32Array(nbVertices * 3); - const indices = new Uint32Array(nbTriangles * 3); - - const normal = new Vector3(0, 0, 1); - const curvyNormal1 = rotateAround(normal, new Vector3(0, 1, 0), Math.PI * 0.3); - const curvyNormal2 = rotateAround(normal, new Vector3(0, 1, 0), -Math.PI * 0.3); - - // The vertices are aranged in rows of 2 vertices, we stack the rows on top of each other until we reach the top of the blade - let vertexIndex = 0; - let normalIndex = 0; - let indexIndex = 0; - const step = 1 / nbStacks; - for (let i = 0; i < nbStacks; i++) { - positions[vertexIndex++] = -0.05 * (nbStacks - i) * step; - positions[vertexIndex++] = i * step; - positions[vertexIndex++] = 0; - - positions[vertexIndex++] = 0.05 * (nbStacks - i) * step; - positions[vertexIndex++] = i * step; - positions[vertexIndex++] = 0; - - normals[normalIndex++] = curvyNormal1.x; - normals[normalIndex++] = curvyNormal1.y; - normals[normalIndex++] = curvyNormal1.z; - - normals[normalIndex++] = curvyNormal2.x; - normals[normalIndex++] = curvyNormal2.y; - normals[normalIndex++] = curvyNormal2.z; - - if (i === 0) { - continue; + const nbVertices = 2 * nbStacks + 1; + const nbTriangles = 2 * (nbStacks - 1) + 1; + + const positions = new Float32Array(nbVertices * 3); + const normals = new Float32Array(nbVertices * 3); + const indices = new Uint32Array(nbTriangles * 3); + + const normal = new Vector3(0, 0, 1); + const curvyNormal1 = rotateAround(normal, new Vector3(0, 1, 0), Math.PI * 0.3); + const curvyNormal2 = rotateAround(normal, new Vector3(0, 1, 0), -Math.PI * 0.3); + + // The vertices are aranged in rows of 2 vertices, we stack the rows on top of each other until we reach the top of the blade + let vertexIndex = 0; + let normalIndex = 0; + let indexIndex = 0; + const step = 1 / nbStacks; + for (let i = 0; i < nbStacks; i++) { + positions[vertexIndex++] = -0.05 * (nbStacks - i) * step; + positions[vertexIndex++] = i * step; + positions[vertexIndex++] = 0; + + positions[vertexIndex++] = 0.05 * (nbStacks - i) * step; + positions[vertexIndex++] = i * step; + positions[vertexIndex++] = 0; + + normals[normalIndex++] = curvyNormal1.x; + normals[normalIndex++] = curvyNormal1.y; + normals[normalIndex++] = curvyNormal1.z; + + normals[normalIndex++] = curvyNormal2.x; + normals[normalIndex++] = curvyNormal2.y; + normals[normalIndex++] = curvyNormal2.z; + + if (i === 0) { + continue; + } + + // make 2 triangles out of the vertices + indices[indexIndex++] = 2 * (i - 1); + indices[indexIndex++] = 2 * (i - 1) + 1; + indices[indexIndex++] = 2 * i; + + indices[indexIndex++] = 2 * i; + indices[indexIndex++] = 2 * (i - 1) + 1; + indices[indexIndex++] = 2 * i + 1; } - // make 2 triangles out of the vertices - indices[indexIndex++] = 2 * (i - 1); - indices[indexIndex++] = 2 * (i - 1) + 1; - indices[indexIndex++] = 2 * i; - - indices[indexIndex++] = 2 * i; - indices[indexIndex++] = 2 * (i - 1) + 1; - indices[indexIndex++] = 2 * i + 1; - } - - // the last vertex is the tip of the blade - positions[vertexIndex++] = 0; - positions[vertexIndex++] = nbStacks * step; - positions[vertexIndex++] = 0; + // the last vertex is the tip of the blade + positions[vertexIndex++] = 0; + positions[vertexIndex++] = nbStacks * step; + positions[vertexIndex++] = 0; - normals[normalIndex++] = 0; - normals[normalIndex++] = 0; - normals[normalIndex++] = 1; + normals[normalIndex++] = 0; + normals[normalIndex++] = 0; + normals[normalIndex++] = 1; - // last triangle - indices[indexIndex++] = 2 * (nbStacks - 1); - indices[indexIndex++] = 2 * (nbStacks - 1) + 1; - indices[indexIndex++] = 2 * nbStacks; + // last triangle + indices[indexIndex++] = 2 * (nbStacks - 1); + indices[indexIndex++] = 2 * (nbStacks - 1) + 1; + indices[indexIndex++] = 2 * nbStacks; - const vertexData = new VertexData(); - vertexData.positions = positions; - vertexData.normals = normals; - vertexData.indices = indices; + const vertexData = new VertexData(); + vertexData.positions = positions; + vertexData.normals = normals; + vertexData.indices = indices; - const grassBlade = new Mesh("grassBlade", scene); - vertexData.applyToMesh(grassBlade); + const grassBlade = new Mesh("grassBlade", scene); + vertexData.applyToMesh(grassBlade); - grassBlade.material = createGrassMaterial(scene); + grassBlade.material = createGrassMaterial(scene); - return grassBlade; -} \ No newline at end of file + return grassBlade; +} diff --git a/src/ts/proceduralAssets/grass/grassMaterial.ts b/src/ts/proceduralAssets/grass/grassMaterial.ts index 67d82ae9e..a4c6c3ed2 100644 --- a/src/ts/proceduralAssets/grass/grassMaterial.ts +++ b/src/ts/proceduralAssets/grass/grassMaterial.ts @@ -10,42 +10,42 @@ import perlinNoise from "../../../asset/perlin.png"; import { PointLight } from "@babylonjs/core/Lights/pointLight"; export function createGrassMaterial(scene: Scene) { - const shaderName = "grassMaterial"; - Effect.ShadersStore[`${shaderName}FragmentShader`] = grassFragment; - Effect.ShadersStore[`${shaderName}VertexShader`] = grassVertex; + const shaderName = "grassMaterial"; + Effect.ShadersStore[`${shaderName}FragmentShader`] = grassFragment; + Effect.ShadersStore[`${shaderName}VertexShader`] = grassVertex; - const grassMaterial = new ShaderMaterial(shaderName, scene, shaderName, { - attributes: ["position", "normal"], - uniforms: ["world", "worldView", "worldViewProjection", "view", "projection", "viewProjection", "time", "lightDirection", "cameraPosition", "playerPosition"], - defines: ["#define INSTANCES"], - samplers: ["perlinNoise"] - }); + const grassMaterial = new ShaderMaterial(shaderName, scene, shaderName, { + attributes: ["position", "normal"], + uniforms: ["world", "worldView", "worldViewProjection", "view", "projection", "viewProjection", "time", "lightDirection", "cameraPosition", "playerPosition"], + defines: ["#define INSTANCES"], + samplers: ["perlinNoise"] + }); - const perlinTexture = new Texture(perlinNoise, scene); + const perlinTexture = new Texture(perlinNoise, scene); - grassMaterial.backFaceCulling = false; - grassMaterial.setTexture("perlinNoise", perlinTexture); + grassMaterial.backFaceCulling = false; + grassMaterial.setTexture("perlinNoise", perlinTexture); - let elapsedSeconds = 0; - scene.onBeforeRenderObservable.add(() => { - elapsedSeconds += scene.getEngine().getDeltaTime() / 1000; + let elapsedSeconds = 0; + scene.onBeforeRenderObservable.add(() => { + elapsedSeconds += scene.getEngine().getDeltaTime() / 1000; - if(scene.activeCamera === null) throw new Error("Active camera is null"); + if (scene.activeCamera === null) throw new Error("Active camera is null"); - const star = scene.lights[1]; - if(!(star instanceof PointLight)) throw new Error("Could not find star light"); + const star = scene.lights[1]; + if (!(star instanceof PointLight)) throw new Error("Could not find star light"); - const lightDirection = star.position.subtract(scene.activeCamera.globalPosition).normalize(); - grassMaterial.setVector3("lightDirection", lightDirection); + const lightDirection = star.position.subtract(scene.activeCamera.globalPosition).normalize(); + grassMaterial.setVector3("lightDirection", lightDirection); - if(scene.activeCamera.parent !== null && !(scene.activeCamera.parent instanceof TransformNode)) throw new Error("Camera parent is not a TransformNode"); + if (scene.activeCamera.parent !== null && !(scene.activeCamera.parent instanceof TransformNode)) throw new Error("Camera parent is not a TransformNode"); - const playerPosition = scene.activeCamera.parent !== null ? scene.activeCamera.parent.getAbsolutePosition() : scene.activeCamera.globalPosition; // high y to avoid interaction with grass - const cameraPosition = scene.activeCamera.globalPosition; - grassMaterial.setVector3("playerPosition", playerPosition); - grassMaterial.setVector3("cameraPosition", cameraPosition); - grassMaterial.setFloat("time", elapsedSeconds); - }); + const playerPosition = scene.activeCamera.parent !== null ? scene.activeCamera.parent.getAbsolutePosition() : scene.activeCamera.globalPosition; // high y to avoid interaction with grass + const cameraPosition = scene.activeCamera.globalPosition; + grassMaterial.setVector3("playerPosition", playerPosition); + grassMaterial.setVector3("cameraPosition", cameraPosition); + grassMaterial.setFloat("time", elapsedSeconds); + }); - return grassMaterial; -} \ No newline at end of file + return grassMaterial; +} diff --git a/src/ts/spacelegs/characterControls.ts b/src/ts/spacelegs/characterControls.ts index 8bbc1b2db..6719cc5ad 100644 --- a/src/ts/spacelegs/characterControls.ts +++ b/src/ts/spacelegs/characterControls.ts @@ -3,7 +3,7 @@ import { TransformNode } from "@babylonjs/core/Meshes"; import { Scene } from "@babylonjs/core/scene"; import { Vector3 } from "@babylonjs/core/Maths/math.vector"; import { Input } from "../inputs/input"; -import { setRotationQuaternion, setUpVector, Transformable, translate } from "../uberCore/transforms/basicTransform"; +import { setRotationQuaternion, setUpVector, translate } from "../uberCore/transforms/basicTransform"; import { Assets } from "../assets"; import { AnimationGroup } from "@babylonjs/core/Animations/animationGroup"; import { Keyboard } from "../inputs/keyboard"; @@ -15,6 +15,7 @@ import { Quaternion } from "@babylonjs/core/Maths/math"; import "@babylonjs/core/Collisions/collisionCoordinator"; import { Camera } from "@babylonjs/core/Cameras/camera"; import { ArcRotateCamera } from "@babylonjs/core/Cameras/arcRotateCamera"; +import { Transformable } from "../architecture/transformable"; class AnimationGroupWrapper { name: string; @@ -252,4 +253,9 @@ export class CharacterControls implements Controls { this.getActiveCamera().getViewMatrix(); return playerMovement; } + + dispose() { + this.character.dispose(); + this.thirdPersonCamera.dispose(); + } } diff --git a/src/ts/spaceship/shipControls.ts b/src/ts/spaceship/shipControls.ts index 260ae0e37..dbd4d89d9 100644 --- a/src/ts/spaceship/shipControls.ts +++ b/src/ts/spaceship/shipControls.ts @@ -13,7 +13,7 @@ import { Observable } from "@babylonjs/core/Misc/observable"; import { Axis } from "@babylonjs/core/Maths/math.axis"; import { HavokPlugin } from "@babylonjs/core/Physics/v2/Plugins/havokPlugin"; import { setEnabledBody } from "../utils/havok"; -import { getForwardDirection, getUpwardDirection, pitch, roll, rotate, Transformable, translate } from "../uberCore/transforms/basicTransform"; +import { getForwardDirection, getUpwardDirection, pitch, roll, rotate, translate } from "../uberCore/transforms/basicTransform"; import { TransformNode } from "@babylonjs/core/Meshes"; import { Controls } from "../uberCore/controls"; import { Assets } from "../assets"; @@ -26,6 +26,7 @@ import { ArcRotateCamera } from "@babylonjs/core/Cameras/arcRotateCamera"; import { PhysicsRaycastResult } from "@babylonjs/core/Physics/physicsRaycastResult"; import { PhysicsEngineV2 } from "@babylonjs/core/Physics/v2"; import { CollisionMask } from "../settings"; +import { Transformable } from "../architecture/transformable"; enum ShipState { FLYING, @@ -330,4 +331,11 @@ export class ShipControls implements Controls { this.getActiveCamera().getViewMatrix(); return this.getTransform().getAbsolutePosition(); } + + dispose() { + this.instanceRoot.dispose(); + this.aggregate.dispose(); + this.thirdPersonCamera.dispose(); + this.firstPersonCamera.dispose(); + } } diff --git a/src/ts/spacestation/spaceStation.ts b/src/ts/spacestation/spaceStation.ts index 967dd0062..fcae7a06d 100644 --- a/src/ts/spacestation/spaceStation.ts +++ b/src/ts/spacestation/spaceStation.ts @@ -2,13 +2,20 @@ import { InstancedMesh } from "@babylonjs/core/Meshes/instancedMesh"; import { Scene } from "@babylonjs/core/scene"; import { isSizeOnScreenEnough } from "../utils/isObjectVisibleOnScreen"; import { Camera } from "@babylonjs/core/Cameras/camera"; -import { AbstractObject } from "../bodies/abstractObject"; import { SpaceStationModel } from "./spacestationModel"; import { PostProcessType } from "../postProcesses/postProcessTypes"; import { Assets } from "../assets"; import { Axis } from "@babylonjs/core/Maths/math.axis"; +import { OrbitalObject } from "../architecture/orbitalObject"; +import { Cullable } from "../bodies/cullable"; +import { TransformNode } from "@babylonjs/core/Meshes"; +import { OrbitProperties } from "../orbit/orbitProperties"; +import { Vector3 } from "@babylonjs/core/Maths/math.vector"; +import { OrbitalObjectPhysicalProperties } from "../architecture/physicalProperties"; + +export class SpaceStation implements OrbitalObject, Cullable { + readonly name: string; -export class SpaceStation extends AbstractObject { readonly model: SpaceStationModel; readonly postProcesses: PostProcessType[] = []; @@ -17,13 +24,19 @@ export class SpaceStation extends AbstractObject { readonly ringInstances: InstancedMesh[] = []; - constructor(scene: Scene, parentBody?: AbstractObject) { - super("spaceStation", scene, parentBody); + readonly parent: OrbitalObject | null = null; + + constructor(scene: Scene, parentBody: OrbitalObject | null = null) { + //TODO: do not hardcode name + this.name = "Spacestation"; + //TODO: do not hardcode seed const seed = 1; this.model = new SpaceStationModel(seed, parentBody?.model); + this.parent = parentBody; + this.instance = Assets.CreateSpaceStationInstance(); this.instance.parent = this.getTransform(); @@ -37,7 +50,23 @@ export class SpaceStation extends AbstractObject { this.getTransform().rotate(Axis.Y, this.model.physicalProperties.axialTilt); } - public override getBoundingRadius(): number { + getTransform(): TransformNode { + return this.instance; + } + + getRotationAxis(): Vector3 { + return this.getTransform().up; + } + + getOrbitProperties(): OrbitProperties { + return this.model.orbit; + } + + getPhysicalProperties(): OrbitalObjectPhysicalProperties { + return this.model.physicalProperties; + } + + public getBoundingRadius(): number { return 1e3; } @@ -45,14 +74,14 @@ export class SpaceStation extends AbstractObject { return "Space Station"; } - public override computeCulling(camera: Camera): void { + public computeCulling(camera: Camera): void { const isVisible = isSizeOnScreenEnough(this, camera); for (const mesh of this.instance.getChildMeshes()) { mesh.isVisible = isVisible; } } - public override updateRotation(deltaTime: number): number { + public updateRotation(deltaTime: number): number { const dtheta = deltaTime / this.model.physicalProperties.rotationPeriod; if (this.ringInstances.length === 0) this.instance.rotate(Axis.Z, dtheta); @@ -64,7 +93,7 @@ export class SpaceStation extends AbstractObject { return dtheta; } - public override dispose(): void { + public dispose(): void { this.instance.dispose(); } } diff --git a/src/ts/spacestation/spacestationModel.ts b/src/ts/spacestation/spacestationModel.ts index f4b7c0049..b7a150560 100644 --- a/src/ts/spacestation/spacestationModel.ts +++ b/src/ts/spacestation/spacestationModel.ts @@ -1,19 +1,21 @@ import { seededSquirrelNoise } from "squirrel-noise"; import { Settings } from "../settings"; -import { BaseModel, GENERATION_STEPS, PhysicalProperties } from "../model/common"; +import { GENERATION_STEPS } from "../model/common"; import { OrbitProperties } from "../orbit/orbitProperties"; import { getOrbitalPeriod } from "../orbit/orbit"; import { Vector3 } from "@babylonjs/core/Maths/math.vector"; +import { OrbitalObjectModel } from "../architecture/orbitalObject"; +import { OrbitalObjectPhysicalProperties } from "../architecture/physicalProperties"; -export class SpaceStationModel implements BaseModel { +export class SpaceStationModel implements OrbitalObjectModel { readonly seed: number; readonly rng: (step: number) => number; readonly orbit: OrbitProperties; - readonly physicalProperties: PhysicalProperties; - readonly parentBody: BaseModel | null; - readonly childrenBodies: BaseModel[] = []; + readonly physicalProperties: OrbitalObjectPhysicalProperties; + readonly parentBody: OrbitalObjectModel | null; + readonly childrenBodies: OrbitalObjectModel[] = []; - constructor(seed: number, parentBody?: BaseModel) { + constructor(seed: number, parentBody?: OrbitalObjectModel) { this.seed = seed; this.rng = seededSquirrelNoise(this.seed); diff --git a/src/ts/starSystem/StarSystemView.ts b/src/ts/starSystem/StarSystemView.ts index 77b9bbc2f..ce9083f46 100644 --- a/src/ts/starSystem/StarSystemView.ts +++ b/src/ts/starSystem/StarSystemView.ts @@ -12,15 +12,14 @@ import { Color4 } from "@babylonjs/core/Maths/math.color"; import { HemisphericLight } from "@babylonjs/core/Lights/hemisphericLight"; import { Vector3 } from "@babylonjs/core/Maths/math"; import { Settings } from "../settings"; -import { AbstractBody } from "../bodies/abstractBody"; import { StarSystemHelper } from "./starSystemHelper"; import { positionNearObject } from "../utils/positionNearObject"; import { ShipControls } from "../spaceship/shipControls"; import { OrbitRenderer } from "../orbit/orbitRenderer"; import { BlackHole } from "../stellarObjects/blackHole/blackHole"; -import { ChunkForgeWorkers } from "../planemos/telluricPlanemo/terrain/chunks/chunkForgeWorkers"; +import { ChunkForgeWorkers } from "../planets/telluricPlanet/terrain/chunks/chunkForgeWorkers"; import "@babylonjs/core/Loading/loadingScreen"; -import { ChunkForge } from "../planemos/telluricPlanemo/terrain/chunks/chunkForge"; +import { ChunkForge } from "../planets/telluricPlanet/terrain/chunks/chunkForge"; export class StarSystemView { private readonly helmetOverlay: HelmetOverlay; @@ -92,12 +91,12 @@ export class StarSystemView { this.ui.update(this.scene.getActiveCamera()); - const nearestBody = starSystem.getNearestOrbitalObject(); + const nearestOrbitalObject = starSystem.getNearestOrbitalObject(); + const nearestCelestialBody = starSystem.getNearestCelestialBody(this.scene.getActiveCamera().globalPosition); - if (nearestBody instanceof AbstractBody) { - this.bodyEditor.update(nearestBody, starSystem.postProcessManager, this.scene); - } - this.helmetOverlay.update(nearestBody); + this.bodyEditor.update(nearestCelestialBody, starSystem.postProcessManager, this.scene); + + this.helmetOverlay.update(nearestOrbitalObject); this.orbitRenderer.update(); }); @@ -140,7 +139,7 @@ export class StarSystemView { this.scene.getEngine().loadingScreen.loadingUIText = `Warping to ${this.getStarSystem().model.getName()}`; this.getStarSystem().initPositions(100, this.chunkForge); - this.ui.createObjectOverlays(this.getStarSystem().getObjects()); + this.ui.createObjectOverlays(this.getStarSystem().getOrbitalObjects()); const firstBody = this.getStarSystem().getBodies()[0]; if (firstBody === undefined) throw new Error("No bodies in star system"); diff --git a/src/ts/starSystem/starSystemController.ts b/src/ts/starSystem/starSystemController.ts index cefb28bc4..e91c0b39b 100644 --- a/src/ts/starSystem/starSystemController.ts +++ b/src/ts/starSystem/starSystemController.ts @@ -1,18 +1,13 @@ import { Vector3 } from "@babylonjs/core/Maths/math.vector"; -import { AbstractBody } from "../bodies/abstractBody"; - import { Matrix, Quaternion } from "@babylonjs/core/Maths/math"; import { PostProcessType } from "../postProcesses/postProcessTypes"; import { getTransformationQuaternion } from "../utils/algebra"; import { PostProcessManager } from "../postProcesses/postProcessManager"; import { UberScene } from "../uberCore/uberScene"; -import { AbstractObject } from "../bodies/abstractObject"; import { SpaceStation } from "../spacestation/spaceStation"; -import { StellarObject } from "../stellarObjects/stellarObject"; -import { Planemo, PlanemoMaterial } from "../planemos/planemo"; -import { TelluricPlanemo } from "../planemos/telluricPlanemo/telluricPlanemo"; -import { GasPlanet } from "../planemos/gasPlanet/gasPlanet"; +import { TelluricPlanet } from "../planets/telluricPlanet/telluricPlanet"; +import { GasPlanet } from "../planets/gasPlanet/gasPlanet"; import { Mandelbulb } from "../mandelbulb/mandelbulb"; import { StarSystemModel } from "./starSystemModel"; import { rotateAround, setUpVector, translate } from "../uberCore/transforms/basicTransform"; @@ -20,7 +15,11 @@ import { Star } from "../stellarObjects/star/star"; import { BlackHole } from "../stellarObjects/blackHole/blackHole"; import { NeutronStar } from "../stellarObjects/neutronStar/neutronStar"; import { SystemSeed } from "../utils/systemSeed"; -import { ChunkForge } from "../planemos/telluricPlanemo/terrain/chunks/chunkForge"; +import { ChunkForge } from "../planets/telluricPlanet/terrain/chunks/chunkForge"; +import { OrbitalObject } from "../architecture/orbitalObject"; +import { CelestialBody } from "../architecture/celestialBody"; +import { StellarObject } from "../architecture/stellarObject"; +import { Planet } from "../architecture/planet"; export class StarSystemController { readonly scene: UberScene; @@ -29,31 +28,26 @@ export class StarSystemController { private readonly universeRotation: Quaternion = Quaternion.Identity(); - private readonly orbitalObjects: AbstractObject[] = []; + private readonly orbitalObjects: OrbitalObject[] = []; private readonly spaceStations: SpaceStation[] = []; - readonly celestialBodies: AbstractBody[] = []; + readonly celestialBodies: CelestialBody[] = []; /** * The list of all stellar objects in the system (stars, black holes, pulsars) */ readonly stellarObjects: StellarObject[] = []; - /** - * The list of all planemos in the system (planets and satellites) - */ - readonly planemosWithMaterial: PlanemoMaterial[] = []; - /** * The list of all planets in the system (telluric and gas) */ - readonly planets: Planemo[] = []; + readonly planets: Planet[] = []; /** * The list of all telluric planets in the system */ - readonly telluricPlanemos: TelluricPlanemo[] = []; + readonly telluricPlanets: TelluricPlanet[] = []; /** * The list of all gas planets in the system @@ -70,9 +64,9 @@ export class StarSystemController { */ readonly model: StarSystemModel; - private nearestOrbitalObject: AbstractObject | null = null; + private nearestOrbitalObject: OrbitalObject | null = null; - private closestToScreenCenterOrbitalObject: AbstractObject | null = null; + private closestToScreenCenterOrbitalObject: OrbitalObject | null = null; constructor(model: StarSystemModel | SystemSeed, scene: UberScene) { this.scene = scene; @@ -85,12 +79,11 @@ export class StarSystemController { * Adds a telluric planet to the system and returns it * @param planet The planet to add to the system */ - public addTelluricPlanet(planet: TelluricPlanemo): TelluricPlanemo { + public addTelluricPlanet(planet: TelluricPlanet): TelluricPlanet { this.orbitalObjects.push(planet); this.celestialBodies.push(planet); - this.planemosWithMaterial.push(planet); this.planets.push(planet); - this.telluricPlanemos.push(planet); + this.telluricPlanets.push(planet); return planet; } @@ -101,25 +94,11 @@ export class StarSystemController { public addGasPlanet(planet: GasPlanet): GasPlanet { this.orbitalObjects.push(planet); this.celestialBodies.push(planet); - this.planemosWithMaterial.push(planet); this.planets.push(planet); this.gasPlanets.push(planet); return planet; } - /** - * Adds a satellite to the system and returns it - * @param satellite The satellite to add to the system - * @returns The satellite added to the system - */ - public addTelluricSatellite(satellite: TelluricPlanemo): TelluricPlanemo { - this.orbitalObjects.push(satellite); - this.celestialBodies.push(satellite); - this.planemosWithMaterial.push(satellite); - this.telluricPlanemos.push(satellite); - return satellite; - } - /** * Adds a Mandelbulb to the system and returns it * @param mandelbulb The mandelbulb to add to the system @@ -166,11 +145,11 @@ export class StarSystemController { /** * Returns the list of all celestial bodies managed by the star system */ - public getBodies(): AbstractBody[] { + public getBodies(): CelestialBody[] { return this.celestialBodies; } - public getObjects(): AbstractObject[] { + public getOrbitalObjects(): OrbitalObject[] { const objects = []; for (const body of this.celestialBodies) objects.push(body); for (const spacestation of this.spaceStations) objects.push(spacestation); @@ -182,7 +161,7 @@ export class StarSystemController { let nearest = null; let smallerDistance = -1; for (const body of this.celestialBodies) { - const distance = body.getTransform().getAbsolutePosition().subtract(position).length() - body.model.radius; + const distance = body.getTransform().getAbsolutePosition().subtract(position).length() - body.getRadius(); if (nearest === null || distance < smallerDistance) { nearest = body; smallerDistance = distance; @@ -224,14 +203,14 @@ export class StarSystemController { this.closestToScreenCenterOrbitalObject = nearest; } - public getClosestToScreenCenterOrbitalObject(): AbstractObject | null { + public getClosestToScreenCenterOrbitalObject(): OrbitalObject | null { return this.closestToScreenCenterOrbitalObject; } /** * Returns the nearest orbital object to the origin */ - public getNearestOrbitalObject(): AbstractObject { + public getNearestOrbitalObject(): OrbitalObject { const nearest = this.nearestOrbitalObject; if (nearest === null) throw new Error("There are no bodies in the solar system"); return nearest; @@ -240,12 +219,12 @@ export class StarSystemController { /** * Returns the nearest body to the given position */ - public getNearestCelestialBody(position: Vector3): AbstractBody { + public getNearestCelestialBody(position: Vector3): CelestialBody { if (this.celestialBodies.length === 0) throw new Error("There are no bodies or spacestation in the solar system"); let nearest = null; let smallerDistance = -1; for (const body of this.celestialBodies) { - const distance = body.getTransform().getAbsolutePosition().subtract(position).length() - body.model.radius; + const distance = body.getTransform().getAbsolutePosition().subtract(position).length() - body.getRadius(); if (nearest === null || distance < smallerDistance) { nearest = body; smallerDistance = distance; @@ -261,11 +240,12 @@ export class StarSystemController { */ public initPositions(nbWarmUpUpdates: number, chunkForge: ChunkForge): void { for (const object of this.orbitalObjects) { - const displacement = new Vector3(object.model.orbit.radius, 0, 0); - const quaternion = getTransformationQuaternion(Vector3.Up(), object.model.orbit.normalToPlane); + const orbit = object.getOrbitProperties(); + const displacement = new Vector3(orbit.radius, 0, 0); + const quaternion = getTransformationQuaternion(Vector3.Up(), orbit.normalToPlane); displacement.applyRotationQuaternionInPlace(quaternion); - if (object.parentObject !== null) { - translate(object.getTransform(), object.parentObject.getTransform().getAbsolutePosition()); + if (object.parent !== null) { + translate(object.getTransform(), object.parent.getTransform().getAbsolutePosition()); } translate(object.getTransform(), displacement); } @@ -281,25 +261,24 @@ export class StarSystemController { const promises: Promise[] = []; this.postProcessManager.addStarField(this.stellarObjects, this.celestialBodies, this.universeRotation); - for (const object of this.orbitalObjects) { + for (const object of this.celestialBodies) { for (const postProcess of object.postProcesses) { switch (postProcess) { case PostProcessType.RING: - if (!(object instanceof AbstractBody)) throw new Error("Rings post process can only be added to bodies. Source:" + object.name); promises.push(this.postProcessManager.addRings(object, this.stellarObjects)); break; case PostProcessType.ATMOSPHERE: - if (!(object instanceof GasPlanet) && !(object instanceof TelluricPlanemo)) + if (!(object instanceof GasPlanet) && !(object instanceof TelluricPlanet)) throw new Error("Atmosphere post process can only be added to gas or telluric planets. Source:" + object.name); - this.postProcessManager.addAtmosphere(object as GasPlanet | TelluricPlanemo, this.stellarObjects); + this.postProcessManager.addAtmosphere(object as GasPlanet | TelluricPlanet, this.stellarObjects); break; case PostProcessType.CLOUDS: - if (!(object instanceof TelluricPlanemo)) throw new Error("Clouds post process can only be added to telluric planets. Source:" + object.name); - promises.push(this.postProcessManager.addClouds(object as TelluricPlanemo, this.stellarObjects)); + if (!(object instanceof TelluricPlanet)) throw new Error("Clouds post process can only be added to telluric planets. Source:" + object.name); + promises.push(this.postProcessManager.addClouds(object as TelluricPlanet, this.stellarObjects)); break; case PostProcessType.OCEAN: - if (!(object instanceof TelluricPlanemo)) throw new Error("Ocean post process can only be added to telluric planets. Source:" + object.name); - this.postProcessManager.addOcean(object as TelluricPlanemo, this.stellarObjects); + if (!(object instanceof TelluricPlanet)) throw new Error("Ocean post process can only be added to telluric planets. Source:" + object.name); + this.postProcessManager.addOcean(object as TelluricPlanet, this.stellarObjects); break; case PostProcessType.VOLUMETRIC_LIGHT: if (!(object instanceof Star)) throw new Error("Volumetric light post process can only be added to stars. Source:" + object.name); @@ -318,7 +297,7 @@ export class StarSystemController { this.postProcessManager.addMatterJet(object as NeutronStar); break; case PostProcessType.SHADOW: - promises.push(this.postProcessManager.addShadowCaster(object as AbstractBody, this.stellarObjects)); + promises.push(this.postProcessManager.addShadowCaster(object, this.stellarObjects)); break; case PostProcessType.LENS_FLARE: this.postProcessManager.addLensFlare(object as StellarObject); @@ -348,24 +327,25 @@ export class StarSystemController { const shouldCompensateTranslation = distanceOfNearestToCamera < nearestBody.getBoundingRadius() * (nearestBody instanceof SpaceStation ? 80 : 10); const shouldCompensateRotation = distanceOfNearestToCamera < nearestBody.getBoundingRadius() * 4; - nearestBody.updateInternalClock(deltaTime); + //nearestBody.updateInternalClock(deltaTime); const initialPosition = nearestBody.getTransform().getAbsolutePosition(); - const newPosition = nearestBody.computeNextOrbitalPosition(deltaTime); + const newPosition = OrbitalObject.computeNextOrbitalPosition(nearestBody, deltaTime); const nearestBodyDisplacement = newPosition.subtract(initialPosition); if (!shouldCompensateTranslation) translate(nearestBody.getTransform(), nearestBodyDisplacement); - const dthetaNearest = nearestBody.getDeltaTheta(deltaTime); + const dthetaNearest = OrbitalObject.getDeltaTheta(nearestBody, deltaTime); // if we don't compensate the rotation of the nearest body, we must rotate it accordingly - if (!shouldCompensateRotation) nearestBody.updateRotation(deltaTime); + if (!shouldCompensateRotation) OrbitalObject.updateRotation(nearestBody, deltaTime); // As the nearest object is kept in place, we need to transfer its movement to other bodies for (const object of this.orbitalObjects) { - const oldOrbitNormal = object.model.orbit.normalToPlane.clone(); + const orbit = object.getOrbitProperties(); + const oldOrbitNormal = orbit.normalToPlane.clone(); if (shouldCompensateRotation) { // the normal to the orbit planes must be rotated as well (even the one of the nearest body) const rotation = Quaternion.RotationAxis(nearestBody.getRotationAxis(), -dthetaNearest); - object.model.orbit.normalToPlane.applyRotationQuaternionInPlace(rotation); + orbit.normalToPlane.applyRotationQuaternionInPlace(rotation); } if (object === nearestBody) continue; @@ -379,7 +359,7 @@ export class StarSystemController { rotateAround(object.getTransform(), nearestBody.getTransform().getAbsolutePosition(), nearestBody.getRotationAxis(), -dthetaNearest); // we must as well rotate their rotation axis to keep consistency - const newNormal = object.model.orbit.normalToPlane.clone(); + const newNormal = orbit.normalToPlane.clone(); const angle = Math.acos(Vector3.Dot(oldOrbitNormal, newNormal)); if (angle > 0.02) { // FIXME: when time goes very fast, this will get wrongfully executed @@ -401,20 +381,27 @@ export class StarSystemController { for (const object of this.orbitalObjects) { if (object === nearestBody) continue; - object.updateInternalClock(deltaTime); - object.updateOrbitalPosition(deltaTime); - object.updateRotation(deltaTime); + //object.updateInternalClock(deltaTime); + OrbitalObject.updateOrbitalPosition(object, deltaTime); + OrbitalObject.updateRotation(object, deltaTime); } controller.update(deltaTime); - for (const body of this.telluricPlanemos) { + for (const body of this.telluricPlanets) { // Meshes with LOD are updated (surface quadtrees) body.updateLOD(controller.getTransform().getAbsolutePosition(), chunkForge); } - for (const object of this.orbitalObjects) { - // We disable objects that are too small on the screen + for (const object of this.telluricPlanets) { + object.computeCulling(controller.getActiveCamera()); + } + + for (const object of this.gasPlanets) { + object.computeCulling(controller.getActiveCamera()); + } + + for (const object of this.spaceStations) { object.computeCulling(controller.getActiveCamera()); } @@ -436,12 +423,12 @@ export class StarSystemController { const controller = this.scene.getActiveController(); const nearestBody = this.getNearestCelestialBody(this.scene.getActiveCamera().globalPosition); - for (const planet of this.planemosWithMaterial) { + for (const planet of this.planets) { planet.updateMaterial(controller.getActiveCamera(), this.stellarObjects, deltaTime); } for (const stellarObject of this.stellarObjects) { - if (stellarObject instanceof Star) stellarObject.updateMaterial(); + if (stellarObject instanceof Star) stellarObject.updateMaterial(deltaTime); } this.postProcessManager.setBody(nearestBody); diff --git a/src/ts/starSystem/starSystemHelper.ts b/src/ts/starSystem/starSystemHelper.ts index 87116a3de..5d7f4803f 100644 --- a/src/ts/starSystem/starSystemHelper.ts +++ b/src/ts/starSystem/starSystemHelper.ts @@ -1,5 +1,4 @@ import { StarSystemController } from "./starSystemController"; -import { StellarObject } from "../stellarObjects/stellarObject"; import { StarModel } from "../stellarObjects/star/starModel"; import { Star } from "../stellarObjects/star/star"; import { starName } from "../utils/parseToStrings"; @@ -10,13 +9,14 @@ import { BlackHoleModel } from "../stellarObjects/blackHole/blackHoleModel"; import { BlackHole } from "../stellarObjects/blackHole/blackHole"; import { NeutronStarModel } from "../stellarObjects/neutronStar/neutronStarModel"; import { NeutronStar } from "../stellarObjects/neutronStar/neutronStar"; +import { TelluricPlanetModel } from "../planets/telluricPlanet/telluricPlanetModel"; +import { TelluricPlanet } from "../planets/telluricPlanet/telluricPlanet"; +import { GasPlanetModel } from "../planets/gasPlanet/gasPlanetModel"; +import { GasPlanet } from "../planets/gasPlanet/gasPlanet"; +import { getMoonSeed } from "../planets/common"; +import { Planet } from "../architecture/planet"; +import { StellarObject } from "../architecture/stellarObject"; import { BODY_TYPE } from "../model/common"; -import { TelluricPlanemoModel } from "../planemos/telluricPlanemo/telluricPlanemoModel"; -import { TelluricPlanemo } from "../planemos/telluricPlanemo/telluricPlanemo"; -import { GasPlanetModel } from "../planemos/gasPlanet/gasPlanetModel"; -import { GasPlanet } from "../planemos/gasPlanet/gasPlanet"; -import { Planemo } from "../planemos/planemo"; -import { getMoonSeed } from "../planemos/common"; export class StarSystemHelper { public static makeStar(starsystem: StarSystemController, model?: number | StarModel): Star { @@ -94,9 +94,9 @@ export class StarSystemHelper { */ public static makeTelluricPlanet( starsystem: StarSystemController, - model: number | TelluricPlanemoModel = starsystem.model.getPlanetSeed(starsystem.planets.length) - ): TelluricPlanemo { - const planet = new TelluricPlanemo(`${starsystem.model.getName()} ${romanNumeral(starsystem.planets.length + 1)}`, starsystem.scene, model, starsystem.stellarObjects[0]); + model: number | TelluricPlanetModel = starsystem.model.getPlanetSeed(starsystem.planets.length) + ): TelluricPlanet { + const planet = new TelluricPlanet(`${starsystem.model.getName()} ${romanNumeral(starsystem.planets.length + 1)}`, starsystem.scene, model, starsystem.stellarObjects[0]); starsystem.addTelluricPlanet(planet); return planet; } @@ -117,14 +117,14 @@ export class StarSystemHelper { for (let i = 0; i < n; i++) { switch (starsystem.model.getBodyTypeOfPlanet(starsystem.planets.length)) { - case BODY_TYPE.TELLURIC: + case BODY_TYPE.TELLURIC_PLANET: StarSystemHelper.makeSatellites(starsystem, StarSystemHelper.makeTelluricPlanet(starsystem)); break; - case BODY_TYPE.GAS: + case BODY_TYPE.GAS_PLANET: StarSystemHelper.makeSatellites(starsystem, StarSystemHelper.makeGasPlanet(starsystem)); break; case BODY_TYPE.MANDELBULB: - StarSystemHelper.makeSatellites(starsystem, StarSystemHelper.makeMandelbulb(starsystem)); + StarSystemHelper.makeMandelbulb(starsystem); break; default: throw new Error(`Unknown body type ${starsystem.model.getBodyTypeOfPlanet(starsystem.planets.length)}`); @@ -134,14 +134,14 @@ export class StarSystemHelper { public static makeSatellite( starsystem: StarSystemController, - planet: Planemo, - model: TelluricPlanemoModel | number = getMoonSeed(planet.model, planet.model.childrenBodies.length) - ): TelluricPlanemo { - const satellite = new TelluricPlanemo(`${planet.name} ${romanNumeral(planet.model.childrenBodies.length + 1)}`, starsystem.scene, model, planet); + planet: Planet, + model: TelluricPlanetModel | number = getMoonSeed(planet.model, planet.model.childrenBodies.length) + ): TelluricPlanet { + const satellite = new TelluricPlanet(`${planet.name} ${romanNumeral(planet.model.childrenBodies.length + 1)}`, starsystem.scene, model, planet); planet.model.childrenBodies.push(satellite.model); - starsystem.addTelluricSatellite(satellite); + starsystem.addTelluricPlanet(satellite); return satellite; } @@ -152,7 +152,7 @@ export class StarSystemHelper { * @param planet The planet to make satellites for * @param n The number of satellites to make */ - public static makeSatellites(starsystem: StarSystemController, planet: Planemo, n = planet.model.nbMoons): void { + public static makeSatellites(starsystem: StarSystemController, planet: Planet, n = planet.model.nbMoons): void { if (n < 0) throw new Error(`Cannot make a negative amount of satellites : ${n}`); if (planet.model.childrenBodies.length + n > planet.model.nbMoons) console.warn( diff --git a/src/ts/starSystem/starSystemModel.ts b/src/ts/starSystem/starSystemModel.ts index e4cdad7fb..37a5f8f8c 100644 --- a/src/ts/starSystem/starSystemModel.ts +++ b/src/ts/starSystem/starSystemModel.ts @@ -59,8 +59,8 @@ export class StarSystemModel { public getBodyTypeOfPlanet(index: number) { if (uniformRandBool(0.01, this.rng, GENERATION_STEPS.CHOOSE_PLANET_TYPE + (index + 20) * 500)) return BODY_TYPE.MANDELBULB; - if (uniformRandBool(0.5, this.rng, GENERATION_STEPS.CHOOSE_PLANET_TYPE + index)) return BODY_TYPE.TELLURIC; - return BODY_TYPE.GAS; + if (uniformRandBool(0.5, this.rng, GENERATION_STEPS.CHOOSE_PLANET_TYPE + index)) return BODY_TYPE.TELLURIC_PLANET; + return BODY_TYPE.GAS_PLANET; } public getPlanetSeed(index: number) { diff --git a/src/ts/stellarObjects/blackHole/blackHole.ts b/src/ts/stellarObjects/blackHole/blackHole.ts index 3ded2e5bf..6f73f348f 100644 --- a/src/ts/stellarObjects/blackHole/blackHole.ts +++ b/src/ts/stellarObjects/blackHole/blackHole.ts @@ -6,19 +6,36 @@ import { Light } from "@babylonjs/core/Lights/light"; import { PostProcessType } from "../../postProcesses/postProcessTypes"; import { Camera } from "@babylonjs/core/Cameras/camera"; import { BlackHoleModel } from "./blackHoleModel"; -import { AbstractBody } from "../../bodies/abstractBody"; +import { StellarObject } from "../../architecture/stellarObject"; +import { Cullable } from "../../bodies/cullable"; +import { CelestialBody } from "../../architecture/celestialBody"; +import { TransformNode } from "@babylonjs/core/Meshes"; +import { OrbitProperties } from "../../orbit/orbitProperties"; +import { RingsUniforms } from "../../postProcesses/rings/ringsUniform"; +import { OrbitalObjectPhysicalProperties } from "../../architecture/physicalProperties"; + +export class BlackHole implements StellarObject, Cullable { + readonly name: string; + + private readonly transform: TransformNode; -export class BlackHole extends AbstractBody { readonly light: PointLight; readonly model: BlackHoleModel; - constructor(name: string, scene: Scene, model: BlackHoleModel | number, parentBody?: AbstractBody) { - super(name, scene, parentBody); + readonly postProcesses: PostProcessType[] = []; + + readonly parent: CelestialBody | null; + + constructor(name: string, scene: Scene, model: BlackHoleModel | number, parentBody: CelestialBody | null = null) { + this.name = name; this.model = model instanceof BlackHoleModel ? model : new BlackHoleModel(model); - this.getTransform().rotate(Axis.X, this.model.physicalProperties.axialTilt); + this.parent = parentBody; + + this.transform = new TransformNode(`${name}Transform`, scene); + this.transform.rotate(Axis.X, this.model.physicalProperties.axialTilt); this.light = new PointLight(`${name}Light`, Vector3.Zero(), scene); //this.light.diffuse.fromArray(getRgbFromTemperature(this.model.physicalProperties.temperature).asArray()); @@ -29,16 +46,48 @@ export class BlackHole extends AbstractBody { this.postProcesses.push(PostProcessType.BLACK_HOLE); } + getTransform(): TransformNode { + return this.transform; + } + + getRotationAxis(): Vector3 { + return this.getTransform().up; + } + + getLight(): PointLight { + return this.light; + } + + getOrbitProperties(): OrbitProperties { + return this.model.orbit; + } + + getPhysicalProperties(): OrbitalObjectPhysicalProperties { + return this.model.physicalProperties; + } + + getRingsUniforms(): RingsUniforms | null { + return null; + } + getTypeName(): string { return "Black Hole"; } - public override computeCulling(camera: Camera): void { - // nothing to do + public computeCulling(camera: Camera): void { + return; + } + + public getRadius(): number { + return this.model.radius; + } + + public getBoundingRadius(): number { + return this.getRadius() + this.model.physicalProperties.accretionDiskRadius; } - public override dispose(): void { + public dispose(): void { this.light.dispose(); - super.dispose(); + this.transform.dispose(); } } diff --git a/src/ts/stellarObjects/blackHole/blackHoleModel.ts b/src/ts/stellarObjects/blackHole/blackHoleModel.ts index 645752191..7cbbbf82e 100644 --- a/src/ts/stellarObjects/blackHole/blackHoleModel.ts +++ b/src/ts/stellarObjects/blackHole/blackHoleModel.ts @@ -4,7 +4,10 @@ import { Vector3 } from "@babylonjs/core/Maths/math.vector"; import { normalRandom } from "extended-random"; import { OrbitProperties } from "../../orbit/orbitProperties"; import { STELLAR_TYPE } from "../common"; -import { BlackHolePhysicalProperties, BODY_TYPE, BodyModel, GENERATION_STEPS, StellarObjectModel } from "../../model/common"; +import { BODY_TYPE, GENERATION_STEPS } from "../../model/common"; +import { StellarObjectModel } from "../../architecture/stellarObject"; +import { BlackHolePhysicalProperties } from "../../architecture/physicalProperties"; +import { CelestialBodyModel } from "../../architecture/celestialBody"; export class BlackHoleModel implements StellarObjectModel { readonly bodyType = BODY_TYPE.BLACK_HOLE; @@ -13,19 +16,17 @@ export class BlackHoleModel implements StellarObjectModel { readonly radius: number; - readonly ringsUniforms = null; - readonly stellarType = STELLAR_TYPE.BLACK_HOLE; readonly orbit: OrbitProperties; readonly physicalProperties: BlackHolePhysicalProperties; - readonly parentBody: BodyModel | null; + readonly parentBody: CelestialBodyModel | null; - readonly childrenBodies: BodyModel[] = []; + readonly childrenBodies: CelestialBodyModel[] = []; - constructor(seed: number, parentBody?: BodyModel) { + constructor(seed: number, parentBody?: CelestialBodyModel) { this.seed = seed; this.rng = seededSquirrelNoise(this.seed); diff --git a/src/ts/stellarObjects/neutronStar/neutronStar.ts b/src/ts/stellarObjects/neutronStar/neutronStar.ts index 0522942f7..edbcd45de 100644 --- a/src/ts/stellarObjects/neutronStar/neutronStar.ts +++ b/src/ts/stellarObjects/neutronStar/neutronStar.ts @@ -1,8 +1,8 @@ import { Star } from "../star/star"; import { NeutronStarModel } from "./neutronStarModel"; import { UberScene } from "../../uberCore/uberScene"; -import { AbstractBody } from "../../bodies/abstractBody"; import { PostProcessType } from "../../postProcesses/postProcessTypes"; +import { CelestialBody } from "../../architecture/celestialBody"; export class NeutronStar extends Star { readonly descriptor: NeutronStarModel; @@ -14,7 +14,7 @@ export class NeutronStar extends Star { * @param model The seed of the star in [-1, 1] * @param parentBody */ - constructor(name: string, scene: UberScene, model: number | NeutronStarModel, parentBody?: AbstractBody) { + constructor(name: string, scene: UberScene, model: number | NeutronStarModel, parentBody: CelestialBody | null = null) { super(name, scene, model, parentBody); this.descriptor = model instanceof NeutronStarModel ? model : new NeutronStarModel(model, parentBody?.model); diff --git a/src/ts/stellarObjects/neutronStar/neutronStarModel.ts b/src/ts/stellarObjects/neutronStar/neutronStarModel.ts index a39209eb6..7655af8b5 100644 --- a/src/ts/stellarObjects/neutronStar/neutronStarModel.ts +++ b/src/ts/stellarObjects/neutronStar/neutronStarModel.ts @@ -1,8 +1,8 @@ import { StarModel } from "../star/starModel"; -import { BodyModel } from "../../model/common"; +import { CelestialBodyModel } from "../../architecture/celestialBody"; export class NeutronStarModel extends StarModel { - constructor(seed: number, parentBody?: BodyModel) { + constructor(seed: number, parentBody: CelestialBodyModel | null = null) { super(seed, parentBody); } } diff --git a/src/ts/stellarObjects/star/star.ts b/src/ts/stellarObjects/star/star.ts index 71fed8e98..3a499fbce 100644 --- a/src/ts/stellarObjects/star/star.ts +++ b/src/ts/stellarObjects/star/star.ts @@ -1,4 +1,3 @@ -import { AbstractBody } from "../../bodies/abstractBody"; import { Mesh } from "@babylonjs/core/Meshes/mesh"; import { PointLight } from "@babylonjs/core/Lights/pointLight"; import { StarMaterial } from "./starMaterial"; @@ -15,14 +14,33 @@ import { PostProcessType } from "../../postProcesses/postProcessTypes"; import { getStellarTypeString } from "../common"; import { Camera } from "@babylonjs/core/Cameras/camera"; import { PhysicsShapeSphere } from "@babylonjs/core/Physics/v2/physicsShape"; +import { isSizeOnScreenEnough } from "../../utils/isObjectVisibleOnScreen"; +import { CelestialBody } from "../../architecture/celestialBody"; +import { OrbitalObject } from "../../architecture/orbitalObject"; +import { TransformNode } from "@babylonjs/core/Meshes"; +import { PhysicsAggregate } from "@babylonjs/core/Physics/v2/physicsAggregate"; +import { PhysicsShapeType } from "@babylonjs/core/Physics/v2/IPhysicsEnginePlugin"; +import { StellarObject } from "../../architecture/stellarObject"; +import { Cullable } from "../../bodies/cullable"; +import { OrbitProperties } from "../../orbit/orbitProperties"; +import { RingsUniforms } from "../../postProcesses/rings/ringsUniform"; +import { OrbitalObjectPhysicalProperties } from "../../architecture/physicalProperties"; + +export class Star implements StellarObject, Cullable { + readonly name: string; -export class Star extends AbstractBody { readonly mesh: Mesh; readonly light: PointLight; private readonly material: StarMaterial; + readonly aggregate: PhysicsAggregate; + + readonly postProcesses: PostProcessType[] = []; + readonly model: StarModel; + readonly parent: OrbitalObject | null; + /** * New Star * @param name The name of the star @@ -30,26 +48,37 @@ export class Star extends AbstractBody { * @param parentBody The bodies the star is orbiting * @param model The seed of the star in [-1, 1] */ - constructor(name: string, scene: UberScene, model: StarModel | number, parentBody?: AbstractBody) { - super(name, scene, parentBody); + constructor(name: string, scene: UberScene, model: StarModel | number, parentBody: CelestialBody | null = null) { + this.name = name; + + this.parent = parentBody; this.model = model instanceof StarModel ? model : new StarModel(model, parentBody?.model); const isSphere = this.model.rng(42) > 0.1; - this.mesh = - isSphere - ? MeshBuilder.CreateSphere( - `${name}Mesh`, - { - diameter: this.model.radius * 2, - segments: 32 - }, - scene - ) - : Assets.CreateBananaClone(2 * this.model.radius); - this.mesh.parent = this.getTransform(); + this.mesh = isSphere + ? MeshBuilder.CreateSphere( + `${name}Mesh`, + { + diameter: this.model.radius * 2, + segments: 32 + }, + scene + ) + : Assets.CreateBananaClone(2 * this.model.radius); + this.aggregate = new PhysicsAggregate( + this.getTransform(), + PhysicsShapeType.CONTAINER, + { + mass: 0, + restitution: 0.2 + }, + scene + ); + this.aggregate.body.setMassProperties({ inertia: Vector3.Zero(), mass: 0 }); + this.aggregate.body.disablePreStep = false; //FIXME: the radius here is a dirty fix because bakeTransformIntoVertexData does not work for reasons unknown const physicsShape = new PhysicsShapeSphere(Vector3.Zero(), isSphere ? this.model.radius : 0.1, scene); this.aggregate.shape.addChildFromParent(this.getTransform(), physicsShape, this.mesh); @@ -68,23 +97,53 @@ export class Star extends AbstractBody { if (this.model.ringsUniforms !== null) this.postProcesses.push(PostProcessType.RING); } + getTransform(): TransformNode { + return this.mesh; + } + + getRotationAxis(): Vector3 { + return this.getTransform().up; + } + + getLight(): PointLight { + return this.light; + } + + getOrbitProperties(): OrbitProperties { + return this.model.orbit; + } + + getPhysicalProperties(): OrbitalObjectPhysicalProperties { + return this.model.physicalProperties; + } + + getRingsUniforms(): RingsUniforms | null { + return this.model.ringsUniforms; + } + getTypeName(): string { return `${getStellarTypeString(this.model.stellarType)} star`; } - public updateMaterial(): void { - this.material.update(this.getInternalClock()); + public updateMaterial(deltaTime: number): void { + this.material.update(deltaTime); + } + + public getRadius(): number { + return this.model.radius; + } + + public getBoundingRadius(): number { + return this.getRadius(); } - public override computeCulling(camera: Camera): void { - //this.mesh.isVisible = true; + public computeCulling(camera: Camera): void { + this.mesh.isVisible = isSizeOnScreenEnough(this, camera); } - public override dispose(): void { - this.aggregate.dispose(); + public dispose(): void { this.mesh.dispose(); this.light.dispose(); this.material.dispose(); - super.dispose(); } } diff --git a/src/ts/stellarObjects/star/starMaterial.ts b/src/ts/stellarObjects/star/starMaterial.ts index 626a085dc..f265c5e4f 100644 --- a/src/ts/stellarObjects/star/starMaterial.ts +++ b/src/ts/stellarObjects/star/starMaterial.ts @@ -15,6 +15,8 @@ export class StarMaterial extends ShaderMaterial { starModel: StarModel; starSeed: number; + private internalClock = 0; + constructor(star: TransformNode, model: StarModel, scene: Scene) { const shaderName = "starMaterial"; if (Effect.ShadersStore[`${shaderName}FragmentShader`] === undefined) { @@ -46,8 +48,10 @@ export class StarMaterial extends ShaderMaterial { this.starSeed = model.seed; } - public update(internalTime: number) { - this.setFloat("time", internalTime % 100000); + public update(deltaTime: number) { + this.internalClock += deltaTime; + + this.setFloat("time", this.internalClock % 100000); this.setVector3("starColor", this.starModel.surfaceColor); this.setQuaternion("starInverseRotationQuaternion", getInverseRotationQuaternion(this.star)); this.setFloat("seed", this.starSeed); diff --git a/src/ts/stellarObjects/star/starModel.ts b/src/ts/stellarObjects/star/starModel.ts index 1a38dc1b0..261ee858e 100644 --- a/src/ts/stellarObjects/star/starModel.ts +++ b/src/ts/stellarObjects/star/starModel.ts @@ -6,9 +6,12 @@ import { getRgbFromTemperature } from "../../utils/specrend"; import { Settings } from "../../settings"; import { getOrbitalPeriod } from "../../orbit/orbit"; import { OrbitProperties } from "../../orbit/orbitProperties"; -import { BODY_TYPE, BodyModel, GENERATION_STEPS, StarPhysicalProperties, StellarObjectModel } from "../../model/common"; +import { BODY_TYPE, GENERATION_STEPS } from "../../model/common"; import { STELLAR_TYPE } from "../common"; import { RingsUniforms } from "../../postProcesses/rings/ringsUniform"; +import { StarPhysicalProperties } from "../../architecture/physicalProperties"; +import { CelestialBodyModel } from "../../architecture/celestialBody"; +import { StellarObjectModel } from "../../architecture/stellarObject"; export class StarModel implements StellarObjectModel { readonly bodyType = BODY_TYPE.STAR; @@ -29,17 +32,17 @@ export class StarModel implements StellarObjectModel { static RING_PROPORTION = 0.2; readonly ringsUniforms; - readonly parentBody: BodyModel | null; + readonly parentBody: CelestialBodyModel | null; - readonly childrenBodies: BodyModel[] = []; + readonly childrenBodies: CelestialBodyModel[] = []; - constructor(seed: number, parentBody?: BodyModel) { + constructor(seed: number, parentBody: CelestialBodyModel | null = null) { this.seed = seed; this.rng = seededSquirrelNoise(this.seed); const surfaceTemperature = clamp(normalRandom(5778, 2000, this.rng, GENERATION_STEPS.TEMPERATURE), 3000, 10000); - this.parentBody = parentBody ?? null; + this.parentBody = parentBody; this.physicalProperties = { mass: this.mass, diff --git a/src/ts/uberCore/controls.ts b/src/ts/uberCore/controls.ts index 8b509e7fa..1a5d9f3c9 100644 --- a/src/ts/uberCore/controls.ts +++ b/src/ts/uberCore/controls.ts @@ -1,8 +1,7 @@ import { Vector3 } from "@babylonjs/core/Maths/math.vector"; import { Input } from "../inputs/input"; - -import { Transformable } from "./transforms/basicTransform"; import { Camera } from "@babylonjs/core/Cameras/camera"; +import { Transformable } from "../architecture/transformable"; export interface Controls extends Transformable { /** diff --git a/src/ts/uberCore/transforms/basicTransform.ts b/src/ts/uberCore/transforms/basicTransform.ts index b09ed3c53..986b580be 100644 --- a/src/ts/uberCore/transforms/basicTransform.ts +++ b/src/ts/uberCore/transforms/basicTransform.ts @@ -2,10 +2,6 @@ import { TransformNode } from "@babylonjs/core/Meshes/transformNode"; import { Matrix, Quaternion, Vector3 } from "@babylonjs/core/Maths/math.vector"; import { Axis, Space } from "@babylonjs/core/Maths/math.axis"; -export function getPosition(transformNode: TransformNode): Vector3 { - return transformNode.position; -} - export function translate(transformNode: TransformNode, displacement: Vector3): void { transformNode.setAbsolutePosition(transformNode.getAbsolutePosition().add(displacement)); transformNode.computeWorldMatrix(true); @@ -129,12 +125,4 @@ export function yaw(transformNode: TransformNode, amount: number): void { rotate(transformNode, getUpwardDirection(transformNode), amount); } -/* #endregion directions */ - -export function dispose(transformNode: TransformNode): void { - transformNode.dispose(); -} - -export interface Transformable { - getTransform(): TransformNode; -} +/* #endregion directions */ \ No newline at end of file diff --git a/src/ts/ui/bodyEditor/bodyEditor.ts b/src/ts/ui/bodyEditor/bodyEditor.ts index 366baedb4..5b17149d5 100644 --- a/src/ts/ui/bodyEditor/bodyEditor.ts +++ b/src/ts/ui/bodyEditor/bodyEditor.ts @@ -1,10 +1,9 @@ import editorHTML from "../../../html/bodyEditor.html"; -import { TelluricPlanemo } from "../../planemos/telluricPlanemo/telluricPlanemo"; -import { AbstractBody } from "../../bodies/abstractBody"; +import { TelluricPlanet } from "../../planets/telluricPlanet/telluricPlanet"; import "handle-sliderjs/dist/css/style2.css"; -import { ColorMode } from "../../planemos/telluricPlanemo/colorSettingsInterface"; +import { ColorMode } from "../../planets/telluricPlanet/colorSettingsInterface"; import { hide, show } from "../../utils/html"; -import { GasPlanet } from "../../planemos/gasPlanet/gasPlanet"; +import { GasPlanet } from "../../planets/gasPlanet/gasPlanet"; import { EditorPanel } from "./editorPanel"; import { GeneralPanel } from "./panels/generalPanel"; import { PhysicPanel } from "./panels/physicPanel"; @@ -20,6 +19,7 @@ import { UberScene } from "../../uberCore/uberScene"; import { BlackholePanel } from "./panels/blackholePanel"; import { Star } from "../../stellarObjects/star/star"; import { BlackHole } from "../../stellarObjects/blackHole/blackHole"; +import { CelestialBody } from "../../architecture/celestialBody"; export enum EditorVisibility { HIDDEN, @@ -141,7 +141,7 @@ export class BodyEditor { return this.visibility; } - public setBody(body: AbstractBody, postProcessManager: PostProcessManager, scene: UberScene) { + public setBody(body: CelestialBody, postProcessManager: PostProcessManager, scene: UberScene) { this.currentBodyId = body.name; for (const panel of this.panels) panel.disable(); @@ -150,22 +150,22 @@ export class BodyEditor { this.generalPanel.setVisibility(this.currentPanel === this.generalPanel); this.generalPanel.init(body, postProcessManager.colorCorrection, scene); - const rings = postProcessManager.getRings(body as AbstractBody); + const rings = postProcessManager.getRings(body); if (rings) { this.ringsPanel.enable(); this.ringsPanel.setVisibility(this.currentPanel === this.ringsPanel); this.ringsPanel.init(body, rings); } - if (body instanceof TelluricPlanemo || body instanceof GasPlanet) { - const atmosphere = postProcessManager.getAtmosphere(body as TelluricPlanemo); + if (body instanceof TelluricPlanet || body instanceof GasPlanet) { + const atmosphere = postProcessManager.getAtmosphere(body as TelluricPlanet); if (atmosphere) { this.atmospherePanel.enable(); this.atmospherePanel.setVisibility(this.currentPanel === this.atmospherePanel); this.atmospherePanel.init(body, atmosphere); } - if (body instanceof TelluricPlanemo) { + if (body instanceof TelluricPlanet) { this.initToolbar(body); this.surfacePanel.enable(); @@ -176,14 +176,14 @@ export class BodyEditor { this.physicPanel.setVisibility(this.currentPanel === this.physicPanel); this.physicPanel.init(body); - const clouds = postProcessManager.getClouds(body as TelluricPlanemo); + const clouds = postProcessManager.getClouds(body as TelluricPlanet); if (clouds) { this.cloudsPanel.enable(); this.cloudsPanel.setVisibility(this.currentPanel === this.cloudsPanel); this.cloudsPanel.init(body, clouds); } - const ocean = postProcessManager.getOcean(body as TelluricPlanemo); + const ocean = postProcessManager.getOcean(body as TelluricPlanet); if (ocean) { this.oceanPanel.enable(); this.oceanPanel.setVisibility(this.currentPanel === this.oceanPanel); @@ -217,7 +217,7 @@ export class BodyEditor { } } - public initToolbar(planet: TelluricPlanemo) { + public initToolbar(planet: TelluricPlanet) { const material = planet.material; const colorSettings = material.colorSettings; document.getElementById("defaultMapButton")?.addEventListener("click", () => { @@ -246,7 +246,7 @@ export class BodyEditor { for (const panel of this.panels) panel.updateAllSliders(); } - public update(nearestBody: AbstractBody, postProcessManager: PostProcessManager, scene: UberScene) { + public update(nearestBody: CelestialBody, postProcessManager: PostProcessManager, scene: UberScene) { if (nearestBody.name !== this.currentBodyId) this.setBody(nearestBody, postProcessManager, scene); } } diff --git a/src/ts/ui/bodyEditor/editorPanel.ts b/src/ts/ui/bodyEditor/editorPanel.ts index b30472030..537ca7054 100644 --- a/src/ts/ui/bodyEditor/editorPanel.ts +++ b/src/ts/ui/bodyEditor/editorPanel.ts @@ -1,7 +1,7 @@ import { Slider } from "handle-sliderjs"; -import { AbstractBody } from "../../bodies/abstractBody"; import { UberScene } from "../../uberCore/uberScene"; import { PostProcess } from "@babylonjs/core/PostProcesses/postProcess"; +import { CelestialBody } from "../../architecture/celestialBody"; export abstract class EditorPanel { sliders: Slider[] = []; @@ -14,7 +14,7 @@ export abstract class EditorPanel { this.panel = document.getElementById(id + "UI") as HTMLElement; } - abstract init(body: AbstractBody, postProcess: PostProcess, scene: UberScene): void; + abstract init(body: CelestialBody, postProcess: PostProcess, scene: UberScene): void; updateAllSliders() { for (const slider of this.sliders) slider.update(false); diff --git a/src/ts/ui/bodyEditor/panels/atmospherePanel.ts b/src/ts/ui/bodyEditor/panels/atmospherePanel.ts index 8a482037d..1f7892893 100644 --- a/src/ts/ui/bodyEditor/panels/atmospherePanel.ts +++ b/src/ts/ui/bodyEditor/panels/atmospherePanel.ts @@ -1,16 +1,15 @@ import { EditorPanel } from "../editorPanel"; import { clearAllEventListenersById } from "../../../utils/html"; -import { TelluricPlanemo } from "../../../planemos/telluricPlanemo/telluricPlanemo"; -import { GasPlanet } from "../../../planemos/gasPlanet/gasPlanet"; import { Settings } from "../../../settings"; import { Slider } from "handle-sliderjs"; import { AtmosphericScatteringPostProcess } from "../../../postProcesses/atmosphericScatteringPostProcess"; +import { CelestialBody } from "../../../architecture/celestialBody"; export class AtmospherePanel extends EditorPanel { constructor() { super("atmosphere"); } - init(planet: TelluricPlanemo | GasPlanet, atmosphere: AtmosphericScatteringPostProcess) { + init(planet: CelestialBody, atmosphere: AtmosphericScatteringPostProcess) { for (const slider of this.sliders) slider.remove(); const atmosphereToggler = clearAllEventListenersById("atmosphereToggler"); diff --git a/src/ts/ui/bodyEditor/panels/blackholePanel.ts b/src/ts/ui/bodyEditor/panels/blackholePanel.ts index 442d1a778..6d9835c5a 100644 --- a/src/ts/ui/bodyEditor/panels/blackholePanel.ts +++ b/src/ts/ui/bodyEditor/panels/blackholePanel.ts @@ -14,9 +14,16 @@ export class BlackholePanel extends EditorPanel { new Slider("diskRadius", document.getElementById("diskRadius") as HTMLElement, 0, 1000, blackHole.blackHoleUniforms.accretionDiskRadius / 1e5, (val: number) => { blackHole.blackHoleUniforms.accretionDiskRadius = val * 1e5; }), - new Slider("minkowskiWarpingFactor", document.getElementById("minkowskiWarpingFactor") as HTMLElement, 0, 5 * 10, blackHole.blackHoleUniforms.warpingMinkowskiFactor * 10, (val: number) => { - blackHole.blackHoleUniforms.warpingMinkowskiFactor = val / 10; - }), + new Slider( + "minkowskiWarpingFactor", + document.getElementById("minkowskiWarpingFactor") as HTMLElement, + 0, + 5 * 10, + blackHole.blackHoleUniforms.warpingMinkowskiFactor * 10, + (val: number) => { + blackHole.blackHoleUniforms.warpingMinkowskiFactor = val / 10; + } + ) ]; } } diff --git a/src/ts/ui/bodyEditor/panels/cloudsPanel.ts b/src/ts/ui/bodyEditor/panels/cloudsPanel.ts index 79fbfb397..97b9af756 100644 --- a/src/ts/ui/bodyEditor/panels/cloudsPanel.ts +++ b/src/ts/ui/bodyEditor/panels/cloudsPanel.ts @@ -1,16 +1,16 @@ import { EditorPanel } from "../editorPanel"; import { clearAllEventListenersById } from "../../../utils/html"; -import { TelluricPlanemo } from "../../../planemos/telluricPlanemo/telluricPlanemo"; import { Settings } from "../../../settings"; import { Slider } from "handle-sliderjs"; import { Color3 } from "@babylonjs/core/Maths/math.color"; import { CloudsPostProcess } from "../../../postProcesses/volumetricCloudsPostProcess"; +import { CelestialBody } from "../../../architecture/celestialBody"; export class CloudsPanel extends EditorPanel { constructor() { super("clouds"); } - init(planet: TelluricPlanemo, flatClouds: CloudsPostProcess) { + init(planet: CelestialBody, flatClouds: CloudsPostProcess) { for (const slider of this.sliders) slider.remove(); const cloudsToggler = clearAllEventListenersById("cloudsToggler"); diff --git a/src/ts/ui/bodyEditor/panels/gasCloudsPanel.ts b/src/ts/ui/bodyEditor/panels/gasCloudsPanel.ts index 453eafa43..a039ee93b 100644 --- a/src/ts/ui/bodyEditor/panels/gasCloudsPanel.ts +++ b/src/ts/ui/bodyEditor/panels/gasCloudsPanel.ts @@ -1,5 +1,5 @@ import { EditorPanel } from "../editorPanel"; -import { GasPlanet } from "../../../planemos/gasPlanet/gasPlanet"; +import { GasPlanet } from "../../../planets/gasPlanet/gasPlanet"; import { clearAllEventListenersById } from "../../../utils/html"; import { Slider } from "handle-sliderjs"; import { Color3 } from "@babylonjs/core/Maths/math.color"; diff --git a/src/ts/ui/bodyEditor/panels/generalPanel.ts b/src/ts/ui/bodyEditor/panels/generalPanel.ts index 8962f3b06..24c428dcc 100644 --- a/src/ts/ui/bodyEditor/panels/generalPanel.ts +++ b/src/ts/ui/bodyEditor/panels/generalPanel.ts @@ -5,9 +5,10 @@ import { Slider } from "handle-sliderjs"; import { Settings } from "../../../settings"; import { UberScene } from "../../../uberCore/uberScene"; import { ColorCorrection } from "../../../uberCore/postProcesses/colorCorrection"; -import { getRotationQuaternion, rotate, Transformable } from "../../../uberCore/transforms/basicTransform"; +import { getRotationQuaternion, rotate } from "../../../uberCore/transforms/basicTransform"; -import { BoundingSphere } from "../../../bodies/common"; +import { BoundingSphere } from "../../../architecture/boundingSphere"; +import { Transformable } from "../../../architecture/transformable"; export class GeneralPanel extends EditorPanel { constructor() { diff --git a/src/ts/ui/bodyEditor/panels/oceanPanel.ts b/src/ts/ui/bodyEditor/panels/oceanPanel.ts index 9cd82cbe6..d443cda53 100644 --- a/src/ts/ui/bodyEditor/panels/oceanPanel.ts +++ b/src/ts/ui/bodyEditor/panels/oceanPanel.ts @@ -1,14 +1,14 @@ import { EditorPanel } from "../editorPanel"; import { clearAllEventListenersById } from "../../../utils/html"; -import { TelluricPlanemo } from "../../../planemos/telluricPlanemo/telluricPlanemo"; import { Slider } from "handle-sliderjs"; import { OceanPostProcess } from "../../../postProcesses/oceanPostProcess"; +import { CelestialBody } from "../../../architecture/celestialBody"; export class OceanPanel extends EditorPanel { constructor() { super("ocean"); } - init(planet: TelluricPlanemo, ocean: OceanPostProcess) { + init(planet: CelestialBody, ocean: OceanPostProcess) { for (const slider of this.sliders) slider.remove(); const oceanToggler = clearAllEventListenersById("oceanToggler"); diff --git a/src/ts/ui/bodyEditor/panels/physicPanel.ts b/src/ts/ui/bodyEditor/panels/physicPanel.ts index a50ca5fca..83a641ea2 100644 --- a/src/ts/ui/bodyEditor/panels/physicPanel.ts +++ b/src/ts/ui/bodyEditor/panels/physicPanel.ts @@ -1,12 +1,12 @@ import { EditorPanel } from "../editorPanel"; import { Slider } from "handle-sliderjs"; -import { TelluricPlanemo } from "../../../planemos/telluricPlanemo/telluricPlanemo"; +import { TelluricPlanet } from "../../../planets/telluricPlanet/telluricPlanet"; export class PhysicPanel extends EditorPanel { constructor() { super("physic"); } - init(planet: TelluricPlanemo) { + init(planet: TelluricPlanet) { for (const slider of this.sliders) slider.remove(); this.sliders = [ diff --git a/src/ts/ui/bodyEditor/panels/ringsPanel.ts b/src/ts/ui/bodyEditor/panels/ringsPanel.ts index a043fe1b1..f6048707e 100644 --- a/src/ts/ui/bodyEditor/panels/ringsPanel.ts +++ b/src/ts/ui/bodyEditor/panels/ringsPanel.ts @@ -1,15 +1,15 @@ import { EditorPanel } from "../editorPanel"; import { clearAllEventListenersById } from "../../../utils/html"; -import { AbstractBody } from "../../../bodies/abstractBody"; import { Slider } from "handle-sliderjs"; import { Color3 } from "@babylonjs/core/Maths/math.color"; import { RingsPostProcess } from "../../../postProcesses/rings/ringsPostProcess"; +import { CelestialBody } from "../../../architecture/celestialBody"; export class RingsPanel extends EditorPanel { constructor() { super("rings"); } - init(body: AbstractBody, rings: RingsPostProcess) { + init(body: CelestialBody, rings: RingsPostProcess) { for (const slider of this.sliders) slider.remove(); const ringsToggler = clearAllEventListenersById("ringsToggler"); diff --git a/src/ts/ui/bodyEditor/panels/surfacePanel.ts b/src/ts/ui/bodyEditor/panels/surfacePanel.ts index 6da839fce..0de91291b 100644 --- a/src/ts/ui/bodyEditor/panels/surfacePanel.ts +++ b/src/ts/ui/bodyEditor/panels/surfacePanel.ts @@ -1,5 +1,5 @@ import { EditorPanel } from "../editorPanel"; -import { TelluricPlanemo } from "../../../planemos/telluricPlanemo/telluricPlanemo"; +import { TelluricPlanet } from "../../../planets/telluricPlanet/telluricPlanet"; import { clearAllEventListenersById } from "../../../utils/html"; import { Color3 } from "@babylonjs/core/Maths/math.color"; import { Slider } from "handle-sliderjs"; @@ -8,7 +8,7 @@ export class SurfacePanel extends EditorPanel { constructor() { super("surface"); } - init(planet: TelluricPlanemo) { + init(planet: TelluricPlanet) { for (const slider of this.sliders) slider.remove(); const material = planet.material; diff --git a/src/ts/ui/helmetOverlay.ts b/src/ts/ui/helmetOverlay.ts index 5ddafc267..92ad0ea06 100644 --- a/src/ts/ui/helmetOverlay.ts +++ b/src/ts/ui/helmetOverlay.ts @@ -1,20 +1,14 @@ import overlayHTML from "../../html/helmetOverlay.html"; -import { AbstractObject } from "../bodies/abstractObject"; +import { OrbitalObject } from "../architecture/orbitalObject"; export class HelmetOverlay { private readonly parentNode: HTMLElement; private readonly bodyNamePlate: HTMLElement; - private readonly bodySeedPlate: HTMLElement; constructor() { document.body.insertAdjacentHTML("beforeend", overlayHTML); this.parentNode = document.getElementById("helmetOverlay") as HTMLElement; this.bodyNamePlate = document.getElementById("bodyName") as HTMLElement; - this.bodySeedPlate = document.getElementById("bodySeed") as HTMLElement; - this.bodySeedPlate.addEventListener("click", () => { - const seed = this.bodySeedPlate.innerText.replace("Seed: ", ""); - if (seed.length > 0) navigator.clipboard.writeText(seed); - }); } public setVisibility(visible: boolean) { @@ -25,8 +19,7 @@ export class HelmetOverlay { return this.parentNode.style.visibility === "visible"; } - public update(currentBody: AbstractObject) { + public update(currentBody: OrbitalObject) { this.bodyNamePlate.innerText = currentBody.name; - this.bodySeedPlate.innerText = `Seed: ${currentBody.model.seed.toString()}`; } } diff --git a/src/ts/ui/objectOverlay.ts b/src/ts/ui/objectOverlay.ts index 4af9ec36f..dad3889b7 100644 --- a/src/ts/ui/objectOverlay.ts +++ b/src/ts/ui/objectOverlay.ts @@ -1,5 +1,4 @@ import { TextBlock } from "@babylonjs/gui/2D/controls/textBlock"; -import { AbstractObject } from "../bodies/abstractObject"; import { StackPanel } from "@babylonjs/gui/2D/controls/stackPanel"; import { Image } from "@babylonjs/gui/2D/controls/image"; import cursorImage from "../../asset/textures/hoveredCircle.png"; @@ -8,6 +7,7 @@ import { Vector3 } from "@babylonjs/core/Maths/math.vector"; import { getAngularSize } from "../utils/isObjectVisibleOnScreen"; import { Camera } from "@babylonjs/core/Cameras/camera"; import { LOCAL_DIRECTION } from "../uberCore/localDirections"; +import { OrbitalObject } from "../architecture/orbitalObject"; export class ObjectOverlay { readonly textRoot: StackPanel; @@ -16,11 +16,11 @@ export class ObjectOverlay { readonly typeText: TextBlock; readonly distanceText: TextBlock; readonly etaText: TextBlock; - readonly object: AbstractObject; + readonly object: OrbitalObject; private lastDistance: number = 0; - constructor(object: AbstractObject) { + constructor(object: OrbitalObject) { this.object = object; this.textRoot = new StackPanel(object.name + "OverlayTextRoot"); @@ -80,7 +80,7 @@ export class ObjectOverlay { this.cursor.linkWithMesh(this.object.getTransform()); } - update(camera: Camera, target: AbstractObject | null) { + update(camera: Camera, target: OrbitalObject | null) { const viewRay = camera.getDirection(LOCAL_DIRECTION.BACKWARD); const objectRay = this.object.getTransform().getAbsolutePosition().subtract(camera.globalPosition); const distance = objectRay.length(); diff --git a/src/ts/ui/systemUI.ts b/src/ts/ui/systemUI.ts index e6d6f3d28..540c359da 100644 --- a/src/ts/ui/systemUI.ts +++ b/src/ts/ui/systemUI.ts @@ -1,14 +1,14 @@ import { Scene } from "@babylonjs/core/scene"; import { AdvancedDynamicTexture } from "@babylonjs/gui/2D/advancedDynamicTexture"; -import { AbstractObject } from "../bodies/abstractObject"; import { ObjectOverlay } from "./objectOverlay"; import { Camera } from "@babylonjs/core/Cameras/camera"; +import { OrbitalObject } from "../architecture/orbitalObject"; export class SystemUI { readonly gui: AdvancedDynamicTexture; private objectOverlays: ObjectOverlay[] = []; - private target: AbstractObject | null = null; + private target: OrbitalObject | null = null; constructor(scene: Scene) { this.gui = AdvancedDynamicTexture.CreateFullscreenUI("SystemUI", true, scene); @@ -22,7 +22,7 @@ export class SystemUI { return this.gui.rootContainer.alpha === 1; } - public createObjectOverlays(objects: AbstractObject[]) { + public createObjectOverlays(objects: OrbitalObject[]) { this.removeObjectOverlays(); for (const object of objects) { @@ -50,7 +50,7 @@ export class SystemUI { } } - setTarget(object: AbstractObject | null) { + setTarget(object: OrbitalObject | null) { if (this.target === object) { this.target = null; return; diff --git a/src/ts/utils/extractRelevantPostProcesses.ts b/src/ts/utils/extractRelevantPostProcesses.ts index da6e19257..3f3501f11 100644 --- a/src/ts/utils/extractRelevantPostProcesses.ts +++ b/src/ts/utils/extractRelevantPostProcesses.ts @@ -1,9 +1,9 @@ import { Engine } from "@babylonjs/core/Engines/engine"; import { ObjectPostProcess } from "../postProcesses/objectPostProcess"; import { PostProcessRenderEffect } from "@babylonjs/core/PostProcesses/RenderPipeline/postProcessRenderEffect"; -import { AbstractObject } from "../bodies/abstractObject"; +import { CelestialBody } from "../architecture/celestialBody"; -export function extractRelevantPostProcesses(postProcesses: ObjectPostProcess[], body: AbstractObject): [ObjectPostProcess[], ObjectPostProcess[]] { +export function extractRelevantPostProcesses(postProcesses: ObjectPostProcess[], body: CelestialBody): [ObjectPostProcess[], ObjectPostProcess[]] { const relevant = []; const notRelevant = []; for (const postProcess of postProcesses) { @@ -13,7 +13,7 @@ export function extractRelevantPostProcesses(postProcesses: ObjectPostProcess[], return [relevant, notRelevant]; } -export function makeSplitRenderEffects(name: string, body: AbstractObject, postProcesses: ObjectPostProcess[], engine: Engine): [PostProcessRenderEffect, PostProcessRenderEffect] { +export function makeSplitRenderEffects(name: string, body: CelestialBody, postProcesses: ObjectPostProcess[], engine: Engine): [PostProcessRenderEffect, PostProcessRenderEffect] { const [bodyRings, otherRings] = extractRelevantPostProcesses(postProcesses, body); const otherRingsRenderEffect = new PostProcessRenderEffect(engine, `other${name}RenderEffect`, () => { return otherRings; diff --git a/src/ts/utils/isObjectVisibleOnScreen.ts b/src/ts/utils/isObjectVisibleOnScreen.ts index c572d97e4..09b4c6ce0 100644 --- a/src/ts/utils/isObjectVisibleOnScreen.ts +++ b/src/ts/utils/isObjectVisibleOnScreen.ts @@ -1,7 +1,7 @@ import { Vector3 } from "@babylonjs/core/Maths/math"; import { Camera } from "@babylonjs/core/Cameras/camera"; -import { Transformable } from "../uberCore/transforms/basicTransform"; -import { BoundingSphere } from "../bodies/common"; +import { BoundingSphere } from "../architecture/boundingSphere"; +import { Transformable } from "../architecture/transformable"; /** * Computes the angular size in radians of an object viewed by a camera diff --git a/src/ts/utils/nearestBody.ts b/src/ts/utils/nearestBody.ts index dc4dddd89..5ed4b6d69 100644 --- a/src/ts/utils/nearestBody.ts +++ b/src/ts/utils/nearestBody.ts @@ -1,9 +1,9 @@ -import { AbstractBody } from "../bodies/abstractBody"; -import { Transformable } from "../uberCore/transforms/basicTransform"; -import { BoundingSphere } from "../bodies/common"; +import { BoundingSphere } from "../architecture/boundingSphere"; import { Vector3 } from "@babylonjs/core/Maths/math.vector"; +import { CelestialBody } from "../architecture/celestialBody"; +import { Transformable } from "../architecture/transformable"; -export function nearestBody(objectPosition: Vector3, bodies: AbstractBody[]): AbstractBody { +export function nearestBody(objectPosition: Vector3, bodies: CelestialBody[]): CelestialBody { let distance = -1; if (bodies.length === 0) throw new Error("no bodieees !"); let nearest = bodies[0]; diff --git a/src/ts/utils/positionNearObject.ts b/src/ts/utils/positionNearObject.ts index 6ee2b9578..3ddf90d8e 100644 --- a/src/ts/utils/positionNearObject.ts +++ b/src/ts/utils/positionNearObject.ts @@ -1,8 +1,8 @@ import { Vector3 } from "@babylonjs/core/Maths/math.vector"; import { StarSystemController } from "../starSystem/starSystemController"; import { nearestBody } from "./nearestBody"; -import { Transformable } from "../uberCore/transforms/basicTransform"; -import { BoundingSphere } from "../bodies/common"; +import { Transformable } from "../architecture/transformable"; +import { BoundingSphere } from "../architecture/boundingSphere"; export function positionNearObject(transformable: Transformable, object: Transformable & BoundingSphere, starSystem: StarSystemController, nRadius = 3): void { // go from the nearest star to be on the sunny side of the object diff --git a/src/ts/utils/wrappers.ts b/src/ts/utils/wrappers.ts index 0fcbe56f4..4f6a63346 100644 --- a/src/ts/utils/wrappers.ts +++ b/src/ts/utils/wrappers.ts @@ -1,9 +1,10 @@ -import { Transformable } from "../uberCore/transforms/basicTransform"; -import { BoundingSphere } from "../bodies/common"; + import { TransformNode } from "@babylonjs/core/Meshes"; import { Quaternion } from "@babylonjs/core/Maths/math"; import { DirectionalLight } from "@babylonjs/core/Lights/directionalLight"; import { PointLight } from "@babylonjs/core/Lights/pointLight"; +import { Transformable } from "../architecture/transformable"; +import { BoundingSphere } from "../architecture/boundingSphere"; export class TransformNodeWrapper implements Transformable, BoundingSphere { readonly transform: TransformNode; @@ -21,6 +22,10 @@ export class TransformNodeWrapper implements Transformable, BoundingSphere { getTransform(): TransformNode { return this.transform; } + + dispose(): void { + this.transform.dispose(); + } } export class DirectionalLightWrapper implements Transformable { @@ -36,6 +41,11 @@ export class DirectionalLightWrapper implements Transformable { getTransform(): TransformNode { return this.transform; } + + dispose() { + this.light.dispose(); + this.transform.dispose(); + } } export class PointLightWrapper implements Transformable { @@ -51,4 +61,9 @@ export class PointLightWrapper implements Transformable { getTransform(): TransformNode { return this.transform; } + + dispose() { + this.light.dispose(); + this.transform.dispose(); + } } diff --git a/src/ts/xr.ts b/src/ts/xr.ts index e04b6f1df..3e08010b0 100644 --- a/src/ts/xr.ts +++ b/src/ts/xr.ts @@ -10,8 +10,8 @@ import { Engine } from "@babylonjs/core/Engines/engine"; import HavokPhysics from "@babylonjs/havok"; import { HavokPlugin } from "@babylonjs/core/Physics/v2/Plugins/havokPlugin"; import { setMaxLinVel } from "./utils/havok"; -import { TelluricPlanemo } from "./planemos/telluricPlanemo/telluricPlanemo"; -import { ChunkForgeWorkers } from "./planemos/telluricPlanemo/terrain/chunks/chunkForgeWorkers"; +import { TelluricPlanet } from "./planets/telluricPlanet/telluricPlanet"; +import { ChunkForgeWorkers } from "./planets/telluricPlanet/terrain/chunks/chunkForgeWorkers"; import { Star } from "./stellarObjects/star/star"; import { Settings } from "./settings"; import { ScenePerformancePriority } from "@babylonjs/core"; @@ -80,7 +80,7 @@ const xrCamera = xr.baseExperience.camera; xrCamera.setTransformationFromNonVRCamera(camera); xrCamera.maxZ = camera.maxZ; -const planet = new TelluricPlanemo("xrPlanet", scene, 0.51, undefined); +const planet = new TelluricPlanet("xrPlanet", scene, 0.51, null); translate(planet.getTransform(), new Vector3(0, 0, sphereRadius * 4)); const star = new Star("star", scene, 0.2); //PointLightWrapper(new PointLight("dir01", new Vector3(0, 1, 0), scene)); @@ -126,7 +126,7 @@ scene.onBeforeRenderObservable.add(() => { chunkForge.update(); - star.updateMaterial(); + star.updateMaterial(deltaTime); //ocean.update(deltaTime); });