@hology/core 0.0.20 → 0.0.23
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/config/project-config.d.ts +2 -0
- package/dist/config/project-config.js +1 -1
- package/dist/csm.js +1 -1
- package/dist/gameplay/actors/actor.d.ts +2 -2
- package/dist/gameplay/actors/actor.js +1 -1
- package/dist/gameplay/actors/builtin/camera-actor.d.ts +1 -1
- package/dist/gameplay/actors/builtin/camera-actor.js +1 -1
- package/dist/gameplay/actors/builtin/components/mesh-component.d.ts +4 -4
- package/dist/gameplay/actors/builtin/components/mesh-component.js +1 -1
- package/dist/gameplay/actors/builtin/positional-audio-actor.js +1 -1
- package/dist/gameplay/actors/builtin/spawn-point.d.ts +1 -1
- package/dist/gameplay/actors/builtin/spawn-point.js +1 -1
- package/dist/gameplay/actors/builtin/trigger-volume.js +1 -1
- package/dist/gameplay/actors/camera/camera-component.js +1 -1
- package/dist/gameplay/actors/camera/third-party-camera-component.js +1 -1
- package/dist/gameplay/actors/factory.js +1 -1
- package/dist/gameplay/initiate.d.ts +1 -0
- package/dist/gameplay/initiate.js +1 -1
- package/dist/gameplay/services/physics/physics-system.d.ts +1 -0
- package/dist/gameplay/services/physics/physics-system.js +1 -1
- package/dist/gameplay/services/render.d.ts +6 -1
- package/dist/gameplay/services/render.js +1 -1
- package/dist/gameplay/services/world.js +1 -1
- package/dist/rendering.d.ts +4 -0
- package/dist/rendering.js +1 -1
- package/dist/scene/asset-resource-loader.d.ts +2 -0
- package/dist/scene/asset-resource-loader.js +1 -1
- package/dist/scene/materializer.d.ts +2 -1
- package/dist/scene/materializer.js +1 -1
- package/dist/scene/model.d.ts +4 -1
- package/dist/scene/model.js +1 -1
- package/dist/scene/storage/storage.d.ts +1 -0
- package/dist/scene/storage/storage.js +1 -1
- package/dist/shader/parameter.d.ts +2 -2
- package/dist/shader/parameter.js +1 -1
- package/dist/utils/materials.d.ts +1 -0
- package/dist/utils/materials.js +5 -0
- package/package.json +2 -2
- package/tsconfig.tsbuildinfo +1 -1
package/dist/csm.js
CHANGED
@@ -1,4 +1,4 @@
|
|
1
|
-
import*as e from"three";const
|
1
|
+
import*as e from"three";const n=e.Object3D.prototype.add,t=new WeakMap,a=new WeakMap;export const CSMUtil={renderingView:null,onBeforeCompile(e,n){e.defines=e.defines||{},e.defines.USE_CSM=1,e.defines.CSM_CASCADES=this.renderingView.csm.cascades;const t=Math.min(this.renderingView.camera.far,this.renderingView.csm.maxFar),a=[];this.renderingView.csm.getExtendedBreaks(a),n.uniforms.CSM_cascades={value:a},n.uniforms.cameraNear={value:this.renderingView.camera.near},n.uniforms.shadowFar={value:t}},patchThreeAdd(){const r=this.renderingView;t.set(r.scene,r.csm),e.Object3D.prototype.add=function(...r){let i=this;for(;null!=i.parent;)i=i.parent;const s=i,o=t.get(s);if(null==o)return n.apply(this,arguments),this;a.has(s)||a.set(s,new WeakSet);const c=a.get(s);function d(e){e&&!c.has(e)&&(c.add(e),null==o||o.setupMaterial(e))}return r.forEach((n=>null==n?void 0:n.traverse((n=>{if(n instanceof e.Mesh||n instanceof e.SkinnedMesh)if(n.material instanceof Array)for(const e of n.material)d(e);else d(n.material)})))),n.apply(this,arguments),this}}};
|
2
2
|
/*
|
3
3
|
* Copyright (©) 2023. All rights reserved.
|
4
4
|
* See the LICENSE.md file for details.
|
@@ -1,5 +1,5 @@
|
|
1
1
|
import { Subject } from "rxjs";
|
2
|
-
import {
|
2
|
+
import { Object3D } from "three";
|
3
3
|
import { Constructable } from "typedi";
|
4
4
|
import { ActorComponent, ComponentAttachProps } from "./component";
|
5
5
|
export declare function Actor(): (targetConstructor: any) => void;
|
@@ -10,7 +10,7 @@ export type ActorId = number;
|
|
10
10
|
export declare abstract class BaseActor {
|
11
11
|
readonly id: ActorId;
|
12
12
|
__isInitialised: boolean;
|
13
|
-
readonly
|
13
|
+
readonly object: Object3D;
|
14
14
|
readonly disposed: Subject<true>;
|
15
15
|
get position(): import("three").Vector3;
|
16
16
|
get quaternion(): import("three").Quaternion;
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{__decorate as t,__metadata as e}from"tslib";import o,{ignore as i}from"@plumier/reflect";import{Subject as n,skipWhile as r}from"rxjs";import{Group as s}from"three";import a,{Service as p}from"typedi";import{ActorComponent as d}from"./component";import{initComponents as c}from"./internal/component-init";import{activeContainerInstance as l,containerRefMap as u}from"./internal/container-map";import{randomString as m}from"../../utils/math";import{inject as h}from"../inject";import{ViewController as f}from"../services/render";export function Actor(){const t=p({transient:!0});return function(e){e.__isActor=!0,t(e),o.noop()(e),o.parameterProperties()(e)}}let v=0;export class BaseActor{get position(){var t;return null===(t=this.
|
1
|
+
import{__decorate as t,__metadata as e}from"tslib";import o,{ignore as i}from"@plumier/reflect";import{Subject as n,skipWhile as r}from"rxjs";import{Group as s}from"three";import a,{Service as p}from"typedi";import{ActorComponent as d}from"./component";import{initComponents as c}from"./internal/component-init";import{activeContainerInstance as l,containerRefMap as u}from"./internal/container-map";import{randomString as m}from"../../utils/math";import{inject as h}from"../inject";import{ViewController as f}from"../services/render";export function Actor(){const t=p({transient:!0});return function(e){e.__isActor=!0,t(e),o.noop()(e),o.parameterProperties()(e)}}let v=0;export class BaseActor{get position(){var t;return null===(t=this.object)||void 0===t?void 0:t.position}get quaternion(){var t;return null===(t=this.object)||void 0===t?void 0:t.quaternion}get rotation(){var t;return null===(t=this.object)||void 0===t?void 0:t.rotation}onInit(){}onBeginPlay(){}onEndPlay(){}onUpdate(t){}onLateUpdate(t){}constructor(){this.id=++v,this.__isInitialised=!1,this.object=new s,this.disposed=new n,this.onUpdate!==BaseActor.prototype.onUpdate&&h(f).onUpdate(this).pipe(r((()=>!this.__isInitialised))).subscribe((t=>this.onUpdate(t))),this.onLateUpdate!==BaseActor.prototype.onLateUpdate&&h(f).onLateUpdate(this).pipe(r((()=>!this.__isInitialised))).subscribe((t=>this.onLateUpdate(t)))}attach(t,e){var o,i;const n=l.value,r=null!==(i=null!==(o=u.get(this))&&void 0!==o?o:l.value)&&void 0!==i?i:a.of("default");l.value=r;const s=m();r.set({id:s,type:t,transient:!0});const p=r.get(s);if(l.value=n,null!=e)for(const t of Object.keys(e))p[t]=e[t];return this.__isInitialised&&(p.actor=this,p.onInit(),c(p,this)),p}getComponent(t){for(const e of Object.values(this))if(e instanceof t)return e}}t([i(),e("design:type",Object),e("design:paramtypes",[])],BaseActor.prototype,"position",null),t([i(),e("design:type",Object),e("design:paramtypes",[])],BaseActor.prototype,"quaternion",null),t([i(),e("design:type",Object),e("design:paramtypes",[])],BaseActor.prototype,"rotation",null);export function _setupActorUpdateEventHandlers(){this.onUpdate!==d.prototype.onUpdate&&h(f).onUpdate(this.actor).pipe(r((()=>!this.actor.__isInitialised))).subscribe((t=>this.onUpdate(t))),this.onLateUpdate!==d.prototype.onLateUpdate&&h(f).onLateUpdate(this.actor).pipe(r((()=>!this.actor.__isInitialised))).subscribe((t=>this.onLateUpdate(t)))}
|
2
2
|
/*
|
3
3
|
* Copyright (©) 2023. All rights reserved.
|
4
4
|
* See the LICENSE.md file for details.
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{__decorate as e,__metadata as o}from"tslib";import{ArrowHelper as r,ConeGeometry as t,EdgesGeometry as a,LineBasicMaterial as n,LineSegments as s,MeshStandardMaterial as l,Vector3 as i}from"three";import{Actor as c,BaseActor as m}from"../actor";import{CameraComponent as p}from"../camera/camera-component";import{ActorComponent as d,Attach as w,Component as y}from"../component";let h=class extends d{constructor(){super(...arguments),this.arrowColor=16101442}onInit(){const e=new t(1,1,4);e.rotateX(Math.PI/2),e.rotateZ(Math.PI/4),e.scale(1,9/16,1);const o=new a(e),c=(new l({color:3355443}),new s(o,new n({color:16777215}))),m=new r(new i(0,0,-1),new i(0,0,0),1.2,this.arrowColor,.15,.2);c.add(m),m.layers.disableAll(),m.layers.enable(19),m.traverse((e=>{e.layers.disableAll(),e.layers.enable(19)})),this.actor.
|
1
|
+
import{__decorate as e,__metadata as o}from"tslib";import{ArrowHelper as r,ConeGeometry as t,EdgesGeometry as a,LineBasicMaterial as n,LineSegments as s,MeshStandardMaterial as l,Vector3 as i}from"three";import{Actor as c,BaseActor as m}from"../actor";import{CameraComponent as p}from"../camera/camera-component";import{ActorComponent as d,Attach as w,Component as y}from"../component";let h=class extends d{constructor(){super(...arguments),this.arrowColor=16101442}onInit(){const e=new t(1,1,4);e.rotateX(Math.PI/2),e.rotateZ(Math.PI/4),e.scale(1,9/16,1);const o=new a(e),c=(new l({color:3355443}),new s(o,new n({color:16777215}))),m=new r(new i(0,0,-1),new i(0,0,0),1.2,this.arrowColor,.15,.2);c.add(m),m.layers.disableAll(),m.layers.enable(19),m.traverse((e=>{e.layers.disableAll(),e.layers.enable(19)})),this.actor.object.add(c)}};h=e([y({inEditor:!0,editorOnly:!0})],h);export{h as CameraMesh};let b=class extends m{};e([w(),o("design:type",p)],b.prototype,"camera",void 0),e([w(),o("design:type",h)],b.prototype,"mesh",void 0),b=e([c()],b);export{b as CameraActor};
|
2
2
|
/*
|
3
3
|
* Copyright (©) 2023. All rights reserved.
|
4
4
|
* See the LICENSE.md file for details.
|
@@ -1,9 +1,9 @@
|
|
1
1
|
import { PhysicsBodyType, PhysicsSystem } from "../../../../gameplay/services/physics/physics-system";
|
2
|
-
import { Euler,
|
2
|
+
import { Euler, Object3D, Vector3 } from "three";
|
3
3
|
import { ActorComponent } from "../../component";
|
4
|
-
export declare class MeshComponent extends ActorComponent {
|
4
|
+
export declare class MeshComponent<TObj extends Object3D = Object3D> extends ActorComponent {
|
5
5
|
private physicsSystem;
|
6
|
-
|
6
|
+
object: TObj;
|
7
7
|
readonly position: Vector3;
|
8
8
|
readonly rotation: Euler;
|
9
9
|
readonly scale: Vector3;
|
@@ -14,7 +14,7 @@ export declare class MeshComponent extends ActorComponent {
|
|
14
14
|
private currentMesh;
|
15
15
|
constructor(physicsSystem: PhysicsSystem);
|
16
16
|
onInit(): void | Promise<void>;
|
17
|
-
|
17
|
+
setObject(replacement: TObj): void;
|
18
18
|
private updateMesh;
|
19
19
|
private getCollisionShapes;
|
20
20
|
}
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{__decorate as t,__metadata as s}from"tslib";import{PhysicsBodyType as i,PhysicsSystem as e}from"../../../../gameplay/services/physics/physics-system";import{AssetMeshInstance as o}from"../../../../scene/asset-resource-loader";import{PhysicalShapeMesh as n}from"../../../../";import{Parameter as r}from"../../../../shader/parameter";import{Euler as
|
1
|
+
import{__decorate as t,__metadata as s}from"tslib";import{PhysicsBodyType as i,PhysicsSystem as e}from"../../../../gameplay/services/physics/physics-system";import{AssetMeshInstance as o}from"../../../../scene/asset-resource-loader";import{PhysicalShapeMesh as n}from"../../../../";import{Parameter as r}from"../../../../shader/parameter";import{Euler as c,Object3D as h,Vector3 as p}from"three";import{ActorComponent as a,Component as l}from"../../component";import{firstValueFrom as m}from"rxjs";const y={friction:.1,mass:0,bodyType:i.static,continousCollisionDetection:!1};let d=class extends a{constructor(t){super(),this.physicsSystem=t,this.position=new p,this.rotation=new c,this.scale=new p(1,1,1),this.mass=y.mass,this.friction=y.friction,this.bodyType=i.static,this.continousCollisionDetection=y.continousCollisionDetection}onInit(){null!=this.object&&(this.currentMesh=this.object,this.updateMesh()),m(this.disposed).then((()=>{this.physicsSystem.removeActor(this.actor)}))}setObject(t){null!=this.currentMesh&&this.actor.object.remove(this.currentMesh),this.object=this.currentMesh=t,this.updateMesh()}updateMesh(){this.currentMesh.position.copy(this.position),this.currentMesh.rotation.copy(this.rotation),this.currentMesh.scale.copy(this.scale);const t=this.getCollisionShapes();t.length>0&&this.physicsSystem.addActor(this.actor,t,Object.assign(Object.assign({},y),{isTrigger:!1,mass:this.mass,friction:this.friction,type:this.bodyType,continousCollisionDetection:this.continousCollisionDetection})),this.actor.object.add(this.currentMesh)}getCollisionShapes(){return this.currentMesh instanceof o?this.currentMesh.collisionShapes:this.currentMesh instanceof n?[this.currentMesh.collisionShape]:"collisionShape"in this.currentMesh?(console.error("Could not understand wehre to get collision shapes from. This is likely due to an import issue"),[this.currentMesh.collisionShape]):[]}};t([r({type:h}),s("design:type",Object)],d.prototype,"object",void 0),t([r(),s("design:type",p)],d.prototype,"position",void 0),t([r(),s("design:type",c)],d.prototype,"rotation",void 0),t([r(),s("design:type",p)],d.prototype,"scale",void 0),t([r(),s("design:type",Number)],d.prototype,"mass",void 0),t([r(),s("design:type",Number)],d.prototype,"friction",void 0),t([r({options:[{name:"Static",value:i.static},{name:"Dynamic",value:i.dynamic}]}),s("design:type",Number)],d.prototype,"bodyType",void 0),d=t([l({inEditor:!0}),s("design:paramtypes",[e])],d);export{d as MeshComponent};
|
2
2
|
/*
|
3
3
|
* Copyright (©) 2023. All rights reserved.
|
4
4
|
* See the LICENSE.md file for details.
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{__decorate as t,__metadata as i}from"tslib";import*as e from"three";import{Actor as o,BaseActor as r}from"../actor";import{ActorComponent as
|
1
|
+
import{__decorate as t,__metadata as i}from"tslib";import*as e from"three";import{Actor as o,BaseActor as r}from"../actor";import{ActorComponent as s,Component as n,attach as a}from"../component";import{Parameter as l}from"../../../shader";import{ViewController as d}from"../../services/render";import{inject as u}from"../../inject";import{PositionalAudioHelper as p}from"../../../utils/three/positional-audio-helper";let c=class extends r{constructor(){super(...arguments),this.audio=a(m)}};c=t([o()],c);export{c as PositionalAudioActor};let h=class extends s{onInit(){const t=(new e.TextureLoader).load("assets/audio.png"),i=new e.SpriteMaterial({map:t}),o=new e.Sprite(i);this.actor.object.add(o),this.helper=new p(this.positionalAudio)}};h=t([n({inEditor:!0,editorOnly:!0})],h);let m=class extends s{constructor(){super(...arguments),this.view=u(d),this.sound=new e.PositionalAudio(this.view.audioListener),this.visualisation=a(h,{positionalAudio:this.sound})}onInit(){var t,i;this.sound.setBuffer(this.audioBuffer),null!=this.refDistance&&this.sound.setRefDistance(this.refDistance),null!=this.rollofFactor&&this.sound.setRolloffFactor(this.rollofFactor),null!=this.maxDistance&&this.sound.setMaxDistance(this.maxDistance),null!=this.directionalInnerAngle&&null!=this.directionalOuterAngle&&null!=this.directionalOuterGain&&this.sound.setDirectionalCone(this.directionalInnerAngle,this.directionalOuterAngle,this.directionalOuterGain),null===(i=null===(t=this.visualisation)||void 0===t?void 0:t.helper)||void 0===i||i.update(),this.actor.object.add(this.sound),this.sound.play()}};t([l(),i("design:type",AudioBuffer)],m.prototype,"audioBuffer",void 0),t([l(),i("design:type",Number)],m.prototype,"refDistance",void 0),t([l(),i("design:type",Number)],m.prototype,"rollofFactor",void 0),t([l(),i("design:type",Number)],m.prototype,"maxDistance",void 0),t([l(),i("design:type",Number)],m.prototype,"directionalInnerAngle",void 0),t([l(),i("design:type",Number)],m.prototype,"directionalOuterAngle",void 0),t([l({range:[0,1]}),i("design:type",Number)],m.prototype,"directionalOuterGain",void 0),m=t([n({inEditor:!0})],m);export{m as PositionalAudioComponent};
|
2
2
|
/*
|
3
3
|
* Copyright (©) 2023. All rights reserved.
|
4
4
|
* See the LICENSE.md file for details.
|
@@ -5,7 +5,7 @@ export declare class SpawnPointMesh extends ActorComponent {
|
|
5
5
|
onInit(): void | Promise<void>;
|
6
6
|
}
|
7
7
|
export declare class SpawnPoint extends BaseActor {
|
8
|
-
mesh
|
8
|
+
private mesh;
|
9
9
|
private readonly world;
|
10
10
|
spawnActor<T extends BaseActor>(type: Type<T>): Promise<T>;
|
11
11
|
}
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{__decorate as t,__metadata as o}from"tslib";import{
|
1
|
+
import{__decorate as t,__metadata as o}from"tslib";import{ArrowHelper as r,Vector3 as e,Euler as i}from"three";import{Actor as s,BaseActor as n}from"../actor";import{Component as p,ActorComponent as m,Attach as c}from"../component";import{World as a}from"../../../gameplay/services/world";import{inject as d}from"../../../gameplay/inject";import{createLineSphere as l}from"../../../utils/three/line-sphere";let h=class extends m{onInit(){const t=l(1);this.actor.object.add(t);const o=new r(new e(0,0,1),new e,1,1268122,.3,.3);this.actor.object.add(o)}};h=t([p({inEditor:!0,editorOnly:!0})],h);export{h as SpawnPointMesh};let w=class extends n{constructor(){super(...arguments),this.world=d(a)}spawnActor(t){return this.world.spawnActor(t,this.position,new i(0,this.rotation.y,0,"XYZ"))}};t([c(),o("design:type",h)],w.prototype,"mesh",void 0),w=t([s()],w);export{w as SpawnPoint};
|
2
2
|
/*
|
3
3
|
* Copyright (©) 2023. All rights reserved.
|
4
4
|
* See the LICENSE.md file for details.
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{__decorate as t,__metadata as s}from"tslib";import{EdgesGeometry as i,LineSegments as e,LineBasicMaterial as o,Vector3 as r,BoxGeometry as n,Mesh as c,MeshBasicMaterial as h,Group as p}from"three";import{Actor as a,BaseActor as d}from"../actor";import{Component as m,ActorComponent as y,Attach as l}from"../component";import{PhysicsSystem as v}from"../../services/physics/physics-system";import{BoxCollisionShape as g}from"../../../scene/collision/collision-shape";import{firstValueFrom as w}from"rxjs";let A=class extends y{constructor(){super(...arguments),this.dimensions=new r(1,1,1)}onInit(){const t=new n(this.dimensions.x,this.dimensions.y,this.dimensions.z),s=new i(t),r=new e(s,new o({color:16777215})),a=(new c(t,new h({color:16777215,transparent:!0,opacity:.3,visible:!1})),new p);a.add(r),this.actor.
|
1
|
+
import{__decorate as t,__metadata as s}from"tslib";import{EdgesGeometry as i,LineSegments as e,LineBasicMaterial as o,Vector3 as r,BoxGeometry as n,Mesh as c,MeshBasicMaterial as h,Group as p}from"three";import{Actor as a,BaseActor as d}from"../actor";import{Component as m,ActorComponent as y,Attach as l}from"../component";import{PhysicsSystem as v}from"../../services/physics/physics-system";import{BoxCollisionShape as g}from"../../../scene/collision/collision-shape";import{firstValueFrom as w}from"rxjs";let A=class extends y{constructor(){super(...arguments),this.dimensions=new r(1,1,1)}onInit(){const t=new n(this.dimensions.x,this.dimensions.y,this.dimensions.z),s=new i(t),r=new e(s,new o({color:16777215})),a=(new c(t,new h({color:16777215,transparent:!0,opacity:.3,visible:!1})),new p);a.add(r),this.actor.object.add(a)}};A=t([m({inEditor:!0,editorOnly:!0})],A);export{A as TriggerVolumeMesh};let O=class extends y{constructor(t){super(),this.physicsSystem=t,this.dimensions=new r(1,1,1)}onInit(){this.editorMesh=this.attach(A),console.log("add actor",this.actor),this.physicsSystem.addActor(this.actor,[new g(this.dimensions)],{isTrigger:!0}),w(this.disposed).then((()=>{this.physicsSystem.removeActor(this.actor)}))}onBeginOverlapWithActor(t){return this.physicsSystem.onBeginOverlapWithActor(this.actor,t)}onEndOverlapWithActor(t){return this.physicsSystem.onEndOverlapWithActor(this.actor,t)}onBeginOverlapWithActorType(t){return this.physicsSystem.onBeginOverlapWithActorType(this.actor,t)}onEndOverlapWithActorType(t){return this.physicsSystem.onEndOverlapWithActorType(this.actor,t)}};O=t([m({inEditor:!0,editorOnly:!1}),s("design:paramtypes",[v])],O);export{O as TriggerVolumeComponent};let u=class extends d{};t([l(),s("design:type",O)],u.prototype,"trigger",void 0),u=t([a()],u);export{u as TriggerVolume};
|
2
2
|
/*
|
3
3
|
* Copyright (©) 2023. All rights reserved.
|
4
4
|
* See the LICENSE.md file for details.
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{__decorate as e,__metadata as t}from"tslib";import{ActorComponent as i,Component as r}from"../component";import{ViewController as n}from"../../services/render";import{PerspectiveCamera as s}from"three";import{Parameter as o}from"../../../shader/parameter";const a=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let h=class extends i{constructor(e){super(),this.viewController=e,this.near=.5,this.far=500,this.viewAngle=a?30:45,this.aspect=this.viewController.htmlElement.clientWidth/this.viewController.htmlElement.clientHeight,this.instance=new s(this.viewAngle,this.aspect,this.near,this.far)}onInit(){this.actor.
|
1
|
+
import{__decorate as e,__metadata as t}from"tslib";import{ActorComponent as i,Component as r}from"../component";import{ViewController as n}from"../../services/render";import{PerspectiveCamera as s}from"three";import{Parameter as o}from"../../../shader/parameter";const a=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let h=class extends i{constructor(e){super(),this.viewController=e,this.near=.5,this.far=500,this.viewAngle=a?30:45,this.aspect=this.viewController.htmlElement.clientWidth/this.viewController.htmlElement.clientHeight,this.instance=new s(this.viewAngle,this.aspect,this.near,this.far)}onInit(){this.actor.object.add(this.instance),this.instance.near=this.near,this.instance.far=this.far,this.instance.fov=this.viewAngle}};e([o(),t("design:type",Object)],h.prototype,"near",void 0),e([o(),t("design:type",Number)],h.prototype,"far",void 0),e([o(),t("design:type",Number)],h.prototype,"viewAngle",void 0),h=e([r({inEditor:!0}),t("design:paramtypes",[n])],h);export{h as CameraComponent};
|
2
2
|
/*
|
3
3
|
* Copyright (©) 2023. All rights reserved.
|
4
4
|
* See the LICENSE.md file for details.
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{__awaiter as t,__decorate as
|
1
|
+
import{__awaiter as t,__decorate as s,__metadata as e}from"tslib";import{ActorComponent as i,Component as o,Attach as n}from"../component";import{CameraComponent as h}from"./camera-component";import{Vector3 as a}from"three";import{ViewController as r}from"../../services/render";import{DecimalInput as c,RestrictedRotationInput as m}from"../../input";import{PhysicsSystem as d,RayTestResult as l}from"../../services/physics/physics-system";import{clamp as u,lerp as p}from"three/src/math/MathUtils";let f=class extends i{constructor(t,s){super(),this.viewController=t,this.physicsSystem=s,this.distance=9,this.minDistance=1.5,this.maxDistance=this.distance,this.height=3,this.offsetX=-1,this.offsetZ=1.5,this.autoActivate=!0,this.bounceBackSpeed=5,this.collisionCheckRadius=.5,this.restrictedDistance=Math.max(this.distance,this.maxDistance),this.rotationInput=new m(-Math.PI/4,Math.PI/2-.7),this.zoomInput=new c(1,0,1),this.offset=new a,this.lookAtOffset=new a(this.offsetX,0,this.offsetZ),this.isMouseLocked=!1,this.canvas=null,this.pointerLockInactivatedAt=null,this.onMouseDown=t=>{this.isMouseLocked||this.hideCursor()},this.onKeyDown=t=>{"Escape"===t.key&&this.showCursor()},this.onPointerLockChange=()=>{null!=document.pointerLockElement||null!=document.mozPointerLockElement||this.showCursor()}}onInit(){return t(this,void 0,void 0,(function*(){this.restrictedDistance=Math.max(this.distance,this.maxDistance),this.lookAtOffset.set(this.offsetX,0,this.offsetZ),this.autoActivate&&this.viewController.setCamera(this.camera.instance),this.physicsSystem.afterStep.subscribe((t=>{this.setFromRotation(t)}));const t=this.element;t.addEventListener("mousedown",this.onMouseDown),t.addEventListener("keydown",this.onKeyDown),document.addEventListener("pointerlockchange",this.onPointerLockChange,!1),this.disposed.subscribe((()=>{t.removeEventListener("mousedown",this.onMouseDown),t.removeEventListener("keydown",this.onKeyDown),document.removeEventListener("pointerlockchange",this.onPointerLockChange,!1)}))}))}get element(){return this.viewController.htmlElement}hideCursor(){null!=this.pointerLockInactivatedAt&&performance.now()-this.pointerLockInactivatedAt<1600||(this.element.style.cursor="none",null==this.canvas&&(this.canvas=this.element.getElementsByTagName("canvas")[0]),this.canvas&&(this.canvas.requestPointerLock(),this.isMouseLocked=!0))}showCursor(){this.pointerLockInactivatedAt=performance.now(),this.element.style.cursor="default",window.document.exitPointerLock(),this.isMouseLocked=!1}setFromRotation(t){const s=u(Math.min(this.restrictedDistance,this.distance),this.minDistance,Math.max(this.distance*this.zoomInput.value,this.minDistance)),e=Math.cos(this.rotationInput.rotation.x)*s;this.offset.x=Math.sin(this.rotationInput.rotation.y)*e,this.offset.y=Math.sin(this.rotationInput.rotation.x)*s+2,this.offset.z=Math.cos(this.rotationInput.rotation.y)*-e,this.offset.add(this.lookAtOffset),this.updateCameraPosition(),this.checkForCollision(t)}checkForCollision(t){const s=this.getLookAtPosition(),e=v;let i=!1,o=this.distance;const n=new l,h=this.camera.instance.getWorldPosition(y);for(let t=-1;t<=1;t++){const a=w.subVectors(h,s);e.copy(h).add(a.multiplyScalar(1.2)),e.x+=t*this.collisionCheckRadius,this.physicsSystem.rayTest(s,e,n,{debugLifetime:0}),n.hasHit&&n.distance<this.distance&&(o=Math.min(n.distance,o),i||(i=n.hasHit))}i||(this.restrictedDistance=p(this.restrictedDistance,this.distance,this.bounceBackSpeed*t))}getLookAtPosition(){const t=k;return t.set(0,0,0),t.y=this.height,t.add(this.lookAtOffset),t.applyMatrix4(this.actor.object.matrixWorld),t}updateCameraPosition(){this.camera.instance.position.copy(this.offset);const t=this.getLookAtPosition();this.camera.instance.lookAt(t)}};s([n(),e("design:type",h)],f.prototype,"camera",void 0),f=s([o(),e("design:paramtypes",[r,d])],f);export{f as ThirdPartyCameraComponent};const k=new a,v=new a,w=(new a,new a),y=new a;
|
2
2
|
/*
|
3
3
|
* Copyright (©) 2023. All rights reserved.
|
4
4
|
* See the LICENSE.md file for details.
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{__awaiter as t,__decorate as i,__metadata as
|
1
|
+
import{__awaiter as t,__decorate as i,__metadata as o}from"tslib";import{ContainerInstance as n}from"typedi";import{Service as e}from"typedi";import{initComponents as r}from"./internal/component-init";import{activeContainerInstance as s,containerRefMap as c}from"./internal/container-map";let a=class{constructor(t,i){this.container=t,this.env=i}create(i,o,n,e){return t(this,void 0,void 0,(function*(){const t=this.container;s.value=t;const r=(1e4*Math.random()).toString();t.set({id:r,type:i,transient:!0});const a=t.get(r);return s.value=null,t.remove(i),c.set(a,t),o&&a.object.position.copy(o),n&&a.object.rotation.copy(n),!0!==e&&(yield this.initActor(a)),a}))}initActor(i){var o;return t(this,void 0,void 0,(function*(){yield r(i,i,null!==(o=this.env.inEditor)&&void 0!==o&&o),yield i.onInit(),i.__isInitialised=!0}))}};a=i([e(),o("design:paramtypes",[n,Object])],a);export{a as ActorFactory};
|
2
2
|
/*
|
3
3
|
* Copyright (©) 2023. All rights reserved.
|
4
4
|
* See the LICENSE.md file for details.
|
@@ -35,6 +35,7 @@ export declare class HologyRuntime<T_Game = unknown> {
|
|
35
35
|
private containerInstance;
|
36
36
|
status: HologyRuntimeStatus;
|
37
37
|
gameInstance?: T_Game;
|
38
|
+
isShutdown: boolean;
|
38
39
|
private _resolver;
|
39
40
|
/**
|
40
41
|
* A promise that you can await on to delay some logic until the runtime has finished loading
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{__awaiter as
|
1
|
+
import{__awaiter as t}from"tslib";import e from"typedi";import{loadScene as n}from"../scene/bootstrap";import{ActorFactory as o}from"./actors/factory";import{World as s}from"./services/world";import{ViewController as r}from"./services/render";import{RenderingView as i}from"../rendering";import{PhysicsSystem as a}from"./services/physics/physics-system";import{MeshComponent as c}from"./actors/builtin/components/mesh-component";import{activeContainerInstance as m}from"./actors/internal/container-map";import{InputService as d}from"./input";import{RuntimeBackendService as l}from"../scene/runtime-backend-service";import{RuntimeAssetsService as p}from"../scene/runtime-asset-service";import{AssetResourceLoader as h}from"../scene/asset-resource-loader";import{AssetLoader as u}from"./services/asset-loader";export function initiateGame(d,f){if(0!=f.element.childNodes.length)return console.error("Can not initialize the game with a non-empty html element"),null;e.has(r);const g=e.of("default"),w=new HologyRuntime(g),v=new o(g,{inEditor:!1});var y;e.set(o,v),y=f.element,Object.assign(y.style,{position:"absolute",top:"0",left:"0",width:"100%",height:"100%"});const I=new i(f.element);I.renderer.shadowMap.autoUpdate=!0,e.set(i,I);const S=new r(I);e.set(r,S);const b=new s(e.get(o));e.set(s,b);const D=new l(f.dataDir),x=new p(D),G=new h;G.setDataDir(f.dataDir);const H=new u(G,x);return e.set(u,H),(()=>{t(this,void 0,void 0,(function*(){const t=e.get(a);if(yield t.start(),w.isShutdown)return;const{scene:o,actors:s}=yield n(I,f.sceneName,f.dataDir,f.shaders,f.actors,v,D,x,G);if(b.scene=o,w.isShutdown)return void I.stop();e.import([c]);for(const t of s)b.addActor(t);t.addFromScene(o),I.loop((t=>{})),w.status=5,m.value=g,g.remove(d),g.set({id:d,type:d});const r=g.get(d);m.value=null,w.gameInstance=r,r instanceof GameInstance&&r.onStart(),w._resolver(!0)}))})(),w}export class GameInstance{onStart(){}onShutdown(){}}export function createHologyScene(){}export class HologyRuntime{constructor(t){this.containerInstance=t,this.status=0,this.isShutdown=!1,this.ready=new Promise((t=>{this._resolver=t}))}getWorld(){return this.containerInstance.get(s)}getService(t){return this.containerInstance.get(t)}shutdown(){this.isShutdown=!0,this.gameInstance instanceof GameInstance&&this.gameInstance.onShutdown(),this.containerInstance.get(d).stop();const t=this.containerInstance.get(i);null==t||t.stop();for(const t of this.getWorld().actors)this.getWorld().removeActor(t);this.containerInstance.get(a).stop(),this.containerInstance.reset()}}
|
2
2
|
/*
|
3
3
|
* Copyright (©) 2023. All rights reserved.
|
4
4
|
* See the LICENSE.md file for details.
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{__awaiter as e,__decorate as t,__metadata as i}from"tslib";import*as o from"@dimforge/rapier3d-compat";import{QueryFilterFlags as s}from"@dimforge/rapier3d-compat";import{Quaternion as r,RaycastResult as n,Vec3 as a}from"cannon-es";import{filter as l,map as c,Observable as d,Subject as h,takeUntil as u}from"rxjs";import*as y from"three";import{ArrowHelper as p,BufferAttribute as g,BufferGeometry as m,Group as f,LineSegments as w,Matrix4 as v,MeshBasicMaterial as x,Object3D as B,Raycaster as A,Scene as b,Vector3 as C}from"three";import{Service as D}from"typedi";import{AssetMeshInstance as z}from"../../../scene/asset-resource-loader";import{BoxCollisionShape as T,CapsuleCollisionShape as M,ConeCollisionShape as R,ConvexPolyhedronCollisionShape as S,CylinderCollisionShape as E,PhysicalShapeMesh as W,PlaneCollisionShape as _,SphereCollisionShape as F,TrimeshCollisionShape as V}from"../../../";import{LandscapeGroup as P}from"../../../scene/landscape/landscape";import{ViewController as k}from"../render";import{World as I}from"../world";import*as L from"three/examples/jsm/utils/BufferGeometryUtils.js";import{calculateEffectiveScale as O}from"../../../utils/three/traverse";export class RayTestResult{constructor(){this.hasHit=!1,this.hitPoint=new C,this.hitNormal=new C}}new n,new a,new a;export var PhysicsBodyType;!function(e){e[e.dynamic=1]="dynamic",e[e.static=2]="static",e[e.kinematic=4]="kinematic",e[e.kinematicVelocityBased=8]="kinematicVelocityBased"}(PhysicsBodyType||(PhysicsBodyType={}));let N=class{set showDebug(e){this.shouldRenderDebug=e,this.debugMesh&&(this.debugMesh.visible=e)}get showDebug(){return this.shouldRenderDebug}constructor(e,t){this.viewController=e,this.gameWorld=t,this.staticMeshes=new Map,this.staticBodies=new Map,this.actorBodies=new Map,this.bodyActors=new Map,this.collisionEvents=new h,this.beforeStep=new h,this.afterStep=new h,this.shouldRenderDebug=!1,this._raycaster=new A,this._reusableResult=new RayTestResult,this._raytestDiff=new C,this._raytestDirection=new C,this.controlledActors=new Set,this.ready=this.setup()}createDebugMesh(){return new w(new m,new x({color:255}))}start(){return e(this,void 0,void 0,(function*(){return yield this.ready,this.handleTick(),this.ready}))}renderDebug(){null==this.debugMesh&&(this.debugMesh=this.createDebugMesh(),this.debugMesh.visible=this.shouldRenderDebug,this.debugMesh.raycast=function(){},this.gameWorld.scene.add(this.debugMesh));const e=this.world.debugRender();this.debugMesh.geometry.setAttribute("position",new g(e.vertices,3))}setup(){return e(this,void 0,void 0,(function*(){if(null!=this.rapier)throw new Error("Rapier is already estup");this.rapier=yield X(),this.eventQueue=new o.EventQueue(!0),this.setupWorld()}))}handleTick(){this.viewController.onUpdate().subscribe((e=>{this.beforeStep.next(e),this.updatePhysics(),this.afterStep.next(e),this.showDebug&&this.renderDebug(),this.world.bodies.forEach((e=>{var t,i,o;if(e.isFixed())return;const s=null!==(t=this.staticMeshes.get(e))&&void 0!==t?t:null===(i=this.bodyActors.get(e))||void 0===i?void 0:i.container;var r,n;null!=s&&(Y(s.position,e.translation()),(e.isDynamic()||e.isKinematic()&&!this.controlledActors.has(null===(o=this.bodyActors.get(e))||void 0===o?void 0:o.id))&&(r=s.quaternion,n=e.rotation(),r.x=n.x,r.y=n.y,r.z=n.z,r.w=n.w))}))}))}_updateWorld(){this.world.timestep=0,this.world.step()}updatePhysics(){this.world.step(this.eventQueue),this.eventQueue.drainCollisionEvents(((e,t,i)=>{this.collisionEvents.next({handle1:e,handle2:t,started:i}),this.collisionEvents.next({handle1:t,handle2:e,started:i})}))}rayTestFromCamera(e,t,i){this._raycaster.setFromCamera(K,this.viewController.getCamera());const o=this._raycaster.ray.origin,s=this._raycaster.ray.direction.multiplyScalar(e).add(o);return this.rayTest(o,s,t,i)}rayTest(e,t,i,s){var r,n;null==i&&(i=this._reusableResult);const a=this._raytestDiff,l=this._raytestDirection;if(a.subVectors(t,e),l.copy(a).normalize(),0===l.length())return console.warn("Ray test called with to and from being equal"),i;const c=new o.Ray(e,l),d=a.length(),h=this.world.castRayAndGetNormal(c,d,!1,void 0,void 0,void 0,null!=(null==s?void 0:s.excludeActor)?this.actorBodies.get(s.excludeActor.id):void 0);if(i.hasHit=null!=h,i.hasHit){const t=c.pointAt(h.toi);i._internal=h,Y(i.hitNormal,h.normal),Y(i.hitPoint,t),i.distance=$.subVectors(i.hitPoint,e).length();const o=this.world.bodies.getAll().find((e=>function(e,t){for(let i=0,o=e.numColliders();i<o;i++){const o=e.collider(i);if(t(o))return o}}(e,(e=>e===h.collider))));i.actor=null!=o?this.bodyActors.get(o):null}if(this.showDebug){const t=new p(l,e,d,null!==(r=null==s?void 0:s.debugColor)&&void 0!==r?r:255);this.gameWorld.scene.add(t),setTimeout((()=>this.gameWorld.scene.remove(t)),null!==(n=null==s?void 0:s.debugLifetime)&&void 0!==n?n:200)}return this._reusableResult}setGravity(e,t,i){this.world.gravity.x=e,this.world.gravity.y=t,this.world.gravity.z=i}getGravity(){return j.set(this.world.gravity.x,this.world.gravity.y,this.world.gravity.z)}addFromScene(e){this.addRecursively(e)}addRecursively(e){var t,i;if(this.removeSceneObject(e),!function(e){var t,i;if(null!=(null===(t=e.userData)||void 0===t?void 0:t.src)){return"actor"===(null===(i=e.userData)||void 0===i?void 0:i.src).type}return!1}(e))if(e instanceof W&&null!=e.collisionShape){const t=this.createStaticBody(e,[e.collisionShape]);this.staticMeshes.set(t,e),this.staticBodies.set(e,t)}else if(e instanceof z&&!1!==(null===(i=null===(t=e.userData)||void 0===t?void 0:t.src)||void 0===i?void 0:i.collisionDetection))if(e.children[0]&&e.children[0].instanceMatrix)this.createForInstancedMesh(e.children[0],e.collisionShapes);else{const t=this.createStaticBody(e,e.collisionShapes);this.staticMeshes.set(t,e),this.staticBodies.set(e,t)}else e instanceof P?this.addLandscapeGroup(e):(e instanceof f||e instanceof b)&&e.children.forEach((e=>this.addRecursively(e)))}createForInstancedMesh(e,t){const i=new v;for(let o=0;o<e.count;o++){const s=new B;s.matrix.identity(),i.fromArray(e.instanceMatrix.array,16*o),s.applyMatrix4(i);this.createStaticBody(s,t)}}getCharacterController(e=.01){var t;return null===(t=this.world)||void 0===t?void 0:t.createCharacterController(e)}getActorComputedMovement(e,t,i){const o=this.actorBodies.get(e.id);this.controlledActors.add(e.id);const r=o.collider(0);t.computeColliderMovement(r,i,s.EXCLUDE_SENSORS,null,te);const n=t.computedMovement();return Y(ee,n),ee}setNextKinematicTranslation(e,t){const i=this.actorBodies.get(e.id),o=i.translation();o.x+=t.x,o.y+=t.y,o.z+=t.z,null==i||i.setNextKinematicTranslation(o)}setAngularVelocity(e,t){const i=this.actorBodies.get(e.id);U.x=t.x,U.y=t.y,U.z=t.z,null==i||i.setAngvel(U,!0)}setLinearVelocity(e,t){const i=this.actorBodies.get(e.id);U.x=t.x,U.y=t.y,U.z=t.z,null==i||i.setLinvel(U,!0)}getLinearVelocity(e,t=new C){const i=this.actorBodies.get(e.id).linvel();return t.x=i.x,t.y=i.y,t.z=i.z,t}getAngularVelocity(e,t=new C){const i=this.actorBodies.get(e.id).angvel();return t.x=i.x,t.y=i.y,t.z=i.z,t}setLinearDamping(e,t){const i=this.actorBodies.get(e.id);null==i||i.setLinearDamping(t)}setAngularDamping(e,t){const i=this.actorBodies.get(e.id);null==i||i.setAngularDamping(t)}createCharacterCollision(){return new o.CharacterCollision}addLandscapeGroup(e){const t=e.userData.src,i=t.landscape.heightMaps;for(const r of e.sections){this.staticBodies.has(r)&&this.world.removeRigidBody(this.staticBodies.get(r));const e=t.landscape.options.density+1,n=t.landscape.options.sectionSize,a=new Array(e);for(let t=0;t<e;t++)a[t]=new Array(e).fill(0);const l=i.find((e=>e.x===r.x&&e.y==r.y));if(null!=l)for(const t of l.points){if(null==a[t.i%e])continue;const i=e-1-Math.floor(t.i/e);i in a[t.i%e]?a[t.i%e][i]=t.y/n:console.warn("wrong index",{points:a,point:t,i:t.i%e,k:i,heightMap:l})}const c=t.landscape.options.density,d=a.flatMap((e=>e.reverse())),h=o.ColliderDesc.heightfield(c,c,new Float32Array(d),new o.Vector3(n,n,n));var s=r.getWorldPosition(new C);const u=this.world.createRigidBody(o.RigidBodyDesc.fixed()),y=new o.Vector3(0,0,0);J(y,s),u.setTranslation(y,!1),this.world.createCollider(h,u),this.staticBodies.set(r,u)}}addActor(e,t,i={}){var s,r;if(0==t.length)return void console.error("No collision shapes were defined when adding actor to the physics system.");this.removeActor(e);const n=e.container;let a;switch(null!==(s=i.type)&&void 0!==s?s:PhysicsBodyType.static){case PhysicsBodyType.dynamic:a=o.RigidBodyDesc.dynamic(),a.mass=null!==(r=i.mass)&&void 0!==r?r:1;break;case PhysicsBodyType.kinematic:a=o.RigidBodyDesc.kinematicPositionBased();break;case PhysicsBodyType.kinematicVelocityBased:a=o.RigidBodyDesc.kinematicVelocityBased();break;default:a=(i.isTrigger,o.RigidBodyDesc.kinematicVelocityBased())}const l=this.world.createRigidBody(a);l.enableCcd(1==i.continousCollisionDetection);for(const e of t)this.addShape(l,e,n);Z(l,(e=>{null!=i.isTrigger&&(e.setSensor(i.isTrigger),e.setActiveCollisionTypes(o.ActiveCollisionTypes.ALL)),null!=i.friction&&e.setFriction(i.friction),null!=i.restitution&&e.setDensity(i.restitution),null!=i.mass&&e.setMass(i.mass),null!=i.restitution&&e.setRestitution(i.restitution)})),Q(l,n),this.actorBodies.set(e.id,l),this.bodyActors.set(l,e)}applyTorque(e,t){const i=this.actorBodies.get(e.id);U.x=t.x,U.y=t.y,U.z=t.z,null==i||i.addTorque(U,!0)}applyTorqueImpulse(e,t){const i=this.actorBodies.get(e.id);U.x=t.x,U.y=t.y,U.z=t.z,null==i||i.applyTorqueImpulse(U,!0)}resetForces(e){const t=this.actorBodies.get(e.id);null==t||t.resetForces(!1)}resetTorques(e){const t=this.actorBodies.get(e.id);null==t||t.resetTorques(!1)}applyForce(e,t){const i=this.actorBodies.get(e.id);U.x=t.x,U.y=t.y,U.z=t.z,null==i||i.addForce(U,!0)}applyImpulse(e,t){const i=this.actorBodies.get(e.id);U.x=t.x,U.y=t.y,U.z=t.z,null==i||i.applyImpulse(U,!0)}applyLocalForce(e,t,i){const o=this.actorBodies.get(e.id);J(U,t),null==i?null==o||o.addForce(U,!0):(J(H,i),null==o||o.addForceAtPoint(U,H,!0))}applyLocalImpulse(e,t,i){const o=this.actorBodies.get(e.id);J(U,t),null==i?o.applyImpulse(U,!0):(J(H,i),o.applyImpulseAtPoint(U,H,!0))}removeActor(e){this.controlledActors.delete(e.id);const t=this.actorBodies.get(e.id);null!=t&&(this.bodyActors.delete(t),this.world.removeRigidBody(t)),this.actorBodies.delete(e.id)}removeSceneObject(e){let t=this.staticBodies.get(e);null!=t&&this.world.getRigidBody(t.handle)&&this.world.removeRigidBody(t)}activateActorEvents(e){const t=this.actorBodies.get(e.id);t&&Z(t,(e=>e.setActiveEvents(o.ActiveEvents.COLLISION_EVENTS)))}_onCollisionWithActorEvent(e,t,i){return this.activateActorEvents(e),this.collisionEvents.pipe(u(e.disposed),l((({started:e})=>e===i)),c((({handle1:e,handle2:t,started:i})=>({a1:this.bodyActors.get(this.world.getCollider(e).parent()),a2:this.bodyActors.get(this.world.getCollider(t).parent()),started:i}))),l((({a1:i,a2:o})=>null!=i&&null!=o&&i.id===e.id&&t(i,o))),c((({a2:e})=>e)))}onBeginOverlapWithActorType(e,t){return this._onCollisionWithActorEvent(e,((e,i)=>i instanceof t),!0)}onEndOverlapWithActorType(e,t){return this._onCollisionWithActorEvent(e,((e,i)=>i instanceof t),!1)}onBeginOverlapWithActor(e,t){return this._onCollisionWithActorEvent(e,((e,i)=>t.id===i.id),!0)}onEndOverlapWithActor(e,t){return this._onCollisionWithActorEvent(e,((e,i)=>t.id===i.id),!1)}onCollisionWithActor(e,t){return this.onBeginOverlapWithActor(e,t)}onCollisionWithActorType(e,t){return this.onBeginOverlapWithActorType(e,t)}onCollision(e){return new d((t=>{if(null==this.actorBodies.get(e.id))throw new Error("Actor must be added to the physics system before setting up collision event handler");return()=>{}}))}updateActorTransform(e){const t=this.actorBodies.get(e.id);null!=t?Q(t,e.container):console.warn("Actor has not been added to physics world",e)}setupWorld(){const e=new o.World({x:0,y:-9.81,z:0});this.world=e,e.maxVelocityIterations=4}getActorContacts(e,t){const i=this.actorBodies.get(e.id);if(i&&i.numColliders()>0){const s=i.collider(0);let r=s.shape,n=s.translation(),a=s.rotation(),l=t,c=.3;const d=this.world.castShape(n,a,l,r,c,!0,null,null,null,this.actorBodies.get(e.id),(e=>e.shape.type!=o.ShapeType.HeightField));if(null!=d){const e=new C,t=new C,i=new C;return Y(e,d.witness2),Y(t,d.witness1),Y(i,d.normal1),i.negate(),[{ri:e,rj:t,ni:i}]}return[]}return console.warn("Actor is not added to the physics system"),[]}stop(){this.world.free()}createStaticBody(e,t){const i=this.world.createRigidBody(o.RigidBodyDesc.kinematicPositionBased());for(const o of t)this.addShape(i,o,e);return Q(i,e),i}addShape(e,t,i){const o=this.createShape(t,i.scale);o.friction=.1;const s=t.offset.clone().multiply(i.scale);var n,a;J(o.translation,s),n=o.rotation,a=(new r).setFromEuler(t.rotation.x,t.rotation.y,t.rotation.z),n.x=a.x,n.y=a.y,n.z=a.z,n.w=a.w;this.world.createCollider(o,e)}createShape(e,t){if(e instanceof T)return o.ColliderDesc.cuboid(e.dimensions.x*t.x/2,e.dimensions.y*t.y/2,e.dimensions.z*t.z/2);if(e instanceof M){return o.ColliderDesc.capsule(e.length/2*t.y,e.radius*Math.max(t.z,t.x))}if(e instanceof V){const t=null!=e.geometry.getIndex()?e.geometry:L.mergeVertices(e.geometry);return o.ColliderDesc.trimesh(new Float32Array(t.getAttribute("position").array),new Uint32Array(t.getIndex().array))}if(e instanceof S){let i;e.mesh instanceof y.Mesh?i=e.mesh.geometry:e.mesh instanceof y.BufferGeometry?i=e.mesh:console.log("Unknownd shape",{shapeInfo:e});const s=new Float32Array(i.getAttribute("position").array);if(e.mesh instanceof y.Mesh){const t=O(e.mesh);for(let e=0;e<s.length;e+=3)s[e]*=t.x,s[e+1]*=t.y,s[e+2]*=t.z}for(let e=0;e<s.length;e+=3)s[e]*=t.x,s[e+1]*=t.y,s[e+2]*=t.z;return o.ColliderDesc.convexHull(s)}return e instanceof F?o.ColliderDesc.ball(e.radius*Math.max(t.x,t.y,t.z)):e instanceof E?o.ColliderDesc.cylinder(e.height/2*t.y,e.radiusTop*Math.max(t.z,t.x)):e instanceof R?o.ColliderDesc.cone(e.height*t.y,e.radiusBottom/2*Math.max(t.z,t.x)):e instanceof _?o.ColliderDesc.cuboid(e.width/2*t.x,e.height/2*t.y,.01):(console.error("Unsupported shape",e),o.ColliderDesc.cuboid(1,1,1))}};N=t([D(),i("design:paramtypes",[k,I])],N);export{N as PhysicsSystem};const q=new C,G=new y.Quaternion;function Q(e,t){const i=t.getWorldPosition(q),s=t.getWorldQuaternion(G);e.setTranslation(new o.Vector3(i.x,i.y,i.z),!1),e.setRotation(new o.Quaternion(s.x,s.y,s.z,s.w),!1)}const j=new C,U=new o.Vector3(0,0,0),H=new o.Vector3(0,0,0),K=(new C,{x:0,y:0}),X=()=>e(void 0,void 0,void 0,(function*(){let e=yield import("@dimforge/rapier3d-compat");return yield e.init(),e}));function J(e,t){e.x=t.x,e.y=t.y,e.z=t.z}function Y(e,t){e.x=t.x,e.y=t.y,e.z=t.z}function Z(e,t){for(let i=0,o=e.numColliders();i<o;i++){t(e.collider(i))}}const $=new C,ee=new C,te=e=>!e.isSensor();
|
1
|
+
import{__awaiter as e,__decorate as t,__metadata as i}from"tslib";import*as o from"@dimforge/rapier3d-compat";import{QueryFilterFlags as s}from"@dimforge/rapier3d-compat";import{Quaternion as r,RaycastResult as n,Vec3 as l}from"cannon-es";import{filter as a,map as d,Observable as c,Subject as h,takeUntil as u}from"rxjs";import*as y from"three";import{ArrowHelper as p,BufferAttribute as g,BufferGeometry as m,Group as f,LineSegments as w,Matrix4 as v,MeshBasicMaterial as x,Object3D as B,Raycaster as b,Scene as A,Vector3 as C}from"three";import{Service as D}from"typedi";import{AssetMeshInstance as z}from"../../../scene/asset-resource-loader";import{BoxCollisionShape as M,CapsuleCollisionShape as T,ConeCollisionShape as R,ConvexPolyhedronCollisionShape as S,CylinderCollisionShape as E,PhysicalShapeMesh as W,PlaneCollisionShape as _,SphereCollisionShape as F,TrimeshCollisionShape as V}from"../../../";import{LandscapeGroup as P}from"../../../scene/landscape/landscape";import{ViewController as k}from"../render";import{World as I}from"../world";import*as L from"three/examples/jsm/utils/BufferGeometryUtils.js";import{calculateEffectiveScale as O}from"../../../utils/three/traverse";export class RayTestResult{constructor(){this.hasHit=!1,this.hitPoint=new C,this.hitNormal=new C}}new n,new l,new l;export var PhysicsBodyType;!function(e){e[e.dynamic=1]="dynamic",e[e.static=2]="static",e[e.kinematic=4]="kinematic",e[e.kinematicVelocityBased=8]="kinematicVelocityBased"}(PhysicsBodyType||(PhysicsBodyType={}));let j=class{set showDebug(e){this.shouldRenderDebug=e,this.debugMesh&&(this.debugMesh.visible=e)}get showDebug(){return this.shouldRenderDebug}constructor(e,t){this.viewController=e,this.gameWorld=t,this.staticMeshes=new Map,this.staticBodies=new Map,this.actorBodies=new Map,this.bodyActors=new Map,this.collisionEvents=new h,this.beforeStep=new h,this.afterStep=new h,this.shouldRenderDebug=!1,this._raycaster=new b,this._reusableResult=new RayTestResult,this._raytestDiff=new C,this._raytestDirection=new C,this.controlledActors=new Set,this.ready=this.setup()}createDebugMesh(){return new w(new m,new x({color:255}))}start(){return e(this,void 0,void 0,(function*(){return yield this.ready,this.handleTick(),this.ready}))}renderDebug(){null==this.debugMesh&&(this.debugMesh=this.createDebugMesh(),this.debugMesh.visible=this.shouldRenderDebug,this.debugMesh.raycast=function(){},this.gameWorld.scene.add(this.debugMesh));const e=this.world.debugRender();this.debugMesh.geometry.setAttribute("position",new g(e.vertices,3))}setup(){return e(this,void 0,void 0,(function*(){if(null!=this.rapier)throw new Error("Rapier is already estup");this.rapier=yield X(),this.eventQueue=new o.EventQueue(!0),this.setupWorld()}))}handleTick(){this.fixedupdateSub=this.viewController.onUpdate().subscribe((e=>{e=Math.min(.1,e),this.beforeStep.next(e),this.updatePhysics(e),this.afterStep.next(e),this.showDebug&&this.renderDebug(),this.world.bodies.forEach((e=>{var t,i,o;if(e.isFixed())return;const s=null!==(t=this.staticMeshes.get(e))&&void 0!==t?t:null===(i=this.bodyActors.get(e))||void 0===i?void 0:i.object;var r,n;null!=s&&(Y(s.position,e.translation()),(e.isDynamic()||e.isKinematic()&&!this.controlledActors.has(null===(o=this.bodyActors.get(e))||void 0===o?void 0:o.id))&&(r=s.quaternion,n=e.rotation(),r.x=n.x,r.y=n.y,r.z=n.z,r.w=n.w))}))}))}_updateWorld(){this.world.timestep=0,this.world.step()}updatePhysics(e){this.world.timestep=e,this.world.step(this.eventQueue),this.eventQueue.drainCollisionEvents(((e,t,i)=>{this.collisionEvents.next({handle1:e,handle2:t,started:i}),this.collisionEvents.next({handle1:t,handle2:e,started:i})}))}rayTestFromCamera(e,t,i){this._raycaster.setFromCamera(K,this.viewController.getCamera());const o=this._raycaster.ray.origin,s=this._raycaster.ray.direction.multiplyScalar(e).add(o);return this.rayTest(o,s,t,i)}rayTest(e,t,i,s){var r,n;null==i&&(i=this._reusableResult);const l=this._raytestDiff,a=this._raytestDirection;if(l.subVectors(t,e),a.copy(l).normalize(),0===a.length())return console.warn("Ray test called with to and from being equal"),i;const d=new o.Ray(e,a),c=l.length(),h=this.world.castRayAndGetNormal(d,c,!1,void 0,void 0,void 0,null!=(null==s?void 0:s.excludeActor)?this.actorBodies.get(s.excludeActor.id):void 0);if(i.hasHit=null!=h,i.hasHit){const t=d.pointAt(h.toi);i._internal=h,Y(i.hitNormal,h.normal),Y(i.hitPoint,t),i.distance=$.subVectors(i.hitPoint,e).length();const o=this.world.bodies.getAll().find((e=>function(e,t){for(let i=0,o=e.numColliders();i<o;i++){const o=e.collider(i);if(t(o))return o}}(e,(e=>e===h.collider))));i.actor=null!=o?this.bodyActors.get(o):null}if(this.showDebug){const t=new p(a,e,c,null!==(r=null==s?void 0:s.debugColor)&&void 0!==r?r:255);this.gameWorld.scene.add(t),setTimeout((()=>this.gameWorld.scene.remove(t)),null!==(n=null==s?void 0:s.debugLifetime)&&void 0!==n?n:200)}return this._reusableResult}setGravity(e,t,i){this.world.gravity.x=e,this.world.gravity.y=t,this.world.gravity.z=i}getGravity(){return Q.set(this.world.gravity.x,this.world.gravity.y,this.world.gravity.z)}addFromScene(e){this.addRecursively(e)}addRecursively(e){var t,i;if(this.removeSceneObject(e),!function(e){var t,i;if(null!=(null===(t=e.userData)||void 0===t?void 0:t.src)){return"actor"===(null===(i=e.userData)||void 0===i?void 0:i.src).type}return!1}(e))if(e instanceof W&&null!=e.collisionShape){const t=this.createStaticBody(e,[e.collisionShape]);this.staticMeshes.set(t,e),this.staticBodies.set(e,t)}else if(e instanceof z&&!1!==(null===(i=null===(t=e.userData)||void 0===t?void 0:t.src)||void 0===i?void 0:i.collisionDetection))if(e.children[0]&&e.children[0].instanceMatrix)this.createForInstancedMesh(e.children[0],e.collisionShapes);else{const t=this.createStaticBody(e,e.collisionShapes);this.staticMeshes.set(t,e),this.staticBodies.set(e,t)}else e instanceof P?this.addLandscapeGroup(e):(e instanceof f||e instanceof A)&&e.children.forEach((e=>this.addRecursively(e)))}createForInstancedMesh(e,t){const i=new v;for(let o=0;o<e.count;o++){const s=new B;s.matrix.identity(),i.fromArray(e.instanceMatrix.array,16*o),s.applyMatrix4(i);this.createStaticBody(s,t)}}getCharacterController(e=.01){var t;return null===(t=this.world)||void 0===t?void 0:t.createCharacterController(e)}getActorComputedMovement(e,t,i){const o=this.actorBodies.get(e.id);this.controlledActors.add(e.id);const r=o.collider(0);t.computeColliderMovement(r,i,s.EXCLUDE_SENSORS,null,te);const n=t.computedMovement();return Y(ee,n),ee}setNextKinematicTranslation(e,t){const i=this.actorBodies.get(e.id),o=i.translation();o.x+=t.x,o.y+=t.y,o.z+=t.z,null==i||i.setNextKinematicTranslation(o)}setAngularVelocity(e,t){const i=this.actorBodies.get(e.id);U.x=t.x,U.y=t.y,U.z=t.z,null==i||i.setAngvel(U,!0)}setLinearVelocity(e,t){const i=this.actorBodies.get(e.id);U.x=t.x,U.y=t.y,U.z=t.z,null==i||i.setLinvel(U,!0)}getLinearVelocity(e,t=new C){const i=this.actorBodies.get(e.id).linvel();return t.x=i.x,t.y=i.y,t.z=i.z,t}getAngularVelocity(e,t=new C){const i=this.actorBodies.get(e.id).angvel();return t.x=i.x,t.y=i.y,t.z=i.z,t}setLinearDamping(e,t){const i=this.actorBodies.get(e.id);null==i||i.setLinearDamping(t)}setAngularDamping(e,t){const i=this.actorBodies.get(e.id);null==i||i.setAngularDamping(t)}createCharacterCollision(){return new o.CharacterCollision}addLandscapeGroup(e){const t=e.userData.src,i=t.landscape.heightMaps;for(const r of e.sections){this.staticBodies.has(r)&&this.world.removeRigidBody(this.staticBodies.get(r));const e=t.landscape.options.density+1,n=t.landscape.options.sectionSize,l=new Array(e);for(let t=0;t<e;t++)l[t]=new Array(e).fill(0);const a=i.find((e=>e.x===r.x&&e.y==r.y));if(null!=a)for(const t of a.points){if(null==l[t.i%e])continue;const i=e-1-Math.floor(t.i/e);i in l[t.i%e]?l[t.i%e][i]=t.y/n:console.warn("wrong index",{points:l,point:t,i:t.i%e,k:i,heightMap:a})}const d=t.landscape.options.density,c=l.flatMap((e=>e.reverse())),h=o.ColliderDesc.heightfield(d,d,new Float32Array(c),new o.Vector3(n,n,n));var s=r.getWorldPosition(new C);const u=this.world.createRigidBody(o.RigidBodyDesc.fixed()),y=new o.Vector3(0,0,0);J(y,s),u.setTranslation(y,!1),this.world.createCollider(h,u),this.staticBodies.set(r,u)}}addActor(e,t,i={}){var s,r;if(0==t.length)return void console.error("No collision shapes were defined when adding actor to the physics system.");this.removeActor(e);const n=e.object;let l;switch(null!==(s=i.type)&&void 0!==s?s:PhysicsBodyType.static){case PhysicsBodyType.dynamic:l=o.RigidBodyDesc.dynamic(),l.mass=null!==(r=i.mass)&&void 0!==r?r:1;break;case PhysicsBodyType.kinematic:l=o.RigidBodyDesc.kinematicPositionBased();break;case PhysicsBodyType.kinematicVelocityBased:l=o.RigidBodyDesc.kinematicVelocityBased();break;default:l=(i.isTrigger,o.RigidBodyDesc.kinematicVelocityBased())}const a=this.world.createRigidBody(l);a.enableCcd(1==i.continousCollisionDetection);for(const e of t)this.addShape(a,e,n);Z(a,(e=>{null!=i.isTrigger&&(e.setSensor(i.isTrigger),e.setActiveCollisionTypes(o.ActiveCollisionTypes.ALL)),null!=i.friction&&e.setFriction(i.friction),null!=i.restitution&&e.setDensity(i.restitution),null!=i.mass&&e.setMass(i.mass),null!=i.restitution&&e.setRestitution(i.restitution)})),G(a,n),this.actorBodies.set(e.id,a),this.bodyActors.set(a,e)}applyTorque(e,t){const i=this.actorBodies.get(e.id);U.x=t.x,U.y=t.y,U.z=t.z,null==i||i.addTorque(U,!0)}applyTorqueImpulse(e,t){const i=this.actorBodies.get(e.id);U.x=t.x,U.y=t.y,U.z=t.z,null==i||i.applyTorqueImpulse(U,!0)}resetForces(e){const t=this.actorBodies.get(e.id);null==t||t.resetForces(!1)}resetTorques(e){const t=this.actorBodies.get(e.id);null==t||t.resetTorques(!1)}applyForce(e,t){const i=this.actorBodies.get(e.id);U.x=t.x,U.y=t.y,U.z=t.z,null==i||i.addForce(U,!0)}applyImpulse(e,t){const i=this.actorBodies.get(e.id);U.x=t.x,U.y=t.y,U.z=t.z,null==i||i.applyImpulse(U,!0)}applyLocalForce(e,t,i){const o=this.actorBodies.get(e.id);J(U,t),null==i?null==o||o.addForce(U,!0):(J(H,i),null==o||o.addForceAtPoint(U,H,!0))}applyLocalImpulse(e,t,i){const o=this.actorBodies.get(e.id);J(U,t),null==i?o.applyImpulse(U,!0):(J(H,i),o.applyImpulseAtPoint(U,H,!0))}removeActor(e){this.controlledActors.delete(e.id);const t=this.actorBodies.get(e.id);null!=t&&(this.bodyActors.delete(t),this.world.removeRigidBody(t)),this.actorBodies.delete(e.id)}removeSceneObject(e){let t=this.staticBodies.get(e);null!=t&&this.world.getRigidBody(t.handle)&&this.world.removeRigidBody(t)}activateActorEvents(e){const t=this.actorBodies.get(e.id);t&&Z(t,(e=>e.setActiveEvents(o.ActiveEvents.COLLISION_EVENTS)))}_onCollisionWithActorEvent(e,t,i){return this.activateActorEvents(e),this.collisionEvents.pipe(u(e.disposed),a((({started:e})=>e===i)),d((({handle1:e,handle2:t,started:i})=>({a1:this.bodyActors.get(this.world.getCollider(e).parent()),a2:this.bodyActors.get(this.world.getCollider(t).parent()),started:i}))),a((({a1:i,a2:o})=>null!=i&&null!=o&&i.id===e.id&&t(i,o))),d((({a2:e})=>e)))}onBeginOverlapWithActorType(e,t){return this._onCollisionWithActorEvent(e,((e,i)=>i instanceof t),!0)}onEndOverlapWithActorType(e,t){return this._onCollisionWithActorEvent(e,((e,i)=>i instanceof t),!1)}onBeginOverlapWithActor(e,t){return this._onCollisionWithActorEvent(e,((e,i)=>t.id===i.id),!0)}onEndOverlapWithActor(e,t){return this._onCollisionWithActorEvent(e,((e,i)=>t.id===i.id),!1)}onCollisionWithActor(e,t){return this.onBeginOverlapWithActor(e,t)}onCollisionWithActorType(e,t){return this.onBeginOverlapWithActorType(e,t)}onCollision(e){return new c((t=>{if(null==this.actorBodies.get(e.id))throw new Error("Actor must be added to the physics system before setting up collision event handler");return()=>{}}))}updateActorTransform(e){const t=this.actorBodies.get(e.id);null!=t?G(t,e.object):console.warn("Actor has not been added to physics world",e)}setupWorld(){const e=new o.World({x:0,y:-9.81,z:0});this.world=e,e.maxVelocityIterations=4}getActorContacts(e,t){const i=this.actorBodies.get(e.id);if(i&&i.numColliders()>0){const s=i.collider(0);let r=s.shape,n=s.translation(),l=s.rotation(),a=t,d=.3;const c=this.world.castShape(n,l,a,r,d,!0,null,null,null,this.actorBodies.get(e.id),(e=>e.shape.type!=o.ShapeType.HeightField));if(null!=c){const e=new C,t=new C,i=new C;return Y(e,c.witness2),Y(t,c.witness1),Y(i,c.normal1),i.negate(),[{ri:e,rj:t,ni:i}]}return[]}return console.warn("Actor is not added to the physics system"),[]}stop(){var e,t,i;null===(e=this.world)||void 0===e||e.bodies.forEach((e=>this.world.removeRigidBody(e))),null===(t=this.world)||void 0===t||t.free(),null===(i=this.fixedupdateSub)||void 0===i||i.unsubscribe()}createStaticBody(e,t){const i=this.world.createRigidBody(o.RigidBodyDesc.kinematicPositionBased());for(const o of t)this.addShape(i,o,e);return G(i,e),i}addShape(e,t,i){const o=this.createShape(t,i.scale);o.friction=.1;const s=t.offset.clone().multiply(i.scale);var n,l;J(o.translation,s),n=o.rotation,l=(new r).setFromEuler(t.rotation.x,t.rotation.y,t.rotation.z),n.x=l.x,n.y=l.y,n.z=l.z,n.w=l.w;this.world.createCollider(o,e)}createShape(e,t){if(e instanceof M)return o.ColliderDesc.cuboid(e.dimensions.x*t.x/2,e.dimensions.y*t.y/2,e.dimensions.z*t.z/2);if(e instanceof T){return o.ColliderDesc.capsule(e.length/2*t.y,e.radius*Math.max(t.z,t.x))}if(e instanceof V){const t=null!=e.geometry.getIndex()?e.geometry:L.mergeVertices(e.geometry);return o.ColliderDesc.trimesh(new Float32Array(t.getAttribute("position").array),new Uint32Array(t.getIndex().array))}if(e instanceof S){let i;e.mesh instanceof y.Mesh?i=e.mesh.geometry:e.mesh instanceof y.BufferGeometry?i=e.mesh:console.log("Unknownd shape",{shapeInfo:e});const s=new Float32Array(i.getAttribute("position").array);if(e.mesh instanceof y.Mesh){const t=O(e.mesh);for(let e=0;e<s.length;e+=3)s[e]*=t.x,s[e+1]*=t.y,s[e+2]*=t.z}for(let e=0;e<s.length;e+=3)s[e]*=t.x,s[e+1]*=t.y,s[e+2]*=t.z;return o.ColliderDesc.convexHull(s)}return e instanceof F?o.ColliderDesc.ball(e.radius*Math.max(t.x,t.y,t.z)):e instanceof E?o.ColliderDesc.cylinder(e.height/2*t.y,e.radiusTop*Math.max(t.z,t.x)):e instanceof R?o.ColliderDesc.cone(e.height*t.y,e.radiusBottom/2*Math.max(t.z,t.x)):e instanceof _?o.ColliderDesc.cuboid(e.width/2*t.x,e.height/2*t.y,.01):(console.error("Unsupported shape",e),o.ColliderDesc.cuboid(1,1,1))}};j=t([D(),i("design:paramtypes",[k,I])],j);export{j as PhysicsSystem};const N=new C,q=new y.Quaternion;function G(e,t){const i=t.getWorldPosition(N),s=t.getWorldQuaternion(q);e.setTranslation(new o.Vector3(i.x,i.y,i.z),!1),e.setRotation(new o.Quaternion(s.x,s.y,s.z,s.w),!1)}const Q=new C,U=new o.Vector3(0,0,0),H=new o.Vector3(0,0,0),K=(new C,{x:0,y:0}),X=()=>e(void 0,void 0,void 0,(function*(){let e=yield import("@dimforge/rapier3d-compat");return yield e.init(),e}));function J(e,t){e.x=t.x,e.y=t.y,e.z=t.z}function Y(e,t){e.x=t.x,e.y=t.y,e.z=t.z}function Z(e,t){for(let i=0,o=e.numColliders();i<o;i++){t(e.collider(i))}}const $=new C,ee=new C,te=e=>!e.isSensor();
|
2
2
|
/*
|
3
3
|
* Copyright (©) 2023. All rights reserved.
|
4
4
|
* See the LICENSE.md file for details.
|
@@ -2,15 +2,20 @@ import { Camera } from "three";
|
|
2
2
|
import { RenderingView } from "../../rendering";
|
3
3
|
import { Observable } from "rxjs";
|
4
4
|
import * as THREE from "three";
|
5
|
+
import { CameraActor } from "../../gameplay/actors/builtin/camera-actor";
|
5
6
|
export declare class ViewController {
|
6
7
|
private view;
|
7
8
|
private readonly tick;
|
8
9
|
private readonly lateTick;
|
9
10
|
readonly audioListener: THREE.AudioListener;
|
10
11
|
constructor(view: RenderingView);
|
12
|
+
set fpsCap(fps: number);
|
13
|
+
get fpsCap(): number;
|
14
|
+
set showStats(value: boolean);
|
15
|
+
get showStats(): boolean;
|
11
16
|
onUpdate(actor?: any): Observable<number>;
|
12
17
|
onLateUpdate(actor?: any): Observable<number>;
|
13
|
-
setCamera(camera: Camera): void;
|
18
|
+
setCamera(camera: Camera | CameraActor): void;
|
14
19
|
getCamera(): Camera;
|
15
20
|
get htmlElement(): HTMLElement;
|
16
21
|
pauseRendering(): void;
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{__decorate as
|
1
|
+
import{__decorate as t,__metadata as e}from"tslib";import{Service as i}from"typedi";import{RenderingView as s}from"../../rendering";import{Subject as a,takeUntil as r}from"rxjs";import*as o from"three";import{CameraActor as n}from"../../gameplay/actors/builtin/camera-actor";let p=class{constructor(t){this.view=t,this.tick=new a,this.lateTick=new a,this.audioListener=new o.AudioListener,t.onLoop((t=>{this.tick.next(t),this.lateTick.next(t)})),t.camera.add(this.audioListener),window.hology_view=this}set fpsCap(t){this.view.fpsCap=t}get fpsCap(){return this.view.fpsCap}set showStats(t){this.view.showStats=t}get showStats(){return this.view.showStats}onUpdate(t){return null!=t&&this.tick.pipe(r(t.disposed)),this.tick}onLateUpdate(t){return null!=t&&this.lateTick.pipe(r(t.disposed)),this.lateTick}setCamera(t){const e=t instanceof n?t.camera.instance:t;this.view.setCamera(e),e.add(this.audioListener)}getCamera(){return this.view.camera}get htmlElement(){return this.view.container}pauseRendering(){this.view.paused=!0}unpauseRendering(){this.view.paused=!1}dispose(){this.view.stop()}};p=t([i(),e("design:paramtypes",[s])],p);export{p as ViewController};
|
2
2
|
/*
|
3
3
|
* Copyright (©) 2023. All rights reserved.
|
4
4
|
* See the LICENSE.md file for details.
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{__awaiter as t,__decorate as o,__metadata as r}from"tslib";import{Service as
|
1
|
+
import{__awaiter as t,__decorate as o,__metadata as r}from"tslib";import{Service as e}from"typedi";import{ActorFactory as c}from"../actors/factory";import{ActorComponent as i}from"../../gameplay/actors/component";let s=class{constructor(t){this.actorFactory=t,this.actors=[]}spawnActor(o,r,e){return t(this,void 0,void 0,(function*(){const t=yield this.actorFactory.create(o,r,e);return this.addActor(t,r,e),t}))}addActor(t,o,r){o&&t.object.position.copy(o),r&&t.object.rotation.copy(r),this.scene.add(t.object),this.actors.push(t),n(t,(t=>t.onBeginPlay()))}removeActor(t){n(t,(t=>t.onEndPlay())),this.actors.splice(this.actors.indexOf(t),1),this.scene.remove(t.object),t.disposed.next(!0)}findActorByType(t,o){return this.actors.find((r=>r instanceof t&&(null==o||r.object.name==o)))}findActorsByType(t,o){return this.actors.filter((r=>r instanceof t&&(null==o||r.object.name==o)))}};s=o([e(),r("design:paramtypes",[c])],s);export{s as World};function n(t,o){return o(t),Object.entries(t).filter((([t,o])=>o instanceof i)).forEach((([t,r])=>{n(r,o)}))}
|
2
2
|
/*
|
3
3
|
* Copyright (©) 2023. All rights reserved.
|
4
4
|
* See the LICENSE.md file for details.
|
package/dist/rendering.d.ts
CHANGED
@@ -36,6 +36,10 @@ export declare class RenderingView {
|
|
36
36
|
private onLoopCallbacks;
|
37
37
|
onLoop(onFrame: (deltaTime: number) => any): void;
|
38
38
|
removeOnLoop(onFrame: (deltaTime: number) => any): void;
|
39
|
+
private stats;
|
40
|
+
private _showStats;
|
41
|
+
set showStats(value: boolean);
|
42
|
+
get showStats(): boolean;
|
39
43
|
loop(onFrame: (deltaTime: number) => any, showStats?: boolean): void;
|
40
44
|
private insetHeight;
|
41
45
|
private insetWidth;
|
package/dist/rendering.js
CHANGED
@@ -1,4 +1,4 @@
|
|
1
|
-
import*as e from"three";import{Mesh as t,Matrix4 as i,ShaderMaterial as
|
1
|
+
import*as e from"three";import{Mesh as t,Matrix4 as i,ShaderMaterial as s,PerspectiveCamera as r,ShaderChunk as n}from"three";import{EffectComposer as a}from"three-stdlib";import{RenderPass as h}from"three-stdlib";import{ShaderPass as o}from"three-stdlib";import{FXAAShader as d}from"three-stdlib";import{CSM as l}from"three-stdlib";import{CSMUtil as c}from"./csm";import{GammaCorrectionShader as m}from"three-stdlib";import{Reflector as p}from"three-stdlib";import{depthUniformName as u,resolutionUniformName as g,supportsDepthTextureExtension as v,nearUniformName as f,farUniformName as w}from"./shader-nodes/depth";import{elapsedTimeUniformName as x}from"./shader-nodes/time";import{OutlinePass as C}from"./utils/three/outline-pass";import b from"./utils/three/stats";import{lambertVertexShaderOverride as R}from"./rendering/shader-override";import{DepthPass as y}from"./utils/three/depth-pass";const P=new e.MeshDepthMaterial;P.depthPacking=e.RGBADepthPacking,P.blending=e.NoBlending;n.lights_pars_begin;n.lights_lambert_vertex=R;export class RenderingView{setPaused(e){this.paused=e}resizeRender(){this.previousClientWith===this.container.clientWidth&&this.previousClientHeight===this.container.clientHeight||(this.camera instanceof r&&(this.camera.aspect=this.container.clientWidth/this.container.clientHeight,this.camera.updateProjectionMatrix()),this.renderer.setPixelRatio(window.devicePixelRatio*this.resolutionScale),this.renderer.setSize(this.container.clientWidth,this.container.clientHeight),this.composer.setSize(this.container.clientWidth*this.resolutionScale,this.container.clientHeight*this.resolutionScale),this.previousClientWith=this.container.clientWidth,this.previousClientHeight=this.container.clientHeight)}constructor(t,i={}){this.container=t,this.options=i,this.windowVisible=!0,this.running=!0,this.paused=!1,this.fpsCap=null,this.resolutionScale=1,this.onResize=()=>{this.resizeRender(),this.paused||this.composer.render()},this.onVisiblityChane=()=>{this.windowVisible=!document.hidden},this.isDepthTextureExtensionSupported=!1,this.onLoopCallbacks=[],this.stats=b(),this._showStats=!1,this.insetHeight=200,this.insetWidth=this.insetHeight*(16/9),this.insetOffsetY=250,this.insetMargin=10,this.maxInsetCameras=4,this.overlayCameras=new Set,window.renderer=this.renderer=new e.WebGLRenderer({antialias:!0,powerPreference:"high-performance"}),this.scene=new e.Scene,this.renderer.setPixelRatio(window.devicePixelRatio*this.resolutionScale),this.renderer.setSize(t.clientWidth,t.clientHeight),this.composer=new a(this.renderer);var s=t.clientWidth/t.clientHeight;const r=new e.PerspectiveCamera(45,s,.5,500);r.layers.enable(19),this.setCamera(r),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=e.PCFSoftShadowMap,this.renderer.shadowMap.autoUpdate=!1,this.renderer.outputEncoding=e.sRGBEncoding,this.renderer.physicallyCorrectLights=!1,this.renderer.gammaFactor=1.4,c.renderingView=this,c.patchThreeAdd(),this.isDepthTextureExtensionSupported=v(this.renderer),t.replaceChildren(this.renderer.domElement),this.setupEventListeners(),this.depthRenderTarget=RenderingView.createDepthRenderTarget(this.renderer,this.container);const n=new h(this.scene,this.camera);if(this.composer.addPass(n),this.outlinePass=new C(new e.Vector2(t.clientWidth,t.clientHeight),this.scene,this.camera),!0===i.enableOutlines){this.outlinePass.edgeThickness=0,this.outlinePass.edgeGlow=0,this.outlinePass.edgeThickness=1.5,this.outlinePass.edgeStrength=5,this.outlinePass.clear=!1,this.composer.addPass(this.outlinePass);const e=new o(d);e.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(e);var l=new o(m);l.clear=!1,this.composer.addPass(l)}}setCamera(t){this.camera=t,this.composer.passes.forEach((e=>{e instanceof h?e.camera=t:e instanceof C?e.renderCamera=t:e instanceof y&&(e.camera=t)})),null==this.csm?this.csm=new l({maxFar:200,lightFar:300,cascades:5,shadowMapSize:2048,lightDirection:new e.Vector3(.5,-1,-.6).normalize(),lightIntensity:.5,camera:this.camera,parent:this.scene}):(this.csm.camera=this.camera,this.camera instanceof r&&(this.csm.maxFar=this.camera.far)),this.csm.updateFrustums()}setSelectedObjects(e){const t=new Map;for(const i of e)t.set(i.uuid,i);for(const i of e)i.traverse((e=>{e.uuid!==i.uuid&&t.has(e.uuid)&&t.delete(e.uuid)}));this.outlinePass.selectedObjects=Array.from(t.values())}static createDepthRenderTarget(t,i){var s=!!t.extensions.get("WEBGL_depth_texture");const r=new e.WebGLRenderTarget(i.clientWidth*t.getPixelRatio(),i.clientHeight*t.getPixelRatio());return r.texture.minFilter=e.NearestFilter,r.texture.magFilter=e.NearestFilter,r.texture.generateMipmaps=!1,r.stencilBuffer=!1,!0===s&&(r.depthTexture=new e.DepthTexture(128,128),r.depthTexture.type=e.UnsignedShortType,r.depthTexture.minFilter=e.NearestFilter,r.depthTexture.magFilter=e.NearestFilter),r}setupEventListeners(){window.addEventListener("resize",this.onResize),window.addEventListener("orientationchange",this.onResize),document.addEventListener("visibilitychange",this.onVisiblityChane)}stop(){this.running=!1,window.removeEventListener("resize",this.onResize),window.removeEventListener("orientationchange",this.onResize),document.removeEventListener("visibilitychange",this.onVisiblityChane),this.onLoopCallbacks=[],this.renderer.dispose(),this.depthRenderTarget.dispose(),this.csm.dispose(),this.container.replaceChildren()}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.find(e);this.onLoopCallbacks.splice(t,1)}set showStats(e){this._showStats=e,this._showStats&&!this.container.contains(this.stats.dom)?this.container.appendChild(this.stats.dom):!this._showStats&&this.container.contains(this.stats.dom)&&this.container.removeChild(this.stats.dom)}get showStats(){return this._showStats}loop(s,r=!1){const n=this.stats;n.showPanel(0),this.showStats=r;performance.now();e.Ray.prototype.intersectTriangle;let a=0;const h=new i,o=new i,d=e=>{var i,r;const l=this.renderer.getContext();if(this.paused&&this.running&&l.drawingBufferHeight>1)return void setTimeout((()=>d(e)),500);this.renderer.autoClear=!1,this.renderer.clear(),this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),this.camera,n.begin();let c=(e*=.001)-a;if(a=e,h.copy(this.camera.matrixWorld),c>1){let e=c;for(;e>.05;)s(S),e-=S;s(e)}else s(c);this.onLoopCallbacks.forEach((e=>e(c))),null===(i=this.camera)||void 0===i||i.updateMatrixWorld(),o.copy(this.camera.matrixWorld),o.equals(h)||(this.renderer.shadowMap.needsUpdate=!0),this.resizeRender();const m=[],g=[];if(this.scene.traverse((i=>{var s,r,n,a,h,o;i instanceof t&&i.visible&&((null===(r=null===(s=i.material)||void 0===s?void 0:s.userData)||void 0===r?void 0:r.water)||(null===(n=i.material)||void 0===n?void 0:n.uniforms)&&null!=(null===(a=i.material)||void 0===a?void 0:a.uniforms[u]))?(i.visible=!1,m.push(i),this.initDepthUniform(i.material),i.renderOrder=100):i instanceof p&&(i.visible=!1,g.push(i)),i instanceof t&&(null===(h=i.material)||void 0===h?void 0:h.uniforms)&&null!=(null===(o=i.material)||void 0===o?void 0:o.uniforms[x])&&(i.material.uniforms[x].value=e)})),m.length>0){if(this.scene.overrideMaterial=P,this.renderer.setRenderTarget(this.depthRenderTarget),!this.paused&&null!=this.camera)try{this.renderer.clear(),this.renderer.render(this.scene,this.camera)}catch(e){console.warn(e)}this.renderer.setRenderTarget(null),this.scene.overrideMaterial=null}m.forEach((e=>e.visible=!0)),g.forEach((e=>e.visible=!0));try{!this.paused&&this.running&&(this.composer.render(c),this.renderOverlay())}catch(e){console.warn(e)}n.end(),null===(r=this.csm)||void 0===r||r.update(),this.running&&(this.fpsCap?setTimeout((()=>{requestAnimationFrame(d)}),1e3/this.fpsCap):requestAnimationFrame(d))};requestAnimationFrame(d)}renderOverlay(){const e=Array.from(this.overlayCameras.values()).slice(0,this.maxInsetCameras),t=this.container.clientWidth/2,i=e.length*this.insetWidth+(e.length-1)*this.insetMargin;for(let s=0;s<e.length;s++)this.renderer.clearDepth(),this.renderer.setViewport(t-i/2+this.insetWidth*s+this.insetMargin*s,this.insetOffsetY,this.insetWidth,this.insetHeight),this.renderer.render(this.scene,e[s])}addOverlayCamera(e){this.overlayCameras.add(e)}clearOverlayCameras(){this.overlayCameras.clear()}removeOverlayCamera(e){this.overlayCameras.delete(e)}render(){this.composer.render()}initDepthUniform(e){e instanceof s&&(e.uniforms[u].value=this.isDepthTextureExtensionSupported?this.depthRenderTarget.depthTexture:this.depthRenderTarget.texture,null!=e.uniforms[g]&&e.uniforms[g].value.set(this.container.clientWidth*this.renderer.getPixelRatio(),this.container.clientHeight*this.renderer.getPixelRatio()),this.camera instanceof r&&(e.uniforms[f].value=this.camera.near,e.uniforms[w].value=this.camera.far))}}export function setRenderingPaused(e){var t,i;null!=(null===(i=null===(t=window.editor)||void 0===t?void 0:t.viewer)||void 0===i?void 0:i.renderingView)&&(window.editor.viewer.renderingView.paused=e)}const S=.05;
|
2
2
|
/*
|
3
3
|
* Copyright (©) 2023. All rights reserved.
|
4
4
|
* See the LICENSE.md file for details.
|
@@ -8,8 +8,10 @@ export declare class AssetResourceLoader {
|
|
8
8
|
private loadingManager;
|
9
9
|
private glbLoader;
|
10
10
|
private fbxLoader;
|
11
|
+
private objLoader;
|
11
12
|
private textureLoader;
|
12
13
|
private audioLoader;
|
14
|
+
protected onError(error: unknown): void;
|
13
15
|
private makeReady;
|
14
16
|
private ready;
|
15
17
|
constructor();
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{__awaiter as e}from"tslib";import{AudioLoader as t,Group as i,LoadingManager as s,TextureLoader as
|
1
|
+
import{__awaiter as e}from"tslib";import{AudioLoader as t,Group as i,LoadingManager as s,Mesh as o,TextureLoader as r}from"three";import{GLTFLoader as n,MTLLoader as a,OBJLoader as h}from"three-stdlib";import{FBXLoader as l}from"three-stdlib";import{cloneMesh as c}from"../utils/mesh";import{pathJoin as d}from"../utils/files";import{Subject as u,firstValueFrom as f}from"rxjs";import{importCollisionShapes as p}from"./collision/collision-shape-import";import*as g from"three";import{iterateMaterials as m}from"../utils/materials";const y=["glb","gltf","fbx","obj"];export class AssetResourceLoader{onError(e){console.error(e)}constructor(){this.cache=new Map,this.textureCache=new Map,this.loadingManager=new s,this.glbLoader=new n(this.loadingManager),this.fbxLoader=new l(this.loadingManager),this.objLoader=new h(this.loadingManager),this.textureLoader=new r(this.loadingManager),this.audioLoader=new t(this.loadingManager),this.makeReady=new u,this.ready=f(this.makeReady),this.collisionShapeCache=new Map}setDataDir(e){this.basePath=d(e,"asset-resources"),this.makeReady.next(!0)}getUri(e){return d(this.basePath,e)+`?windowId=${getElectronArg("windowId")}`}getTexture(t){return e(this,void 0,void 0,(function*(){return null==t?null:(yield this.ready,this.cache.has(t.id)||(yield this.textureLoader.loadAsync(this.getUri(t.fileKey)).then((e=>(e.wrapS=g.RepeatWrapping,e.wrapT=g.RepeatWrapping,e.flipY=!1,this.textureCache.set(t.id,e),e)))),this.textureCache.get(t.id))}))}getMesh(t){var s;return e(this,void 0,void 0,(function*(){if(yield this.ready,!y.includes(null===(s=t.fileFormat)||void 0===s?void 0:s.toLowerCase()))return console.error("Unsupported mesh file format "+t.fileFormat,t),{scene:new i};if(!this.cache.has(t.fileKey))try{yield this.loadMesh(t)}catch(e){return this.onError(e),{scene:new i}}const{scene:e}=this.cache.get(t.fileKey),o=this.computeCollisionShapes(t,e),r=(new AssetMeshInstance).copy(c(e));return r.collisionShapes=o,{scene:r}}))}getAudio(t){return e(this,void 0,void 0,(function*(){return yield this.ready,this.audioLoader.loadAsync(this.getUri(t.fileKey))}))}computeCollisionShapes(e,t){return this.collisionShapeCache.get(e.id)||this.collisionShapeCache.set(e.id,p(t)),this.collisionShapeCache.get(e.id)}loadMesh(t){return e(this,void 0,void 0,(function*(){return yield this.ready,yield this.loadByAsset(t).then((e=>(e.scene.animations=[],this.cache.set(t.fileKey,e),e)))}))}loadByAsset(t){return e(this,void 0,void 0,(function*(){const e=this.getUri(t.fileKey);switch(t.fileFormat){case"glb":case"gltf":return this.glbLoader.loadAsync(e).then((e=>({scene:e.scene})));case"fbx":return this.fbxLoader.loadAsync(e).then((e=>({scene:e})));case"obj":if(null!=t.materialLib){const e=new a;e.materialOptions={normalizeRGB:!1};const i=yield e.loadAsync(this.getUri(t.materialLib));this.objLoader.setMaterials(i)}return this.objLoader.loadAsync(e).then((e=>(w(e),e))).then((e=>({scene:e})))}}))}}function w(e){var t;if(e instanceof o)for(const t of m(e.material))t instanceof g.MeshPhongMaterial&&!t.color.isLinear&&(t.color.isLinear=!0,t.color.convertSRGBToLinear());null===(t=e.children)||void 0===t||t.forEach(w)}export class AssetMeshInstance extends i{}export function getElectronArg(e){var t;const i=`--${e}=`,s=null===(t=window.process)||void 0===t?void 0:t.argv.find((e=>e.startsWith(i)));return null==s?void 0:s.substring(i.length)}
|
2
2
|
/*
|
3
3
|
* Copyright (©) 2023. All rights reserved.
|
4
4
|
* See the LICENSE.md file for details.
|
@@ -1,4 +1,5 @@
|
|
1
1
|
import { Subject } from "rxjs";
|
2
|
+
import * as THREE from "three";
|
2
3
|
import { Euler, Material, Object3D, Scene, Vector3 } from "three";
|
3
4
|
import { GameComponent } from "../game-component/game-component";
|
4
5
|
import { RenderingView } from "../rendering";
|
@@ -207,7 +208,7 @@ export declare class SceneMaterializer {
|
|
207
208
|
updateActors(actors: ActorImpl[]): void;
|
208
209
|
updateShaders(shaders: ShaderImpl[]): void;
|
209
210
|
private update;
|
210
|
-
|
211
|
+
materializeAndInitActor(source: SceneObject, parent?: THREE.Object3D<THREE.Event>): Promise<THREE.Object3D<THREE.Event>>;
|
211
212
|
private findParent;
|
212
213
|
private fixFogColor;
|
213
214
|
private findMeshWithGeometry;
|