unity-webgl
Version:
Unity-WebGL provides an easy solution for embedding Unity WebGL builds in your web projects, with two-way communication between your webApp and Unity application with advanced API's.
459 lines (453 loc) • 17.2 kB
TypeScript
/**
* Unity Boolean Like Type Declaration.
*/
type UnityBooleanLike =
/**
* Represents the boolean value `false`.
*/
0
/**
* Represents the boolean value `true`.
*/
| 1;
type UnityModule = {
/**
* Stringifies a pointer to a string.
* @param pointer The pointer to the string.
* @param length The length of the string.
* @deprecated Deprecated in Unity 2021.2, use UTF8ToString instead.
*/
Pointer_stringify(pointer: number, length: number): string;
/**
* Converts a pointer to a string.
* @param pointer The pointer to the string.
*/
UTF8ToString(pointer: number): string;
/**
* Enables or disabled the fullscreen mode of the UnityInstance.
* @param fullScreen sets the fullscreen mode.
*/
SetFullscreen(fullScreen: UnityBooleanLike): void;
/**
* A reference to the Unity Instance's Canvas.
*/
canvas?: HTMLCanvasElement;
};
/**
* Type declaration for the UnityInstance.
*/
declare class UnityInstance {
/**
* Creates a new instance of Unity Instance.
*/
constructor();
/**
* Sends a message to the UnityInstance to invoke a public method.
* @param objectName the name of the game object in your Unity scene.
* @param methodName the name of the public method on the game object.
* @param parameter an optional parameter to pass along to the method.
*/
SendMessage(objectName: string, methodName: string, parameter?: string | number | boolean): void;
/**
* Enables or disabled the fullscreen mode of the UnityInstance.
* @param fullScreen sets the fullscreen mode.
*/
SetFullscreen(fullScreen: UnityBooleanLike): void;
/**
* Quits the Unity WebGL application and removes it from the memory.
* @returns a promise which resolves when the application did quit.
*/
Quit(): Promise<void>;
/**
* The internal Unity Module.
*/
Module: UnityModule;
}
interface EventListener {
(...args: any[]): void;
_?: EventListener;
}
type EventListenerOptions = {
once?: boolean;
};
interface UnityEventMap {
beforeMount: (instance: UnityWebgl) => void;
mounted: (instance: UnityWebgl, unityInstance: UnityInstance) => void;
beforeUnmount: (instance: UnityWebgl) => void;
unmounted: () => void;
progress: (progress: number) => void;
debug: (msg: string) => void;
error: (error: string | Error) => void;
}
declare class UnityWebglEvent {
private _e;
constructor();
/**
* Register event listener
* @param name event name
* @param listener event listener
* @param options event listener options
*/
on<K extends keyof UnityEventMap>(name: K, listener: UnityEventMap[K], options?: EventListenerOptions): this;
on(name: string, listener: EventListener, options?: EventListenerOptions): this;
/**
* Remove event listener
* @param name event name
* @param listener event listener
*/
off<K extends keyof UnityEventMap>(name: K, listener: UnityEventMap[K]): this;
off(name: string, listener: EventListener): this;
/**
* Dispatch event
* @param name event name
* @param args event args
*/
emit(name: string, ...args: any[]): this;
/**
* clear all event listeners
*/
protected clear(): void;
/**
* Register event listener for unity client
* @param name event name
* @param listener event listener
*/
addUnityListener(name: string, listener: EventListener, options?: EventListenerOptions): this;
/**
* Remove event listener from unity client
* @param name event name
* @param listener event listener
*/
removeUnityListener(name: string, listener?: EventListener): this;
}
/**
* WebGLContextAttributes object that contains the actual context parameters.
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getContextAttributes
*/
type WebGLContextAttributes = {
/**
* If set to true, the context will have an alpha (transparency) channel.
* @default true
*/
readonly alpha?: boolean;
/**
* If set to true, the context will attempt to perform antialiased rendering
* if possible.
* @default true
*/
readonly antialias?: boolean;
/**
* If set to true, the context will have a 16 bit depth buffer. Defaults to
* true. Use gl.enable(DEPTH_TEST) to enable the depth test and
* gl.depthFunc(), gl.depthMask(), and gl.depthRange() to configure the depth
* test.
* @default true
*/
readonly depth?: boolean;
/**
* If the value is true, context creation will fail if the implementation
* determines that the performance of the created WebGL context would be
* dramatically lower than that of a native application making equivalent
* OpenGL calls. This could happen for a number of reasons, including an
* implementation might switch to a software rasterizer if the user's GPU
* driver is known to be unstable. And an implementation might require reading
* back the framebuffer from GPU memory to system memory before compositing it
* with the rest of the page, significantly reducing performance.
* @default false
*/
readonly failIfMajorPerformanceCaveat?: boolean;
/**
* Provides a hint to the user agent indicating what configuration of GPU is
* suitable for this WebGL context. This may influence which GPU is used in a
* system with multiple GPUs. For example, a dual-GPU system might have one
* GPU that consumes less power at the expense of rendering performance.
* Note that this property is only a hint and a WebGL implementation may
* choose to ignore it. WebGL implementations use context lost and restored
* events to regulate power and memory consumption, regardless of the value of
* this attribute.
* @default "default"
*/
readonly powerPreference?: 'default' | 'high-performance' | 'low-power';
/**
* If set to true, the color channels in the framebuffer will be stored
* premultipled by the alpha channel to improve performance.
* @default true
*/
readonly premultipliedAlpha?: boolean;
/**
* If set to false, the buffer will be cleared after rendering. If you wish to
* use canvas.toDataURL(), you will either need to draw to the canvas
* immediately before calling toDataURL(), or set preserveDrawingBuffer to
* true to keep the buffer available after the browser has displayed the
* buffer (at the cost of increased memory use).
* @default false
*/
readonly preserveDrawingBuffer?: boolean;
/**
* Stenciling enables and disables drawing on a per-pixel basis. It is
* typically used in multipass rendering to achieve special effects.
* @default false
*/
readonly stencil?: boolean;
/**
* If set to true, the context will have an 8 bit stencil buffer. Defaults to
* false. Use gl.enable(STENCIL_TEST) to enable depth test and
* gl.stencilFunc(), gl.stencilFuncSeparate(), gl.stencilMask(),
* gl.stencilMaskSeparate(), gl.stencilOp(), and gl.stencilOpSeparate()
* to configure the stencil test.
* @default false
*/
readonly desynchronized?: boolean;
/**
* xrCompatible is a boolean that indicates whether the context is compatible.
* @default false
*/
readonly xrCompatible?: boolean;
};
/**
* The cache control mode determines how the Unity should cache the resource.
* - `must-revalidate`: The cache returns to an enabled state and the file is
* revalidated before being loaded from the cache.
* - `immutable`: the cache is enabled and the file is loaded from the cache
* without revalidation.
* - `no-store`: The cache is disabled.
*/
type UnityCacheControlMode =
/**
* The cache returns to an enabled state and the file is revalidated before
* being loaded from the cache.
*/
'must-revalidate'
/**
* the cache is enabled and the file is loaded from the cache without revalidation.
*/
| 'immutable'
/**
* The cache is disabled.
*/
| 'no-store'
/**
* Fallback for when the cache control mode is not recognized.
*/
| string;
/**
* Banners can be used to display non-critical warnings and error messages from
* the Unity Instance.
*/
type UnityInstanceBannerType = 'error' | 'warning';
/**
* The Unity Arguments can be passed to a create Unity instance method in order to initialize it.
*/
interface UnityArguments {
/**
* The url to the build data file generated by Unity.
* @public
* @type {string}
*/
readonly dataUrl: string;
/**
* The url to the framework file generated by Unity.
* @public
* @type {string}
*/
readonly frameworkUrl: string;
/**
* The url to the unity code file generated by Unity.
* @public
* @type {string}
*/
readonly codeUrl: string;
/**
* The url to the web worker file generated by Unity.
* @public
* @type {string}
*/
readonly workerUrl?: string;
/**
* The url where the streaming assets can be found.
* @public
* @type {string}
*/
readonly streamingAssetsUrl?: string;
/**
* The url to the framework file generated by Unity.
* This is set to the memory file when memory is stored in an external file,
* otherwise it is set to an empty string.
* @public
* @type {string}
*/
readonly memoryUrl?: string;
/**
* The url to the unity code file generated by Unity.
* This is set to the JSON file containing debug symbols when the
* current build is using debug symbols, otherwise it is set to an empty string.
* @public
* @type {string}
*/
readonly symbolsUrl?: string;
/**
* The application's company name. This argument is treated as meta data
* which will be provided to the Unity Instance.
* @public
* @type {string}
*/
readonly companyName?: string;
/**
* The application's product name. This argument is treated as meta data
* which will be provided to the Unity Instance.
* @public
* @type {string}
*/
readonly productName?: string;
/**
* The application's product version. This argument is treated as meta data
* which will be provided to the Unity Instance.
* @public
* @type {string}
*/
readonly productVersion?: string;
/**
* The Canvas can appear too blurry on retina screens. The devicePixelRatio
* determines how much extra pixel density should be added to allow for a
* sharper image.
* @public
* @type {string}
* @see https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
*/
readonly devicePixelRatio?: number;
/**
* If set to true, all file writes inside the Unity Application
* persistentDataPath directory automatically persist so that the contents are
* remembered when the user revisits the website the next time. If unset (or
* set to false), you must manually sync file modifications inside the
* Application persistentDataPath directory by calling the
* JS_FileSystem_Sync() JavaScript function.
*/
readonly autoSyncPersistentDataPath?: boolean;
/**
* When disabling the match WebGL to canvas size flag, the canvas allows for
* client side customization of the WebGL canvas target size instead of
* requiring it to always match 1:1 with the High DPI CSS size of the canvas.
* Supported since Unity 2021.1b
* @public
* @type {boolean}
* @see https://issuetracker.unity3d.com/issues/webgl-builds-dont-allow-separate-control-on-canvas-render-buffer-size
*/
readonly matchWebGLToCanvasSize?: boolean;
/**
* This object allow you to configure WebGLRenderingContext creation options
* which will be pass additional context attributes to the Unity canvas.
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext
*/
readonly webglContextAttributes?: WebGLContextAttributes;
/**
* An array of strings containing the names of the events that should be
* disabled on the canvas. This can be useful when you want to allow the user
* to interact with the canvas, but not with the Unity WebGL canvas. The
* default disabled events are `contextmenu` and `dragstart`.
*/
readonly disabledCanvasEvents?: (keyof GlobalEventHandlersEventMap)[];
/**
* By default, the WebGL Cache stores the asset data file .data and
* AssetBundle files .bundle, and revalidates them before loading them from
* the cache. You can change this behavior by overriding the default
* caching behavior. This argument is treated as meta data which will be
* provided to the Unity Instance.
*/
readonly cacheControl?: (url: string) => UnityCacheControlMode;
/**
* Add an event listener using this function to receive non-critical warnings
* and error messages from the Unity Instance.
*/
readonly showBanner?: (message: string, type?: UnityInstanceBannerType) => void;
/**
* When assigned this method will intercept all incomming messages from the
* Unity Module into the console. These messages will contain both of the
* internal information messages as well as the debuggers log messages.
*/
print?: (message: string) => void;
/**
* When assigned this method will intercept all incomming error logs from the
* Unity Module into the console. These messages will contain both of the
* runtime problems as well as the jslib and javascript errors thrown by the
* Unity Instance.
*/
printError?: (message: string) => void;
}
/**
* Most of the Unity Config's properties are also part of the Unity Arguments.
* This type is used to pick the properties that are configurable from the
* Unity Arguments.
*/
type ConfigurableUnityArguments = Pick<UnityArguments, 'dataUrl' | 'frameworkUrl' | 'codeUrl' | 'workerUrl' | 'streamingAssetsUrl' | 'memoryUrl' | 'symbolsUrl' | 'companyName' | 'productName' | 'productVersion' | 'webglContextAttributes' | 'cacheControl' | 'devicePixelRatio' | 'matchWebGLToCanvasSize' | 'disabledCanvasEvents' | 'autoSyncPersistentDataPath'>;
/**
* The Unity config is provided when instantiating a Unity context. This config
* will eventually be used to create the Unity Arguments which will be passed
* to the create Unity instance method in order to initialize it.
*/
type UnityConfig = ConfigurableUnityArguments & {
/**
* The url to the build json file generated by Unity.
*/
readonly loaderUrl: string;
};
type CanvasElementOrString = HTMLCanvasElement | string;
declare class UnityWebgl extends UnityWebglEvent {
private _config;
private _unity;
private _loader;
private _canvas;
constructor(canvas: CanvasElementOrString, config: UnityConfig);
constructor(config: UnityConfig);
/**
* @deprecated Use `render()` instead.
*/
create(canvas: CanvasElementOrString): Promise<void>;
/**
* Renders the UnityInstance into the target html canvas element.
* @param canvas The target html canvas element.
*/
render(canvas: CanvasElementOrString): Promise<void>;
/**
* Sends a message to the UnityInstance to invoke a public method.
* @param {string} objectName Unity scene name.
* @param {string} methodName public method name.
* @param {any} value an optional method parameter.
* @returns
*/
sendMessage(objectName: string, methodName: string, value?: any): this;
/**
* @deprecated Use `sendMessage()` instead.
*/
send(objectName: string, methodName: string, value?: any): this;
/**
* Asynchronously ask for the pointer to be locked on current canvas.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/requestPointerLock
*/
requestPointerLock(): void;
/**
* Takes a screenshot of the canvas and returns a base64 encoded string.
* @param {string} dataType Defines the type of screenshot, e.g "image/jpeg"
* @param {number} quality Defines the quality of the screenshot, e.g 0.92
* @returns A base 64 encoded string of the screenshot.
*/
takeScreenshot(dataType?: string, quality?: any): string | undefined;
/**
* Enables or disabled the Fullscreen mode of the Unity Instance.
* @param {boolean} enabled
*/
setFullscreen(enabled: boolean): void;
/**
* Quits the Unity instance and clears it from memory so that Unmount from the DOM.
*/
unload(): Promise<void>;
/**
* 保障Unity组件可以安全卸载. 在unity实例从内存中销毁之前保障Dom存在.
*
* Warning! This is a workaround for the fact that the Unity WebGL instances
* which are build with Unity 2021.2 and newer cannot be unmounted before the
* Unity Instance is unloaded.
*/
unsafe_unload(): Promise<void>;
}
export { type UnityArguments, type UnityConfig, UnityInstance, UnityWebgl as default };