import { BlinnPhongMaterial, Camera, CameraClearFlags, Color, DirectLight, Engine, Entity, Layer, MeshRenderer, PrimitiveMesh, WebGLEngine } from "oasis-engine"; import { PaladinAdapter } from "./adapter/PaladinAdapter"; import { ARBackground } from "./ar/ARBackground"; import { ARMode } from "./ar/AREnum"; import { ARManager } from "./ar/ARManager"; import { ARFeature } from "./ar/ARFeature"; import { BoxControl } from "./control/BoxControl"; import { ARBackgroundControl } from "./control/ARBackgroundControl"; export enum CameraRenderOrder { ARBackground = 1, Scene = 2 } export enum GameState { // 未初始化 NotInit = 0, // 初始化引擎 InitEngine, // 初始化 AR InitAR, // 初始化 场景 InitScene, // 开始 Start } export class GameCtrl { // 单例 static _ins: GameCtrl; // 引擎 private _engine: WebGLEngine; // 当前的根节点 private _root: Entity; // 当前的状态 private _state: GameState = GameState.NotInit; /** * 获取单例 */ static get ins(): GameCtrl { if (!this._ins) { this._ins = new GameCtrl(); } return this._ins; } /** * 跳转到某个状态 * @param state - 状态 * @param arg - 携带参数 */ public jump(state: GameState, ...arg) { console.log("jump", state); if (this._state !== state) { switch (state) { case GameState.InitEngine: this.initEngine(); this.jump(GameState.InitAR); break; case GameState.InitAR: this.initAR(); break; case GameState.InitScene: this.initScene(); this.jump(GameState.Start); break; case GameState.Start: // 开始游戏 break; } } } /** * 初始化引擎 */ public initEngine(): void { const canvas = PaladinAdapter.canvas; const engine = (this._engine = new WebGLEngine(canvas)); // 初始化根节点 this._root = engine.sceneManager.activeScene.createRootEntity(); // 初始化相机 engine.run(); } /** * 初始化 AR */ public initAR(): void { const canvas = this._engine.canvas; // 初始化 AR ARManager.ins.create( this._engine, { mode: ARMode.Camera, pixelWidth: canvas.width, pixelHeight: canvas.height, near: 0.01, far: 500 }, () => { ARManager.ins.start(() => { Engine.registerFeature(ARFeature); this._root.createChild("bg").addComponent(ARBackgroundControl); this.jump(GameState.InitScene); }); } ); } /** * 初始化场景 */ public initScene(): void { const { _root: root, _engine: engine } = this; // 初始化虚拟相机 const cameraEntity = root.createChild("Camera"); const camera = cameraEntity.addComponent(Camera); camera.cullingMask = Layer.Layer0; camera.priority = CameraRenderOrder.Scene; camera.clearFlags = CameraClearFlags.Depth; // 添加方向光 const lightEntity = root.createChild("light"); lightEntity.addComponent(DirectLight); lightEntity.transform.setPosition(5, 5, 5); lightEntity.transform.setRotation(-30, 20, 0); // 添加 box const boxEntity = root.createChild("Box"); boxEntity.transform.setPosition(0, 0, -10); const boxRenderer = boxEntity.addComponent(MeshRenderer); boxRenderer.mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); const boxMaterial = new BlinnPhongMaterial(engine); boxMaterial.baseColor = new Color(0.3, 0.3, 0.3, 1); boxRenderer.setMaterial(boxMaterial); boxEntity.addComponent(BoxControl); } }