diff --git a/.vscode/cSpell.json b/.vscode/cSpell.json index 43327368fb..0c81138520 100644 --- a/.vscode/cSpell.json +++ b/.vscode/cSpell.json @@ -15,6 +15,7 @@ "deserialization", "deserialize", "deserializes", + "Dpad", "earcut", "emscripten", "endregion", diff --git a/@types/globals.d.ts b/@types/globals.d.ts index d82abda768..1dcbffbf00 100644 --- a/@types/globals.d.ts +++ b/@types/globals.d.ts @@ -26,6 +26,7 @@ declare const gfx: any; declare const global: any; +declare const xr: any; interface Window { diff --git a/@types/jsb.d.ts b/@types/jsb.d.ts index f8c0a5a4f5..d63002634a 100644 --- a/@types/jsb.d.ts +++ b/@types/jsb.d.ts @@ -71,6 +71,40 @@ declare namespace jsb { export let onTouchEnd: TouchEventCallback | undefined; export let onTouchCancel: TouchEventCallback | undefined; + export interface ControllerInfo { + id: number; + axisInfoList: AxisInfo[], + buttonInfoList: ButtonInfo[], + } + + export interface AxisInfo { + code: number, + value: number, + } + + export interface ButtonInfo { + code: number, + isPressed: boolean, + } + + export let onControllerInput: (infoList: ControllerInfo[]) => void | undefined; + export let onHandleInput: (infoList: ControllerInfo[]) => void | undefined; + export let onControllerChange: (controllerIds: number[]) => void | undefined; + + export interface PoseInfo { + code: number, + x: number, + y: number, + z: number, + quaternionX: number, + quaternionY: number, + quaternionZ: number, + quaternionW: number, + } + + export let onHandlePoseInput: (infoList: PoseInfo[]) => void | undefined; + export let onHMDPoseInput: (infoList: PoseInfo[]) => void | undefined; + export interface KeyboardEvent { altKey: boolean; ctrlKey: boolean; diff --git a/@types/pal/input.d.ts b/@types/pal/input.d.ts index b834576d77..08b0b644c1 100644 --- a/@types/pal/input.d.ts +++ b/@types/pal/input.d.ts @@ -1,4 +1,10 @@ declare module 'pal/input' { + type InputSourceButton = import('pal/input/input-source').InputSourceButton; + type InputSourceStick = import('pal/input/input-source').InputSourceStick; + type InputSourceDpad = import('pal/input/input-source').InputSourceDpad; + type InputSourcePosition = import('pal/input/input-source').InputSourcePosition; + type InputSourceOrientation = import('pal/input/input-source').InputSourceOrientation; + type TouchCallback = (res: import('cocos/input/types').EventTouch) => void; /** * Class designed for touch input. @@ -40,11 +46,119 @@ declare module 'pal/input' { public dispatchKeyboardUpEvent? (nativeKeyboardEvent: any); } + type GamepadCallback = (res: import('cocos/input/types/event').EventGamepad) => void; + /** * Class designed for gamepad input */ - export class GamepadInputSource { - // TODO: add more details for GamepadInputSource class + export class GamepadInputDevice { + /** + * @engineInternal + */ + public static _init (); + /** + * @engineInternal + */ + public static _on (eventType: import('cocos/input/types/event-enum').InputEventType, cb: GamepadCallback, target?: any); + + public static all: GamepadInputDevice[]; + /** + * @en The gamepad device id + * @zh 手柄设备 id + */ + public get deviceId (): number; + /** + * @en whether the gamepad is connected + * @zh 手柄是否处于连接状态 + */ + public get connected (): boolean; + /** + * @en The control button in the north direction which is generally the button Y + * @zh 处于北向的控制按键,一般是按键 Y + */ + public get buttonNorth (): InputSourceButton; + /** + * @en The control button in the east direction which is generally the button B + * @zh 处于东向的控制按键,一般是按键 B + */ + public get buttonEast (): InputSourceButton; + /** + * @en The control button in the west direction which is generally the button X + * @zh 处于西向的控制按键,一般是按键 X + */ + public get buttonWest (): InputSourceButton; + /** + * @en The control button in the south direction which is generally the button A + * @zh 处于南向的控制按键,一般是按键 A + */ + public get buttonSouth (): InputSourceButton; + + /** + * @en The button L1 + * @zh 按键 L1 + */ + public get buttonL1 (): InputSourceButton; + /** + * @en The button L2 + * @zh 按键 L2 + */ + public get buttonL2 (): InputSourceButton; + /** + * @en The button L3 + * @zh 按键 L3 + */ + public get buttonL3 (): InputSourceButton; + /** + * @en The button R1 + * @zh 按键 R1 + */ + public get buttonR1 (): InputSourceButton; + /** + * @en The button R2 + * @zh 按键 R2 + */ + public get buttonR2 (): InputSourceButton; + /** + * @en The button R3 + * @zh 按键 R3 + */ + public get buttonR3 (): InputSourceButton; + + // public get buttonTouchPad (): InputSourceButton; + // public get buttonHome (): InputSourceButton; + + /** + * @en The button Share + * @zh 分享按键 + */ + public get buttonShare (): InputSourceButton; + /** + * @en The button Options + * @zh 选项按键 + */ + public get buttonOptions (): InputSourceButton; + + /** + * @en The dpad buttons + * @zh 方向按键 + */ + public get dpad (): InputSourceDpad; + /** + * @en The left stick + * @zh 左摇杆 + */ + public get leftStick (): InputSourceStick; + /** + * @en The right stick + * @zh 右摇杆 + */ + public get rightStick (): InputSourceStick; + + /** + * @en The button Start + * @zh 开始按键 + */ + public get buttonStart (): InputSourceButton; } type AccelerometerCallback = (res: import('cocos/input/types').EventAcceleration) => void; @@ -73,4 +187,175 @@ declare module 'pal/input' { */ public on (eventType: import('cocos/input/types/event-enum').InputEventType, callback: AccelerometerCallback, target?: any); } + + type HandleCallback = (res: import('cocos/input/types').EventHandle) => void; + /** + * Class designed for handle input. + */ + export class HandleInputDevice { + /** + * Register the handle event callback. + * @engineInternal + */ + public _on (eventType: import('cocos/input/types/event-enum').InputEventType, callback: HandleCallback, target?: any); + + /** + * @en The control button in the north direction which is generally the button Y + * @zh 处于北向的控制按键,一般是按键 Y + */ + public get buttonNorth (): InputSourceButton; + /** + * @en The control button in the east direction which is generally the button B + * @zh 处于东向的控制按键,一般是按键 B + */ + public get buttonEast (): InputSourceButton; + /** + * @en The control button in the west direction which is generally the button X + * @zh 处于西向的控制按键,一般是按键 X + */ + public get buttonWest (): InputSourceButton; + /** + * @en The control button in the south direction which is generally the button A + * @zh 处于南向的控制按键,一般是按键 A + */ + public get buttonSouth (): InputSourceButton; + + /** + * @en The button Left Trigger + * @zh 左扳机按键 + */ + public get buttonTriggerLeft (): InputSourceButton; + /** + * @en The button Right Trigger + * @zh 右扳机按键 + */ + public get buttonTriggerRight (): InputSourceButton; + /** + * @en The grab Left Trigger + * @zh 左扳机扣动 + */ + public get triggerLeft (): InputSourceButton; + /** + * @en The grab Right Trigger + * @zh 右扳机扣动 + */ + public get triggerRight (): InputSourceButton; + /** + * @en The grab Left Grip + * @zh 左手柄握住 + */ + public get gripLeft (): InputSourceButton; + /** + * @en The grab Right Grip + * @zh 右手柄握住 + */ + public get gripRight (): InputSourceButton; + + /** + * @en The left stick + * @zh 左摇杆 + */ + public get leftStick (): InputSourceStick; + /** + * @en The right stick + * @zh 右摇杆 + */ + public get rightStick (): InputSourceStick; + + /** + * @en The button Left Stick + * @zh 左摇杆按键 + */ + public get buttonLeftStick (): InputSourceButton; + /** + * @en The button Right Stick + * @zh 右摇杆按键 + */ + public get buttonRightStick (): InputSourceButton; + + /** + * @en The position Left hand + * @zh 左手位置 + */ + public get handLeftPosition (): InputSourcePosition; + /** + * @en The orientation Left hand + * @zh 左手方向 + */ + public get handLeftOrientation (): InputSourceOrientation; + /** + * @en The position Right hand + * @zh 右手位置 + */ + public get handRightPosition (): InputSourcePosition; + /** + * @en The orientation Right hand + * @zh 右手方向 + */ + public get handRightOrientation (): InputSourceOrientation; + + /** + * @en The position Left aim + * @zh 左射线位置 + */ + public get aimLeftPosition (): InputSourcePosition; + /** + * @en The orientation Left aim + * @zh 左射线方向 + */ + public get aimLeftOrientation (): InputSourceOrientation; + /** + * @en The position Right aim + * @zh 右射线位置 + */ + public get aimRightPosition (): InputSourcePosition; + /** + * @en The orientation Right aim + * @zh 右射线方向 + */ + public get aimRightOrientation (): InputSourceOrientation; + } + + type HMDCallback = (res: import('cocos/input/types').EventHMD) => void; + /** + * Class designed for HMD input. + */ + export class HMDInputDevice { + /** + * Register the hmd event callback. + * @engineInternal + */ + public _on (eventType: import('cocos/input/types/event-enum').InputEventType, callback: HMDCallback, target?: any); + + /** + * @en The position Left view + * @zh 左窗口位置 + */ + public get viewLeftPosition (): InputSourcePosition; + /** + * @en The orientation Left view + * @zh 左窗口方向 + */ + public get viewLeftOrientation (): InputSourceOrientation; + /** + * @en The position Right view + * @zh 右窗口位置 + */ + public get viewRightPosition (): InputSourcePosition; + /** + * @en The orientation Right view + * @zh 右窗口方向 + */ + public get viewRightOrientation (): InputSourceOrientation; + /** + * @en The position Middle head + * @zh 头部中间位置 + */ + public get headMiddlePosition (): InputSourcePosition; + /** + * @en The orientation Middle head + * @zh 头部中间方向 + */ + public get headMiddleOrientation (): InputSourceOrientation; + } } diff --git a/@types/pal/system-info.d.ts b/@types/pal/system-info.d.ts index 8c0f5bb993..9cf22ccffa 100644 --- a/@types/pal/system-info.d.ts +++ b/@types/pal/system-info.d.ts @@ -39,6 +39,7 @@ declare module 'pal/system-info' { public get osMainVersion (): number; public get browserType (): BrowserType; public get browserVersion (): string; + public get isXR (): boolean; public hasFeature (feature: Feature): boolean; public getBatteryLevel (): number; diff --git a/cc.config.json b/cc.config.json index 5deee558bc..655b52c6b9 100644 --- a/cc.config.json +++ b/cc.config.json @@ -93,6 +93,7 @@ }, "audio": { "modules": [ "audio" ] }, "video": { "modules": [ "video" ] }, + "xr": { "modules": [ "xr" ] }, "terrain": { "modules": [ "terrain" ], "dependentAssets": [ "1d08ef62-a503-4ce2-8b9a-46c90873f7d3" ] diff --git a/cocos/2d/assembler/label/ttfUtils.ts b/cocos/2d/assembler/label/ttfUtils.ts index 816d2e064a..f30abef07d 100644 --- a/cocos/2d/assembler/label/ttfUtils.ts +++ b/cocos/2d/assembler/label/ttfUtils.ts @@ -120,6 +120,7 @@ export const ttfUtils = { this.updateUVs(comp); // Empty comp.renderData.vertDirty = false; // comp.markForUpdateRenderData(false); + comp.contentWidth = _nodeContentSize.width; _context = null; _canvas = null; diff --git a/cocos/2d/components/label.ts b/cocos/2d/components/label.ts index be921e0786..5f39f36bd1 100644 --- a/cocos/2d/components/label.ts +++ b/cocos/2d/components/label.ts @@ -676,6 +676,22 @@ export class Label extends UIRenderer { protected _fontAtlas: FontAtlas | null = null; protected _letterTexture: LetterRenderTexture | null = null; + protected _contentWidth = 0; + + /** + * @engineInternal + */ + get contentWidth () { + return this._contentWidth; + } + + /** + * @engineInternal + */ + set contentWidth (val) { + this._contentWidth = val; + } + constructor () { super(); if (EDITOR) { diff --git a/cocos/2d/renderer/render-entity.ts b/cocos/2d/renderer/render-entity.ts index e303b4eb7a..d9dde93670 100644 --- a/cocos/2d/renderer/render-entity.ts +++ b/cocos/2d/renderer/render-entity.ts @@ -108,7 +108,7 @@ export class RenderEntity { } } - protected _enabled = true; + protected _enabled = false; get enabled () { return this._enabled; } diff --git a/cocos/core/components/camera-component.ts b/cocos/core/components/camera-component.ts index 3e1faa6599..68f4a49487 100644 --- a/cocos/core/components/camera-component.ts +++ b/cocos/core/components/camera-component.ts @@ -32,11 +32,12 @@ import { Ray } from '../geometry'; import { Color, Rect, toRadian, Vec3 } from '../math'; import { CAMERA_DEFAULT_MASK } from '../pipeline/define'; import { scene } from '../renderer'; -import { SKYBOX_FLAG, CameraProjection, CameraFOVAxis, CameraAperture, CameraISO, CameraShutter } from '../renderer/scene/camera'; +import { SKYBOX_FLAG, CameraProjection, CameraFOVAxis, CameraAperture, CameraISO, CameraShutter, + CameraType, TrackingType } from '../renderer/scene/camera'; import { Root } from '../root'; import { Node } from '../scene-graph/node'; import { Layers } from '../scene-graph/layers'; -import { Enum } from '../value-types'; +import { ccenum, Enum } from '../value-types'; import { TransformBit } from '../scene-graph/node-enum'; import { legacyCC } from '../global-exports'; import { RenderWindow } from '../renderer/core/render-window'; @@ -155,6 +156,10 @@ export class Camera extends Component { protected _camera: scene.Camera | null = null; protected _inEditorMode = false; protected _flows: string[] | undefined = undefined; + @serializable + protected _cameraType: CameraType = CameraType.DEFAULT; + @serializable + protected _trackingType: TrackingType = TrackingType.NO_TRACKING; /** * @en The render camera representation. @@ -488,8 +493,36 @@ export class Camera extends Component { } } + get cameraType () { + return this._cameraType; + } + + set cameraType (val) { + if (this._cameraType === val) { + return; + } + this._cameraType = val; + if (this.camera) { + this.camera.cameraType = val; + } + } + + get trackingType () { + return this._trackingType; + } + + set trackingType (val) { + if (this._trackingType === val) { + return; + } + this._trackingType = val; + if (this.camera) { + this.camera.trackingType = val; + } + } + public onLoad () { - this._createCamera(); + this._createCamera(); } public onEnable () { @@ -604,6 +637,8 @@ export class Camera extends Component { window: this._inEditorMode ? legacyCC.director.root && legacyCC.director.root.mainWindow : legacyCC.director.root && legacyCC.director.root.tempWindow, priority: this._priority, + cameraType: this.cameraType, + trackingType: this.trackingType, }); this._camera.setViewportInOrientedSpace(this._rect); diff --git a/cocos/core/game.ts b/cocos/core/game.ts index 908518a7fd..5a1fba10fd 100644 --- a/cocos/core/game.ts +++ b/cocos/core/game.ts @@ -686,6 +686,17 @@ export class Game extends EventTarget { if (DEBUG) { console.timeEnd('Init Base'); } + + if (sys.isXR) { + // XrEntry must not be destroyed + xr.entry = xr.XrEntry.getInstance(); + + const xrMSAA = settings.querySettings(Settings.Category.RENDERING, 'msaa') ?? 1; + const xrRenderingScale = settings.querySettings(Settings.Category.RENDERING, 'renderingScale') ?? 1.0; + xr.entry.setMultisamplesRTT(xrMSAA); + xr.entry.setRenderingScale(xrRenderingScale); + } + this.emit(Game.EVENT_POST_BASE_INIT); return this.onPostBaseInitDelegate.dispatch(); }) diff --git a/cocos/core/gfx/base/device.ts b/cocos/core/gfx/base/device.ts index 4374963815..83fe68140c 100644 --- a/cocos/core/gfx/base/device.ts +++ b/cocos/core/gfx/base/device.ts @@ -281,6 +281,12 @@ export abstract class Device { */ public abstract getSampler (info: Readonly): Sampler; + /** + * @en Get swapchains. + * @zh 获取交换链列表。 + */ + public abstract getSwapchains (): Readonly; + /** * @en Create global barrier. * @zh 创建全局内存屏障。 diff --git a/cocos/core/gfx/empty/empty-device.ts b/cocos/core/gfx/empty/empty-device.ts index f1b799e6e5..55187b4a36 100644 --- a/cocos/core/gfx/empty/empty-device.ts +++ b/cocos/core/gfx/empty/empty-device.ts @@ -64,6 +64,8 @@ import { EmptyTexture } from './empty-texture'; import { legacyCC } from '../../global-exports'; export class EmptyDevice extends Device { + private _swapchain: EmptySwapchain | null = null; + public initialize (info: DeviceInfo): boolean { this._gfxAPI = API.UNKNOWN; @@ -87,6 +89,8 @@ export class EmptyDevice extends Device { this._cmdBuff.destroy(); this._cmdBuff = null; } + + this._swapchain = null; } public flushCommands (cmdBuffs: Readonly) {} @@ -101,6 +105,7 @@ export class EmptyDevice extends Device { public createSwapchain (info: Readonly): Swapchain { const swapchain = new EmptySwapchain(); + this._swapchain = swapchain; swapchain.initialize(info); return swapchain; } @@ -179,6 +184,10 @@ export class EmptyDevice extends Device { return this._samplers.get(hash)!; } + public getSwapchains (): Readonly { + return [this._swapchain as Swapchain]; + } + public getGeneralBarrier (info: Readonly) { const hash = GeneralBarrier.computeHash(info); if (!this._generalBarrierss.has(hash)) { diff --git a/cocos/core/gfx/webgl/webgl-device.ts b/cocos/core/gfx/webgl/webgl-device.ts index 4a27a6c226..f0af2063ae 100644 --- a/cocos/core/gfx/webgl/webgl-device.ts +++ b/cocos/core/gfx/webgl/webgl-device.ts @@ -235,6 +235,8 @@ export class WebGLDevice extends Device { this._cmdBuff.destroy(); this._cmdBuff = null; } + + this._swapchain = null; } public flushCommands (cmdBuffs: CommandBuffer[]) {} @@ -499,6 +501,10 @@ export class WebGLDevice extends Device { return this._samplers.get(hash)!; } + public getSwapchains (): Readonly { + return [this._swapchain as Swapchain]; + } + public getGeneralBarrier (info: Readonly) { const hash = GeneralBarrier.computeHash(info); if (!this._generalBarrierss.has(hash)) { diff --git a/cocos/core/gfx/webgl2/webgl2-device.ts b/cocos/core/gfx/webgl2/webgl2-device.ts index 77c84fddeb..45b31d1798 100644 --- a/cocos/core/gfx/webgl2/webgl2-device.ts +++ b/cocos/core/gfx/webgl2/webgl2-device.ts @@ -553,6 +553,10 @@ export class WebGL2Device extends Device { return this._samplers.get(hash)!; } + public getSwapchains (): Readonly { + return [this._swapchain as Swapchain]; + } + public getGeneralBarrier (info: Readonly) { const hash = GeneralBarrier.computeHash(info); if (!this._generalBarrierss.has(hash)) { diff --git a/cocos/core/pipeline/forward/forward-stage.ts b/cocos/core/pipeline/forward/forward-stage.ts index e5ca638eee..1b17166952 100644 --- a/cocos/core/pipeline/forward/forward-stage.ts +++ b/cocos/core/pipeline/forward/forward-stage.ts @@ -83,6 +83,8 @@ export class ForwardStage extends RenderStage { private declare _planarQueue: PlanarShadowQueue; private declare _uiPhase: UIPhase; + additiveInstanceQueues: RenderInstancedQueue[] = []; + constructor () { super(); this._batchedQueue = new RenderBatchedQueue(); @@ -154,6 +156,10 @@ export class ForwardStage extends RenderStage { const cmdBuff = pipeline.commandBuffers[0]; pipeline.pipelineUBO.updateShadowUBO(camera); + for (let i = 0; i < this.additiveInstanceQueues.length; i++) { + this.additiveInstanceQueues[i].uploadBuffers(cmdBuff); + } + this._instancedQueue.uploadBuffers(cmdBuff); this._batchedQueue.uploadBuffers(cmdBuff); this._additiveLightQueue.gatherLightPasses(camera, cmdBuff); @@ -173,6 +179,11 @@ export class ForwardStage extends RenderStage { colors, camera.clearDepth, camera.clearStencil); cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet); this._renderQueues[0].recordCommandBuffer(device, renderPass, cmdBuff); + + for (let i = 0; i < this.additiveInstanceQueues.length; i++) { + this.additiveInstanceQueues[i].recordCommandBuffer(device, renderPass, cmdBuff); + } + this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff); this._batchedQueue.recordCommandBuffer(device, renderPass, cmdBuff); diff --git a/cocos/core/pipeline/global-descriptor-set-manager.ts b/cocos/core/pipeline/global-descriptor-set-manager.ts index 2f329b6f64..575cd1b92f 100644 --- a/cocos/core/pipeline/global-descriptor-set-manager.ts +++ b/cocos/core/pipeline/global-descriptor-set-manager.ts @@ -88,6 +88,13 @@ export class GlobalDSManager { this._globalDescriptorSet = this._device.createDescriptorSet(new DescriptorSetInfo(this._descriptorSetLayout)); } + regenLayout () { + const layoutInfo = new DescriptorSetLayoutInfo(globalDescriptorSetLayout.bindings); + this._descriptorSetLayout = this._device.createDescriptorSetLayout(layoutInfo); + + this._globalDescriptorSet = this._device.createDescriptorSet(new DescriptorSetInfo(this._descriptorSetLayout)); + } + /** * @en Bind buffer for all descriptorSets, so that all created descriptorSet buffer are consistent * @zh 为所有的 descriptorSet 绑定 buffer,使得所有已创建的 descriptorSet buffer 保持一致 diff --git a/cocos/core/pipeline/pipeline-ubo.ts b/cocos/core/pipeline/pipeline-ubo.ts index 1a84ab35cb..ceefa4bf45 100644 --- a/cocos/core/pipeline/pipeline-ubo.ts +++ b/cocos/core/pipeline/pipeline-ubo.ts @@ -27,7 +27,7 @@ import { UBOGlobal, UBOShadow, UBOCamera, UNIFORM_SHADOWMAP_BINDING, supportsR32FloatTexture, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, UBOCSM } from './define'; import { Device, BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet } from '../gfx'; import { Camera } from '../renderer/scene/camera'; -import { Mat4, Vec3, Vec4, Color } from '../math'; +import { Mat4, Vec3, Vec4, Color, toRadian } from '../math'; import { PipelineRuntime } from './custom/pipeline'; import { legacyCC } from '../global-exports'; import { CSMLevel, PCFType, Shadows, ShadowType } from '../renderer/scene/shadows'; @@ -161,6 +161,8 @@ export class PipelineUBO { cv[UBOCamera.CAMERA_POS_OFFSET + 3] = this.getCombineSignY(); cv[UBOCamera.SURFACE_TRANSFORM_OFFSET] = camera.surfaceTransform; + cv[UBOCamera.SURFACE_TRANSFORM_OFFSET + 2] = Math.cos(toRadian(sceneData.skybox.getRotationAngle())); + cv[UBOCamera.SURFACE_TRANSFORM_OFFSET + 3] = Math.sin(toRadian(sceneData.skybox.getRotationAngle())); const colorTempRGB = fog.colorArray; cv[UBOCamera.GLOBAL_FOG_COLOR_OFFSET] = colorTempRGB.x; diff --git a/cocos/core/platform/sys.ts b/cocos/core/platform/sys.ts index 28cd500bf4..fcd7c3492d 100644 --- a/cocos/core/platform/sys.ts +++ b/cocos/core/platform/sys.ts @@ -180,6 +180,12 @@ export const sys = { */ browserVersion: systemInfo.browserVersion, + /** + * @en Whether the running platform is xr app + * @zh 指示运行平台是否是XR平台 + */ + isXR: systemInfo.isXR, + /** * @en Indicate the real pixel resolution of the whole game window * @zh 指示游戏窗口的像素分辨率 diff --git a/cocos/core/renderer/scene/camera.jsb.ts b/cocos/core/renderer/scene/camera.jsb.ts index b3374451f1..7b40f8edcf 100644 --- a/cocos/core/renderer/scene/camera.jsb.ts +++ b/cocos/core/renderer/scene/camera.jsb.ts @@ -89,6 +89,20 @@ export enum CameraShutter { D4000, } +export enum CameraType { + DEFAULT = -1, + LEFT_EYE = 0, + RIGHT_EYE = 1, + MAIN = 2, +} + +export enum TrackingType { + NO_TRACKING = 0, + POSITION_AND_ROTATION = 1, + POSITION = 2, + ROTATION = 3, +} + export interface ICameraInfo { name: string; node: Node; @@ -97,6 +111,8 @@ export interface ICameraInfo { window?: RenderWindow | null; priority: number; pipeline?: string; + cameraType?: CameraType; + trackingType?: TrackingType; } export const SKYBOX_FLAG = ClearFlagBit.STENCIL << 1; diff --git a/cocos/core/renderer/scene/camera.ts b/cocos/core/renderer/scene/camera.ts index c8c41c3197..129eaeda34 100644 --- a/cocos/core/renderer/scene/camera.ts +++ b/cocos/core/renderer/scene/camera.ts @@ -94,6 +94,20 @@ export enum CameraShutter { D4000, } +export enum CameraType { + DEFAULT = -1, + LEFT_EYE = 0, + RIGHT_EYE = 1, + MAIN = 2, +} + +export enum TrackingType { + NO_TRACKING = 0, + POSITION_AND_ROTATION = 1, + POSITION = 2, + ROTATION = 3, +} + const FSTOPS: number[] = [1.8, 2.0, 2.2, 2.5, 2.8, 3.2, 3.5, 4.0, 4.5, 5.0, 5.6, 6.3, 7.1, 8.0, 9.0, 10.0, 11.0, 13.0, 14.0, 16.0, 18.0, 20.0, 22.0]; const SHUTTERS: number[] = [1.0, 1.0 / 2.0, 1.0 / 4.0, 1.0 / 8.0, 1.0 / 15.0, 1.0 / 30.0, 1.0 / 60.0, 1.0 / 125.0, 1.0 / 250.0, 1.0 / 500.0, 1.0 / 1000.0, 1.0 / 2000.0, 1.0 / 4000.0]; @@ -107,6 +121,8 @@ export interface ICameraInfo { window?: RenderWindow | null; priority: number; pipeline?: string; + cameraType?: CameraType; + trackingType?: TrackingType; } const v_a = new Vec3(); @@ -563,6 +579,8 @@ export class Camera { private _exposure = 0; private _clearStencil = 0; private _geometryRenderer: GeometryRenderer | null = null; + private _cameraType: CameraType = CameraType.DEFAULT; + private _trackingType: TrackingType = TrackingType.NO_TRACKING; constructor (device: Device) { this._device = device; @@ -598,6 +616,12 @@ export class Camera { * @zh 初始化相机,开发者通常不应该使用这个方法,初始化流程是自动管理的。 */ public initialize (info: ICameraInfo) { + if (info.trackingType !== undefined) { + this._trackingType = info.trackingType; + } + if (info.cameraType !== undefined) { + this._cameraType = info.cameraType; + } this.node = info.node; this._width = 1; this._height = 1; @@ -795,7 +819,7 @@ export class Camera { * @en create geometry renderer for this camera * @zh 创建这个摄像机的几何体渲染器 */ - public initGeometryRenderer() { + public initGeometryRenderer () { if (!this._geometryRenderer) { this._geometryRenderer = legacyCC.internal.GeometryRenderer ? new legacyCC.internal.GeometryRenderer() : null; this._geometryRenderer?.activate(this._device); @@ -811,6 +835,22 @@ export class Camera { return this._geometryRenderer; } + get cameraType () : CameraType { + return this._cameraType; + } + + set cameraType (type: CameraType) { + this._cameraType = type; + } + + get trackingType () : TrackingType { + return this._trackingType; + } + + set trackingType (type: TrackingType) { + this._trackingType = type; + } + /** * @en Change the target render window to another one * @zh 修改相机的目标渲染窗口 diff --git a/cocos/core/renderer/scene/skybox.ts b/cocos/core/renderer/scene/skybox.ts index 82a59cdd6e..2ca880ec7d 100644 --- a/cocos/core/renderer/scene/skybox.ts +++ b/cocos/core/renderer/scene/skybox.ts @@ -226,6 +226,7 @@ export class Skybox { protected _activated = false; protected _reflectionHDR: TextureCube | null = null; protected _reflectionLDR: TextureCube | null = null; + protected _rotationAngle = 0; public initialize (skyboxInfo: SkyboxInfo) { this._activated = false; @@ -290,6 +291,19 @@ export class Skybox { this._updatePipeline(); } + /** + * @en Set skybox rotation angle + * @zh 设置天空盒旋转角度 + * @param angle @en rotation angle @zh 旋转角度 + */ + public setRotationAngle (angle: number) { + this._rotationAngle = angle; + } + + public getRotationAngle () { + return this._rotationAngle; + } + public updateMaterialRenderInfo () { this._updateGlobalBinding(); this._updatePipeline(); @@ -369,19 +383,13 @@ export class Skybox { if (this.enabled) { const envmap = this.envmap ? this.envmap : this._default; - if (this._editableMaterial) { - this._editableMaterial.setProperty('environmentMap', envmap); - this._editableMaterial.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE }); - } else if (skybox_material) { - skybox_material.setProperty('environmentMap', envmap); - skybox_material.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE }); + const skyboxMat = this._editableMaterial ? this._editableMaterial : skybox_material; + if (skyboxMat) { + skyboxMat.setProperty('environmentMap', envmap); + skyboxMat.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE }); } if (this._model) { - if (this._editableMaterial) { - this._model.setSubModelMaterial(0, this._editableMaterial); - } else { - this._model.setSubModelMaterial(0, skybox_material!); - } + this._model.setSubModelMaterial(0, skyboxMat!); this._updateSubModes(); } } diff --git a/cocos/core/scene-graph/node.jsb.ts b/cocos/core/scene-graph/node.jsb.ts index 2422b35d8a..29fdeffdce 100644 --- a/cocos/core/scene-graph/node.jsb.ts +++ b/cocos/core/scene-graph/node.jsb.ts @@ -1063,11 +1063,11 @@ Object.defineProperty(nodeProto, '_parent', { configurable: true, enumerable: true, get () { - return this._parentInternal; + this._parentRef = this._parentInternal; + return this._parentRef; }, set (v) { - // jsb.registerNativeRef(v, this); // Root JSB object to avoid child node being garbage collected - this._parentInternal = v; + this._parentRef = this._parentInternal = v; }, }); @@ -1075,10 +1075,11 @@ Object.defineProperty(nodeProto, 'parent', { configurable: true, enumerable: true, get () { - return this.getParent(); + this._parentRef = this.getParent(); + return this._parentRef; }, set (v) { - // jsb.registerNativeRef(v, this); // Root JSB object to avoid child node being garbage collected + this._parentRef = v; this.setParent(v); }, }); @@ -1263,6 +1264,7 @@ nodeProto._instantiate = function (cloned: Node, isSyncedNode: boolean) { // nodeProto._ctor = function (name?: string) { this.__nativeRefs = {}; + this._parentRef = null; this.__jsb_ref_id = undefined; this._iN$t = null; this.__editorExtras__ = { editorOnly: true }; diff --git a/cocos/core/scene-graph/scene-globals.ts b/cocos/core/scene-graph/scene-globals.ts index ce702c8f45..0134ce1382 100644 --- a/cocos/core/scene-graph/scene-globals.ts +++ b/cocos/core/scene-graph/scene-globals.ts @@ -409,6 +409,23 @@ export class SkyboxInfo { } } + /** + * @en Rotate the skybox + * @zh 旋转天空盒 + */ + @type(CCFloat) + @range([0, 360]) + @rangeStep(1) + @slide + @tooltip('i18n:skybox.rotationAngle') + set rotationAngle (val: number) { + this._rotationAngle = val; + if (this._resource) { this._resource.setRotationAngle(this._rotationAngle); } + } + get rotationAngle () { + return this._rotationAngle; + } + /** * @en The optional diffusion convolution map used in tandem with IBL * @zh 使用的漫反射卷积图 @@ -523,6 +540,8 @@ export class SkyboxInfo { @serializable @type(TextureCube) protected _reflectionLDR: TextureCube | null = null; + @serializable + protected _rotationAngle = 0; protected _resource: Skybox | null = null; @@ -539,6 +558,7 @@ export class SkyboxInfo { this._resource.setDiffuseMaps(this._diffuseMapHDR, this._diffuseMapLDR); this._resource.setSkyboxMaterial(this._editableMaterial); this._resource.setReflectionMaps(this._reflectionHDR, this._reflectionLDR); + this._resource.setRotationAngle(this._rotationAngle); this._resource.activate(); // update global DS first } } diff --git a/cocos/core/splash-screen.ts b/cocos/core/splash-screen.ts index f35faae6c9..3ca30dde1b 100644 --- a/cocos/core/splash-screen.ts +++ b/cocos/core/splash-screen.ts @@ -37,6 +37,7 @@ import { legacyCC } from './global-exports'; import { SetIndex } from './pipeline/define'; import { Mat4, Vec2 } from './math'; import { Settings, settings } from './settings'; +import { sys } from './platform/sys'; const v2_0 = new Vec2(); type SplashEffectType = 'NONE' | 'FADE-INOUT'; @@ -281,41 +282,55 @@ export class SplashScreen { private frame () { const { device, swapchain } = this; - device.acquire([swapchain]); - // record command - const cmdBuff = this.cmdBuff; - const framebuffer = this.framebuffer; - const renderArea = this.renderArea; - renderArea.width = swapchain.width; - renderArea.height = swapchain.height; + if (!sys.isXR || xr.entry.isRenderAllowable()) { + const renderSize = sys.isXR ? 2 : 1; + for (let xrEye = 0; xrEye < renderSize; xrEye++) { + if (sys.isXR) { + xr.entry.renderLoopStart(xrEye); + } - cmdBuff.begin(); - cmdBuff.beginRenderPass(framebuffer.renderPass, framebuffer, renderArea, this.clearColors, 1.0, 0); + device.acquire([swapchain]); + // record command + const cmdBuff = this.cmdBuff; + const framebuffer = this.framebuffer; + const renderArea = this.renderArea; - const logoPass = this.logoMat.passes[0]; - const logoPso = PipelineStateManager.getOrCreatePipelineState(device, logoPass, this.shader, framebuffer.renderPass, this.quadAssmebler); + renderArea.width = swapchain.width; + renderArea.height = swapchain.height; - cmdBuff.bindPipelineState(logoPso); - cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, logoPass.descriptorSet); - cmdBuff.bindInputAssembler(this.quadAssmebler); - cmdBuff.draw(this.quadAssmebler); + cmdBuff.begin(); + cmdBuff.beginRenderPass(framebuffer.renderPass, framebuffer, renderArea, this.clearColors, 1.0, 0); - if (this.settings.displayWatermark && this.watermarkMat) { - const wartermarkPass = this.watermarkMat.passes[0]; - const watermarkPso = PipelineStateManager.getOrCreatePipelineState(device, - wartermarkPass, this.shader, framebuffer.renderPass, this.quadAssmebler); - cmdBuff.bindPipelineState(watermarkPso); - cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, wartermarkPass.descriptorSet); - cmdBuff.bindInputAssembler(this.quadAssmebler); - cmdBuff.draw(this.quadAssmebler); + const logoPass = this.logoMat.passes[0]; + const logoPso = PipelineStateManager.getOrCreatePipelineState(device, logoPass, this.shader, framebuffer.renderPass, this.quadAssmebler); + + cmdBuff.bindPipelineState(logoPso); + cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, logoPass.descriptorSet); + cmdBuff.bindInputAssembler(this.quadAssmebler); + cmdBuff.draw(this.quadAssmebler); + + if (this.settings.displayWatermark && this.watermarkMat) { + const wartermarkPass = this.watermarkMat.passes[0]; + const watermarkPso = PipelineStateManager.getOrCreatePipelineState(device, + wartermarkPass, this.shader, framebuffer.renderPass, this.quadAssmebler); + cmdBuff.bindPipelineState(watermarkPso); + cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, wartermarkPass.descriptorSet); + cmdBuff.bindInputAssembler(this.quadAssmebler); + cmdBuff.draw(this.quadAssmebler); + } + + cmdBuff.endRenderPass(); + cmdBuff.end(); + device.flushCommands([cmdBuff]); + device.queue.submit([cmdBuff]); + device.present(); + + if (sys.isXR) { + xr.entry.renderLoopEnd(xrEye); + } + } } - - cmdBuff.endRenderPass(); - cmdBuff.end(); - device.flushCommands([cmdBuff]); - device.queue.submit([cmdBuff]); - device.present(); } private destroy () { diff --git a/cocos/input/index.ts b/cocos/input/index.ts index a2a7a0b790..2e15540123 100644 --- a/cocos/input/index.ts +++ b/cocos/input/index.ts @@ -2,3 +2,5 @@ import './deprecated'; export { input, Input } from './input'; export { systemEvent, SystemEvent } from './system-event'; +// TODO: support gamepad state query +// export { GamepadInputDevice as Gamepad } from 'pal/input'; diff --git a/cocos/input/input.ts b/cocos/input/input.ts index 97176ceb94..7c7cb8b948 100644 --- a/cocos/input/input.ts +++ b/cocos/input/input.ts @@ -25,11 +25,11 @@ */ import { EDITOR, NATIVE } from 'internal:constants'; -import { TouchInputSource, MouseInputSource, KeyboardInputSource, AccelerometerInputSource } from 'pal/input'; +import { TouchInputSource, MouseInputSource, KeyboardInputSource, AccelerometerInputSource, GamepadInputDevice, HandleInputDevice, HMDInputDevice } from 'pal/input'; import { touchManager } from '../../pal/input/touch-manager'; import { sys } from '../core/platform/sys'; import { EventTarget } from '../core/event/event-target'; -import { Event, EventAcceleration, EventKeyboard, EventMouse, EventTouch, Touch } from './types'; +import { Event, EventAcceleration, EventGamepad, EventHandle, EventHMD, EventKeyboard, EventMouse, EventTouch, Touch } from './types'; import { InputEventType } from './types/event-enum'; import { legacyCC } from '../core/global-exports'; @@ -87,15 +87,20 @@ interface InputEventMap { [Input.EventType.KEY_PRESSING]: (event: EventKeyboard) => void, [Input.EventType.KEY_UP]: (event: EventKeyboard) => void, [Input.EventType.DEVICEMOTION]: (event: EventAcceleration) => void, + [Input.EventType.GAMEPAD_CHANGE]: (event: EventGamepad) => void, + [Input.EventType.GAMEPAD_INPUT]: (event: EventGamepad) => void, + [Input.EventType.HANDLE_INPUT]: (event: EventHandle) => void, + [Input.EventType.HANDLE_POSE_INPUT]: (event: EventHandle) => void, + [Input.EventType.HMD_POSE_INPUT]: (event: EventHMD) => void, } /** * @en - * This Input class manages all events of input. include: touch, mouse, accelerometer and keyboard. + * This Input class manages all events of input. include: touch, mouse, accelerometer, gamepad, handle, hmd and keyboard. * You can get the `Input` instance with `input`. * * @zh - * 该输入类管理所有的输入事件,包括:触摸、鼠标、加速计 和 键盘。 + * 该输入类管理所有的输入事件,包括:触摸、鼠标、加速计、游戏手柄、6DOF手柄、头戴显示器 和 键盘。 * 你可以通过 `input` 获取到 `Input` 的实例。 * * @example @@ -128,11 +133,16 @@ export class Input { private _mouseInput = new MouseInputSource(); private _keyboardInput = new KeyboardInputSource(); private _accelerometerInput = new AccelerometerInputSource(); + private _handleInput = new HandleInputDevice(); + private _hmdInput = new HMDInputDevice(); private _eventTouchList: EventTouch[] = []; private _eventMouseList: EventMouse[] = []; private _eventKeyboardList: EventKeyboard[] = []; private _eventAccelerationList: EventAcceleration[] = []; + private _eventGamepadList: EventGamepad[] = []; + private _eventHandleList: EventHandle[] = []; + private _eventHMDList: EventHMD[] = []; private _needSimulateTouchMoveEvent = false; @@ -143,6 +153,7 @@ export class Input { this._registerEvent(); this._inputEventDispatcher = new InputEventDispatcher(this._eventTarget); this._registerEventDispatcher(this._inputEventDispatcher); + GamepadInputDevice._init(); } /** @@ -321,6 +332,23 @@ export class Input { const eventAccelerationList = this._eventAccelerationList; this._accelerometerInput.on(InputEventType.DEVICEMOTION, (event) => { this._dispatchOrPushEvent(event, eventAccelerationList); }); } + + if (sys.hasFeature(sys.Feature.EVENT_GAMEPAD)) { + const eventGamepadList = this._eventGamepadList; + GamepadInputDevice._on(InputEventType.GAMEPAD_CHANGE, (event) => { this._dispatchOrPushEvent(event, eventGamepadList); }); + GamepadInputDevice._on(InputEventType.GAMEPAD_INPUT, (event) => { this._dispatchOrPushEvent(event, eventGamepadList); }); + } + + if (sys.hasFeature(sys.Feature.EVENT_HANDLE)) { + const eventHandleList = this._eventHandleList; + this._handleInput._on(InputEventType.HANDLE_INPUT, (event) => { this._dispatchOrPushEvent(event, eventHandleList); }); + this._handleInput._on(InputEventType.HANDLE_POSE_INPUT, (event) => { this._dispatchOrPushEvent(event, eventHandleList); }); + } + + if (sys.hasFeature(sys.Feature.EVENT_HMD)) { + const eventHMDList = this._eventHMDList; + this._hmdInput._on(InputEventType.HMD_POSE_INPUT, (event) => { this._dispatchOrPushEvent(event, eventHMDList); }); + } } private _clearEvents () { @@ -328,6 +356,9 @@ export class Input { this._eventTouchList.length = 0; this._eventKeyboardList.length = 0; this._eventAccelerationList.length = 0; + this._eventGamepadList.length = 0; + this._eventHandleList.length = 0; + this._eventHMDList.length = 0; } private _dispatchOrPushEvent (event: Event, eventList: Event[]) { @@ -387,16 +418,37 @@ export class Input { this._emitEvent(eventAcceleration); } + const eventGamepadList = this._eventGamepadList; + // TODO: culling event queue + for (let i = 0, length = eventGamepadList.length; i < length; ++i) { + const eventGamepad = eventGamepadList[i]; + this._emitEvent(eventGamepad); + } + + const eventHandleList = this._eventHandleList; + // TODO: culling event queue + for (let i = 0, length = eventHandleList.length; i < length; ++i) { + const eventHandle = eventHandleList[i]; + this._emitEvent(eventHandle); + } + + const eventHMDList = this._eventHMDList; + // TODO: culling event queue + for (let i = 0, length = eventHMDList.length; i < length; ++i) { + const eventHMD = eventHMDList[i]; + this._emitEvent(eventHMD); + } + this._clearEvents(); } } /** * @en - * The singleton of the Input class, this singleton manages all events of input. include: touch, mouse, accelerometer and keyboard. + * The singleton of the Input class, this singleton manages all events of input. include: touch, mouse, accelerometer, gamepad, handle, hmd and keyboard. * * @zh - * 输入类单例,该单例管理所有的输入事件,包括:触摸、鼠标、加速计 和 键盘。 + * 输入类单例,该单例管理所有的输入事件,包括:触摸、鼠标、加速计、游戏手柄、6DOF手柄、头戴显示器 和 键盘。 * * @example * ``` diff --git a/cocos/input/types/event-enum.ts b/cocos/input/types/event-enum.ts index 8248ce8d8e..7d2c15fd47 100644 --- a/cocos/input/types/event-enum.ts +++ b/cocos/input/types/event-enum.ts @@ -373,6 +373,35 @@ export enum InputEventType { * 重力感应 */ DEVICEMOTION = 'devicemotion', + + /** + * @en The event type for gamepad input + * @zh 手柄输入事件 + */ + GAMEPAD_INPUT = 'gamepad-input', + /** + * @en The event type for gamepad device change, including gamepad connecting and disconnecting + * @zh 手柄设备改变时触发的事件,包括手柄连接,手柄断开连接 + */ + GAMEPAD_CHANGE = 'gamepad-change', + + /** + * @en The event type for 6DOF handle input + * @zh 6DOF手柄输入事件 + */ + HANDLE_INPUT = 'handle-input', + + /** + * @en The event type for handle pose input + * @zh 手柄姿态输入事件 + */ + HANDLE_POSE_INPUT = 'handle-pose-input', + + /** + * @en The event type for hmd pose input + * @zh 头戴显示器姿态输入事件 + */ + HMD_POSE_INPUT = 'hmd-pose-input' } export type SystemEventTypeUnion = SystemEventType | NodeEventType | InputEventType | string; diff --git a/cocos/input/types/event/event-gamepad.ts b/cocos/input/types/event/event-gamepad.ts new file mode 100644 index 0000000000..fb87002d77 --- /dev/null +++ b/cocos/input/types/event/event-gamepad.ts @@ -0,0 +1,52 @@ +/* + Copyright (c) 2022 Chukong Technologies Inc. + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +/** + * @packageDocumentation + * @module event + */ + +import { GamepadInputDevice as Gamepad } from 'pal/input'; +import { Event } from './event'; + +/** + * @en + * The gamepad event. + * @zh + * 手柄事件。 + */ +export class EventGamepad extends Event { + /** + * @en The gamepad device which trigger the current gamepad event + * @zh 触发当前手柄事件的手柄设备 + */ + public gamepad: Gamepad; + + constructor (type: string, gamepad: Gamepad) { + super(type, false); + this.gamepad = gamepad; + } +} diff --git a/cocos/input/types/event/event-handle.ts b/cocos/input/types/event/event-handle.ts new file mode 100644 index 0000000000..689a6122b1 --- /dev/null +++ b/cocos/input/types/event/event-handle.ts @@ -0,0 +1,52 @@ +/* + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { HandleInputDevice } from 'pal/input'; +import { Event } from './event'; +import { SystemEventTypeUnion } from '../event-enum'; + +/** + * @en + * The 6DOF handle event. + * + * @zh + * 6DOF手柄事件。 + */ +export class EventHandle extends Event { + /** + * @en The handle device which trigger the current handle event + * @zh 触发当前手柄事件的手柄设备 + */ + public handleInputDevice: HandleInputDevice; + + /** + * @param eventType - The type of the event + * @param handleInputDevice - The handle device which trigger the current handle event + */ + constructor (eventType: SystemEventTypeUnion, handleInputDevice: HandleInputDevice) { + super(eventType, false); + this.handleInputDevice = handleInputDevice; + } +} diff --git a/cocos/input/types/event/event-hmd.ts b/cocos/input/types/event/event-hmd.ts new file mode 100644 index 0000000000..b31852e342 --- /dev/null +++ b/cocos/input/types/event/event-hmd.ts @@ -0,0 +1,52 @@ +/* + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { HMDInputDevice } from 'pal/input'; +import { Event } from './event'; +import { SystemEventTypeUnion } from '../event-enum'; + +/** + * @en + * The HMD event. + * + * @zh + * 头戴显示器事件。 + */ +export class EventHMD extends Event { + /** + * @en The hmd device which trigger the current hmd event + * @zh 触发当前头戴显示器事件的头戴显示器设备 + */ + public hmdInputDevice: HMDInputDevice; + + /** + * @param eventType - The type of the event + * @param hmdInputDevice - The hmd device which trigger the current hmd event + */ + constructor (eventType: SystemEventTypeUnion, hmdInputDevice: HMDInputDevice) { + super(eventType, false); + this.hmdInputDevice = hmdInputDevice; + } +} diff --git a/cocos/input/types/event/index.ts b/cocos/input/types/event/index.ts index c7c4a07e19..b09e8b1f6c 100644 --- a/cocos/input/types/event/index.ts +++ b/cocos/input/types/event/index.ts @@ -3,3 +3,6 @@ export * from './event-acceleration'; export * from './event-keyboard'; export * from './event-mouse'; export * from './event-touch'; +export * from './event-gamepad'; +export * from './event-handle'; +export * from './event-hmd'; diff --git a/cocos/particle/line.ts b/cocos/particle/line.ts index c43627c142..0671908508 100644 --- a/cocos/particle/line.ts +++ b/cocos/particle/line.ts @@ -67,10 +67,21 @@ export class Line extends Component { this._materialInstance.setProperty('mainTexture', val); } } - + @serializable private _material: Material | null = null; private _materialInstance: MaterialInstance | null = null; + @type(Material) + @displayOrder(1) + @tooltip('i18n:line.material') + get material() { + return this._material; + } + + set material(val) { + this._material = val; + } + @serializable private _worldSpace = false; @@ -213,6 +224,8 @@ export class Line extends Component { if (this._material === null) { this._material = new Material(); this._material.copy(builtinResMgr.get('default-trail-material')); + } + if (this._material) { define[CC_USE_WORLD_SPACE] = this.worldSpace; _matInsInfo.parent = this._material; _matInsInfo.subModelIdx = 0; diff --git a/cocos/physics/framework/components/colliders/collider.ts b/cocos/physics/framework/components/colliders/collider.ts index 77b8c62fe5..5ca9dc145f 100644 --- a/cocos/physics/framework/components/colliders/collider.ts +++ b/cocos/physics/framework/components/colliders/collider.ts @@ -37,6 +37,7 @@ import { IBaseShape } from '../../../spec/i-physics-shape'; import { AABB, Sphere } from '../../../../core/geometry'; import { EColliderType, EAxisDirection } from '../../physics-enum'; import { selector, createShape } from '../../physics-selector'; +import { XrControlEventType } from '../../../../xr/event/xr-event-handle'; /** * @en @@ -252,7 +253,7 @@ export class Collider extends Eventify(Component) { * @param callback - The event callback, signature:`(event?:ICollisionEvent|ITriggerEvent)=>void`. * @param target - The event callback target. */ - public on void>(type: TriggerEventType | CollisionEventType, callback: TFunction, target?, once?: boolean): any { + public on void>(type: TriggerEventType | CollisionEventType | XrControlEventType, callback: TFunction, target?, once?: boolean): any { const ret = super.on(type, callback, target, once); this._updateNeedEvent(type); return ret; @@ -267,7 +268,7 @@ export class Collider extends Eventify(Component) { * @param callback - The event callback, signature:`(event?:ICollisionEvent|ITriggerEvent)=>void`. * @param target - The event callback target. */ - public off (type: TriggerEventType | CollisionEventType, callback?: (...any) => void, target?) { + public off (type: TriggerEventType | CollisionEventType | XrControlEventType, callback?: (...any) => void, target?) { super.off(type, callback, target); this._updateNeedEvent(); } diff --git a/cocos/profiler/profiler.ts b/cocos/profiler/profiler.ts index 985f8f233c..06e0c3aea1 100644 --- a/cocos/profiler/profiler.ts +++ b/cocos/profiler/profiler.ts @@ -38,7 +38,7 @@ import { Pass } from '../core/renderer'; import { preTransforms } from '../core/math/mat4'; import { Root } from '../core/root'; import { PipelineRuntime } from '../core/pipeline/custom/pipeline'; -import { director, System } from '../core'; +import { director, System, sys } from '../core'; import { Settings, settings } from '../core/settings'; const _characters = '0123456789. '; @@ -397,7 +397,10 @@ export class Profiler extends System { const clipSpaceSignY = this._device!.capabilities.clipSpaceSignY; if (surfaceTransform !== this.offsetData[3]) { const preTransform = preTransforms[surfaceTransform]; - const x = -0.9; const y = -0.9 * clipSpaceSignY; + let x = -0.9; let y = -0.9 * clipSpaceSignY; + if (sys.isXR) { + x = -0.5; y = -0.5 * clipSpaceSignY; + } this.offsetData[0] = x * preTransform[0] + y * preTransform[2]; this.offsetData[1] = x * preTransform[1] + y * preTransform[3]; this.offsetData[2] = this._eachNumWidth; diff --git a/cocos/ui/button.ts b/cocos/ui/button.ts index e03c808ed3..58a0b94b5c 100644 --- a/cocos/ui/button.ts +++ b/cocos/ui/button.ts @@ -38,6 +38,7 @@ import { Sprite } from '../2d/components/sprite'; import { legacyCC } from '../core/global-exports'; import { TransformBit } from '../core/scene-graph/node-enum'; import { NodeEventType } from '../core/scene-graph/node-event'; +import { XrUIPressEventType } from '../xr/event/xr-event-handle'; const _tempColor = new Color(); @@ -693,6 +694,11 @@ export class Button extends Component { this.node.on(NodeEventType.MOUSE_ENTER, this._onMouseMoveIn, this); this.node.on(NodeEventType.MOUSE_LEAVE, this._onMouseMoveOut, this); + + this.node.on(XrUIPressEventType.XRUI_HOVER_ENTERED, this._xrHoverEnter, this); + this.node.on(XrUIPressEventType.XRUI_HOVER_EXITED, this._xrHoverExit, this); + this.node.on(XrUIPressEventType.XRUI_CLICK, this._xrClick, this); + this.node.on(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick, this); } protected _registerTargetEvent (target) { @@ -711,6 +717,11 @@ export class Button extends Component { this.node.off(NodeEventType.MOUSE_ENTER, this._onMouseMoveIn, this); this.node.off(NodeEventType.MOUSE_LEAVE, this._onMouseMoveOut, this); + + this.node.off(XrUIPressEventType.XRUI_HOVER_ENTERED, this._xrHoverEnter, this); + this.node.off(XrUIPressEventType.XRUI_HOVER_EXITED, this._xrHoverExit, this); + this.node.off(XrUIPressEventType.XRUI_CLICK, this._xrClick, this); + this.node.off(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick, this); } protected _unregisterTargetEvent (target) { @@ -979,6 +990,38 @@ export class Button extends Component { this._updateScaleTransition(state); } } + + private _xrHoverEnter() { + this._onMouseMoveIn(); + this._updateState(); + } + + private _xrHoverExit() { + this._onMouseMoveOut(); + if (this._pressed) { + this._pressed = false; + this._updateState(); + } + } + + private _xrClick() { + if (!this._interactable || !this.enabledInHierarchy) { return; } + this._pressed = true; + this._updateState(); + } + + private _xrUnClick() { + if (!this._interactable || !this.enabledInHierarchy) { + return; + } + + if (this._pressed) { + ComponentEventHandler.emitEvents(this.clickEvents, this); + this.node.emit(EventType.CLICK, this); + } + this._pressed = false; + this._updateState(); + } } legacyCC.Button = Button; diff --git a/cocos/ui/editbox/edit-box.ts b/cocos/ui/editbox/edit-box.ts index 7587a133eb..ca47af58ce 100644 --- a/cocos/ui/editbox/edit-box.ts +++ b/cocos/ui/editbox/edit-box.ts @@ -38,9 +38,9 @@ import { Sprite } from '../../2d/components/sprite'; import { EditBoxImpl } from './edit-box-impl'; import { EditBoxImplBase } from './edit-box-impl-base'; import { InputFlag, InputMode, KeyboardReturnType } from './types'; -import { sys } from '../../core/platform/sys'; import { legacyCC } from '../../core/global-exports'; import { NodeEventType } from '../../core/scene-graph/node-event'; +import { XrKeyboardEventType, XrUIPressEventType } from '../../xr/event/xr-event-handle'; const LEFT_PADDING = 2; @@ -57,6 +57,8 @@ enum EventType { EDITING_DID_ENDED = 'editing-did-ended', TEXT_CHANGED = 'text-changed', EDITING_RETURN = 'editing-return', + XR_EDITING_DID_BEGAN = 'xr-editing-did-began', + XR_EDITING_DID_ENDED = 'xr-editing-did-ended', } /** * @en @@ -692,11 +694,17 @@ export class EditBox extends Component { protected _registerEvent () { this.node.on(NodeEventType.TOUCH_START, this._onTouchBegan, this); this.node.on(NodeEventType.TOUCH_END, this._onTouchEnded, this); + + this.node.on(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick, this); + this.node.on(XrKeyboardEventType.XR_KEYBOARD_INPUT, this._xrKeyBoardInput, this); } protected _unregisterEvent () { this.node.off(NodeEventType.TOUCH_START, this._onTouchBegan, this); this.node.off(NodeEventType.TOUCH_END, this._onTouchEnded, this); + + this.node.off(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick, this); + this.node.off(XrKeyboardEventType.XR_KEYBOARD_INPUT, this._xrKeyBoardInput, this); } private _onBackgroundSpriteFrameChanged () { @@ -759,6 +767,14 @@ export class EditBox extends Component { this._syncSize(); } + + protected _xrUnClick() { + this.node.emit(EventType.XR_EDITING_DID_BEGAN, this._maxLength, this.string); + } + + protected _xrKeyBoardInput(str: string) { + this.string = str; + } } // this equals to sys.isBrowser diff --git a/cocos/ui/scroll-view.ts b/cocos/ui/scroll-view.ts index 636fe2c4aa..57cf58ea01 100644 --- a/cocos/ui/scroll-view.ts +++ b/cocos/ui/scroll-view.ts @@ -28,7 +28,7 @@ import { ccclass, help, executionOrder, menu, requireComponent, tooltip, display import { EDITOR } from 'internal:constants'; import { EventHandler as ComponentEventHandler } from '../core/components/component-event-handler'; import { UITransform } from '../2d/framework'; -import { Event, EventMouse, EventTouch, Touch, SystemEventType } from '../input/types'; +import { Event, EventMouse, EventTouch, Touch, SystemEventType, EventHandle, EventGamepad } from '../input/types'; import { logID } from '../core/platform/debug'; import { Size, Vec2, Vec3 } from '../core/math'; import { Layout } from './layout'; @@ -39,6 +39,8 @@ import { director, Director } from '../core/director'; import { TransformBit } from '../core/scene-graph/node-enum'; import { legacyCC } from '../core/global-exports'; import { NodeEventType } from '../core/scene-graph/node-event'; +import { Input, input } from '../input/input'; +import { DeviceType, XrUIPressEvent, XrUIPressEventType } from '../xr/event/xr-event-handle'; const NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED = 5; const OUT_OF_BOUNDARY_BREAKING_FACTOR = 0.05; @@ -190,6 +192,12 @@ export enum EventType { TOUCH_UP = 'touch-up', } +enum XrhoverType { + NONE = 0, + LEFT = 1, + RIGHT = 2 +} + /** * @en * Layout container for a view hierarchy that can be scrolled by the user, @@ -435,6 +443,9 @@ export class ScrollView extends ViewGroup { protected _contentPos = new Vec3(); protected _deltaPos = new Vec3(); + protected _hoverIn: XrhoverType = XrhoverType.NONE; + protected _scrollState = new Vec2(0, 0); + /** * @en * Scroll the content to the bottom boundary of ScrollView. @@ -999,6 +1010,12 @@ export class ScrollView extends ViewGroup { this.node.on(NodeEventType.TOUCH_END, this._onTouchEnded, this, true); this.node.on(NodeEventType.TOUCH_CANCEL, this._onTouchCancelled, this, true); this.node.on(NodeEventType.MOUSE_WHEEL, this._onMouseWheel, this, true); + + this.node.on(XrUIPressEventType.XRUI_HOVER_ENTERED, this._xrHoverEnter, this); + this.node.on(XrUIPressEventType.XRUI_HOVER_EXITED, this._xrHoverExit, this); + + input.on(Input.EventType.HANDLE_INPUT, this._dispatchEventHandleInput, this); + input.on(Input.EventType.GAMEPAD_INPUT, this._dispatchEventHandleInput, this); } protected _unregisterEvent () { @@ -1007,6 +1024,11 @@ export class ScrollView extends ViewGroup { this.node.off(NodeEventType.TOUCH_END, this._onTouchEnded, this, true); this.node.off(NodeEventType.TOUCH_CANCEL, this._onTouchCancelled, this, true); this.node.off(NodeEventType.MOUSE_WHEEL, this._onMouseWheel, this, true); + + this.node.off(XrUIPressEventType.XRUI_HOVER_ENTERED, this._xrHoverEnter, this); + this.node.off(XrUIPressEventType.XRUI_HOVER_EXITED, this._xrHoverExit, this); + input.off(Input.EventType.HANDLE_INPUT, this._dispatchEventHandleInput, this); + input.off(Input.EventType.GAMEPAD_INPUT, this._dispatchEventHandleInput, this); } protected _onMouseWheel (event: EventMouse, captureListeners?: Node[]) { @@ -1810,6 +1832,73 @@ export class ScrollView extends ViewGroup { this._calculateBoundary(); } } + + protected _xrHoverEnter(event: XrUIPressEvent) { + if (event.deviceType === DeviceType.Left) { + this._hoverIn = XrhoverType.LEFT; + } else if (event.deviceType === DeviceType.Right) { + this._hoverIn = XrhoverType.RIGHT; + } + this._autoScrolling = false; + this._dispatchEvent(EventType.SCROLL_BEGAN); + } + + protected _xrHoverExit() { + this._hoverIn = XrhoverType.NONE; + this._autoScrolling = true; + this._dispatchEvent(EventType.SCROLL_ENDED); + } + + private _dispatchEventHandleInput(event: EventHandle | EventGamepad) { + let handleInputDevice; + if (event instanceof EventGamepad) { + handleInputDevice = event.gamepad; + } else if (event instanceof EventHandle) { + handleInputDevice = event.handleInputDevice; + } + let value; + if (!this.enabledInHierarchy) { + return; + } + if (this._hoverIn === XrhoverType.NONE) { + return; + } else if (this._hoverIn === XrhoverType.LEFT) { + value = handleInputDevice.leftStick.getValue(); + if (!value.equals(Vec2.ZERO)) { + this._xrThumbStickMove(value); + } + } else if (this._hoverIn === XrhoverType.RIGHT) { + value = handleInputDevice.rightStick.getValue(); + if (!value.equals(Vec2.ZERO)) { + this._xrThumbStickMove(value); + } + } + + if (!value && this._scrollState.equals(Vec2.ZERO)) { + this._xrThumbStickMoveEnd(); + this._scrollState.set(value); + } + } + + protected _xrThumbStickMove(event: Vec2) { + const deltaMove = new Vec3(); + const wheelPrecision = -62.5; + const scrollY = event.y; + if (this.vertical) { + deltaMove.set(0, scrollY * wheelPrecision, 0); + } else if (this.horizontal) { + deltaMove.set(scrollY * wheelPrecision, 0, 0); + } + + this._mouseWheelEventElapsedTime = 0; + this._processDeltaMove(deltaMove); + this._dispatchEvent(EventType.SCROLLING); + } + + protected _xrThumbStickMoveEnd() { + this._autoScrolling = true; + this._dispatchEvent(EventType.TOUCH_UP); + } } /** diff --git a/cocos/ui/slider.ts b/cocos/ui/slider.ts index 81c9c801a7..efa8807fe5 100644 --- a/cocos/ui/slider.ts +++ b/cocos/ui/slider.ts @@ -35,6 +35,8 @@ import { clamp01 } from '../core/math/utils'; import { Sprite } from '../2d/components/sprite'; import { legacyCC } from '../core/global-exports'; import { NodeEventType } from '../core/scene-graph/node-event'; +import { input, Input } from '../input/input'; +import { XrUIPressEvent, XrUIPressEventType } from '../xr/event/xr-event-handle'; const _tempPos = new Vec3(); /** @@ -186,6 +188,10 @@ export class Slider extends Component { this.node.on(NodeEventType.TOUCH_MOVE, this._onTouchMoved, this); this.node.on(NodeEventType.TOUCH_END, this._onTouchEnded, this); this.node.on(NodeEventType.TOUCH_CANCEL, this._onTouchCancelled, this); + + this.node.on(XrUIPressEventType.XRUI_HOVER_STAY, this._xrHoverStay, this); + this.node.on(XrUIPressEventType.XRUI_CLICK, this._xrClick, this); + this.node.on(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick, this); if (this._handle && this._handle.isValid) { this._handle.node.on(NodeEventType.TOUCH_START, this._onHandleDragStart, this); this._handle.node.on(NodeEventType.TOUCH_MOVE, this._onTouchMoved, this); @@ -198,6 +204,10 @@ export class Slider extends Component { this.node.off(NodeEventType.TOUCH_MOVE, this._onTouchMoved, this); this.node.off(NodeEventType.TOUCH_END, this._onTouchEnded, this); this.node.off(NodeEventType.TOUCH_CANCEL, this._onTouchCancelled, this); + + this.node.off(XrUIPressEventType.XRUI_HOVER_STAY, this._xrHoverStay, this); + this.node.off(XrUIPressEventType.XRUI_CLICK, this._xrClick, this); + this.node.off(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick, this); if (this._handle && this._handle.isValid) { this._handle.node.off(NodeEventType.TOUCH_START, this._onHandleDragStart, this); this._handle.node.off(NodeEventType.TOUCH_MOVE, this._onTouchMoved, this); @@ -314,6 +324,40 @@ export class Slider extends Component { this._updateHandlePosition(); } } + + protected _xrHandleProgress(point: Vec3) { + if (!this._touchHandle) { + const uiTrans = this.node._uiProps.uiTransformComp!; + if (this.direction === Direction.Horizontal) { + this.progress = clamp01(0.5 + (point.x - this.node.worldPosition.x) / (uiTrans.width * this.node.worldScale.x)); + } else { + this.progress = clamp01(0.5 + (point.y - this.node.worldPosition.y) / (uiTrans.height * this.node.worldScale.y)); + } + } + } + + protected _xrClick(event: XrUIPressEvent) { + if (!this._handle) { + return; + } + this._dragging = true; + this._xrHandleProgress(event.hitPoint); + this._emitSlideEvent(); + } + + protected _xrUnClick() { + this._dragging = false; + this._touchHandle = false; + } + + protected _xrHoverStay(event: XrUIPressEvent) { + if (!this._dragging) { + return; + } + + this._xrHandleProgress(event.hitPoint); + this._emitSlideEvent(); + } } /** diff --git a/cocos/xr/event/xr-event-handle.ts b/cocos/xr/event/xr-event-handle.ts new file mode 100644 index 0000000000..495971f1d3 --- /dev/null +++ b/cocos/xr/event/xr-event-handle.ts @@ -0,0 +1,205 @@ +/* + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ + +/** + * @packageDocumentation + * @module component/xr + */ + +import { Vec3 } from '../../core/math'; +import { Node } from '../../core/scene-graph/node'; +import { Event } from '../../input/types'; + +export enum DeviceType { + Other = 0, + Left = 1, + Right = 2 +} + +/** + * @en The input event type + * @zh 输入事件类型 + */ +export enum XrControlEventType { + SELECT_ENTERED = 'select-entered', + SELECT_EXITED = 'select-exited', + SELECT_CANCELED = 'select-canceled', + + ACTIVATED = 'OnActivited', + DEACTIVITED = 'Deactivited', + ACTIVATE_CANCELED = 'activate-canceled', + + UIPRESS_ENTERED = 'UI-press-entered', + UIPRESS_EXITED = 'UI-press-exited', + UIPRESS_CANCELED = 'UI-press-canceled', + + HOVER_ENTERED = 'hover-entered', + HOVER_EXITED = 'hover-exited', + HOVER_STAY = 'hover-stay', + HOVER_CANCELED = 'hover-canceled' +} + +/** + * @en + * Xr handle event. + * + * @zh + * xr手柄事件。 + */ +export class XrEventHandle extends Event { + // export class XrEventHandle { + /** + * @en Event trigger + * @zh 事件触发者(左右手柄等) + */ + public deviceType = DeviceType.Other; + + /** + * @en Collision detection point + * @zh 碰撞检测点 + */ + public hitPoint = new Vec3(); + + /** + * @en Controller model + * @zh Controller模型 + */ + public model: Node | null = null; + + /** + * @en Handle events + * @zh 手柄事件 + */ + public eventHandle = 0; + + /** + * @en Trigger Id + * @zh 触发者Id + */ + public triggerId: string | undefined = ""; + + /** + * @en The attached node + * @zh 被附着者节点 + */ + public attachNode: Node | null = null; + + /** + * @en Whether to force grab + * @zh 是否强制抓取 + */ + public forceGrab = true; +} + +/** + * @en Xr 3DUI event type + * @zh xr的3DUI事件类型 + */ +export enum XrUIPressEventType { + XRUI_HOVER_ENTERED = "xrui-hover-entered", + XRUI_HOVER_EXITED = "xrui-hover-exited", + XRUI_HOVER_STAY = "xrui-hover-stay", + XRUI_CLICK = "xrui-click", + XRUI_UNCLICK = "xrui-unclick" +} + +/** + * @en Xr Keyboard event type + * @zh xr的虚拟键盘事件类型 + */ +export enum XrKeyboardEventType { + /** + * @en + * The event type for XR keyboard case switching event + * + * @zh + * XR键盘大小写切换事件 + */ + XR_CAPS_LOCK = 'xr-caps-lock', + + /** + * @en + * The event type for XR keyboard initialization event + * + * @zh + * XR键盘初始化事件 + */ + XR_KEYBOARD_INIT = 'xr-keyboard-init', + + /** + * @en + * The event type for XR keyboard input event + * + * @zh + * XR键盘input事件 + */ + XR_KEYBOARD_INPUT = 'xr-keyboard-input', + + /** + * @en + * The event type for XR keyboard to latin + * + * @zh + * 转latin + */ + TO_LATIN = 'to-latin', + + /** + * @en + * The event type for XR keyboard to symbol + * + * @zh + * 转symbol + */ + TO_SYMBOL = 'to-symbol', + + /** + * @en + * The event type for XR keyboard to math_symbol + * + * @zh + * 转math_symbol + */ + TO_MATH_SYMBOL = 'to-math-symbol', +} + +/** + * @en Xr 3DUI event. + * + * @zh xr的3DUI事件。 + */ +export class XrUIPressEvent extends Event { + /** + * @en Event trigger + * @zh 事件触发者(左右手柄等) + */ + public deviceType = DeviceType.Other; + + /** + * @en Collision detection point + * @zh 碰撞检测点 + */ + public hitPoint = new Vec3(); +} diff --git a/cocos/xr/index.ts b/cocos/xr/index.ts new file mode 100644 index 0000000000..57b3f9f0f5 --- /dev/null +++ b/cocos/xr/index.ts @@ -0,0 +1,31 @@ +/* + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ + +/** + * @packageDocumentation + * @hidden + */ + +export * from './event/xr-event-handle'; diff --git a/editor/assets/chunks/builtin/uniforms/cc-global.chunk b/editor/assets/chunks/builtin/uniforms/cc-global.chunk index 0159581c56..0a4ab4865e 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-global.chunk +++ b/editor/assets/chunks/builtin/uniforms/cc-global.chunk @@ -23,7 +23,7 @@ layout(set = 0, binding = 1) uniform CCCamera { highp mat4 cc_matViewProj; // view-projection matrix highp mat4 cc_matViewProjInv; // inverse view-projection matrix highp vec4 cc_cameraPos; // xyz: camera position - mediump vec4 cc_surfaceTransform; // x: surface transform + mediump vec4 cc_surfaceTransform; // x: surface transform y: unused zw: skybox rotation angle cos/sin value mediump vec4 cc_screenScale; // xy: screen scale, zw: inverse screen scale mediump vec4 cc_exposure; // x: exposure, y: inverse exposure, z: HDR flag, w: inverse standard exposure value mediump vec4 cc_mainLitDir; // xyz: main direcitonal light direction, w: enable shadow diff --git a/editor/assets/chunks/common/math/coordinates.chunk b/editor/assets/chunks/common/math/coordinates.chunk index 76adc0e908..cfa7ff33e4 100644 --- a/editor/assets/chunks/common/math/coordinates.chunk +++ b/editor/assets/chunks/common/math/coordinates.chunk @@ -43,15 +43,21 @@ vec3 CalculateNormalFromTangentSpace(vec3 normalFromTangentSpace, float normalSt normalFromTangentSpace.z * normalize(normal); } +vec3 RotationVecFromAxisY(vec3 v, float cosTheta, float sinTheta) +{ + vec3 result; + result.x = dot(v, vec3(cosTheta, 0.0, -sinTheta)); + result.y = v.y; + result.z = dot(v, vec3(sinTheta, 0.0, cosTheta)); + return result; +} + // rotationAngle: radians, 0-2Pi void RotateTangentAndBinormal(inout vec3 tangent, inout vec3 binormal, vec3 normal, float rotationAngle) { float cosTheta = cos(rotationAngle), sinTheta = sin(rotationAngle); - vec3 T = vec3(0.0), B = vec3(0.0); - B.x = dot(vec3(1.0, 0.0, 0.0), vec3(cosTheta, 0.0, -sinTheta)); - B.z = dot(vec3(1.0, 0.0, 0.0), vec3(sinTheta, 0.0, cosTheta)); - T.x = dot(vec3(0.0, 0.0, 1.0), vec3(cosTheta, 0.0, -sinTheta)); - T.z = dot(vec3(0.0, 0.0, 1.0), vec3(sinTheta, 0.0, cosTheta)); + vec3 B = RotationVecFromAxisY(vec3(1.0, 0.0, 0.0), cosTheta, sinTheta); + vec3 T = RotationVecFromAxisY(vec3(0.0, 0.0, 1.0), cosTheta, sinTheta); vec3 tangentNew, binormalNew; binormalNew.x = dot(B, binormal); diff --git a/editor/assets/chunks/common/texture/cubemap.chunk b/editor/assets/chunks/common/texture/cubemap.chunk index 87fd12895e..7c36653a7d 100644 --- a/editor/assets/chunks/common/texture/cubemap.chunk +++ b/editor/assets/chunks/common/texture/cubemap.chunk @@ -11,8 +11,9 @@ float delta = (dot(dFdx(R), dFdy(R))) * 1000.0; float mipBias = mix(0.0, 5.0, clamp(delta, 0.0, 1.0)); - vec4 biased = fragTextureLod(cc_environment, R, mip + mipBias); - vec4 filtered = texture(cc_environment, R); + vec3 rotationDir = RotationVecFromAxisY(R.xyz, cc_surfaceTransform.z, cc_surfaceTransform.w); + vec4 biased = fragTextureLod(cc_environment, rotationDir, mip + mipBias); + vec4 filtered = texture(cc_environment, rotationDir); #if CC_USE_IBL == IBL_RGBE biased.rgb = unpackRGBE(biased); @@ -34,8 +35,9 @@ #if !CC_SURFACES_USE_LEGACY_COMPATIBLE_LIGHTING && !CC_IBL_CONVOLUTED roughness = pow(roughness, 0.5); #endif - - vec4 envmap = fragTextureLod(cc_environment, R, roughness * (mipCount - 1.0)); + + vec3 rotationDir = RotationVecFromAxisY(R.xyz, cc_surfaceTransform.z, cc_surfaceTransform.w); + vec4 envmap = fragTextureLod(cc_environment, rotationDir, roughness * (mipCount - 1.0)); #if CC_USE_IBL == IBL_RGBE return unpackRGBE(envmap); diff --git a/editor/assets/chunks/legacy/shading-standard-base.chunk b/editor/assets/chunks/legacy/shading-standard-base.chunk index 0a0c91c944..f7223f3fd0 100644 --- a/editor/assets/chunks/legacy/shading-standard-base.chunk +++ b/editor/assets/chunks/legacy/shading-standard-base.chunk @@ -159,10 +159,11 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) { vec3 R = normalize(reflect(-V, N)); + vec3 rotationDir = RotationVecFromAxisY(R.xyz, cc_surfaceTransform.z, cc_surfaceTransform.w); #if USE_REFLECTION_DENOISE && !CC_IBL_CONVOLUTED - vec3 env = GetEnvReflectionWithMipFiltering(R, s.roughness, cc_ambientGround.w, 0.6); + vec3 env = GetEnvReflectionWithMipFiltering(rotationDir, s.roughness, cc_ambientGround.w, 0.6); #else - vec4 envmap = fragTextureLod(cc_environment, R, s.roughness * (cc_ambientGround.w - 1.0)); + vec4 envmap = fragTextureLod(cc_environment, rotationDir, s.roughness * (cc_ambientGround.w - 1.0)); #if CC_USE_IBL == IBL_RGBE vec3 env = unpackRGBE(envmap); diff --git a/editor/assets/effects/builtin-particle-xr-trail.effect b/editor/assets/effects/builtin-particle-xr-trail.effect new file mode 100644 index 0000000000..4472d2e21f --- /dev/null +++ b/editor/assets/effects/builtin-particle-xr-trail.effect @@ -0,0 +1,57 @@ +CCEffect %{ + temporaries: + b1: &b1 + targets: + - blend: true + blendSrc: src_alpha + blendDst: one_minus_src_alpha + blendSrcAlpha: src_alpha + blendDstAlpha: one_minus_src_alpha + d1: &d1 { depthTest: true, depthWrite: false } + r1: &r1 { cullMode: none } + p1: &p1 + mainTexture: { value: white } + mainTiling_Offset: { value: [1, 1, 0, 0] } + frameTile_velLenScale: { value: [1, 1, 0, 0] } + p2: &p2 + <<: *p1 + tintColor: { value: [0.5, 0.5, 0.5, 0.5], editor: { type: color } } + + techniques: + - name: add + passes: + - vert: builtin/internal/particle-trail:vs_main + frag: tinted-fs:add + rasterizerState: *r1 + depthStencilState: *d1 + blendState: *b1 + properties: *p2 +}% + +// TODO: soft particle + +CCProgram tinted-fs %{ + precision mediump float; + #include + + in vec2 uv; + in vec4 color; + #if CC_DRAW_WIRE_FRAME + in vec3 vBarycentric; + #endif + + uniform sampler2D mainTexture; + uniform FragConstants { + vec4 tintColor; + }; + + vec4 add () { + vec4 col = 2.0 * color * tintColor * texture(mainTexture, uv); +#if CC_DRAW_WIRE_FRAME + if (any(lessThan(vBarycentric, vec3(0.02)))) { + col = vec4(0., 1., 1., 1.); + } +#endif + return CCFragOutput(col); + } +}% diff --git a/editor/assets/effects/builtin-particle-xr-trail.effect.meta b/editor/assets/effects/builtin-particle-xr-trail.effect.meta new file mode 100644 index 0000000000..0ef43dd47c --- /dev/null +++ b/editor/assets/effects/builtin-particle-xr-trail.effect.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.5.9", + "importer": "effect", + "imported": true, + "uuid": "e38f81af-70ec-4f7a-b377-767b0ec76377", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/effects/pipeline/skybox.effect b/editor/assets/effects/pipeline/skybox.effect index 446e599179..2f94ab40b1 100644 --- a/editor/assets/effects/pipeline/skybox.effect +++ b/editor/assets/effects/pipeline/skybox.effect @@ -56,15 +56,17 @@ CCProgram sky-fs %{ #include #include #include + #include in mediump vec4 viewDir; uniform samplerCube environmentMap; vec4 frag () { + vec3 rotationDir = RotationVecFromAxisY(viewDir.xyz, cc_surfaceTransform.z, cc_surfaceTransform.w); #if USE_RGBE_CUBEMAP - vec3 c = unpackRGBE(fragTextureLod(environmentMap, viewDir.xyz, 0.0)); + vec3 c = unpackRGBE(fragTextureLod(environmentMap, rotationDir.xyz, 0.0)); #else - vec3 c = SRGBToLinear(fragTextureLod(environmentMap, viewDir.xyz, 0.0).rgb); + vec3 c = SRGBToLinear(fragTextureLod(environmentMap, rotationDir.xyz, 0.0).rgb); #endif return CCFragOutput(vec4(c * cc_ambientSky.w, 1.0)); } diff --git a/editor/assets/effects/surfaces/sky.effect b/editor/assets/effects/surfaces/sky.effect index ee0192e58d..1a75ea6806 100644 --- a/editor/assets/effects/surfaces/sky.effect +++ b/editor/assets/effects/surfaces/sky.effect @@ -35,10 +35,11 @@ CCProgram surface-fragment %{ vec3 c = vec3(1.0); #if CC_USE_IBL vec3 normal = normalize(FSInput_worldNormal); + vec3 rotationDir = RotationVecFromAxisY(normal.xyz, cc_surfaceTransform.z, cc_surfaceTransform.w); #if USE_RGBE_CUBEMAP - c *= unpackRGBE(fragTextureLod(environmentMap, normal.xyz, 0.0)); + c *= unpackRGBE(fragTextureLod(environmentMap, rotationDir.xyz, 0.0)); #else - c *= SRGBToLinear(fragTextureLod(environmentMap, normal.xyz, 0.0).rgb); + c *= SRGBToLinear(fragTextureLod(environmentMap, rotationDir.xyz, 0.0).rgb); #endif #endif return vec4(c * cc_ambientSky.w, 1.0); diff --git a/editor/engine-features/render-config.json b/editor/engine-features/render-config.json index 0b76c5917c..6f2f8eb65d 100644 --- a/editor/engine-features/render-config.json +++ b/editor/engine-features/render-config.json @@ -53,6 +53,12 @@ "category": "2d", "wechatPlugin": true }, + "xr": { + "default": ["xr"], + "label": "i18n:ENGINE.features.xr.label", + "description": "i18n:ENGINE.features.xr.description", + "wechatPlugin": false + }, "ui": { "default": ["ui"], "label": "i18n:ENGINE.features.ui.label", diff --git a/editor/engine-features/types.ts b/editor/engine-features/types.ts index 34c07b84b4..467f787c0e 100644 --- a/editor/engine-features/types.ts +++ b/editor/engine-features/types.ts @@ -7,6 +7,7 @@ export type EngineFeature = | 'graphcis' | '3d' | '2d' + | 'xr' | 'ui' | 'particle' | 'physics' diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index 085c31d493..b8baed93b1 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -915,6 +915,10 @@ module.exports = { label: "Marionette Animation System", description: "Enable the Marionette animation system", }, + xr: { + label: "XR", + description: "Enable the XR function system", + }, custom_pipeline: { label: "Custom Render Pipeline (Experimental)", description: "Enable custom render pipeline", diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index 441849cc2f..2c87782fa2 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -896,6 +896,10 @@ module.exports = { label: "Marionette 动画系统", description: "启用 Marionette 动画系统。", }, + xr: { + label: "XR", + description: "启用 XR 功能系统。", + }, custom_pipeline: { label: "自定义渲染管线(实验)", description: "启用自定义渲染管线。", diff --git a/editor/inspector/components/class.js b/editor/inspector/components/class.js index 52e4de392d..27dbf736d6 100644 --- a/editor/inspector/components/class.js +++ b/editor/inspector/components/class.js @@ -32,7 +32,10 @@ exports.methods = { $group.$header.addEventListener('change', (e) => { const tabNames = Object.keys($group.tabs); const tabName = tabNames[e.target.value || 0]; - $group.querySelectorAll('.tab-content').forEach((child) => { + $group.childNodes.forEach((child) => { + if (!child.classList.contains('tab-content')) { + return; + } if (child.getAttribute('name') === tabName) { child.style.display = 'block'; } else { diff --git a/editor/inspector/utils/prop.js b/editor/inspector/utils/prop.js index 9790167bf6..bb059198c0 100644 --- a/editor/inspector/utils/prop.js +++ b/editor/inspector/utils/prop.js @@ -378,7 +378,10 @@ exports.createTabGroup = function(dump, panel) { $group.$header.addEventListener('change', (e) => { const tabNames = Object.keys($group.tabs); const tabName = tabNames[e.target.value || 0]; - $group.querySelectorAll('.tab-content').forEach((child) => { + $group.childNodes.forEach((child) => { + if (!child.classList.contains('tab-content')) { + return; + } if (child.getAttribute('name') === tabName) { child.style.display = 'block'; } else { diff --git a/exports/xr.ts b/exports/xr.ts new file mode 100644 index 0000000000..5368d95d40 --- /dev/null +++ b/exports/xr.ts @@ -0,0 +1,31 @@ +/* + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ + +/** + * @packageDocumentation + * @hidden + */ + + export * from '../cocos/xr'; diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 4833ca13f8..b2587e651f 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -28,6 +28,7 @@ cc_set_if_undefined(USE_JOB_SYSTEM_TASKFLOW OFF) cc_set_if_undefined(USE_JOB_SYSTEM_TBB OFF) cc_set_if_undefined(USE_PHYSICS_PHYSX OFF) cc_set_if_undefined(USE_MODULES OFF) +cc_set_if_undefined(USE_XR OFF) cc_set_if_undefined(USE_SERVER_MODE OFF) cc_set_if_undefined(USE_PLUGINS ON) cc_set_if_undefined(USE_OCCLUSION_QUERY ON) @@ -203,6 +204,7 @@ cc_inspect_values( USE_PHYSICS_PHYSX USE_JOB_SYSTEM_TBB USE_JOB_SYSTEM_TASKFLOW + USE_XR USE_SERVER_MODE USE_CCACHE CCACHE_EXECUTABLE @@ -526,6 +528,8 @@ cocos_source_files( cocos/platform/interfaces/modules/ISystem.h cocos/platform/interfaces/modules/ISystemWindow.h cocos/platform/interfaces/modules/IVibrator.h + cocos/platform/interfaces/modules/XRCommon.h + cocos/platform/interfaces/modules/IXRInterface.h ) cocos_source_files( @@ -607,6 +611,8 @@ elseif(ANDROID OR OHOS) cocos/platform/java/modules/CommonSystem.h cocos/platform/java/modules/SystemWindow.cpp cocos/platform/java/modules/SystemWindow.h + cocos/platform/java/modules/XRInterface.cpp + cocos/platform/java/modules/XRInterface.h ) endif() @@ -2097,6 +2103,13 @@ if(USE_WEBVIEW) ) endif() +if(USE_XR) + cocos_source_files( + NO_WERROR cocos/bindings/auto/jsb_xr_auto.cpp + cocos/bindings/auto/jsb_xr_auto.h + ) +endif() + if(USE_MIDDLEWARE) cocos_source_files( cocos/editor-support/IOBuffer.cpp @@ -2869,6 +2882,7 @@ function(cc_apply_definations target) $,CC_USE_VIDEO=1,CC_USE_VIDEO=0> $,CC_USE_WEBVIEW=1,CC_USE_WEBVIEW=0> $,CC_USE_AUDIO=1,CC_USE_AUDIO=0> + $,CC_USE_XR=1,CC_USE_XR=0> $,CC_USE_SOCKET=1,CC_USE_SOCKET=0> $,CC_USE_WEBSOCKET_SERVER=1,CC_USE_WEBSOCKET_SERVER=0> $,CC_USE_EDITBOX=1,CC_USE_EDITBOX=0> @@ -2903,6 +2917,17 @@ if(USE_MODULES) cc_apply_definations(ccutils) endif() +if(USE_XR) + cc_xr_apply_definations(${ENGINE_NAME}) + if(USE_MODULES) + cc_xr_apply_definations(ccmath) + cc_xr_apply_definations(cclog) + cc_xr_apply_definations(ccfilesystem) + cc_xr_apply_definations(ccunzip) + cc_xr_apply_definations(ccbindings) + cc_xr_apply_definations(ccutils) + endif() +endif() if(MSVC) set(V8_DIR diff --git a/native/README.md b/native/README.md index bc9a7ee904..9dd432368d 100644 --- a/native/README.md +++ b/native/README.md @@ -20,6 +20,7 @@ System Requirements -------------------------------- - macOS 10.14+ - iOS 11.0+ +- iOS Simulator 13.0+ - 64-bit Windows 7+ - with vulkan 1.0 to 1.2 if want to run with vulkan - Android 4.4+ diff --git a/native/cmake/predefine.cmake b/native/cmake/predefine.cmake index 30446637ec..f1e2509727 100644 --- a/native/cmake/predefine.cmake +++ b/native/cmake/predefine.cmake @@ -220,10 +220,19 @@ function(cc_redirect_property target from_property to_property) endif() endfunction() - -find_program(NODE_EXECUTABLE NAMES node) -find_program(TSC_EXECUTABLE NAMES tsc) -find_program(CCACHE_EXECUTABLE NAMES ccache) +if(NOT DEFINED NODE_EXECUTABLE) + if(DEFINED EDITOR_NODEJS) + set(NODE_EXECUTABLE ${EDITOR_NODEJS}) + else() + find_program(NODE_EXECUTABLE NAMES node) + endif() +endif() +if(NOT DEFINED TSC_EXECUTABLE) + find_program(TSC_EXECUTABLE NAMES tsc) +endif() +if(NOT DEFINED CCACHE_EXECUTABLE) + find_program(CCACHE_EXECUTABLE NAMES ccache) +endif() ## predefined configurations for game applications include(${CMAKE_CURRENT_LIST_DIR}/../../templates/cmake/common.cmake) diff --git a/native/cmake/scripts/plugins_parser.js b/native/cmake/scripts/plugins_parser.js index 4355b4c125..3e8502f66d 100644 --- a/native/cmake/scripts/plugins_parser.js +++ b/native/cmake/scripts/plugins_parser.js @@ -268,3 +268,4 @@ if (cc_config_json_list.length == 0) { fs.writeFileSync(plugin_cmake_output_file, output_lines.join("\n") + "\n", { encoding: 'utf8' }); } } +process.exit(0); \ No newline at end of file diff --git a/native/cocos/2d/renderer/RenderEntity.h b/native/cocos/2d/renderer/RenderEntity.h index c597aebfdc..677cc65e5c 100644 --- a/native/cocos/2d/renderer/RenderEntity.h +++ b/native/cocos/2d/renderer/RenderEntity.h @@ -58,7 +58,7 @@ struct EntityAttrLayout { uint8_t colorA{255}; uint8_t maskMode{0}; uint8_t colorDirtyBit{1}; - uint8_t enabledIndex{1}; + uint8_t enabledIndex{0}; uint8_t useLocal{0}; }; diff --git a/native/cocos/3d/models/SkinningModel.cpp b/native/cocos/3d/models/SkinningModel.cpp index 8943e385b0..c4838c2586 100644 --- a/native/cocos/3d/models/SkinningModel.cpp +++ b/native/cocos/3d/models/SkinningModel.cpp @@ -135,7 +135,7 @@ void SkinningModel::updateTransform(uint32_t stamp) { Vec3::min(v3Min, v31, &v3Min); Vec3::max(v3Max, v32, &v3Max); } - if (_modelBounds->isValid() && _worldBounds) { + if (_modelBounds && _modelBounds->isValid() && _worldBounds) { geometry::AABB::fromPoints(v3Min, v3Max, _modelBounds); _modelBounds->transform(root->getWorldMatrix(), _worldBounds); _worldBoundsDirty = true; diff --git a/native/cocos/application/ApplicationManager.h b/native/cocos/application/ApplicationManager.h index 5d1099782d..dfbd6e751a 100644 --- a/native/cocos/application/ApplicationManager.h +++ b/native/cocos/application/ApplicationManager.h @@ -73,6 +73,8 @@ private: #define CC_CURRENT_APPLICATION_SAFE() CC_APPLICATION_MANAGER()->getCurrentAppSafe() #define CC_CURRENT_ENGINE() CC_CURRENT_APPLICATION_SAFE()->getEngine() #define CC_GET_PLATFORM_INTERFACE(intf) CC_CURRENT_ENGINE()->getInterface() +#define CC_GET_XR_INTERFACE() BasePlatform::getPlatform()->getInterface() + /** * @brief Called at the user-defined main entry */ diff --git a/native/cocos/bindings/auto/jsb_xr_auto.cpp b/native/cocos/bindings/auto/jsb_xr_auto.cpp new file mode 100644 index 0000000000..e69de29bb2 diff --git a/native/cocos/bindings/auto/jsb_xr_auto.h b/native/cocos/bindings/auto/jsb_xr_auto.h new file mode 100644 index 0000000000..e69de29bb2 diff --git a/native/cocos/bindings/event/EventDispatcher.cpp b/native/cocos/bindings/event/EventDispatcher.cpp index 83addf773e..bafaaa14f4 100644 --- a/native/cocos/bindings/event/EventDispatcher.cpp +++ b/native/cocos/bindings/event/EventDispatcher.cpp @@ -37,6 +37,7 @@ ccstd::vector jsTouchObjPool; se::Object *jsTouchObjArray = nullptr; se::Object *jsMouseEventObj = nullptr; se::Object *jsKeyboardEventObj = nullptr; +se::Object *jsControllerEventArray = nullptr; se::Object *jsResizeEventObj = nullptr; se::Object *jsOrientationEventObj = nullptr; bool inited = false; @@ -72,6 +73,12 @@ void EventDispatcher::destroy() { jsTouchObjArray = nullptr; } + if (jsControllerEventArray != nullptr) { + jsControllerEventArray->unroot(); + jsControllerEventArray->decRef(); + jsControllerEventArray = nullptr; + } + if (jsMouseEventObj != nullptr) { jsMouseEventObj->unroot(); jsMouseEventObj->decRef(); @@ -237,6 +244,56 @@ void EventDispatcher::dispatchKeyboardEvent(const KeyboardEvent &keyboardEvent) EventDispatcher::doDispatchJsEvent(eventName, args); } +void EventDispatcher::dispatchControllerEvent(const ControllerEvent &controllerEvent) { + se::AutoHandleScope scope; + if (!jsControllerEventArray) { + jsControllerEventArray = se::Object::createArrayObject(0); + jsControllerEventArray->root(); + } + + const char *eventName = "onControllerInput"; + if (controllerEvent.type == ControllerEvent::Type::HANDLE) { + eventName = "onHandleInput"; + } + uint32_t controllerIndex = 0; + jsControllerEventArray->setProperty("length", se::Value(static_cast(controllerEvent.controllerInfos.size()))); + + for (const auto &controller : controllerEvent.controllerInfos) { + se::HandleObject jsController{se::Object::createPlainObject()}; + jsController->setProperty("id", se::Value(controller->napdId)); + + se::HandleObject jsButtonInfoList{se::Object::createArrayObject(static_cast(controller->buttonInfos.size()))}; + + uint32_t buttonIndex = 0; + for (const auto &buttonInfo : controller->buttonInfos) { + se::HandleObject jsButtonInfo{se::Object::createPlainObject()}; + jsButtonInfo->setProperty("code", se::Value(static_cast(buttonInfo.key))); + jsButtonInfo->setProperty("isPressed", se::Value(static_cast(buttonInfo.isPress))); + jsButtonInfoList->setArrayElement(buttonIndex, se::Value(jsButtonInfo)); + buttonIndex++; + } + + se::HandleObject jsAxisInfoList{se::Object::createArrayObject(static_cast(controller->axisInfos.size()))}; + + uint32_t axisIndex = 0; + for (const auto &axisInfo : controller->axisInfos) { + se::HandleObject jsAxisInfo{se::Object::createPlainObject()}; + jsAxisInfo->setProperty("code", se::Value(static_cast(axisInfo.axis))); + jsAxisInfo->setProperty("value", se::Value(axisInfo.value)); + jsAxisInfoList->setArrayElement(axisIndex, se::Value(jsAxisInfo)); + axisIndex++; + } + jsController->setProperty("axisInfoList", se::Value(jsAxisInfoList)); + jsController->setProperty("buttonInfoList", se::Value(jsButtonInfoList)); + + jsControllerEventArray->setArrayElement(controllerIndex, se::Value(jsController)); + controllerIndex++; + } + se::ValueArray args; + args.emplace_back(se::Value(jsControllerEventArray)); + EventDispatcher::doDispatchJsEvent(eventName, args); +} + void EventDispatcher::dispatchTickEvent(float /*dt*/) { if (!se::ScriptEngine::getInstance()->isValid()) { return; diff --git a/native/cocos/bindings/event/EventDispatcher.h b/native/cocos/bindings/event/EventDispatcher.h index 0444b279c1..e61550e681 100644 --- a/native/cocos/bindings/event/EventDispatcher.h +++ b/native/cocos/bindings/event/EventDispatcher.h @@ -26,6 +26,7 @@ #pragma once #include +#include #include "base/std/container/string.h" #include "base/std/container/unordered_map.h" #include "base/std/container/vector.h" @@ -44,7 +45,8 @@ enum class OSEventType { DEVICE_OSEVENT = 4, WINDOW_OSEVENT = 5, APP_OSEVENT = 6, - UNKNOWN_OSEVENT = 7 + CONTROLLER_OSEVENT = 7, + UNKNOWN_OSEVENT = 8 }; class OSEvent { @@ -115,6 +117,66 @@ public: Type type = Type::UNKNOWN; }; +enum class StickKeyCode { + UNDEFINE = 0, + A, + B, + X, + Y, + L1, + R1, + MINUS, + PLUS, + L3, + R3, + MENU, + START, + TRIGGER_LEFT, + TRIGGER_RIGHT, +}; + +enum class StickAxisCode { + UNDEFINE = 0, + X, + Y, + LEFT_STICK_X, + LEFT_STICK_Y, + RIGHT_STICK_X, + RIGHT_STICK_Y, + L2, + R2, + LEFT_GRIP, + RIGHT_GRIP, +}; + +struct ControllerInfo { + struct AxisInfo { + StickAxisCode axis{StickAxisCode::UNDEFINE}; + float value{0.F}; + AxisInfo(StickAxisCode axis, float value) : axis(axis), value(value) {} + }; + struct ButtonInfo { + StickKeyCode key{StickKeyCode::UNDEFINE}; + bool isPress{false}; + ButtonInfo(StickKeyCode key, bool isPress) : key(key), isPress(isPress) {} + }; + + int napdId{0}; + std::vector axisInfos; + std::vector buttonInfos; +}; + +struct ControllerEvent : public OSEvent { + CONSTRUCT_EVENT(ControllerEvent, OSEventType::CONTROLLER_OSEVENT) + enum class Type { + GAMEPAD, + HANDLE, + UNKNOWN + }; + Type type = Type::UNKNOWN; + std::vector> controllerInfos; +}; + class MouseEvent : public OSEvent { public: CONSTRUCT_EVENT(MouseEvent, OSEventType::MOUSE_OSEVENT) @@ -259,6 +321,7 @@ public: static void dispatchTouchEvent(const TouchEvent &touchEvent); static void dispatchMouseEvent(const MouseEvent &mouseEvent); static void dispatchKeyboardEvent(const KeyboardEvent &keyboardEvent); + static void dispatchControllerEvent(const ControllerEvent &controllerEvent); static void dispatchTickEvent(float dt); static void dispatchResizeEvent(int width, int height); static void dispatchOrientationChangeEvent(int orientation); @@ -277,9 +340,9 @@ public: static void removeAllCustomEventListeners(const ccstd::string &eventName); static void removeAllEventListeners(); static void dispatchCustomEvent(const CustomEvent &event); + static void doDispatchJsEvent(const char *jsFunctionName, const std::vector &args); private: - static void doDispatchJsEvent(const char *jsFunctionName, const std::vector &args); static void dispatchCustomEvent(const char *eventName, int argNum, ...); struct Node { diff --git a/native/cocos/bindings/jswrapper/ValueArrayPool.cpp b/native/cocos/bindings/jswrapper/ValueArrayPool.cpp index 752a2bccff..944f8289f1 100644 --- a/native/cocos/bindings/jswrapper/ValueArrayPool.cpp +++ b/native/cocos/bindings/jswrapper/ValueArrayPool.cpp @@ -26,6 +26,7 @@ #include "ValueArrayPool.h" #include "base/Macros.h" +#include "base/memory/Memory.h" #include "config.h" namespace se { @@ -41,14 +42,15 @@ ValueArrayPool::ValueArrayPool() { } } -ValueArray &ValueArrayPool::get(uint32_t argc) { +ValueArray &ValueArrayPool::get(uint32_t argc, bool &outNeedDelete) { if (SE_UNLIKELY(_depth >= _pools.size())) { - auto *ptr = _pools.data(); - _pools.resize(_depth + 1); - CC_ASSERT(_pools.data() == ptr); - initPool(_depth); + outNeedDelete = true; + auto *ret = ccnew ValueArray(); + ret->resize(argc); + return *ret; } + outNeedDelete = false; CC_ASSERT(argc <= MAX_ARGS); auto &ret = _pools[_depth][argc]; CC_ASSERT(ret.size() == argc); diff --git a/native/cocos/bindings/jswrapper/ValueArrayPool.h b/native/cocos/bindings/jswrapper/ValueArrayPool.h index 066ee0aff3..82c66090d6 100644 --- a/native/cocos/bindings/jswrapper/ValueArrayPool.h +++ b/native/cocos/bindings/jswrapper/ValueArrayPool.h @@ -33,8 +33,8 @@ namespace se { class CallbackDepthGuard final { public: - CallbackDepthGuard(ValueArray &arr, uint32_t &depth) - : _arr(arr), _depth(depth) { + CallbackDepthGuard(ValueArray &arr, uint32_t &depth, bool needDelete) + : _arr(arr), _depth(depth), _needDelete(needDelete) { ++_depth; } @@ -43,11 +43,15 @@ public: for (auto &e : _arr) { e.setUndefined(); } + if (_needDelete) { + delete &_arr; + } } private: ValueArray &_arr; uint32_t &_depth; + const bool _needDelete{false}; }; class ValueArrayPool final { @@ -56,7 +60,7 @@ public: ValueArrayPool(); - ValueArray &get(uint32_t argc); + ValueArray &get(uint32_t argc, bool &outNeedDelete); uint32_t _depth{0}; diff --git a/native/cocos/bindings/jswrapper/sm/HelperMacros.h b/native/cocos/bindings/jswrapper/sm/HelperMacros.h index 23bd508e0d..ad6f356bc0 100644 --- a/native/cocos/bindings/jswrapper/sm/HelperMacros.h +++ b/native/cocos/bindings/jswrapper/sm/HelperMacros.h @@ -99,8 +99,9 @@ void printJSBInvokeAtFrame(int n); JS::CallArgs _argv = JS::CallArgsFromVp(argc, _vp); \ JS::RootedObject _thizObj(_cx); \ _argv.computeThis(_cx, &_thizObj); \ - se::ValueArray &args = se::gValueArrayPool.get(argc); \ - se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; \ + bool needDeleteValueArray{false}; \ + se::ValueArray &args = se::gValueArrayPool.get(argc, needDeleteValueArray); \ + se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth, needDeleteValueArray}; \ se::internal::jsToSeArgs(_cx, argc, _argv, args); \ se::PrivateObjectBase *privateObject = static_cast(se::internal::getPrivate(_cx, _thizObj, 0)); \ se::Object *thisObject = reinterpret_cast(se::internal::getPrivate(_cx, _thizObj, 1)); \ @@ -155,8 +156,9 @@ void printJSBInvokeAtFrame(int n); JsbInvokeScope(#funcName); \ bool ret = false; \ JS::CallArgs _argv = JS::CallArgsFromVp(argc, _vp); \ - se::ValueArray &args = se::gValueArrayPool.get(argc); \ - se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; \ + bool needDeleteValueArray{false}; \ + se::ValueArray &args = se::gValueArrayPool.get(argc, needDeleteValueArray); \ + se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth, needDeleteValueArray}; \ se::internal::jsToSeArgs(_cx, argc, _argv, args); \ se::Object *thisObject = se::Object::_createJSObjectForConstructor(cls, _argv); \ thisObject->_setFinalizeCallback(finalizeCb##Registry); \ @@ -204,8 +206,9 @@ void printJSBInvokeAtFrame(int n); _argv.computeThis(_cx, &_thizObj); \ se::PrivateObjectBase *privateObject = static_cast(se::internal::getPrivate(_cx, _thizObj, 0)); \ se::Object *thisObject = reinterpret_cast(se::internal::getPrivate(_cx, _thizObj, 1)); \ - se::ValueArray &args = se::gValueArrayPool.get(1); \ - se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; \ + bool needDeleteValueArray{false}; \ + se::ValueArray &args = se::gValueArrayPool.get(1, needDeleteValueArray); \ + se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth, needDeleteValueArray}; \ se::Value &data{args[0]}; \ se::internal::jsToSeValue(_cx, _argv[0], &data); \ se::State state(thisObject, privateObject, args); \ diff --git a/native/cocos/bindings/jswrapper/v8/HelperMacros.h b/native/cocos/bindings/jswrapper/v8/HelperMacros.h index 54f797be97..6ef8755ac9 100644 --- a/native/cocos/bindings/jswrapper/v8/HelperMacros.h +++ b/native/cocos/bindings/jswrapper/v8/HelperMacros.h @@ -112,8 +112,9 @@ void printJSBInvokeAtFrame(int n); bool ret = false; \ v8::Isolate *_isolate = _v8args.GetIsolate(); \ v8::HandleScope _hs(_isolate); \ - se::ValueArray &args = se::gValueArrayPool.get(_v8args.Length()); \ - se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; \ + bool needDeleteValueArray{false}; \ + se::ValueArray &args = se::gValueArrayPool.get(_v8args.Length(), needDeleteValueArray); \ + se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth, needDeleteValueArray}; \ se::internal::jsToSeArgs(_v8args, args); \ se::Object *thisObject = se::internal::getPrivate(_isolate, _v8args.This()); \ se::State state(thisObject, args); \ @@ -156,8 +157,9 @@ void printJSBInvokeAtFrame(int n); v8::Isolate *_isolate = _v8args.GetIsolate(); \ v8::HandleScope _hs(_isolate); \ bool ret = true; \ - se::ValueArray &args = se::gValueArrayPool.get(_v8args.Length()); \ - se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; \ + bool needDeleteValueArray{false}; \ + se::ValueArray &args = se::gValueArrayPool.get(_v8args.Length(), needDeleteValueArray); \ + se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth, needDeleteValueArray}; \ se::internal::jsToSeArgs(_v8args, args); \ se::Object *thisObject = se::Object::_createJSObject(cls, _v8args.This()); \ thisObject->_setFinalizeCallback(_SE(finalizeCb)); \ @@ -197,8 +199,9 @@ void printJSBInvokeAtFrame(int n); v8::HandleScope _hs(_isolate); \ bool ret = true; \ se::Object *thisObject = se::internal::getPrivate(_isolate, _v8args.This()); \ - se::ValueArray &args = se::gValueArrayPool.get(1); \ - se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; \ + bool needDeleteValueArray{false}; \ + se::ValueArray &args = se::gValueArrayPool.get(1, needDeleteValueArray); \ + se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth, needDeleteValueArray}; \ se::Value &data{args[0]}; \ se::internal::jsToSeValue(_isolate, _value, &data); \ se::State state(thisObject, args); \ diff --git a/native/cocos/bindings/manual/jsb_module_register.cpp b/native/cocos/bindings/manual/jsb_module_register.cpp index 2c6b736aa0..95679ccc57 100644 --- a/native/cocos/bindings/manual/jsb_module_register.cpp +++ b/native/cocos/bindings/manual/jsb_module_register.cpp @@ -61,6 +61,10 @@ #include "cocos/bindings/manual/jsb_audio_manual.h" #endif +#if CC_USE_XR + #include "cocos/bindings/auto/jsb_xr_auto.h" +#endif + #if (CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_MACOS) #include "cocos/bindings/manual/JavaScriptObjCBridge.h" #endif @@ -153,6 +157,10 @@ bool jsb_register_all_modules() { se->addRegisterCallback(register_all_audio_manual); #endif +#if CC_USE_XR + se->addRegisterCallback(register_all_xr); +#endif + #if CC_USE_SOCKET se->addRegisterCallback(register_all_websocket); se->addRegisterCallback(register_all_socketio); diff --git a/native/cocos/bindings/sebind/class_v8.cpp b/native/cocos/bindings/sebind/class_v8.cpp index a13aaefc96..ad79f3827e 100644 --- a/native/cocos/bindings/sebind/class_v8.cpp +++ b/native/cocos/bindings/sebind/class_v8.cpp @@ -33,8 +33,9 @@ void genericFunction(const v8::FunctionCallbackInfo &v8args) { bool ret = false; v8::Isolate *isolate = v8args.GetIsolate(); v8::HandleScope handleScope(isolate); - se::ValueArray &args = se::gValueArrayPool.get(v8args.Length()); - se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; + bool needDeleteValueArray{false}; + se::ValueArray &args = se::gValueArrayPool.get(v8args.Length(), needDeleteValueArray); + se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth, needDeleteValueArray}; se::internal::jsToSeArgs(v8args, args); auto *thisObject = reinterpret_cast(se::internal::getPrivate(isolate, v8args.This())); se::State state(thisObject, args); diff --git a/native/cocos/bindings/sebind/class_v8.h b/native/cocos/bindings/sebind/class_v8.h index ff084fc74a..00e30f3016 100644 --- a/native/cocos/bindings/sebind/class_v8.h +++ b/native/cocos/bindings/sebind/class_v8.h @@ -52,8 +52,9 @@ void genericConstructor(const v8::FunctionCallbackInfo &v8args) { v8::Isolate *isolate = v8args.GetIsolate(); v8::HandleScope handleScope(isolate); std::optional ret; - se::ValueArray &args = se::gValueArrayPool.get(v8args.Length()); - se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; + bool needDeleteValueArray{false}; + se::ValueArray &args = se::gValueArrayPool.get(v8args.Length(), needDeleteValueArray); + se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth, needDeleteValueArray}; se::internal::jsToSeArgs(v8args, args); auto *self = reinterpret_cast(v8args.Data().IsEmpty() ? nullptr : v8args.Data().As()->Value()); se::Object *thisObject = se::Object::_createJSObject(self->kls, v8args.This()); @@ -97,8 +98,9 @@ void genericAccessorSet(v8::Local /*prop*/, v8::Local jsVal v8::HandleScope handleScope(isolate); bool ret = true; auto *thisObject = reinterpret_cast(se::internal::getPrivate(isolate, v8args.This())); - se::ValueArray &args = se::gValueArrayPool.get(1); - se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; + bool needDeleteValueArray{false}; + se::ValueArray &args = se::gValueArrayPool.get(1, needDeleteValueArray); + se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth, needDeleteValueArray}; se::Value &data{args[0]}; se::internal::jsToSeValue(isolate, jsVal, &data); se::State state(thisObject, args); diff --git a/native/cocos/core/Root.cpp b/native/cocos/core/Root.cpp index 465c575e65..e2d7888f89 100644 --- a/native/cocos/core/Root.cpp +++ b/native/cocos/core/Root.cpp @@ -27,6 +27,8 @@ #include "2d/renderer/Batcher2d.h" #include "core/event/CallbacksInvoker.h" #include "core/event/EventTypesToJS.h" +#include "platform/BasePlatform.h" +#include "platform/java/modules/XRInterface.h" #include "profiler/Profiler.h" #include "renderer/gfx-base/GFXDef.h" #include "renderer/gfx-base/GFXDevice.h" @@ -70,6 +72,7 @@ Root::~Root() { void Root::initialize(gfx::Swapchain *swapchain) { _swapchain = swapchain; + _xr = CC_GET_XR_INTERFACE(); gfx::RenderPassInfo renderPassInfo; @@ -119,6 +122,11 @@ void Root::destroy() { void Root::resize(uint32_t width, uint32_t height) { for (const auto &window : _windows) { if (window->getSwapchain()) { + if (_xr) { + // xr, window's width and height should not change by device + width = window->getWidth(); + height = window->getHeight(); + } window->resize(width, height); } } @@ -225,6 +233,15 @@ public: bool isOcclusionQueryEnabled() const override { return pipeline->isOcclusionQueryEnabled(); } + + void resetRenderQueue(bool reset) override { + pipeline->resetRenderQueue(reset); + } + + bool isRenderQueueReset() const override { + return pipeline->isRenderQueueReset(); + } + pipeline::RenderPipeline *pipeline = nullptr; }; @@ -306,20 +323,7 @@ void Root::resetCumulativeTime() { _cumulativeTime = 0; } -void Root::frameMove(float deltaTime, int32_t totalFrames) { - CCObject::deferredDestroy(); - - _frameTime = deltaTime; - - ++_frameCount; - _cumulativeTime += deltaTime; - _fpsTime += deltaTime; - if (_fpsTime > 1.0F) { - _fps = _frameCount; - _frameCount = 0; - _fpsTime = 0.0; - } - +void Root::frameMoveBegin() { for (const auto &scene : _scenes) { scene->removeBatches(); } @@ -330,7 +334,10 @@ void Root::frameMove(float deltaTime, int32_t totalFrames) { // _cameraList.clear(); - for (const auto &window : _windows) { +} + +void Root::frameMoveProcess(bool isNeedUpdateScene, int32_t totalFrames, const ccstd::vector> &windows) { + for (const auto &window : windows) { window->extractRenderCameras(_cameraList); } @@ -345,12 +352,18 @@ void Root::frameMove(float deltaTime, int32_t totalFrames) { _batcher->uploadBuffers(); } - for (const auto &scene : _scenes) { - scene->update(stamp); + if (isNeedUpdateScene) { + for (const auto &scene : _scenes) { + scene->update(stamp); + } } CC_PROFILER_UPDATE; + } +} +void Root::frameMoveEnd() { + if (_pipelineRuntime != nullptr && !_cameraList.empty()) { _eventProcessor->emit(EventTypesToJS::DIRECTOR_BEFORE_COMMIT, this); std::stable_sort(_cameraList.begin(), _cameraList.end(), [](const auto *a, const auto *b) { @@ -376,6 +389,29 @@ void Root::frameMove(float deltaTime, int32_t totalFrames) { } } +void Root::frameMove(float deltaTime, int32_t totalFrames) { + CCObject::deferredDestroy(); + + _frameTime = deltaTime; + + ++_frameCount; + _cumulativeTime += deltaTime; + _fpsTime += deltaTime; + if (_fpsTime > 1.0F) { + _fps = _frameCount; + _frameCount = 0; + _fpsTime = 0.0; + } + + if (_xr) { + doXRFrameMove(totalFrames); + } else { + frameMoveBegin(); + frameMoveProcess(true, totalFrames, _windows); + frameMoveEnd(); + } +} + scene::RenderWindow *Root::createWindow(scene::IRenderWindowInfo &info) { IntrusivePtr window = ccnew scene::RenderWindow(); @@ -453,4 +489,91 @@ void Root::destroyScenes() { _scenes.clear(); } +void Root::doXRFrameMove(int32_t totalFrames) { + if (_xr->isRenderAllowable()) { + bool isSceneUpdated = false; + int viewCount = _xr->getXRConfig(xr::XRConfigKey::VIEW_COUNT).getInt(); + for (int xrEye = 0; xrEye < viewCount; xrEye++) { + _xr->beginRenderEyeFrame(xrEye); + + ccstd::vector> allCameras; + for (const auto &window : _windows) { + const ccstd::vector> &wndCams = window->getCameras(); + allCameras.insert(allCameras.end(), wndCams.begin(), wndCams.end()); + } + + // when choose PreEyeCamera, only hmd has PoseTracker + // draw left eye change hmd node's position to -ipd/2 | draw right eye change hmd node's position to ipd/2 + for (const auto &camera : allCameras) { + if (camera->getTrackingType() != cc::scene::TrackingType::NO_TRACKING) { + Node *camNode = camera->getNode(); + if (camNode) { + const auto &viewPosition = _xr->getHMDViewPosition(xrEye, static_cast(camera->getTrackingType())); + camNode->setPosition({viewPosition[0], viewPosition[1], viewPosition[2]}); + } + } + } + + frameMoveBegin(); + //condition1: mainwindow has left camera && right camera, + //but we only need left/right camera when in left/right eye loop + //condition2: main camera draw twice + ccstd::vector> xrWindows; + for (const auto &window : _windows) { + if (window->getSwapchain()) { + // not rt + _xr->bindXREyeWithRenderWindow(window, static_cast(xrEye)); + } + xrWindows.emplace_back(window); + } + + bool isNeedUpdateScene = xrEye == static_cast(xr::XREye::LEFT) || (xrEye == static_cast(xr::XREye::RIGHT) && !isSceneUpdated); + frameMoveProcess(isNeedUpdateScene, totalFrames, xrWindows); + auto camIter = _cameraList.begin(); + while (camIter != _cameraList.end()) { + scene::Camera *cam = *camIter; + bool isMismatchedCam = + (static_cast(xrEye) == xr::XREye::LEFT && cam->getCameraType() == scene::CameraType::RIGHT_EYE) || + (static_cast(xrEye) == xr::XREye::RIGHT && cam->getCameraType() == scene::CameraType::LEFT_EYE); + if (isMismatchedCam) { + // currently is left eye loop, so right camera do not need active + camIter = _cameraList.erase(camIter); + } else { + camIter++; + } + } + + if (_pipelineRuntime != nullptr && !_cameraList.empty()) { + if (isNeedUpdateScene) { + isSceneUpdated = true; + // only one eye enable culling (without other cameras) + if (_cameraList.size() == 1 && _cameraList[0]->getTrackingType() != cc::scene::TrackingType::NO_TRACKING) { + _cameraList[0]->setCullingEnable(true); + _pipelineRuntime->resetRenderQueue(true); + } + } else { + // another eye disable culling (without other cameras) + if (_cameraList.size() == 1 && _cameraList[0]->getTrackingType() != cc::scene::TrackingType::NO_TRACKING) { + _cameraList[0]->setCullingEnable(false); + _pipelineRuntime->resetRenderQueue(false); + } + } + } + + frameMoveEnd(); + _xr->endRenderEyeFrame(xrEye); + } + // recovery to normal status (condition: xr scene jump to normal scene) + if (_pipelineRuntime) { + _pipelineRuntime->resetRenderQueue(true); + } + + for (scene::Camera *cam : _cameraList) { + cam->setCullingEnable(true); + } + } else { + CC_LOG_WARNING("[XR] isRenderAllowable is false !!!"); + } +} + } // namespace cc diff --git a/native/cocos/core/Root.h b/native/cocos/core/Root.h index 75825f49b9..e36b3e2dd6 100644 --- a/native/cocos/core/Root.h +++ b/native/cocos/core/Root.h @@ -2,7 +2,7 @@ Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. http://www.cocos.com - + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated engine source code (the "Software"), a limited, worldwide, royalty-free, non-assignable, revocable and non-exclusive license @@ -10,10 +10,10 @@ not use Cocos Creator software for developing other software or tools that's used for developing games. You are not granted to publish, distribute, sublicense, and/or sell copies of Cocos Creator. - + The software or tools in this License Agreement are licensed, not sold. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -277,6 +277,11 @@ public: inline CallbacksInvoker *getEventProcessor() const { return _eventProcessor; } private: + void frameMoveBegin(); + void frameMoveProcess(bool isNeedUpdateScene, int32_t totalFrames, const ccstd::vector> &windows); + void frameMoveEnd(); + void doXRFrameMove(int32_t totalFrames); + gfx::Device *_device{nullptr}; gfx::Swapchain *_swapchain{nullptr}; Batcher2d *_batcher{nullptr}; @@ -298,6 +303,7 @@ private: bool _useDeferredPipeline{false}; bool _usesCustomPipeline{false}; CallbacksInvoker *_eventProcessor{nullptr}; + IXRInterface *_xr{nullptr}; // Cache ccstd::vector to avoid allocate every frame in frameMove ccstd::vector _cameraList; diff --git a/native/cocos/core/scene-graph/Node.cpp b/native/cocos/core/scene-graph/Node.cpp index ff6ba00aa2..790fb492b5 100644 --- a/native/cocos/core/scene-graph/Node.cpp +++ b/native/cocos/core/scene-graph/Node.cpp @@ -67,6 +67,12 @@ Node::Node(const ccstd::string &name) { Node::~Node() { CC_SAFE_DELETE(_eventProcessor); + if (!_children.empty()) { + // Reset children's _parent to nullptr to avoid dangerous pointer + for (const auto &child : _children) { + child->_parent = nullptr; + } + } } void Node::onBatchCreated(bool dontChildPrefab) { diff --git a/native/cocos/engine/Engine.cpp b/native/cocos/engine/Engine.cpp index bcf21e6b38..952bc249d9 100644 --- a/native/cocos/engine/Engine.cpp +++ b/native/cocos/engine/Engine.cpp @@ -323,6 +323,9 @@ bool Engine::handleEvent(const OSEvent &ev) { } else if (type == OSEventType::KEYBOARD_OSEVENT) { cc::EventDispatcher::dispatchKeyboardEvent(OSEvent::castEvent(ev)); isHandled = true; + } else if (type == OSEventType::CONTROLLER_OSEVENT) { + cc::EventDispatcher::dispatchControllerEvent(OSEvent::castEvent(ev)); + isHandled = true; } else if (type == OSEventType::CUSTOM_OSEVENT) { cc::EventDispatcher::dispatchCustomEvent(OSEvent::castEvent(ev)); isHandled = true; diff --git a/native/cocos/platform/BasePlatform.h b/native/cocos/platform/BasePlatform.h index 423ffa12db..6f5eacb82f 100644 --- a/native/cocos/platform/BasePlatform.h +++ b/native/cocos/platform/BasePlatform.h @@ -130,7 +130,18 @@ public: return intf; } } - CC_ASSERT(false); + return nullptr; + } + + template + std::enable_if_t::value, T *> + getInterface() { + for (const auto &it : _osInterfaces) { + T *intf = dynamic_cast(it.get()); + if (intf) { + return intf; + } + } return nullptr; } diff --git a/native/cocos/platform/android/AndroidPlatform.cpp b/native/cocos/platform/android/AndroidPlatform.cpp index 8d5e6658dc..5924866986 100644 --- a/native/cocos/platform/android/AndroidPlatform.cpp +++ b/native/cocos/platform/android/AndroidPlatform.cpp @@ -25,6 +25,7 @@ #include +#include "application/ApplicationManager.h" #include "base/Log.h" #include "base/memory/Memory.h" #include "bindings/event/CustomEventTypes.h" @@ -42,8 +43,7 @@ #include "platform/java/modules/Network.h" #include "platform/java/modules/SystemWindow.h" #include "platform/java/modules/Vibrator.h" - -#include "bindings/event/EventDispatcher.h" +#include "platform/java/modules/XRInterface.h" #include "paddleboat.h" @@ -63,10 +63,10 @@ #define INPUT_ACTION_COUNT 6 -//Interval time per frame, in milliseconds +// Interval time per frame, in milliseconds #define LOW_FREQUENCY_TIME_INTERVAL 50 -//Maximum runtime of game threads while in the background, in seconds +// Maximum runtime of game threads while in the background, in seconds #define LOW_FREQUENCY_EXPIRED_DURATION_SECONDS 60 #define CC_ENABLE_SUSPEND_GAME_THREAD true @@ -298,8 +298,17 @@ public: _launched = true; if (cocos_main(0, nullptr) != 0) { CC_LOG_ERROR("AndroidPlatform: Launch game failed!"); + } else { + IXRInterface *xr = CC_GET_XR_INTERFACE(); + if (xr) { + xr->onRenderResume(); + } } } else { + IXRInterface *xr = CC_GET_XR_INTERFACE(); + if (xr) { + xr->onRenderResume(); + } cc::CustomEvent event; event.name = EVENT_RECREATE_WINDOW; event.args->ptrVal = reinterpret_cast(_androidPlatform->_app->window); @@ -311,6 +320,10 @@ public: _hasWindow = false; // The window is going away -- kill the surface CC_LOG_DEBUG("AndroidPlatform: APP_CMD_TERM_WINDOW"); + IXRInterface *xr = CC_GET_XR_INTERFACE(); + if (xr) { + xr->onRenderPause(); + } cc::CustomEvent event; event.name = EVENT_DESTROY_WINDOW; event.args->ptrVal = reinterpret_cast(_androidPlatform->_app->window); @@ -336,6 +349,10 @@ public: } case APP_CMD_DESTROY: { CC_LOG_INFO("AndroidPlatform: APP_CMD_DESTROY"); + IXRInterface *xr = _androidPlatform->getInterface(); + if (xr) { + xr->onRenderDestroy(); + } WindowEvent ev; ev.type = WindowEvent::Type::CLOSE; _androidPlatform->dispatchEvent(ev); @@ -479,6 +496,14 @@ void gameControllerStatusCallback(const int32_t controllerIndex, AndroidPlatform::~AndroidPlatform() = default; int AndroidPlatform::init() { +#if CC_USE_XR + registerInterface(std::make_shared()); +#endif + IXRInterface *xr = CC_GET_XR_INTERFACE(); + if (xr) { + JniHelper::getEnv(); + xr->initialize(JniHelper::getJavaVM(), getActivity()); + } cc::FileUtilsAndroid::setassetmanager(_app->activity->assetManager); _inputProxy = ccnew GameInputProxy(this); _inputProxy->registerAppEventCallback([this](int32_t cmd) { @@ -491,6 +516,13 @@ int AndroidPlatform::init() { _lowFrequencyTimer.reset(); _loopTimeOut = LOW_FREQUENCY_TIME_INTERVAL; _isLowFrequencyLoopEnabled = true; + IXRInterface *xr = getInterface(); + bool isXRInstanceCreated = xr && xr->getXRConfig(xr::XRConfigKey::INSTANCE_CREATED).getBool(); + if (!isXRInstanceCreated) { + // xr will not sleep, -1 we will block forever waiting for events. + _loopTimeOut = -1; + _isLowFrequencyLoopEnabled = false; + } } }); _app->userData = _inputProxy; @@ -523,6 +555,7 @@ int32_t AndroidPlatform::run(int /*argc*/, const char ** /*argv*/) { } int32_t AndroidPlatform::loop() { + IXRInterface *xr = getInterface(); while (true) { int events; struct android_poll_source *source; @@ -540,9 +573,13 @@ int32_t AndroidPlatform::loop() { return 0; } } + + if (xr && !xr->platformLoopStart()) continue; _inputProxy->handleInput(); - if (_inputProxy->isAnimating()) { + if (_inputProxy->isAnimating() && (xr ? xr->getXRConfig(xr::XRConfigKey::SESSION_RUNNING).getBool() : true)) { + if (xr) xr->beginRenderFrame(); runTask(); + if (xr) xr->endRenderFrame(); if (_inputProxy->isActive()) { flushTasksOnGameThreadAtForegroundJNI(); } @@ -551,13 +588,14 @@ int32_t AndroidPlatform::loop() { #if CC_ENABLE_SUSPEND_GAME_THREAD if (_isLowFrequencyLoopEnabled) { - //Suspend a game thread after it has been running in the background for a specified amount of time + // Suspend a game thread after it has been running in the background for a specified amount of time if (_lowFrequencyTimer.getSeconds() > LOW_FREQUENCY_EXPIRED_DURATION_SECONDS) { _isLowFrequencyLoopEnabled = false; _loopTimeOut = -1; } } #endif + if (xr) xr->platformLoopEnd(); } } diff --git a/native/cocos/platform/android/java/src/com/cocos/lib/CocosDownloader.java b/native/cocos/platform/android/java/src/com/cocos/lib/CocosDownloader.java index c7d4300bb2..60ecf2eea3 100644 --- a/native/cocos/platform/android/java/src/com/cocos/lib/CocosDownloader.java +++ b/native/cocos/platform/android/java/src/com/cocos/lib/CocosDownloader.java @@ -157,6 +157,17 @@ public class CocosDownloader { if (tempFile.isDirectory()) break; File parent = tempFile.getParentFile(); + if (parent == null) { + String errStr = "Invalid path " + path + " : The current path is inaccessible."; + Log.e("CocosDownloader", errStr); + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + downloader.nativeOnFinish(downloader._id, id, 0, errStr, null); + } + }); + break; + } if (!parent.isDirectory() && !parent.mkdirs()) break; finalFile = new File(path); diff --git a/native/cocos/platform/interfaces/modules/IXRInterface.h b/native/cocos/platform/interfaces/modules/IXRInterface.h new file mode 100644 index 0000000000..851b7dcc92 --- /dev/null +++ b/native/cocos/platform/interfaces/modules/IXRInterface.h @@ -0,0 +1,312 @@ +/**************************************************************************** + Copyright (c) 2021-2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include +#include "base/std/container/array.h" +#include "gfx-base/GFXDef-common.h" +#include "math/Vec2.h" +#include "platform/interfaces/OSInterface.h" +#if CC_USE_VULKAN + #include "vulkan/vulkan_core.h" +#endif +#include "XRCommon.h" +namespace cc { +// forward declare +namespace gfx { +class GLES3GPUContext; +} + +enum class EGLSurfaceType { + NONE, + WINDOW, + PBUFFER +}; + +/** + * @en Mainly responsible for the docking work of the engine and the xr library + * @zh 主要负责引擎与xr库的对接工作 + */ +class CC_DLL IXRInterface : public OSInterface { +public: + /** + * @en get xr device vendor + * @zh 获取XR设备品牌 + * @return xr::XRVendor + */ + virtual xr::XRVendor getVendor() = 0; + + /** + * @en get xr config parameter + * @zh 获取XR配置参数 + */ + virtual xr::XRConfigValue getXRConfig(xr::XRConfigKey key) = 0; + + /** + * @en set xr config parameter + * @zh 设置XR配置参数 + * @param key + * @param value + */ + virtual void setXRConfig(xr::XRConfigKey key, xr::XRConfigValue value) = 0; + + /** + * @en get XR runtime version + * @zh 获取XR运行时版本号 + * @return + */ + virtual uint32_t getRuntimeVersion() = 0; + /** + * @en initialize xr runtime envirment + * @zh 初始化XR运行环境 + * @param javaVM android JVM + * @param activity android activity + */ + virtual void initialize(void *javaVM, void *activity) = 0; + + // render thread lifecycle + /** + * @en call when render pause + * @zh 渲染暂停时调用 + */ + virtual void onRenderPause() = 0; + /** + * @en call when render resume + * @zh 渲染恢复时调用 + */ + virtual void onRenderResume() = 0; + /** + * @en call when render destroy + * @zh 渲染结束退出时调用 + */ + virtual void onRenderDestroy() = 0; + // render thread lifecycle + + // gfx + /** + * @en call before gfx device initialize + * @zh GFX设备初始化前调用 + * @param gfxApi + */ + virtual void preGFXDeviceInitialize(gfx::API gfxApi) = 0; + /** + * @en call after gfx device initialize + * @zh GFX设备初始化后调用 + * @param gfxApi + */ + virtual void postGFXDeviceInitialize(gfx::API gfxApi) = 0; + /** + * @en call when gfx device acquire + * @zh GFX设备请求渲染 + * @param gfxApi + * @return + */ + virtual const xr::XRSwapchain &doGFXDeviceAcquire(gfx::API gfxApi) = 0; + /** + * @en call when gfx device present + * @zh GFX设备是否需要展示操作 + */ + virtual bool isGFXDeviceNeedsPresent(gfx::API gfxApi) = 0; + /** + * @en call after gfx device present + * @zh GFX设备展示操作执行之后调用 + * @param gfxApi + */ + virtual void postGFXDevicePresent(gfx::API gfxApi) = 0; + /** + * @en call when create gfx device's swapchain + * @zh 创建GFX交换链时调用 + */ + virtual void createXRSwapchains() = 0; + /** + * @en get xr swapchain list + * @zh 获取XR交换链列表 + * @return + */ + virtual const std::vector &getXRSwapchains() = 0; + /** + * @en get xr swapchain's format + * @zh 获取XR交换链格式 + * @return + */ + virtual gfx::Format getXRSwapchainFormat() = 0; + /** + * @en bind engine's swapchain with xr swapchain + * @zh 绑定引擎交换链与XR交换链对应关系 + * @param typedID engine swapchain's type id + */ + virtual void updateXRSwapchainTypedID(uint32_t typedID) = 0; + // gfx + + // vulkan +#ifdef CC_USE_VULKAN + /** + * @en get the vk version required by XR + * @zh 获取XR要求的VK版本信息 + * @param engineVkApiVersion engine's vk version + */ + virtual uint32_t getXRVkApiVersion(uint32_t engineVkApiVersion) = 0; + /** + * @en initialize vulkan envirment + * @zh 初始化vk运行环境 + * @param addr + */ + virtual void initializeVulkanData(const PFN_vkGetInstanceProcAddr &addr) = 0; + /** + * @en create vulkan instance + * @zh 创建vk实例 + * @param instInfo + * @return + */ + virtual VkInstance createXRVulkanInstance(const VkInstanceCreateInfo &instInfo) = 0; + /** + * @en create vulkan device + * @zh 创建vk逻辑设备 + * @param deviceInfo + * @return + */ + virtual VkDevice createXRVulkanDevice(const VkDeviceCreateInfo *deviceInfo) = 0; + /** + * @en get vulkan physical device + * @zh 获取vk物理设备 + * @return + */ + virtual VkPhysicalDevice getXRVulkanGraphicsDevice() = 0; + /** + * @en get vkImage list from xrswapchain + * @zh 获取xr交换链中vkimage列表 + * @param vkImages + * @param eye + */ + virtual void getXRSwapchainVkImages(std::vector &vkImages, uint32_t eye) = 0; +#endif + // vulkan + + // gles3 +#ifdef CC_USE_GLES3 + /** + * @en initialize gles envirment + * @zh 初始化gles运行环境 + * @param gles3wLoadFuncProc + * @param gpuContext + */ + virtual void initializeGLESData(xr::PFNGLES3WLOADPROC gles3wLoadFuncProc, gfx::GLES3GPUContext *gpuContext) = 0; + /** + * @en attach current texture id to fbo + * @zh 绑定当前纹理到帧缓冲区 + */ + virtual void attachGLESFramebufferTexture2D() = 0; + /** + * @en acquire EGLSurfaceType by engine swapchain's type id + * @zh 根据引擎交换链获取对应需要创建的EGLSurface类型 + * @param typedID + * @return + */ + virtual EGLSurfaceType acquireEGLSurfaceType(uint32_t typedID) = 0; +#endif + // gles3 + + // stereo render loop + /** + * @en call when platform loop start + * @zh 平台循环开始时调用 + * @return + */ + virtual bool platformLoopStart() = 0; + /** + * @en call when frame render begin + * @zh 一帧开始时调用 + * @return + */ + virtual bool beginRenderFrame() = 0; + /** + * @en whether the current frame allows rendering + * @zh 当前帧是否允许渲染 + * @return + */ + virtual bool isRenderAllowable() = 0; + /** + * @en call when single eye render begin + * @zh 单眼渲染开始时调用 + * @param eye + * @return + */ + virtual bool beginRenderEyeFrame(uint32_t eye) = 0; + /** + * @en call when single eye render end + * @zh 单眼渲染结束时调用 + * @param eye + * @return + */ + virtual bool endRenderEyeFrame(uint32_t eye) = 0; + /** + * @en call when frame render end + * @zh 一帧结束时调用 + * @return + */ + virtual bool endRenderFrame() = 0; + /** + * @en call when platform loop end + * @zh 平台循环结束时调用 + * @return + */ + virtual bool platformLoopEnd() = 0; + // stereo render loop + + /** + * @en get hmd view position data + * @zh 获取hmd双眼位置坐标 + * @param eye + * @return + */ + virtual ccstd::vector getHMDViewPosition(uint32_t eye, int trackingType) = 0; + /** + * @en get xr view projection data + * @zh 获取xr双眼投影矩阵数据 + * @param eye + * @param near + * @param far + * @return + */ + virtual ccstd::vector getXRViewProjectionData(uint32_t eye, float near, float far) = 0; + + // renderwindow + /** + * @en get renderwindow's xreye type + * @zh 获取当前RenderWindow的XREye类型 + * @param window + * @return + */ + virtual xr::XREye getXREyeByRenderWindow(void *window) = 0; + /** + * @en bind renderwindow with xr eye + * @zh 建立RenderWindow与XREye的对应关系 + * @param window + * @param eye + */ + virtual void bindXREyeWithRenderWindow(void *window, xr::XREye eye) = 0; +}; +} // namespace cc diff --git a/native/cocos/platform/interfaces/modules/XRCommon.h b/native/cocos/platform/interfaces/modules/XRCommon.h new file mode 100644 index 0000000000..d51497f555 --- /dev/null +++ b/native/cocos/platform/interfaces/modules/XRCommon.h @@ -0,0 +1,318 @@ +/**************************************************************************** + Copyright (c) 2021-2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#ifndef XR_COMMON_H_ +#define XR_COMMON_H_ +#include +#include +#include +#include +#include + +namespace cc { +namespace xr { +#define XR_INTERFACE_RUNTIME_VERSION_1_0 1 + +enum class XREye { + NONE = -1, + LEFT = 0, + RIGHT = 1, + MONO = 2 +}; + +enum class XRVendor { + MONADO, + META, + HUAWEIVR, + PICO, + ROKID, +}; + +enum class XRConfigKey { + MULTI_SAMPLES, + RENDER_SCALE, + SESSION_RUNNING, + INSTANCE_CREATED, + VK_QUEUE_FAMILY_INDEX, + METRICS_STATE, + VIEW_COUNT, + SWAPCHAIN_WIDTH, + SWAPCHAIN_HEIGHT, + SWAPCHAIN_FORMAT, + MULTITHREAD_MODE, + LOGIC_THREAD_ID, + RENDER_THREAD_ID, + DEVICE_VENDOR, + RUNTIME_VERSION, + PRESENT_ENABLE, + RENDER_EYE_FRAME_LEFT, + RENDER_EYE_FRAME_RIGHT +}; + +enum class XRConfigValueType { + UNKNOWN, + INT, + FLOAT, + BOOL, + STRING, + VOID_POINTER +}; + +struct XRConfigValue { + int vInt = 0; + float vFloat = 0; + bool vBool = false; + void *vPtr = nullptr; + std::string vString; + XRConfigValueType valueType = XRConfigValueType::UNKNOWN; + bool isInt() { + return valueType == XRConfigValueType::INT; + } + + bool isFloat() { + return valueType == XRConfigValueType::FLOAT; + } + + bool isBool() { + return valueType == XRConfigValueType::BOOL; + } + + bool isPointer() { + return valueType == XRConfigValueType::VOID_POINTER; + } + + bool isString() { + return valueType == XRConfigValueType::STRING; + } + + bool getBool() { + return vBool; + } + + int getInt() { + return vInt; + } + + float getFloat() { + return vFloat; + } + + std::string getString() { + return vString; + } + + void *getPointer() { + return vPtr; + } + + XRConfigValue() { + } + + XRConfigValue(int value) { + valueType = XRConfigValueType::INT; + vInt = value; + } + + XRConfigValue(float value) { + valueType = XRConfigValueType::FLOAT; + vFloat = value; + } + + XRConfigValue(std::string value) { + valueType = XRConfigValueType::STRING; + vString = value; + } + + XRConfigValue(bool value) { + valueType = XRConfigValueType::BOOL; + vBool = value; + } + + XRConfigValue(void *value) { + valueType = XRConfigValueType::VOID_POINTER; + vPtr = value; + } +}; + +enum class XREventType { + CLICK, + STICK, + GRAB, + POSE, + UNKNOWN +}; + +struct XRControllerInfo { + virtual ~XRControllerInfo() = default; + virtual XREventType getXREventType() const = 0; +}; + +struct XRClick : public XRControllerInfo { + enum class Type { + TRIGGER_LEFT, + SHOULDER_LEFT, + THUMBSTICK_LEFT, + X, + Y, + MENU, + TRIGGER_RIGHT, + SHOULDER_RIGHT, + THUMBSTICK_RIGHT, + A, + B, + HOME, + BACK, + START, + DPAD_UP, + DPAD_DOWN, + DPAD_LEFT, + DPAD_RIGHT, + UNKNOWN + }; + + bool isPress = false; + Type type = Type::UNKNOWN; + + XRClick(Type type, bool isPress) + : type(type), + isPress(isPress) {} + + XREventType getXREventType() const override { + return XREventType::CLICK; + } +}; + +struct XRStick : public XRControllerInfo { + enum class Type { + STICK_LEFT, + STICK_RIGHT, + UNKNOWN + }; + + bool isActive = false; + float x = 0.F; + float y = 0.F; + Type type = Type::UNKNOWN; + + XRStick(Type type, bool isActive) + : type(type), + isActive(isActive) {} + + XRStick(Type type, float x, float y) + : type(type), + isActive(true), + x(x), + y(y) {} + + XREventType getXREventType() const override { + return XREventType::STICK; + } +}; + +struct XRGrab : public XRControllerInfo { + enum class Type { + TRIGGER_LEFT, + GRIP_LEFT, + TRIGGER_RIGHT, + GRIP_RIGHT, + UNKNOWN + }; + + bool isActive = false; + float value = 0.F; + Type type = Type::UNKNOWN; + + XRGrab(Type type, bool isActive) + : type(type), + isActive(isActive) {} + + XRGrab(Type type, float value) + : type(type), + isActive(true), + value(value) {} + + XREventType getXREventType() const override { + return XREventType::GRAB; + } +}; + +struct XRPose : public XRControllerInfo { + enum class Type { + VIEW_LEFT, + HAND_LEFT, + AIM_LEFT, + VIEW_RIGHT, + HAND_RIGHT, + AIM_RIGHT, + HEAD_MIDDLE, + UNKNOWN + }; + + bool isActive = false; + float px = 0.F; + float py = 0.F; + float pz = 0.F; + float qx = 0.F; + float qy = 0.F; + float qz = 0.F; + float qw = 1.F; + Type type = Type::UNKNOWN; + + XRPose(Type type, bool isActive) + : type(type), + isActive(isActive) {} + + XRPose(Type type, float position[3], float quaternion[4]) + : type(type), isActive(true), px(position[0]), py(position[1]), pz(position[2]), qx(quaternion[0]), qy(quaternion[1]), qz(quaternion[2]), qw(quaternion[3]) {} + + XREventType getXREventType() const override { + return XREventType::POSE; + } +}; + +struct XRControllerEvent { + std::vector> xrControllerInfos; +}; +typedef std::function XRControllerCallback; +using PFNGLES3WLOADPROC = void *(*)(const char *); + +typedef std::function XRConfigChangeCallback; + +struct XRSwapchain { + void *xrSwapchainHandle = nullptr; + uint32_t width = 0; + uint32_t height = 0; + uint32_t glDrawFramebuffer = 0; + uint32_t swapchainImageIndex = 0; + uint32_t eye = 0; +}; + +#define GraphicsApiOpenglES "OpenGLES" +#define GraphicsApiVulkan_1_0 "Vulkan1" +#define GraphicsApiVulkan_1_1 "Vulkan2" + +} // namespace xr +} // namespace cc +#endif // XR_COMMON_H_ diff --git a/native/cocos/platform/java/modules/XRInterface.cpp b/native/cocos/platform/java/modules/XRInterface.cpp new file mode 100644 index 0000000000..4899e13137 --- /dev/null +++ b/native/cocos/platform/java/modules/XRInterface.cpp @@ -0,0 +1,840 @@ +/**************************************************************************** + Copyright (c) 2021-2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "XRInterface.h" +#include +#include +#include +#include +#include "android/AndroidPlatform.h" +#include "base/Log.h" +#include "base/Macros.h" +#include "bindings/event/EventDispatcher.h" +#include "cocos/bindings/jswrapper/SeApi.h" +#include "java/jni/JniHelper.h" +#include "renderer/GFXDeviceManager.h" +#ifdef CC_USE_VULKAN + #include "gfx-vulkan/VKDevice.h" +#endif +#ifdef CC_USE_GLES3 + #include "gfx-gles-common/gles3w.h" + #include "gfx-gles3/GLES3Device.h" + #include "renderer/gfx-gles3/GLES3GPUObjects.h" +#endif + +#if CC_USE_XR + #include "Xr.h" +#endif +#include "application/ApplicationManager.h" +#include "base/threading/MessageQueue.h" + +// print log +const bool IS_ENABLE_XR_LOG = false; + +namespace cc { +ControllerEvent controllerEvent; +static se::Object *jsPoseEventArray = nullptr; +static void dispatchGamepadEventInternal(const xr::XRControllerEvent &xrControllerEvent) { + if (xrControllerEvent.xrControllerInfos.empty()) { + return; + } + + auto *controllerInfo = ccnew ControllerInfo(); + if (!controllerInfo) { + return; + } + + size_t length = xrControllerEvent.xrControllerInfos.size(); + for (size_t i = 0; i < length; i++) { + switch (xrControllerEvent.xrControllerInfos.at(i)->getXREventType()) { + case xr::XREventType::CLICK: { + auto *xrClick = static_cast(xrControllerEvent.xrControllerInfos.at(i).get()); + switch (xrClick->type) { + case xr::XRClick::Type::MENU: + controllerInfo->buttonInfos.emplace_back(ControllerInfo::ButtonInfo(StickKeyCode::MENU, xrClick->isPress)); + break; + case xr::XRClick::Type::TRIGGER_LEFT: + controllerInfo->buttonInfos.emplace_back(ControllerInfo::ButtonInfo(StickKeyCode::TRIGGER_LEFT, xrClick->isPress)); + break; + case xr::XRClick::Type::SHOULDER_LEFT: + controllerInfo->buttonInfos.emplace_back(ControllerInfo::ButtonInfo(StickKeyCode::L1, xrClick->isPress)); + break; + case xr::XRClick::Type::THUMBSTICK_LEFT: + controllerInfo->buttonInfos.emplace_back(ControllerInfo::ButtonInfo(StickKeyCode::L3, xrClick->isPress)); + break; + case xr::XRClick::Type::X: + controllerInfo->buttonInfos.emplace_back(ControllerInfo::ButtonInfo(StickKeyCode::Y, xrClick->isPress)); + break; + case xr::XRClick::Type::Y: + controllerInfo->buttonInfos.emplace_back(ControllerInfo::ButtonInfo(StickKeyCode::X, xrClick->isPress)); + break; + case xr::XRClick::Type::TRIGGER_RIGHT: + controllerInfo->buttonInfos.emplace_back(ControllerInfo::ButtonInfo(StickKeyCode::TRIGGER_RIGHT, xrClick->isPress)); + break; + case xr::XRClick::Type::SHOULDER_RIGHT: + controllerInfo->buttonInfos.emplace_back(ControllerInfo::ButtonInfo(StickKeyCode::R1, xrClick->isPress)); + break; + case xr::XRClick::Type::THUMBSTICK_RIGHT: + controllerInfo->buttonInfos.emplace_back(ControllerInfo::ButtonInfo(StickKeyCode::R3, xrClick->isPress)); + break; + case xr::XRClick::Type::A: + controllerInfo->buttonInfos.emplace_back(ControllerInfo::ButtonInfo(StickKeyCode::B, xrClick->isPress)); + break; + case xr::XRClick::Type::B: + controllerInfo->buttonInfos.emplace_back(ControllerInfo::ButtonInfo(StickKeyCode::A, xrClick->isPress)); + break; + case xr::XRClick::Type::HOME: + CC_LOG_INFO("[XRInterface] exit when home click in rokid."); +#if CC_USE_XR + xr::XrEntry::getInstance()->destroyXrInstance(); + xr::XrEntry::destroyInstance(); +#endif + CC_CURRENT_APPLICATION_SAFE()->close(); + break; + case xr::XRClick::Type::START: + controllerInfo->buttonInfos.emplace_back(ControllerInfo::ButtonInfo(StickKeyCode::START, xrClick->isPress)); + break; + case xr::XRClick::Type::DPAD_UP: + controllerInfo->axisInfos.emplace_back(ControllerInfo::AxisInfo(StickAxisCode::Y, xrClick->isPress ? 1.F : 0.F)); + break; + case xr::XRClick::Type::DPAD_DOWN: + controllerInfo->axisInfos.emplace_back(ControllerInfo::AxisInfo(StickAxisCode::Y, xrClick->isPress ? -1.F : 0.F)); + break; + case xr::XRClick::Type::DPAD_LEFT: + controllerInfo->axisInfos.emplace_back(ControllerInfo::AxisInfo(StickAxisCode::X, xrClick->isPress ? -1.F : 0.F)); + break; + case xr::XRClick::Type::DPAD_RIGHT: + controllerInfo->axisInfos.emplace_back(ControllerInfo::AxisInfo(StickAxisCode::X, xrClick->isPress ? 1.F : 0.F)); + break; + default: + break; + } + } break; + case xr::XREventType::STICK: { + auto *xrStick = static_cast(xrControllerEvent.xrControllerInfos.at(i).get()); + switch (xrStick->type) { + case xr::XRStick::Type::STICK_LEFT: + controllerInfo->axisInfos.emplace_back(ControllerInfo::AxisInfo(StickAxisCode::LEFT_STICK_X, xrStick->x)); + controllerInfo->axisInfos.emplace_back(ControllerInfo::AxisInfo(StickAxisCode::LEFT_STICK_Y, xrStick->y)); + break; + case xr::XRStick::Type::STICK_RIGHT: + controllerInfo->axisInfos.emplace_back(ControllerInfo::AxisInfo(StickAxisCode::RIGHT_STICK_X, xrStick->x)); + controllerInfo->axisInfos.emplace_back(ControllerInfo::AxisInfo(StickAxisCode::RIGHT_STICK_Y, xrStick->y)); + break; + default: + break; + } + } break; + case xr::XREventType::GRAB: { + auto *xrGrab = static_cast(xrControllerEvent.xrControllerInfos.at(i).get()); + switch (xrGrab->type) { + case xr::XRGrab::Type::TRIGGER_LEFT: + controllerInfo->axisInfos.emplace_back(ControllerInfo::AxisInfo(StickAxisCode::L2, xrGrab->value)); + break; + case xr::XRGrab::Type::TRIGGER_RIGHT: + controllerInfo->axisInfos.emplace_back(ControllerInfo::AxisInfo(StickAxisCode::R2, xrGrab->value)); + break; + default: + break; + } + } break; + default: + break; + } + } + + controllerInfo->napdId = 0; // xr only one gamepad connection + controllerEvent.controllerInfos.emplace_back(controllerInfo); + controllerEvent.type = ControllerEvent::Type::GAMEPAD; + static_cast(BasePlatform::getPlatform())->dispatchEvent(controllerEvent); + controllerEvent.type = ControllerEvent::Type::UNKNOWN; + controllerEvent.controllerInfos.clear(); +} + +static void dispatchHandleEventInternal(const xr::XRControllerEvent &xrControllerEvent) { + if (xrControllerEvent.xrControllerInfos.empty()) { + return; + } + + auto *controllerInfo = ccnew ControllerInfo(); + if (!controllerInfo) { + return; + } + + size_t length = xrControllerEvent.xrControllerInfos.size(); + se::AutoHandleScope scope; + uint32_t poseIndex = 0; + for (size_t i = 0; i < length; i++) { + switch (xrControllerEvent.xrControllerInfos.at(i)->getXREventType()) { + case xr::XREventType::CLICK: { + auto *xrClick = static_cast(xrControllerEvent.xrControllerInfos.at(i).get()); + switch (xrClick->type) { + case xr::XRClick::Type::MENU: +#if !XR_OEM_SEED + controllerInfo->buttonInfos.emplace_back(ControllerInfo::ButtonInfo(StickKeyCode::MENU, xrClick->isPress)); +#else + CC_LOG_INFO("[XRInterface] exit when menu click in seed."); + CC_CURRENT_APPLICATION_SAFE()->close(); +#endif + break; + case xr::XRClick::Type::TRIGGER_LEFT: + controllerInfo->buttonInfos.emplace_back(ControllerInfo::ButtonInfo(StickKeyCode::TRIGGER_LEFT, xrClick->isPress)); + break; + case xr::XRClick::Type::THUMBSTICK_LEFT: + controllerInfo->buttonInfos.emplace_back(ControllerInfo::ButtonInfo(StickKeyCode::L3, xrClick->isPress)); + break; + case xr::XRClick::Type::X: + controllerInfo->buttonInfos.emplace_back(ControllerInfo::ButtonInfo(StickKeyCode::Y, xrClick->isPress)); + break; + case xr::XRClick::Type::Y: + controllerInfo->buttonInfos.emplace_back(ControllerInfo::ButtonInfo(StickKeyCode::X, xrClick->isPress)); + break; + case xr::XRClick::Type::TRIGGER_RIGHT: + controllerInfo->buttonInfos.emplace_back(ControllerInfo::ButtonInfo(StickKeyCode::TRIGGER_RIGHT, xrClick->isPress)); + break; + case xr::XRClick::Type::THUMBSTICK_RIGHT: + controllerInfo->buttonInfos.emplace_back(ControllerInfo::ButtonInfo(StickKeyCode::R3, xrClick->isPress)); + break; + case xr::XRClick::Type::A: + controllerInfo->buttonInfos.emplace_back(ControllerInfo::ButtonInfo(StickKeyCode::B, xrClick->isPress)); + break; + case xr::XRClick::Type::B: + controllerInfo->buttonInfos.emplace_back(ControllerInfo::ButtonInfo(StickKeyCode::A, xrClick->isPress)); + break; + default: + break; + } + } break; + case xr::XREventType::STICK: { + auto *xrStick = static_cast(xrControllerEvent.xrControllerInfos.at(i).get()); + switch (xrStick->type) { + case xr::XRStick::Type::STICK_LEFT: + controllerInfo->axisInfos.emplace_back(ControllerInfo::AxisInfo(StickAxisCode::LEFT_STICK_X, xrStick->x)); + controllerInfo->axisInfos.emplace_back(ControllerInfo::AxisInfo(StickAxisCode::LEFT_STICK_Y, xrStick->y)); + break; + case xr::XRStick::Type::STICK_RIGHT: + controllerInfo->axisInfos.emplace_back(ControllerInfo::AxisInfo(StickAxisCode::RIGHT_STICK_X, xrStick->x)); + controllerInfo->axisInfos.emplace_back(ControllerInfo::AxisInfo(StickAxisCode::RIGHT_STICK_Y, xrStick->y)); + break; + default: + break; + } + } break; + case xr::XREventType::GRAB: { + auto *xrGrab = static_cast(xrControllerEvent.xrControllerInfos.at(i).get()); + switch (xrGrab->type) { + case xr::XRGrab::Type::TRIGGER_LEFT: + controllerInfo->axisInfos.emplace_back(ControllerInfo::AxisInfo(StickAxisCode::L2, xrGrab->value)); + break; + case xr::XRGrab::Type::TRIGGER_RIGHT: + controllerInfo->axisInfos.emplace_back(ControllerInfo::AxisInfo(StickAxisCode::R2, xrGrab->value)); + break; + case xr::XRGrab::Type::GRIP_LEFT: + controllerInfo->axisInfos.emplace_back(ControllerInfo::AxisInfo(StickAxisCode::LEFT_GRIP, xrGrab->value)); + break; + case xr::XRGrab::Type::GRIP_RIGHT: + controllerInfo->axisInfos.emplace_back(ControllerInfo::AxisInfo(StickAxisCode::RIGHT_GRIP, xrGrab->value)); + break; + default: + break; + } + } break; + case xr::XREventType::POSE: { + auto *xrPose = static_cast(xrControllerEvent.xrControllerInfos.at(i).get()); + switch (xrPose->type) { + case xr::XRPose::Type::HAND_LEFT: + case xr::XRPose::Type::HAND_RIGHT: + case xr::XRPose::Type::AIM_LEFT: + case xr::XRPose::Type::AIM_RIGHT: { + auto *jsPose = se::Object::createPlainObject(); + jsPose->setProperty("code", se::Value(static_cast(xrPose->type))); + jsPose->setProperty("x", se::Value(xrPose->px)); + jsPose->setProperty("y", se::Value(xrPose->py)); + jsPose->setProperty("z", se::Value(xrPose->pz)); + jsPose->setProperty("quaternionX", se::Value(xrPose->qx)); + jsPose->setProperty("quaternionY", se::Value(xrPose->qy)); + jsPose->setProperty("quaternionZ", se::Value(xrPose->qz)); + jsPose->setProperty("quaternionW", se::Value(xrPose->qw)); + if (!jsPoseEventArray) { + jsPoseEventArray = se::Object::createArrayObject(0); + jsPoseEventArray->root(); + } + jsPoseEventArray->setArrayElement(poseIndex, se::Value(jsPose)); + poseIndex++; + } break; + default: + break; + } + } break; + default: + break; + } + } + + if (poseIndex > 0) { + jsPoseEventArray->setProperty("length", se::Value(poseIndex)); + se::ValueArray args; + args.emplace_back(se::Value(jsPoseEventArray)); + EventDispatcher::doDispatchJsEvent("onHandlePoseInput", args); + } + + if (!controllerInfo->buttonInfos.empty() || !controllerInfo->axisInfos.empty()) { + controllerInfo->napdId = 0; // xr only one handle connection + controllerEvent.controllerInfos.emplace_back(controllerInfo); + controllerEvent.type = ControllerEvent::Type::HANDLE; + EventDispatcher::dispatchControllerEvent(controllerEvent); + controllerEvent.type = ControllerEvent::Type::UNKNOWN; + controllerEvent.controllerInfos.clear(); + } else { + CC_SAFE_DELETE(controllerInfo); + } +} + +static void dispatchHMDEventInternal(const xr::XRControllerEvent &xrControllerEvent) { + if (xrControllerEvent.xrControllerInfos.empty()) { + return; + } + + size_t length = xrControllerEvent.xrControllerInfos.size(); + se::AutoHandleScope scope; + uint32_t poseIndex = 0; + for (size_t i = 0; i < length; i++) { + if (xrControllerEvent.xrControllerInfos.at(i)->getXREventType() == xr::XREventType::POSE) { + auto *xrPose = static_cast(xrControllerEvent.xrControllerInfos.at(i).get()); + switch (xrPose->type) { + case xr::XRPose::Type::VIEW_LEFT: + case xr::XRPose::Type::VIEW_RIGHT: + case xr::XRPose::Type::HEAD_MIDDLE: { + auto *jsPose = se::Object::createPlainObject(); + jsPose->setProperty("code", se::Value(static_cast(xrPose->type))); + jsPose->setProperty("x", se::Value(xrPose->px)); + jsPose->setProperty("y", se::Value(xrPose->py)); + jsPose->setProperty("z", se::Value(xrPose->pz)); + jsPose->setProperty("quaternionX", se::Value(xrPose->qx)); + jsPose->setProperty("quaternionY", se::Value(xrPose->qy)); + jsPose->setProperty("quaternionZ", se::Value(xrPose->qz)); + jsPose->setProperty("quaternionW", se::Value(xrPose->qw)); + if (!jsPoseEventArray) { + jsPoseEventArray = se::Object::createArrayObject(0); + jsPoseEventArray->root(); + } + jsPoseEventArray->setArrayElement(poseIndex, se::Value(jsPose)); + poseIndex++; + } break; + default: + break; + } + } + } + + if (poseIndex > 0) { + jsPoseEventArray->setProperty("length", se::Value(poseIndex)); + se::ValueArray args; + args.emplace_back(se::Value(jsPoseEventArray)); + EventDispatcher::doDispatchJsEvent("onHMDPoseInput", args); + } +} + +xr::XRVendor XRInterface::getVendor() { +#if CC_USE_XR + return (xr::XRVendor)xr::XrEntry::getInstance()->getXRConfig(cc::xr::XRConfigKey::DEVICE_VENDOR).getInt(); +#endif + return xr::XRVendor::MONADO; +} + +xr::XRConfigValue XRInterface::getXRConfig(xr::XRConfigKey key) { +#if CC_USE_XR + return xr::XrEntry::getInstance()->getXRConfig(key); +#endif + CC_UNUSED_PARAM(key); + cc::xr::XRConfigValue configValue; + return configValue; +} + +void XRInterface::setXRConfig(xr::XRConfigKey key, xr::XRConfigValue value) { +#if CC_USE_XR + CC_LOG_INFO("[XR] setConfigParameterI %d", key); + xr::XrEntry::getInstance()->setXRConfig(key, value); +#else + CC_UNUSED_PARAM(key); + CC_UNUSED_PARAM(value); +#endif +} + +uint32_t XRInterface::getRuntimeVersion() { +#if CC_USE_XR + return xr::XrEntry::getInstance()->getXRConfig(cc::xr::XRConfigKey::RUNTIME_VERSION).getInt(); +#endif + return 1; +} + +void XRInterface::initialize(void *javaVM, void *activity) { +#if CC_USE_XR + CC_LOG_INFO("[XR] initialize vm.%p,aty.%p | %d", javaVM, activity, (int)gettid()); + xr::XrEntry::getInstance()->initPlatformData(javaVM, activity); + xr::XrEntry::getInstance()->setGamepadCallback(&dispatchGamepadEventInternal); + xr::XrEntry::getInstance()->setHandleCallback(&dispatchHandleEventInternal); + xr::XrEntry::getInstance()->setHMDCallback(&dispatchHMDEventInternal); + xr::XrEntry::getInstance()->setXRConfig(xr::XRConfigKey::LOGIC_THREAD_ID, (int)gettid()); + xr::XrEntry::getInstance()->setXRConfigCallback([this](xr::XRConfigKey key, xr::XRConfigValue value) { + if (IS_ENABLE_XR_LOG) CC_LOG_INFO("XRConfigCallback.%d", key); + if (key == xr::XRConfigKey::RENDER_EYE_FRAME_LEFT || key == xr::XRConfigKey::RENDER_EYE_FRAME_RIGHT) { + if (value.getInt() == 0) + this->beginRenderEyeFrame(key == xr::XRConfigKey::RENDER_EYE_FRAME_LEFT ? 0 : 1); + if (value.getInt() == 1) + this->endRenderEyeFrame(key == xr::XRConfigKey::RENDER_EYE_FRAME_LEFT ? 0 : 1); + } + }); + #if XR_OEM_PICO + std::string graphicsApiName = GraphicsApiOpenglES; + #if CC_USE_VULKAN + graphicsApiName = GraphicsApiVulkan_1_0; + #endif + xr::XrEntry::getInstance()->createXrInstance(graphicsApiName.c_str()); + #endif +#else + CC_UNUSED_PARAM(javaVM); + CC_UNUSED_PARAM(activity); +#endif +} + +// render thread lifecycle +void XRInterface::onRenderPause() { +#if CC_USE_XR + if (!_renderPaused) { + _renderPaused = true; + _renderResumed = false; + CC_LOG_INFO("[XR] onRenderPause"); + xr::XrEntry::getInstance()->pauseXrInstance(); + } +#endif +} + +void XRInterface::onRenderResume() { +#if CC_USE_XR + if (!_renderResumed) { + _renderResumed = true; + _renderPaused = false; + CC_LOG_INFO("[XR] onRenderResume"); + xr::XrEntry::getInstance()->resumeXrInstance(); + } +#endif +} + +void XRInterface::onRenderDestroy() { +#if CC_USE_XR + CC_LOG_INFO("[XR] onRenderDestroy"); + xr::XrEntry::getInstance()->destroyXrInstance(); + xr::XrEntry::destroyInstance(); + if (jsPoseEventArray != nullptr) { + jsPoseEventArray->unroot(); + jsPoseEventArray->decRef(); + jsPoseEventArray = nullptr; + } +#endif +} +// render thread lifecycle + +// gfx +void XRInterface::preGFXDeviceInitialize(gfx::API gfxApi) { +#if CC_USE_XR + CC_LOG_INFO("[XR] preGFXDeviceInitialize.api.%d | Multi Thread.%d", gfxApi, gfx::DeviceAgent::getInstance() ? 1 : 0); + setXRConfig(xr::XRConfigKey::MULTITHREAD_MODE, gfx::DeviceAgent::getInstance() ? true : false); + xr::XrEntry::getInstance()->setXRConfig(xr::XRConfigKey::RENDER_THREAD_ID, (int)gettid()); + + if (gfxApi == gfx::API::GLES3 || gfxApi == gfx::API::VULKAN) { + #if !XR_OEM_PICO + std::string graphicsApiName = gfxApi == gfx::API::GLES3 ? GraphicsApiOpenglES : GraphicsApiVulkan_1_1; + xr::XrEntry::getInstance()->createXrInstance(graphicsApiName.c_str()); + #endif + } +#else + CC_UNUSED_PARAM(gfxApi); +#endif +} + +void XRInterface::postGFXDeviceInitialize(gfx::API gfxApi) { +#if CC_USE_XR + CC_LOG_INFO("[XR] postGFXDeviceInitialize.api.%d", gfxApi); + if (gfxApi == gfx::API::GLES3) { + #if CC_USE_GLES3 + xr::XrEntry::getInstance()->initXrSession(_gles3wLoadFuncProc, + _gles3GPUContext->eglDisplay, + _gles3GPUContext->eglConfig, + _gles3GPUContext->eglDefaultContext); + #endif + } else if (gfxApi == gfx::API::VULKAN) { + #if CC_USE_VULKAN + int vkQueueFamilyIndex = xr::XrEntry::getInstance()->getXRConfig(cc::xr::XRConfigKey::VK_QUEUE_FAMILY_INDEX).getInt(); + cc::xr::XrEntry::getInstance()->initXrSession(_vkInstance, _vkPhysicalDevice, _vkDevice, vkQueueFamilyIndex); + #endif + } +#else + CC_UNUSED_PARAM(gfxApi); +#endif +} + +const xr::XRSwapchain &XRInterface::doGFXDeviceAcquire(gfx::API gfxApi) { +#if CC_USE_XR + // CC_LOG_INFO("[XR] doGFXDeviceAcquire.api.%d", gfxApi); + if (gfxApi == gfx::API::GLES3 || gfxApi == gfx::API::VULKAN) { + return xr::XrEntry::getInstance()->acquireXrSwapchain((uint32_t)gfxApi); + } +#else + CC_UNUSED_PARAM(gfxApi); +#endif + return _acquireSwapchain; +} + +bool XRInterface::isGFXDeviceNeedsPresent(gfx::API gfxApi) { + CC_UNUSED_PARAM(gfxApi); +#if CC_USE_XR + // CC_LOG_INFO("[XR] isGFXDeviceNeedsPresent.api.%d", gfxApi); + // if (gfxApi == gfx::API::GLES3 || gfxApi == gfx::API::VULKAN) { + // } + return xr::XrEntry::getInstance()->getXRConfig(cc::xr::XRConfigKey::PRESENT_ENABLE).getBool(); +#endif + return true; +} + +void XRInterface::postGFXDevicePresent(gfx::API gfxApi) { +#if CC_USE_XR + // CC_LOG_INFO("[XR] postGFXDevicePresent.api.%d", gfxApi); + if (gfxApi == gfx::API::GLES3 || gfxApi == gfx::API::VULKAN) { + } +#else + CC_UNUSED_PARAM(gfxApi); +#endif +} + +void XRInterface::createXRSwapchains() { +#if CC_USE_XR + CC_LOG_INFO("[XR] createXRSwapchains"); + if (gfx::DeviceAgent::getInstance()) { + ENQUEUE_MESSAGE_0(gfx::DeviceAgent::getInstance()->getMessageQueue(), + CreateXRSwapchains, + { + CC_LOG_INFO("[XR] [RT] initXrSwapchains"); + xr::XrEntry::getInstance()->setXRConfig(xr::XRConfigKey::RENDER_THREAD_ID, (int)gettid()); + JniHelper::getEnv(); + xr::XrEntry::getInstance()->initXrSwapchains(); + }); + } else { + xr::XrEntry::getInstance()->initXrSwapchains(); + } +#endif +} + +const std::vector &XRInterface::getXRSwapchains() { +#if CC_USE_XR + CC_LOG_INFO("[XR] getXRSwapchains"); + if (_xrSwapchains.size() == 0) + _xrSwapchains = xr::XrEntry::getInstance()->getCocosXrSwapchains(); +#endif + return _xrSwapchains; +} + +gfx::Format XRInterface::getXRSwapchainFormat() { +#if CC_USE_XR + int swapchainFormat = xr::XrEntry::getInstance()->getXRConfig(xr::XRConfigKey::SWAPCHAIN_FORMAT).getInt(); + #if CC_USE_GLES3 + if (swapchainFormat == GL_SRGB_ALPHA_EXT) { + return gfx::Format::SRGB8_A8; + } else if (swapchainFormat == GL_RGBA8) { + return gfx::Format::RGBA8; + } else if (swapchainFormat == GL_BGRA8_EXT) { + return gfx::Format::BGRA8; + } + #endif + + #if CC_USE_VULKAN + if (swapchainFormat == VK_FORMAT_R8G8B8A8_SRGB) { + return gfx::Format::SRGB8_A8; + } else if (swapchainFormat == VK_FORMAT_R8G8B8A8_UNORM) { + return gfx::Format::RGBA8; + } else if (swapchainFormat == VK_FORMAT_B8G8R8A8_UNORM) { + return gfx::Format::BGRA8; + } + #endif +#endif + return gfx::Format::BGRA8; +} + +void XRInterface::updateXRSwapchainTypedID(uint32_t typedID) { +#if CC_USE_XR + #if XR_OEM_HUAWEIVR + _eglSurfaceTypeMap[typedID] = EGLSurfaceType::WINDOW; + #else + _eglSurfaceTypeMap[typedID] = EGLSurfaceType::PBUFFER; + #endif +#else + CC_UNUSED_PARAM(typedID); +#endif +} +// gfx + +// vulkan +#ifdef CC_USE_VULKAN +uint32_t XRInterface::getXRVkApiVersion(uint32_t engineVkApiVersion) { + #if CC_USE_XR + return xr::XrEntry::getInstance()->getXrVkApiVersion(engineVkApiVersion); + #else + return engineVkApiVersion; + #endif +} + +void XRInterface::initializeVulkanData(const PFN_vkGetInstanceProcAddr &addr) { + _vkGetInstanceProcAddr = addr; +} + +VkInstance XRInterface::createXRVulkanInstance(const VkInstanceCreateInfo &instInfo) { + #if CC_USE_XR + _vkInstance = xr::XrEntry::getInstance()->xrVkCreateInstance(instInfo, _vkGetInstanceProcAddr); + _vkPhysicalDevice = xr::XrEntry::getInstance()->getXrVkGraphicsDevice(_vkInstance); + return _vkInstance; + #else + CC_UNUSED_PARAM(instInfo); + return nullptr; + #endif +} + +VkDevice XRInterface::createXRVulkanDevice(const VkDeviceCreateInfo *deviceInfo) { + #if CC_USE_XR + VK_CHECK(xr::XrEntry::getInstance()->xrVkCreateDevice(deviceInfo, _vkGetInstanceProcAddr, _vkPhysicalDevice, &_vkDevice)); + #else + CC_UNUSED_PARAM(deviceInfo); + #endif + return _vkDevice; +} + +VkPhysicalDevice XRInterface::getXRVulkanGraphicsDevice() { + return _vkPhysicalDevice; +} + +void XRInterface::getXRSwapchainVkImages(std::vector &vkImages, uint32_t eye) { + #if CC_USE_XR + xr::XrEntry::getInstance()->getSwapchainImages(vkImages, eye); + #else + CC_UNUSED_PARAM(vkImages); + CC_UNUSED_PARAM(eye); + #endif +} +#endif +// vulkan + +// gles +#ifdef CC_USE_GLES3 +void XRInterface::initializeGLESData(PFNGLES3WLOADPROC gles3wLoadFuncProc, gfx::GLES3GPUContext *gpuContext) { + #if CC_USE_XR + _gles3wLoadFuncProc = gles3wLoadFuncProc; + _gles3GPUContext = gpuContext; + void *eglDisplay = gpuContext->eglDisplay; + void *eglConfig = gpuContext->eglConfig; + void *eglDefaultContext = gpuContext->eglDefaultContext; + CC_LOG_INFO("[XR] initializeGLESData.egl.%p/%p/%p", eglDisplay, eglConfig, eglDefaultContext); + #else + CC_UNUSED_PARAM(gles3wLoadFuncProc); + CC_UNUSED_PARAM(gpuContext); + #endif +} + +void XRInterface::attachGLESFramebufferTexture2D() { + #if CC_USE_XR + xr::XrEntry::getInstance()->attachXrFramebufferTexture2D(); + #endif +} + +EGLSurfaceType XRInterface::acquireEGLSurfaceType(uint32_t typedID) { + #if CC_USE_XR + if (_eglSurfaceTypeMap.count(typedID) > 0) { + return _eglSurfaceTypeMap[typedID]; + } + #else + CC_UNUSED_PARAM(typedID); + #endif + return EGLSurfaceType::WINDOW; +} +#endif +// gles + +// stereo render loop +bool XRInterface::platformLoopStart() { +#if CC_USE_XR + // CC_LOG_INFO("[XR] platformLoopStart"); + return xr::XrEntry::getInstance()->platformLoopStart(); +#else + return false; +#endif +} + +bool XRInterface::beginRenderFrame() { +#if CC_USE_XR + if (IS_ENABLE_XR_LOG) CC_LOG_INFO("[XR] beginRenderFrame.%d", _committedFrame); + if (gfx::DeviceAgent::getInstance()) { + static uint64_t frameId = 0; + frameId++; + if (_committedFrame) { + gfx::DeviceAgent::getInstance()->presentWait(); + _committedFrame = false; + } + if (IS_ENABLE_XR_LOG) CC_LOG_INFO("[XR] beginRenderFrame waitFrame.%lld", frameId); + xr::XrEntry::getInstance()->waitFrame(); + ENQUEUE_MESSAGE_1(gfx::DeviceAgent::getInstance()->getMessageQueue(), + BeginRenderFrame, frameId, frameId, + { + if (IS_ENABLE_XR_LOG) CC_LOG_INFO("[XR] [RT] beginRenderFrame.%lld", frameId); + xr::XrEntry::getInstance()->frameStart(); + }); + return true; + } else { + return xr::XrEntry::getInstance()->frameStart(); + } +#else + return false; +#endif +} + +bool XRInterface::isRenderAllowable() { +#if CC_USE_XR + return xr::XrEntry::getInstance()->isRenderAllowable(); +#else + return false; +#endif +} + +bool XRInterface::beginRenderEyeFrame(uint32_t eye) { +#if CC_USE_XR + if (IS_ENABLE_XR_LOG) CC_LOG_INFO("[XR] beginRenderEyeFrame %d", eye); + if (gfx::DeviceAgent::getInstance()) { + ENQUEUE_MESSAGE_1(gfx::DeviceAgent::getInstance()->getMessageQueue(), + BeginRenderEyeFrame, eye, eye, + { + if (IS_ENABLE_XR_LOG) CC_LOG_INFO("[XR] [RT] beginRenderEyeFrame %d", eye); + xr::XrEntry::getInstance()->renderLoopStart(eye); + }); + } else { + xr::XrEntry::getInstance()->renderLoopStart(eye); + } +#else + CC_UNUSED_PARAM(eye); +#endif + return true; +} + +bool XRInterface::endRenderEyeFrame(uint32_t eye) { +#if CC_USE_XR + if (IS_ENABLE_XR_LOG) CC_LOG_INFO("[XR] endRenderEyeFrame %d", eye); + if (gfx::DeviceAgent::getInstance()) { + ENQUEUE_MESSAGE_1(gfx::DeviceAgent::getInstance()->getMessageQueue(), + EndRenderEyeFrame, eye, eye, + { + if (IS_ENABLE_XR_LOG) CC_LOG_INFO("[XR] [RT] endRenderEyeFrame %d", eye); + xr::XrEntry::getInstance()->renderLoopEnd(eye); + }); + } else { + xr::XrEntry::getInstance()->renderLoopEnd(eye); + } +#else + CC_UNUSED_PARAM(eye); +#endif + return true; +} + +bool XRInterface::endRenderFrame() { +#if CC_USE_XR + if (IS_ENABLE_XR_LOG) CC_LOG_INFO("[XR] endRenderFrame.%d", + cc::ApplicationManager::getInstance()->getCurrentAppSafe()->getEngine()->getTotalFrames()); + + if (gfx::DeviceAgent::getInstance()) { + ENQUEUE_MESSAGE_0(gfx::DeviceAgent::getInstance()->getMessageQueue(), + EndRenderFrame, + { + xr::XrEntry::getInstance()->frameEnd(); + gfx::DeviceAgent::getInstance()->presentSignal(); + if (IS_ENABLE_XR_LOG) CC_LOG_INFO("[XR] [RT] presentSignal endRenderFrame.%d", + cc::ApplicationManager::getInstance()->getCurrentAppSafe()->getEngine()->getTotalFrames()); + }); + _committedFrame = true; + // CC_LOG_INFO("[XR] endRenderFrame pass presentWait errno %d", errno); + } else { + xr::XrEntry::getInstance()->frameEnd(); + } +#endif + return true; +} + +bool XRInterface::platformLoopEnd() { +#if CC_USE_XR + return xr::XrEntry::getInstance()->platformLoopEnd(); +#else + return false; +#endif +} +// stereo render loop + +ccstd::vector XRInterface::getHMDViewPosition(uint32_t eye, int trackingType) { +#if CC_USE_XR + return xr::XrEntry::getInstance()->getHMDViewPosition(eye, trackingType); +#else + CC_UNUSED_PARAM(eye); + CC_UNUSED_PARAM(trackingType); + ccstd::vector res; + res.reserve(3); + return res; +#endif +} + +ccstd::vector XRInterface::getXRViewProjectionData(uint32_t eye, float near, float far) { +#if CC_USE_XR + return xr::XrEntry::getInstance()->computeViewProjection(eye, near, far, 1.0F); +#else + CC_UNUSED_PARAM(eye); + CC_UNUSED_PARAM(near); + CC_UNUSED_PARAM(far); + ccstd::vector res; + res.reserve(16); + return res; +#endif +} + +// renderwindow +xr::XREye XRInterface::getXREyeByRenderWindow(void *window) { + if (!window) { + return xr::XREye::NONE; + } + if (_xrWindowMap.count(window) > 0) { + return _xrWindowMap[window]; + } + return xr::XREye::NONE; +} + +void XRInterface::bindXREyeWithRenderWindow(void *window, xr::XREye eye) { + if (_xrWindowMap.count(window) > 0) { + _xrWindowMap[window] = eye; + } else { + _xrWindowMap.emplace(std::make_pair(window, eye)); + } +} +} // namespace cc diff --git a/native/cocos/platform/java/modules/XRInterface.h b/native/cocos/platform/java/modules/XRInterface.h new file mode 100644 index 0000000000..a2b19db8b0 --- /dev/null +++ b/native/cocos/platform/java/modules/XRInterface.h @@ -0,0 +1,114 @@ +/**************************************************************************** + Copyright (c) 2021-2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IXRInterface.h" +namespace cc { + +class XRInterface : public IXRInterface { +public: + xr::XRVendor getVendor() override; + xr::XRConfigValue getXRConfig(xr::XRConfigKey key) override; + void setXRConfig(xr::XRConfigKey key, xr::XRConfigValue value) override; + + uint32_t getRuntimeVersion() override; + void initialize(void *javaVM, void *activity) override; + + // render thread lifecycle + void onRenderPause() override; + void onRenderResume() override; + void onRenderDestroy() override; + // render thread lifecycle + + // gfx + void preGFXDeviceInitialize(gfx::API gfxApi) override; + void postGFXDeviceInitialize(gfx::API gfxApi) override; + const xr::XRSwapchain &doGFXDeviceAcquire(gfx::API gfxApi) override; + bool isGFXDeviceNeedsPresent(gfx::API gfxApi) override; + void postGFXDevicePresent(gfx::API gfxApi) override; + void createXRSwapchains() override; + const std::vector &getXRSwapchains() override; + gfx::Format getXRSwapchainFormat() override; + void updateXRSwapchainTypedID(uint32_t typedID) override; + // gfx + + // vulkan +#ifdef CC_USE_VULKAN + uint32_t getXRVkApiVersion(uint32_t engineVkApiVersion) override; + void initializeVulkanData(const PFN_vkGetInstanceProcAddr &addr) override; + VkInstance createXRVulkanInstance(const VkInstanceCreateInfo &instInfo) override; + VkDevice createXRVulkanDevice(const VkDeviceCreateInfo *deviceInfo) override; + VkPhysicalDevice getXRVulkanGraphicsDevice() override; + void getXRSwapchainVkImages(std::vector &vkImages, uint32_t eye) override; +#endif + // vulkan + + // gles +#ifdef CC_USE_GLES3 + void initializeGLESData(xr::PFNGLES3WLOADPROC gles3wLoadFuncProc, gfx::GLES3GPUContext *gpuContext) override; + void attachGLESFramebufferTexture2D() override; + EGLSurfaceType acquireEGLSurfaceType(uint32_t typedID) override; +#endif + // gles + + // stereo render loop + bool platformLoopStart() override; + bool beginRenderFrame() override; + bool isRenderAllowable() override; + bool beginRenderEyeFrame(uint32_t eye) override; + bool endRenderEyeFrame(uint32_t eye) override; + bool endRenderFrame() override; + bool platformLoopEnd() override; + // stereo render loop + + ccstd::vector getHMDViewPosition(uint32_t eye, int trackingType) override; + ccstd::vector getXRViewProjectionData(uint32_t eye, float near, float far) override; + // renderwindow + xr::XREye getXREyeByRenderWindow(void *window) override; + void bindXREyeWithRenderWindow(void *window, xr::XREye eye) override; + +private: +#if CC_USE_VULKAN + PFN_vkGetInstanceProcAddr _vkGetInstanceProcAddr{nullptr}; + VkPhysicalDevice _vkPhysicalDevice{nullptr}; + VkInstance _vkInstance{nullptr}; + VkDevice _vkDevice{nullptr}; +#endif + +#if CC_USE_GLES3 + xr::PFNGLES3WLOADPROC _gles3wLoadFuncProc{nullptr}; + gfx::GLES3GPUContext *_gles3GPUContext{nullptr}; +#endif + xr::XRSwapchain _acquireSwapchain; + std::vector _xrSwapchains; + bool _renderPaused{false}; + bool _renderResumed{false}; + std::unordered_map _xrWindowMap; + std::unordered_map _eglSurfaceTypeMap; + bool _committedFrame{false}; +}; + +} // namespace cc diff --git a/native/cocos/renderer/GFXDeviceManager.h b/native/cocos/renderer/GFXDeviceManager.h index 9ac84716ab..4091a07ed4 100644 --- a/native/cocos/renderer/GFXDeviceManager.h +++ b/native/cocos/renderer/GFXDeviceManager.h @@ -64,7 +64,13 @@ namespace cc { namespace gfx { class CC_DLL DeviceManager final { +#if CC_USE_XR && CC_USE_VULKAN && XR_OEM_META static constexpr bool DETACH_DEVICE_THREAD{true}; +#elif CC_USE_XR + static constexpr bool DETACH_DEVICE_THREAD{false}; +#else + static constexpr bool DETACH_DEVICE_THREAD{true}; +#endif static constexpr bool FORCE_DISABLE_VALIDATION{false}; static constexpr bool FORCE_ENABLE_VALIDATION{false}; diff --git a/native/cocos/renderer/gfx-agent/DeviceAgent.cpp b/native/cocos/renderer/gfx-agent/DeviceAgent.cpp index bb10518934..2a07266298 100644 --- a/native/cocos/renderer/gfx-agent/DeviceAgent.cpp +++ b/native/cocos/renderer/gfx-agent/DeviceAgent.cpp @@ -67,7 +67,7 @@ bool DeviceAgent::doInit(const DeviceInfo &info) { if (!_actor->initialize(info)) { return false; } - + _xr = CC_GET_XR_INTERFACE(); _api = _actor->getGfxAPI(); _deviceName = _actor->getDeviceName(); _queue = ccnew QueueAgent(_actor->getQueue()); @@ -145,19 +145,28 @@ void DeviceAgent::acquire(Swapchain *const *swapchains, uint32_t count) { } void DeviceAgent::present() { - ENQUEUE_MESSAGE_2( - _mainMessageQueue, DevicePresent, - actor, _actor, - frameBoundarySemaphore, &_frameBoundarySemaphore, - { - actor->present(); - frameBoundarySemaphore->signal(); - }); + if (_xr) { + ENQUEUE_MESSAGE_1( + _mainMessageQueue, DevicePresent, + actor, _actor, + { + actor->present(); + }); + } else { + ENQUEUE_MESSAGE_2( + _mainMessageQueue, DevicePresent, + actor, _actor, + frameBoundarySemaphore, &_frameBoundarySemaphore, + { + actor->present(); + frameBoundarySemaphore->signal(); + }); - MessageQueue::freeChunksInFreeQueue(_mainMessageQueue); - _mainMessageQueue->finishWriting(); - _currentIndex = (_currentIndex + 1) % MAX_FRAME_INDEX; - _frameBoundarySemaphore.wait(); + MessageQueue::freeChunksInFreeQueue(_mainMessageQueue); + _mainMessageQueue->finishWriting(); + _currentIndex = (_currentIndex + 1) % MAX_FRAME_INDEX; + _frameBoundarySemaphore.wait(); + } } void DeviceAgent::setMultithreaded(bool multithreaded) { @@ -411,5 +420,16 @@ void DeviceAgent::getQueryPoolResults(QueryPool *queryPool) { queryPoolAgent->_results = actorQueryPoolAgent->_results; } +void DeviceAgent::presentSignal() { + _frameBoundarySemaphore.signal(); +} + +void DeviceAgent::presentWait() { + MessageQueue::freeChunksInFreeQueue(_mainMessageQueue); + _mainMessageQueue->finishWriting(); + _currentIndex = (_currentIndex + 1) % MAX_FRAME_INDEX; + _frameBoundarySemaphore.wait(); +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-agent/DeviceAgent.h b/native/cocos/renderer/gfx-agent/DeviceAgent.h index 2377d1bd30..029d0d3c93 100644 --- a/native/cocos/renderer/gfx-agent/DeviceAgent.h +++ b/native/cocos/renderer/gfx-agent/DeviceAgent.h @@ -101,6 +101,9 @@ public: inline MessageQueue *getMessageQueue() const { return _mainMessageQueue; } + void presentWait(); + void presentSignal(); + protected: static DeviceAgent *instance; @@ -116,9 +119,14 @@ protected: MessageQueue *_mainMessageQueue{nullptr}; uint32_t _currentIndex = 0U; +#if CC_USE_XR + Semaphore _frameBoundarySemaphore{0}; +#else Semaphore _frameBoundarySemaphore{MAX_CPU_FRAME_AHEAD}; +#endif ccstd::unordered_set _cmdBuffRefs; + IXRInterface *_xr{nullptr}; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/GFXDevice.cpp b/native/cocos/renderer/gfx-base/GFXDevice.cpp index 914ea46cef..ee8548b3ef 100644 --- a/native/cocos/renderer/gfx-base/GFXDevice.cpp +++ b/native/cocos/renderer/gfx-base/GFXDevice.cpp @@ -61,6 +61,7 @@ bool Device::initialize(const DeviceInfo &info) { static_assert(sizeof(void *) == 8, "pointer size assumption broken"); #endif + _xr = CC_GET_XR_INTERFACE(); bool result = doInit(info); CC_SAFE_ADD_REF(_cmdBuff); @@ -140,5 +141,20 @@ BufferBarrier *Device::getBufferBarrier(const BufferBarrierInfo &info) { return _bufferBarriers[info]; } +Swapchain *Device::createXRSwapchain(const SwapchainInfo &info) { + _xr->createXRSwapchains(); + int swapChainWidth = _xr->getXRConfig(xr::XRConfigKey::SWAPCHAIN_WIDTH).getInt(); + int swapChainHeight = _xr->getXRConfig(xr::XRConfigKey::SWAPCHAIN_HEIGHT).getInt(); + Swapchain *res = createSwapchain(); + _xr->updateXRSwapchainTypedID(res->getTypedID()); + SwapchainInfo swapchainInfo; + swapchainInfo.copy(info); + swapchainInfo.width = swapChainWidth; + swapchainInfo.height = swapChainHeight; + res->initialize(swapchainInfo); + _swapchains.push_back(res); + return res; +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-base/GFXDevice.h b/native/cocos/renderer/gfx-base/GFXDevice.h index f1140378b2..904b15f9aa 100644 --- a/native/cocos/renderer/gfx-base/GFXDevice.h +++ b/native/cocos/renderer/gfx-base/GFXDevice.h @@ -40,8 +40,10 @@ #include "GFXShader.h" #include "GFXSwapchain.h" #include "GFXTexture.h" +#include "application/ApplicationManager.h" #include "base/RefCounted.h" #include "base/std/container/array.h" +#include "platform/java/modules/XRInterface.h" #include "states/GFXBufferBarrier.h" #include "states/GFXGeneralBarrier.h" #include "states/GFXSampler.h" @@ -73,6 +75,7 @@ public: inline Queue *createQueue(const QueueInfo &info); inline QueryPool *createQueryPool(const QueryPoolInfo &info); inline Swapchain *createSwapchain(const SwapchainInfo &info); + inline const ccstd::vector &getSwapchains() const { return _swapchains; } inline Buffer *createBuffer(const BufferInfo &info); inline Buffer *createBuffer(const BufferViewInfo &info); inline Texture *createTexture(const TextureInfo &info); @@ -150,6 +153,7 @@ protected: virtual DescriptorSetLayout *createDescriptorSetLayout() = 0; virtual PipelineLayout *createPipelineLayout() = 0; virtual PipelineState *createPipelineState() = 0; + virtual Swapchain *createXRSwapchain(const SwapchainInfo &info); virtual Sampler *createSampler(const SamplerInfo &info) { return ccnew Sampler(info); } virtual GeneralBarrier *createGeneralBarrier(const GeneralBarrierInfo &info) { return ccnew GeneralBarrier(info); } @@ -188,6 +192,8 @@ protected: ccstd::unordered_map> _textureBarriers; ccstd::unordered_map> _bufferBarriers; + IXRInterface *_xr{nullptr}; + private: ccstd::vector _swapchains; // weak reference }; @@ -213,6 +219,9 @@ QueryPool *Device::createQueryPool(const QueryPoolInfo &info) { } Swapchain *Device::createSwapchain(const SwapchainInfo &info) { + if (_xr) { + return createXRSwapchain(info); + } Swapchain *res = createSwapchain(); res->initialize(info); _swapchains.push_back(res); diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp index 1ed8e04628..8e153deb83 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp @@ -43,6 +43,8 @@ #include "GLES3Shader.h" #include "GLES3Swapchain.h" #include "GLES3Texture.h" +#include "application/ApplicationManager.h" +#include "platform/java/modules/XRInterface.h" #include "profiler/Profiler.h" #include "states/GLES3GeneralBarrier.h" #include "states/GLES3Sampler.h" @@ -72,6 +74,8 @@ GLES3Device::~GLES3Device() { } bool GLES3Device::doInit(const DeviceInfo & /*info*/) { + _xr = CC_GET_XR_INTERFACE(); + if (_xr) _xr->preGFXDeviceInitialize(_api); _gpuContext = ccnew GLES3GPUContext; _gpuStateCache = ccnew GLES3GPUStateCache; _gpuFramebufferHub = ccnew GLES3GPUFramebufferHub; @@ -224,6 +228,10 @@ bool GLES3Device::doInit(const DeviceInfo & /*info*/) { CC_LOG_INFO("COMPRESSED_FORMATS: %s", compressedFmts.c_str()); CC_LOG_INFO("FRAMEBUFFER_FETCH: %s", fbfLevelStr.c_str()); + if (_xr) { + _xr->initializeGLESData(pfnGLES3wLoadProc(), GLES3Device::getInstance()->context()); + _xr->postGFXDeviceInitialize(_api); + } return true; } @@ -246,6 +254,24 @@ void GLES3Device::acquire(Swapchain *const *swapchains, uint32_t count) { if (_onAcquire) _onAcquire->execute(); _swapchains.clear(); + if (_xr) { + GLuint xrFramebuffer = 0; +#if XR_OEM_HUAWEIVR + stateCache()->glTextures[stateCache()->texUint] = 0; + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, reinterpret_cast(&xrFramebuffer)); + stateCache()->glDrawFramebuffer = xrFramebuffer; +#else + xr::XRSwapchain xrSwapchain = _xr->doGFXDeviceAcquire(_api); + xrFramebuffer = xrSwapchain.glDrawFramebuffer; +#endif + for (uint32_t i = 0; i < count; ++i) { + GL_CHECK(_xr->attachGLESFramebufferTexture2D();); + static_cast(swapchains[i])->gpuSwapchain()->glFramebuffer = xrFramebuffer; + _swapchains.push_back(static_cast(swapchains[i])->gpuSwapchain()); + } + return; + } + for (uint32_t i = 0; i < count; ++i) { _swapchains.push_back(static_cast(swapchains[i])->gpuSwapchain()); } @@ -258,9 +284,11 @@ void GLES3Device::present() { _numInstances = queue->_numInstances; _numTriangles = queue->_numTriangles; + bool isGFXDeviceNeedsPresent = _xr ? _xr->isGFXDeviceNeedsPresent(_api) : true; for (auto *swapchain : _swapchains) { - _gpuContext->present(swapchain); + if (isGFXDeviceNeedsPresent) _gpuContext->present(swapchain); } + if (_xr) _xr->postGFXDevicePresent(_api); // Clear queue stats queue->_numDrawCalls = 0; diff --git a/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp b/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp index 3b18f1c89d..9350ba4557 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp @@ -295,8 +295,8 @@ void GLES3GPUContext::bindContext(bool bound) { } void GLES3GPUContext::makeCurrent(const GLES3GPUSwapchain *drawSwapchain, const GLES3GPUSwapchain *readSwapchain) { - EGLSurface drawSurface = drawSwapchain ? drawSwapchain->eglSurface : _eglCurrentDrawSurface; - EGLSurface readSurface = readSwapchain ? readSwapchain->eglSurface : _eglCurrentReadSurface; + EGLSurface drawSurface = drawSwapchain && drawSwapchain->eglSurface ? drawSwapchain->eglSurface : _eglCurrentDrawSurface; + EGLSurface readSurface = readSwapchain && readSwapchain->eglSurface ? readSwapchain->eglSurface : _eglCurrentReadSurface; if (_eglCurrentDrawSurface == drawSurface && _eglCurrentReadSurface == readSurface) return; makeCurrent(drawSurface, readSurface, _eglCurrentContext); diff --git a/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp b/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp index 294d8aa548..4ca0f43a96 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp @@ -96,10 +96,23 @@ void GLES3Swapchain::doInit(const SwapchainInfo &info) { #endif #endif - EGL_CHECK(_gpuSwapchain->eglSurface = eglCreateWindowSurface(context->eglDisplay, context->eglConfig, window, nullptr)); - if (_gpuSwapchain->eglSurface == EGL_NO_SURFACE) { - CC_LOG_ERROR("Create window surface failed."); - return; + IXRInterface *xr = CC_GET_XR_INTERFACE(); + EGLSurfaceType surfaceType = xr ? xr->acquireEGLSurfaceType(getTypedID()) : EGLSurfaceType::WINDOW; + if (surfaceType == EGLSurfaceType::PBUFFER) { + EGLint pbufferAttribs[]{ + EGL_WIDTH, 1, + EGL_HEIGHT, 1, + EGL_NONE}; + EGL_CHECK(_gpuSwapchain->eglSurface = eglCreatePbufferSurface(context->eglDisplay, context->eglConfig, pbufferAttribs)); + } else if (surfaceType == EGLSurfaceType::WINDOW) { + EGL_CHECK(_gpuSwapchain->eglSurface = eglCreateWindowSurface(context->eglDisplay, context->eglConfig, window, nullptr)); + if (_gpuSwapchain->eglSurface == EGL_NO_SURFACE) { + CC_LOG_ERROR("Create window surface failed."); + return; + } + } + if (xr) { + GLES3Device::getInstance()->context()->makeCurrent(_gpuSwapchain, _gpuSwapchain); } switch (_vsyncMode) { @@ -195,10 +208,21 @@ void GLES3Swapchain::doCreateSurface(void *windowHandle) { #endif if (_gpuSwapchain->eglSurface == EGL_NO_SURFACE) { - EGL_CHECK(_gpuSwapchain->eglSurface = eglCreateWindowSurface(context->eglDisplay, context->eglConfig, window, nullptr)); - if (_gpuSwapchain->eglSurface == EGL_NO_SURFACE) { - CC_LOG_ERROR("Recreate window surface failed."); - return; + IXRInterface *xr = CC_GET_XR_INTERFACE(); + EGLSurfaceType surfaceType = xr ? xr->acquireEGLSurfaceType(getTypedID()) : EGLSurfaceType::WINDOW; + if (surfaceType == EGLSurfaceType::PBUFFER) { + EGLint pbufferAttribs[]{ + EGL_WIDTH, 1, + EGL_HEIGHT, 1, + EGL_NONE}; + EGL_CHECK(_gpuSwapchain->eglSurface = eglCreatePbufferSurface(context->eglDisplay, context->eglConfig, pbufferAttribs)); + } else if (surfaceType == EGLSurfaceType::WINDOW) { + EGL_CHECK(_gpuSwapchain->eglSurface = eglCreateWindowSurface(context->eglDisplay, context->eglConfig, window, nullptr)); + + if (_gpuSwapchain->eglSurface == EGL_NO_SURFACE) { + CC_LOG_ERROR("Recreate window surface failed."); + return; + } } } diff --git a/native/cocos/renderer/gfx-gles3/GLES3Wrangler.cpp b/native/cocos/renderer/gfx-gles3/GLES3Wrangler.cpp index 91f52a3ed8..46cc2ebce9 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Wrangler.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Wrangler.cpp @@ -31,6 +31,7 @@ static HMODULE libegl = NULL; static HMODULE libgles = NULL; +static PFNGLES3WLOADPROC pfnGles3wLoad = NULL; bool gles3wOpen() { libegl = LoadLibraryA("libEGL.dll"); @@ -70,6 +71,7 @@ void *gles3wLoad(const char *proc) { static void *libegl = nullptr; static void *libgles = nullptr; +static PFNGLES3WLOADPROC pfnGles3wLoad = nullptr; bool gles3wOpen() { libegl = dlopen("libEGL.so", RTLD_LAZY | RTLD_GLOBAL); @@ -100,15 +102,19 @@ void *gles3wLoad(const char *proc) { } #endif +PFNGLES3WLOADPROC pfnGLES3wLoadProc() { + return pfnGles3wLoad; +} + bool gles3wInit() { if (!gles3wOpen()) { return false; } - eglwLoadProcs(gles3wLoad); gles2wLoadProcs(gles3wLoad); gles3wLoadProcs(gles3wLoad); + pfnGles3wLoad = gles3wLoad; return true; } diff --git a/native/cocos/renderer/gfx-gles3/GLES3Wrangler.h b/native/cocos/renderer/gfx-gles3/GLES3Wrangler.h index feb2c437d7..03a7e722f7 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Wrangler.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Wrangler.h @@ -29,5 +29,6 @@ #include "../gfx-gles-common/gles2w.h" #include "../gfx-gles-common/gles3w.h" +PFNGLES3WLOADPROC pfnGLES3wLoadProc(); bool gles3wInit(); bool gles3wExit(); diff --git a/native/cocos/renderer/gfx-validator/DeviceValidator.cpp b/native/cocos/renderer/gfx-validator/DeviceValidator.cpp index 71be99fd5f..15462b3ebb 100644 --- a/native/cocos/renderer/gfx-validator/DeviceValidator.cpp +++ b/native/cocos/renderer/gfx-validator/DeviceValidator.cpp @@ -77,7 +77,7 @@ bool DeviceValidator::doInit(const DeviceInfo &info) { if (!_actor->initialize(info)) { return false; } - + _xr = CC_GET_XR_INTERFACE(); _api = _actor->getGfxAPI(); _deviceName = _actor->getDeviceName(); _queue = ccnew QueueValidator(_actor->getQueue()); diff --git a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp index 332f512bdd..23af8a8196 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp @@ -48,6 +48,7 @@ #include "states/VKTextureBarrier.h" #include "gfx-base/SPIRVUtils.h" +#include "platform/BasePlatform.h" #include "profiler/Profiler.h" #if CC_SWAPPY_ENABLED @@ -95,6 +96,10 @@ CCVKDevice::~CCVKDevice() { } bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { + _xr = CC_GET_XR_INTERFACE(); + if (_xr) { + _xr->preGFXDeviceInitialize(_api); + } _gpuContext = ccnew CCVKGPUContext; if (!_gpuContext->initialize()) { CC_SAFE_DESTROY_AND_DELETE(_gpuContext) @@ -217,8 +222,11 @@ bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { } } - VK_CHECK(vkCreateDevice(_gpuContext->physicalDevice, &deviceCreateInfo, nullptr, &_gpuDevice->vkDevice)); - + if (_xr) { + _gpuDevice->vkDevice = _xr->createXRVulkanDevice(&deviceCreateInfo); + } else { + VK_CHECK(vkCreateDevice(_gpuContext->physicalDevice, &deviceCreateInfo, nullptr, &_gpuDevice->vkDevice)); + } volkLoadDevice(_gpuDevice->vkDevice); SPIRVUtils::getInstance()->initialize(static_cast(_gpuDevice->minorVersion)); @@ -477,6 +485,11 @@ bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { CC_LOG_INFO("DEVICE_EXTENSIONS: %s", deviceExtensions.c_str()); CC_LOG_INFO("COMPRESSED_FORMATS: %s", compressedFmts.c_str()); + if (_xr) { + cc::gfx::CCVKGPUQueue *vkQueue = static_cast(getQueue())->gpuQueue(); + _xr->setXRConfig(xr::XRConfigKey::VK_QUEUE_FAMILY_INDEX, static_cast(vkQueue->queueFamilyIndex)); + _xr->postGFXDeviceInitialize(_api); + } return true; } @@ -610,14 +623,24 @@ void CCVKDevice::acquire(Swapchain *const *swapchains, uint32_t count) { vkSwapchains.clear(); vkAcquireBarriers.resize(count, acquireBarrier); vkPresentBarriers.resize(count, presentBarrier); - for (uint32_t i = 0U; i < count; ++i) { auto *swapchain = static_cast(swapchains[i]); if (swapchain->gpuSwapchain()->lastPresentResult == VK_NOT_READY) { - if (!swapchain->checkSwapchainStatus()) continue; + if (!swapchain->checkSwapchainStatus()) { + continue; + } + } + + if (_xr) { + xr::XRSwapchain xrSwapchain = _xr->doGFXDeviceAcquire(_api); + swapchain->gpuSwapchain()->curImageIndex = xrSwapchain.swapchainImageIndex; + } + if (swapchain->gpuSwapchain()->vkSwapchain) { + vkSwapchains.push_back(swapchain->gpuSwapchain()->vkSwapchain); + } + if (swapchain->gpuSwapchain()) { + gpuSwapchains.push_back(swapchain->gpuSwapchain()); } - vkSwapchains.push_back(swapchain->gpuSwapchain()->vkSwapchain); - gpuSwapchains.push_back(swapchain->gpuSwapchain()); vkSwapchainIndices.push_back(swapchain->gpuSwapchain()->curImageIndex); } @@ -653,6 +676,7 @@ void CCVKDevice::acquire(Swapchain *const *swapchains, uint32_t count) { void CCVKDevice::present() { CC_PROFILE(CCVKDevicePresent); + bool isGFXDeviceNeedsPresent = _xr ? _xr->isGFXDeviceNeedsPresent(_api) : true; auto *queue = static_cast(_queue); _numDrawCalls = queue->_numDrawCalls; _numInstances = queue->_numInstances; @@ -682,7 +706,7 @@ void CCVKDevice::present() { presentInfo.pSwapchains = vkSwapchains.data(); presentInfo.pImageIndices = vkSwapchainIndices.data(); - VkResult res = vkCCPresentFunc(queue->gpuQueue()->vkQueue, &presentInfo); + VkResult res = !isGFXDeviceNeedsPresent ? VK_SUCCESS : vkCCPresentFunc(queue->gpuQueue()->vkQueue, &presentInfo); for (auto *gpuSwapchain : gpuSwapchains) { gpuSwapchain->lastPresentResult = res; } @@ -699,6 +723,9 @@ void CCVKDevice::present() { gpuFencePool()->reset(); gpuRecycleBin()->clear(); gpuStagingBufferPool()->reset(); + if (_xr) { + _xr->postGFXDevicePresent(_api); + } } CCVKGPUFencePool *CCVKDevice::gpuFencePool() { return _gpuFencePools[_gpuDevice->curBackBufferIndex]; } diff --git a/native/cocos/renderer/gfx-vulkan/VKGPUContext.cpp b/native/cocos/renderer/gfx-vulkan/VKGPUContext.cpp index 994ddcd084..b1fefa87c4 100644 --- a/native/cocos/renderer/gfx-vulkan/VKGPUContext.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKGPUContext.cpp @@ -24,6 +24,8 @@ ****************************************************************************/ #include "VKGPUObjects.h" +#include "application/ApplicationManager.h" +#include "platform/java/modules/XRInterface.h" namespace cc { namespace gfx { @@ -118,6 +120,8 @@ bool CCVKGPUContext::initialize() { } } + IXRInterface *xr = CC_GET_XR_INTERFACE(); + if (xr) apiVersion = xr->getXRVkApiVersion(apiVersion); minorVersion = VK_VERSION_MINOR(apiVersion); if (minorVersion < 1) { requestedExtensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME); @@ -242,12 +246,16 @@ bool CCVKGPUContext::initialize() { #endif // Create the Vulkan instance - VkResult res = vkCreateInstance(&instanceInfo, nullptr, &vkInstance); - if (res == VK_ERROR_LAYER_NOT_PRESENT) { - CC_LOG_ERROR("Create Vulkan instance failed due to missing layers, aborting..."); - return false; + if (xr) { + xr->initializeVulkanData(vkGetInstanceProcAddr); + vkInstance = xr->createXRVulkanInstance(instanceInfo); + } else { + VkResult res = vkCreateInstance(&instanceInfo, nullptr, &vkInstance); + if (res == VK_ERROR_LAYER_NOT_PRESENT) { + CC_LOG_ERROR("Create Vulkan instance failed due to missing layers, aborting..."); + return false; + } } - volkLoadInstanceOnly(vkInstance); #if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION || FORCE_ENABLE_VALIDATION @@ -263,14 +271,18 @@ bool CCVKGPUContext::initialize() { // Querying valid physical devices on the machine uint32_t physicalDeviceCount{0}; - res = vkEnumeratePhysicalDevices(vkInstance, &physicalDeviceCount, nullptr); + VkResult res = vkEnumeratePhysicalDevices(vkInstance, &physicalDeviceCount, nullptr); if (res || physicalDeviceCount < 1) { return false; } ccstd::vector physicalDeviceHandles(physicalDeviceCount); - VK_CHECK(vkEnumeratePhysicalDevices(vkInstance, &physicalDeviceCount, physicalDeviceHandles.data())); + if (xr) { + physicalDeviceHandles[0] = xr->getXRVulkanGraphicsDevice(); + } else { + VK_CHECK(vkEnumeratePhysicalDevices(vkInstance, &physicalDeviceCount, physicalDeviceHandles.data())); + } ccstd::vector physicalDevicePropertiesList(physicalDeviceCount); diff --git a/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp b/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp index 3706f99643..54990eea3d 100644 --- a/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp @@ -31,6 +31,7 @@ #include "VKRenderPass.h" #include "VKTexture.h" #include "VKUtils.h" +#include "platform/BasePlatform.h" #include "application/ApplicationManager.h" #include "platform/interfaces/modules/ISystemWindow.h" @@ -58,6 +59,7 @@ void CCVKSwapchain::doInit(const SwapchainInfo &info) { const auto *gpuContext = CCVKDevice::getInstance()->gpuContext(); _gpuSwapchain = ccnew CCVKGPUSwapchain; gpuDevice->swapchains.insert(_gpuSwapchain); + _xr = CC_GET_XR_INTERFACE(); createVkSurface(); @@ -66,8 +68,12 @@ void CCVKSwapchain::doInit(const SwapchainInfo &info) { uint32_t queueFamilyPropertiesCount = utils::toUint(gpuContext->queueFamilyProperties.size()); _gpuSwapchain->queueFamilyPresentables.resize(queueFamilyPropertiesCount); for (uint32_t propertyIndex = 0U; propertyIndex < queueFamilyPropertiesCount; propertyIndex++) { - vkGetPhysicalDeviceSurfaceSupportKHR(gpuContext->physicalDevice, propertyIndex, - _gpuSwapchain->vkSurface, &_gpuSwapchain->queueFamilyPresentables[propertyIndex]); + if (_xr) { + _gpuSwapchain->queueFamilyPresentables[propertyIndex] = true; + } else { + vkGetPhysicalDeviceSurfaceSupportKHR(gpuContext->physicalDevice, propertyIndex, + _gpuSwapchain->vkSurface, &_gpuSwapchain->queueFamilyPresentables[propertyIndex]); + } } // find other possible queues if not presentable @@ -85,122 +91,125 @@ void CCVKSwapchain::doInit(const SwapchainInfo &info) { Format colorFmt = Format::BGRA8; Format depthStencilFmt = Format::DEPTH_STENCIL; - VkSurfaceCapabilitiesKHR surfaceCapabilities{}; - vkGetPhysicalDeviceSurfaceCapabilitiesKHR(gpuContext->physicalDevice, _gpuSwapchain->vkSurface, &surfaceCapabilities); + if (_gpuSwapchain->vkSurface != VK_NULL_HANDLE) { + VkSurfaceCapabilitiesKHR surfaceCapabilities{}; + vkGetPhysicalDeviceSurfaceCapabilitiesKHR(gpuContext->physicalDevice, _gpuSwapchain->vkSurface, &surfaceCapabilities); - uint32_t surfaceFormatCount = 0U; - VK_CHECK(vkGetPhysicalDeviceSurfaceFormatsKHR(gpuContext->physicalDevice, _gpuSwapchain->vkSurface, &surfaceFormatCount, nullptr)); - ccstd::vector surfaceFormats(surfaceFormatCount); - VK_CHECK(vkGetPhysicalDeviceSurfaceFormatsKHR(gpuContext->physicalDevice, _gpuSwapchain->vkSurface, &surfaceFormatCount, surfaceFormats.data())); + uint32_t surfaceFormatCount = 0U; + VK_CHECK(vkGetPhysicalDeviceSurfaceFormatsKHR(gpuContext->physicalDevice, _gpuSwapchain->vkSurface, &surfaceFormatCount, nullptr)); + ccstd::vector surfaceFormats(surfaceFormatCount); + VK_CHECK(vkGetPhysicalDeviceSurfaceFormatsKHR(gpuContext->physicalDevice, _gpuSwapchain->vkSurface, &surfaceFormatCount, surfaceFormats.data())); - uint32_t presentModeCount = 0U; - VK_CHECK(vkGetPhysicalDeviceSurfacePresentModesKHR(gpuContext->physicalDevice, _gpuSwapchain->vkSurface, &presentModeCount, nullptr)); - ccstd::vector presentModes(presentModeCount); - VK_CHECK(vkGetPhysicalDeviceSurfacePresentModesKHR(gpuContext->physicalDevice, _gpuSwapchain->vkSurface, &presentModeCount, presentModes.data())); + uint32_t presentModeCount = 0U; + VK_CHECK(vkGetPhysicalDeviceSurfacePresentModesKHR(gpuContext->physicalDevice, _gpuSwapchain->vkSurface, &presentModeCount, nullptr)); + ccstd::vector presentModes(presentModeCount); + VK_CHECK(vkGetPhysicalDeviceSurfacePresentModesKHR(gpuContext->physicalDevice, _gpuSwapchain->vkSurface, &presentModeCount, presentModes.data())); - VkFormat colorFormat = VK_FORMAT_B8G8R8A8_UNORM; - VkColorSpaceKHR colorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; - // If the surface format list only includes one entry with VK_FORMAT_UNDEFINED, - // there is no preferred format, so we assume VK_FORMAT_B8G8R8A8_UNORM - if ((surfaceFormatCount == 1) && (surfaceFormats[0].format == VK_FORMAT_UNDEFINED)) { - colorFormat = VK_FORMAT_B8G8R8A8_UNORM; - colorSpace = surfaceFormats[0].colorSpace; - } else { - // iterate over the list of available surface format and - // check for the presence of VK_FORMAT_B8G8R8A8_UNORM - bool imageFormatFound = false; - for (VkSurfaceFormatKHR &surfaceFormat : surfaceFormats) { - if (surfaceFormat.format == VK_FORMAT_B8G8R8A8_UNORM) { - colorFormat = surfaceFormat.format; - colorSpace = surfaceFormat.colorSpace; - imageFormatFound = true; + VkFormat colorFormat = VK_FORMAT_B8G8R8A8_UNORM; + VkColorSpaceKHR colorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; + // If the surface format list only includes one entry with VK_FORMAT_UNDEFINED, + // there is no preferred format, so we assume VK_FORMAT_B8G8R8A8_UNORM + if ((surfaceFormatCount == 1) && (surfaceFormats[0].format == VK_FORMAT_UNDEFINED)) { + colorFormat = VK_FORMAT_B8G8R8A8_UNORM; + colorSpace = surfaceFormats[0].colorSpace; + } else { + // iterate over the list of available surface format and + // check for the presence of VK_FORMAT_B8G8R8A8_UNORM + bool imageFormatFound = false; + for (VkSurfaceFormatKHR &surfaceFormat : surfaceFormats) { + if (surfaceFormat.format == VK_FORMAT_B8G8R8A8_UNORM) { + colorFormat = surfaceFormat.format; + colorSpace = surfaceFormat.colorSpace; + imageFormatFound = true; + break; + } + } + + // in case VK_FORMAT_B8G8R8A8_UNORM is not available + // select the first available color format + if (!imageFormatFound) { + colorFormat = surfaceFormats[0].format; + colorSpace = surfaceFormats[0].colorSpace; + switch (colorFormat) { + case VK_FORMAT_R8G8B8A8_UNORM: colorFmt = Format::RGBA8; break; + case VK_FORMAT_R8G8B8A8_SRGB: colorFmt = Format::SRGB8_A8; break; + case VK_FORMAT_R5G6B5_UNORM_PACK16: colorFmt = Format::R5G6B5; break; + default: CC_ASSERT(false); break; + } + } + } + + // Select a present mode for the swapchain + + ccstd::vector presentModePriorityList; + + switch (_vsyncMode) { + case VsyncMode::OFF: presentModePriorityList.insert(presentModePriorityList.end(), {VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR}); break; + case VsyncMode::ON: presentModePriorityList.insert(presentModePriorityList.end(), {VK_PRESENT_MODE_FIFO_KHR}); break; + case VsyncMode::RELAXED: presentModePriorityList.insert(presentModePriorityList.end(), {VK_PRESENT_MODE_FIFO_RELAXED_KHR, VK_PRESENT_MODE_FIFO_KHR}); break; + case VsyncMode::MAILBOX: presentModePriorityList.insert(presentModePriorityList.end(), {VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR}); break; + case VsyncMode::HALF: presentModePriorityList.insert(presentModePriorityList.end(), {VK_PRESENT_MODE_FIFO_KHR}); break; // no easy fallback + } + + VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR; + + // UNASSIGNED-BestPractices-vkCreateSwapchainKHR-swapchain-presentmode-not-fifo +#if !defined(VK_USE_PLATFORM_ANDROID_KHR) + for (VkPresentModeKHR presentMode : presentModePriorityList) { + if (std::find(presentModes.begin(), presentModes.end(), presentMode) != presentModes.end()) { + swapchainPresentMode = presentMode; break; } } - - // in case VK_FORMAT_B8G8R8A8_UNORM is not available - // select the first available color format - if (!imageFormatFound) { - colorFormat = surfaceFormats[0].format; - colorSpace = surfaceFormats[0].colorSpace; - switch (colorFormat) { - case VK_FORMAT_R8G8B8A8_UNORM: colorFmt = Format::RGBA8; break; - case VK_FORMAT_R8G8B8A8_SRGB: colorFmt = Format::SRGB8_A8; break; - case VK_FORMAT_R5G6B5_UNORM_PACK16: colorFmt = Format::R5G6B5; break; - default: CC_ASSERT(false); break; - } - } - } - - // Select a present mode for the swapchain - - ccstd::vector presentModePriorityList; - - switch (_vsyncMode) { - case VsyncMode::OFF: presentModePriorityList.insert(presentModePriorityList.end(), {VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR}); break; - case VsyncMode::ON: presentModePriorityList.insert(presentModePriorityList.end(), {VK_PRESENT_MODE_FIFO_KHR}); break; - case VsyncMode::RELAXED: presentModePriorityList.insert(presentModePriorityList.end(), {VK_PRESENT_MODE_FIFO_RELAXED_KHR, VK_PRESENT_MODE_FIFO_KHR}); break; - case VsyncMode::MAILBOX: presentModePriorityList.insert(presentModePriorityList.end(), {VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR}); break; - case VsyncMode::HALF: presentModePriorityList.insert(presentModePriorityList.end(), {VK_PRESENT_MODE_FIFO_KHR}); break; // no easy fallback - } - - VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR; - - // UNASSIGNED-BestPractices-vkCreateSwapchainKHR-swapchain-presentmode-not-fifo -#if !defined(VK_USE_PLATFORM_ANDROID_KHR) - for (VkPresentModeKHR presentMode : presentModePriorityList) { - if (std::find(presentModes.begin(), presentModes.end(), presentMode) != presentModes.end()) { - swapchainPresentMode = presentMode; - break; - } - } #endif - // Determine the number of images - uint32_t desiredNumberOfSwapchainImages = std::max(gpuDevice->backBufferCount, surfaceCapabilities.minImageCount); + // Determine the number of images + uint32_t desiredNumberOfSwapchainImages = std::max(gpuDevice->backBufferCount, surfaceCapabilities.minImageCount); - VkExtent2D imageExtent = {1U, 1U}; + VkExtent2D imageExtent = {1U, 1U}; - // Find a supported composite alpha format (not all devices support alpha opaque) - VkCompositeAlphaFlagBitsKHR compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; - // Simply select the first composite alpha format available - ccstd::vector compositeAlphaFlags = { - VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, - VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR, - VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR, - VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR, - }; - for (VkCompositeAlphaFlagBitsKHR compositeAlphaFlag : compositeAlphaFlags) { - if (surfaceCapabilities.supportedCompositeAlpha & compositeAlphaFlag) { - compositeAlpha = compositeAlphaFlag; - break; + // Find a supported composite alpha format (not all devices support alpha opaque) + VkCompositeAlphaFlagBitsKHR compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; + // Simply select the first composite alpha format available + ccstd::vector compositeAlphaFlags = { + VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, + VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR, + VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR, + VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR, }; - } - VkImageUsageFlags imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; - // Enable transfer source on swap chain images if supported - if (surfaceCapabilities.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) { - imageUsage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; - } + for (VkCompositeAlphaFlagBitsKHR compositeAlphaFlag : compositeAlphaFlags) { + if (surfaceCapabilities.supportedCompositeAlpha & compositeAlphaFlag) { + compositeAlpha = compositeAlphaFlag; + break; + }; + } + VkImageUsageFlags imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + // Enable transfer source on swap chain images if supported + if (surfaceCapabilities.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) { + imageUsage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + } - // Enable transfer destination on swap chain images if supported - if (surfaceCapabilities.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT) { - imageUsage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT; + // Enable transfer destination on swap chain images if supported + if (surfaceCapabilities.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT) { + imageUsage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT; + } + + _gpuSwapchain->createInfo.surface = _gpuSwapchain->vkSurface; + _gpuSwapchain->createInfo.minImageCount = desiredNumberOfSwapchainImages; + _gpuSwapchain->createInfo.imageFormat = colorFormat; + _gpuSwapchain->createInfo.imageColorSpace = colorSpace; + _gpuSwapchain->createInfo.imageExtent = imageExtent; + _gpuSwapchain->createInfo.imageUsage = imageUsage; + _gpuSwapchain->createInfo.imageArrayLayers = 1; + _gpuSwapchain->createInfo.preTransform = VkSurfaceTransformFlagBitsKHR::VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; + _gpuSwapchain->createInfo.compositeAlpha = compositeAlpha; + _gpuSwapchain->createInfo.presentMode = swapchainPresentMode; + _gpuSwapchain->createInfo.clipped = VK_TRUE; // Setting clipped to VK_TRUE allows the implementation to discard rendering outside of the surface area } - - _gpuSwapchain->createInfo.surface = _gpuSwapchain->vkSurface; - _gpuSwapchain->createInfo.minImageCount = desiredNumberOfSwapchainImages; - _gpuSwapchain->createInfo.imageFormat = colorFormat; - _gpuSwapchain->createInfo.imageColorSpace = colorSpace; - _gpuSwapchain->createInfo.imageExtent = imageExtent; - _gpuSwapchain->createInfo.imageUsage = imageUsage; - _gpuSwapchain->createInfo.imageArrayLayers = 1; - _gpuSwapchain->createInfo.preTransform = VkSurfaceTransformFlagBitsKHR::VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; - _gpuSwapchain->createInfo.compositeAlpha = compositeAlpha; - _gpuSwapchain->createInfo.presentMode = swapchainPresentMode; - _gpuSwapchain->createInfo.clipped = VK_TRUE; // Setting clipped to VK_TRUE allows the implementation to discard rendering outside of the surface area - ///////////////////// Texture Creation ///////////////////// - + if (_xr) { + colorFmt = _xr->getXRSwapchainFormat(); + } _colorTexture = ccnew CCVKTexture; _depthStencilTexture = ccnew CCVKTexture; @@ -266,59 +275,87 @@ void CCVKSwapchain::doResize(uint32_t width, uint32_t height, SurfaceTransform / } bool CCVKSwapchain::checkSwapchainStatus(uint32_t width, uint32_t height) { - if (_gpuSwapchain->vkSurface == VK_NULL_HANDLE) { // vkSurface will be set to VK_NULL_HANDLE after call doDestroySurface - return false; - } - auto *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); - const auto *gpuContext = CCVKDevice::getInstance()->gpuContext(); + uint32_t newWidth = width; + uint32_t newHeight = height; + uint32_t imageCount = 0; + if (_xr) { + newWidth = static_cast(_colorTexture.get())->_info.width; + newHeight = static_cast(_colorTexture.get())->_info.height; + // xr double eyes need six images + std::vector vkImagesLeft; + std::vector vkImagesRight; + _xr->getXRSwapchainVkImages(vkImagesLeft, static_cast(cc::xr::XREye::LEFT)); + _xr->getXRSwapchainVkImages(vkImagesRight, static_cast(cc::xr::XREye::RIGHT)); + _gpuSwapchain->swapchainImages.resize(vkImagesLeft.size() + vkImagesRight.size()); + _gpuSwapchain->swapchainImages.clear(); + // 0-1-2 + _gpuSwapchain->swapchainImages.insert(_gpuSwapchain->swapchainImages.end(), vkImagesLeft.begin(), vkImagesLeft.end()); + // 3-4-5 + _gpuSwapchain->swapchainImages.insert(_gpuSwapchain->swapchainImages.end(), vkImagesRight.begin(), vkImagesRight.end()); - VkSurfaceCapabilitiesKHR surfaceCapabilities; - VK_CHECK(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(gpuContext->physicalDevice, _gpuSwapchain->vkSurface, &surfaceCapabilities)); - - // surfaceCapabilities.currentExtent seems to remain the same - // during any size/orientation change events on android devices - // so we prefer the system input (oriented size) here - uint32_t newWidth = width ? width : surfaceCapabilities.currentExtent.width; - uint32_t newHeight = height ? height : surfaceCapabilities.currentExtent.height; - - if (_gpuSwapchain->createInfo.imageExtent.width == newWidth && - _gpuSwapchain->createInfo.imageExtent.height == newHeight && _gpuSwapchain->lastPresentResult == VK_SUCCESS) { - return true; - } - - if (newWidth == static_cast(-1)) { - _gpuSwapchain->createInfo.imageExtent.width = _colorTexture->getWidth(); - _gpuSwapchain->createInfo.imageExtent.height = _colorTexture->getHeight(); - } else { + imageCount = _gpuSwapchain->swapchainImages.size(); _gpuSwapchain->createInfo.imageExtent.width = newWidth; _gpuSwapchain->createInfo.imageExtent.height = newHeight; + auto *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); + gpuDevice->curBackBufferIndex = 0; + _gpuSwapchain->curImageIndex = 0; + CCVKDevice::getInstance()->updateBackBufferCount(imageCount); + CCVKDevice::getInstance()->waitAllFences(); + CC_LOG_INFO("Resizing surface: %dx%d, surface rotation: %d degrees", newWidth, newHeight, static_cast(_transform) * 90); + } else { + if (_gpuSwapchain->vkSurface == VK_NULL_HANDLE) { // vkSurface will be set to VK_NULL_HANDLE after call doDestroySurface + return false; + } + auto *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); + const auto *gpuContext = CCVKDevice::getInstance()->gpuContext(); + + VkSurfaceCapabilitiesKHR surfaceCapabilities; + VK_CHECK(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(gpuContext->physicalDevice, _gpuSwapchain->vkSurface, &surfaceCapabilities)); + + // surfaceCapabilities.currentExtent seems to remain the same + // during any size/orientation change events on android devices + // so we prefer the system input (oriented size) here + newWidth = width ? width : surfaceCapabilities.currentExtent.width; + newHeight = height ? height : surfaceCapabilities.currentExtent.height; + + if (_gpuSwapchain->createInfo.imageExtent.width == newWidth && + _gpuSwapchain->createInfo.imageExtent.height == newHeight && _gpuSwapchain->lastPresentResult == VK_SUCCESS) { + return true; + } + + if (newWidth == static_cast(-1)) { + _gpuSwapchain->createInfo.imageExtent.width = _colorTexture->getWidth(); + _gpuSwapchain->createInfo.imageExtent.height = _colorTexture->getHeight(); + } else { + _gpuSwapchain->createInfo.imageExtent.width = newWidth; + _gpuSwapchain->createInfo.imageExtent.height = newHeight; + } + + if (newWidth == 0 || newHeight == 0) { + _gpuSwapchain->lastPresentResult = VK_NOT_READY; + return false; + } + + _gpuSwapchain->createInfo.surface = _gpuSwapchain->vkSurface; + _gpuSwapchain->createInfo.oldSwapchain = _gpuSwapchain->vkSwapchain; + + CC_LOG_INFO("Resizing surface: %dx%d", newWidth, newHeight); + + CCVKDevice::getInstance()->waitAllFences(); + + VkSwapchainKHR vkSwapchain = VK_NULL_HANDLE; + VK_CHECK(vkCreateSwapchainKHR(gpuDevice->vkDevice, &_gpuSwapchain->createInfo, nullptr, &vkSwapchain)); + + destroySwapchain(gpuDevice); + + _gpuSwapchain->vkSwapchain = vkSwapchain; + + VK_CHECK(vkGetSwapchainImagesKHR(gpuDevice->vkDevice, _gpuSwapchain->vkSwapchain, &imageCount, nullptr)); + CCVKDevice::getInstance()->updateBackBufferCount(imageCount); + _gpuSwapchain->swapchainImages.resize(imageCount); + VK_CHECK(vkGetSwapchainImagesKHR(gpuDevice->vkDevice, _gpuSwapchain->vkSwapchain, &imageCount, _gpuSwapchain->swapchainImages.data())); } - if (newWidth == 0 || newHeight == 0) { - _gpuSwapchain->lastPresentResult = VK_NOT_READY; - return false; - } - - _gpuSwapchain->createInfo.surface = _gpuSwapchain->vkSurface; - _gpuSwapchain->createInfo.oldSwapchain = _gpuSwapchain->vkSwapchain; - - CC_LOG_INFO("Resizing surface: %dx%d", newWidth, newHeight); - - CCVKDevice::getInstance()->waitAllFences(); - - VkSwapchainKHR vkSwapchain = VK_NULL_HANDLE; - VK_CHECK(vkCreateSwapchainKHR(gpuDevice->vkDevice, &_gpuSwapchain->createInfo, nullptr, &vkSwapchain)); - - destroySwapchain(gpuDevice); - - _gpuSwapchain->vkSwapchain = vkSwapchain; - - uint32_t imageCount; - VK_CHECK(vkGetSwapchainImagesKHR(gpuDevice->vkDevice, _gpuSwapchain->vkSwapchain, &imageCount, nullptr)); - CCVKDevice::getInstance()->updateBackBufferCount(imageCount); - _gpuSwapchain->swapchainImages.resize(imageCount); - VK_CHECK(vkGetSwapchainImagesKHR(gpuDevice->vkDevice, _gpuSwapchain->vkSwapchain, &imageCount, _gpuSwapchain->swapchainImages.data())); - // should skip size check, since the old swapchain has already been destroyed static_cast(_colorTexture.get())->_info.width = 1; static_cast(_depthStencilTexture.get())->_info.width = 1; @@ -424,6 +461,11 @@ void CCVKSwapchain::doCreateSurface(void *windowHandle) { // NOLINT } void CCVKSwapchain::createVkSurface() { + if (_xr) { + // xr do not need VkSurface + _gpuSwapchain->vkSurface = VK_NULL_HANDLE; + return; + } const auto *gpuContext = CCVKDevice::getInstance()->gpuContext(); #if defined(VK_USE_PLATFORM_ANDROID_KHR) diff --git a/native/cocos/renderer/gfx-vulkan/VKSwapchain.h b/native/cocos/renderer/gfx-vulkan/VKSwapchain.h index 6655e3b961..b49bffa6a7 100644 --- a/native/cocos/renderer/gfx-vulkan/VKSwapchain.h +++ b/native/cocos/renderer/gfx-vulkan/VKSwapchain.h @@ -27,6 +27,7 @@ #include "VKStd.h" #include "gfx-base/GFXSwapchain.h" +#include "platform/java/modules/XRInterface.h" namespace cc { namespace gfx { @@ -59,6 +60,7 @@ protected: void destroySwapchain(CCVKGPUDevice *gpuDevice); CCVKGPUSwapchain *_gpuSwapchain = nullptr; + IXRInterface *_xr = nullptr; }; } // namespace gfx diff --git a/native/cocos/renderer/pipeline/PipelineUBO.cpp b/native/cocos/renderer/pipeline/PipelineUBO.cpp index 2903b7febf..b9043debf4 100644 --- a/native/cocos/renderer/pipeline/PipelineUBO.cpp +++ b/native/cocos/renderer/pipeline/PipelineUBO.cpp @@ -37,6 +37,7 @@ #include "scene/Fog.h" #include "scene/RenderScene.h" #include "scene/Shadow.h" +#include "scene/Skybox.h" #include "scene/SpotLight.h" namespace cc { @@ -166,6 +167,9 @@ void PipelineUBO::updateCameraUBOView(const RenderPipeline *pipeline, float *out output[UBOCamera::CAMERA_POS_OFFSET + 3] = getCombineSignY(); output[UBOCamera::SURFACE_TRANSFORM_OFFSET + 0] = static_cast(camera->getSurfaceTransform()); + const float angle = sceneData->getSkybox()->getRotationAngle(); + output[UBOCamera::SURFACE_TRANSFORM_OFFSET + 2] = static_cast(cos(mathutils::toRadian(angle))); + output[UBOCamera::SURFACE_TRANSFORM_OFFSET + 3] = static_cast(sin(mathutils::toRadian(angle))); if (fog != nullptr) { const auto &colorTempRGB = fog->getColorArray(); diff --git a/native/cocos/renderer/pipeline/RenderPipeline.h b/native/cocos/renderer/pipeline/RenderPipeline.h index 8eca1b6e86..4ba53ca326 100644 --- a/native/cocos/renderer/pipeline/RenderPipeline.h +++ b/native/cocos/renderer/pipeline/RenderPipeline.h @@ -136,6 +136,9 @@ public: #endif } + inline void resetRenderQueue(bool reset) { _resetRenderQueue = reset; } + inline bool isRenderQueueReset() const { return _resetRenderQueue; } + protected: static RenderPipeline *instance; @@ -188,6 +191,8 @@ protected: bool _clusterEnabled{false}; bool _bloomEnabled{false}; bool _occlusionQueryEnabled{false}; + + bool _resetRenderQueue{true}; }; } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineImpl.cpp b/native/cocos/renderer/pipeline/custom/NativePipelineImpl.cpp index 68fbbb99f8..e650e1a2cc 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineImpl.cpp +++ b/native/cocos/renderer/pipeline/custom/NativePipelineImpl.cpp @@ -570,6 +570,14 @@ bool NativePipeline::isOcclusionQueryEnabled() const { return false; } +void NativePipeline::resetRenderQueue(bool reset) { + // noop +} + +bool NativePipeline::isRenderQueueReset() const { + return true; +} + } // namespace render } // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h index b94c84cd64..3ca477a7a9 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h +++ b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h @@ -303,6 +303,9 @@ public: bool isOcclusionQueryEnabled() const override; + void resetRenderQueue(bool reset) override; + bool isRenderQueueReset() const override; + gfx::Device* device{nullptr}; gfx::Swapchain* swapchain{nullptr}; MacroRecord macros; diff --git a/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h b/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h index 42539eca7d..612ffc470f 100644 --- a/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h +++ b/native/cocos/renderer/pipeline/custom/RenderInterfaceTypes.h @@ -108,6 +108,9 @@ public: virtual void setValue(const ccstd::string& name, bool value) = 0; virtual bool isOcclusionQueryEnabled() const = 0; + + virtual void resetRenderQueue(bool reset) = 0; + virtual bool isRenderQueueReset() const = 0; }; class Setter { diff --git a/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp b/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp index 00b4a89403..ac1b3732b7 100644 --- a/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp +++ b/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp @@ -33,6 +33,7 @@ #include "ForwardFlow.h" #include "gfx-base/GFXDevice.h" #include "profiler/Profiler.h" +#include "scene/Camera.h" #include "scene/RenderScene.h" namespace cc { @@ -111,8 +112,11 @@ void ForwardPipeline::render(const ccstd::vector &cameras) { decideProfilerCamera(cameras); for (auto *camera : cameras) { - validPunctualLightsCulling(this, camera); - sceneCulling(this, camera); + bool isCullingEnable = camera->isCullingEnabled(); + if (isCullingEnable) { + validPunctualLightsCulling(this, camera); + sceneCulling(this, camera); + } for (auto const &flow : _flows) { flow->render(camera); } diff --git a/native/cocos/renderer/pipeline/forward/ForwardStage.cpp b/native/cocos/renderer/pipeline/forward/ForwardStage.cpp index 538757807f..091f61eb00 100644 --- a/native/cocos/renderer/pipeline/forward/ForwardStage.cpp +++ b/native/cocos/renderer/pipeline/forward/ForwardStage.cpp @@ -96,6 +96,8 @@ void ForwardStage::destroy() { } void ForwardStage::dispenseRenderObject2Queues() { + if (!_pipeline->isRenderQueueReset()) return; + _instancedQueue->clear(); _batchedQueue->clear(); diff --git a/native/cocos/scene/Camera.cpp b/native/cocos/scene/Camera.cpp index 26ac4471b2..58ca5a6dc5 100644 --- a/native/cocos/scene/Camera.cpp +++ b/native/cocos/scene/Camera.cpp @@ -33,6 +33,7 @@ #if CC_USE_GEOMETRY_RENDERER #include "renderer/pipeline/GeometryRenderer.h" #endif +#include "platform/BasePlatform.h" namespace cc { namespace scene { @@ -81,11 +82,14 @@ Camera::Camera(gfx::Device *device) assignMat4(correctionMatrices[static_cast(gfx::SurfaceTransform::ROTATE_180)], -1, 0, 0, 0, 0, -ySign); assignMat4(correctionMatrices[static_cast(gfx::SurfaceTransform::ROTATE_270)], 0, -1, 0, 0, ySign, 0); } + _xr = CC_GET_XR_INTERFACE(); } Camera::~Camera() = default; bool Camera::initialize(const ICameraInfo &info) { + _trackingType = info.trackingType; + _cameraType = info.cameraType; _node = info.node; _width = 1.F; _height = 1.F; @@ -194,6 +198,17 @@ void Camera::update(bool forceUpdate /*false*/) { _isProjDirty = false; } + if (_xr) { + xr::XREye wndXREye = _xr->getXREyeByRenderWindow(_window); + if (wndXREye != xr::XREye::NONE && _proj == CameraProjection::PERSPECTIVE && _xr->getXRConfig(xr::XRConfigKey::SESSION_RUNNING).getBool()) { + // xr flow + const auto &projFloat = _xr->getXRViewProjectionData(static_cast(wndXREye), _nearClip, _farClip); + std::memcpy(_matProj.m, projFloat.data(), sizeof(float) * 16); + _matProjInv = _matProj.getInversed(); + viewProjDirty = true; + } + } + // view-projection if (viewProjDirty) { Mat4::multiply(_matProj, _matView, &_matViewProj); @@ -201,6 +216,7 @@ void Camera::update(bool forceUpdate /*false*/) { _frustum->update(_matViewProj, _matViewProjInv); } } + void Camera::changeTargetWindow(RenderWindow *window) { if (_window) { _window->detachCamera(this); diff --git a/native/cocos/scene/Camera.h b/native/cocos/scene/Camera.h index d0addbc750..42ec505f16 100644 --- a/native/cocos/scene/Camera.h +++ b/native/cocos/scene/Camera.h @@ -38,6 +38,7 @@ #include "math/Mat4.h" #include "math/Vec3.h" #include "math/Vec4.h" +#include "platform/java/modules/XRInterface.h" #include "renderer/gfx-base/GFXDef-common.h" #include "renderer/pipeline/Define.h" @@ -115,6 +116,20 @@ enum class CameraShutter { D4000, }; +enum class CameraType { + DEFAULT = -1, + LEFT_EYE = 0, + RIGHT_EYE = 1, + MAIN = 2, +}; + +enum class TrackingType { + NO_TRACKING = 0, + POSITION_AND_ROTATION = 1, + POSITION = 2, + ROTATION = 3, +}; + struct ICameraInfo { ccstd::string name; Node *node{nullptr}; @@ -123,6 +138,8 @@ struct ICameraInfo { RenderWindow *window{nullptr}; uint32_t priority{0}; ccstd::optional pipeline; + CameraType cameraType{CameraType::DEFAULT}; + TrackingType trackingType{TrackingType::NO_TRACKING}; }; class Camera : public RefCounted { @@ -324,6 +341,15 @@ public: void detachCamera(); + inline CameraType getCameraType() const { return _cameraType; } + inline void setCameraType(CameraType type) { _cameraType = type; } + + inline TrackingType getTrackingType() const { return _trackingType; } + inline void setTrackingType(TrackingType type) { _trackingType = type; } + + inline bool isCullingEnabled() const { return _isCullingEnabled; } + inline void setCullingEnable(bool val) { _isCullingEnabled = val; } + protected: void setExposure(float ev100); @@ -338,6 +364,7 @@ private: IntrusivePtr _node; ccstd::string _name; bool _enabled{false}; + bool _isCullingEnabled{true}; CameraProjection _proj{CameraProjection::UNKNOWN}; float _aspect{0.F}; float _orthoHeight{10.0F}; @@ -371,6 +398,8 @@ private: uint32_t _height{0}; gfx::ClearFlagBit _clearFlag{gfx::ClearFlagBit::NONE}; float _clearDepth{1.0F}; + CameraType _cameraType{CameraType::DEFAULT}; + TrackingType _trackingType{TrackingType::NO_TRACKING}; #if CC_USE_GEOMETRY_RENDERER IntrusivePtr _geometryRenderer; @@ -383,6 +412,7 @@ private: uint32_t _visibility = pipeline::CAMERA_DEFAULT_MASK; float _exposure{0.F}; uint32_t _clearStencil{0}; + IXRInterface *_xr{nullptr}; CC_DISALLOW_COPY_MOVE_ASSIGN(Camera); }; diff --git a/native/cocos/scene/Model.cpp b/native/cocos/scene/Model.cpp index c7dec628eb..c8fdc66731 100644 --- a/native/cocos/scene/Model.cpp +++ b/native/cocos/scene/Model.cpp @@ -233,12 +233,12 @@ void Model::updateUBOs(uint32_t stamp) { _localDataUpdated = false; getTransform()->updateWorldTransform(); const auto &worldMatrix = getTransform()->getWorldMatrix(); - Mat4 mat4; int idx = _instMatWorldIdx; if (idx >= 0) { ccstd::vector &attrs = getInstancedAttributeBlock().views; uploadMat4AsVec4x3(worldMatrix, ccstd::get(attrs[idx]), ccstd::get(attrs[idx + 1]), ccstd::get(attrs[idx + 2])); } else if (_localBuffer) { + Mat4 mat4; mat4ToFloat32Array(worldMatrix, _localData, pipeline::UBOLocal::MAT_WORLD_OFFSET); Mat4::inverseTranspose(worldMatrix, &mat4); diff --git a/native/cocos/scene/Skybox.cpp b/native/cocos/scene/Skybox.cpp index d7efdb27ce..616bd8473b 100644 --- a/native/cocos/scene/Skybox.cpp +++ b/native/cocos/scene/Skybox.cpp @@ -191,6 +191,7 @@ void SkyboxInfo::activate(Skybox *resource) { _resource->setDiffuseMaps(_diffuseMapHDR, _diffuseMapLDR); _resource->setReflectionMaps(_reflectionHDR, _reflectionLDR); _resource->setSkyboxMaterial(_editableMaterial); + _resource->setRotationAngle(_rotationAngle); _resource->activate(); // update global DS first } } @@ -285,6 +286,10 @@ void Skybox::setSkyboxMaterial(Material *skyboxMat) { _editableMaterial = skyboxMat; } +void Skybox::setRotationAngle(float angle) { + _rotationAngle = angle; +} + void Skybox::activate() { auto *pipeline = Root::getInstance()->getPipeline(); _globalDSManager = pipeline->getGlobalDSManager(); diff --git a/native/cocos/scene/Skybox.h b/native/cocos/scene/Skybox.h index d05efb04de..704e931068 100644 --- a/native/cocos/scene/Skybox.h +++ b/native/cocos/scene/Skybox.h @@ -190,6 +190,7 @@ public: bool _useHDR{true}; EnvironmentLightingType _envLightingType{EnvironmentLightingType::HEMISPHERE_DIFFUSE}; IntrusivePtr _editableMaterial; + float _rotationAngle{0.F}; Skybox *_resource{nullptr}; }; @@ -277,6 +278,13 @@ public: TextureCube *getDiffuseMap() const; void setDiffuseMap(TextureCube *val); void setSkyboxMaterial(Material *skyboxMat); + /** + * @en Set skybox rotate angle + * @zh 设置天空盒旋转角度 + * @param angle @en rotation angle @zh 旋转角度 + */ + void setRotationAngle(float angle); + float getRotationAngle() const { return _rotationAngle; }; TextureCube *getReflectionMap() const; @@ -302,7 +310,7 @@ private: bool _useDiffuseMap{false}; bool _activated{false}; IntrusivePtr _editableMaterial; - + float _rotationAngle{0.F}; CC_DISALLOW_COPY_MOVE_ASSIGN(Skybox); }; diff --git a/native/tools/bindings-generator/targets/spidermonkey/conversions.yaml b/native/tools/bindings-generator/targets/spidermonkey/conversions.yaml index babe3fc9f5..db99ee3662 100644 --- a/native/tools/bindings-generator/targets/spidermonkey/conversions.yaml +++ b/native/tools/bindings-generator/targets/spidermonkey/conversions.yaml @@ -25,6 +25,7 @@ conversions: "spine::": "sp." "dragonBones::": "dragonbones." "cc::gfx::": "gfx." + "cc::xr::": "xr." "cc::pipeline::": "nr." "cc::render::": "render." "cc::scene::": "jsb." diff --git a/native/tools/tojs/genbindings.py b/native/tools/tojs/genbindings.py index ee61d00385..9e9ad7223e 100755 --- a/native/tools/tojs/genbindings.py +++ b/native/tools/tojs/genbindings.py @@ -13,6 +13,7 @@ else: import ConfigParser as configparser defaultSections = [ + 'xr', 'cocos', 'video', 'webview', diff --git a/native/tools/tojs/render.ini b/native/tools/tojs/render.ini index ec9be54ee6..f772cfe3d0 100644 --- a/native/tools/tojs/render.ini +++ b/native/tools/tojs/render.ini @@ -48,7 +48,7 @@ classes_need_extend = # will apply to all class names. This is a convenience wildcard to be able to skip similar named # functions from all classes. -skip = PipelineRuntime::[getMacros setValue isOcclusionQueryEnabled], +skip = PipelineRuntime::[getMacros setValue isOcclusionQueryEnabled resetRenderQueue isRenderQueueReset], SceneVisitor::[bindDescriptorSet updateBuffer] skip_public_fields = diff --git a/native/tools/tojs/scene.ini b/native/tools/tojs/scene.ini index d4a79990fd..f35d84f622 100644 --- a/native/tools/tojs/scene.ini +++ b/native/tools/tojs/scene.ini @@ -101,7 +101,7 @@ getter_setter = Root::[device:_device mainWindow curWindow tempWindow windows sc DirectionalLight::[direction illuminance illuminanceHDR illuminanceLDR shadowEnabled/isShadowEnabled shadowPcf shadowBias shadowNormalBias shadowSaturation shadowDistance shadowInvisibleOcclusionRange csmLevel/getCSMLevel/setCSMLevel csmNeedUpdate/isCSMNeedUpdate/setCSMNeedUpdate csmLayerLambda/getCSMLayerLambda/setCSMLayerLambda csmOptimizationMode/getCSMOptimizationMode/setCSMOptimizationMode shadowFixedArea/isShadowFixedArea shadowNear shadowFar shadowOrthoSize], SpotLight::[position size range luminance luminanceHDR luminanceLDR direction spotAngle angle aabb/getAABB frustum shadowEnabled/isShadowEnabled shadowPcf shadowBias shadowNormalBias], SphereLight::[position size range luminance luminanceHDR luminanceLDR aabb/getAABB], - Camera::[iso isoValue ec exposure shutter shutterValue apertureValue width height scene name window forward aperture position projectionType/getProjectionType/setProjectionType fovAxis fov nearClip farClip viewport orthoHeight clearColor clearDepth clearFlag clearStencil enabled/isEnabled/setEnabled exposure frustum isWindowSize/isWindowSize/setWindowSize priority screenScale visibility node surfaceTransform geometryRenderer], + Camera::[iso isoValue ec exposure shutter shutterValue apertureValue width height scene name window forward aperture position projectionType/getProjectionType/setProjectionType fovAxis fov nearClip farClip viewport orthoHeight clearColor clearDepth clearFlag clearStencil enabled/isEnabled/setEnabled exposure frustum isWindowSize/isWindowSize/setWindowSize priority screenScale visibility node surfaceTransform geometryRenderer cameraType trackingType], RenderScene::[name cameras? mainLight? sphereLights? spotLights? models], Skybox::[model enabled/isEnabled/setEnabled useHDR/isUseHDR/setUseHDR useIBL/isUseIBL/setUseIBL useDiffuseMap/isUseDiffuseMap/setUseDiffuseMap isRGBE/isRGBE/setRGBE envmap diffuseMap], Fog::[enabled/isEnabled/setEnabled accurate/isAccurate/setAccurate fogColor type fogDensity fogStart fogEnd fogAtten fogTop fogRange fogRange colorArray], @@ -122,7 +122,7 @@ field = Ambient::[SUN_ILLUM SKY_ILLUM], Shadows::[MAX_FAR COEFFICIENT_OF_EXPANSION], ShadowsInfo::[_enabled _type _normal _distance _shadowColor _maxReceived _size], FogInfo::[_type _fogColor _isEnabled _fogDensity _fogStart _fogEnd _fogAtten _fogTop _fogRange _accurate], - SkyboxInfo::[_envLightingType _envmapHDR _envmapLDR _diffuseMapHDR _diffuseMapLDR _enabled _useHDR _editableMaterial _reflectionHDR _reflectionLDR], + SkyboxInfo::[_envLightingType _envmapHDR _envmapLDR _diffuseMapHDR _diffuseMapLDR _enabled _useHDR _editableMaterial _reflectionHDR _reflectionLDR _rotationAngle], OctreeInfo::[_enabled _minPos _maxPos _depth], Node::[_siblingIndex _parent _active$ _id] diff --git a/native/tools/tojs/xr.ini b/native/tools/tojs/xr.ini new file mode 100644 index 0000000000..ce3b13b892 --- /dev/null +++ b/native/tools/tojs/xr.ini @@ -0,0 +1,66 @@ +[xr] +# the prefix to be added to the generated functions. You might or might not use this in your own +# templates +prefix = xr + +# create a target namespace (in javascript, this would create some code like the equiv. to `ns = ns || {}`) +# all classes will be embedded in that namespace +target_namespace = xr + +macro_judgement = #if (CC_USE_XR > 0) + +android_headers = + +clang_headers = + +cxxgenerator_headers = + +cocos_headers = -I%(cocosdir)s/cocos/platform/interfaces/modules + +android_flags = -target armv7-none-linux-androideabi -D_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS -DANDROID -D__ANDROID_API__=14 -gcc-toolchain %(gcc_toolchain_dir)s --sysroot=%(androidndkdir)s/platforms/android-14/arch-arm -idirafter %(androidndkdir)s/sources/android/support/include -idirafter %(androidndkdir)s/sysroot/usr/include -idirafter %(androidndkdir)s/sysroot/usr/include/arm-linux-androideabi -idirafter %(clangllvmdir)s/lib64/clang/5.0/include -I%(androidndkdir)s/sources/cxx-stl/llvm-libc++/include + +clang_flags = -nostdinc -x c++ -std=c++17 -fsigned-char -mfloat-abi=soft -U__SSE__ + +cocos_flags = -DANDROID -DCC_PLATFORM=3 -DCC_PLATFORM_IOS=1 -DCC_PLATFORM_MACOS=4 -DCC_PLATFORM_WINDOWS=2 -DCC_PLATFORM_ANDROID=3 + +# extra arguments for clang +extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s + +# what headers to parse +headers = %(cocosdir)s/external/sources/xr/Xr.h + +replace_headers = + +# what classes to produce code for. You can use regular expressions here. When testing the regular +# expression, it will be enclosed in "^$", like this: "^Menu*$". +classes = XrEntry + +# what should we skip? in the format ClassName::[function function] +# ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also +# regular expressions, they will not be surrounded by "^$". If you want to skip a whole class, just +# add a single "*" as functions. See bellow for several examples. A special class name is "*", which +# will apply to all class names. This is a convenience wildcard to be able to skip similar named +# functions from all classes. + +skip = XrEntry::[setGamepadCallback setHandleCallback setHMDCallback setXRConfig getXRConfig] + +field = + +rename_functions = + +rename_classes = + +# for all class names, should we remove something when registering in the target VM? +remove_prefix = + +# classes for which there will be no "parent" lookup +classes_have_no_parents = + +# base classes which will be skipped when their sub-classes found them. +base_classes_to_skip = + +# classes that create no constructor +# Set is special and we will use a hand-written constructor +abstract_classes = XrEntry + +classes_owned_by_cpp = diff --git a/pal/input/input-source.ts b/pal/input/input-source.ts new file mode 100644 index 0000000000..e93f37d418 --- /dev/null +++ b/pal/input/input-source.ts @@ -0,0 +1,314 @@ +/* + Copyright (c) 2022 Chukong Technologies Inc. + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { Vec2, Vec3, Quat } from '../../cocos/core/math'; + +/** + * @en The abstract class for input source, which is used to control the input signal of a mono input source + * @zh InputSource 抽象类,该类用于控制单一输入源的输入信号 + */ +export abstract class InputSource { + /** + * @en Get the signal value of the input source + * @zh 获取输入源的信号值 + */ + abstract getValue (): T; +} + +/** + * @en The class for input source of 1D Axis, which is used to control the input signal of a mono input source + * @zh 1D 轴的 InputSource 类,该类用于控制单一输入源的输入信号 + */ +export class InputSourceAxis1D extends InputSource { + /** + * @en Get the signal value of the input source, ranged from -1 to 1 + * @zh 获取输入源的信号值,取值范围从 -1 到 1 + */ + getValue (): number { + throw new Error('Method not implemented.'); + } +} + +/** + * @en The class for input source of 2D Axis, which is used to control the input signal of a mono input source + * @zh 2D 轴的 InputSource 类,该类用于控制单一输入源的输入信号 + */ +export class InputSourceAxis2D extends InputSource { + /** + * @en Get the signal value of the input source, which returns a Vec2 object. + * @zh 获取输入源的信号值,该方法返回一个 Vec2 对象 + */ + getValue (): Vec2 { + throw new Error('Method not implemented.'); + } +} + +/** + * @en The class for input source of 3D Axis, which is used to control the input signal of a mono input source + * @zh 3D 轴的 InputSource 类,该类用于控制单一输入源的输入信号 + */ +export class InputSourceAxis3D extends InputSource { + /** + * @en Get the signal value of the input source, which returns a Vec3 object. + * @zh 获取输入源的信号值,该方法返回一个 Vec3 对象 + */ + getValue (): Vec3 { + throw new Error('Method not implemented.'); + } +} + +/** + * @en The class for input source of Quaternion, which is used to control the input signal of a mono input source + * @zh 四元数的 InputSource 类,该类用于控制单一输入源的输入信号 + */ + export class InputSourceQuat extends InputSource { + /** + * @en Get the signal value of the input source, which returns a Quat object. + * @zh 获取输入源的信号值,该方法返回一个 Quat 对象 + */ + getValue (): Quat { + throw new Error('Method not implemented.'); + } +} + +/** + * @en The class for input source of 1D Axis, which is used to control the input signal of a composite of multi input source + * @zh 1D 轴的 InputSource 类,该类用于控制多个输入源组合的输入信号 + */ +export class CompositeInputSourceAxis1D extends InputSourceAxis1D { + /** + * @en The input source object of positive 1D axis + * @zh 1D 轴的正向的输入源对象 + */ + public positive: InputSourceButton; + /** + * @en The input source object of negative 1D axis + * @zh 1D 轴的负向的输入源对象 + */ + public negative: InputSourceButton; + constructor (options: {positive: InputSourceButton, negative: InputSourceButton}) { + super(); + this.positive = options.positive; + this.negative = options.negative; + } + /** + * @en Get the signal value of the input source, ranged from -1 to 1. + * @zh 获取输入源的信号值,取值范围从 -1 到 1 + */ + public getValue (): number { + const positiveValue = this.positive.getValue(); + const negativeValue = this.negative.getValue(); + if (Math.abs(positiveValue) > Math.abs(negativeValue)) { + return positiveValue; + } + return -negativeValue; + } +} + +/** + * @en The class for input source of 2D Axis, which is used to control the input signal of a composite of multi input source + * @zh 2D 轴的 InputSource 类,该类用于控制多个输入源组合的输入信号 + */ +export class CompositeInputSourceAxis2D extends InputSourceAxis2D { + /** + * @en The input source object of up direction of 2D axis + * @zh 2D 轴的向上的输入源对象 + */ + public up: InputSourceButton; + /** + * @en The input source object of down direction of 2D axis + * @zh 2D 轴的向下的输入源对象 + */ + public down: InputSourceButton; + /** + * @en The input source object of left direction of 2D axis + * @zh 2D 轴的向左的输入源对象 + */ + public left: InputSourceButton; + /** + * @en The input source object of right direction of 2D axis + * @zh 2D 轴的向右的输入源对象 + */ + public right: InputSourceButton; + + /** + * @en The composite input source object on the x axis of 2D axis + * @zh 2D 轴在 x 轴上的组合输入源对象 + */ + public xAxis: CompositeInputSourceAxis1D; + /** + * @en The composite input source object on the y axis of 2D axis + * @zh 2D 轴在 y 轴上的组合输入源对象 + */ + public yAxis: CompositeInputSourceAxis1D; + constructor (options: {up: InputSourceButton, down: InputSourceButton, left: InputSourceButton, right: InputSourceButton}) { + super(); + this.up = options.up; + this.down = options.down; + this.left = options.left; + this.right = options.right; + this.xAxis = new CompositeInputSourceAxis1D({ positive: this.right, negative: this.left }); + this.yAxis = new CompositeInputSourceAxis1D({ positive: this.up, negative: this.down }); + } + /** + * @en Get the signal value of the input source, which returns a Vec2 object. + * @zh 获取输入源的信号值,该方法返回一个 Vec2 对象 + */ + getValue (): Vec2 { + return new Vec2(this.xAxis.getValue(), this.yAxis.getValue()); + } +} + +/** + * @en The class for input source of 3D Axis, which is used to control the input signal of a composite of multi input source + * @zh 3D 轴的 InputSource 类,该类用于控制多个输入源组合的输入信号 + */ +export class CompositeInputSourceAxis3D extends InputSourceAxis3D { + /** + * @en The input source object of up direction of 3D axis + * @zh 3D 轴的向上的输入源对象 + */ + public up: InputSourceButton; + /** + * @en The input source object of down direction of 3D axis + * @zh 3D 轴的向下的输入源对象 + */ + public down: InputSourceButton; + /** + * @en The input source object of left direction of 3D axis + * @zh 3D 轴的向左的输入源对象 + */ + public left: InputSourceButton; + /** + * @en The input source object of right direction of 3D axis + * @zh 3D 轴的向右的输入源对象 + */ + public right: InputSourceButton; + /** + * @en The input source object of forward direction of 3D axis + * @zh 3D 轴的向前的输入源对象 + */ + public forward: InputSourceButton; + /** + * @en The input source object of backward direction of 3D axis + * @zh 3D 轴的向后的输入源对象 + */ + public backward: InputSourceButton; + + /** + * @en The composite input source object on the x axis of 3D axis + * @zh 3D 轴在 x 轴上的组合输入源对象 + */ + public xAxis: CompositeInputSourceAxis1D; + /** + * @en The composite input source object on the y axis of 3D axis + * @zh 3D 轴在 y 轴上的组合输入源对象 + */ + public yAxis: CompositeInputSourceAxis1D; + /** + * @en The composite input source object on the z axis of 3D axis + * @zh 3D 轴在 z 轴上的组合输入源对象 + */ + public zAxis: CompositeInputSourceAxis1D; + constructor (options: {up: InputSourceButton, down: InputSourceButton, left: InputSourceButton, + right: InputSourceButton, forward: InputSourceButton, backward: InputSourceButton}) { + super(); + this.up = options.up; + this.down = options.down; + this.left = options.left; + this.right = options.right; + this.forward = options.forward; + this.backward = options.backward; + + this.xAxis = new CompositeInputSourceAxis1D({ positive: this.right, negative: this.left }); + this.yAxis = new CompositeInputSourceAxis1D({ positive: this.up, negative: this.down }); + this.zAxis = new CompositeInputSourceAxis1D({ positive: this.forward, negative: this.backward }); + } + + /** + * @en Get the signal value of the input source, which returns a Vec3 object. + * @zh 获取输入源的信号值,该方法返回一个 Vec3 对象 + */ + getValue (): Vec3 { + return new Vec3(this.xAxis.getValue(), this.yAxis.getValue(), this.zAxis.getValue()); + } +} + +/** + * @en The class for input source of mono button, whose input signal value is ranged from 0 to 1 + * @zh 单一按键输入源类, 输入信号源的取值范围是 0 到 1 + */ +export class InputSourceButton extends InputSourceAxis1D { + /** + * @en Get the signal value of the input source, ranged from 0 to 1 + * @zh 获取输入源的信号值,取值范围从 0 到 1 + */ + getValue (): number { + return super.getValue(); + } +} + +/** + * @en The class for input source of dpad, whose input signal value a Vec2 object + * @zh 手柄方向键输入源类, 输入信号源的取值是一个 Vec2 对象 + */ +export class InputSourceDpad extends CompositeInputSourceAxis2D { +} + +/** + * @en The class for input source of stick, whose input signal value a Vec2 object + * @zh 摇杆输入源类, 输入信号源的取值是一个 Vec2 对象 + */ +export class InputSourceStick extends CompositeInputSourceAxis2D { +} + +/** + * @en The class for input source of orientation, whose input signal value a Quat object + * @zh 方向输入源类, 输入信号源的取值是一个 Quat 对象 + */ + export class InputSourceOrientation extends InputSourceQuat { + /** + * @en Get the signal value of the input source, which returns a Quat object. + * @zh 获取输入源的信号值,该方法返回一个 Quat 对象 + */ + getValue (): Quat { + return super.getValue(); + } +} + +/** + * @en The class for input source of position, whose input signal value a Vec3 object + * @zh 坐标输入源类, 输入信号源的取值是一个 Vec3 对象 + */ + export class InputSourcePosition extends InputSourceAxis3D { + /** + * @en Get the signal value of the input source, which returns a Vec3 object. + * @zh 获取输入源的信号值,该方法返回一个 Vec3 对象 + */ + getValue (): Vec3 { + return super.getValue(); + } +} diff --git a/pal/input/minigame/gamepad-input.ts b/pal/input/minigame/gamepad-input.ts index 83dc7bd498..b01638f962 100644 --- a/pal/input/minigame/gamepad-input.ts +++ b/pal/input/minigame/gamepad-input.ts @@ -1,7 +1,144 @@ -export class GamepadInputSource { - support: boolean; +import { GamepadCallback } from 'pal/input'; +import { InputEventType } from '../../../cocos/input/types/event-enum'; +import { EventTarget } from '../../../cocos/core/event/event-target'; +import { InputSourceButton, InputSourceDpad, InputSourceStick } from '../input-source'; - constructor () { - this.support = false; +export class GamepadInputDevice { + public static all: GamepadInputDevice[] = []; + + public get buttonNorth () { return this._buttonNorth; } + public get buttonEast () { return this._buttonEast; } + public get buttonWest () { return this._buttonWest; } + public get buttonSouth () { return this._buttonSouth; } + public get buttonL1 () { return this._buttonL1; } + public get buttonL2 () { return this._buttonL2; } + public get buttonL3 () { return this._buttonL3; } + public get buttonR1 () { return this._buttonR1; } + public get buttonR2 () { return this._buttonR2; } + public get buttonR3 () { return this._buttonR3; } + // public get buttonTouchPad () { return this._buttonTouchPad; } + // public get buttonHome () { return this._buttonHome; } + public get buttonShare () { return this._buttonShare; } + public get buttonOptions () { return this._buttonOptions; } + public get dpad () { return this._dpad; } + public get leftStick () { return this._leftStick; } + public get rightStick () { return this._rightStick; } + public get buttonStart () { return this._buttonStart; } + + public get deviceId () { + return this._deviceId; + } + public get connected () { + return this._connected; + } + + private static _eventTarget: EventTarget = new EventTarget(); + + private _buttonNorth!: InputSourceButton; + private _buttonEast!: InputSourceButton; + private _buttonWest!: InputSourceButton; + private _buttonSouth!: InputSourceButton; + private _buttonL1!: InputSourceButton; + private _buttonL2!: InputSourceButton; + private _buttonL3!: InputSourceButton; + private _buttonR1!: InputSourceButton; + private _buttonR2!: InputSourceButton; + private _buttonR3!: InputSourceButton; + // private buttonTouchPad!: InputSourceButton; + // private buttonHome!: InputSourceButton; + private _buttonShare!: InputSourceButton; + private _buttonOptions!: InputSourceButton; + private _dpad!: InputSourceDpad; + private _leftStick!: InputSourceStick; + private _rightStick!: InputSourceStick; + private _buttonStart!: InputSourceButton; + + private _deviceId = -1; + private _connected = false; + + constructor (deviceId: number) { + this._deviceId = deviceId; + this._initInputSource(); + } + + /** + * @engineInternal + */ + public static _init () { + // not supported + } + + /** + * @engineInternal + */ + public static _on (eventType: InputEventType, cb: GamepadCallback, target?: any) { + GamepadInputDevice._eventTarget.on(eventType, cb, target); + } + + private _initInputSource () { + this._buttonNorth = new InputSourceButton(); + this._buttonNorth.getValue = () => 0; + this._buttonEast = new InputSourceButton(); + this._buttonEast.getValue = () => 0; + this._buttonWest = new InputSourceButton(); + this._buttonWest.getValue = () => 0; + this._buttonSouth = new InputSourceButton(); + this._buttonSouth.getValue = () => 0; + + this._buttonL1 = new InputSourceButton(); + this._buttonL1.getValue = () => 0; + this._buttonL2 = new InputSourceButton(); + this._buttonL2.getValue = () => 0; + this._buttonL3 = new InputSourceButton(); + this._buttonL3.getValue = () => 0; + this._buttonR1 = new InputSourceButton(); + this._buttonR1.getValue = () => 0; + this._buttonR2 = new InputSourceButton(); + this._buttonR2.getValue = () => 0; + this._buttonR3 = new InputSourceButton(); + this._buttonR3.getValue = () => 0; + + // this._buttonTouchPad = new InputSourceButton(); + // this._buttonTouchPad.getValue = () => 0; + // this._buttonHome = new InputSourceButton(); + // this._buttonHome.getValue = () => 0; + + this._buttonShare = new InputSourceButton(); + this._buttonShare.getValue = () => 0; + this._buttonOptions = new InputSourceButton(); + this._buttonOptions.getValue = () => 0; + + const dpadUp = new InputSourceButton(); + dpadUp.getValue = () => 0; + const dpadDown = new InputSourceButton(); + dpadDown.getValue = () => 0; + const dpadLeft = new InputSourceButton(); + dpadLeft.getValue = () => 0; + const dpadRight = new InputSourceButton(); + dpadRight.getValue = () => 0; + this._dpad = new InputSourceDpad({ up: dpadUp, down: dpadDown, left: dpadLeft, right: dpadRight }); + + const leftStickUp = new InputSourceButton(); + leftStickUp.getValue = () => 0; + const leftStickDown = new InputSourceButton(); + leftStickDown.getValue = () => 0; + const leftStickLeft = new InputSourceButton(); + leftStickLeft.getValue = () => 0; + const leftStickRight = new InputSourceButton(); + leftStickRight.getValue = () => 0; + this._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight }); + + const rightStickUp = new InputSourceButton(); + rightStickUp.getValue = () => 0; + const rightStickDown = new InputSourceButton(); + rightStickDown.getValue = () => 0; + const rightStickLeft = new InputSourceButton(); + rightStickLeft.getValue = () => 0; + const rightStickRight = new InputSourceButton(); + rightStickRight.getValue = () => 0; + this._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight }); + + this._buttonStart = new InputSourceButton(); + this._buttonStart.getValue = () => 0; } } diff --git a/pal/input/minigame/handle-input.ts b/pal/input/minigame/handle-input.ts new file mode 100644 index 0000000000..f861620d43 --- /dev/null +++ b/pal/input/minigame/handle-input.ts @@ -0,0 +1,134 @@ +import { HandleCallback } from 'pal/input'; +import { InputEventType } from '../../../cocos/input/types/event-enum'; +import { EventTarget } from '../../../cocos/core/event'; +import { InputSourceButton, InputSourceStick, InputSourcePosition, InputSourceOrientation } from '../input-source'; +import { Vec3, Quat } from '../../../cocos/core/math'; + +export class HandleInputDevice { + public get buttonNorth () { return this._buttonNorth; } + public get buttonEast () { return this._buttonEast; } + public get buttonWest () { return this._buttonWest; } + public get buttonSouth () { return this._buttonSouth; } + public get buttonTriggerLeft () { return this._buttonTriggerLeft; } + public get buttonTriggerRight () { return this._buttonTriggerRight; } + public get triggerLeft () { return this._triggerLeft; } + public get triggerRight () { return this._triggerRight; } + public get gripLeft () { return this._gripLeft; } + public get gripRight () { return this._gripRight; } + public get leftStick () { return this._leftStick; } + public get rightStick () { return this._rightStick; } + public get buttonLeftStick () { return this._buttonLeftStick; } + public get buttonRightStick () { return this._buttonRightStick; } + public get handLeftPosition () { return this._handLeftPosition; } + public get handLeftOrientation () { return this._handLeftOrientation; } + public get handRightPosition () { return this._handRightPosition; } + public get handRightOrientation () { return this._handRightOrientation; } + public get aimLeftPosition () { return this._aimLeftPosition; } + public get aimLeftOrientation () { return this._aimLeftOrientation; } + public get aimRightPosition () { return this._aimRightPosition; } + public get aimRightOrientation () { return this._aimRightOrientation; } + + private _eventTarget: EventTarget = new EventTarget(); + + private _buttonNorth!: InputSourceButton; + private _buttonEast!: InputSourceButton; + private _buttonWest!: InputSourceButton; + private _buttonSouth!: InputSourceButton; + private _buttonTriggerLeft!: InputSourceButton; + private _buttonTriggerRight!: InputSourceButton; + private _triggerLeft!: InputSourceButton; + private _triggerRight!: InputSourceButton; + private _gripLeft!: InputSourceButton; + private _gripRight!: InputSourceButton; + private _leftStick!: InputSourceStick; + private _rightStick!: InputSourceStick; + private _buttonLeftStick!: InputSourceButton; + private _buttonRightStick!: InputSourceButton; + private _handLeftPosition!: InputSourcePosition; + private _handLeftOrientation!: InputSourceOrientation; + private _handRightPosition!: InputSourcePosition; + private _handRightOrientation!: InputSourceOrientation; + private _aimLeftPosition!: InputSourcePosition; + private _aimLeftOrientation!: InputSourceOrientation; + private _aimRightPosition!: InputSourcePosition; + private _aimRightOrientation!: InputSourceOrientation; + + constructor () { + this._initInputSource(); + } + + /** + * @engineInternal + */ + public _on (eventType: InputEventType, callback: HandleCallback, target?: any) { + this._eventTarget.on(eventType, callback, target); + } + + private _initInputSource () { + this._buttonNorth = new InputSourceButton(); + this._buttonNorth.getValue = () => 0; + this._buttonEast = new InputSourceButton(); + this._buttonEast.getValue = () => 0; + this._buttonWest = new InputSourceButton(); + this._buttonWest.getValue = () => 0; + this._buttonSouth = new InputSourceButton(); + this._buttonSouth.getValue = () => 0; + + this._buttonTriggerLeft = new InputSourceButton(); + this._buttonTriggerLeft.getValue = () => 0; + this._buttonTriggerRight = new InputSourceButton(); + this._buttonTriggerRight.getValue = () => 0; + this._triggerLeft = new InputSourceButton(); + this._triggerLeft.getValue = () => 0; + this._triggerRight = new InputSourceButton(); + this._triggerRight.getValue = () => 0; + this._gripLeft = new InputSourceButton(); + this._gripLeft.getValue = () => 0; + this._gripRight = new InputSourceButton(); + this._gripRight.getValue = () => 0; + + this._buttonLeftStick = new InputSourceButton(); + this._buttonLeftStick.getValue = () => 0; + const leftStickUp = new InputSourceButton(); + leftStickUp.getValue = () => 0; + const leftStickDown = new InputSourceButton(); + leftStickDown.getValue = () => 0; + const leftStickLeft = new InputSourceButton(); + leftStickLeft.getValue = () => 0; + const leftStickRight = new InputSourceButton(); + leftStickRight.getValue = () => 0; + this._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight }); + + this._buttonRightStick = new InputSourceButton(); + this._buttonRightStick.getValue = () => 0; + const rightStickUp = new InputSourceButton(); + rightStickUp.getValue = () => 0; + const rightStickDown = new InputSourceButton(); + rightStickDown.getValue = () => 0; + const rightStickLeft = new InputSourceButton(); + rightStickLeft.getValue = () => 0; + const rightStickRight = new InputSourceButton(); + rightStickRight.getValue = () => 0; + this._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight }); + + this._handLeftPosition = new InputSourcePosition(); + this._handLeftPosition.getValue = () => Vec3.ZERO; + this._handLeftOrientation = new InputSourceOrientation(); + this._handLeftOrientation.getValue = () => Quat.IDENTITY; + + this._handRightPosition = new InputSourcePosition(); + this._handRightPosition.getValue = () => Vec3.ZERO; + this._handRightOrientation = new InputSourceOrientation(); + this._handRightOrientation.getValue = () => Quat.IDENTITY; + + this._aimLeftPosition = new InputSourcePosition(); + this._aimLeftPosition.getValue = () => Vec3.ZERO; + this._aimLeftOrientation = new InputSourceOrientation(); + this._aimLeftOrientation.getValue = () => Quat.IDENTITY; + + this._aimRightPosition = new InputSourcePosition(); + this._aimRightPosition.getValue = () => Vec3.ZERO; + this._aimRightOrientation = new InputSourceOrientation(); + this._aimRightOrientation.getValue = () => Quat.IDENTITY; + } +} diff --git a/pal/input/minigame/hmd-input.ts b/pal/input/minigame/hmd-input.ts new file mode 100644 index 0000000000..7cbd0a37c3 --- /dev/null +++ b/pal/input/minigame/hmd-input.ts @@ -0,0 +1,51 @@ +import { HMDCallback } from 'pal/input'; +import { InputEventType } from '../../../cocos/input/types/event-enum'; +import { EventTarget } from '../../../cocos/core/event/event-target'; +import { InputSourcePosition, InputSourceOrientation } from '../input-source'; +import { Vec3, Quat } from '../../../cocos/core/math'; + +export class HMDInputDevice { + public get viewLeftPosition () { return this._viewLeftPosition; } + public get viewLeftOrientation () { return this._viewLeftOrientation; } + public get viewRightPosition () { return this._viewRightPosition; } + public get viewRightOrientation () { return this._viewRightOrientation; } + public get headMiddlePosition () { return this._headMiddlePosition; } + public get headMiddleOrientation () { return this._headMiddleOrientation; } + + private _eventTarget: EventTarget = new EventTarget(); + + private _viewLeftPosition!: InputSourcePosition; + private _viewLeftOrientation!: InputSourceOrientation; + private _viewRightPosition!: InputSourcePosition; + private _viewRightOrientation!: InputSourceOrientation; + private _headMiddlePosition!: InputSourcePosition; + private _headMiddleOrientation!: InputSourceOrientation; + + constructor () { + this._initInputSource(); + } + + /** + * @engineInternal + */ + public _on (eventType: InputEventType, callback: HMDCallback, target?: any) { + this._eventTarget.on(eventType, callback, target); + } + + private _initInputSource () { + this._viewLeftPosition = new InputSourcePosition(); + this._viewLeftPosition.getValue = () => Vec3.ZERO; + this._viewLeftOrientation = new InputSourceOrientation(); + this._viewLeftOrientation.getValue = () => Quat.IDENTITY; + + this._viewRightPosition = new InputSourcePosition(); + this._viewRightPosition.getValue = () => Vec3.ZERO; + this._viewRightOrientation = new InputSourceOrientation(); + this._viewRightOrientation.getValue = () => Quat.IDENTITY; + + this._headMiddlePosition = new InputSourcePosition(); + this._headMiddlePosition.getValue = () => Vec3.ZERO; + this._headMiddleOrientation = new InputSourceOrientation(); + this._headMiddleOrientation.getValue = () => Quat.IDENTITY; + } +} diff --git a/pal/input/minigame/index.ts b/pal/input/minigame/index.ts index 37dcdcd2a5..ec3ed2aaf0 100644 --- a/pal/input/minigame/index.ts +++ b/pal/input/minigame/index.ts @@ -1,5 +1,7 @@ export * from './accelerometer-input'; export * from './gamepad-input'; +export * from './handle-input'; +export * from './hmd-input'; export * from './keyboard-input'; export * from './mouse-input'; export * from './touch-input'; diff --git a/pal/input/native/gamepad-input.ts b/pal/input/native/gamepad-input.ts index 83dc7bd498..34340d5140 100644 --- a/pal/input/native/gamepad-input.ts +++ b/pal/input/native/gamepad-input.ts @@ -1,7 +1,356 @@ -export class GamepadInputSource { - support: boolean; +/* eslint-disable brace-style */ +import { GamepadCallback } from 'pal/input'; +import { systemInfo } from 'pal/system-info'; +import { InputEventType } from '../../../cocos/input/types/event-enum'; +import { Feature } from '../../system-info/enum-type'; +import { EventTarget } from '../../../cocos/core/event/event-target'; +import { EventGamepad } from '../../../cocos/input/types'; +import { InputSourceButton, InputSourceDpad, InputSourceStick } from '../input-source'; +import { fastRemoveAt } from '../../../cocos/core/utils/array'; - constructor () { - this.support = false; +enum Button { + BUTTON_SOUTH, + BUTTON_EAST, + BUTTON_WEST, + BUTTON_NORTH, + NS_MINUS, + NS_PLUS, + BUTTON_L1, + BUTTON_L2, + BUTTON_L3, + BUTTON_R1, + BUTTON_R2, + BUTTON_R3, + DPAD_UP, + DPAD_DOWN, + DPAD_LEFT, + DPAD_RIGHT, + LEFT_STICK_UP, + LEFT_STICK_DOWN, + LEFT_STICK_LEFT, + LEFT_STICK_RIGHT, + RIGHT_STICK_UP, + RIGHT_STICK_DOWN, + RIGHT_STICK_LEFT, + RIGHT_STICK_RIGHT, + ROKID_MENU, + ROKID_START, +} + +type NativeButtonState = Record + +const _nativeButtonMap = { + 1: Button.BUTTON_EAST, + 2: Button.BUTTON_SOUTH, + 3: Button.BUTTON_NORTH, + 4: Button.BUTTON_WEST, + 5: Button.BUTTON_L1, + 6: Button.BUTTON_R1, + 7: Button.NS_MINUS, + 8: Button.NS_PLUS, + 9: Button.BUTTON_L3, + 10: Button.BUTTON_R3, + 11: Button.ROKID_MENU, + 12: Button.ROKID_START, +}; + +interface IAxisValue { + negative: number; + positive: number; +} + +export class GamepadInputDevice { + public static all: GamepadInputDevice[] = []; + + public get buttonNorth () { return this._buttonNorth; } + public get buttonEast () { return this._buttonEast; } + public get buttonWest () { return this._buttonWest; } + public get buttonSouth () { return this._buttonSouth; } + public get buttonL1 () { return this._buttonL1; } + public get buttonL2 () { return this._buttonL2; } + public get buttonL3 () { return this._buttonL3; } + public get buttonR1 () { return this._buttonR1; } + public get buttonR2 () { return this._buttonR2; } + public get buttonR3 () { return this._buttonR3; } + // public get buttonTouchPad () { return this._buttonTouchPad; } + // public get buttonHome () { return this._buttonHome; } + public get buttonShare () { return this._buttonShare; } + public get buttonOptions () { return this._buttonOptions; } + public get dpad () { return this._dpad; } + public get leftStick () { return this._leftStick; } + public get rightStick () { return this._rightStick; } + public get buttonStart () { return this._buttonStart; } + + public get deviceId () { + return this._deviceId; + } + public get connected () { + return this._connected; + } + + private static _eventTarget: EventTarget = new EventTarget(); + + private _buttonNorth!: InputSourceButton; + private _buttonEast!: InputSourceButton; + private _buttonWest!: InputSourceButton; + private _buttonSouth!: InputSourceButton; + private _buttonL1!: InputSourceButton; + private _buttonL2!: InputSourceButton; + private _buttonL3!: InputSourceButton; + private _buttonR1!: InputSourceButton; + private _buttonR2!: InputSourceButton; + private _buttonR3!: InputSourceButton; + // private buttonTouchPad!: InputSourceButton; + // private buttonHome!: InputSourceButton; + private _buttonShare!: InputSourceButton; + private _buttonOptions!: InputSourceButton; + private _dpad!: InputSourceDpad; + private _leftStick!: InputSourceStick; + private _rightStick!: InputSourceStick; + private _buttonStart!: InputSourceButton; + + private _deviceId = -1; + private _connected = false; + private _nativeButtonState: NativeButtonState = { + [Button.BUTTON_SOUTH]: 0, + [Button.BUTTON_EAST]: 0, + [Button.BUTTON_WEST]: 0, + [Button.BUTTON_NORTH]: 0, + [Button.NS_MINUS]: 0, + [Button.NS_PLUS]: 0, + [Button.BUTTON_L1]: 0, + [Button.BUTTON_L2]: 0, + [Button.BUTTON_L3]: 0, + [Button.BUTTON_R1]: 0, + [Button.BUTTON_R2]: 0, + [Button.BUTTON_R3]: 0, + [Button.DPAD_UP]: 0, + [Button.DPAD_DOWN]: 0, + [Button.DPAD_LEFT]: 0, + [Button.DPAD_RIGHT]: 0, + [Button.LEFT_STICK_UP]: 0, + [Button.LEFT_STICK_DOWN]: 0, + [Button.LEFT_STICK_LEFT]: 0, + [Button.LEFT_STICK_RIGHT]: 0, + [Button.RIGHT_STICK_UP]: 0, + [Button.RIGHT_STICK_DOWN]: 0, + [Button.RIGHT_STICK_LEFT]: 0, + [Button.RIGHT_STICK_RIGHT]: 0, + [Button.ROKID_MENU]: 0, + [Button.ROKID_START]: 0, + }; + + constructor (deviceId: number) { + this._deviceId = deviceId; + this._initInputSource(); + } + + /** + * @engineInternal + */ + public static _init () { + if (!systemInfo.hasFeature(Feature.EVENT_GAMEPAD)) { + return; + } + GamepadInputDevice._registerEvent(); + } + + /** + * @engineInternal + */ + public static _on (eventType: InputEventType, cb: GamepadCallback, target?: any) { + GamepadInputDevice._eventTarget.on(eventType, cb, target); + } + + private static _removeInputDevice (id: number) { + const removeIndex = GamepadInputDevice.all.findIndex((device) => device.deviceId === id); + if (removeIndex === -1) { + return; + } + fastRemoveAt(GamepadInputDevice.all, removeIndex); + } + private static _getInputDevice (id: number) { + return GamepadInputDevice.all.find((device) => device.deviceId === id); + } + private static _createInputDevice (id: number, connected: boolean) { + const device = new GamepadInputDevice(id); + device._connected = connected; + GamepadInputDevice.all.push(device); + return device; + } + private static _getOrCreateInputDevice (id: number, connected: boolean): GamepadInputDevice { + let device = GamepadInputDevice._getInputDevice(id); + if (!device) { + device = GamepadInputDevice._createInputDevice(id, connected); + } + device._connected = connected; + return device; + } + + private static _registerEvent () { + jsb.onControllerInput = (infoList: jsb.ControllerInfo[]) => { + for (let i = 0; i < infoList.length; ++i) { + const info = infoList[i]; + const device = GamepadInputDevice._getOrCreateInputDevice(info.id, true); + device._updateNativeButtonState(info); + GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_INPUT, new EventGamepad(InputEventType.GAMEPAD_INPUT, device)); + } + }; + + jsb.onControllerChange = (controllerIds) => { + // check connecting + for (let i = 0; i < controllerIds.length; ++i) { + const id = controllerIds[i]; + let device = GamepadInputDevice._getInputDevice(id); + if (!device) { + device = GamepadInputDevice._createInputDevice(id, true); + GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, device)); + } + } + // check disconnecting + const allDevices = GamepadInputDevice.all; + for (let i = 0; i < allDevices.length; ++i) { + const device = allDevices[i]; + if (!controllerIds.includes(device.deviceId)) { + GamepadInputDevice._removeInputDevice(device.deviceId); + device._connected = false; + GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, device)); + } + } + }; + } + + private _axisToButtons (axisValue: number): IAxisValue { + const value = Math.abs(axisValue); + if (axisValue > 0) { + return { negative: 0, positive: value }; + } else if (axisValue < 0) { + return { negative: value, positive: 0 }; + } else { + return { negative: 0, positive: 0 }; + } + } + + private _updateNativeButtonState (info: jsb.ControllerInfo) { + const { buttonInfoList, axisInfoList } = info; + for (let i = 0; i < buttonInfoList.length; ++i) { + const buttonInfo = buttonInfoList[i]; + const button = _nativeButtonMap[buttonInfo.code]; + this._nativeButtonState[button] = buttonInfo.isPressed ? 1 : 0; + } + for (let i = 0; i < axisInfoList.length; ++i) { + const axisInfo = axisInfoList[i]; + const { code, value } = axisInfo; + let negativeButton: Button | undefined; + let positiveButton: Button | undefined; + let axisValue: IAxisValue | undefined; + switch (code) { + case 1: + negativeButton = Button.DPAD_LEFT; + positiveButton = Button.DPAD_RIGHT; + axisValue = this._axisToButtons(value); + break; + case 2: + negativeButton = Button.DPAD_DOWN; + positiveButton = Button.DPAD_UP; + axisValue = this._axisToButtons(value); + break; + case 3: + negativeButton = Button.LEFT_STICK_LEFT; + positiveButton = Button.LEFT_STICK_RIGHT; + axisValue = this._axisToButtons(value); + break; + case 4: + negativeButton = Button.LEFT_STICK_DOWN; + positiveButton = Button.LEFT_STICK_UP; + axisValue = this._axisToButtons(value); + break; + case 5: + negativeButton = Button.RIGHT_STICK_LEFT; + positiveButton = Button.RIGHT_STICK_RIGHT; + axisValue = this._axisToButtons(value); + break; + case 6: + negativeButton = Button.RIGHT_STICK_DOWN; + positiveButton = Button.RIGHT_STICK_UP; + axisValue = this._axisToButtons(value); + break; + default: + if (code === 7) { this._nativeButtonState[Button.BUTTON_L2] = value; } + else if (code === 8) { this._nativeButtonState[Button.BUTTON_R2] = value; } + break; + } + if (negativeButton && positiveButton && axisValue) { + this._nativeButtonState[negativeButton] = axisValue.negative; + this._nativeButtonState[positiveButton] = axisValue.positive; + } + } + } + + private _initInputSource () { + this._buttonNorth = new InputSourceButton(); + this._buttonNorth.getValue = () => this._nativeButtonState[Button.BUTTON_NORTH]; + this._buttonEast = new InputSourceButton(); + this._buttonEast.getValue = () => this._nativeButtonState[Button.BUTTON_EAST]; + this._buttonWest = new InputSourceButton(); + this._buttonWest.getValue = () => this._nativeButtonState[Button.BUTTON_WEST]; + this._buttonSouth = new InputSourceButton(); + this._buttonSouth.getValue = () => this._nativeButtonState[Button.BUTTON_SOUTH]; + + this._buttonL1 = new InputSourceButton(); + this._buttonL1.getValue = () => this._nativeButtonState[Button.BUTTON_L1]; + this._buttonL2 = new InputSourceButton(); + this._buttonL2.getValue = () => this._nativeButtonState[Button.BUTTON_L2]; + this._buttonL3 = new InputSourceButton(); + this._buttonL3.getValue = () => this._nativeButtonState[Button.BUTTON_L3]; + this._buttonR1 = new InputSourceButton(); + this._buttonR1.getValue = () => this._nativeButtonState[Button.BUTTON_R1]; + this._buttonR2 = new InputSourceButton(); + this._buttonR2.getValue = () => this._nativeButtonState[Button.BUTTON_R2]; + this._buttonR3 = new InputSourceButton(); + this._buttonR3.getValue = () => this._nativeButtonState[Button.BUTTON_R3]; + + // this._buttonTouchPad = new InputSourceButton(); + // this._buttonTouchPad.getValue = () => 0; // TODO: NX unavailable + // this._buttonHome = new InputSourceButton(); + // this._buttonHome.getValue = () => 0; // TODO: NX unavailable + + this._buttonShare = new InputSourceButton(); + this._buttonShare.getValue = () => this._nativeButtonState[Button.NS_MINUS]; // TODO: NX only for now + this._buttonOptions = new InputSourceButton(); + this._buttonOptions.getValue = () => this._nativeButtonState[Button.NS_PLUS] || this._nativeButtonState[Button.ROKID_MENU]; + + const dpadUp = new InputSourceButton(); + dpadUp.getValue = () => this._nativeButtonState[Button.DPAD_UP]; + const dpadDown = new InputSourceButton(); + dpadDown.getValue = () => this._nativeButtonState[Button.DPAD_DOWN]; + const dpadLeft = new InputSourceButton(); + dpadLeft.getValue = () => this._nativeButtonState[Button.DPAD_LEFT]; + const dpadRight = new InputSourceButton(); + dpadRight.getValue = () => this._nativeButtonState[Button.DPAD_RIGHT]; + this._dpad = new InputSourceDpad({ up: dpadUp, down: dpadDown, left: dpadLeft, right: dpadRight }); + + const leftStickUp = new InputSourceButton(); + leftStickUp.getValue = () => this._nativeButtonState[Button.LEFT_STICK_UP]; + const leftStickDown = new InputSourceButton(); + leftStickDown.getValue = () => this._nativeButtonState[Button.LEFT_STICK_DOWN]; + const leftStickLeft = new InputSourceButton(); + leftStickLeft.getValue = () => this._nativeButtonState[Button.LEFT_STICK_LEFT]; + const leftStickRight = new InputSourceButton(); + leftStickRight.getValue = () => this._nativeButtonState[Button.LEFT_STICK_RIGHT]; + this._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight }); + + const rightStickUp = new InputSourceButton(); + rightStickUp.getValue = () => this._nativeButtonState[Button.RIGHT_STICK_UP]; + const rightStickDown = new InputSourceButton(); + rightStickDown.getValue = () => this._nativeButtonState[Button.RIGHT_STICK_DOWN]; + const rightStickLeft = new InputSourceButton(); + rightStickLeft.getValue = () => this._nativeButtonState[Button.RIGHT_STICK_LEFT]; + const rightStickRight = new InputSourceButton(); + rightStickRight.getValue = () => this._nativeButtonState[Button.RIGHT_STICK_RIGHT]; + this._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight }); + + this._buttonStart = new InputSourceButton(); + this._buttonStart.getValue = () => this._nativeButtonState[Button.ROKID_START]; // TODO: Rokid only for now } } diff --git a/pal/input/native/handle-input.ts b/pal/input/native/handle-input.ts new file mode 100644 index 0000000000..df7dde16a0 --- /dev/null +++ b/pal/input/native/handle-input.ts @@ -0,0 +1,321 @@ +import { HandleCallback } from 'pal/input'; +import { InputEventType } from '../../../cocos/input/types/event-enum'; +import { EventTarget } from '../../../cocos/core/event/event-target'; +import { EventHandle } from '../../../cocos/input/types'; +import { InputSourceButton, InputSourceStick, InputSourcePosition, InputSourceOrientation } from '../input-source'; +import { Vec3, Quat } from '../../../cocos/core/math'; + +enum Button { + BUTTON_EAST, + BUTTON_SOUTH, + BUTTON_WEST, + BUTTON_NORTH, + BUTTON_TRIGGER_LEFT, + BUTTON_TRIGGER_RIGHT, + TRIGGER_LEFT, + TRIGGER_RIGHT, + GRIP_LEFT, + GRIP_RIGHT, + BUTTON_LEFT_STICK, + LEFT_STICK_UP, + LEFT_STICK_DOWN, + LEFT_STICK_LEFT, + LEFT_STICK_RIGHT, + BUTTON_RIGHT_STICK, + RIGHT_STICK_UP, + RIGHT_STICK_DOWN, + RIGHT_STICK_LEFT, + RIGHT_STICK_RIGHT, +} + +enum Pose { + HAND_LEFT, + HAND_RIGHT, + AIM_LEFT, + AIM_RIGHT, +} + +interface IPoseValue { + position: Vec3; + orientation: Quat; +} + +type NativeButtonState = Record +type NativePoseState = Record + +const _nativeButtonMap = { + 1: Button.BUTTON_EAST, + 2: Button.BUTTON_SOUTH, + 3: Button.BUTTON_NORTH, + 4: Button.BUTTON_WEST, + 9: Button.BUTTON_LEFT_STICK, + 10: Button.BUTTON_RIGHT_STICK, + 13: Button.BUTTON_TRIGGER_LEFT, + 14: Button.BUTTON_TRIGGER_RIGHT, +}; + +interface IAxisValue { + negative: number; + positive: number; +} + +export class HandleInputDevice { + public get buttonNorth () { return this._buttonNorth; } + public get buttonEast () { return this._buttonEast; } + public get buttonWest () { return this._buttonWest; } + public get buttonSouth () { return this._buttonSouth; } + public get buttonTriggerLeft () { return this._buttonTriggerLeft; } + public get buttonTriggerRight () { return this._buttonTriggerRight; } + public get triggerLeft () { return this._triggerLeft; } + public get triggerRight () { return this._triggerRight; } + public get gripLeft () { return this._gripLeft; } + public get gripRight () { return this._gripRight; } + public get leftStick () { return this._leftStick; } + public get rightStick () { return this._rightStick; } + public get buttonLeftStick () { return this._buttonLeftStick; } + public get buttonRightStick () { return this._buttonRightStick; } + public get handLeftPosition () { return this._handLeftPosition; } + public get handLeftOrientation () { return this._handLeftOrientation; } + public get handRightPosition () { return this._handRightPosition; } + public get handRightOrientation () { return this._handRightOrientation; } + public get aimLeftPosition () { return this._aimLeftPosition; } + public get aimLeftOrientation () { return this._aimLeftOrientation; } + public get aimRightPosition () { return this._aimRightPosition; } + public get aimRightOrientation () { return this._aimRightOrientation; } + + private _eventTarget: EventTarget = new EventTarget(); + + private _buttonNorth!: InputSourceButton; + private _buttonEast!: InputSourceButton; + private _buttonWest!: InputSourceButton; + private _buttonSouth!: InputSourceButton; + private _buttonTriggerLeft!: InputSourceButton; + private _buttonTriggerRight!: InputSourceButton; + private _triggerLeft!: InputSourceButton; + private _triggerRight!: InputSourceButton; + private _gripLeft!: InputSourceButton; + private _gripRight!: InputSourceButton; + private _leftStick!: InputSourceStick; + private _rightStick!: InputSourceStick; + private _buttonLeftStick!: InputSourceButton; + private _buttonRightStick!: InputSourceButton; + private _handLeftPosition!: InputSourcePosition; + private _handLeftOrientation!: InputSourceOrientation; + private _handRightPosition!: InputSourcePosition; + private _handRightOrientation!: InputSourceOrientation; + private _aimLeftPosition!: InputSourcePosition; + private _aimLeftOrientation!: InputSourceOrientation; + private _aimRightPosition!: InputSourcePosition; + private _aimRightOrientation!: InputSourceOrientation; + + private _nativeButtonState: NativeButtonState = { + [Button.BUTTON_SOUTH]: 0, + [Button.BUTTON_EAST]: 0, + [Button.BUTTON_WEST]: 0, + [Button.BUTTON_NORTH]: 0, + [Button.BUTTON_TRIGGER_LEFT]: 0, + [Button.BUTTON_TRIGGER_RIGHT]: 0, + [Button.TRIGGER_LEFT]: 0, + [Button.TRIGGER_RIGHT]: 0, + [Button.GRIP_LEFT]: 0, + [Button.GRIP_RIGHT]: 0, + [Button.LEFT_STICK_UP]: 0, + [Button.LEFT_STICK_DOWN]: 0, + [Button.LEFT_STICK_LEFT]: 0, + [Button.LEFT_STICK_RIGHT]: 0, + [Button.RIGHT_STICK_UP]: 0, + [Button.RIGHT_STICK_DOWN]: 0, + [Button.RIGHT_STICK_LEFT]: 0, + [Button.RIGHT_STICK_RIGHT]: 0, + [Button.BUTTON_LEFT_STICK]: 0, + [Button.BUTTON_RIGHT_STICK]: 0, + }; + + private _nativePoseState: NativePoseState = { + [Pose.HAND_LEFT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, + [Pose.HAND_RIGHT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, + [Pose.AIM_LEFT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, + [Pose.AIM_RIGHT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, + } + + constructor () { + this._initInputSource(); + this._registerEvent(); + } + + private _registerEvent () { + jsb.onHandleInput = (infoList: jsb.ControllerInfo[]) => { + for (let i = 0; i < infoList.length; ++i) { + const info = infoList[i]; + this._updateNativeButtonState(info); + this._eventTarget.emit(InputEventType.HANDLE_INPUT, new EventHandle(InputEventType.HANDLE_INPUT, this)); + } + }; + + jsb.onHandlePoseInput = (infoList: jsb.PoseInfo[]) => { + for (let i = 0; i < infoList.length; ++i) { + const info = infoList[i]; + this._updateNativePoseState(info); + } + this._eventTarget.emit(InputEventType.HANDLE_POSE_INPUT, new EventHandle(InputEventType.HANDLE_POSE_INPUT, this)); + }; + } + + /** + * @engineInternal + */ + public _on (eventType: InputEventType, callback: HandleCallback, target?: any) { + this._eventTarget.on(eventType, callback, target); + } + + private _axisToButtons (axisValue: number): IAxisValue { + const value = Math.abs(axisValue); + if (axisValue > 0) { + return { negative: 0, positive: value }; + } else if (axisValue < 0) { + return { negative: value, positive: 0 }; + } else { + return { negative: 0, positive: 0 }; + } + } + + private _updateNativeButtonState (info: jsb.ControllerInfo) { + const { buttonInfoList, axisInfoList } = info; + for (let i = 0; i < buttonInfoList.length; ++i) { + const buttonInfo = buttonInfoList[i]; + const button = _nativeButtonMap[buttonInfo.code]; + this._nativeButtonState[button] = buttonInfo.isPressed ? 1 : 0; + } + for (let i = 0; i < axisInfoList.length; ++i) { + const axisInfo = axisInfoList[i]; + const { code, value } = axisInfo; + let negativeButton: Button | undefined; + let positiveButton: Button | undefined; + let axisValue: IAxisValue | undefined; + switch (code) { + case 3: + negativeButton = Button.LEFT_STICK_LEFT; + positiveButton = Button.LEFT_STICK_RIGHT; + axisValue = this._axisToButtons(value); + break; + case 4: + negativeButton = Button.LEFT_STICK_DOWN; + positiveButton = Button.LEFT_STICK_UP; + axisValue = this._axisToButtons(value); + break; + case 5: + negativeButton = Button.RIGHT_STICK_LEFT; + positiveButton = Button.RIGHT_STICK_RIGHT; + axisValue = this._axisToButtons(value); + break; + case 6: + negativeButton = Button.RIGHT_STICK_DOWN; + positiveButton = Button.RIGHT_STICK_UP; + axisValue = this._axisToButtons(value); + break; + default: + if (code === 7) { + this._nativeButtonState[Button.TRIGGER_LEFT] = value; + } else if (code === 8) { + this._nativeButtonState[Button.TRIGGER_RIGHT] = value; + } else if (code === 9) { + this._nativeButtonState[Button.GRIP_LEFT] = value; + } else if (code === 10) { + this._nativeButtonState[Button.GRIP_RIGHT] = value; + } + break; + } + if (negativeButton && positiveButton && axisValue) { + this._nativeButtonState[negativeButton] = axisValue.negative; + this._nativeButtonState[positiveButton] = axisValue.positive; + } + } + } + + private _updateNativePoseState (info: jsb.PoseInfo) { + switch (info.code) { + case 1: + this._nativePoseState[Pose.HAND_LEFT] = { position: new Vec3(info.x, info.y, info.z), orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) }; + break; + case 2: + this._nativePoseState[Pose.AIM_LEFT] = { position: new Vec3(info.x, info.y, info.z), orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) }; + break; + case 4: + this._nativePoseState[Pose.HAND_RIGHT] = { position: new Vec3(info.x, info.y, info.z), orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) }; + break; + case 5: + this._nativePoseState[Pose.AIM_RIGHT] = { position: new Vec3(info.x, info.y, info.z), orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) }; + break; + default: + break; + } + } + + private _initInputSource () { + this._buttonNorth = new InputSourceButton(); + this._buttonNorth.getValue = () => this._nativeButtonState[Button.BUTTON_NORTH]; + this._buttonEast = new InputSourceButton(); + this._buttonEast.getValue = () => this._nativeButtonState[Button.BUTTON_EAST]; + this._buttonWest = new InputSourceButton(); + this._buttonWest.getValue = () => this._nativeButtonState[Button.BUTTON_WEST]; + this._buttonSouth = new InputSourceButton(); + this._buttonSouth.getValue = () => this._nativeButtonState[Button.BUTTON_SOUTH]; + + this._buttonTriggerLeft = new InputSourceButton(); + this._buttonTriggerLeft.getValue = () => this._nativeButtonState[Button.BUTTON_TRIGGER_LEFT]; + this._buttonTriggerRight = new InputSourceButton(); + this._buttonTriggerRight.getValue = () => this._nativeButtonState[Button.BUTTON_TRIGGER_RIGHT]; + this._triggerLeft = new InputSourceButton(); + this._triggerLeft.getValue = () => this._nativeButtonState[Button.TRIGGER_LEFT]; + this._triggerRight = new InputSourceButton(); + this._triggerRight.getValue = () => this._nativeButtonState[Button.TRIGGER_RIGHT]; + this._gripLeft = new InputSourceButton(); + this._gripLeft.getValue = () => this._nativeButtonState[Button.GRIP_LEFT]; + this._gripRight = new InputSourceButton(); + this._gripRight.getValue = () => this._nativeButtonState[Button.GRIP_RIGHT]; + + this._buttonLeftStick = new InputSourceButton(); + this._buttonLeftStick.getValue = () => this._nativeButtonState[Button.BUTTON_LEFT_STICK]; + const leftStickUp = new InputSourceButton(); + leftStickUp.getValue = () => this._nativeButtonState[Button.LEFT_STICK_UP]; + const leftStickDown = new InputSourceButton(); + leftStickDown.getValue = () => this._nativeButtonState[Button.LEFT_STICK_DOWN]; + const leftStickLeft = new InputSourceButton(); + leftStickLeft.getValue = () => this._nativeButtonState[Button.LEFT_STICK_LEFT]; + const leftStickRight = new InputSourceButton(); + leftStickRight.getValue = () => this._nativeButtonState[Button.LEFT_STICK_RIGHT]; + this._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight }); + + this._buttonRightStick = new InputSourceButton(); + this._buttonRightStick.getValue = () => this._nativeButtonState[Button.BUTTON_RIGHT_STICK]; + const rightStickUp = new InputSourceButton(); + rightStickUp.getValue = () => this._nativeButtonState[Button.RIGHT_STICK_UP]; + const rightStickDown = new InputSourceButton(); + rightStickDown.getValue = () => this._nativeButtonState[Button.RIGHT_STICK_DOWN]; + const rightStickLeft = new InputSourceButton(); + rightStickLeft.getValue = () => this._nativeButtonState[Button.RIGHT_STICK_LEFT]; + const rightStickRight = new InputSourceButton(); + rightStickRight.getValue = () => this._nativeButtonState[Button.RIGHT_STICK_RIGHT]; + this._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight }); + + this._handLeftPosition = new InputSourcePosition(); + this._handLeftPosition.getValue = () => this._nativePoseState[Pose.HAND_LEFT].position; + this._handLeftOrientation = new InputSourceOrientation(); + this._handLeftOrientation.getValue = () => this._nativePoseState[Pose.HAND_LEFT].orientation; + + this._handRightPosition = new InputSourcePosition(); + this._handRightPosition.getValue = () => this._nativePoseState[Pose.HAND_RIGHT].position; + this._handRightOrientation = new InputSourceOrientation(); + this._handRightOrientation.getValue = () => this._nativePoseState[Pose.HAND_RIGHT].orientation; + + this._aimLeftPosition = new InputSourcePosition(); + this._aimLeftPosition.getValue = () => this._nativePoseState[Pose.AIM_LEFT].position; + this._aimLeftOrientation = new InputSourceOrientation(); + this._aimLeftOrientation.getValue = () => this._nativePoseState[Pose.AIM_LEFT].orientation; + + this._aimRightPosition = new InputSourcePosition(); + this._aimRightPosition.getValue = () => this._nativePoseState[Pose.AIM_RIGHT].position; + this._aimRightOrientation = new InputSourceOrientation(); + this._aimRightOrientation.getValue = () => this._nativePoseState[Pose.AIM_RIGHT].orientation; + } +} diff --git a/pal/input/native/hmd-input.ts b/pal/input/native/hmd-input.ts new file mode 100644 index 0000000000..b82ee21c62 --- /dev/null +++ b/pal/input/native/hmd-input.ts @@ -0,0 +1,98 @@ +import { HMDCallback } from 'pal/input'; +import { InputEventType } from '../../../cocos/input/types/event-enum'; +import { EventTarget } from '../../../cocos/core/event/event-target'; +import { EventHMD } from '../../../cocos/input/types'; +import { InputSourcePosition, InputSourceOrientation } from '../input-source'; +import { Vec3, Quat } from '../../../cocos/core/math'; + +enum Pose { + VIEW_LEFT, + VIEW_RIGHT, + HEAD_MIDDLE, +} + +interface IPoseValue { + position: Vec3; + orientation: Quat; +} + +type NativePoseState = Record + +export class HMDInputDevice { + public get viewLeftPosition () { return this._viewLeftPosition; } + public get viewLeftOrientation () { return this._viewLeftOrientation; } + public get viewRightPosition () { return this._viewRightPosition; } + public get viewRightOrientation () { return this._viewRightOrientation; } + public get headMiddlePosition () { return this._headMiddlePosition; } + public get headMiddleOrientation () { return this._headMiddleOrientation; } + + private _eventTarget: EventTarget = new EventTarget(); + + private _viewLeftPosition!: InputSourcePosition; + private _viewLeftOrientation!: InputSourceOrientation; + private _viewRightPosition!: InputSourcePosition; + private _viewRightOrientation!: InputSourceOrientation; + private _headMiddlePosition!: InputSourcePosition; + private _headMiddleOrientation!: InputSourceOrientation; + + private _nativePoseState: NativePoseState = { + [Pose.VIEW_LEFT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, + [Pose.VIEW_RIGHT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, + [Pose.HEAD_MIDDLE]: { position: Vec3.ZERO, orientation: Quat.IDENTITY }, + } + + constructor () { + this._initInputSource(); + this._registerEvent(); + } + + private _registerEvent () { + jsb.onHMDPoseInput = (infoList: jsb.PoseInfo[]) => { + for (let i = 0; i < infoList.length; ++i) { + const info = infoList[i]; + this._updateNativePoseState(info); + } + this._eventTarget.emit(InputEventType.HMD_POSE_INPUT, new EventHMD(InputEventType.HMD_POSE_INPUT, this)); + }; + } + + /** + * @engineInternal + */ + public _on (eventType: InputEventType, callback: HMDCallback, target?: any) { + this._eventTarget.on(eventType, callback, target); + } + + private _updateNativePoseState (info: jsb.PoseInfo) { + switch (info.code) { + case 0: + this._nativePoseState[Pose.VIEW_LEFT] = { position: new Vec3(info.x, info.y, info.z), orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) }; + break; + case 3: + this._nativePoseState[Pose.VIEW_RIGHT] = { position: new Vec3(info.x, info.y, info.z), orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) }; + break; + case 6: + this._nativePoseState[Pose.HEAD_MIDDLE] = { position: new Vec3(info.x, info.y, info.z), orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) }; + break; + default: + break; + } + } + + private _initInputSource () { + this._viewLeftPosition = new InputSourcePosition(); + this._viewLeftPosition.getValue = () => this._nativePoseState[Pose.VIEW_LEFT].position; + this._viewLeftOrientation = new InputSourceOrientation(); + this._viewLeftOrientation.getValue = () => this._nativePoseState[Pose.VIEW_LEFT].orientation; + + this._viewRightPosition = new InputSourcePosition(); + this._viewRightPosition.getValue = () => this._nativePoseState[Pose.VIEW_RIGHT].position; + this._viewRightOrientation = new InputSourceOrientation(); + this._viewRightOrientation.getValue = () => this._nativePoseState[Pose.VIEW_RIGHT].orientation; + + this._headMiddlePosition = new InputSourcePosition(); + this._headMiddlePosition.getValue = () => this._nativePoseState[Pose.HEAD_MIDDLE].position; + this._headMiddleOrientation = new InputSourceOrientation(); + this._headMiddleOrientation.getValue = () => this._nativePoseState[Pose.HEAD_MIDDLE].orientation; + } +} diff --git a/pal/input/native/index.ts b/pal/input/native/index.ts index 37dcdcd2a5..ec3ed2aaf0 100644 --- a/pal/input/native/index.ts +++ b/pal/input/native/index.ts @@ -1,5 +1,7 @@ export * from './accelerometer-input'; export * from './gamepad-input'; +export * from './handle-input'; +export * from './hmd-input'; export * from './keyboard-input'; export * from './mouse-input'; export * from './touch-input'; diff --git a/pal/input/web/gamepad-input.ts b/pal/input/web/gamepad-input.ts index 83dc7bd498..1895c67aab 100644 --- a/pal/input/web/gamepad-input.ts +++ b/pal/input/web/gamepad-input.ts @@ -1,7 +1,437 @@ -export class GamepadInputSource { - support: boolean; +import { GamepadCallback } from 'pal/input'; +import { systemInfo } from 'pal/system-info'; +import { InputEventType } from '../../../cocos/input/types/event-enum'; +import { EventTarget } from '../../../cocos/core/event/event-target'; +import legacyCC from '../../../predefine'; +import { Feature } from '../../system-info/enum-type'; +import { InputSourceButton, InputSourceDpad, InputSourceStick } from '../input-source'; +import { fastRemoveAt } from '../../../cocos/core/utils/array'; +import { EventGamepad } from '../../../cocos/input/types'; - constructor () { - this.support = false; +//#region button index alias +const BUTTON_SOUTH = 0; +const BUTTON_EAST = 1; +const BUTTON_WEST = 2; +const BUTTON_NORTH = 3; +const BUTTON_L1 = 4; +const BUTTON_R1 = 5; +const BUTTON_L2 = 6; +const BUTTON_R2 = 7; +const BUTTON_SHARE = 8; +const BUTTON_OPTIONS = 9; +const BUTTON_L3 = 10; +const BUTTON_R3 = 11; +const BUTTON_DPAD_UP = 12; +const BUTTON_DPAD_DOWN = 13; +const BUTTON_DPAD_LEFT = 14; +const BUTTON_DPAD_RIGHT = 15; +const BUTTON_HOME = 16; +const BUTTON_TOUCH_PAD = 17; +const AXIS_LEFT_STICK_X = 0; +const AXIS_LEFT_STICK_Y = 1; +const AXIS_RIGHT_STICK_X = 2; +const AXIS_RIGHT_STICK_Y = 3; +//#endregion button index alias + +const EPSILON = 0.01; +type WebGamepad = Gamepad; + +interface IAxisValue { + negative: number; + positive: number; +} +export class GamepadInputDevice { + public static all: GamepadInputDevice[] = []; + + public get buttonNorth () { return this._buttonNorth; } + public get buttonEast () { return this._buttonEast; } + public get buttonWest () { return this._buttonWest; } + public get buttonSouth () { return this._buttonSouth; } + public get buttonL1 () { return this._buttonL1; } + public get buttonL2 () { return this._buttonL2; } + public get buttonL3 () { return this._buttonL3; } + public get buttonR1 () { return this._buttonR1; } + public get buttonR2 () { return this._buttonR2; } + public get buttonR3 () { return this._buttonR3; } + // public get buttonTouchPad () { return this._buttonTouchPad; } + // public get buttonHome () { return this._buttonHome; } + public get buttonShare () { return this._buttonShare; } + public get buttonOptions () { return this._buttonOptions; } + public get dpad () { return this._dpad; } + public get leftStick () { return this._leftStick; } + public get rightStick () { return this._rightStick; } + public get buttonStart () { return this._buttonStart; } + + public get deviceId () { + return this._deviceId; + } + public get connected () { + return this._connected; + } + + private static _eventTarget: EventTarget = new EventTarget(); + private static _cachedWebGamepads: (WebGamepad | null)[] = []; + private static _intervalId = -1; + + private _buttonNorth!: InputSourceButton; + private _buttonEast!: InputSourceButton; + private _buttonWest!: InputSourceButton; + private _buttonSouth!: InputSourceButton; + private _buttonL1!: InputSourceButton; + private _buttonL2!: InputSourceButton; + private _buttonL3!: InputSourceButton; + private _buttonR1!: InputSourceButton; + private _buttonR2!: InputSourceButton; + private _buttonR3!: InputSourceButton; + // private buttonTouchPad!: InputSourceButton; + // private buttonHome!: InputSourceButton; + private _buttonShare!: InputSourceButton; + private _buttonOptions!: InputSourceButton; + private _dpad!: InputSourceDpad; + private _leftStick!: InputSourceStick; + private _rightStick!: InputSourceStick; + private _buttonStart!: InputSourceButton; + + private _deviceId = -1; + private _connected = false; + + constructor (deviceId: number) { + this._deviceId = deviceId; + this._initInputSource(); + } + + /** + * @engineInternal + */ + public static _init () { + if (!systemInfo.hasFeature(Feature.EVENT_GAMEPAD)) { + return; + } + GamepadInputDevice._registerEvent(); + } + + /** + * @engineInternal + */ + public static _on (eventType: InputEventType, cb: GamepadCallback, target?: any) { + GamepadInputDevice._eventTarget.on(eventType, cb, target); + } + + private static _removeInputDevice (id: number) { + const removeIndex = GamepadInputDevice.all.findIndex((device) => device.deviceId === id); + if (removeIndex === -1) { + return; + } + fastRemoveAt(GamepadInputDevice.all, removeIndex); + } + private static _getOrCreateInputDevice (id: number, connected: boolean): GamepadInputDevice { + let device = GamepadInputDevice.all.find((device) => device.deviceId === id); + if (!device) { + device = new GamepadInputDevice(id); + GamepadInputDevice.all.push(device); + } + device._connected = connected; + return device; + } + + private static _ensureDirectorDefined () { + return new Promise((resolve) => { + GamepadInputDevice._intervalId = setInterval(() => { + if (legacyCC.director && legacyCC.Director) { + clearInterval(GamepadInputDevice._intervalId); + GamepadInputDevice._intervalId = -1; + resolve(); + } + }, 50); + }); + } + + private static _registerEvent () { + GamepadInputDevice._ensureDirectorDefined().then(() => { + legacyCC.director.on(legacyCC.Director.EVENT_BEGIN_FRAME, GamepadInputDevice._scanGamepads); + }).catch((e) => {}); + window.addEventListener('gamepadconnected', (e) => { + GamepadInputDevice._cachedWebGamepads[e.gamepad.index] = e.gamepad; + const device = GamepadInputDevice._getOrCreateInputDevice(e.gamepad.index, true); + GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, device)); + }); + window.addEventListener('gamepaddisconnected', (e) => { + GamepadInputDevice._cachedWebGamepads[e.gamepad.index] = null; + const device = GamepadInputDevice._getOrCreateInputDevice(e.gamepad.index, false); + GamepadInputDevice._removeInputDevice(e.gamepad.index); + GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, device)); + }); + } + + private static _scanGamepads () { + const webGamepads = GamepadInputDevice._getWebGamePads(); + if (!webGamepads) { + return; + } + const devices: GamepadInputDevice[] = []; + for (let i = 0; i < webGamepads.length; ++i) { + const webGamepad = webGamepads?.[i]; + if (!webGamepad) { + continue; + } + const cachedWebGamepad = GamepadInputDevice._cachedWebGamepads[webGamepad.index]; + // TODO: what if cachedWebGamepad is null + if (cachedWebGamepad) { + let device: GamepadInputDevice | undefined; + const cachedButtons = cachedWebGamepad.buttons; + for (let j = 0; j < cachedButtons.length; ++j) { + const cachedButton = cachedButtons[j]; + const button = webGamepad.buttons[j]; + if (Math.abs(cachedButton.value - button.value) > EPSILON) { + device = GamepadInputDevice._getOrCreateInputDevice(webGamepad.index, true); + break; + } + } + if (device) { + devices.push(device); + continue; + } + + const cachedAxes = cachedWebGamepad.axes; + for (let j = 0; j < cachedAxes.length; ++j) { + const cachedAxisValue = cachedAxes[j]; + const axisValue = webGamepad.axes[j]; + if (Math.abs(cachedAxisValue - axisValue) > EPSILON) { + device = GamepadInputDevice._getOrCreateInputDevice(webGamepad.index, true); + break; + } + } + if (device) { + devices.push(device); + continue; + } + } + } + // update cache + GamepadInputDevice._cachedWebGamepads = webGamepads; + // emit event + for (let i = 0; i < devices.length; ++i) { + const device = devices[i]; + GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_INPUT, new EventGamepad(InputEventType.GAMEPAD_INPUT, device)); + } + } + + private static _getWebGamePads (): (WebGamepad | null)[] { + if (typeof navigator.getGamepads === 'function') { + return navigator.getGamepads(); + // @ts-expect-error Property 'webkitGetGamepads' does not exist on type 'Navigator' + } else if (typeof navigator.webkitGetGamepads === 'function') { + // @ts-expect-error Property 'webkitGetGamepads' does not exist on type 'Navigator' + return navigator.webkitGetGamepads() as (Gamepad | null)[]; + } + return []; + } + + private static _getWebGamepad (deviceId: number): WebGamepad | undefined { + const webGamepads = GamepadInputDevice._getWebGamePads(); + for (let i = 0; i < webGamepads.length; ++i) { + const webGamepad = webGamepads[i]; + if (webGamepad && webGamepad.index === deviceId) { + return webGamepad; + } + } + return undefined; + } + + private _axisToButtons (axisValue: number): IAxisValue { + const value = Math.abs(axisValue); + if (axisValue > 0) { + return { negative: 0, positive: value }; + } else if (axisValue < 0) { + return { negative: value, positive: 0 }; + } else { + return { negative: 0, positive: 0 }; + } + } + + private _initInputSource () { + this._buttonNorth = new InputSourceButton(); + this._buttonNorth.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { return webGamepad.buttons[BUTTON_NORTH].value; } + return 0; + }; + this._buttonEast = new InputSourceButton(); + this._buttonEast.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { return webGamepad.buttons[BUTTON_EAST].value; } + return 0; + }; + this._buttonWest = new InputSourceButton(); + this._buttonWest.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { return webGamepad.buttons[BUTTON_WEST].value; } + return 0; + }; + this._buttonSouth = new InputSourceButton(); + this._buttonSouth.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { return webGamepad.buttons[BUTTON_SOUTH].value; } + return 0; + }; + + this._buttonL1 = new InputSourceButton(); + this._buttonL1.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { return webGamepad.buttons[BUTTON_L1].value; } + return 0; + }; + this._buttonL2 = new InputSourceButton(); + this._buttonL2.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { return webGamepad.buttons[BUTTON_L2].value; } + return 0; + }; + this._buttonL3 = new InputSourceButton(); + this._buttonL3.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { return webGamepad.buttons[BUTTON_L3].value; } + return 0; + }; + this._buttonR1 = new InputSourceButton(); + this._buttonR1.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { return webGamepad.buttons[BUTTON_R1].value; } + return 0; + }; + this._buttonR2 = new InputSourceButton(); + this._buttonR2.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { return webGamepad.buttons[BUTTON_R2].value; } + return 0; + }; + this._buttonR3 = new InputSourceButton(); + this._buttonR3.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { return webGamepad.buttons[BUTTON_R3].value; } + return 0; + }; + + // this._buttonTouchPad = new InputSourceButton(); + // this._buttonTouchPad.getValue = () => { + // const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + // if (webGamepad) { return webGamepad.buttons[BUTTON_TOUCH_PAD].value; } + // return 0; + // }; + // this._buttonHome = new InputSourceButton(); + // this._buttonHome.getValue = () => { + // const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + // if (webGamepad) { return webGamepad.buttons[BUTTON_HOME].value; } + // return 0; + // }; + this._buttonShare = new InputSourceButton(); + this._buttonShare.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { return webGamepad.buttons[BUTTON_SHARE].value; } + return 0; + }; + this._buttonOptions = new InputSourceButton(); + this._buttonOptions.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { return webGamepad.buttons[BUTTON_OPTIONS].value; } + return 0; + }; + + const dpadUp = new InputSourceButton(); + dpadUp.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { return webGamepad.buttons[BUTTON_DPAD_UP].value; } + return 0; + }; + const dpadDown = new InputSourceButton(); + dpadDown.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { return webGamepad.buttons[BUTTON_DPAD_DOWN].value; } + return 0; + }; + const dpadLeft = new InputSourceButton(); + dpadLeft.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { return webGamepad.buttons[BUTTON_DPAD_LEFT].value; } + return 0; + }; + const dpadRight = new InputSourceButton(); + dpadRight.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { return webGamepad.buttons[BUTTON_DPAD_RIGHT].value; } + return 0; + }; + this._dpad = new InputSourceDpad({ up: dpadUp, down: dpadDown, left: dpadLeft, right: dpadRight }); + + const leftStickUp = new InputSourceButton(); + leftStickUp.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { + return this._axisToButtons(webGamepad.axes[AXIS_LEFT_STICK_Y]).negative; + } + return 0; + }; + const leftStickDown = new InputSourceButton(); + leftStickDown.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { + return this._axisToButtons(webGamepad.axes[AXIS_LEFT_STICK_Y]).positive; + } + return 0; + }; + const leftStickLeft = new InputSourceButton(); + leftStickLeft.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { + return this._axisToButtons(webGamepad.axes[AXIS_LEFT_STICK_X]).negative; + } + return 0; + }; + const leftStickRight = new InputSourceButton(); + leftStickRight.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { + return this._axisToButtons(webGamepad.axes[AXIS_LEFT_STICK_X]).positive; + } + return 0; + }; + this._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight }); + + const rightStickUp = new InputSourceButton(); + rightStickUp.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { + return this._axisToButtons(webGamepad.axes[AXIS_RIGHT_STICK_Y]).negative; + } + return 0; + }; + const rightStickDown = new InputSourceButton(); + rightStickDown.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { + return this._axisToButtons(webGamepad.axes[AXIS_RIGHT_STICK_Y]).positive; + } + return 0; + }; + const rightStickLeft = new InputSourceButton(); + rightStickLeft.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { + return this._axisToButtons(webGamepad.axes[AXIS_RIGHT_STICK_X]).negative; + } + return 0; + }; + const rightStickRight = new InputSourceButton(); + rightStickRight.getValue = () => { + const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId); + if (webGamepad) { + return this._axisToButtons(webGamepad.axes[AXIS_RIGHT_STICK_X]).positive; + } + return 0; + }; + this._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight }); + + this._buttonStart = new InputSourceButton(); + this._buttonStart.getValue = () => 0; } } diff --git a/pal/input/web/handle-input.ts b/pal/input/web/handle-input.ts new file mode 100644 index 0000000000..f861620d43 --- /dev/null +++ b/pal/input/web/handle-input.ts @@ -0,0 +1,134 @@ +import { HandleCallback } from 'pal/input'; +import { InputEventType } from '../../../cocos/input/types/event-enum'; +import { EventTarget } from '../../../cocos/core/event'; +import { InputSourceButton, InputSourceStick, InputSourcePosition, InputSourceOrientation } from '../input-source'; +import { Vec3, Quat } from '../../../cocos/core/math'; + +export class HandleInputDevice { + public get buttonNorth () { return this._buttonNorth; } + public get buttonEast () { return this._buttonEast; } + public get buttonWest () { return this._buttonWest; } + public get buttonSouth () { return this._buttonSouth; } + public get buttonTriggerLeft () { return this._buttonTriggerLeft; } + public get buttonTriggerRight () { return this._buttonTriggerRight; } + public get triggerLeft () { return this._triggerLeft; } + public get triggerRight () { return this._triggerRight; } + public get gripLeft () { return this._gripLeft; } + public get gripRight () { return this._gripRight; } + public get leftStick () { return this._leftStick; } + public get rightStick () { return this._rightStick; } + public get buttonLeftStick () { return this._buttonLeftStick; } + public get buttonRightStick () { return this._buttonRightStick; } + public get handLeftPosition () { return this._handLeftPosition; } + public get handLeftOrientation () { return this._handLeftOrientation; } + public get handRightPosition () { return this._handRightPosition; } + public get handRightOrientation () { return this._handRightOrientation; } + public get aimLeftPosition () { return this._aimLeftPosition; } + public get aimLeftOrientation () { return this._aimLeftOrientation; } + public get aimRightPosition () { return this._aimRightPosition; } + public get aimRightOrientation () { return this._aimRightOrientation; } + + private _eventTarget: EventTarget = new EventTarget(); + + private _buttonNorth!: InputSourceButton; + private _buttonEast!: InputSourceButton; + private _buttonWest!: InputSourceButton; + private _buttonSouth!: InputSourceButton; + private _buttonTriggerLeft!: InputSourceButton; + private _buttonTriggerRight!: InputSourceButton; + private _triggerLeft!: InputSourceButton; + private _triggerRight!: InputSourceButton; + private _gripLeft!: InputSourceButton; + private _gripRight!: InputSourceButton; + private _leftStick!: InputSourceStick; + private _rightStick!: InputSourceStick; + private _buttonLeftStick!: InputSourceButton; + private _buttonRightStick!: InputSourceButton; + private _handLeftPosition!: InputSourcePosition; + private _handLeftOrientation!: InputSourceOrientation; + private _handRightPosition!: InputSourcePosition; + private _handRightOrientation!: InputSourceOrientation; + private _aimLeftPosition!: InputSourcePosition; + private _aimLeftOrientation!: InputSourceOrientation; + private _aimRightPosition!: InputSourcePosition; + private _aimRightOrientation!: InputSourceOrientation; + + constructor () { + this._initInputSource(); + } + + /** + * @engineInternal + */ + public _on (eventType: InputEventType, callback: HandleCallback, target?: any) { + this._eventTarget.on(eventType, callback, target); + } + + private _initInputSource () { + this._buttonNorth = new InputSourceButton(); + this._buttonNorth.getValue = () => 0; + this._buttonEast = new InputSourceButton(); + this._buttonEast.getValue = () => 0; + this._buttonWest = new InputSourceButton(); + this._buttonWest.getValue = () => 0; + this._buttonSouth = new InputSourceButton(); + this._buttonSouth.getValue = () => 0; + + this._buttonTriggerLeft = new InputSourceButton(); + this._buttonTriggerLeft.getValue = () => 0; + this._buttonTriggerRight = new InputSourceButton(); + this._buttonTriggerRight.getValue = () => 0; + this._triggerLeft = new InputSourceButton(); + this._triggerLeft.getValue = () => 0; + this._triggerRight = new InputSourceButton(); + this._triggerRight.getValue = () => 0; + this._gripLeft = new InputSourceButton(); + this._gripLeft.getValue = () => 0; + this._gripRight = new InputSourceButton(); + this._gripRight.getValue = () => 0; + + this._buttonLeftStick = new InputSourceButton(); + this._buttonLeftStick.getValue = () => 0; + const leftStickUp = new InputSourceButton(); + leftStickUp.getValue = () => 0; + const leftStickDown = new InputSourceButton(); + leftStickDown.getValue = () => 0; + const leftStickLeft = new InputSourceButton(); + leftStickLeft.getValue = () => 0; + const leftStickRight = new InputSourceButton(); + leftStickRight.getValue = () => 0; + this._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight }); + + this._buttonRightStick = new InputSourceButton(); + this._buttonRightStick.getValue = () => 0; + const rightStickUp = new InputSourceButton(); + rightStickUp.getValue = () => 0; + const rightStickDown = new InputSourceButton(); + rightStickDown.getValue = () => 0; + const rightStickLeft = new InputSourceButton(); + rightStickLeft.getValue = () => 0; + const rightStickRight = new InputSourceButton(); + rightStickRight.getValue = () => 0; + this._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight }); + + this._handLeftPosition = new InputSourcePosition(); + this._handLeftPosition.getValue = () => Vec3.ZERO; + this._handLeftOrientation = new InputSourceOrientation(); + this._handLeftOrientation.getValue = () => Quat.IDENTITY; + + this._handRightPosition = new InputSourcePosition(); + this._handRightPosition.getValue = () => Vec3.ZERO; + this._handRightOrientation = new InputSourceOrientation(); + this._handRightOrientation.getValue = () => Quat.IDENTITY; + + this._aimLeftPosition = new InputSourcePosition(); + this._aimLeftPosition.getValue = () => Vec3.ZERO; + this._aimLeftOrientation = new InputSourceOrientation(); + this._aimLeftOrientation.getValue = () => Quat.IDENTITY; + + this._aimRightPosition = new InputSourcePosition(); + this._aimRightPosition.getValue = () => Vec3.ZERO; + this._aimRightOrientation = new InputSourceOrientation(); + this._aimRightOrientation.getValue = () => Quat.IDENTITY; + } +} diff --git a/pal/input/web/hmd-input.ts b/pal/input/web/hmd-input.ts new file mode 100644 index 0000000000..7cbd0a37c3 --- /dev/null +++ b/pal/input/web/hmd-input.ts @@ -0,0 +1,51 @@ +import { HMDCallback } from 'pal/input'; +import { InputEventType } from '../../../cocos/input/types/event-enum'; +import { EventTarget } from '../../../cocos/core/event/event-target'; +import { InputSourcePosition, InputSourceOrientation } from '../input-source'; +import { Vec3, Quat } from '../../../cocos/core/math'; + +export class HMDInputDevice { + public get viewLeftPosition () { return this._viewLeftPosition; } + public get viewLeftOrientation () { return this._viewLeftOrientation; } + public get viewRightPosition () { return this._viewRightPosition; } + public get viewRightOrientation () { return this._viewRightOrientation; } + public get headMiddlePosition () { return this._headMiddlePosition; } + public get headMiddleOrientation () { return this._headMiddleOrientation; } + + private _eventTarget: EventTarget = new EventTarget(); + + private _viewLeftPosition!: InputSourcePosition; + private _viewLeftOrientation!: InputSourceOrientation; + private _viewRightPosition!: InputSourcePosition; + private _viewRightOrientation!: InputSourceOrientation; + private _headMiddlePosition!: InputSourcePosition; + private _headMiddleOrientation!: InputSourceOrientation; + + constructor () { + this._initInputSource(); + } + + /** + * @engineInternal + */ + public _on (eventType: InputEventType, callback: HMDCallback, target?: any) { + this._eventTarget.on(eventType, callback, target); + } + + private _initInputSource () { + this._viewLeftPosition = new InputSourcePosition(); + this._viewLeftPosition.getValue = () => Vec3.ZERO; + this._viewLeftOrientation = new InputSourceOrientation(); + this._viewLeftOrientation.getValue = () => Quat.IDENTITY; + + this._viewRightPosition = new InputSourcePosition(); + this._viewRightPosition.getValue = () => Vec3.ZERO; + this._viewRightOrientation = new InputSourceOrientation(); + this._viewRightOrientation.getValue = () => Quat.IDENTITY; + + this._headMiddlePosition = new InputSourcePosition(); + this._headMiddlePosition.getValue = () => Vec3.ZERO; + this._headMiddleOrientation = new InputSourceOrientation(); + this._headMiddleOrientation.getValue = () => Quat.IDENTITY; + } +} diff --git a/pal/input/web/index.ts b/pal/input/web/index.ts index 37dcdcd2a5..ec3ed2aaf0 100644 --- a/pal/input/web/index.ts +++ b/pal/input/web/index.ts @@ -1,5 +1,7 @@ export * from './accelerometer-input'; export * from './gamepad-input'; +export * from './handle-input'; +export * from './hmd-input'; export * from './keyboard-input'; export * from './mouse-input'; export * from './touch-input'; diff --git a/pal/system-info/enum-type/feature.ts b/pal/system-info/enum-type/feature.ts index c9764883eb..82189fbdd3 100644 --- a/pal/system-info/enum-type/feature.ts +++ b/pal/system-info/enum-type/feature.ts @@ -56,4 +56,19 @@ export enum Feature { * @zh 是否支持派发 EventAcceleration。 */ EVENT_ACCELEROMETER = 'EVENT_ACCELEROMETER', + /** + * @en Feature to support dispatching EventGamepad. + * @zh 是否支持派发 EventGamepad. + */ + EVENT_GAMEPAD = 'EVENT_GAMEPAD', + /** + * @en Feature to support dispatching EventHandle. + * @zh 是否支持派发 EventHandle + */ + EVENT_HANDLE = 'EVENT_HANDLE', + /** + * @en Feature to support dispatching EventHMD. + * @zh 是否支持派发 EventHMD + */ + EVENT_HMD = 'EVENT_HMD', } diff --git a/pal/system-info/minigame/system-info.ts b/pal/system-info/minigame/system-info.ts index c7be9755d4..3fc5de8202 100644 --- a/pal/system-info/minigame/system-info.ts +++ b/pal/system-info/minigame/system-info.ts @@ -44,6 +44,7 @@ class SystemInfo extends EventTarget { public readonly osMainVersion: number; public readonly browserType: BrowserType; public readonly browserVersion: string; + public readonly isXR: boolean; private _featureMap: IFeatureMap; constructor () { @@ -93,6 +94,8 @@ class SystemInfo extends EventTarget { this.browserType = BrowserType.UNKNOWN; this.browserVersion = ''; + this.isXR = false; + // init capability const _tmpCanvas1 = document.createElement('canvas'); // TODO: remove this let supportWebp; @@ -115,6 +118,9 @@ class SystemInfo extends EventTarget { [Feature.EVENT_MOUSE]: isPCWechat, [Feature.EVENT_TOUCH]: true, [Feature.EVENT_ACCELEROMETER]: !isPCWechat, + [Feature.EVENT_GAMEPAD]: false, + [Feature.EVENT_HANDLE]: this.isXR, + [Feature.EVENT_HMD]: this.isXR, }; this._registerEvent(); diff --git a/pal/system-info/native/system-info.ts b/pal/system-info/native/system-info.ts index 15f0c23246..ebf5145083 100644 --- a/pal/system-info/native/system-info.ts +++ b/pal/system-info/native/system-info.ts @@ -34,6 +34,7 @@ class SystemInfo extends EventTarget { public readonly osMainVersion: number; public readonly browserType: BrowserType; public readonly browserVersion: string; + public readonly isXR: boolean; private _featureMap: IFeatureMap; // TODO: need to wrap the function __isObjectValid() @@ -75,6 +76,8 @@ class SystemInfo extends EventTarget { this.browserType = BrowserType.UNKNOWN; this.browserVersion = ''; + this.isXR = typeof xr !== 'undefined'; + this._featureMap = { [Feature.WEBP]: true, [Feature.IMAGE_BITMAP]: false, @@ -87,6 +90,9 @@ class SystemInfo extends EventTarget { [Feature.EVENT_MOUSE]: !this.isMobile, [Feature.EVENT_TOUCH]: true, [Feature.EVENT_ACCELEROMETER]: this.isMobile, + [Feature.EVENT_GAMEPAD]: true, + [Feature.EVENT_HANDLE]: this.isXR, + [Feature.EVENT_HMD]: this.isXR, }; this._registerEvent(); diff --git a/pal/system-info/web/system-info.ts b/pal/system-info/web/system-info.ts index 5abf671b85..88f9d949c1 100644 --- a/pal/system-info/web/system-info.ts +++ b/pal/system-info/web/system-info.ts @@ -18,6 +18,7 @@ class SystemInfo extends EventTarget { public readonly osMainVersion: number; public readonly browserType: BrowserType; public readonly browserVersion: string; + public readonly isXR: boolean; private _battery?: any; private _featureMap: IFeatureMap; @@ -142,6 +143,8 @@ class SystemInfo extends EventTarget { } this.browserVersion = tmp ? tmp[4] : ''; + this.isXR = false; + // init capability const _tmpCanvas1 = document.createElement('canvas'); const supportCanvas = TEST ? false : !!_tmpCanvas1.getContext('2d'); @@ -189,6 +192,10 @@ class SystemInfo extends EventTarget { [Feature.EVENT_MOUSE]: supportMouse, [Feature.EVENT_TOUCH]: supportTouch || supportMouse, [Feature.EVENT_ACCELEROMETER]: (window.DeviceMotionEvent !== undefined || window.DeviceOrientationEvent !== undefined), + // @ts-expect-error undefined webkitGetGamepads + [Feature.EVENT_GAMEPAD]: (navigator.getGamepads !== undefined || navigator.webkitGetGamepads !== undefined), + [Feature.EVENT_HANDLE]: this.isXR, + [Feature.EVENT_HMD]: this.isXR, }; this._registerEvent(); diff --git a/scripts/native-pack-tool/source/platforms/huawei-agc.ts b/scripts/native-pack-tool/source/platforms/huawei-agc.ts index 4c546be39a..c6d96f3674 100644 --- a/scripts/native-pack-tool/source/platforms/huawei-agc.ts +++ b/scripts/native-pack-tool/source/platforms/huawei-agc.ts @@ -4,23 +4,35 @@ import * as ps from 'path'; import { AndroidPackTool } from "./android"; export class HuaweiAGCPackTool extends AndroidPackTool { + + // 模板复用 android 平台的 + private readonly _platform: string = 'android'; + /** - * 共用 android 平台的流程 - * copyPlatformTemplate 拷贝平台模板倒 native/engine 目录下时,重写为从 android 平台的模板拷贝 agc + * 拷贝 android 平台模板到 project/native/engine/huawei-agc 目录下 */ protected async copyPlatformTemplate() { // 原生工程不重复拷贝 TODO 复用前需要做版本检测 if (!fs.existsSync(this.paths.nativePrjDir)) { // 拷贝 lite 仓库的 templates/android/build 文件到构建输出目录 - await fs.copy(ps.join(this.paths.nativeTemplateDirInCocos, 'android', 'build'), this.paths.nativePrjDir, { overwrite: false }); + await fs.copy(ps.join(this.paths.nativeTemplateDirInCocos, this._platform, 'build'), this.paths.nativePrjDir, { overwrite: false }); } // 原生工程不重复拷贝 TODO 复用前需要做版本检测 if (!fs.existsSync(this.paths.platformTemplateDirInPrj)) { // 拷贝 lite 仓库的 templates/android/template 文件到构建输出目录 - await fs.copy(ps.join(this.paths.nativeTemplateDirInCocos, 'android', 'template'), this.paths.platformTemplateDirInPrj, { overwrite: false }); + await fs.copy(ps.join(this.paths.nativeTemplateDirInCocos, this._platform, 'template'), this.paths.platformTemplateDirInPrj, { overwrite: false }); this.writeEngineVersion(); } else { this.validateNativeDir(); } } + + /** + * 校验 engine/template/android 和 project/native/engine/huawei-agc 下的模板文件 + */ + protected validatePlatformDirectory(missing: string[]): void { + const srcDir = ps.join(this.paths.nativeTemplateDirInCocos, this._platform, 'template'); + const dstDir = this.paths.platformTemplateDirInPrj; + this.validateDirectory(srcDir, dstDir, missing); + } } diff --git a/templates/android/template/app/build.gradle b/templates/android/template/app/build.gradle index 0917da1268..540d6b684d 100644 --- a/templates/android/template/app/build.gradle +++ b/templates/android/template/app/build.gradle @@ -74,6 +74,14 @@ android { if (project.hasProperty("RELEASE_STORE_FILE")) { signingConfig signingConfigs.release } + + externalNativeBuild { + cmake { + // switch HIDE_SYMBOLS to OFF to skip compilation flag `-fvisibility=hidden` + arguments "-DHIDE_SYMBOLS=ON" + } + } + // resValue "string", "app_name", PROP_APP_NAME } diff --git a/templates/android/template/instantapp/build.gradle b/templates/android/template/instantapp/build.gradle index 72ba70e637..a7f17fd436 100644 --- a/templates/android/template/instantapp/build.gradle +++ b/templates/android/template/instantapp/build.gradle @@ -71,6 +71,14 @@ android { if (project.hasProperty("RELEASE_STORE_FILE")) { signingConfig signingConfigs.release } + + externalNativeBuild { + cmake { + // switch HIDE_SYMBOLS to OFF to skip compilation flag `-fvisibility=hidden` + arguments "-DHIDE_SYMBOLS=ON" + } + } + // resValue "string", "app_name", PROP_APP_NAME } diff --git a/templates/cmake/android.cmake b/templates/cmake/android.cmake index cbcadf09da..7d5b198f98 100644 --- a/templates/cmake/android.cmake +++ b/templates/cmake/android.cmake @@ -6,15 +6,17 @@ macro(cc_android_before_target target_name) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsigned-char -ffunction-sections -fdata-sections -fstrict-aliasing") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsigned-char -ffunction-sections -fdata-sections -fstrict-aliasing -frtti -fexceptions") -if("${ANDROID_ABI}" STREQUAL "armeabi-v7a") - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -mfpu=neon-fp16") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mfpu=neon-fp16") -endif() + if("${ANDROID_ABI}" STREQUAL "armeabi-v7a") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -mfpu=neon-fp16") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mfpu=neon-fp16") + endif() set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -fvisibility=default -fno-omit-frame-pointer") - set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -fvisibility=hidden") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -fvisibility=default -fno-omit-frame-pointer") - set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fvisibility=hidden -fvisibility-inlines-hidden") + if(NOT DEFINED HIDE_SYMBOLS OR HIDE_SYMBOLS) # hidden by default + set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -fvisibility=hidden") + set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fvisibility=hidden -fvisibility-inlines-hidden") + endif() cc_common_before_target(${target_name}) endmacro() diff --git a/templates/xr-huaweivr/build/build.gradle b/templates/xr-huaweivr/build/build.gradle new file mode 100644 index 0000000000..d748464112 --- /dev/null +++ b/templates/xr-huaweivr/build/build.gradle @@ -0,0 +1,18 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + + repositories { + google() + mavenCentral() + // jcenter() // keeped as anchor, will be removed soon + } + dependencies { + classpath 'com.android.tools.build:gradle:4.1.0' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +apply from: NATIVE_DIR +"/build.gradle" diff --git a/templates/xr-huaweivr/build/gradle.properties b/templates/xr-huaweivr/build/gradle.properties new file mode 100644 index 0000000000..6a701a83ce --- /dev/null +++ b/templates/xr-huaweivr/build/gradle.properties @@ -0,0 +1,66 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +# Default value: -Xmx10248m -XX:MaxPermSize=256m +# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true +org.gradle.jvmargs=-Xmx4608m +android.useAndroidX=true + +android.injected.testOnly=false + +# Android SDK version that will be used as the compile project +PROP_COMPILE_SDK_VERSION=28 + +# Android SDK version that will be used as the earliest version of android this application can run on +PROP_MIN_SDK_VERSION=21 + +# Android SDK version that will be used as the latest version of android this application has been tested on +PROP_TARGET_SDK_VERSION=27 + +# Android Build Tools version that will be used as the compile project +PROP_BUILD_TOOLS_VERSION=28.0.0 + +# Android Application Name +PROP_APP_NAME=Cocos Game + +# Instant App +PROP_ENABLE_INSTANT_APP=true + +PROP_NDK_PATH= + +# Cocos Engine Path +COCOS_ENGINE_PATH= + +# Res path +RES_PATH= + +# Native source dir +NATIVE_DIR= + +# Application ID +APPLICATION_ID= + +# List of CPU Archtexture to build that application with +# Available architextures (armeabi-v7a | arm64-v8a | x86 | x86_64) +# To build for multiple architexture, use the `:` between them +# Example - PROP_APP_ABI=armeabi-v7a:arm64-v8a:x86 +PROP_APP_ABI=arm64-v8a + +# fill in sign information for release mode +# RELEASE_STORE_FILE= +# RELEASE_STORE_PASSWORD= +# RELEASE_KEY_ALIAS= +# RELEASE_KEY_PASSWORD= diff --git a/templates/xr-huaweivr/build/gradle/wrapper/gradle-wrapper.jar b/templates/xr-huaweivr/build/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..8c0fb64a86 Binary files /dev/null and b/templates/xr-huaweivr/build/gradle/wrapper/gradle-wrapper.jar differ diff --git a/templates/xr-huaweivr/build/gradle/wrapper/gradle-wrapper.properties b/templates/xr-huaweivr/build/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..69d02eef07 --- /dev/null +++ b/templates/xr-huaweivr/build/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Fri Oct 27 10:18:28 CST 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.5.1-all.zip diff --git a/templates/xr-huaweivr/build/gradlew b/templates/xr-huaweivr/build/gradlew new file mode 100644 index 0000000000..91a7e269e1 --- /dev/null +++ b/templates/xr-huaweivr/build/gradlew @@ -0,0 +1,164 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# For Cygwin, ensure paths are in UNIX format before anything is touched. +if $cygwin ; then + [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` +fi + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >&- +APP_HOME="`pwd -P`" +cd "$SAVED" >&- + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/templates/xr-huaweivr/build/gradlew.bat b/templates/xr-huaweivr/build/gradlew.bat new file mode 100644 index 0000000000..8a0b282aa6 --- /dev/null +++ b/templates/xr-huaweivr/build/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/templates/xr-huaweivr/build/libservice/AndroidManifest.xml b/templates/xr-huaweivr/build/libservice/AndroidManifest.xml new file mode 100644 index 0000000000..55d9c69b56 --- /dev/null +++ b/templates/xr-huaweivr/build/libservice/AndroidManifest.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/templates/xr-huaweivr/build/libservice/build.gradle b/templates/xr-huaweivr/build/libservice/build.gradle new file mode 100644 index 0000000000..4417d18639 --- /dev/null +++ b/templates/xr-huaweivr/build/libservice/build.gradle @@ -0,0 +1,37 @@ +apply plugin: 'com.android.library' + +android { + compileSdkVersion PROP_COMPILE_SDK_VERSION.toInteger() + + defaultConfig { + minSdkVersion PROP_MIN_SDK_VERSION + targetSdkVersion PROP_TARGET_SDK_VERSION + versionCode 1 + versionName "1.0" + } + + sourceSets.main { + java.srcDirs "src" + res.srcDirs 'res' + jniLibs.srcDirs 'libs' + jniLibs.srcDirs "${COCOS_ENGINE_PATH}/external/sources/xr/huaweivr/android/java/libs" + manifest.srcFile "AndroidManifest.xml" + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar','*.aar']) + implementation fileTree(dir: "${COCOS_ENGINE_PATH}/external/sources/xr/huaweivr/android/java/libs", include: ['*.jar','*.aar']) + implementation project(':libcocos') +} diff --git a/templates/xr-huaweivr/build/libservice/proguard-rules.pro b/templates/xr-huaweivr/build/libservice/proguard-rules.pro new file mode 100644 index 0000000000..f1b424510d --- /dev/null +++ b/templates/xr-huaweivr/build/libservice/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/templates/xr-huaweivr/build/libservice/src/com/cocos/service/SDKWrapper.java b/templates/xr-huaweivr/build/libservice/src/com/cocos/service/SDKWrapper.java new file mode 100644 index 0000000000..67666ebde4 --- /dev/null +++ b/templates/xr-huaweivr/build/libservice/src/com/cocos/service/SDKWrapper.java @@ -0,0 +1,193 @@ +/**************************************************************************** + Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. + http://www.cocos.com + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +package com.cocos.service; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.content.res.AssetManager; +import android.content.res.Configuration; +import android.os.Bundle; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.List; + +public final class SDKWrapper { + private SDKWrapper() {} + private static class SDKWrapperInstance { + private static final SDKWrapper mInstance = new SDKWrapper(); + } + public static SDKWrapper shared() { return SDKWrapperInstance.mInstance; } + + @SuppressWarnings("unused") + public interface SDKInterface { + default void init(Context context) {} + default void onStart() {} + default void onPause() {} + default void onResume() {} + default void onStop() {} + default void onDestroy() {} + default void onRestart() {} + default void onNewIntent(Intent intent) {} + default void onActivityResult(int requestCode, int resultCode, Intent data) {} + default void onConfigurationChanged(Configuration newConfig) {} + default void onRestoreInstanceState(Bundle savedInstanceState) {} + default void onSaveInstanceState(Bundle outState) {} + default void onBackPressed() {} + default void onLowMemory() {} + } + + private WeakReference mActivity = null; + private List serviceInstances; + + private void loadSDKInterface() { + ArrayList instances = new ArrayList<>(); + try { + String json = this.getJson("service.json"); + JSONObject jsonObject = new JSONObject(json); + JSONArray serviceClasses = jsonObject.getJSONArray("serviceClasses"); + if (serviceClasses == null) return; + int length = serviceClasses.length(); + for (int i = 0; i < length; i++) { + instances.add((SDKInterface) Class.forName(serviceClasses.getString(i)).newInstance()); + } + } catch (Exception ignored) { } + this.serviceInstances = instances; + } + + @SuppressWarnings("SameParameterValue") + private String getJson(String fileName) { + StringBuilder sb = new StringBuilder(); + try { + AssetManager am = this.mActivity.get().getAssets(); + BufferedReader br = new BufferedReader(new InputStreamReader(am.open(fileName))); + String next; + while (null != (next = br.readLine())) { sb.append(next); } + } catch (IOException e) { + sb.delete(0, sb.length()); + } + return sb.toString().trim(); + } + + public Activity getActivity() { return this.mActivity.get(); } + + public void init(Activity activity) { + try { + Class libUpdateClient = Class.forName("com.huawei.hvr.LibUpdateClient"); + Object libUpdateClientObj = libUpdateClient.getConstructor(android.content.Context.class).newInstance(activity); + libUpdateClient.getMethod("runUpdate").invoke(libUpdateClientObj); + } catch (Exception e) { + e.printStackTrace(); + } + + this.mActivity = new WeakReference<>(activity); + this.loadSDKInterface(); + for (SDKInterface sdk : this.serviceInstances) { + sdk.init(activity); + } + } + + public void onResume() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onResume(); + } + } + + public void onPause() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onPause(); + } + } + + public void onDestroy() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onDestroy(); + } + } + + public void onActivityResult(int requestCode, int resultCode, Intent data) { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onActivityResult(requestCode, resultCode, data); + } + } + + public void onNewIntent(Intent intent) { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onNewIntent(intent); + } + } + + public void onRestart() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onRestart(); + } + } + + public void onStop() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onStop(); + } + } + + public void onBackPressed() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onBackPressed(); + } + } + + public void onConfigurationChanged(Configuration newConfig) { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onConfigurationChanged(newConfig); + } + } + + public void onRestoreInstanceState(Bundle savedInstanceState) { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onRestoreInstanceState(savedInstanceState); + } + } + + public void onSaveInstanceState(Bundle outState) { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onSaveInstanceState(outState); + } + } + + public void onStart() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onStart(); + } + } + + public void onLowMemory() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onLowMemory(); + } + } +} \ No newline at end of file diff --git a/templates/xr-huaweivr/build/settings.gradle b/templates/xr-huaweivr/build/settings.gradle new file mode 100644 index 0000000000..80cad73242 --- /dev/null +++ b/templates/xr-huaweivr/build/settings.gradle @@ -0,0 +1,9 @@ +include ':libcocos',':libservice',':CocosGame' +project(':libcocos').projectDir = new File(COCOS_ENGINE_PATH,'cocos/platform/android/libcocos2dx') +project(':CocosGame').projectDir = new File(NATIVE_DIR, 'app') +if(PROP_ENABLE_INSTANT_APP == "true" || PROP_ENABLE_INSTANT_APP == "yes") { + include ':instantapp' + project(':instantapp').projectDir = new File(NATIVE_DIR, 'instantapp') +} + +rootProject.name = "CocosGame" diff --git a/templates/xr-huaweivr/template/.gitignore b/templates/xr-huaweivr/template/.gitignore new file mode 100644 index 0000000000..9c4de5825b --- /dev/null +++ b/templates/xr-huaweivr/template/.gitignore @@ -0,0 +1,7 @@ +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build +/captures diff --git a/templates/xr-huaweivr/template/CMakeLists.txt b/templates/xr-huaweivr/template/CMakeLists.txt new file mode 100644 index 0000000000..b6f90857a9 --- /dev/null +++ b/templates/xr-huaweivr/template/CMakeLists.txt @@ -0,0 +1,15 @@ +cmake_minimum_required(VERSION 3.8) + +option(APP_NAME "Project Name" "CocosGame") +project(${APP_NAME} CXX) +set(CC_LIB_NAME cocos) +set(CC_PROJECT_DIR ${CMAKE_CURRENT_LIST_DIR}) +set(CC_PROJ_SOURCES) +set(CC_COMMON_SOURCES) +set(CC_ALL_SOURCES) + +include(${CMAKE_CURRENT_LIST_DIR}/../common/CMakeLists.txt) + +cc_android_before_target(${CC_LIB_NAME}) +add_library(${CC_LIB_NAME} SHARED ${CC_ALL_SOURCES}) +cc_android_after_target(${CC_LIB_NAME}) diff --git a/templates/xr-huaweivr/template/app/.gitignore b/templates/xr-huaweivr/template/app/.gitignore new file mode 100644 index 0000000000..1de99493d6 --- /dev/null +++ b/templates/xr-huaweivr/template/app/.gitignore @@ -0,0 +1,2 @@ +/build +/jniLibs diff --git a/templates/xr-huaweivr/template/app/AndroidManifest.xml b/templates/xr-huaweivr/template/app/AndroidManifest.xml new file mode 100644 index 0000000000..88646e758b --- /dev/null +++ b/templates/xr-huaweivr/template/app/AndroidManifest.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + diff --git a/templates/xr-huaweivr/template/app/build.gradle b/templates/xr-huaweivr/template/app/build.gradle new file mode 100644 index 0000000000..eadb361daa --- /dev/null +++ b/templates/xr-huaweivr/template/app/build.gradle @@ -0,0 +1,97 @@ +import org.apache.tools.ant.taskdefs.condition.Os + +apply plugin: 'com.android.application' + +RES_PATH = RES_PATH.replace("\\", "/") +COCOS_ENGINE_PATH = COCOS_ENGINE_PATH.replace("\\", "/") + +buildDir = "${RES_PATH}/proj/build/$project.name" +android { + compileSdkVersion PROP_COMPILE_SDK_VERSION.toInteger() + buildToolsVersion PROP_BUILD_TOOLS_VERSION + ndkPath PROP_NDK_PATH + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + defaultConfig { + applicationId APPLICATION_ID + minSdkVersion PROP_MIN_SDK_VERSION + targetSdkVersion PROP_TARGET_SDK_VERSION + versionCode 1 + versionName "1.0" + + externalNativeBuild { + cmake { + targets "cocos" + arguments "-DRES_DIR=${RES_PATH}", "-DCOCOS_X_PATH=${COCOS_ENGINE_PATH}", "-DANDROID_STL=c++_static", "-DANDROID_TOOLCHAIN=clang", "-DANDROID_ARM_NEON=TRUE", "-DANDROID_LD=gold" + } + ndk { abiFilters PROP_APP_ABI.split(':') } + } + } + + sourceSets.main { + java.srcDirs "../src", "src" + res.srcDirs "../res", 'res' + jniLibs.srcDirs "../libs", 'libs' + manifest.srcFile "AndroidManifest.xml" + assets.srcDir "${RES_PATH}/data" + jniLibs { + // Vulkan validation layer + // srcDir "${android.ndkDirectory}/sources/third_party/vulkan/src/build-android/jniLibs" + } + } + + externalNativeBuild { + cmake { + path "../CMakeLists.txt" + buildStagingDirectory "${RES_PATH}/proj/build" + } + } + + signingConfigs { + + release { + if (project.hasProperty("RELEASE_STORE_FILE") && !RELEASE_STORE_FILE.isEmpty()) { + storeFile file(RELEASE_STORE_FILE) + storePassword RELEASE_STORE_PASSWORD + keyAlias RELEASE_KEY_ALIAS + keyPassword RELEASE_KEY_PASSWORD + } + } + } + + buildTypes { + release { + debuggable false + jniDebuggable false + renderscriptDebuggable false + minifyEnabled true + shrinkResources true + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + proguardFiles "${COCOS_ENGINE_PATH}/external/sources/xr/huaweivr/android/java/proguard-rules.pro" + if (project.hasProperty("RELEASE_STORE_FILE")) { + signingConfig signingConfigs.release + } + // resValue "string", "app_name", PROP_APP_NAME + } + + debug { + debuggable true + jniDebuggable true + renderscriptDebuggable true + // resValue "string", "app_name", "${PROP_APP_NAME}-dbg" + // applicationIdSuffix ".debug" + } + } +} + +dependencies { + implementation fileTree(dir: '../libs', include: ['*.jar','*.aar']) + implementation fileTree(dir: 'libs', include: ['*.jar','*.aar']) + implementation fileTree(dir: "${COCOS_ENGINE_PATH}/cocos/platform/android/java/libs", include: ['*.jar']) + implementation project(':libservice') + implementation project(':libcocos') +} diff --git a/templates/xr-huaweivr/template/app/proguard-rules.pro b/templates/xr-huaweivr/template/app/proguard-rules.pro new file mode 100644 index 0000000000..dbb43fbbf1 --- /dev/null +++ b/templates/xr-huaweivr/template/app/proguard-rules.pro @@ -0,0 +1,42 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in E:\developSoftware\Android\SDK/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Proguard Cocos2d-x-lite for release +-keep public class com.cocos.** { *; } +-dontwarn com.cocos.** + +# Proguard Apache HTTP for release +-keep class org.apache.http.** { *; } +-dontwarn org.apache.http.** + +# Proguard okhttp for release +-keep class okhttp3.** { *; } +-dontwarn okhttp3.** + +-keep class okio.** { *; } +-dontwarn okio.** + +# Proguard Android Webivew for release. you can comment if you are not using a webview +-keep public class android.net.http.SslError +-keep public class android.webkit.WebViewClient + +-keep public class com.google.** { *; } + +-dontwarn android.webkit.WebView +-dontwarn android.net.http.SslError +-dontwarn android.webkit.WebViewClient diff --git a/templates/xr-huaweivr/template/app/src/com/cocos/game/AppActivity.java b/templates/xr-huaweivr/template/app/src/com/cocos/game/AppActivity.java new file mode 100644 index 0000000000..bacee31947 --- /dev/null +++ b/templates/xr-huaweivr/template/app/src/com/cocos/game/AppActivity.java @@ -0,0 +1,125 @@ +/**************************************************************************** +Copyright (c) 2015-2016 Chukong Technologies Inc. +Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ +package com.cocos.game; + +import android.os.Bundle; +import android.content.Intent; +import android.content.res.Configuration; + +import com.cocos.service.SDKWrapper; +import com.cocos.lib.CocosActivity; + +public class AppActivity extends CocosActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + // DO OTHER INITIALIZATION BELOW + SDKWrapper.shared().init(this); + + } + + @Override + protected void onResume() { + super.onResume(); + SDKWrapper.shared().onResume(); + } + + @Override + protected void onPause() { + super.onPause(); + SDKWrapper.shared().onPause(); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + // Workaround in https://stackoverflow.com/questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508 + if (!isTaskRoot()) { + return; + } + SDKWrapper.shared().onDestroy(); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + SDKWrapper.shared().onActivityResult(requestCode, resultCode, data); + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + SDKWrapper.shared().onNewIntent(intent); + } + + @Override + protected void onRestart() { + super.onRestart(); + SDKWrapper.shared().onRestart(); + } + + @Override + protected void onStop() { + super.onStop(); + SDKWrapper.shared().onStop(); + } + + @Override + public void onBackPressed() { + SDKWrapper.shared().onBackPressed(); + super.onBackPressed(); + } + + @Override + public void onConfigurationChanged(Configuration newConfig) { + SDKWrapper.shared().onConfigurationChanged(newConfig); + super.onConfigurationChanged(newConfig); + } + + @Override + protected void onRestoreInstanceState(Bundle savedInstanceState) { + SDKWrapper.shared().onRestoreInstanceState(savedInstanceState); + super.onRestoreInstanceState(savedInstanceState); + } + + @Override + protected void onSaveInstanceState(Bundle outState) { + SDKWrapper.shared().onSaveInstanceState(outState); + super.onSaveInstanceState(outState); + } + + @Override + protected void onStart() { + SDKWrapper.shared().onStart(); + super.onStart(); + } + + @Override + public void onLowMemory() { + SDKWrapper.shared().onLowMemory(); + super.onLowMemory(); + } +} diff --git a/templates/xr-huaweivr/template/build-cfg.json b/templates/xr-huaweivr/template/build-cfg.json new file mode 100644 index 0000000000..fb658e2985 --- /dev/null +++ b/templates/xr-huaweivr/template/build-cfg.json @@ -0,0 +1,8 @@ +{ + "ndk_module_path" :[ + "${COCOS_ROOT}", + "${COCOS_ROOT}/cocos", + "${COCOS_ROOT}/external" + ], + "copy_resources": [] +} diff --git a/templates/xr-huaweivr/template/build.gradle b/templates/xr-huaweivr/template/build.gradle new file mode 100644 index 0000000000..2ae589d169 --- /dev/null +++ b/templates/xr-huaweivr/template/build.gradle @@ -0,0 +1,31 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + + repositories { + google() + mavenCentral() + // jcenter() // keeped as anchor, will be removed soon + } + dependencies { + classpath 'com.android.tools.build:gradle:4.1.0' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + google() + mavenCentral() + // jcenter() // keeped as anchor, will be removed soon + flatDir { + dirs 'libs' + } + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/templates/xr-huaweivr/template/instantapp/AndroidManifest.xml b/templates/xr-huaweivr/template/instantapp/AndroidManifest.xml new file mode 100644 index 0000000000..d4578bd08f --- /dev/null +++ b/templates/xr-huaweivr/template/instantapp/AndroidManifest.xml @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/templates/xr-huaweivr/template/instantapp/build.gradle b/templates/xr-huaweivr/template/instantapp/build.gradle new file mode 100644 index 0000000000..5691f073f7 --- /dev/null +++ b/templates/xr-huaweivr/template/instantapp/build.gradle @@ -0,0 +1,94 @@ +import org.apache.tools.ant.taskdefs.condition.Os + +apply plugin: 'com.android.application' + +RES_PATH = RES_PATH.replace("\\", "/") +COCOS_ENGINE_PATH = COCOS_ENGINE_PATH.replace("\\", "/") +buildDir = "${RES_PATH}/proj/build/$project.name" + +android { + compileSdkVersion PROP_COMPILE_SDK_VERSION.toInteger() + buildToolsVersion PROP_BUILD_TOOLS_VERSION + ndkPath PROP_NDK_PATH + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + defaultConfig { + applicationId "com.cocos.helloworld" + minSdkVersion PROP_MIN_SDK_VERSION + targetSdkVersion PROP_TARGET_SDK_VERSION + versionCode 1 + versionName "1.0" + + externalNativeBuild { + cmake { + targets "cocos" + arguments "-DRES_DIR=${RES_PATH}", "-DCOCOS_X_PATH=${COCOS_ENGINE_PATH}","-DANDROID_STL=c++_static", "-DANDROID_TOOLCHAIN=clang", "-DANDROID_ARM_NEON=TRUE", "-DANDROID_LD=gold" + cppFlags "-frtti -fexceptions -fsigned-char -DANDROID_INSTANT=1" + } + ndk { abiFilters PROP_APP_ABI.split(':') } + } + } + + sourceSets.main { + java.srcDirs "../src", "src" + res.srcDirs "../res", 'res' + jniLibs.srcDirs "../libs", 'libs' + manifest.srcFile "AndroidManifest.xml" + assets.srcDir "${RES_PATH}/data" + } + + externalNativeBuild { + cmake { + path "../CMakeLists.txt" + buildStagingDirectory "${RES_PATH}/proj/build" + } + } + + signingConfigs { + + release { + if (project.hasProperty("RELEASE_STORE_FILE") && !RELEASE_STORE_FILE.isEmpty()) { + storeFile file(RELEASE_STORE_FILE) + storePassword RELEASE_STORE_PASSWORD + keyAlias RELEASE_KEY_ALIAS + keyPassword RELEASE_KEY_PASSWORD + } + } + } + + buildTypes { + release { + debuggable false + jniDebuggable false + renderscriptDebuggable false + minifyEnabled true + shrinkResources true + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + proguardFiles "${COCOS_ENGINE_PATH}/external/sources/xr/huaweivr/android/java/proguard-rules.pro" + if (project.hasProperty("RELEASE_STORE_FILE")) { + signingConfig signingConfigs.release + } + // resValue "string", "app_name", PROP_APP_NAME + } + + debug { + debuggable true + jniDebuggable true + renderscriptDebuggable true + // resValue "string", "app_name", "${PROP_APP_NAME}-dbg" + // applicationIdSuffix ".debug" + } + } +} + +dependencies { + implementation fileTree(dir: '../libs', include: ['*.jar','*.aar']) + implementation fileTree(dir: 'libs', include: ['*.jar','*.aar']) + implementation fileTree(dir: "${COCOS_ENGINE_PATH}/cocos/platform/android/java/libs", include: ['*.jar']) + implementation project(':libservice') + implementation project(':libcocos') +} diff --git a/templates/xr-huaweivr/template/instantapp/proguard-rules.pro b/templates/xr-huaweivr/template/instantapp/proguard-rules.pro new file mode 100644 index 0000000000..dbb43fbbf1 --- /dev/null +++ b/templates/xr-huaweivr/template/instantapp/proguard-rules.pro @@ -0,0 +1,42 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in E:\developSoftware\Android\SDK/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Proguard Cocos2d-x-lite for release +-keep public class com.cocos.** { *; } +-dontwarn com.cocos.** + +# Proguard Apache HTTP for release +-keep class org.apache.http.** { *; } +-dontwarn org.apache.http.** + +# Proguard okhttp for release +-keep class okhttp3.** { *; } +-dontwarn okhttp3.** + +-keep class okio.** { *; } +-dontwarn okio.** + +# Proguard Android Webivew for release. you can comment if you are not using a webview +-keep public class android.net.http.SslError +-keep public class android.webkit.WebViewClient + +-keep public class com.google.** { *; } + +-dontwarn android.webkit.WebView +-dontwarn android.net.http.SslError +-dontwarn android.webkit.WebViewClient diff --git a/templates/xr-huaweivr/template/instantapp/src/com/cocos/game/InstantActivity.java b/templates/xr-huaweivr/template/instantapp/src/com/cocos/game/InstantActivity.java new file mode 100644 index 0000000000..9655ead6f4 --- /dev/null +++ b/templates/xr-huaweivr/template/instantapp/src/com/cocos/game/InstantActivity.java @@ -0,0 +1,125 @@ +/**************************************************************************** +Copyright (c) 2015-2016 Chukong Technologies Inc. +Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ +package com.cocos.game; + +import android.os.Bundle; +import android.content.Intent; +import android.content.res.Configuration; + +import com.cocos.service.SDKWrapper; +import com.cocos.lib.CocosActivity; + +public class InstantActivity extends CocosActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + // DO OTHER INITIALIZATION BELOW + SDKWrapper.shared().init(this); + + } + + @Override + protected void onResume() { + super.onResume(); + SDKWrapper.shared().onResume(); + } + + @Override + protected void onPause() { + super.onPause(); + SDKWrapper.shared().onPause(); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + // Workaround in https://stackoverflow.com/questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508 + if (!isTaskRoot()) { + return; + } + SDKWrapper.shared().onDestroy(); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + SDKWrapper.shared().onActivityResult(requestCode, resultCode, data); + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + SDKWrapper.shared().onNewIntent(intent); + } + + @Override + protected void onRestart() { + super.onRestart(); + SDKWrapper.shared().onRestart(); + } + + @Override + protected void onStop() { + super.onStop(); + SDKWrapper.shared().onStop(); + } + + @Override + public void onBackPressed() { + SDKWrapper.shared().onBackPressed(); + super.onBackPressed(); + } + + @Override + public void onConfigurationChanged(Configuration newConfig) { + SDKWrapper.shared().onConfigurationChanged(newConfig); + super.onConfigurationChanged(newConfig); + } + + @Override + protected void onRestoreInstanceState(Bundle savedInstanceState) { + SDKWrapper.shared().onRestoreInstanceState(savedInstanceState); + super.onRestoreInstanceState(savedInstanceState); + } + + @Override + protected void onSaveInstanceState(Bundle outState) { + SDKWrapper.shared().onSaveInstanceState(outState); + super.onSaveInstanceState(outState); + } + + @Override + protected void onStart() { + SDKWrapper.shared().onStart(); + super.onStart(); + } + + @Override + public void onLowMemory() { + SDKWrapper.shared().onLowMemory(); + super.onLowMemory(); + } +} diff --git a/templates/xr-huaweivr/template/res/mipmap-hdpi/ic_launcher.png b/templates/xr-huaweivr/template/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000000..888c0d56ab Binary files /dev/null and b/templates/xr-huaweivr/template/res/mipmap-hdpi/ic_launcher.png differ diff --git a/templates/xr-huaweivr/template/res/mipmap-mdpi/ic_launcher.png b/templates/xr-huaweivr/template/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000000..d5e3c770af Binary files /dev/null and b/templates/xr-huaweivr/template/res/mipmap-mdpi/ic_launcher.png differ diff --git a/templates/xr-huaweivr/template/res/mipmap-xhdpi/ic_launcher.png b/templates/xr-huaweivr/template/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000000..2b6f32ae03 Binary files /dev/null and b/templates/xr-huaweivr/template/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/templates/xr-huaweivr/template/res/mipmap-xxhdpi/ic_launcher.png b/templates/xr-huaweivr/template/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000000..2f1e5a6b37 Binary files /dev/null and b/templates/xr-huaweivr/template/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/templates/xr-huaweivr/template/res/mipmap-xxxhdpi/ic_launcher.png b/templates/xr-huaweivr/template/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000000..a9ebc7956e Binary files /dev/null and b/templates/xr-huaweivr/template/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/templates/xr-huaweivr/template/res/values/strings.xml b/templates/xr-huaweivr/template/res/values/strings.xml new file mode 100644 index 0000000000..1043872e78 --- /dev/null +++ b/templates/xr-huaweivr/template/res/values/strings.xml @@ -0,0 +1,3 @@ + + CocosGame + diff --git a/templates/xr-meta/build/build.gradle b/templates/xr-meta/build/build.gradle new file mode 100644 index 0000000000..d748464112 --- /dev/null +++ b/templates/xr-meta/build/build.gradle @@ -0,0 +1,18 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + + repositories { + google() + mavenCentral() + // jcenter() // keeped as anchor, will be removed soon + } + dependencies { + classpath 'com.android.tools.build:gradle:4.1.0' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +apply from: NATIVE_DIR +"/build.gradle" diff --git a/templates/xr-meta/build/gradle.properties b/templates/xr-meta/build/gradle.properties new file mode 100644 index 0000000000..6a701a83ce --- /dev/null +++ b/templates/xr-meta/build/gradle.properties @@ -0,0 +1,66 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +# Default value: -Xmx10248m -XX:MaxPermSize=256m +# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true +org.gradle.jvmargs=-Xmx4608m +android.useAndroidX=true + +android.injected.testOnly=false + +# Android SDK version that will be used as the compile project +PROP_COMPILE_SDK_VERSION=28 + +# Android SDK version that will be used as the earliest version of android this application can run on +PROP_MIN_SDK_VERSION=21 + +# Android SDK version that will be used as the latest version of android this application has been tested on +PROP_TARGET_SDK_VERSION=27 + +# Android Build Tools version that will be used as the compile project +PROP_BUILD_TOOLS_VERSION=28.0.0 + +# Android Application Name +PROP_APP_NAME=Cocos Game + +# Instant App +PROP_ENABLE_INSTANT_APP=true + +PROP_NDK_PATH= + +# Cocos Engine Path +COCOS_ENGINE_PATH= + +# Res path +RES_PATH= + +# Native source dir +NATIVE_DIR= + +# Application ID +APPLICATION_ID= + +# List of CPU Archtexture to build that application with +# Available architextures (armeabi-v7a | arm64-v8a | x86 | x86_64) +# To build for multiple architexture, use the `:` between them +# Example - PROP_APP_ABI=armeabi-v7a:arm64-v8a:x86 +PROP_APP_ABI=arm64-v8a + +# fill in sign information for release mode +# RELEASE_STORE_FILE= +# RELEASE_STORE_PASSWORD= +# RELEASE_KEY_ALIAS= +# RELEASE_KEY_PASSWORD= diff --git a/templates/xr-meta/build/gradle/wrapper/gradle-wrapper.jar b/templates/xr-meta/build/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..8c0fb64a86 Binary files /dev/null and b/templates/xr-meta/build/gradle/wrapper/gradle-wrapper.jar differ diff --git a/templates/xr-meta/build/gradle/wrapper/gradle-wrapper.properties b/templates/xr-meta/build/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..69d02eef07 --- /dev/null +++ b/templates/xr-meta/build/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Fri Oct 27 10:18:28 CST 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.5.1-all.zip diff --git a/templates/xr-meta/build/gradlew b/templates/xr-meta/build/gradlew new file mode 100644 index 0000000000..91a7e269e1 --- /dev/null +++ b/templates/xr-meta/build/gradlew @@ -0,0 +1,164 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# For Cygwin, ensure paths are in UNIX format before anything is touched. +if $cygwin ; then + [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` +fi + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >&- +APP_HOME="`pwd -P`" +cd "$SAVED" >&- + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/templates/xr-meta/build/gradlew.bat b/templates/xr-meta/build/gradlew.bat new file mode 100644 index 0000000000..8a0b282aa6 --- /dev/null +++ b/templates/xr-meta/build/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/templates/xr-meta/build/libservice/AndroidManifest.xml b/templates/xr-meta/build/libservice/AndroidManifest.xml new file mode 100644 index 0000000000..89f191e0e4 --- /dev/null +++ b/templates/xr-meta/build/libservice/AndroidManifest.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + diff --git a/templates/xr-meta/build/libservice/build.gradle b/templates/xr-meta/build/libservice/build.gradle new file mode 100644 index 0000000000..1cb73a2af2 --- /dev/null +++ b/templates/xr-meta/build/libservice/build.gradle @@ -0,0 +1,35 @@ +apply plugin: 'com.android.library' + +android { + compileSdkVersion PROP_COMPILE_SDK_VERSION.toInteger() + + defaultConfig { + minSdkVersion PROP_MIN_SDK_VERSION + targetSdkVersion PROP_TARGET_SDK_VERSION + versionCode 1 + versionName "1.0" + } + + sourceSets.main { + java.srcDirs "src" + res.srcDirs 'res' + jniLibs.srcDirs 'libs' + manifest.srcFile "AndroidManifest.xml" + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar','*.aar']) + implementation project(':libcocos') +} diff --git a/templates/xr-meta/build/libservice/proguard-rules.pro b/templates/xr-meta/build/libservice/proguard-rules.pro new file mode 100644 index 0000000000..f1b424510d --- /dev/null +++ b/templates/xr-meta/build/libservice/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/templates/xr-meta/build/libservice/src/com/cocos/service/SDKWrapper.java b/templates/xr-meta/build/libservice/src/com/cocos/service/SDKWrapper.java new file mode 100644 index 0000000000..e7ab46f77d --- /dev/null +++ b/templates/xr-meta/build/libservice/src/com/cocos/service/SDKWrapper.java @@ -0,0 +1,185 @@ +/**************************************************************************** + Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. + http://www.cocos.com + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +package com.cocos.service; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.content.res.AssetManager; +import android.content.res.Configuration; +import android.os.Bundle; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.List; + +public final class SDKWrapper { + private SDKWrapper() {} + private static class SDKWrapperInstance { + private static final SDKWrapper mInstance = new SDKWrapper(); + } + public static SDKWrapper shared() { return SDKWrapperInstance.mInstance; } + + @SuppressWarnings("unused") + public interface SDKInterface { + default void init(Context context) {} + default void onStart() {} + default void onPause() {} + default void onResume() {} + default void onStop() {} + default void onDestroy() {} + default void onRestart() {} + default void onNewIntent(Intent intent) {} + default void onActivityResult(int requestCode, int resultCode, Intent data) {} + default void onConfigurationChanged(Configuration newConfig) {} + default void onRestoreInstanceState(Bundle savedInstanceState) {} + default void onSaveInstanceState(Bundle outState) {} + default void onBackPressed() {} + default void onLowMemory() {} + } + + private WeakReference mActivity = null; + private List serviceInstances; + + private void loadSDKInterface() { + ArrayList instances = new ArrayList<>(); + try { + String json = this.getJson("service.json"); + JSONObject jsonObject = new JSONObject(json); + JSONArray serviceClasses = jsonObject.getJSONArray("serviceClasses"); + if (serviceClasses == null) return; + int length = serviceClasses.length(); + for (int i = 0; i < length; i++) { + instances.add((SDKInterface) Class.forName(serviceClasses.getString(i)).newInstance()); + } + } catch (Exception ignored) { } + this.serviceInstances = instances; + } + + @SuppressWarnings("SameParameterValue") + private String getJson(String fileName) { + StringBuilder sb = new StringBuilder(); + try { + AssetManager am = this.mActivity.get().getAssets(); + BufferedReader br = new BufferedReader(new InputStreamReader(am.open(fileName))); + String next; + while (null != (next = br.readLine())) { sb.append(next); } + } catch (IOException e) { + sb.delete(0, sb.length()); + } + return sb.toString().trim(); + } + + public Activity getActivity() { return this.mActivity.get(); } + + public void init(Activity activity) { + this.mActivity = new WeakReference<>(activity); + this.loadSDKInterface(); + for (SDKInterface sdk : this.serviceInstances) { + sdk.init(activity); + } + } + + public void onResume() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onResume(); + } + } + + public void onPause() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onPause(); + } + } + + public void onDestroy() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onDestroy(); + } + } + + public void onActivityResult(int requestCode, int resultCode, Intent data) { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onActivityResult(requestCode, resultCode, data); + } + } + + public void onNewIntent(Intent intent) { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onNewIntent(intent); + } + } + + public void onRestart() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onRestart(); + } + } + + public void onStop() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onStop(); + } + } + + public void onBackPressed() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onBackPressed(); + } + } + + public void onConfigurationChanged(Configuration newConfig) { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onConfigurationChanged(newConfig); + } + } + + public void onRestoreInstanceState(Bundle savedInstanceState) { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onRestoreInstanceState(savedInstanceState); + } + } + + public void onSaveInstanceState(Bundle outState) { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onSaveInstanceState(outState); + } + } + + public void onStart() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onStart(); + } + } + + public void onLowMemory() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onLowMemory(); + } + } +} \ No newline at end of file diff --git a/templates/xr-meta/build/settings.gradle b/templates/xr-meta/build/settings.gradle new file mode 100644 index 0000000000..80cad73242 --- /dev/null +++ b/templates/xr-meta/build/settings.gradle @@ -0,0 +1,9 @@ +include ':libcocos',':libservice',':CocosGame' +project(':libcocos').projectDir = new File(COCOS_ENGINE_PATH,'cocos/platform/android/libcocos2dx') +project(':CocosGame').projectDir = new File(NATIVE_DIR, 'app') +if(PROP_ENABLE_INSTANT_APP == "true" || PROP_ENABLE_INSTANT_APP == "yes") { + include ':instantapp' + project(':instantapp').projectDir = new File(NATIVE_DIR, 'instantapp') +} + +rootProject.name = "CocosGame" diff --git a/templates/xr-meta/template/.gitignore b/templates/xr-meta/template/.gitignore new file mode 100644 index 0000000000..9c4de5825b --- /dev/null +++ b/templates/xr-meta/template/.gitignore @@ -0,0 +1,7 @@ +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build +/captures diff --git a/templates/xr-meta/template/CMakeLists.txt b/templates/xr-meta/template/CMakeLists.txt new file mode 100644 index 0000000000..b6f90857a9 --- /dev/null +++ b/templates/xr-meta/template/CMakeLists.txt @@ -0,0 +1,15 @@ +cmake_minimum_required(VERSION 3.8) + +option(APP_NAME "Project Name" "CocosGame") +project(${APP_NAME} CXX) +set(CC_LIB_NAME cocos) +set(CC_PROJECT_DIR ${CMAKE_CURRENT_LIST_DIR}) +set(CC_PROJ_SOURCES) +set(CC_COMMON_SOURCES) +set(CC_ALL_SOURCES) + +include(${CMAKE_CURRENT_LIST_DIR}/../common/CMakeLists.txt) + +cc_android_before_target(${CC_LIB_NAME}) +add_library(${CC_LIB_NAME} SHARED ${CC_ALL_SOURCES}) +cc_android_after_target(${CC_LIB_NAME}) diff --git a/templates/xr-meta/template/app/.gitignore b/templates/xr-meta/template/app/.gitignore new file mode 100644 index 0000000000..1de99493d6 --- /dev/null +++ b/templates/xr-meta/template/app/.gitignore @@ -0,0 +1,2 @@ +/build +/jniLibs diff --git a/templates/xr-meta/template/app/AndroidManifest.xml b/templates/xr-meta/template/app/AndroidManifest.xml new file mode 100644 index 0000000000..88646e758b --- /dev/null +++ b/templates/xr-meta/template/app/AndroidManifest.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + diff --git a/templates/xr-meta/template/app/build.gradle b/templates/xr-meta/template/app/build.gradle new file mode 100644 index 0000000000..0917da1268 --- /dev/null +++ b/templates/xr-meta/template/app/build.gradle @@ -0,0 +1,96 @@ +import org.apache.tools.ant.taskdefs.condition.Os + +apply plugin: 'com.android.application' + +RES_PATH = RES_PATH.replace("\\", "/") +COCOS_ENGINE_PATH = COCOS_ENGINE_PATH.replace("\\", "/") + +buildDir = "${RES_PATH}/proj/build/$project.name" +android { + compileSdkVersion PROP_COMPILE_SDK_VERSION.toInteger() + buildToolsVersion PROP_BUILD_TOOLS_VERSION + ndkPath PROP_NDK_PATH + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + defaultConfig { + applicationId APPLICATION_ID + minSdkVersion PROP_MIN_SDK_VERSION + targetSdkVersion PROP_TARGET_SDK_VERSION + versionCode 1 + versionName "1.0" + + externalNativeBuild { + cmake { + targets "cocos" + arguments "-DRES_DIR=${RES_PATH}", "-DCOCOS_X_PATH=${COCOS_ENGINE_PATH}", "-DANDROID_STL=c++_static", "-DANDROID_TOOLCHAIN=clang", "-DANDROID_ARM_NEON=TRUE", "-DANDROID_LD=gold" + } + ndk { abiFilters PROP_APP_ABI.split(':') } + } + } + + sourceSets.main { + java.srcDirs "../src", "src" + res.srcDirs "../res", 'res' + jniLibs.srcDirs "../libs", 'libs' + manifest.srcFile "AndroidManifest.xml" + assets.srcDir "${RES_PATH}/data" + jniLibs { + // Vulkan validation layer + // srcDir "${android.ndkDirectory}/sources/third_party/vulkan/src/build-android/jniLibs" + } + } + + externalNativeBuild { + cmake { + path "../CMakeLists.txt" + buildStagingDirectory "${RES_PATH}/proj/build" + } + } + + signingConfigs { + + release { + if (project.hasProperty("RELEASE_STORE_FILE") && !RELEASE_STORE_FILE.isEmpty()) { + storeFile file(RELEASE_STORE_FILE) + storePassword RELEASE_STORE_PASSWORD + keyAlias RELEASE_KEY_ALIAS + keyPassword RELEASE_KEY_PASSWORD + } + } + } + + buildTypes { + release { + debuggable false + jniDebuggable false + renderscriptDebuggable false + minifyEnabled true + shrinkResources true + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + if (project.hasProperty("RELEASE_STORE_FILE")) { + signingConfig signingConfigs.release + } + // resValue "string", "app_name", PROP_APP_NAME + } + + debug { + debuggable true + jniDebuggable true + renderscriptDebuggable true + // resValue "string", "app_name", "${PROP_APP_NAME}-dbg" + // applicationIdSuffix ".debug" + } + } +} + +dependencies { + implementation fileTree(dir: '../libs', include: ['*.jar','*.aar']) + implementation fileTree(dir: 'libs', include: ['*.jar','*.aar']) + implementation fileTree(dir: "${COCOS_ENGINE_PATH}/cocos/platform/android/java/libs", include: ['*.jar']) + implementation project(':libservice') + implementation project(':libcocos') +} diff --git a/templates/xr-meta/template/app/proguard-rules.pro b/templates/xr-meta/template/app/proguard-rules.pro new file mode 100644 index 0000000000..dbb43fbbf1 --- /dev/null +++ b/templates/xr-meta/template/app/proguard-rules.pro @@ -0,0 +1,42 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in E:\developSoftware\Android\SDK/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Proguard Cocos2d-x-lite for release +-keep public class com.cocos.** { *; } +-dontwarn com.cocos.** + +# Proguard Apache HTTP for release +-keep class org.apache.http.** { *; } +-dontwarn org.apache.http.** + +# Proguard okhttp for release +-keep class okhttp3.** { *; } +-dontwarn okhttp3.** + +-keep class okio.** { *; } +-dontwarn okio.** + +# Proguard Android Webivew for release. you can comment if you are not using a webview +-keep public class android.net.http.SslError +-keep public class android.webkit.WebViewClient + +-keep public class com.google.** { *; } + +-dontwarn android.webkit.WebView +-dontwarn android.net.http.SslError +-dontwarn android.webkit.WebViewClient diff --git a/templates/xr-meta/template/app/src/com/cocos/game/AppActivity.java b/templates/xr-meta/template/app/src/com/cocos/game/AppActivity.java new file mode 100644 index 0000000000..bca3590fdc --- /dev/null +++ b/templates/xr-meta/template/app/src/com/cocos/game/AppActivity.java @@ -0,0 +1,126 @@ +/**************************************************************************** +Copyright (c) 2015-2016 Chukong Technologies Inc. +Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ +package com.cocos.game; + +import android.os.Bundle; +import android.content.Intent; +import android.content.res.Configuration; + +import com.cocos.service.SDKWrapper; +import com.cocos.lib.CocosActivity; + +public class AppActivity extends CocosActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + // DO OTHER INITIALIZATION BELOW + SDKWrapper.shared().init(this); + + } + + @Override + protected void onResume() { + super.onResume(); + SDKWrapper.shared().onResume(); + } + + @Override + protected void onPause() { + super.onPause(); + SDKWrapper.shared().onPause(); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + // Workaround in https://stackoverflow.com/questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508 + if (!isTaskRoot()) { + return; + } + SDKWrapper.shared().onDestroy(); + System.exit(0); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + SDKWrapper.shared().onActivityResult(requestCode, resultCode, data); + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + SDKWrapper.shared().onNewIntent(intent); + } + + @Override + protected void onRestart() { + super.onRestart(); + SDKWrapper.shared().onRestart(); + } + + @Override + protected void onStop() { + super.onStop(); + SDKWrapper.shared().onStop(); + } + + @Override + public void onBackPressed() { + SDKWrapper.shared().onBackPressed(); + super.onBackPressed(); + } + + @Override + public void onConfigurationChanged(Configuration newConfig) { + SDKWrapper.shared().onConfigurationChanged(newConfig); + super.onConfigurationChanged(newConfig); + } + + @Override + protected void onRestoreInstanceState(Bundle savedInstanceState) { + SDKWrapper.shared().onRestoreInstanceState(savedInstanceState); + super.onRestoreInstanceState(savedInstanceState); + } + + @Override + protected void onSaveInstanceState(Bundle outState) { + SDKWrapper.shared().onSaveInstanceState(outState); + super.onSaveInstanceState(outState); + } + + @Override + protected void onStart() { + SDKWrapper.shared().onStart(); + super.onStart(); + } + + @Override + public void onLowMemory() { + SDKWrapper.shared().onLowMemory(); + super.onLowMemory(); + } +} diff --git a/templates/xr-meta/template/build-cfg.json b/templates/xr-meta/template/build-cfg.json new file mode 100644 index 0000000000..fb658e2985 --- /dev/null +++ b/templates/xr-meta/template/build-cfg.json @@ -0,0 +1,8 @@ +{ + "ndk_module_path" :[ + "${COCOS_ROOT}", + "${COCOS_ROOT}/cocos", + "${COCOS_ROOT}/external" + ], + "copy_resources": [] +} diff --git a/templates/xr-meta/template/build.gradle b/templates/xr-meta/template/build.gradle new file mode 100644 index 0000000000..2ae589d169 --- /dev/null +++ b/templates/xr-meta/template/build.gradle @@ -0,0 +1,31 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + + repositories { + google() + mavenCentral() + // jcenter() // keeped as anchor, will be removed soon + } + dependencies { + classpath 'com.android.tools.build:gradle:4.1.0' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + google() + mavenCentral() + // jcenter() // keeped as anchor, will be removed soon + flatDir { + dirs 'libs' + } + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/templates/xr-meta/template/instantapp/AndroidManifest.xml b/templates/xr-meta/template/instantapp/AndroidManifest.xml new file mode 100644 index 0000000000..d4578bd08f --- /dev/null +++ b/templates/xr-meta/template/instantapp/AndroidManifest.xml @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/templates/xr-meta/template/instantapp/build.gradle b/templates/xr-meta/template/instantapp/build.gradle new file mode 100644 index 0000000000..72ba70e637 --- /dev/null +++ b/templates/xr-meta/template/instantapp/build.gradle @@ -0,0 +1,93 @@ +import org.apache.tools.ant.taskdefs.condition.Os + +apply plugin: 'com.android.application' + +RES_PATH = RES_PATH.replace("\\", "/") +COCOS_ENGINE_PATH = COCOS_ENGINE_PATH.replace("\\", "/") +buildDir = "${RES_PATH}/proj/build/$project.name" + +android { + compileSdkVersion PROP_COMPILE_SDK_VERSION.toInteger() + buildToolsVersion PROP_BUILD_TOOLS_VERSION + ndkPath PROP_NDK_PATH + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + defaultConfig { + applicationId "com.cocos.helloworld" + minSdkVersion PROP_MIN_SDK_VERSION + targetSdkVersion PROP_TARGET_SDK_VERSION + versionCode 1 + versionName "1.0" + + externalNativeBuild { + cmake { + targets "cocos" + arguments "-DRES_DIR=${RES_PATH}", "-DCOCOS_X_PATH=${COCOS_ENGINE_PATH}","-DANDROID_STL=c++_static", "-DANDROID_TOOLCHAIN=clang", "-DANDROID_ARM_NEON=TRUE", "-DANDROID_LD=gold" + cppFlags "-frtti -fexceptions -fsigned-char -DANDROID_INSTANT=1" + } + ndk { abiFilters PROP_APP_ABI.split(':') } + } + } + + sourceSets.main { + java.srcDirs "../src", "src" + res.srcDirs "../res", 'res' + jniLibs.srcDirs "../libs", 'libs' + manifest.srcFile "AndroidManifest.xml" + assets.srcDir "${RES_PATH}/data" + } + + externalNativeBuild { + cmake { + path "../CMakeLists.txt" + buildStagingDirectory "${RES_PATH}/proj/build" + } + } + + signingConfigs { + + release { + if (project.hasProperty("RELEASE_STORE_FILE") && !RELEASE_STORE_FILE.isEmpty()) { + storeFile file(RELEASE_STORE_FILE) + storePassword RELEASE_STORE_PASSWORD + keyAlias RELEASE_KEY_ALIAS + keyPassword RELEASE_KEY_PASSWORD + } + } + } + + buildTypes { + release { + debuggable false + jniDebuggable false + renderscriptDebuggable false + minifyEnabled true + shrinkResources true + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + if (project.hasProperty("RELEASE_STORE_FILE")) { + signingConfig signingConfigs.release + } + // resValue "string", "app_name", PROP_APP_NAME + } + + debug { + debuggable true + jniDebuggable true + renderscriptDebuggable true + // resValue "string", "app_name", "${PROP_APP_NAME}-dbg" + // applicationIdSuffix ".debug" + } + } +} + +dependencies { + implementation fileTree(dir: '../libs', include: ['*.jar','*.aar']) + implementation fileTree(dir: 'libs', include: ['*.jar','*.aar']) + implementation fileTree(dir: "${COCOS_ENGINE_PATH}/cocos/platform/android/java/libs", include: ['*.jar']) + implementation project(':libservice') + implementation project(':libcocos') +} diff --git a/templates/xr-meta/template/instantapp/proguard-rules.pro b/templates/xr-meta/template/instantapp/proguard-rules.pro new file mode 100644 index 0000000000..dbb43fbbf1 --- /dev/null +++ b/templates/xr-meta/template/instantapp/proguard-rules.pro @@ -0,0 +1,42 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in E:\developSoftware\Android\SDK/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Proguard Cocos2d-x-lite for release +-keep public class com.cocos.** { *; } +-dontwarn com.cocos.** + +# Proguard Apache HTTP for release +-keep class org.apache.http.** { *; } +-dontwarn org.apache.http.** + +# Proguard okhttp for release +-keep class okhttp3.** { *; } +-dontwarn okhttp3.** + +-keep class okio.** { *; } +-dontwarn okio.** + +# Proguard Android Webivew for release. you can comment if you are not using a webview +-keep public class android.net.http.SslError +-keep public class android.webkit.WebViewClient + +-keep public class com.google.** { *; } + +-dontwarn android.webkit.WebView +-dontwarn android.net.http.SslError +-dontwarn android.webkit.WebViewClient diff --git a/templates/xr-meta/template/instantapp/src/com/cocos/game/InstantActivity.java b/templates/xr-meta/template/instantapp/src/com/cocos/game/InstantActivity.java new file mode 100644 index 0000000000..318e8398d3 --- /dev/null +++ b/templates/xr-meta/template/instantapp/src/com/cocos/game/InstantActivity.java @@ -0,0 +1,125 @@ +/**************************************************************************** +Copyright (c) 2015-2016 Chukong Technologies Inc. +Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ +package com.cocos.game; + +import android.os.Bundle; +import android.content.Intent; +import android.content.res.Configuration; + +import com.cocos.service.SDKWrapper; +import com.cocos.lib.CocosActivity; + +public class InstantActivity extends CocosActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + // DO OTHER INITIALIZATION BELOW + SDKWrapper.shared().init(this); + + } + + @Override + protected void onResume() { + super.onResume(); + SDKWrapper.shared().onResume(); + } + + @Override + protected void onPause() { + super.onPause(); + SDKWrapper.shared().onPause(); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + // Workaround in https://stackoverflow.com/questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508 + if (!isTaskRoot()) { + return; + } + SDKWrapper.shared().onDestroy(); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + SDKWrapper.shared().onActivityResult(requestCode, resultCode, data); + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + SDKWrapper.shared().onNewIntent(intent); + } + + @Override + protected void onRestart() { + super.onRestart(); + SDKWrapper.shared().onRestart(); + } + + @Override + protected void onStop() { + super.onStop(); + SDKWrapper.shared().onStop(); + } + + @Override + public void onBackPressed() { + SDKWrapper.shared().onBackPressed(); + super.onBackPressed(); + } + + @Override + public void onConfigurationChanged(Configuration newConfig) { + SDKWrapper.shared().onConfigurationChanged(newConfig); + super.onConfigurationChanged(newConfig); + } + + @Override + protected void onRestoreInstanceState(Bundle savedInstanceState) { + SDKWrapper.shared().onRestoreInstanceState(savedInstanceState); + super.onRestoreInstanceState(savedInstanceState); + } + + @Override + protected void onSaveInstanceState(Bundle outState) { + SDKWrapper.shared().onSaveInstanceState(outState); + super.onSaveInstanceState(outState); + } + + @Override + protected void onStart() { + SDKWrapper.shared().onStart(); + super.onStart(); + } + + @Override + public void onLowMemory() { + SDKWrapper.shared().onLowMemory(); + super.onLowMemory(); + } +} diff --git a/templates/xr-meta/template/res/mipmap-hdpi/ic_launcher.png b/templates/xr-meta/template/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000000..888c0d56ab Binary files /dev/null and b/templates/xr-meta/template/res/mipmap-hdpi/ic_launcher.png differ diff --git a/templates/xr-meta/template/res/mipmap-mdpi/ic_launcher.png b/templates/xr-meta/template/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000000..d5e3c770af Binary files /dev/null and b/templates/xr-meta/template/res/mipmap-mdpi/ic_launcher.png differ diff --git a/templates/xr-meta/template/res/mipmap-xhdpi/ic_launcher.png b/templates/xr-meta/template/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000000..2b6f32ae03 Binary files /dev/null and b/templates/xr-meta/template/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/templates/xr-meta/template/res/mipmap-xxhdpi/ic_launcher.png b/templates/xr-meta/template/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000000..2f1e5a6b37 Binary files /dev/null and b/templates/xr-meta/template/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/templates/xr-meta/template/res/mipmap-xxxhdpi/ic_launcher.png b/templates/xr-meta/template/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000000..a9ebc7956e Binary files /dev/null and b/templates/xr-meta/template/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/templates/xr-meta/template/res/values/strings.xml b/templates/xr-meta/template/res/values/strings.xml new file mode 100644 index 0000000000..1043872e78 --- /dev/null +++ b/templates/xr-meta/template/res/values/strings.xml @@ -0,0 +1,3 @@ + + CocosGame + diff --git a/templates/xr-monado/build/build.gradle b/templates/xr-monado/build/build.gradle new file mode 100644 index 0000000000..d748464112 --- /dev/null +++ b/templates/xr-monado/build/build.gradle @@ -0,0 +1,18 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + + repositories { + google() + mavenCentral() + // jcenter() // keeped as anchor, will be removed soon + } + dependencies { + classpath 'com.android.tools.build:gradle:4.1.0' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +apply from: NATIVE_DIR +"/build.gradle" diff --git a/templates/xr-monado/build/gradle.properties b/templates/xr-monado/build/gradle.properties new file mode 100644 index 0000000000..6a701a83ce --- /dev/null +++ b/templates/xr-monado/build/gradle.properties @@ -0,0 +1,66 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +# Default value: -Xmx10248m -XX:MaxPermSize=256m +# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true +org.gradle.jvmargs=-Xmx4608m +android.useAndroidX=true + +android.injected.testOnly=false + +# Android SDK version that will be used as the compile project +PROP_COMPILE_SDK_VERSION=28 + +# Android SDK version that will be used as the earliest version of android this application can run on +PROP_MIN_SDK_VERSION=21 + +# Android SDK version that will be used as the latest version of android this application has been tested on +PROP_TARGET_SDK_VERSION=27 + +# Android Build Tools version that will be used as the compile project +PROP_BUILD_TOOLS_VERSION=28.0.0 + +# Android Application Name +PROP_APP_NAME=Cocos Game + +# Instant App +PROP_ENABLE_INSTANT_APP=true + +PROP_NDK_PATH= + +# Cocos Engine Path +COCOS_ENGINE_PATH= + +# Res path +RES_PATH= + +# Native source dir +NATIVE_DIR= + +# Application ID +APPLICATION_ID= + +# List of CPU Archtexture to build that application with +# Available architextures (armeabi-v7a | arm64-v8a | x86 | x86_64) +# To build for multiple architexture, use the `:` between them +# Example - PROP_APP_ABI=armeabi-v7a:arm64-v8a:x86 +PROP_APP_ABI=arm64-v8a + +# fill in sign information for release mode +# RELEASE_STORE_FILE= +# RELEASE_STORE_PASSWORD= +# RELEASE_KEY_ALIAS= +# RELEASE_KEY_PASSWORD= diff --git a/templates/xr-monado/build/gradle/wrapper/gradle-wrapper.jar b/templates/xr-monado/build/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..8c0fb64a86 Binary files /dev/null and b/templates/xr-monado/build/gradle/wrapper/gradle-wrapper.jar differ diff --git a/templates/xr-monado/build/gradle/wrapper/gradle-wrapper.properties b/templates/xr-monado/build/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..69d02eef07 --- /dev/null +++ b/templates/xr-monado/build/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Fri Oct 27 10:18:28 CST 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.5.1-all.zip diff --git a/templates/xr-monado/build/gradlew b/templates/xr-monado/build/gradlew new file mode 100644 index 0000000000..91a7e269e1 --- /dev/null +++ b/templates/xr-monado/build/gradlew @@ -0,0 +1,164 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# For Cygwin, ensure paths are in UNIX format before anything is touched. +if $cygwin ; then + [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` +fi + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >&- +APP_HOME="`pwd -P`" +cd "$SAVED" >&- + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/templates/xr-monado/build/gradlew.bat b/templates/xr-monado/build/gradlew.bat new file mode 100644 index 0000000000..8a0b282aa6 --- /dev/null +++ b/templates/xr-monado/build/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/templates/xr-monado/build/libservice/AndroidManifest.xml b/templates/xr-monado/build/libservice/AndroidManifest.xml new file mode 100644 index 0000000000..25d278d01c --- /dev/null +++ b/templates/xr-monado/build/libservice/AndroidManifest.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/templates/xr-monado/build/libservice/build.gradle b/templates/xr-monado/build/libservice/build.gradle new file mode 100644 index 0000000000..1cb73a2af2 --- /dev/null +++ b/templates/xr-monado/build/libservice/build.gradle @@ -0,0 +1,35 @@ +apply plugin: 'com.android.library' + +android { + compileSdkVersion PROP_COMPILE_SDK_VERSION.toInteger() + + defaultConfig { + minSdkVersion PROP_MIN_SDK_VERSION + targetSdkVersion PROP_TARGET_SDK_VERSION + versionCode 1 + versionName "1.0" + } + + sourceSets.main { + java.srcDirs "src" + res.srcDirs 'res' + jniLibs.srcDirs 'libs' + manifest.srcFile "AndroidManifest.xml" + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar','*.aar']) + implementation project(':libcocos') +} diff --git a/templates/xr-monado/build/libservice/proguard-rules.pro b/templates/xr-monado/build/libservice/proguard-rules.pro new file mode 100644 index 0000000000..f1b424510d --- /dev/null +++ b/templates/xr-monado/build/libservice/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/templates/xr-monado/build/libservice/src/com/cocos/service/SDKWrapper.java b/templates/xr-monado/build/libservice/src/com/cocos/service/SDKWrapper.java new file mode 100644 index 0000000000..e7ab46f77d --- /dev/null +++ b/templates/xr-monado/build/libservice/src/com/cocos/service/SDKWrapper.java @@ -0,0 +1,185 @@ +/**************************************************************************** + Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. + http://www.cocos.com + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +package com.cocos.service; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.content.res.AssetManager; +import android.content.res.Configuration; +import android.os.Bundle; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.List; + +public final class SDKWrapper { + private SDKWrapper() {} + private static class SDKWrapperInstance { + private static final SDKWrapper mInstance = new SDKWrapper(); + } + public static SDKWrapper shared() { return SDKWrapperInstance.mInstance; } + + @SuppressWarnings("unused") + public interface SDKInterface { + default void init(Context context) {} + default void onStart() {} + default void onPause() {} + default void onResume() {} + default void onStop() {} + default void onDestroy() {} + default void onRestart() {} + default void onNewIntent(Intent intent) {} + default void onActivityResult(int requestCode, int resultCode, Intent data) {} + default void onConfigurationChanged(Configuration newConfig) {} + default void onRestoreInstanceState(Bundle savedInstanceState) {} + default void onSaveInstanceState(Bundle outState) {} + default void onBackPressed() {} + default void onLowMemory() {} + } + + private WeakReference mActivity = null; + private List serviceInstances; + + private void loadSDKInterface() { + ArrayList instances = new ArrayList<>(); + try { + String json = this.getJson("service.json"); + JSONObject jsonObject = new JSONObject(json); + JSONArray serviceClasses = jsonObject.getJSONArray("serviceClasses"); + if (serviceClasses == null) return; + int length = serviceClasses.length(); + for (int i = 0; i < length; i++) { + instances.add((SDKInterface) Class.forName(serviceClasses.getString(i)).newInstance()); + } + } catch (Exception ignored) { } + this.serviceInstances = instances; + } + + @SuppressWarnings("SameParameterValue") + private String getJson(String fileName) { + StringBuilder sb = new StringBuilder(); + try { + AssetManager am = this.mActivity.get().getAssets(); + BufferedReader br = new BufferedReader(new InputStreamReader(am.open(fileName))); + String next; + while (null != (next = br.readLine())) { sb.append(next); } + } catch (IOException e) { + sb.delete(0, sb.length()); + } + return sb.toString().trim(); + } + + public Activity getActivity() { return this.mActivity.get(); } + + public void init(Activity activity) { + this.mActivity = new WeakReference<>(activity); + this.loadSDKInterface(); + for (SDKInterface sdk : this.serviceInstances) { + sdk.init(activity); + } + } + + public void onResume() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onResume(); + } + } + + public void onPause() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onPause(); + } + } + + public void onDestroy() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onDestroy(); + } + } + + public void onActivityResult(int requestCode, int resultCode, Intent data) { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onActivityResult(requestCode, resultCode, data); + } + } + + public void onNewIntent(Intent intent) { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onNewIntent(intent); + } + } + + public void onRestart() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onRestart(); + } + } + + public void onStop() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onStop(); + } + } + + public void onBackPressed() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onBackPressed(); + } + } + + public void onConfigurationChanged(Configuration newConfig) { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onConfigurationChanged(newConfig); + } + } + + public void onRestoreInstanceState(Bundle savedInstanceState) { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onRestoreInstanceState(savedInstanceState); + } + } + + public void onSaveInstanceState(Bundle outState) { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onSaveInstanceState(outState); + } + } + + public void onStart() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onStart(); + } + } + + public void onLowMemory() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onLowMemory(); + } + } +} \ No newline at end of file diff --git a/templates/xr-monado/build/settings.gradle b/templates/xr-monado/build/settings.gradle new file mode 100644 index 0000000000..80cad73242 --- /dev/null +++ b/templates/xr-monado/build/settings.gradle @@ -0,0 +1,9 @@ +include ':libcocos',':libservice',':CocosGame' +project(':libcocos').projectDir = new File(COCOS_ENGINE_PATH,'cocos/platform/android/libcocos2dx') +project(':CocosGame').projectDir = new File(NATIVE_DIR, 'app') +if(PROP_ENABLE_INSTANT_APP == "true" || PROP_ENABLE_INSTANT_APP == "yes") { + include ':instantapp' + project(':instantapp').projectDir = new File(NATIVE_DIR, 'instantapp') +} + +rootProject.name = "CocosGame" diff --git a/templates/xr-monado/template/.gitignore b/templates/xr-monado/template/.gitignore new file mode 100644 index 0000000000..9c4de5825b --- /dev/null +++ b/templates/xr-monado/template/.gitignore @@ -0,0 +1,7 @@ +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build +/captures diff --git a/templates/xr-monado/template/CMakeLists.txt b/templates/xr-monado/template/CMakeLists.txt new file mode 100644 index 0000000000..b6f90857a9 --- /dev/null +++ b/templates/xr-monado/template/CMakeLists.txt @@ -0,0 +1,15 @@ +cmake_minimum_required(VERSION 3.8) + +option(APP_NAME "Project Name" "CocosGame") +project(${APP_NAME} CXX) +set(CC_LIB_NAME cocos) +set(CC_PROJECT_DIR ${CMAKE_CURRENT_LIST_DIR}) +set(CC_PROJ_SOURCES) +set(CC_COMMON_SOURCES) +set(CC_ALL_SOURCES) + +include(${CMAKE_CURRENT_LIST_DIR}/../common/CMakeLists.txt) + +cc_android_before_target(${CC_LIB_NAME}) +add_library(${CC_LIB_NAME} SHARED ${CC_ALL_SOURCES}) +cc_android_after_target(${CC_LIB_NAME}) diff --git a/templates/xr-monado/template/app/.gitignore b/templates/xr-monado/template/app/.gitignore new file mode 100644 index 0000000000..1de99493d6 --- /dev/null +++ b/templates/xr-monado/template/app/.gitignore @@ -0,0 +1,2 @@ +/build +/jniLibs diff --git a/templates/xr-monado/template/app/AndroidManifest.xml b/templates/xr-monado/template/app/AndroidManifest.xml new file mode 100644 index 0000000000..88646e758b --- /dev/null +++ b/templates/xr-monado/template/app/AndroidManifest.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + diff --git a/templates/xr-monado/template/app/build.gradle b/templates/xr-monado/template/app/build.gradle new file mode 100644 index 0000000000..8ee469fa3b --- /dev/null +++ b/templates/xr-monado/template/app/build.gradle @@ -0,0 +1,96 @@ +import org.apache.tools.ant.taskdefs.condition.Os + +apply plugin: 'com.android.application' + +RES_PATH = RES_PATH.replace("\\", "/") +COCOS_ENGINE_PATH = COCOS_ENGINE_PATH.replace("\\", "/") + +buildDir = "${RES_PATH}/proj/build/$project.name" +android { + compileSdkVersion PROP_COMPILE_SDK_VERSION.toInteger() + buildToolsVersion PROP_BUILD_TOOLS_VERSION + ndkPath PROP_NDK_PATH + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + defaultConfig { + applicationId APPLICATION_ID + minSdkVersion PROP_MIN_SDK_VERSION + targetSdkVersion PROP_TARGET_SDK_VERSION + versionCode 1 + versionName "1.0" + + externalNativeBuild { + cmake { + targets "cocos" + arguments "-DRES_DIR=${RES_PATH}", "-DCOCOS_X_PATH=${COCOS_ENGINE_PATH}", "-DANDROID_STL=c++_shared", "-DANDROID_TOOLCHAIN=clang", "-DANDROID_ARM_NEON=TRUE", "-DANDROID_LD=gold" + } + ndk { abiFilters PROP_APP_ABI.split(':') } + } + } + + sourceSets.main { + java.srcDirs "../src", "src" + res.srcDirs "../res", 'res' + jniLibs.srcDirs "../libs", 'libs' + manifest.srcFile "AndroidManifest.xml" + assets.srcDir "${RES_PATH}/data" + jniLibs { + // Vulkan validation layer + // srcDir "${android.ndkDirectory}/sources/third_party/vulkan/src/build-android/jniLibs" + } + } + + externalNativeBuild { + cmake { + path "../CMakeLists.txt" + buildStagingDirectory "${RES_PATH}/proj/build" + } + } + + signingConfigs { + + release { + if (project.hasProperty("RELEASE_STORE_FILE") && !RELEASE_STORE_FILE.isEmpty()) { + storeFile file(RELEASE_STORE_FILE) + storePassword RELEASE_STORE_PASSWORD + keyAlias RELEASE_KEY_ALIAS + keyPassword RELEASE_KEY_PASSWORD + } + } + } + + buildTypes { + release { + debuggable false + jniDebuggable false + renderscriptDebuggable false + minifyEnabled true + shrinkResources true + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + if (project.hasProperty("RELEASE_STORE_FILE")) { + signingConfig signingConfigs.release + } + // resValue "string", "app_name", PROP_APP_NAME + } + + debug { + debuggable true + jniDebuggable true + renderscriptDebuggable true + // resValue "string", "app_name", "${PROP_APP_NAME}-dbg" + // applicationIdSuffix ".debug" + } + } +} + +dependencies { + implementation fileTree(dir: '../libs', include: ['*.jar','*.aar']) + implementation fileTree(dir: 'libs', include: ['*.jar','*.aar']) + implementation fileTree(dir: "${COCOS_ENGINE_PATH}/cocos/platform/android/java/libs", include: ['*.jar']) + implementation project(':libservice') + implementation project(':libcocos') +} diff --git a/templates/xr-monado/template/app/proguard-rules.pro b/templates/xr-monado/template/app/proguard-rules.pro new file mode 100644 index 0000000000..dbb43fbbf1 --- /dev/null +++ b/templates/xr-monado/template/app/proguard-rules.pro @@ -0,0 +1,42 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in E:\developSoftware\Android\SDK/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Proguard Cocos2d-x-lite for release +-keep public class com.cocos.** { *; } +-dontwarn com.cocos.** + +# Proguard Apache HTTP for release +-keep class org.apache.http.** { *; } +-dontwarn org.apache.http.** + +# Proguard okhttp for release +-keep class okhttp3.** { *; } +-dontwarn okhttp3.** + +-keep class okio.** { *; } +-dontwarn okio.** + +# Proguard Android Webivew for release. you can comment if you are not using a webview +-keep public class android.net.http.SslError +-keep public class android.webkit.WebViewClient + +-keep public class com.google.** { *; } + +-dontwarn android.webkit.WebView +-dontwarn android.net.http.SslError +-dontwarn android.webkit.WebViewClient diff --git a/templates/xr-monado/template/app/src/com/cocos/game/AppActivity.java b/templates/xr-monado/template/app/src/com/cocos/game/AppActivity.java new file mode 100644 index 0000000000..5aaece8851 --- /dev/null +++ b/templates/xr-monado/template/app/src/com/cocos/game/AppActivity.java @@ -0,0 +1,125 @@ +/**************************************************************************** +Copyright (c) 2015-2016 Chukong Technologies Inc. +Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ +package com.cocos.game; + +import android.os.Bundle; +import android.content.Intent; +import android.content.res.Configuration; + +import com.cocos.service.SDKWrapper; +import com.cocos.lib.CocosActivity; + +public class AppActivity extends CocosActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + // DO OTHER INITIALIZATION BELOW + SDKWrapper.shared().init(this); + + } + + @Override + protected void onResume() { + super.onResume(); + SDKWrapper.shared().onResume(); + } + + @Override + protected void onPause() { + super.onPause(); + SDKWrapper.shared().onPause(); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + // Workaround in https://stackoverflow.com/questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508 + if (!isTaskRoot()) { + return; + } + SDKWrapper.shared().onDestroy(); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + SDKWrapper.shared().onActivityResult(requestCode, resultCode, data); + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + SDKWrapper.shared().onNewIntent(intent); + } + + @Override + protected void onRestart() { + super.onRestart(); + SDKWrapper.shared().onRestart(); + } + + @Override + protected void onStop() { + super.onStop(); + SDKWrapper.shared().onStop(); + } + + @Override + public void onBackPressed() { + SDKWrapper.shared().onBackPressed(); + super.onBackPressed(); + } + + @Override + public void onConfigurationChanged(Configuration newConfig) { + SDKWrapper.shared().onConfigurationChanged(newConfig); + super.onConfigurationChanged(newConfig); + } + + @Override + protected void onRestoreInstanceState(Bundle savedInstanceState) { + SDKWrapper.shared().onRestoreInstanceState(savedInstanceState); + super.onRestoreInstanceState(savedInstanceState); + } + + @Override + protected void onSaveInstanceState(Bundle outState) { + SDKWrapper.shared().onSaveInstanceState(outState); + super.onSaveInstanceState(outState); + } + + @Override + protected void onStart() { + SDKWrapper.shared().onStart(); + super.onStart(); + } + + @Override + public void onLowMemory() { + SDKWrapper.shared().onLowMemory(); + super.onLowMemory(); + } +} diff --git a/templates/xr-monado/template/build-cfg.json b/templates/xr-monado/template/build-cfg.json new file mode 100644 index 0000000000..fb658e2985 --- /dev/null +++ b/templates/xr-monado/template/build-cfg.json @@ -0,0 +1,8 @@ +{ + "ndk_module_path" :[ + "${COCOS_ROOT}", + "${COCOS_ROOT}/cocos", + "${COCOS_ROOT}/external" + ], + "copy_resources": [] +} diff --git a/templates/xr-monado/template/build.gradle b/templates/xr-monado/template/build.gradle new file mode 100644 index 0000000000..2ae589d169 --- /dev/null +++ b/templates/xr-monado/template/build.gradle @@ -0,0 +1,31 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + + repositories { + google() + mavenCentral() + // jcenter() // keeped as anchor, will be removed soon + } + dependencies { + classpath 'com.android.tools.build:gradle:4.1.0' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + google() + mavenCentral() + // jcenter() // keeped as anchor, will be removed soon + flatDir { + dirs 'libs' + } + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/templates/xr-monado/template/instantapp/AndroidManifest.xml b/templates/xr-monado/template/instantapp/AndroidManifest.xml new file mode 100644 index 0000000000..d4578bd08f --- /dev/null +++ b/templates/xr-monado/template/instantapp/AndroidManifest.xml @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/templates/xr-monado/template/instantapp/build.gradle b/templates/xr-monado/template/instantapp/build.gradle new file mode 100644 index 0000000000..c1f846b7fd --- /dev/null +++ b/templates/xr-monado/template/instantapp/build.gradle @@ -0,0 +1,93 @@ +import org.apache.tools.ant.taskdefs.condition.Os + +apply plugin: 'com.android.application' + +RES_PATH = RES_PATH.replace("\\", "/") +COCOS_ENGINE_PATH = COCOS_ENGINE_PATH.replace("\\", "/") +buildDir = "${RES_PATH}/proj/build/$project.name" + +android { + compileSdkVersion PROP_COMPILE_SDK_VERSION.toInteger() + buildToolsVersion PROP_BUILD_TOOLS_VERSION + ndkPath PROP_NDK_PATH + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + defaultConfig { + applicationId "com.cocos.helloworld" + minSdkVersion PROP_MIN_SDK_VERSION + targetSdkVersion PROP_TARGET_SDK_VERSION + versionCode 1 + versionName "1.0" + + externalNativeBuild { + cmake { + targets "cocos" + arguments "-DRES_DIR=${RES_PATH}", "-DCOCOS_X_PATH=${COCOS_ENGINE_PATH}","-DANDROID_STL=c++_shared", "-DANDROID_TOOLCHAIN=clang", "-DANDROID_ARM_NEON=TRUE", "-DANDROID_LD=gold" + cppFlags "-frtti -fexceptions -fsigned-char -DANDROID_INSTANT=1" + } + ndk { abiFilters PROP_APP_ABI.split(':') } + } + } + + sourceSets.main { + java.srcDirs "../src", "src" + res.srcDirs "../res", 'res' + jniLibs.srcDirs "../libs", 'libs' + manifest.srcFile "AndroidManifest.xml" + assets.srcDir "${RES_PATH}/data" + } + + externalNativeBuild { + cmake { + path "../CMakeLists.txt" + buildStagingDirectory "${RES_PATH}/proj/build" + } + } + + signingConfigs { + + release { + if (project.hasProperty("RELEASE_STORE_FILE") && !RELEASE_STORE_FILE.isEmpty()) { + storeFile file(RELEASE_STORE_FILE) + storePassword RELEASE_STORE_PASSWORD + keyAlias RELEASE_KEY_ALIAS + keyPassword RELEASE_KEY_PASSWORD + } + } + } + + buildTypes { + release { + debuggable false + jniDebuggable false + renderscriptDebuggable false + minifyEnabled true + shrinkResources true + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + if (project.hasProperty("RELEASE_STORE_FILE")) { + signingConfig signingConfigs.release + } + // resValue "string", "app_name", PROP_APP_NAME + } + + debug { + debuggable true + jniDebuggable true + renderscriptDebuggable true + // resValue "string", "app_name", "${PROP_APP_NAME}-dbg" + // applicationIdSuffix ".debug" + } + } +} + +dependencies { + implementation fileTree(dir: '../libs', include: ['*.jar','*.aar']) + implementation fileTree(dir: 'libs', include: ['*.jar','*.aar']) + implementation fileTree(dir: "${COCOS_ENGINE_PATH}/cocos/platform/android/java/libs", include: ['*.jar']) + implementation project(':libservice') + implementation project(':libcocos') +} diff --git a/templates/xr-monado/template/instantapp/proguard-rules.pro b/templates/xr-monado/template/instantapp/proguard-rules.pro new file mode 100644 index 0000000000..dbb43fbbf1 --- /dev/null +++ b/templates/xr-monado/template/instantapp/proguard-rules.pro @@ -0,0 +1,42 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in E:\developSoftware\Android\SDK/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Proguard Cocos2d-x-lite for release +-keep public class com.cocos.** { *; } +-dontwarn com.cocos.** + +# Proguard Apache HTTP for release +-keep class org.apache.http.** { *; } +-dontwarn org.apache.http.** + +# Proguard okhttp for release +-keep class okhttp3.** { *; } +-dontwarn okhttp3.** + +-keep class okio.** { *; } +-dontwarn okio.** + +# Proguard Android Webivew for release. you can comment if you are not using a webview +-keep public class android.net.http.SslError +-keep public class android.webkit.WebViewClient + +-keep public class com.google.** { *; } + +-dontwarn android.webkit.WebView +-dontwarn android.net.http.SslError +-dontwarn android.webkit.WebViewClient diff --git a/templates/xr-monado/template/instantapp/src/com/cocos/game/InstantActivity.java b/templates/xr-monado/template/instantapp/src/com/cocos/game/InstantActivity.java new file mode 100644 index 0000000000..318e8398d3 --- /dev/null +++ b/templates/xr-monado/template/instantapp/src/com/cocos/game/InstantActivity.java @@ -0,0 +1,125 @@ +/**************************************************************************** +Copyright (c) 2015-2016 Chukong Technologies Inc. +Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ +package com.cocos.game; + +import android.os.Bundle; +import android.content.Intent; +import android.content.res.Configuration; + +import com.cocos.service.SDKWrapper; +import com.cocos.lib.CocosActivity; + +public class InstantActivity extends CocosActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + // DO OTHER INITIALIZATION BELOW + SDKWrapper.shared().init(this); + + } + + @Override + protected void onResume() { + super.onResume(); + SDKWrapper.shared().onResume(); + } + + @Override + protected void onPause() { + super.onPause(); + SDKWrapper.shared().onPause(); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + // Workaround in https://stackoverflow.com/questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508 + if (!isTaskRoot()) { + return; + } + SDKWrapper.shared().onDestroy(); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + SDKWrapper.shared().onActivityResult(requestCode, resultCode, data); + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + SDKWrapper.shared().onNewIntent(intent); + } + + @Override + protected void onRestart() { + super.onRestart(); + SDKWrapper.shared().onRestart(); + } + + @Override + protected void onStop() { + super.onStop(); + SDKWrapper.shared().onStop(); + } + + @Override + public void onBackPressed() { + SDKWrapper.shared().onBackPressed(); + super.onBackPressed(); + } + + @Override + public void onConfigurationChanged(Configuration newConfig) { + SDKWrapper.shared().onConfigurationChanged(newConfig); + super.onConfigurationChanged(newConfig); + } + + @Override + protected void onRestoreInstanceState(Bundle savedInstanceState) { + SDKWrapper.shared().onRestoreInstanceState(savedInstanceState); + super.onRestoreInstanceState(savedInstanceState); + } + + @Override + protected void onSaveInstanceState(Bundle outState) { + SDKWrapper.shared().onSaveInstanceState(outState); + super.onSaveInstanceState(outState); + } + + @Override + protected void onStart() { + SDKWrapper.shared().onStart(); + super.onStart(); + } + + @Override + public void onLowMemory() { + SDKWrapper.shared().onLowMemory(); + super.onLowMemory(); + } +} diff --git a/templates/xr-monado/template/res/mipmap-hdpi/ic_launcher.png b/templates/xr-monado/template/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000000..888c0d56ab Binary files /dev/null and b/templates/xr-monado/template/res/mipmap-hdpi/ic_launcher.png differ diff --git a/templates/xr-monado/template/res/mipmap-mdpi/ic_launcher.png b/templates/xr-monado/template/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000000..d5e3c770af Binary files /dev/null and b/templates/xr-monado/template/res/mipmap-mdpi/ic_launcher.png differ diff --git a/templates/xr-monado/template/res/mipmap-xhdpi/ic_launcher.png b/templates/xr-monado/template/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000000..2b6f32ae03 Binary files /dev/null and b/templates/xr-monado/template/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/templates/xr-monado/template/res/mipmap-xxhdpi/ic_launcher.png b/templates/xr-monado/template/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000000..2f1e5a6b37 Binary files /dev/null and b/templates/xr-monado/template/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/templates/xr-monado/template/res/mipmap-xxxhdpi/ic_launcher.png b/templates/xr-monado/template/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000000..a9ebc7956e Binary files /dev/null and b/templates/xr-monado/template/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/templates/xr-monado/template/res/values/strings.xml b/templates/xr-monado/template/res/values/strings.xml new file mode 100644 index 0000000000..1043872e78 --- /dev/null +++ b/templates/xr-monado/template/res/values/strings.xml @@ -0,0 +1,3 @@ + + CocosGame + diff --git a/templates/xr-rokid/build/build.gradle b/templates/xr-rokid/build/build.gradle new file mode 100644 index 0000000000..d748464112 --- /dev/null +++ b/templates/xr-rokid/build/build.gradle @@ -0,0 +1,18 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + + repositories { + google() + mavenCentral() + // jcenter() // keeped as anchor, will be removed soon + } + dependencies { + classpath 'com.android.tools.build:gradle:4.1.0' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +apply from: NATIVE_DIR +"/build.gradle" diff --git a/templates/xr-rokid/build/gradle.properties b/templates/xr-rokid/build/gradle.properties new file mode 100644 index 0000000000..6a701a83ce --- /dev/null +++ b/templates/xr-rokid/build/gradle.properties @@ -0,0 +1,66 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +# Default value: -Xmx10248m -XX:MaxPermSize=256m +# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true +org.gradle.jvmargs=-Xmx4608m +android.useAndroidX=true + +android.injected.testOnly=false + +# Android SDK version that will be used as the compile project +PROP_COMPILE_SDK_VERSION=28 + +# Android SDK version that will be used as the earliest version of android this application can run on +PROP_MIN_SDK_VERSION=21 + +# Android SDK version that will be used as the latest version of android this application has been tested on +PROP_TARGET_SDK_VERSION=27 + +# Android Build Tools version that will be used as the compile project +PROP_BUILD_TOOLS_VERSION=28.0.0 + +# Android Application Name +PROP_APP_NAME=Cocos Game + +# Instant App +PROP_ENABLE_INSTANT_APP=true + +PROP_NDK_PATH= + +# Cocos Engine Path +COCOS_ENGINE_PATH= + +# Res path +RES_PATH= + +# Native source dir +NATIVE_DIR= + +# Application ID +APPLICATION_ID= + +# List of CPU Archtexture to build that application with +# Available architextures (armeabi-v7a | arm64-v8a | x86 | x86_64) +# To build for multiple architexture, use the `:` between them +# Example - PROP_APP_ABI=armeabi-v7a:arm64-v8a:x86 +PROP_APP_ABI=arm64-v8a + +# fill in sign information for release mode +# RELEASE_STORE_FILE= +# RELEASE_STORE_PASSWORD= +# RELEASE_KEY_ALIAS= +# RELEASE_KEY_PASSWORD= diff --git a/templates/xr-rokid/build/gradle/wrapper/gradle-wrapper.jar b/templates/xr-rokid/build/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..8c0fb64a86 Binary files /dev/null and b/templates/xr-rokid/build/gradle/wrapper/gradle-wrapper.jar differ diff --git a/templates/xr-rokid/build/gradle/wrapper/gradle-wrapper.properties b/templates/xr-rokid/build/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..69d02eef07 --- /dev/null +++ b/templates/xr-rokid/build/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Fri Oct 27 10:18:28 CST 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.5.1-all.zip diff --git a/templates/xr-rokid/build/gradlew b/templates/xr-rokid/build/gradlew new file mode 100644 index 0000000000..91a7e269e1 --- /dev/null +++ b/templates/xr-rokid/build/gradlew @@ -0,0 +1,164 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# For Cygwin, ensure paths are in UNIX format before anything is touched. +if $cygwin ; then + [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` +fi + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >&- +APP_HOME="`pwd -P`" +cd "$SAVED" >&- + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/templates/xr-rokid/build/gradlew.bat b/templates/xr-rokid/build/gradlew.bat new file mode 100644 index 0000000000..8a0b282aa6 --- /dev/null +++ b/templates/xr-rokid/build/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/templates/xr-rokid/build/libservice/AndroidManifest.xml b/templates/xr-rokid/build/libservice/AndroidManifest.xml new file mode 100644 index 0000000000..0bd51bf949 --- /dev/null +++ b/templates/xr-rokid/build/libservice/AndroidManifest.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + diff --git a/templates/xr-rokid/build/libservice/build.gradle b/templates/xr-rokid/build/libservice/build.gradle new file mode 100644 index 0000000000..1cb73a2af2 --- /dev/null +++ b/templates/xr-rokid/build/libservice/build.gradle @@ -0,0 +1,35 @@ +apply plugin: 'com.android.library' + +android { + compileSdkVersion PROP_COMPILE_SDK_VERSION.toInteger() + + defaultConfig { + minSdkVersion PROP_MIN_SDK_VERSION + targetSdkVersion PROP_TARGET_SDK_VERSION + versionCode 1 + versionName "1.0" + } + + sourceSets.main { + java.srcDirs "src" + res.srcDirs 'res' + jniLibs.srcDirs 'libs' + manifest.srcFile "AndroidManifest.xml" + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar','*.aar']) + implementation project(':libcocos') +} diff --git a/templates/xr-rokid/build/libservice/proguard-rules.pro b/templates/xr-rokid/build/libservice/proguard-rules.pro new file mode 100644 index 0000000000..f1b424510d --- /dev/null +++ b/templates/xr-rokid/build/libservice/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/templates/xr-rokid/build/libservice/src/com/cocos/service/SDKWrapper.java b/templates/xr-rokid/build/libservice/src/com/cocos/service/SDKWrapper.java new file mode 100644 index 0000000000..e7ab46f77d --- /dev/null +++ b/templates/xr-rokid/build/libservice/src/com/cocos/service/SDKWrapper.java @@ -0,0 +1,185 @@ +/**************************************************************************** + Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. + http://www.cocos.com + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +package com.cocos.service; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.content.res.AssetManager; +import android.content.res.Configuration; +import android.os.Bundle; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.List; + +public final class SDKWrapper { + private SDKWrapper() {} + private static class SDKWrapperInstance { + private static final SDKWrapper mInstance = new SDKWrapper(); + } + public static SDKWrapper shared() { return SDKWrapperInstance.mInstance; } + + @SuppressWarnings("unused") + public interface SDKInterface { + default void init(Context context) {} + default void onStart() {} + default void onPause() {} + default void onResume() {} + default void onStop() {} + default void onDestroy() {} + default void onRestart() {} + default void onNewIntent(Intent intent) {} + default void onActivityResult(int requestCode, int resultCode, Intent data) {} + default void onConfigurationChanged(Configuration newConfig) {} + default void onRestoreInstanceState(Bundle savedInstanceState) {} + default void onSaveInstanceState(Bundle outState) {} + default void onBackPressed() {} + default void onLowMemory() {} + } + + private WeakReference mActivity = null; + private List serviceInstances; + + private void loadSDKInterface() { + ArrayList instances = new ArrayList<>(); + try { + String json = this.getJson("service.json"); + JSONObject jsonObject = new JSONObject(json); + JSONArray serviceClasses = jsonObject.getJSONArray("serviceClasses"); + if (serviceClasses == null) return; + int length = serviceClasses.length(); + for (int i = 0; i < length; i++) { + instances.add((SDKInterface) Class.forName(serviceClasses.getString(i)).newInstance()); + } + } catch (Exception ignored) { } + this.serviceInstances = instances; + } + + @SuppressWarnings("SameParameterValue") + private String getJson(String fileName) { + StringBuilder sb = new StringBuilder(); + try { + AssetManager am = this.mActivity.get().getAssets(); + BufferedReader br = new BufferedReader(new InputStreamReader(am.open(fileName))); + String next; + while (null != (next = br.readLine())) { sb.append(next); } + } catch (IOException e) { + sb.delete(0, sb.length()); + } + return sb.toString().trim(); + } + + public Activity getActivity() { return this.mActivity.get(); } + + public void init(Activity activity) { + this.mActivity = new WeakReference<>(activity); + this.loadSDKInterface(); + for (SDKInterface sdk : this.serviceInstances) { + sdk.init(activity); + } + } + + public void onResume() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onResume(); + } + } + + public void onPause() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onPause(); + } + } + + public void onDestroy() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onDestroy(); + } + } + + public void onActivityResult(int requestCode, int resultCode, Intent data) { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onActivityResult(requestCode, resultCode, data); + } + } + + public void onNewIntent(Intent intent) { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onNewIntent(intent); + } + } + + public void onRestart() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onRestart(); + } + } + + public void onStop() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onStop(); + } + } + + public void onBackPressed() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onBackPressed(); + } + } + + public void onConfigurationChanged(Configuration newConfig) { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onConfigurationChanged(newConfig); + } + } + + public void onRestoreInstanceState(Bundle savedInstanceState) { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onRestoreInstanceState(savedInstanceState); + } + } + + public void onSaveInstanceState(Bundle outState) { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onSaveInstanceState(outState); + } + } + + public void onStart() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onStart(); + } + } + + public void onLowMemory() { + for (SDKInterface sdk : this.serviceInstances) { + sdk.onLowMemory(); + } + } +} \ No newline at end of file diff --git a/templates/xr-rokid/build/settings.gradle b/templates/xr-rokid/build/settings.gradle new file mode 100644 index 0000000000..80cad73242 --- /dev/null +++ b/templates/xr-rokid/build/settings.gradle @@ -0,0 +1,9 @@ +include ':libcocos',':libservice',':CocosGame' +project(':libcocos').projectDir = new File(COCOS_ENGINE_PATH,'cocos/platform/android/libcocos2dx') +project(':CocosGame').projectDir = new File(NATIVE_DIR, 'app') +if(PROP_ENABLE_INSTANT_APP == "true" || PROP_ENABLE_INSTANT_APP == "yes") { + include ':instantapp' + project(':instantapp').projectDir = new File(NATIVE_DIR, 'instantapp') +} + +rootProject.name = "CocosGame" diff --git a/templates/xr-rokid/template/.gitignore b/templates/xr-rokid/template/.gitignore new file mode 100644 index 0000000000..9c4de5825b --- /dev/null +++ b/templates/xr-rokid/template/.gitignore @@ -0,0 +1,7 @@ +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build +/captures diff --git a/templates/xr-rokid/template/CMakeLists.txt b/templates/xr-rokid/template/CMakeLists.txt new file mode 100644 index 0000000000..b6f90857a9 --- /dev/null +++ b/templates/xr-rokid/template/CMakeLists.txt @@ -0,0 +1,15 @@ +cmake_minimum_required(VERSION 3.8) + +option(APP_NAME "Project Name" "CocosGame") +project(${APP_NAME} CXX) +set(CC_LIB_NAME cocos) +set(CC_PROJECT_DIR ${CMAKE_CURRENT_LIST_DIR}) +set(CC_PROJ_SOURCES) +set(CC_COMMON_SOURCES) +set(CC_ALL_SOURCES) + +include(${CMAKE_CURRENT_LIST_DIR}/../common/CMakeLists.txt) + +cc_android_before_target(${CC_LIB_NAME}) +add_library(${CC_LIB_NAME} SHARED ${CC_ALL_SOURCES}) +cc_android_after_target(${CC_LIB_NAME}) diff --git a/templates/xr-rokid/template/app/.gitignore b/templates/xr-rokid/template/app/.gitignore new file mode 100644 index 0000000000..1de99493d6 --- /dev/null +++ b/templates/xr-rokid/template/app/.gitignore @@ -0,0 +1,2 @@ +/build +/jniLibs diff --git a/templates/xr-rokid/template/app/AndroidManifest.xml b/templates/xr-rokid/template/app/AndroidManifest.xml new file mode 100644 index 0000000000..5aeb9b5cb7 --- /dev/null +++ b/templates/xr-rokid/template/app/AndroidManifest.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/templates/xr-rokid/template/app/build.gradle b/templates/xr-rokid/template/app/build.gradle new file mode 100644 index 0000000000..8ee469fa3b --- /dev/null +++ b/templates/xr-rokid/template/app/build.gradle @@ -0,0 +1,96 @@ +import org.apache.tools.ant.taskdefs.condition.Os + +apply plugin: 'com.android.application' + +RES_PATH = RES_PATH.replace("\\", "/") +COCOS_ENGINE_PATH = COCOS_ENGINE_PATH.replace("\\", "/") + +buildDir = "${RES_PATH}/proj/build/$project.name" +android { + compileSdkVersion PROP_COMPILE_SDK_VERSION.toInteger() + buildToolsVersion PROP_BUILD_TOOLS_VERSION + ndkPath PROP_NDK_PATH + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + defaultConfig { + applicationId APPLICATION_ID + minSdkVersion PROP_MIN_SDK_VERSION + targetSdkVersion PROP_TARGET_SDK_VERSION + versionCode 1 + versionName "1.0" + + externalNativeBuild { + cmake { + targets "cocos" + arguments "-DRES_DIR=${RES_PATH}", "-DCOCOS_X_PATH=${COCOS_ENGINE_PATH}", "-DANDROID_STL=c++_shared", "-DANDROID_TOOLCHAIN=clang", "-DANDROID_ARM_NEON=TRUE", "-DANDROID_LD=gold" + } + ndk { abiFilters PROP_APP_ABI.split(':') } + } + } + + sourceSets.main { + java.srcDirs "../src", "src" + res.srcDirs "../res", 'res' + jniLibs.srcDirs "../libs", 'libs' + manifest.srcFile "AndroidManifest.xml" + assets.srcDir "${RES_PATH}/data" + jniLibs { + // Vulkan validation layer + // srcDir "${android.ndkDirectory}/sources/third_party/vulkan/src/build-android/jniLibs" + } + } + + externalNativeBuild { + cmake { + path "../CMakeLists.txt" + buildStagingDirectory "${RES_PATH}/proj/build" + } + } + + signingConfigs { + + release { + if (project.hasProperty("RELEASE_STORE_FILE") && !RELEASE_STORE_FILE.isEmpty()) { + storeFile file(RELEASE_STORE_FILE) + storePassword RELEASE_STORE_PASSWORD + keyAlias RELEASE_KEY_ALIAS + keyPassword RELEASE_KEY_PASSWORD + } + } + } + + buildTypes { + release { + debuggable false + jniDebuggable false + renderscriptDebuggable false + minifyEnabled true + shrinkResources true + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + if (project.hasProperty("RELEASE_STORE_FILE")) { + signingConfig signingConfigs.release + } + // resValue "string", "app_name", PROP_APP_NAME + } + + debug { + debuggable true + jniDebuggable true + renderscriptDebuggable true + // resValue "string", "app_name", "${PROP_APP_NAME}-dbg" + // applicationIdSuffix ".debug" + } + } +} + +dependencies { + implementation fileTree(dir: '../libs', include: ['*.jar','*.aar']) + implementation fileTree(dir: 'libs', include: ['*.jar','*.aar']) + implementation fileTree(dir: "${COCOS_ENGINE_PATH}/cocos/platform/android/java/libs", include: ['*.jar']) + implementation project(':libservice') + implementation project(':libcocos') +} diff --git a/templates/xr-rokid/template/app/proguard-rules.pro b/templates/xr-rokid/template/app/proguard-rules.pro new file mode 100644 index 0000000000..dbb43fbbf1 --- /dev/null +++ b/templates/xr-rokid/template/app/proguard-rules.pro @@ -0,0 +1,42 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in E:\developSoftware\Android\SDK/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Proguard Cocos2d-x-lite for release +-keep public class com.cocos.** { *; } +-dontwarn com.cocos.** + +# Proguard Apache HTTP for release +-keep class org.apache.http.** { *; } +-dontwarn org.apache.http.** + +# Proguard okhttp for release +-keep class okhttp3.** { *; } +-dontwarn okhttp3.** + +-keep class okio.** { *; } +-dontwarn okio.** + +# Proguard Android Webivew for release. you can comment if you are not using a webview +-keep public class android.net.http.SslError +-keep public class android.webkit.WebViewClient + +-keep public class com.google.** { *; } + +-dontwarn android.webkit.WebView +-dontwarn android.net.http.SslError +-dontwarn android.webkit.WebViewClient diff --git a/templates/xr-rokid/template/app/src/com/cocos/game/AppActivity.java b/templates/xr-rokid/template/app/src/com/cocos/game/AppActivity.java new file mode 100644 index 0000000000..bca3590fdc --- /dev/null +++ b/templates/xr-rokid/template/app/src/com/cocos/game/AppActivity.java @@ -0,0 +1,126 @@ +/**************************************************************************** +Copyright (c) 2015-2016 Chukong Technologies Inc. +Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ +package com.cocos.game; + +import android.os.Bundle; +import android.content.Intent; +import android.content.res.Configuration; + +import com.cocos.service.SDKWrapper; +import com.cocos.lib.CocosActivity; + +public class AppActivity extends CocosActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + // DO OTHER INITIALIZATION BELOW + SDKWrapper.shared().init(this); + + } + + @Override + protected void onResume() { + super.onResume(); + SDKWrapper.shared().onResume(); + } + + @Override + protected void onPause() { + super.onPause(); + SDKWrapper.shared().onPause(); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + // Workaround in https://stackoverflow.com/questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508 + if (!isTaskRoot()) { + return; + } + SDKWrapper.shared().onDestroy(); + System.exit(0); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + SDKWrapper.shared().onActivityResult(requestCode, resultCode, data); + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + SDKWrapper.shared().onNewIntent(intent); + } + + @Override + protected void onRestart() { + super.onRestart(); + SDKWrapper.shared().onRestart(); + } + + @Override + protected void onStop() { + super.onStop(); + SDKWrapper.shared().onStop(); + } + + @Override + public void onBackPressed() { + SDKWrapper.shared().onBackPressed(); + super.onBackPressed(); + } + + @Override + public void onConfigurationChanged(Configuration newConfig) { + SDKWrapper.shared().onConfigurationChanged(newConfig); + super.onConfigurationChanged(newConfig); + } + + @Override + protected void onRestoreInstanceState(Bundle savedInstanceState) { + SDKWrapper.shared().onRestoreInstanceState(savedInstanceState); + super.onRestoreInstanceState(savedInstanceState); + } + + @Override + protected void onSaveInstanceState(Bundle outState) { + SDKWrapper.shared().onSaveInstanceState(outState); + super.onSaveInstanceState(outState); + } + + @Override + protected void onStart() { + SDKWrapper.shared().onStart(); + super.onStart(); + } + + @Override + public void onLowMemory() { + SDKWrapper.shared().onLowMemory(); + super.onLowMemory(); + } +} diff --git a/templates/xr-rokid/template/build-cfg.json b/templates/xr-rokid/template/build-cfg.json new file mode 100644 index 0000000000..fb658e2985 --- /dev/null +++ b/templates/xr-rokid/template/build-cfg.json @@ -0,0 +1,8 @@ +{ + "ndk_module_path" :[ + "${COCOS_ROOT}", + "${COCOS_ROOT}/cocos", + "${COCOS_ROOT}/external" + ], + "copy_resources": [] +} diff --git a/templates/xr-rokid/template/build.gradle b/templates/xr-rokid/template/build.gradle new file mode 100644 index 0000000000..2ae589d169 --- /dev/null +++ b/templates/xr-rokid/template/build.gradle @@ -0,0 +1,31 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + + repositories { + google() + mavenCentral() + // jcenter() // keeped as anchor, will be removed soon + } + dependencies { + classpath 'com.android.tools.build:gradle:4.1.0' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + google() + mavenCentral() + // jcenter() // keeped as anchor, will be removed soon + flatDir { + dirs 'libs' + } + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/templates/xr-rokid/template/instantapp/AndroidManifest.xml b/templates/xr-rokid/template/instantapp/AndroidManifest.xml new file mode 100644 index 0000000000..41fa909413 --- /dev/null +++ b/templates/xr-rokid/template/instantapp/AndroidManifest.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/templates/xr-rokid/template/instantapp/build.gradle b/templates/xr-rokid/template/instantapp/build.gradle new file mode 100644 index 0000000000..c1f846b7fd --- /dev/null +++ b/templates/xr-rokid/template/instantapp/build.gradle @@ -0,0 +1,93 @@ +import org.apache.tools.ant.taskdefs.condition.Os + +apply plugin: 'com.android.application' + +RES_PATH = RES_PATH.replace("\\", "/") +COCOS_ENGINE_PATH = COCOS_ENGINE_PATH.replace("\\", "/") +buildDir = "${RES_PATH}/proj/build/$project.name" + +android { + compileSdkVersion PROP_COMPILE_SDK_VERSION.toInteger() + buildToolsVersion PROP_BUILD_TOOLS_VERSION + ndkPath PROP_NDK_PATH + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + defaultConfig { + applicationId "com.cocos.helloworld" + minSdkVersion PROP_MIN_SDK_VERSION + targetSdkVersion PROP_TARGET_SDK_VERSION + versionCode 1 + versionName "1.0" + + externalNativeBuild { + cmake { + targets "cocos" + arguments "-DRES_DIR=${RES_PATH}", "-DCOCOS_X_PATH=${COCOS_ENGINE_PATH}","-DANDROID_STL=c++_shared", "-DANDROID_TOOLCHAIN=clang", "-DANDROID_ARM_NEON=TRUE", "-DANDROID_LD=gold" + cppFlags "-frtti -fexceptions -fsigned-char -DANDROID_INSTANT=1" + } + ndk { abiFilters PROP_APP_ABI.split(':') } + } + } + + sourceSets.main { + java.srcDirs "../src", "src" + res.srcDirs "../res", 'res' + jniLibs.srcDirs "../libs", 'libs' + manifest.srcFile "AndroidManifest.xml" + assets.srcDir "${RES_PATH}/data" + } + + externalNativeBuild { + cmake { + path "../CMakeLists.txt" + buildStagingDirectory "${RES_PATH}/proj/build" + } + } + + signingConfigs { + + release { + if (project.hasProperty("RELEASE_STORE_FILE") && !RELEASE_STORE_FILE.isEmpty()) { + storeFile file(RELEASE_STORE_FILE) + storePassword RELEASE_STORE_PASSWORD + keyAlias RELEASE_KEY_ALIAS + keyPassword RELEASE_KEY_PASSWORD + } + } + } + + buildTypes { + release { + debuggable false + jniDebuggable false + renderscriptDebuggable false + minifyEnabled true + shrinkResources true + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + if (project.hasProperty("RELEASE_STORE_FILE")) { + signingConfig signingConfigs.release + } + // resValue "string", "app_name", PROP_APP_NAME + } + + debug { + debuggable true + jniDebuggable true + renderscriptDebuggable true + // resValue "string", "app_name", "${PROP_APP_NAME}-dbg" + // applicationIdSuffix ".debug" + } + } +} + +dependencies { + implementation fileTree(dir: '../libs', include: ['*.jar','*.aar']) + implementation fileTree(dir: 'libs', include: ['*.jar','*.aar']) + implementation fileTree(dir: "${COCOS_ENGINE_PATH}/cocos/platform/android/java/libs", include: ['*.jar']) + implementation project(':libservice') + implementation project(':libcocos') +} diff --git a/templates/xr-rokid/template/instantapp/proguard-rules.pro b/templates/xr-rokid/template/instantapp/proguard-rules.pro new file mode 100644 index 0000000000..dbb43fbbf1 --- /dev/null +++ b/templates/xr-rokid/template/instantapp/proguard-rules.pro @@ -0,0 +1,42 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in E:\developSoftware\Android\SDK/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Proguard Cocos2d-x-lite for release +-keep public class com.cocos.** { *; } +-dontwarn com.cocos.** + +# Proguard Apache HTTP for release +-keep class org.apache.http.** { *; } +-dontwarn org.apache.http.** + +# Proguard okhttp for release +-keep class okhttp3.** { *; } +-dontwarn okhttp3.** + +-keep class okio.** { *; } +-dontwarn okio.** + +# Proguard Android Webivew for release. you can comment if you are not using a webview +-keep public class android.net.http.SslError +-keep public class android.webkit.WebViewClient + +-keep public class com.google.** { *; } + +-dontwarn android.webkit.WebView +-dontwarn android.net.http.SslError +-dontwarn android.webkit.WebViewClient diff --git a/templates/xr-rokid/template/instantapp/src/com/cocos/game/InstantActivity.java b/templates/xr-rokid/template/instantapp/src/com/cocos/game/InstantActivity.java new file mode 100644 index 0000000000..318e8398d3 --- /dev/null +++ b/templates/xr-rokid/template/instantapp/src/com/cocos/game/InstantActivity.java @@ -0,0 +1,125 @@ +/**************************************************************************** +Copyright (c) 2015-2016 Chukong Technologies Inc. +Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ +package com.cocos.game; + +import android.os.Bundle; +import android.content.Intent; +import android.content.res.Configuration; + +import com.cocos.service.SDKWrapper; +import com.cocos.lib.CocosActivity; + +public class InstantActivity extends CocosActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + // DO OTHER INITIALIZATION BELOW + SDKWrapper.shared().init(this); + + } + + @Override + protected void onResume() { + super.onResume(); + SDKWrapper.shared().onResume(); + } + + @Override + protected void onPause() { + super.onPause(); + SDKWrapper.shared().onPause(); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + // Workaround in https://stackoverflow.com/questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508 + if (!isTaskRoot()) { + return; + } + SDKWrapper.shared().onDestroy(); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + SDKWrapper.shared().onActivityResult(requestCode, resultCode, data); + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + SDKWrapper.shared().onNewIntent(intent); + } + + @Override + protected void onRestart() { + super.onRestart(); + SDKWrapper.shared().onRestart(); + } + + @Override + protected void onStop() { + super.onStop(); + SDKWrapper.shared().onStop(); + } + + @Override + public void onBackPressed() { + SDKWrapper.shared().onBackPressed(); + super.onBackPressed(); + } + + @Override + public void onConfigurationChanged(Configuration newConfig) { + SDKWrapper.shared().onConfigurationChanged(newConfig); + super.onConfigurationChanged(newConfig); + } + + @Override + protected void onRestoreInstanceState(Bundle savedInstanceState) { + SDKWrapper.shared().onRestoreInstanceState(savedInstanceState); + super.onRestoreInstanceState(savedInstanceState); + } + + @Override + protected void onSaveInstanceState(Bundle outState) { + SDKWrapper.shared().onSaveInstanceState(outState); + super.onSaveInstanceState(outState); + } + + @Override + protected void onStart() { + SDKWrapper.shared().onStart(); + super.onStart(); + } + + @Override + public void onLowMemory() { + SDKWrapper.shared().onLowMemory(); + super.onLowMemory(); + } +} diff --git a/templates/xr-rokid/template/res/mipmap-hdpi/ic_launcher.png b/templates/xr-rokid/template/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000000..888c0d56ab Binary files /dev/null and b/templates/xr-rokid/template/res/mipmap-hdpi/ic_launcher.png differ diff --git a/templates/xr-rokid/template/res/mipmap-mdpi/ic_launcher.png b/templates/xr-rokid/template/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000000..d5e3c770af Binary files /dev/null and b/templates/xr-rokid/template/res/mipmap-mdpi/ic_launcher.png differ diff --git a/templates/xr-rokid/template/res/mipmap-xhdpi/ic_launcher.png b/templates/xr-rokid/template/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000000..2b6f32ae03 Binary files /dev/null and b/templates/xr-rokid/template/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/templates/xr-rokid/template/res/mipmap-xxhdpi/ic_launcher.png b/templates/xr-rokid/template/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000000..2f1e5a6b37 Binary files /dev/null and b/templates/xr-rokid/template/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/templates/xr-rokid/template/res/mipmap-xxxhdpi/ic_launcher.png b/templates/xr-rokid/template/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000000..a9ebc7956e Binary files /dev/null and b/templates/xr-rokid/template/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/templates/xr-rokid/template/res/values/strings.xml b/templates/xr-rokid/template/res/values/strings.xml new file mode 100644 index 0000000000..1043872e78 --- /dev/null +++ b/templates/xr-rokid/template/res/values/strings.xml @@ -0,0 +1,3 @@ + + CocosGame +